diff options
author | rjohnson <rjohnson> | 1998-04-01 09:51:44 (GMT) |
---|---|---|
committer | rjohnson <rjohnson> | 1998-04-01 09:51:44 (GMT) |
commit | 066ea7fd88d49cb456f74da71dbe875e4fc0aabb (patch) | |
tree | 8fb30cb152c4dc191be47fa043d2e6f5ea38c7ba | |
parent | 13242623d2ff3ea02ab6a62bfb48a7dbb5c27e22 (diff) | |
download | tk-066ea7fd88d49cb456f74da71dbe875e4fc0aabb.zip tk-066ea7fd88d49cb456f74da71dbe875e4fc0aabb.tar.gz tk-066ea7fd88d49cb456f74da71dbe875e4fc0aabb.tar.bz2 |
Initial revision
469 files changed, 230844 insertions, 0 deletions
diff --git a/deleted_files/xlib/ximage.c b/deleted_files/xlib/ximage.c new file mode 100644 index 0000000..057e973 --- /dev/null +++ b/deleted_files/xlib/ximage.c @@ -0,0 +1,115 @@ +/* + * ximage.c -- + * + * X bitmap and image routines. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) ximage.c 1.6 96/07/23 16:59:10 + */ + +#include "tkInt.h" + + +/* + *---------------------------------------------------------------------- + * + * XCreateBitmapFromData -- + * + * Construct a single plane pixmap from bitmap data. + * + * Results: + * Returns a new Pixmap. + * + * Side effects: + * Allocates a new bitmap and drawable. + * + *---------------------------------------------------------------------- + */ + +Pixmap +XCreateBitmapFromData(display, d, data, width, height) + Display* display; + Drawable d; + _Xconst char* data; + unsigned int width; + unsigned int height; +{ + XImage ximage; + GC gc; + Pixmap pix; + + pix = Tk_GetPixmap(display, d, width, height, 1); + gc = XCreateGC(display, pix, 0, NULL); + if (gc == NULL) { + return None; + } + ximage.height = height; + ximage.width = width; + ximage.depth = 1; + ximage.bits_per_pixel = 1; + ximage.xoffset = 0; + ximage.format = XYBitmap; + ximage.data = (char *)data; + ximage.byte_order = LSBFirst; + ximage.bitmap_unit = 8; + ximage.bitmap_bit_order = LSBFirst; + ximage.bitmap_pad = 8; + ximage.bytes_per_line = (width+7)/8; + + TkPutImage(NULL, 0, display, pix, gc, &ximage, 0, 0, 0, 0, width, height); + XFreeGC(display, gc); + return pix; +} + +/* + *---------------------------------------------------------------------- + * + * XReadBitmapFile -- + * + * Loads a bitmap image in X bitmap format into the specified + * drawable. + * + * Results: + * Sets the size, hotspot, and bitmap on success. + * + * Side effects: + * Creates a new bitmap from the file data. + * + *---------------------------------------------------------------------- + */ + +int +XReadBitmapFile(display, d, filename, width_return, height_return, + bitmap_return, x_hot_return, y_hot_return) + Display* display; + Drawable d; + _Xconst char* filename; + unsigned int* width_return; + unsigned int* height_return; + Pixmap* bitmap_return; + int* x_hot_return; + int* y_hot_return; +{ + Tcl_Interp *dummy; + char *data; + + dummy = Tcl_CreateInterp(); + + data = TkGetBitmapData(dummy, NULL, (char *) filename, + (int *) width_return, (int *) height_return, x_hot_return, + y_hot_return); + if (data == NULL) { + return BitmapFileInvalid; + } + + *bitmap_return = XCreateBitmapFromData(display, d, data, *width_return, + *height_return); + + Tcl_DeleteInterp(dummy); + ckfree(data); + return BitmapSuccess; +} diff --git a/generic/README b/generic/README new file mode 100644 index 0000000..572cc93 --- /dev/null +++ b/generic/README @@ -0,0 +1,5 @@ +This directory contains Tk source files that work on all the platforms +where Tk runs (e.g. UNIX, PCs, and Macintoshes). Platform-specific +sources are in the directories ../unix, ../win, and ../mac. + +SCCS ID: @(#) README 1.1 95/09/11 14:02:45 diff --git a/generic/default.h b/generic/default.h new file mode 100644 index 0000000..91a19f6 --- /dev/null +++ b/generic/default.h @@ -0,0 +1,29 @@ +/* + * default.h -- + * + * This file defines the defaults for all options for all of + * the Tk widgets. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) default.h 1.4 96/02/07 17:33:39 + */ + +#ifndef _DEFAULT +#define _DEFAULT + +#if defined(__WIN32__) || defined(_WIN32) +# include "tkWinDefault.h" +#else +# if defined(MAC_TCL) +# include "tkMacDefault.h" +# else +# include "tkUnixDefault.h" +# endif +#endif + +#endif /* _DEFAULT */ diff --git a/generic/ks_names.h b/generic/ks_names.h new file mode 100644 index 0000000..3eee008 --- /dev/null +++ b/generic/ks_names.h @@ -0,0 +1,917 @@ +/* + * This file is generated from $(INCLUDESRC)/keysymdef.h. Do not edit. + */ +{ "BackSpace", 0xFF08 }, +{ "Tab", 0xFF09 }, +{ "Linefeed", 0xFF0A }, +{ "Clear", 0xFF0B }, +{ "Return", 0xFF0D }, +{ "Pause", 0xFF13 }, +{ "Escape", 0xFF1B }, +{ "Delete", 0xFFFF }, +{ "Multi_key", 0xFF20 }, +{ "Kanji", 0xFF21 }, +{ "Home", 0xFF50 }, +{ "Left", 0xFF51 }, +{ "Up", 0xFF52 }, +{ "Right", 0xFF53 }, +{ "Down", 0xFF54 }, +{ "Prior", 0xFF55 }, +{ "Next", 0xFF56 }, +{ "End", 0xFF57 }, +{ "Begin", 0xFF58 }, +{ "Select", 0xFF60 }, +{ "Print", 0xFF61 }, +{ "Execute", 0xFF62 }, +{ "Insert", 0xFF63 }, +{ "Undo", 0xFF65 }, +{ "Redo", 0xFF66 }, +{ "Menu", 0xFF67 }, +{ "Find", 0xFF68 }, +{ "Cancel", 0xFF69 }, +{ "Help", 0xFF6A }, +{ "Break", 0xFF6B }, +{ "Mode_switch", 0xFF7E }, +{ "script_switch", 0xFF7E }, +{ "Num_Lock", 0xFF7F }, +{ "KP_Space", 0xFF80 }, +{ "KP_Tab", 0xFF89 }, +{ "KP_Enter", 0xFF8D }, +{ "KP_F1", 0xFF91 }, +{ "KP_F2", 0xFF92 }, +{ "KP_F3", 0xFF93 }, +{ "KP_F4", 0xFF94 }, +{ "KP_Equal", 0xFFBD }, +{ "KP_Multiply", 0xFFAA }, +{ "KP_Add", 0xFFAB }, +{ "KP_Separator", 0xFFAC }, +{ "KP_Subtract", 0xFFAD }, +{ "KP_Decimal", 0xFFAE }, +{ "KP_Divide", 0xFFAF }, +{ "KP_0", 0xFFB0 }, +{ "KP_1", 0xFFB1 }, +{ "KP_2", 0xFFB2 }, +{ "KP_3", 0xFFB3 }, +{ "KP_4", 0xFFB4 }, +{ "KP_5", 0xFFB5 }, +{ "KP_6", 0xFFB6 }, +{ "KP_7", 0xFFB7 }, +{ "KP_8", 0xFFB8 }, +{ "KP_9", 0xFFB9 }, +{ "F1", 0xFFBE }, +{ "F2", 0xFFBF }, +{ "F3", 0xFFC0 }, +{ "F4", 0xFFC1 }, +{ "F5", 0xFFC2 }, +{ "F6", 0xFFC3 }, +{ "F7", 0xFFC4 }, +{ "F8", 0xFFC5 }, +{ "F9", 0xFFC6 }, +{ "F10", 0xFFC7 }, +{ "F11", 0xFFC8 }, +{ "L1", 0xFFC8 }, +{ "F12", 0xFFC9 }, +{ "L2", 0xFFC9 }, +{ "F13", 0xFFCA }, +{ "L3", 0xFFCA }, +{ "F14", 0xFFCB }, +{ "L4", 0xFFCB }, +{ "F15", 0xFFCC }, +{ "L5", 0xFFCC }, +{ "F16", 0xFFCD }, +{ "L6", 0xFFCD }, +{ "F17", 0xFFCE }, +{ "L7", 0xFFCE }, +{ "F18", 0xFFCF }, +{ "L8", 0xFFCF }, +{ "F19", 0xFFD0 }, +{ "L9", 0xFFD0 }, +{ "F20", 0xFFD1 }, +{ "L10", 0xFFD1 }, +{ "F21", 0xFFD2 }, +{ "R1", 0xFFD2 }, +{ "F22", 0xFFD3 }, +{ "R2", 0xFFD3 }, +{ "F23", 0xFFD4 }, +{ "R3", 0xFFD4 }, +{ "F24", 0xFFD5 }, +{ "R4", 0xFFD5 }, +{ "F25", 0xFFD6 }, +{ "R5", 0xFFD6 }, +{ "F26", 0xFFD7 }, +{ "R6", 0xFFD7 }, +{ "F27", 0xFFD8 }, +{ "R7", 0xFFD8 }, +{ "F28", 0xFFD9 }, +{ "R8", 0xFFD9 }, +{ "F29", 0xFFDA }, +{ "R9", 0xFFDA }, +{ "F30", 0xFFDB }, +{ "R10", 0xFFDB }, +{ "F31", 0xFFDC }, +{ "R11", 0xFFDC }, +{ "F32", 0xFFDD }, +{ "R12", 0xFFDD }, +{ "R13", 0xFFDE }, +{ "F33", 0xFFDE }, +{ "F34", 0xFFDF }, +{ "R14", 0xFFDF }, +{ "F35", 0xFFE0 }, +{ "R15", 0xFFE0 }, +{ "Shift_L", 0xFFE1 }, +{ "Shift_R", 0xFFE2 }, +{ "Control_L", 0xFFE3 }, +{ "Control_R", 0xFFE4 }, +{ "Caps_Lock", 0xFFE5 }, +{ "Shift_Lock", 0xFFE6 }, +{ "Meta_L", 0xFFE7 }, +{ "Meta_R", 0xFFE8 }, +{ "Alt_L", 0xFFE9 }, +{ "Alt_R", 0xFFEA }, +{ "Super_L", 0xFFEB }, +{ "Super_R", 0xFFEC }, +{ "Hyper_L", 0xFFED }, +{ "Hyper_R", 0xFFEE }, +{ "space", 0x020 }, +{ "exclam", 0x021 }, +{ "quotedbl", 0x022 }, +{ "numbersign", 0x023 }, +{ "dollar", 0x024 }, +{ "percent", 0x025 }, +{ "ampersand", 0x026 }, +{ "quoteright", 0x027 }, +{ "parenleft", 0x028 }, +{ "parenright", 0x029 }, +{ "asterisk", 0x02a }, +{ "plus", 0x02b }, +{ "comma", 0x02c }, +{ "minus", 0x02d }, +{ "period", 0x02e }, +{ "slash", 0x02f }, +{ "0", 0x030 }, +{ "1", 0x031 }, +{ "2", 0x032 }, +{ "3", 0x033 }, +{ "4", 0x034 }, +{ "5", 0x035 }, +{ "6", 0x036 }, +{ "7", 0x037 }, +{ "8", 0x038 }, +{ "9", 0x039 }, +{ "colon", 0x03a }, +{ "semicolon", 0x03b }, +{ "less", 0x03c }, +{ "equal", 0x03d }, +{ "greater", 0x03e }, +{ "question", 0x03f }, +{ "at", 0x040 }, +{ "A", 0x041 }, +{ "B", 0x042 }, +{ "C", 0x043 }, +{ "D", 0x044 }, +{ "E", 0x045 }, +{ "F", 0x046 }, +{ "G", 0x047 }, +{ "H", 0x048 }, +{ "I", 0x049 }, +{ "J", 0x04a }, +{ "K", 0x04b }, +{ "L", 0x04c }, +{ "M", 0x04d }, +{ "N", 0x04e }, +{ "O", 0x04f }, +{ "P", 0x050 }, +{ "Q", 0x051 }, +{ "R", 0x052 }, +{ "S", 0x053 }, +{ "T", 0x054 }, +{ "U", 0x055 }, +{ "V", 0x056 }, +{ "W", 0x057 }, +{ "X", 0x058 }, +{ "Y", 0x059 }, +{ "Z", 0x05a }, +{ "bracketleft", 0x05b }, +{ "backslash", 0x05c }, +{ "bracketright", 0x05d }, +{ "asciicircum", 0x05e }, +{ "underscore", 0x05f }, +{ "quoteleft", 0x060 }, +{ "a", 0x061 }, +{ "b", 0x062 }, +{ "c", 0x063 }, +{ "d", 0x064 }, +{ "e", 0x065 }, +{ "f", 0x066 }, +{ "g", 0x067 }, +{ "h", 0x068 }, +{ "i", 0x069 }, +{ "j", 0x06a }, +{ "k", 0x06b }, +{ "l", 0x06c }, +{ "m", 0x06d }, +{ "n", 0x06e }, +{ "o", 0x06f }, +{ "p", 0x070 }, +{ "q", 0x071 }, +{ "r", 0x072 }, +{ "s", 0x073 }, +{ "t", 0x074 }, +{ "u", 0x075 }, +{ "v", 0x076 }, +{ "w", 0x077 }, +{ "x", 0x078 }, +{ "y", 0x079 }, +{ "z", 0x07a }, +{ "braceleft", 0x07b }, +{ "bar", 0x07c }, +{ "braceright", 0x07d }, +{ "asciitilde", 0x07e }, +{ "nobreakspace", 0x0a0 }, +{ "exclamdown", 0x0a1 }, +{ "cent", 0x0a2 }, +{ "sterling", 0x0a3 }, +{ "currency", 0x0a4 }, +{ "yen", 0x0a5 }, +{ "brokenbar", 0x0a6 }, +{ "section", 0x0a7 }, +{ "diaeresis", 0x0a8 }, +{ "copyright", 0x0a9 }, +{ "ordfeminine", 0x0aa }, +{ "guillemotleft", 0x0ab }, +{ "notsign", 0x0ac }, +{ "hyphen", 0x0ad }, +{ "registered", 0x0ae }, +{ "macron", 0x0af }, +{ "degree", 0x0b0 }, +{ "plusminus", 0x0b1 }, +{ "twosuperior", 0x0b2 }, +{ "threesuperior", 0x0b3 }, +{ "acute", 0x0b4 }, +{ "mu", 0x0b5 }, +{ "paragraph", 0x0b6 }, +{ "periodcentered", 0x0b7 }, +{ "cedilla", 0x0b8 }, +{ "onesuperior", 0x0b9 }, +{ "masculine", 0x0ba }, +{ "guillemotright", 0x0bb }, +{ "onequarter", 0x0bc }, +{ "onehalf", 0x0bd }, +{ "threequarters", 0x0be }, +{ "questiondown", 0x0bf }, +{ "Agrave", 0x0c0 }, +{ "Aacute", 0x0c1 }, +{ "Acircumflex", 0x0c2 }, +{ "Atilde", 0x0c3 }, +{ "Adiaeresis", 0x0c4 }, +{ "Aring", 0x0c5 }, +{ "AE", 0x0c6 }, +{ "Ccedilla", 0x0c7 }, +{ "Egrave", 0x0c8 }, +{ "Eacute", 0x0c9 }, +{ "Ecircumflex", 0x0ca }, +{ "Ediaeresis", 0x0cb }, +{ "Igrave", 0x0cc }, +{ "Iacute", 0x0cd }, +{ "Icircumflex", 0x0ce }, +{ "Idiaeresis", 0x0cf }, +{ "Eth", 0x0d0 }, +{ "Ntilde", 0x0d1 }, +{ "Ograve", 0x0d2 }, +{ "Oacute", 0x0d3 }, +{ "Ocircumflex", 0x0d4 }, +{ "Otilde", 0x0d5 }, +{ "Odiaeresis", 0x0d6 }, +{ "multiply", 0x0d7 }, +{ "Ooblique", 0x0d8 }, +{ "Ugrave", 0x0d9 }, +{ "Uacute", 0x0da }, +{ "Ucircumflex", 0x0db }, +{ "Udiaeresis", 0x0dc }, +{ "Yacute", 0x0dd }, +{ "Thorn", 0x0de }, +{ "ssharp", 0x0df }, +{ "agrave", 0x0e0 }, +{ "aacute", 0x0e1 }, +{ "acircumflex", 0x0e2 }, +{ "atilde", 0x0e3 }, +{ "adiaeresis", 0x0e4 }, +{ "aring", 0x0e5 }, +{ "ae", 0x0e6 }, +{ "ccedilla", 0x0e7 }, +{ "egrave", 0x0e8 }, +{ "eacute", 0x0e9 }, +{ "ecircumflex", 0x0ea }, +{ "ediaeresis", 0x0eb }, +{ "igrave", 0x0ec }, +{ "iacute", 0x0ed }, +{ "icircumflex", 0x0ee }, +{ "idiaeresis", 0x0ef }, +{ "eth", 0x0f0 }, +{ "ntilde", 0x0f1 }, +{ "ograve", 0x0f2 }, +{ "oacute", 0x0f3 }, +{ "ocircumflex", 0x0f4 }, +{ "otilde", 0x0f5 }, +{ "odiaeresis", 0x0f6 }, +{ "division", 0x0f7 }, +{ "oslash", 0x0f8 }, +{ "ugrave", 0x0f9 }, +{ "uacute", 0x0fa }, +{ "ucircumflex", 0x0fb }, +{ "udiaeresis", 0x0fc }, +{ "yacute", 0x0fd }, +{ "thorn", 0x0fe }, +{ "ydiaeresis", 0x0ff }, +{ "Aogonek", 0x1a1 }, +{ "breve", 0x1a2 }, +{ "Lstroke", 0x1a3 }, +{ "Lcaron", 0x1a5 }, +{ "Sacute", 0x1a6 }, +{ "Scaron", 0x1a9 }, +{ "Scedilla", 0x1aa }, +{ "Tcaron", 0x1ab }, +{ "Zacute", 0x1ac }, +{ "Zcaron", 0x1ae }, +{ "Zabovedot", 0x1af }, +{ "aogonek", 0x1b1 }, +{ "ogonek", 0x1b2 }, +{ "lstroke", 0x1b3 }, +{ "lcaron", 0x1b5 }, +{ "sacute", 0x1b6 }, +{ "caron", 0x1b7 }, +{ "scaron", 0x1b9 }, +{ "scedilla", 0x1ba }, +{ "tcaron", 0x1bb }, +{ "zacute", 0x1bc }, +{ "doubleacute", 0x1bd }, +{ "zcaron", 0x1be }, +{ "zabovedot", 0x1bf }, +{ "Racute", 0x1c0 }, +{ "Abreve", 0x1c3 }, +{ "Cacute", 0x1c6 }, +{ "Ccaron", 0x1c8 }, +{ "Eogonek", 0x1ca }, +{ "Ecaron", 0x1cc }, +{ "Dcaron", 0x1cf }, +{ "Nacute", 0x1d1 }, +{ "Ncaron", 0x1d2 }, +{ "Odoubleacute", 0x1d5 }, +{ "Rcaron", 0x1d8 }, +{ "Uring", 0x1d9 }, +{ "Udoubleacute", 0x1db }, +{ "Tcedilla", 0x1de }, +{ "racute", 0x1e0 }, +{ "abreve", 0x1e3 }, +{ "cacute", 0x1e6 }, +{ "ccaron", 0x1e8 }, +{ "eogonek", 0x1ea }, +{ "ecaron", 0x1ec }, +{ "dcaron", 0x1ef }, +{ "nacute", 0x1f1 }, +{ "ncaron", 0x1f2 }, +{ "odoubleacute", 0x1f5 }, +{ "udoubleacute", 0x1fb }, +{ "rcaron", 0x1f8 }, +{ "uring", 0x1f9 }, +{ "tcedilla", 0x1fe }, +{ "abovedot", 0x1ff }, +{ "Hstroke", 0x2a1 }, +{ "Hcircumflex", 0x2a6 }, +{ "Iabovedot", 0x2a9 }, +{ "Gbreve", 0x2ab }, +{ "Jcircumflex", 0x2ac }, +{ "hstroke", 0x2b1 }, +{ "hcircumflex", 0x2b6 }, +{ "idotless", 0x2b9 }, +{ "gbreve", 0x2bb }, +{ "jcircumflex", 0x2bc }, +{ "Cabovedot", 0x2c5 }, +{ "Ccircumflex", 0x2c6 }, +{ "Gabovedot", 0x2d5 }, +{ "Gcircumflex", 0x2d8 }, +{ "Ubreve", 0x2dd }, +{ "Scircumflex", 0x2de }, +{ "cabovedot", 0x2e5 }, +{ "ccircumflex", 0x2e6 }, +{ "gabovedot", 0x2f5 }, +{ "gcircumflex", 0x2f8 }, +{ "ubreve", 0x2fd }, +{ "scircumflex", 0x2fe }, +{ "kappa", 0x3a2 }, +{ "Rcedilla", 0x3a3 }, +{ "Itilde", 0x3a5 }, +{ "Lcedilla", 0x3a6 }, +{ "Emacron", 0x3aa }, +{ "Gcedilla", 0x3ab }, +{ "Tslash", 0x3ac }, +{ "rcedilla", 0x3b3 }, +{ "itilde", 0x3b5 }, +{ "lcedilla", 0x3b6 }, +{ "emacron", 0x3ba }, +{ "gacute", 0x3bb }, +{ "tslash", 0x3bc }, +{ "ENG", 0x3bd }, +{ "eng", 0x3bf }, +{ "Amacron", 0x3c0 }, +{ "Iogonek", 0x3c7 }, +{ "Eabovedot", 0x3cc }, +{ "Imacron", 0x3cf }, +{ "Ncedilla", 0x3d1 }, +{ "Omacron", 0x3d2 }, +{ "Kcedilla", 0x3d3 }, +{ "Uogonek", 0x3d9 }, +{ "Utilde", 0x3dd }, +{ "Umacron", 0x3de }, +{ "amacron", 0x3e0 }, +{ "iogonek", 0x3e7 }, +{ "eabovedot", 0x3ec }, +{ "imacron", 0x3ef }, +{ "ncedilla", 0x3f1 }, +{ "omacron", 0x3f2 }, +{ "kcedilla", 0x3f3 }, +{ "uogonek", 0x3f9 }, +{ "utilde", 0x3fd }, +{ "umacron", 0x3fe }, +{ "overline", 0x47e }, +{ "kana_fullstop", 0x4a1 }, +{ "kana_openingbracket", 0x4a2 }, +{ "kana_closingbracket", 0x4a3 }, +{ "kana_comma", 0x4a4 }, +{ "kana_middledot", 0x4a5 }, +{ "kana_WO", 0x4a6 }, +{ "kana_a", 0x4a7 }, +{ "kana_i", 0x4a8 }, +{ "kana_u", 0x4a9 }, +{ "kana_e", 0x4aa }, +{ "kana_o", 0x4ab }, +{ "kana_ya", 0x4ac }, +{ "kana_yu", 0x4ad }, +{ "kana_yo", 0x4ae }, +{ "kana_tu", 0x4af }, +{ "prolongedsound", 0x4b0 }, +{ "kana_A", 0x4b1 }, +{ "kana_I", 0x4b2 }, +{ "kana_U", 0x4b3 }, +{ "kana_E", 0x4b4 }, +{ "kana_O", 0x4b5 }, +{ "kana_KA", 0x4b6 }, +{ "kana_KI", 0x4b7 }, +{ "kana_KU", 0x4b8 }, +{ "kana_KE", 0x4b9 }, +{ "kana_KO", 0x4ba }, +{ "kana_SA", 0x4bb }, +{ "kana_SHI", 0x4bc }, +{ "kana_SU", 0x4bd }, +{ "kana_SE", 0x4be }, +{ "kana_SO", 0x4bf }, +{ "kana_TA", 0x4c0 }, +{ "kana_TI", 0x4c1 }, +{ "kana_TU", 0x4c2 }, +{ "kana_TE", 0x4c3 }, +{ "kana_TO", 0x4c4 }, +{ "kana_NA", 0x4c5 }, +{ "kana_NI", 0x4c6 }, +{ "kana_NU", 0x4c7 }, +{ "kana_NE", 0x4c8 }, +{ "kana_NO", 0x4c9 }, +{ "kana_HA", 0x4ca }, +{ "kana_HI", 0x4cb }, +{ "kana_HU", 0x4cc }, +{ "kana_HE", 0x4cd }, +{ "kana_HO", 0x4ce }, +{ "kana_MA", 0x4cf }, +{ "kana_MI", 0x4d0 }, +{ "kana_MU", 0x4d1 }, +{ "kana_ME", 0x4d2 }, +{ "kana_MO", 0x4d3 }, +{ "kana_YA", 0x4d4 }, +{ "kana_YU", 0x4d5 }, +{ "kana_YO", 0x4d6 }, +{ "kana_RA", 0x4d7 }, +{ "kana_RI", 0x4d8 }, +{ "kana_RU", 0x4d9 }, +{ "kana_RE", 0x4da }, +{ "kana_RO", 0x4db }, +{ "kana_WA", 0x4dc }, +{ "kana_N", 0x4dd }, +{ "voicedsound", 0x4de }, +{ "semivoicedsound", 0x4df }, +{ "kana_switch", 0xFF7E }, +{ "Arabic_comma", 0x5ac }, +{ "Arabic_semicolon", 0x5bb }, +{ "Arabic_question_mark", 0x5bf }, +{ "Arabic_hamza", 0x5c1 }, +{ "Arabic_maddaonalef", 0x5c2 }, +{ "Arabic_hamzaonalef", 0x5c3 }, +{ "Arabic_hamzaonwaw", 0x5c4 }, +{ "Arabic_hamzaunderalef", 0x5c5 }, +{ "Arabic_hamzaonyeh", 0x5c6 }, +{ "Arabic_alef", 0x5c7 }, +{ "Arabic_beh", 0x5c8 }, +{ "Arabic_tehmarbuta", 0x5c9 }, +{ "Arabic_teh", 0x5ca }, +{ "Arabic_theh", 0x5cb }, +{ "Arabic_jeem", 0x5cc }, +{ "Arabic_hah", 0x5cd }, +{ "Arabic_khah", 0x5ce }, +{ "Arabic_dal", 0x5cf }, +{ "Arabic_thal", 0x5d0 }, +{ "Arabic_ra", 0x5d1 }, +{ "Arabic_zain", 0x5d2 }, +{ "Arabic_seen", 0x5d3 }, +{ "Arabic_sheen", 0x5d4 }, +{ "Arabic_sad", 0x5d5 }, +{ "Arabic_dad", 0x5d6 }, +{ "Arabic_tah", 0x5d7 }, +{ "Arabic_zah", 0x5d8 }, +{ "Arabic_ain", 0x5d9 }, +{ "Arabic_ghain", 0x5da }, +{ "Arabic_tatweel", 0x5e0 }, +{ "Arabic_feh", 0x5e1 }, +{ "Arabic_qaf", 0x5e2 }, +{ "Arabic_kaf", 0x5e3 }, +{ "Arabic_lam", 0x5e4 }, +{ "Arabic_meem", 0x5e5 }, +{ "Arabic_noon", 0x5e6 }, +{ "Arabic_heh", 0x5e7 }, +{ "Arabic_waw", 0x5e8 }, +{ "Arabic_alefmaksura", 0x5e9 }, +{ "Arabic_yeh", 0x5ea }, +{ "Arabic_fathatan", 0x5eb }, +{ "Arabic_dammatan", 0x5ec }, +{ "Arabic_kasratan", 0x5ed }, +{ "Arabic_fatha", 0x5ee }, +{ "Arabic_damma", 0x5ef }, +{ "Arabic_kasra", 0x5f0 }, +{ "Arabic_shadda", 0x5f1 }, +{ "Arabic_sukun", 0x5f2 }, +{ "Arabic_switch", 0xFF7E }, +{ "Serbian_dje", 0x6a1 }, +{ "Macedonia_gje", 0x6a2 }, +{ "Cyrillic_io", 0x6a3 }, +{ "Ukranian_je", 0x6a4 }, +{ "Macedonia_dse", 0x6a5 }, +{ "Ukranian_i", 0x6a6 }, +{ "Ukranian_yi", 0x6a7 }, +{ "Serbian_je", 0x6a8 }, +{ "Serbian_lje", 0x6a9 }, +{ "Serbian_nje", 0x6aa }, +{ "Serbian_tshe", 0x6ab }, +{ "Macedonia_kje", 0x6ac }, +{ "Byelorussian_shortu", 0x6ae }, +{ "Serbian_dze", 0x6af }, +{ "numerosign", 0x6b0 }, +{ "Serbian_DJE", 0x6b1 }, +{ "Macedonia_GJE", 0x6b2 }, +{ "Cyrillic_IO", 0x6b3 }, +{ "Ukranian_JE", 0x6b4 }, +{ "Macedonia_DSE", 0x6b5 }, +{ "Ukranian_I", 0x6b6 }, +{ "Ukranian_YI", 0x6b7 }, +{ "Serbian_JE", 0x6b8 }, +{ "Serbian_LJE", 0x6b9 }, +{ "Serbian_NJE", 0x6ba }, +{ "Serbian_TSHE", 0x6bb }, +{ "Macedonia_KJE", 0x6bc }, +{ "Byelorussian_SHORTU", 0x6be }, +{ "Serbian_DZE", 0x6bf }, +{ "Cyrillic_yu", 0x6c0 }, +{ "Cyrillic_a", 0x6c1 }, +{ "Cyrillic_be", 0x6c2 }, +{ "Cyrillic_tse", 0x6c3 }, +{ "Cyrillic_de", 0x6c4 }, +{ "Cyrillic_ie", 0x6c5 }, +{ "Cyrillic_ef", 0x6c6 }, +{ "Cyrillic_ghe", 0x6c7 }, +{ "Cyrillic_ha", 0x6c8 }, +{ "Cyrillic_i", 0x6c9 }, +{ "Cyrillic_shorti", 0x6ca }, +{ "Cyrillic_ka", 0x6cb }, +{ "Cyrillic_el", 0x6cc }, +{ "Cyrillic_em", 0x6cd }, +{ "Cyrillic_en", 0x6ce }, +{ "Cyrillic_o", 0x6cf }, +{ "Cyrillic_pe", 0x6d0 }, +{ "Cyrillic_ya", 0x6d1 }, +{ "Cyrillic_er", 0x6d2 }, +{ "Cyrillic_es", 0x6d3 }, +{ "Cyrillic_te", 0x6d4 }, +{ "Cyrillic_u", 0x6d5 }, +{ "Cyrillic_zhe", 0x6d6 }, +{ "Cyrillic_ve", 0x6d7 }, +{ "Cyrillic_softsign", 0x6d8 }, +{ "Cyrillic_yeru", 0x6d9 }, +{ "Cyrillic_ze", 0x6da }, +{ "Cyrillic_sha", 0x6db }, +{ "Cyrillic_e", 0x6dc }, +{ "Cyrillic_shcha", 0x6dd }, +{ "Cyrillic_che", 0x6de }, +{ "Cyrillic_hardsign", 0x6df }, +{ "Cyrillic_YU", 0x6e0 }, +{ "Cyrillic_A", 0x6e1 }, +{ "Cyrillic_BE", 0x6e2 }, +{ "Cyrillic_TSE", 0x6e3 }, +{ "Cyrillic_DE", 0x6e4 }, +{ "Cyrillic_IE", 0x6e5 }, +{ "Cyrillic_EF", 0x6e6 }, +{ "Cyrillic_GHE", 0x6e7 }, +{ "Cyrillic_HA", 0x6e8 }, +{ "Cyrillic_I", 0x6e9 }, +{ "Cyrillic_SHORTI", 0x6ea }, +{ "Cyrillic_KA", 0x6eb }, +{ "Cyrillic_EL", 0x6ec }, +{ "Cyrillic_EM", 0x6ed }, +{ "Cyrillic_EN", 0x6ee }, +{ "Cyrillic_O", 0x6ef }, +{ "Cyrillic_PE", 0x6f0 }, +{ "Cyrillic_YA", 0x6f1 }, +{ "Cyrillic_ER", 0x6f2 }, +{ "Cyrillic_ES", 0x6f3 }, +{ "Cyrillic_TE", 0x6f4 }, +{ "Cyrillic_U", 0x6f5 }, +{ "Cyrillic_ZHE", 0x6f6 }, +{ "Cyrillic_VE", 0x6f7 }, +{ "Cyrillic_SOFTSIGN", 0x6f8 }, +{ "Cyrillic_YERU", 0x6f9 }, +{ "Cyrillic_ZE", 0x6fa }, +{ "Cyrillic_SHA", 0x6fb }, +{ "Cyrillic_E", 0x6fc }, +{ "Cyrillic_SHCHA", 0x6fd }, +{ "Cyrillic_CHE", 0x6fe }, +{ "Cyrillic_HARDSIGN", 0x6ff }, +{ "Greek_ALPHAaccent", 0x7a1 }, +{ "Greek_EPSILONaccent", 0x7a2 }, +{ "Greek_ETAaccent", 0x7a3 }, +{ "Greek_IOTAaccent", 0x7a4 }, +{ "Greek_IOTAdiaeresis", 0x7a5 }, +{ "Greek_IOTAaccentdiaeresis", 0x7a6 }, +{ "Greek_OMICRONaccent", 0x7a7 }, +{ "Greek_UPSILONaccent", 0x7a8 }, +{ "Greek_UPSILONdieresis", 0x7a9 }, +{ "Greek_UPSILONaccentdieresis", 0x7aa }, +{ "Greek_OMEGAaccent", 0x7ab }, +{ "Greek_alphaaccent", 0x7b1 }, +{ "Greek_epsilonaccent", 0x7b2 }, +{ "Greek_etaaccent", 0x7b3 }, +{ "Greek_iotaaccent", 0x7b4 }, +{ "Greek_iotadieresis", 0x7b5 }, +{ "Greek_iotaaccentdieresis", 0x7b6 }, +{ "Greek_omicronaccent", 0x7b7 }, +{ "Greek_upsilonaccent", 0x7b8 }, +{ "Greek_upsilondieresis", 0x7b9 }, +{ "Greek_upsilonaccentdieresis", 0x7ba }, +{ "Greek_omegaaccent", 0x7bb }, +{ "Greek_ALPHA", 0x7c1 }, +{ "Greek_BETA", 0x7c2 }, +{ "Greek_GAMMA", 0x7c3 }, +{ "Greek_DELTA", 0x7c4 }, +{ "Greek_EPSILON", 0x7c5 }, +{ "Greek_ZETA", 0x7c6 }, +{ "Greek_ETA", 0x7c7 }, +{ "Greek_THETA", 0x7c8 }, +{ "Greek_IOTA", 0x7c9 }, +{ "Greek_KAPPA", 0x7ca }, +{ "Greek_LAMBDA", 0x7cb }, +{ "Greek_MU", 0x7cc }, +{ "Greek_NU", 0x7cd }, +{ "Greek_XI", 0x7ce }, +{ "Greek_OMICRON", 0x7cf }, +{ "Greek_PI", 0x7d0 }, +{ "Greek_RHO", 0x7d1 }, +{ "Greek_SIGMA", 0x7d2 }, +{ "Greek_TAU", 0x7d4 }, +{ "Greek_UPSILON", 0x7d5 }, +{ "Greek_PHI", 0x7d6 }, +{ "Greek_CHI", 0x7d7 }, +{ "Greek_PSI", 0x7d8 }, +{ "Greek_OMEGA", 0x7d9 }, +{ "Greek_alpha", 0x7e1 }, +{ "Greek_beta", 0x7e2 }, +{ "Greek_gamma", 0x7e3 }, +{ "Greek_delta", 0x7e4 }, +{ "Greek_epsilon", 0x7e5 }, +{ "Greek_zeta", 0x7e6 }, +{ "Greek_eta", 0x7e7 }, +{ "Greek_theta", 0x7e8 }, +{ "Greek_iota", 0x7e9 }, +{ "Greek_kappa", 0x7ea }, +{ "Greek_lambda", 0x7eb }, +{ "Greek_mu", 0x7ec }, +{ "Greek_nu", 0x7ed }, +{ "Greek_xi", 0x7ee }, +{ "Greek_omicron", 0x7ef }, +{ "Greek_pi", 0x7f0 }, +{ "Greek_rho", 0x7f1 }, +{ "Greek_sigma", 0x7f2 }, +{ "Greek_finalsmallsigma", 0x7f3 }, +{ "Greek_tau", 0x7f4 }, +{ "Greek_upsilon", 0x7f5 }, +{ "Greek_phi", 0x7f6 }, +{ "Greek_chi", 0x7f7 }, +{ "Greek_psi", 0x7f8 }, +{ "Greek_omega", 0x7f9 }, +{ "Greek_switch", 0xFF7E }, +{ "leftradical", 0x8a1 }, +{ "topleftradical", 0x8a2 }, +{ "horizconnector", 0x8a3 }, +{ "topintegral", 0x8a4 }, +{ "botintegral", 0x8a5 }, +{ "vertconnector", 0x8a6 }, +{ "topleftsqbracket", 0x8a7 }, +{ "botleftsqbracket", 0x8a8 }, +{ "toprightsqbracket", 0x8a9 }, +{ "botrightsqbracket", 0x8aa }, +{ "topleftparens", 0x8ab }, +{ "botleftparens", 0x8ac }, +{ "toprightparens", 0x8ad }, +{ "botrightparens", 0x8ae }, +{ "leftmiddlecurlybrace", 0x8af }, +{ "rightmiddlecurlybrace", 0x8b0 }, +{ "topleftsummation", 0x8b1 }, +{ "botleftsummation", 0x8b2 }, +{ "topvertsummationconnector", 0x8b3 }, +{ "botvertsummationconnector", 0x8b4 }, +{ "toprightsummation", 0x8b5 }, +{ "botrightsummation", 0x8b6 }, +{ "rightmiddlesummation", 0x8b7 }, +{ "lessthanequal", 0x8bc }, +{ "notequal", 0x8bd }, +{ "greaterthanequal", 0x8be }, +{ "integral", 0x8bf }, +{ "therefore", 0x8c0 }, +{ "variation", 0x8c1 }, +{ "infinity", 0x8c2 }, +{ "nabla", 0x8c5 }, +{ "approximate", 0x8c8 }, +{ "similarequal", 0x8c9 }, +{ "ifonlyif", 0x8cd }, +{ "implies", 0x8ce }, +{ "identical", 0x8cf }, +{ "radical", 0x8d6 }, +{ "includedin", 0x8da }, +{ "includes", 0x8db }, +{ "intersection", 0x8dc }, +{ "union", 0x8dd }, +{ "logicaland", 0x8de }, +{ "logicalor", 0x8df }, +{ "partialderivative", 0x8ef }, +{ "function", 0x8f6 }, +{ "leftarrow", 0x8fb }, +{ "uparrow", 0x8fc }, +{ "rightarrow", 0x8fd }, +{ "downarrow", 0x8fe }, +{ "blank", 0x9df }, +{ "soliddiamond", 0x9e0 }, +{ "checkerboard", 0x9e1 }, +{ "ht", 0x9e2 }, +{ "ff", 0x9e3 }, +{ "cr", 0x9e4 }, +{ "lf", 0x9e5 }, +{ "nl", 0x9e8 }, +{ "vt", 0x9e9 }, +{ "lowrightcorner", 0x9ea }, +{ "uprightcorner", 0x9eb }, +{ "upleftcorner", 0x9ec }, +{ "lowleftcorner", 0x9ed }, +{ "crossinglines", 0x9ee }, +{ "horizlinescan1", 0x9ef }, +{ "horizlinescan3", 0x9f0 }, +{ "horizlinescan5", 0x9f1 }, +{ "horizlinescan7", 0x9f2 }, +{ "horizlinescan9", 0x9f3 }, +{ "leftt", 0x9f4 }, +{ "rightt", 0x9f5 }, +{ "bott", 0x9f6 }, +{ "topt", 0x9f7 }, +{ "vertbar", 0x9f8 }, +{ "emspace", 0xaa1 }, +{ "enspace", 0xaa2 }, +{ "em3space", 0xaa3 }, +{ "em4space", 0xaa4 }, +{ "digitspace", 0xaa5 }, +{ "punctspace", 0xaa6 }, +{ "thinspace", 0xaa7 }, +{ "hairspace", 0xaa8 }, +{ "emdash", 0xaa9 }, +{ "endash", 0xaaa }, +{ "signifblank", 0xaac }, +{ "ellipsis", 0xaae }, +{ "doubbaselinedot", 0xaaf }, +{ "onethird", 0xab0 }, +{ "twothirds", 0xab1 }, +{ "onefifth", 0xab2 }, +{ "twofifths", 0xab3 }, +{ "threefifths", 0xab4 }, +{ "fourfifths", 0xab5 }, +{ "onesixth", 0xab6 }, +{ "fivesixths", 0xab7 }, +{ "careof", 0xab8 }, +{ "figdash", 0xabb }, +{ "leftanglebracket", 0xabc }, +{ "decimalpoint", 0xabd }, +{ "rightanglebracket", 0xabe }, +{ "marker", 0xabf }, +{ "oneeighth", 0xac3 }, +{ "threeeighths", 0xac4 }, +{ "fiveeighths", 0xac5 }, +{ "seveneighths", 0xac6 }, +{ "trademark", 0xac9 }, +{ "signaturemark", 0xaca }, +{ "trademarkincircle", 0xacb }, +{ "leftopentriangle", 0xacc }, +{ "rightopentriangle", 0xacd }, +{ "emopencircle", 0xace }, +{ "emopenrectangle", 0xacf }, +{ "leftsinglequotemark", 0xad0 }, +{ "rightsinglequotemark", 0xad1 }, +{ "leftdoublequotemark", 0xad2 }, +{ "rightdoublequotemark", 0xad3 }, +{ "prescription", 0xad4 }, +{ "minutes", 0xad6 }, +{ "seconds", 0xad7 }, +{ "latincross", 0xad9 }, +{ "hexagram", 0xada }, +{ "filledrectbullet", 0xadb }, +{ "filledlefttribullet", 0xadc }, +{ "filledrighttribullet", 0xadd }, +{ "emfilledcircle", 0xade }, +{ "emfilledrect", 0xadf }, +{ "enopencircbullet", 0xae0 }, +{ "enopensquarebullet", 0xae1 }, +{ "openrectbullet", 0xae2 }, +{ "opentribulletup", 0xae3 }, +{ "opentribulletdown", 0xae4 }, +{ "openstar", 0xae5 }, +{ "enfilledcircbullet", 0xae6 }, +{ "enfilledsqbullet", 0xae7 }, +{ "filledtribulletup", 0xae8 }, +{ "filledtribulletdown", 0xae9 }, +{ "leftpointer", 0xaea }, +{ "rightpointer", 0xaeb }, +{ "club", 0xaec }, +{ "diamond", 0xaed }, +{ "heart", 0xaee }, +{ "maltesecross", 0xaf0 }, +{ "dagger", 0xaf1 }, +{ "doubledagger", 0xaf2 }, +{ "checkmark", 0xaf3 }, +{ "ballotcross", 0xaf4 }, +{ "musicalsharp", 0xaf5 }, +{ "musicalflat", 0xaf6 }, +{ "malesymbol", 0xaf7 }, +{ "femalesymbol", 0xaf8 }, +{ "telephone", 0xaf9 }, +{ "telephonerecorder", 0xafa }, +{ "phonographcopyright", 0xafb }, +{ "caret", 0xafc }, +{ "singlelowquotemark", 0xafd }, +{ "doublelowquotemark", 0xafe }, +{ "cursor", 0xaff }, +{ "leftcaret", 0xba3 }, +{ "rightcaret", 0xba6 }, +{ "downcaret", 0xba8 }, +{ "upcaret", 0xba9 }, +{ "overbar", 0xbc0 }, +{ "downtack", 0xbc2 }, +{ "upshoe", 0xbc3 }, +{ "downstile", 0xbc4 }, +{ "underbar", 0xbc6 }, +{ "jot", 0xbca }, +{ "quad", 0xbcc }, +{ "uptack", 0xbce }, +{ "circle", 0xbcf }, +{ "upstile", 0xbd3 }, +{ "downshoe", 0xbd6 }, +{ "rightshoe", 0xbd8 }, +{ "leftshoe", 0xbda }, +{ "lefttack", 0xbdc }, +{ "righttack", 0xbfc }, +{ "hebrew_aleph", 0xce0 }, +{ "hebrew_beth", 0xce1 }, +{ "hebrew_gimmel", 0xce2 }, +{ "hebrew_daleth", 0xce3 }, +{ "hebrew_he", 0xce4 }, +{ "hebrew_waw", 0xce5 }, +{ "hebrew_zayin", 0xce6 }, +{ "hebrew_het", 0xce7 }, +{ "hebrew_teth", 0xce8 }, +{ "hebrew_yod", 0xce9 }, +{ "hebrew_finalkaph", 0xcea }, +{ "hebrew_kaph", 0xceb }, +{ "hebrew_lamed", 0xcec }, +{ "hebrew_finalmem", 0xced }, +{ "hebrew_mem", 0xcee }, +{ "hebrew_finalnun", 0xcef }, +{ "hebrew_nun", 0xcf0 }, +{ "hebrew_samekh", 0xcf1 }, +{ "hebrew_ayin", 0xcf2 }, +{ "hebrew_finalpe", 0xcf3 }, +{ "hebrew_pe", 0xcf4 }, +{ "hebrew_finalzadi", 0xcf5 }, +{ "hebrew_zadi", 0xcf6 }, +{ "hebrew_kuf", 0xcf7 }, +{ "hebrew_resh", 0xcf8 }, +{ "hebrew_shin", 0xcf9 }, +{ "hebrew_taf", 0xcfa }, +{ "Hebrew_switch", 0xFF7E }, diff --git a/generic/tk.h b/generic/tk.h new file mode 100644 index 0000000..3e470f0 --- /dev/null +++ b/generic/tk.h @@ -0,0 +1,1538 @@ +/* + * tk.h -- + * + * Declarations for Tk-related things that are visible + * outside of the Tk module itself. + * + * Copyright (c) 1989-1994 The Regents of the University of California. + * Copyright (c) 1994 The Australian National University. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tk.h 1.211 97/11/20 12:44:45 + */ + +#ifndef _TK +#define _TK + +/* + * When version numbers change here, you must also go into the following files + * and update the version numbers: + * + * unix/configure.in + * win/makefile.bc + * win/makefile.vc + * library/tk.tcl + * + * The release level should be 0 for alpha, 1 for beta, and 2 for + * final/patch. The release serial value is the number that follows the + * "a", "b", or "p" in the patch level; for example, if the patch level + * is 4.3b2, TK_RELEASE_SERIAL is 2. It restarts at 1 whenever the + * release level is changed, except for the final release, which should + * be 0. + * + * You may also need to update some of these files when the numbers change + * for the version of Tcl that this release of Tk is compiled against. + */ + +#define TK_MAJOR_VERSION 8 +#define TK_MINOR_VERSION 0 +#define TK_RELEASE_LEVEL 2 +#define TK_RELEASE_SERIAL 2 + +#define TK_VERSION "8.0" +#define TK_PATCH_LEVEL "8.0p2" + +/* + * A special definition used to allow this header file to be included + * in resource files. + */ + +#ifndef RESOURCE_INCLUDED + +/* + * The following definitions set up the proper options for Macintosh + * compilers. We use this method because there is no autoconf equivalent. + */ + +#ifdef MAC_TCL +# ifndef REDO_KEYSYM_LOOKUP +# define REDO_KEYSYM_LOOKUP +# endif +#endif + +#ifndef _TCL +# include <tcl.h> +#endif +#ifndef _XLIB_H +# ifdef MAC_TCL +# include <Xlib.h> +# include <X.h> +# else +# include <X11/Xlib.h> +# endif +#endif +#ifdef __STDC__ +# include <stddef.h> +#endif + +/* + * Decide whether or not to use input methods. + */ + +#ifdef XNQueryInputStyle +#define TK_USE_INPUT_METHODS +#endif + +/* + * Dummy types that are used by clients: + */ + +typedef struct Tk_BindingTable_ *Tk_BindingTable; +typedef struct Tk_Canvas_ *Tk_Canvas; +typedef struct Tk_Cursor_ *Tk_Cursor; +typedef struct Tk_ErrorHandler_ *Tk_ErrorHandler; +typedef struct Tk_Font_ *Tk_Font; +typedef struct Tk_Image__ *Tk_Image; +typedef struct Tk_ImageMaster_ *Tk_ImageMaster; +typedef struct Tk_TextLayout_ *Tk_TextLayout; +typedef struct Tk_Window_ *Tk_Window; +typedef struct Tk_3DBorder_ *Tk_3DBorder; + +/* + * Additional types exported to clients. + */ + +typedef char *Tk_Uid; + +/* + * Structure used to specify how to handle argv options. + */ + +typedef struct { + char *key; /* The key string that flags the option in the + * argv array. */ + int type; /* Indicates option type; see below. */ + char *src; /* Value to be used in setting dst; usage + * depends on type. */ + char *dst; /* Address of value to be modified; usage + * depends on type. */ + char *help; /* Documentation message describing this option. */ +} Tk_ArgvInfo; + +/* + * Legal values for the type field of a Tk_ArgvInfo: see the user + * documentation for details. + */ + +#define TK_ARGV_CONSTANT 15 +#define TK_ARGV_INT 16 +#define TK_ARGV_STRING 17 +#define TK_ARGV_UID 18 +#define TK_ARGV_REST 19 +#define TK_ARGV_FLOAT 20 +#define TK_ARGV_FUNC 21 +#define TK_ARGV_GENFUNC 22 +#define TK_ARGV_HELP 23 +#define TK_ARGV_CONST_OPTION 24 +#define TK_ARGV_OPTION_VALUE 25 +#define TK_ARGV_OPTION_NAME_VALUE 26 +#define TK_ARGV_END 27 + +/* + * Flag bits for passing to Tk_ParseArgv: + */ + +#define TK_ARGV_NO_DEFAULTS 0x1 +#define TK_ARGV_NO_LEFTOVERS 0x2 +#define TK_ARGV_NO_ABBREV 0x4 +#define TK_ARGV_DONT_SKIP_FIRST_ARG 0x8 + +/* + * Structure used to describe application-specific configuration + * options: indicates procedures to call to parse an option and + * to return a text string describing an option. + */ + +typedef int (Tk_OptionParseProc) _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, Tk_Window tkwin, char *value, char *widgRec, + int offset)); +typedef char *(Tk_OptionPrintProc) _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin, char *widgRec, int offset, + Tcl_FreeProc **freeProcPtr)); + +typedef struct Tk_CustomOption { + Tk_OptionParseProc *parseProc; /* Procedure to call to parse an + * option and store it in converted + * form. */ + Tk_OptionPrintProc *printProc; /* Procedure to return a printable + * string describing an existing + * option. */ + ClientData clientData; /* Arbitrary one-word value used by + * option parser: passed to + * parseProc and printProc. */ +} Tk_CustomOption; + +/* + * Structure used to specify information for Tk_ConfigureWidget. Each + * structure gives complete information for one option, including + * how the option is specified on the command line, where it appears + * in the option database, etc. + */ + +typedef struct Tk_ConfigSpec { + int type; /* Type of option, such as TK_CONFIG_COLOR; + * see definitions below. Last option in + * table must have type TK_CONFIG_END. */ + char *argvName; /* Switch used to specify option in argv. + * NULL means this spec is part of a group. */ + char *dbName; /* Name for option in option database. */ + char *dbClass; /* Class for option in database. */ + char *defValue; /* Default value for option if not + * specified in command line or database. */ + int offset; /* Where in widget record to store value; + * use Tk_Offset macro to generate values + * for this. */ + int specFlags; /* Any combination of the values defined + * below; other bits are used internally + * by tkConfig.c. */ + Tk_CustomOption *customPtr; /* If type is TK_CONFIG_CUSTOM then this is + * a pointer to info about how to parse and + * print the option. Otherwise it is + * irrelevant. */ +} Tk_ConfigSpec; + +/* + * Type values for Tk_ConfigSpec structures. See the user + * documentation for details. + */ + +#define TK_CONFIG_BOOLEAN 1 +#define TK_CONFIG_INT 2 +#define TK_CONFIG_DOUBLE 3 +#define TK_CONFIG_STRING 4 +#define TK_CONFIG_UID 5 +#define TK_CONFIG_COLOR 6 +#define TK_CONFIG_FONT 7 +#define TK_CONFIG_BITMAP 8 +#define TK_CONFIG_BORDER 9 +#define TK_CONFIG_RELIEF 10 +#define TK_CONFIG_CURSOR 11 +#define TK_CONFIG_ACTIVE_CURSOR 12 +#define TK_CONFIG_JUSTIFY 13 +#define TK_CONFIG_ANCHOR 14 +#define TK_CONFIG_SYNONYM 15 +#define TK_CONFIG_CAP_STYLE 16 +#define TK_CONFIG_JOIN_STYLE 17 +#define TK_CONFIG_PIXELS 18 +#define TK_CONFIG_MM 19 +#define TK_CONFIG_WINDOW 20 +#define TK_CONFIG_CUSTOM 21 +#define TK_CONFIG_END 22 + +/* + * Macro to use to fill in "offset" fields of Tk_ConfigInfos. + * Computes number of bytes from beginning of structure to a + * given field. + */ + +#ifdef offsetof +#define Tk_Offset(type, field) ((int) offsetof(type, field)) +#else +#define Tk_Offset(type, field) ((int) ((char *) &((type *) 0)->field)) +#endif + +/* + * Possible values for flags argument to Tk_ConfigureWidget: + */ + +#define TK_CONFIG_ARGV_ONLY 1 + +/* + * Possible flag values for Tk_ConfigInfo structures. Any bits at + * or above TK_CONFIG_USER_BIT may be used by clients for selecting + * certain entries. Before changing any values here, coordinate with + * tkConfig.c (internal-use-only flags are defined there). + */ + +#define TK_CONFIG_COLOR_ONLY 1 +#define TK_CONFIG_MONO_ONLY 2 +#define TK_CONFIG_NULL_OK 4 +#define TK_CONFIG_DONT_SET_DEFAULT 8 +#define TK_CONFIG_OPTION_SPECIFIED 0x10 +#define TK_CONFIG_USER_BIT 0x100 + +/* + * Enumerated type for describing actions to be taken in response + * to a restrictProc established by Tk_RestrictEvents. + */ + +typedef enum { + TK_DEFER_EVENT, TK_PROCESS_EVENT, TK_DISCARD_EVENT +} Tk_RestrictAction; + +/* + * Priority levels to pass to Tk_AddOption: + */ + +#define TK_WIDGET_DEFAULT_PRIO 20 +#define TK_STARTUP_FILE_PRIO 40 +#define TK_USER_DEFAULT_PRIO 60 +#define TK_INTERACTIVE_PRIO 80 +#define TK_MAX_PRIO 100 + +/* + * Relief values returned by Tk_GetRelief: + */ + +#define TK_RELIEF_RAISED 1 +#define TK_RELIEF_FLAT 2 +#define TK_RELIEF_SUNKEN 4 +#define TK_RELIEF_GROOVE 8 +#define TK_RELIEF_RIDGE 16 +#define TK_RELIEF_SOLID 32 + +/* + * "Which" argument values for Tk_3DBorderGC: + */ + +#define TK_3D_FLAT_GC 1 +#define TK_3D_LIGHT_GC 2 +#define TK_3D_DARK_GC 3 + +/* + * Special EnterNotify/LeaveNotify "mode" for use in events + * generated by tkShare.c. Pick a high enough value that it's + * unlikely to conflict with existing values (like NotifyNormal) + * or any new values defined in the future. + */ + +#define TK_NOTIFY_SHARE 20 + +/* + * Enumerated type for describing a point by which to anchor something: + */ + +typedef enum { + TK_ANCHOR_N, TK_ANCHOR_NE, TK_ANCHOR_E, TK_ANCHOR_SE, + TK_ANCHOR_S, TK_ANCHOR_SW, TK_ANCHOR_W, TK_ANCHOR_NW, + TK_ANCHOR_CENTER +} Tk_Anchor; + +/* + * Enumerated type for describing a style of justification: + */ + +typedef enum { + TK_JUSTIFY_LEFT, TK_JUSTIFY_RIGHT, TK_JUSTIFY_CENTER +} Tk_Justify; + +/* + * The following structure is used by Tk_GetFontMetrics() to return + * information about the properties of a Tk_Font. + */ + +typedef struct Tk_FontMetrics { + int ascent; /* The amount in pixels that the tallest + * letter sticks up above the baseline, plus + * any extra blank space added by the designer + * of the font. */ + int descent; /* The largest amount in pixels that any + * letter sticks below the baseline, plus any + * extra blank space added by the designer of + * the font. */ + int linespace; /* The sum of the ascent and descent. How + * far apart two lines of text in the same + * font should be placed so that none of the + * characters in one line overlap any of the + * characters in the other line. */ +} Tk_FontMetrics; + +/* + * Flags passed to Tk_MeasureChars: + */ + +#define TK_WHOLE_WORDS 1 +#define TK_AT_LEAST_ONE 2 +#define TK_PARTIAL_OK 4 + +/* + * Flags passed to Tk_ComputeTextLayout: + */ + +#define TK_IGNORE_TABS 8 +#define TK_IGNORE_NEWLINES 16 + +/* + * Each geometry manager (the packer, the placer, etc.) is represented + * by a structure of the following form, which indicates procedures + * to invoke in the geometry manager to carry out certain functions. + */ + +typedef void (Tk_GeomRequestProc) _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); +typedef void (Tk_GeomLostSlaveProc) _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); + +typedef struct Tk_GeomMgr { + char *name; /* Name of the geometry manager (command + * used to invoke it, or name of widget + * class that allows embedded widgets). */ + Tk_GeomRequestProc *requestProc; + /* Procedure to invoke when a slave's + * requested geometry changes. */ + Tk_GeomLostSlaveProc *lostSlaveProc; + /* Procedure to invoke when a slave is + * taken away from one geometry manager + * by another. NULL means geometry manager + * doesn't care when slaves are lost. */ +} Tk_GeomMgr; + +/* + * Result values returned by Tk_GetScrollInfo: + */ + +#define TK_SCROLL_MOVETO 1 +#define TK_SCROLL_PAGES 2 +#define TK_SCROLL_UNITS 3 +#define TK_SCROLL_ERROR 4 + +/* + *--------------------------------------------------------------------------- + * + * Extensions to the X event set + * + *--------------------------------------------------------------------------- + */ +#define VirtualEvent (LASTEvent) +#define ActivateNotify (LASTEvent + 1) +#define DeactivateNotify (LASTEvent + 2) +#define TK_LASTEVENT (LASTEvent + 3) + +#define VirtualEventMask (1L << 30) +#define ActivateMask (1L << 29) +#define TK_LASTEVENT (LASTEvent + 3) + + +/* + * A virtual event shares most of its fields with the XKeyEvent and + * XButtonEvent structures. 99% of the time a virtual event will be + * an abstraction of a key or button event, so this structure provides + * the most information to the user. The only difference is the changing + * of the detail field for a virtual event so that it holds the name of the + * virtual event being triggered. + */ + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* True if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window event; /* Window on which event was requested. */ + Window root; /* root window that the event occured on */ + Window subwindow; /* child window */ + Time time; /* milliseconds */ + int x, y; /* pointer x, y coordinates in event window */ + int x_root, y_root; /* coordinates relative to root */ + unsigned int state; /* key or button mask */ + Tk_Uid name; /* Name of virtual event. */ + Bool same_screen; /* same screen flag */ +} XVirtualEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* True if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; /* Window in which event occurred. */ +} XActivateDeactivateEvent; +typedef XActivateDeactivateEvent XActivateEvent; +typedef XActivateDeactivateEvent XDeactivateEvent; + +/* + *-------------------------------------------------------------- + * + * Macros for querying Tk_Window structures. See the + * manual entries for documentation. + * + *-------------------------------------------------------------- + */ + +#define Tk_Display(tkwin) (((Tk_FakeWin *) (tkwin))->display) +#define Tk_ScreenNumber(tkwin) (((Tk_FakeWin *) (tkwin))->screenNum) +#define Tk_Screen(tkwin) (ScreenOfDisplay(Tk_Display(tkwin), \ + Tk_ScreenNumber(tkwin))) +#define Tk_Depth(tkwin) (((Tk_FakeWin *) (tkwin))->depth) +#define Tk_Visual(tkwin) (((Tk_FakeWin *) (tkwin))->visual) +#define Tk_WindowId(tkwin) (((Tk_FakeWin *) (tkwin))->window) +#define Tk_PathName(tkwin) (((Tk_FakeWin *) (tkwin))->pathName) +#define Tk_Name(tkwin) (((Tk_FakeWin *) (tkwin))->nameUid) +#define Tk_Class(tkwin) (((Tk_FakeWin *) (tkwin))->classUid) +#define Tk_X(tkwin) (((Tk_FakeWin *) (tkwin))->changes.x) +#define Tk_Y(tkwin) (((Tk_FakeWin *) (tkwin))->changes.y) +#define Tk_Width(tkwin) (((Tk_FakeWin *) (tkwin))->changes.width) +#define Tk_Height(tkwin) \ + (((Tk_FakeWin *) (tkwin))->changes.height) +#define Tk_Changes(tkwin) (&((Tk_FakeWin *) (tkwin))->changes) +#define Tk_Attributes(tkwin) (&((Tk_FakeWin *) (tkwin))->atts) +#define Tk_IsEmbedded(tkwin) \ + (((Tk_FakeWin *) (tkwin))->flags & TK_EMBEDDED) +#define Tk_IsContainer(tkwin) \ + (((Tk_FakeWin *) (tkwin))->flags & TK_CONTAINER) +#define Tk_IsMapped(tkwin) \ + (((Tk_FakeWin *) (tkwin))->flags & TK_MAPPED) +#define Tk_IsTopLevel(tkwin) \ + (((Tk_FakeWin *) (tkwin))->flags & TK_TOP_LEVEL) +#define Tk_ReqWidth(tkwin) (((Tk_FakeWin *) (tkwin))->reqWidth) +#define Tk_ReqHeight(tkwin) (((Tk_FakeWin *) (tkwin))->reqHeight) +#define Tk_InternalBorderWidth(tkwin) \ + (((Tk_FakeWin *) (tkwin))->internalBorderWidth) +#define Tk_Parent(tkwin) (((Tk_FakeWin *) (tkwin))->parentPtr) +#define Tk_Colormap(tkwin) (((Tk_FakeWin *) (tkwin))->atts.colormap) + +/* + * The structure below is needed by the macros above so that they can + * access the fields of a Tk_Window. The fields not needed by the macros + * are declared as "dummyX". The structure has its own type in order to + * prevent applications from accessing Tk_Window fields except using + * official macros. WARNING!! The structure definition must be kept + * consistent with the TkWindow structure in tkInt.h. If you change one, + * then change the other. See the declaration in tkInt.h for + * documentation on what the fields are used for internally. + */ + +typedef struct Tk_FakeWin { + Display *display; + char *dummy1; + int screenNum; + Visual *visual; + int depth; + Window window; + char *dummy2; + char *dummy3; + Tk_Window parentPtr; + char *dummy4; + char *dummy5; + char *pathName; + Tk_Uid nameUid; + Tk_Uid classUid; + XWindowChanges changes; + unsigned int dummy6; + XSetWindowAttributes atts; + unsigned long dummy7; + unsigned int flags; + char *dummy8; +#ifdef TK_USE_INPUT_METHODS + XIC dummy9; +#endif /* TK_USE_INPUT_METHODS */ + ClientData *dummy10; + int dummy11; + int dummy12; + char *dummy13; + char *dummy14; + ClientData dummy15; + int reqWidth, reqHeight; + int internalBorderWidth; + char *dummy16; + char *dummy17; + ClientData dummy18; + char *dummy19; +} Tk_FakeWin; + +/* + * Flag values for TkWindow (and Tk_FakeWin) structures are: + * + * TK_MAPPED: 1 means window is currently mapped, + * 0 means unmapped. + * TK_TOP_LEVEL: 1 means this is a top-level window (it + * was or will be created as a child of + * a root window). + * TK_ALREADY_DEAD: 1 means the window is in the process of + * being destroyed already. + * TK_NEED_CONFIG_NOTIFY: 1 means that the window has been reconfigured + * before it was made to exist. At the time of + * making it exist a ConfigureNotify event needs + * to be generated. + * TK_GRAB_FLAG: Used to manage grabs. See tkGrab.c for + * details. + * TK_CHECKED_IC: 1 means we've already tried to get an input + * context for this window; if the ic field + * is NULL it means that there isn't a context + * for the field. + * TK_DONT_DESTROY_WINDOW: 1 means that Tk_DestroyWindow should not + * invoke XDestroyWindow to destroy this widget's + * X window. The flag is set when the window + * has already been destroyed elsewhere (e.g. + * by another application) or when it will be + * destroyed later (e.g. by destroying its + * parent). + * TK_WM_COLORMAP_WINDOW: 1 means that this window has at some time + * appeared in the WM_COLORMAP_WINDOWS property + * for its toplevel, so we have to remove it + * from that property if the window is + * deleted and the toplevel isn't. + * TK_EMBEDDED: 1 means that this window (which must be a + * toplevel) is not a free-standing window but + * rather is embedded in some other application. + * TK_CONTAINER: 1 means that this window is a container, and + * that some other application (either in + * this process or elsewhere) may be + * embedding itself inside the window. + * TK_BOTH_HALVES: 1 means that this window is used for + * application embedding (either as + * container or embedded application), and + * both the containing and embedded halves + * are associated with windows in this + * particular process. + * TK_DEFER_MODAL: 1 means that this window has deferred a modal + * loop until all of the bindings for the current + * event have been invoked. + * TK_WRAPPER: 1 means that this window is the extra + * wrapper window created around a toplevel + * to hold the menubar under Unix. See + * tkUnixWm.c for more information. + * TK_REPARENTED: 1 means that this window has been reparented + * so that as far as the window system is + * concerned it isn't a child of its Tk + * parent. Initially this is used only for + * special Unix menubar windows. + */ + + +#define TK_MAPPED 1 +#define TK_TOP_LEVEL 2 +#define TK_ALREADY_DEAD 4 +#define TK_NEED_CONFIG_NOTIFY 8 +#define TK_GRAB_FLAG 0x10 +#define TK_CHECKED_IC 0x20 +#define TK_DONT_DESTROY_WINDOW 0x40 +#define TK_WM_COLORMAP_WINDOW 0x80 +#define TK_EMBEDDED 0x100 +#define TK_CONTAINER 0x200 +#define TK_BOTH_HALVES 0x400 +#define TK_DEFER_MODAL 0x800 +#define TK_WRAPPER 0x1000 +#define TK_REPARENTED 0x2000 + +/* + *-------------------------------------------------------------- + * + * Procedure prototypes and structures used for defining new canvas + * items: + * + *-------------------------------------------------------------- + */ + +/* + * For each item in a canvas widget there exists one record with + * the following structure. Each actual item is represented by + * a record with the following stuff at its beginning, plus additional + * type-specific stuff after that. + */ + +#define TK_TAG_SPACE 3 + +typedef struct Tk_Item { + int id; /* Unique identifier for this item + * (also serves as first tag for + * item). */ + struct Tk_Item *nextPtr; /* Next in display list of all + * items in this canvas. Later items + * in list are drawn on top of earlier + * ones. */ + Tk_Uid staticTagSpace[TK_TAG_SPACE];/* Built-in space for limited # of + * tags. */ + Tk_Uid *tagPtr; /* Pointer to array of tags. Usually + * points to staticTagSpace, but + * may point to malloc-ed space if + * there are lots of tags. */ + int tagSpace; /* Total amount of tag space available + * at tagPtr. */ + int numTags; /* Number of tag slots actually used + * at *tagPtr. */ + struct Tk_ItemType *typePtr; /* Table of procedures that implement + * this type of item. */ + int x1, y1, x2, y2; /* Bounding box for item, in integer + * canvas units. Set by item-specific + * code and guaranteed to contain every + * pixel drawn in item. Item area + * includes x1 and y1 but not x2 + * and y2. */ + + /* + *------------------------------------------------------------------ + * Starting here is additional type-specific stuff; see the + * declarations for individual types to see what is part of + * each type. The actual space below is determined by the + * "itemInfoSize" of the type's Tk_ItemType record. + *------------------------------------------------------------------ + */ +} Tk_Item; + +/* + * Records of the following type are used to describe a type of + * item (e.g. lines, circles, etc.) that can form part of a + * canvas widget. + */ + +typedef int Tk_ItemCreateProc _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv)); +typedef int Tk_ItemConfigureProc _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv, int flags)); +typedef int Tk_ItemCoordProc _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv)); +typedef void Tk_ItemDeleteProc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display)); +typedef void Tk_ItemDisplayProc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display, Drawable dst, + int x, int y, int width, int height)); +typedef double Tk_ItemPointProc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *pointPtr)); +typedef int Tk_ItemAreaProc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *rectPtr)); +typedef int Tk_ItemPostscriptProc _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int prepass)); +typedef void Tk_ItemScaleProc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double originX, double originY, + double scaleX, double scaleY)); +typedef void Tk_ItemTranslateProc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double deltaX, double deltaY)); +typedef int Tk_ItemIndexProc _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, char *indexString, + int *indexPtr)); +typedef void Tk_ItemCursorProc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, int index)); +typedef int Tk_ItemSelectionProc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, int offset, char *buffer, + int maxBytes)); +typedef void Tk_ItemInsertProc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, int beforeThis, char *string)); +typedef void Tk_ItemDCharsProc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, int first, int last)); + +typedef struct Tk_ItemType { + char *name; /* The name of this type of item, such + * as "line". */ + int itemSize; /* Total amount of space needed for + * item's record. */ + Tk_ItemCreateProc *createProc; /* Procedure to create a new item of + * this type. */ + Tk_ConfigSpec *configSpecs; /* Pointer to array of configuration + * specs for this type. Used for + * returning configuration info. */ + Tk_ItemConfigureProc *configProc; /* Procedure to call to change + * configuration options. */ + Tk_ItemCoordProc *coordProc; /* Procedure to call to get and set + * the item's coordinates. */ + Tk_ItemDeleteProc *deleteProc; /* Procedure to delete existing item of + * this type. */ + Tk_ItemDisplayProc *displayProc; /* Procedure to display items of + * this type. */ + int alwaysRedraw; /* Non-zero means displayProc should + * be called even when the item has + * been moved off-screen. */ + Tk_ItemPointProc *pointProc; /* Computes distance from item to + * a given point. */ + Tk_ItemAreaProc *areaProc; /* Computes whether item is inside, + * outside, or overlapping an area. */ + Tk_ItemPostscriptProc *postscriptProc; + /* Procedure to write a Postscript + * description for items of this + * type. */ + Tk_ItemScaleProc *scaleProc; /* Procedure to rescale items of + * this type. */ + Tk_ItemTranslateProc *translateProc;/* Procedure to translate items of + * this type. */ + Tk_ItemIndexProc *indexProc; /* Procedure to determine index of + * indicated character. NULL if + * item doesn't support indexing. */ + Tk_ItemCursorProc *icursorProc; /* Procedure to set insert cursor pos. + * to just before a given position. */ + Tk_ItemSelectionProc *selectionProc;/* Procedure to return selection (in + * STRING format) when it is in this + * item. */ + Tk_ItemInsertProc *insertProc; /* Procedure to insert something into + * an item. */ + Tk_ItemDCharsProc *dCharsProc; /* Procedure to delete characters + * from an item. */ + struct Tk_ItemType *nextPtr; /* Used to link types together into + * a list. */ +} Tk_ItemType; + +/* + * The following structure provides information about the selection and + * the insertion cursor. It is needed by only a few items, such as + * those that display text. It is shared by the generic canvas code + * and the item-specific code, but most of the fields should be written + * only by the canvas generic code. + */ + +typedef struct Tk_CanvasTextInfo { + Tk_3DBorder selBorder; /* Border and background for selected + * characters. Read-only to items.*/ + int selBorderWidth; /* Width of border around selection. + * Read-only to items. */ + XColor *selFgColorPtr; /* Foreground color for selected text. + * Read-only to items. */ + Tk_Item *selItemPtr; /* Pointer to selected item. NULL means + * selection isn't in this canvas. + * Writable by items. */ + int selectFirst; /* Index of first selected character. + * Writable by items. */ + int selectLast; /* Index of last selected character. + * Writable by items. */ + Tk_Item *anchorItemPtr; /* Item corresponding to "selectAnchor": + * not necessarily selItemPtr. Read-only + * to items. */ + int selectAnchor; /* Fixed end of selection (i.e. "select to" + * operation will use this as one end of the + * selection). Writable by items. */ + Tk_3DBorder insertBorder; /* Used to draw vertical bar for insertion + * cursor. Read-only to items. */ + int insertWidth; /* Total width of insertion cursor. Read-only + * to items. */ + int insertBorderWidth; /* Width of 3-D border around insert cursor. + * Read-only to items. */ + Tk_Item *focusItemPtr; /* Item that currently has the input focus, + * or NULL if no such item. Read-only to + * items. */ + int gotFocus; /* Non-zero means that the canvas widget has + * the input focus. Read-only to items.*/ + int cursorOn; /* Non-zero means that an insertion cursor + * should be displayed in focusItemPtr. + * Read-only to items.*/ +} Tk_CanvasTextInfo; + +/* + *-------------------------------------------------------------- + * + * Procedure prototypes and structures used for managing images: + * + *-------------------------------------------------------------- + */ + +typedef struct Tk_ImageType Tk_ImageType; +typedef int (Tk_ImageCreateProc) _ANSI_ARGS_((Tcl_Interp *interp, + char *name, int argc, char **argv, Tk_ImageType *typePtr, + Tk_ImageMaster master, ClientData *masterDataPtr)); +typedef ClientData (Tk_ImageGetProc) _ANSI_ARGS_((Tk_Window tkwin, + ClientData masterData)); +typedef void (Tk_ImageDisplayProc) _ANSI_ARGS_((ClientData instanceData, + Display *display, Drawable drawable, int imageX, int imageY, + int width, int height, int drawableX, int drawableY)); +typedef void (Tk_ImageFreeProc) _ANSI_ARGS_((ClientData instanceData, + Display *display)); +typedef void (Tk_ImageDeleteProc) _ANSI_ARGS_((ClientData masterData)); +typedef void (Tk_ImageChangedProc) _ANSI_ARGS_((ClientData clientData, + int x, int y, int width, int height, int imageWidth, + int imageHeight)); + +/* + * The following structure represents a particular type of image + * (bitmap, xpm image, etc.). It provides information common to + * all images of that type, such as the type name and a collection + * of procedures in the image manager that respond to various + * events. Each image manager is represented by one of these + * structures. + */ + +struct Tk_ImageType { + char *name; /* Name of image type. */ + Tk_ImageCreateProc *createProc; + /* Procedure to call to create a new image + * of this type. */ + Tk_ImageGetProc *getProc; /* Procedure to call the first time + * Tk_GetImage is called in a new way + * (new visual or screen). */ + Tk_ImageDisplayProc *displayProc; + /* Call to draw image, in response to + * Tk_RedrawImage calls. */ + Tk_ImageFreeProc *freeProc; /* Procedure to call whenever Tk_FreeImage + * is called to release an instance of an + * image. */ + Tk_ImageDeleteProc *deleteProc; + /* Procedure to call to delete image. It + * will not be called until after freeProc + * has been called for each instance of the + * image. */ + struct Tk_ImageType *nextPtr; + /* Next in list of all image types currently + * known. Filled in by Tk, not by image + * manager. */ +}; + +/* + *-------------------------------------------------------------- + * + * Additional definitions used to manage images of type "photo". + * + *-------------------------------------------------------------- + */ + +/* + * The following type is used to identify a particular photo image + * to be manipulated: + */ + +typedef void *Tk_PhotoHandle; + +/* + * The following structure describes a block of pixels in memory: + */ + +typedef struct Tk_PhotoImageBlock { + unsigned char *pixelPtr; /* Pointer to the first pixel. */ + int width; /* Width of block, in pixels. */ + int height; /* Height of block, in pixels. */ + int pitch; /* Address difference between corresponding + * pixels in successive lines. */ + int pixelSize; /* Address difference between successive + * pixels in the same line. */ + int offset[3]; /* Address differences between the red, green + * and blue components of the pixel and the + * pixel as a whole. */ +} Tk_PhotoImageBlock; + +/* + * Procedure prototypes and structures used in reading and + * writing photo images: + */ + +typedef struct Tk_PhotoImageFormat Tk_PhotoImageFormat; +typedef int (Tk_ImageFileMatchProc) _ANSI_ARGS_((Tcl_Channel chan, + char *fileName, char *formatString, int *widthPtr, int *heightPtr)); +typedef int (Tk_ImageStringMatchProc) _ANSI_ARGS_((char *string, + char *formatString, int *widthPtr, int *heightPtr)); +typedef int (Tk_ImageFileReadProc) _ANSI_ARGS_((Tcl_Interp *interp, + Tcl_Channel chan, char *fileName, char *formatString, + Tk_PhotoHandle imageHandle, int destX, int destY, + int width, int height, int srcX, int srcY)); +typedef int (Tk_ImageStringReadProc) _ANSI_ARGS_((Tcl_Interp *interp, + char *string, char *formatString, Tk_PhotoHandle imageHandle, + int destX, int destY, int width, int height, int srcX, int srcY)); +typedef int (Tk_ImageFileWriteProc) _ANSI_ARGS_((Tcl_Interp *interp, + char *fileName, char *formatString, Tk_PhotoImageBlock *blockPtr)); +typedef int (Tk_ImageStringWriteProc) _ANSI_ARGS_((Tcl_Interp *interp, + Tcl_DString *dataPtr, char *formatString, + Tk_PhotoImageBlock *blockPtr)); + +/* + * The following structure represents a particular file format for + * storing images (e.g., PPM, GIF, JPEG, etc.). It provides information + * to allow image files of that format to be recognized and read into + * a photo image. + */ + +struct Tk_PhotoImageFormat { + char *name; /* Name of image file format */ + Tk_ImageFileMatchProc *fileMatchProc; + /* Procedure to call to determine whether + * an image file matches this format. */ + Tk_ImageStringMatchProc *stringMatchProc; + /* Procedure to call to determine whether + * the data in a string matches this format. */ + Tk_ImageFileReadProc *fileReadProc; + /* Procedure to call to read data from + * an image file into a photo image. */ + Tk_ImageStringReadProc *stringReadProc; + /* Procedure to call to read data from + * a string into a photo image. */ + Tk_ImageFileWriteProc *fileWriteProc; + /* Procedure to call to write data from + * a photo image to a file. */ + Tk_ImageStringWriteProc *stringWriteProc; + /* Procedure to call to obtain a string + * representation of the data in a photo + * image.*/ + struct Tk_PhotoImageFormat *nextPtr; + /* Next in list of all photo image formats + * currently known. Filled in by Tk, not + * by image format handler. */ +}; + +/* + *-------------------------------------------------------------- + * + * The definitions below provide backward compatibility for + * functions and types related to event handling that used to + * be in Tk but have moved to Tcl. + * + *-------------------------------------------------------------- + */ + +#define TK_READABLE TCL_READABLE +#define TK_WRITABLE TCL_WRITABLE +#define TK_EXCEPTION TCL_EXCEPTION + +#define TK_DONT_WAIT TCL_DONT_WAIT +#define TK_X_EVENTS TCL_WINDOW_EVENTS +#define TK_WINDOW_EVENTS TCL_WINDOW_EVENTS +#define TK_FILE_EVENTS TCL_FILE_EVENTS +#define TK_TIMER_EVENTS TCL_TIMER_EVENTS +#define TK_IDLE_EVENTS TCL_IDLE_EVENTS +#define TK_ALL_EVENTS TCL_ALL_EVENTS + +#define Tk_IdleProc Tcl_IdleProc +#define Tk_FileProc Tcl_FileProc +#define Tk_TimerProc Tcl_TimerProc +#define Tk_TimerToken Tcl_TimerToken + +#define Tk_BackgroundError Tcl_BackgroundError +#define Tk_CancelIdleCall Tcl_CancelIdleCall +#define Tk_CreateFileHandler Tcl_CreateFileHandler +#define Tk_CreateTimerHandler Tcl_CreateTimerHandler +#define Tk_DeleteFileHandler Tcl_DeleteFileHandler +#define Tk_DeleteTimerHandler Tcl_DeleteTimerHandler +#define Tk_DoOneEvent Tcl_DoOneEvent +#define Tk_DoWhenIdle Tcl_DoWhenIdle +#define Tk_Sleep Tcl_Sleep + +/* Additional stuff that has moved to Tcl: */ + +#define Tk_AfterCmd Tcl_AfterCmd +#define Tk_EventuallyFree Tcl_EventuallyFree +#define Tk_FreeProc Tcl_FreeProc +#define Tk_Preserve Tcl_Preserve +#define Tk_Release Tcl_Release + +/* + *-------------------------------------------------------------- + * + * Additional procedure types defined by Tk. + * + *-------------------------------------------------------------- + */ + +typedef int (Tk_ErrorProc) _ANSI_ARGS_((ClientData clientData, + XErrorEvent *errEventPtr)); +typedef void (Tk_EventProc) _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +typedef int (Tk_GenericProc) _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +typedef int (Tk_GetSelProc) _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, char *portion)); +typedef void (Tk_LostSelProc) _ANSI_ARGS_((ClientData clientData)); +typedef Tk_RestrictAction (Tk_RestrictProc) _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +typedef int (Tk_SelectionProc) _ANSI_ARGS_((ClientData clientData, + int offset, char *buffer, int maxBytes)); + +/* + *-------------------------------------------------------------- + * + * Exported procedures and variables. + * + *-------------------------------------------------------------- + */ + +EXTERN XColor * Tk_3DBorderColor _ANSI_ARGS_((Tk_3DBorder border)); +EXTERN GC Tk_3DBorderGC _ANSI_ARGS_((Tk_Window tkwin, + Tk_3DBorder border, int which)); +EXTERN void Tk_3DHorizontalBevel _ANSI_ARGS_((Tk_Window tkwin, + Drawable drawable, Tk_3DBorder border, int x, + int y, int width, int height, int leftIn, + int rightIn, int topBevel, int relief)); +EXTERN void Tk_3DVerticalBevel _ANSI_ARGS_((Tk_Window tkwin, + Drawable drawable, Tk_3DBorder border, int x, + int y, int width, int height, int leftBevel, + int relief)); +EXTERN void Tk_AddOption _ANSI_ARGS_((Tk_Window tkwin, char *name, + char *value, int priority)); +EXTERN void Tk_BindEvent _ANSI_ARGS_((Tk_BindingTable bindingTable, + XEvent *eventPtr, Tk_Window tkwin, int numObjects, + ClientData *objectPtr)); +EXTERN void Tk_CanvasDrawableCoords _ANSI_ARGS_((Tk_Canvas canvas, + double x, double y, short *drawableXPtr, + short *drawableYPtr)); +EXTERN void Tk_CanvasEventuallyRedraw _ANSI_ARGS_(( + Tk_Canvas canvas, int x1, int y1, int x2, + int y2)); +EXTERN int Tk_CanvasGetCoord _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, char *string, + double *doublePtr)); +EXTERN Tk_CanvasTextInfo *Tk_CanvasGetTextInfo _ANSI_ARGS_((Tk_Canvas canvas)); +EXTERN int Tk_CanvasPsBitmap _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Pixmap bitmap, int x, int y, + int width, int height)); +EXTERN int Tk_CanvasPsColor _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, XColor *colorPtr)); +EXTERN int Tk_CanvasPsFont _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Font font)); +EXTERN void Tk_CanvasPsPath _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, double *coordPtr, int numPoints)); +EXTERN int Tk_CanvasPsStipple _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Pixmap bitmap)); +EXTERN double Tk_CanvasPsY _ANSI_ARGS_((Tk_Canvas canvas, double y)); +EXTERN void Tk_CanvasSetStippleOrigin _ANSI_ARGS_(( + Tk_Canvas canvas, GC gc)); +EXTERN int Tk_CanvasTagsParseProc _ANSI_ARGS_(( + ClientData clientData, Tcl_Interp *interp, + Tk_Window tkwin, char *value, char *widgRec, + int offset)); +EXTERN char * Tk_CanvasTagsPrintProc _ANSI_ARGS_(( + ClientData clientData, Tk_Window tkwin, + char *widgRec, int offset, + Tcl_FreeProc **freeProcPtr)); +EXTERN Tk_Window Tk_CanvasTkwin _ANSI_ARGS_((Tk_Canvas canvas)); +EXTERN void Tk_CanvasWindowCoords _ANSI_ARGS_((Tk_Canvas canvas, + double x, double y, short *screenXPtr, + short *screenYPtr)); +EXTERN void Tk_ChangeWindowAttributes _ANSI_ARGS_((Tk_Window tkwin, + unsigned long valueMask, + XSetWindowAttributes *attsPtr)); +EXTERN int Tk_CharBbox _ANSI_ARGS_((Tk_TextLayout layout, + int index, int *xPtr, int *yPtr, int *widthPtr, + int *heightPtr)); +EXTERN void Tk_ClearSelection _ANSI_ARGS_((Tk_Window tkwin, + Atom selection)); +EXTERN int Tk_ClipboardAppend _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Atom target, Atom format, + char* buffer)); +EXTERN int Tk_ClipboardClear _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin)); +EXTERN int Tk_ConfigureInfo _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_ConfigSpec *specs, + char *widgRec, char *argvName, int flags)); +EXTERN int Tk_ConfigureValue _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_ConfigSpec *specs, + char *widgRec, char *argvName, int flags)); +EXTERN int Tk_ConfigureWidget _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_ConfigSpec *specs, + int argc, char **argv, char *widgRec, + int flags)); +EXTERN void Tk_ConfigureWindow _ANSI_ARGS_((Tk_Window tkwin, + unsigned int valueMask, XWindowChanges *valuePtr)); +EXTERN Tk_TextLayout Tk_ComputeTextLayout _ANSI_ARGS_((Tk_Font font, + CONST char *string, int numChars, int wrapLength, + Tk_Justify justify, int flags, int *widthPtr, + int *heightPtr)); +EXTERN Tk_Window Tk_CoordsToWindow _ANSI_ARGS_((int rootX, int rootY, + Tk_Window tkwin)); +EXTERN unsigned long Tk_CreateBinding _ANSI_ARGS_((Tcl_Interp *interp, + Tk_BindingTable bindingTable, ClientData object, + char *eventString, char *command, int append)); +EXTERN Tk_BindingTable Tk_CreateBindingTable _ANSI_ARGS_((Tcl_Interp *interp)); +EXTERN Tk_ErrorHandler Tk_CreateErrorHandler _ANSI_ARGS_((Display *display, + int errNum, int request, int minorCode, + Tk_ErrorProc *errorProc, ClientData clientData)); +EXTERN void Tk_CreateEventHandler _ANSI_ARGS_((Tk_Window token, + unsigned long mask, Tk_EventProc *proc, + ClientData clientData)); +EXTERN void Tk_CreateGenericHandler _ANSI_ARGS_(( + Tk_GenericProc *proc, ClientData clientData)); +EXTERN void Tk_CreateImageType _ANSI_ARGS_(( + Tk_ImageType *typePtr)); +EXTERN void Tk_CreateItemType _ANSI_ARGS_((Tk_ItemType *typePtr)); +EXTERN void Tk_CreatePhotoImageFormat _ANSI_ARGS_(( + Tk_PhotoImageFormat *formatPtr)); +EXTERN void Tk_CreateSelHandler _ANSI_ARGS_((Tk_Window tkwin, + Atom selection, Atom target, + Tk_SelectionProc *proc, ClientData clientData, + Atom format)); +EXTERN Tk_Window Tk_CreateWindow _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window parent, char *name, char *screenName)); +EXTERN Tk_Window Tk_CreateWindowFromPath _ANSI_ARGS_(( + Tcl_Interp *interp, Tk_Window tkwin, + char *pathName, char *screenName)); +EXTERN int Tk_DefineBitmap _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Uid name, char *source, int width, + int height)); +EXTERN void Tk_DefineCursor _ANSI_ARGS_((Tk_Window window, + Tk_Cursor cursor)); +EXTERN void Tk_DeleteAllBindings _ANSI_ARGS_(( + Tk_BindingTable bindingTable, ClientData object)); +EXTERN int Tk_DeleteBinding _ANSI_ARGS_((Tcl_Interp *interp, + Tk_BindingTable bindingTable, ClientData object, + char *eventString)); +EXTERN void Tk_DeleteBindingTable _ANSI_ARGS_(( + Tk_BindingTable bindingTable)); +EXTERN void Tk_DeleteErrorHandler _ANSI_ARGS_(( + Tk_ErrorHandler handler)); +EXTERN void Tk_DeleteEventHandler _ANSI_ARGS_((Tk_Window token, + unsigned long mask, Tk_EventProc *proc, + ClientData clientData)); +EXTERN void Tk_DeleteGenericHandler _ANSI_ARGS_(( + Tk_GenericProc *proc, ClientData clientData)); +EXTERN void Tk_DeleteImage _ANSI_ARGS_((Tcl_Interp *interp, + char *name)); +EXTERN void Tk_DeleteSelHandler _ANSI_ARGS_((Tk_Window tkwin, + Atom selection, Atom target)); +EXTERN void Tk_DestroyWindow _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN char * Tk_DisplayName _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN int Tk_DistanceToTextLayout _ANSI_ARGS_(( + Tk_TextLayout layout, int x, int y)); +EXTERN void Tk_Draw3DPolygon _ANSI_ARGS_((Tk_Window tkwin, + Drawable drawable, Tk_3DBorder border, + XPoint *pointPtr, int numPoints, int borderWidth, + int leftRelief)); +EXTERN void Tk_Draw3DRectangle _ANSI_ARGS_((Tk_Window tkwin, + Drawable drawable, Tk_3DBorder border, int x, + int y, int width, int height, int borderWidth, + int relief)); +EXTERN void Tk_DrawChars _ANSI_ARGS_((Display *display, + Drawable drawable, GC gc, Tk_Font tkfont, + CONST char *source, int numChars, int x, + int y)); +EXTERN void Tk_DrawFocusHighlight _ANSI_ARGS_((Tk_Window tkwin, + GC gc, int width, Drawable drawable)); +EXTERN void Tk_DrawTextLayout _ANSI_ARGS_((Display *display, + Drawable drawable, GC gc, Tk_TextLayout layout, + int x, int y, int firstChar, int lastChar)); +EXTERN void Tk_Fill3DPolygon _ANSI_ARGS_((Tk_Window tkwin, + Drawable drawable, Tk_3DBorder border, + XPoint *pointPtr, int numPoints, int borderWidth, + int leftRelief)); +EXTERN void Tk_Fill3DRectangle _ANSI_ARGS_((Tk_Window tkwin, + Drawable drawable, Tk_3DBorder border, int x, + int y, int width, int height, int borderWidth, + int relief)); +EXTERN Tk_PhotoHandle Tk_FindPhoto _ANSI_ARGS_((Tcl_Interp *interp, + char *imageName)); +EXTERN Font Tk_FontId _ANSI_ARGS_((Tk_Font font)); +EXTERN void Tk_Free3DBorder _ANSI_ARGS_((Tk_3DBorder border)); +EXTERN void Tk_FreeBitmap _ANSI_ARGS_((Display *display, + Pixmap bitmap)); +EXTERN void Tk_FreeColor _ANSI_ARGS_((XColor *colorPtr)); +EXTERN void Tk_FreeColormap _ANSI_ARGS_((Display *display, + Colormap colormap)); +EXTERN void Tk_FreeCursor _ANSI_ARGS_((Display *display, + Tk_Cursor cursor)); +EXTERN void Tk_FreeFont _ANSI_ARGS_((Tk_Font)); +EXTERN void Tk_FreeGC _ANSI_ARGS_((Display *display, GC gc)); +EXTERN void Tk_FreeImage _ANSI_ARGS_((Tk_Image image)); +EXTERN void Tk_FreeOptions _ANSI_ARGS_((Tk_ConfigSpec *specs, + char *widgRec, Display *display, int needFlags)); +EXTERN void Tk_FreePixmap _ANSI_ARGS_((Display *display, + Pixmap pixmap)); +EXTERN void Tk_FreeTextLayout _ANSI_ARGS_(( + Tk_TextLayout textLayout)); +EXTERN void Tk_FreeXId _ANSI_ARGS_((Display *display, XID xid)); +EXTERN GC Tk_GCForColor _ANSI_ARGS_((XColor *colorPtr, + Drawable drawable)); +EXTERN void Tk_GeometryRequest _ANSI_ARGS_((Tk_Window tkwin, + int reqWidth, int reqHeight)); +EXTERN Tk_3DBorder Tk_Get3DBorder _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_Uid colorName)); +EXTERN void Tk_GetAllBindings _ANSI_ARGS_((Tcl_Interp *interp, + Tk_BindingTable bindingTable, ClientData object)); +EXTERN int Tk_GetAnchor _ANSI_ARGS_((Tcl_Interp *interp, + char *string, Tk_Anchor *anchorPtr)); +EXTERN char * Tk_GetAtomName _ANSI_ARGS_((Tk_Window tkwin, + Atom atom)); +EXTERN char * Tk_GetBinding _ANSI_ARGS_((Tcl_Interp *interp, + Tk_BindingTable bindingTable, ClientData object, + char *eventString)); +EXTERN Pixmap Tk_GetBitmap _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_Uid string)); +EXTERN Pixmap Tk_GetBitmapFromData _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *source, + int width, int height)); +EXTERN int Tk_GetCapStyle _ANSI_ARGS_((Tcl_Interp *interp, + char *string, int *capPtr)); +EXTERN XColor * Tk_GetColor _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_Uid name)); +EXTERN XColor * Tk_GetColorByValue _ANSI_ARGS_((Tk_Window tkwin, + XColor *colorPtr)); +EXTERN Colormap Tk_GetColormap _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *string)); +EXTERN Tk_Cursor Tk_GetCursor _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_Uid string)); +EXTERN Tk_Cursor Tk_GetCursorFromData _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *source, char *mask, + int width, int height, int xHot, int yHot, + Tk_Uid fg, Tk_Uid bg)); +EXTERN Tk_Font Tk_GetFont _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, CONST char *string)); +EXTERN Tk_Font Tk_GetFontFromObj _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tcl_Obj *objPtr)); +EXTERN void Tk_GetFontMetrics _ANSI_ARGS_((Tk_Font font, + Tk_FontMetrics *fmPtr)); +EXTERN GC Tk_GetGC _ANSI_ARGS_((Tk_Window tkwin, + unsigned long valueMask, XGCValues *valuePtr)); +EXTERN Tk_Image Tk_GetImage _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *name, + Tk_ImageChangedProc *changeProc, + ClientData clientData)); +EXTERN ClientData Tk_GetImageMasterData _ANSI_ARGS_ ((Tcl_Interp *interp, + char *name, Tk_ImageType **typePtrPtr)); +EXTERN Tk_ItemType * Tk_GetItemTypes _ANSI_ARGS_((void)); +EXTERN int Tk_GetJoinStyle _ANSI_ARGS_((Tcl_Interp *interp, + char *string, int *joinPtr)); +EXTERN int Tk_GetJustify _ANSI_ARGS_((Tcl_Interp *interp, + char *string, Tk_Justify *justifyPtr)); +EXTERN int Tk_GetNumMainWindows _ANSI_ARGS_((void)); +EXTERN Tk_Uid Tk_GetOption _ANSI_ARGS_((Tk_Window tkwin, char *name, + char *className)); +EXTERN int Tk_GetPixels _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *string, int *intPtr)); +EXTERN Pixmap Tk_GetPixmap _ANSI_ARGS_((Display *display, Drawable d, + int width, int height, int depth)); +EXTERN int Tk_GetRelief _ANSI_ARGS_((Tcl_Interp *interp, + char *name, int *reliefPtr)); +EXTERN void Tk_GetRootCoords _ANSI_ARGS_ ((Tk_Window tkwin, + int *xPtr, int *yPtr)); +EXTERN int Tk_GetScrollInfo _ANSI_ARGS_((Tcl_Interp *interp, + int argc, char **argv, double *dblPtr, + int *intPtr)); +EXTERN int Tk_GetScreenMM _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *string, double *doublePtr)); +EXTERN int Tk_GetSelection _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Atom selection, Atom target, + Tk_GetSelProc *proc, ClientData clientData)); +EXTERN Tk_Uid Tk_GetUid _ANSI_ARGS_((CONST char *string)); +EXTERN Visual * Tk_GetVisual _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *string, int *depthPtr, + Colormap *colormapPtr)); +EXTERN void Tk_GetVRootGeometry _ANSI_ARGS_((Tk_Window tkwin, + int *xPtr, int *yPtr, int *widthPtr, + int *heightPtr)); +EXTERN int Tk_Grab _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, int grabGlobal)); +EXTERN void Tk_HandleEvent _ANSI_ARGS_((XEvent *eventPtr)); +EXTERN Tk_Window Tk_IdToWindow _ANSI_ARGS_((Display *display, + Window window)); +EXTERN void Tk_ImageChanged _ANSI_ARGS_(( + Tk_ImageMaster master, int x, int y, + int width, int height, int imageWidth, + int imageHeight)); +EXTERN int Tk_Init _ANSI_ARGS_((Tcl_Interp *interp)); +EXTERN Atom Tk_InternAtom _ANSI_ARGS_((Tk_Window tkwin, + char *name)); +EXTERN int Tk_IntersectTextLayout _ANSI_ARGS_(( + Tk_TextLayout layout, int x, int y, int width, + int height)); +EXTERN void Tk_Main _ANSI_ARGS_((int argc, char **argv, + Tcl_AppInitProc *appInitProc)); +EXTERN void Tk_MainLoop _ANSI_ARGS_((void)); +EXTERN void Tk_MaintainGeometry _ANSI_ARGS_((Tk_Window slave, + Tk_Window master, int x, int y, int width, + int height)); +EXTERN Tk_Window Tk_MainWindow _ANSI_ARGS_((Tcl_Interp *interp)); +EXTERN void Tk_MakeWindowExist _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN void Tk_ManageGeometry _ANSI_ARGS_((Tk_Window tkwin, + Tk_GeomMgr *mgrPtr, ClientData clientData)); +EXTERN void Tk_MapWindow _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN int Tk_MeasureChars _ANSI_ARGS_((Tk_Font tkfont, + CONST char *source, int maxChars, int maxPixels, + int flags, int *lengthPtr)); +EXTERN void Tk_MoveResizeWindow _ANSI_ARGS_((Tk_Window tkwin, + int x, int y, int width, int height)); +EXTERN void Tk_MoveWindow _ANSI_ARGS_((Tk_Window tkwin, int x, + int y)); +EXTERN void Tk_MoveToplevelWindow _ANSI_ARGS_((Tk_Window tkwin, + int x, int y)); +EXTERN char * Tk_NameOf3DBorder _ANSI_ARGS_((Tk_3DBorder border)); +EXTERN char * Tk_NameOfAnchor _ANSI_ARGS_((Tk_Anchor anchor)); +EXTERN char * Tk_NameOfBitmap _ANSI_ARGS_((Display *display, + Pixmap bitmap)); +EXTERN char * Tk_NameOfCapStyle _ANSI_ARGS_((int cap)); +EXTERN char * Tk_NameOfColor _ANSI_ARGS_((XColor *colorPtr)); +EXTERN char * Tk_NameOfCursor _ANSI_ARGS_((Display *display, + Tk_Cursor cursor)); +EXTERN char * Tk_NameOfFont _ANSI_ARGS_((Tk_Font font)); +EXTERN char * Tk_NameOfImage _ANSI_ARGS_(( + Tk_ImageMaster imageMaster)); +EXTERN char * Tk_NameOfJoinStyle _ANSI_ARGS_((int join)); +EXTERN char * Tk_NameOfJustify _ANSI_ARGS_((Tk_Justify justify)); +EXTERN char * Tk_NameOfRelief _ANSI_ARGS_((int relief)); +EXTERN Tk_Window Tk_NameToWindow _ANSI_ARGS_((Tcl_Interp *interp, + char *pathName, Tk_Window tkwin)); +EXTERN void Tk_OwnSelection _ANSI_ARGS_((Tk_Window tkwin, + Atom selection, Tk_LostSelProc *proc, + ClientData clientData)); +EXTERN int Tk_ParseArgv _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, int *argcPtr, char **argv, + Tk_ArgvInfo *argTable, int flags)); +EXTERN void Tk_PhotoPutBlock _ANSI_ARGS_((Tk_PhotoHandle handle, + Tk_PhotoImageBlock *blockPtr, int x, int y, + int width, int height)); +EXTERN void Tk_PhotoPutZoomedBlock _ANSI_ARGS_(( + Tk_PhotoHandle handle, + Tk_PhotoImageBlock *blockPtr, int x, int y, + int width, int height, int zoomX, int zoomY, + int subsampleX, int subsampleY)); +EXTERN int Tk_PhotoGetImage _ANSI_ARGS_((Tk_PhotoHandle handle, + Tk_PhotoImageBlock *blockPtr)); +EXTERN void Tk_PhotoBlank _ANSI_ARGS_((Tk_PhotoHandle handle)); +EXTERN void Tk_PhotoExpand _ANSI_ARGS_((Tk_PhotoHandle handle, + int width, int height )); +EXTERN void Tk_PhotoGetSize _ANSI_ARGS_((Tk_PhotoHandle handle, + int *widthPtr, int *heightPtr)); +EXTERN void Tk_PhotoSetSize _ANSI_ARGS_((Tk_PhotoHandle handle, + int width, int height)); +EXTERN int Tk_PointToChar _ANSI_ARGS_((Tk_TextLayout layout, + int x, int y)); +EXTERN int Tk_PostscriptFontName _ANSI_ARGS_((Tk_Font tkfont, + Tcl_DString *dsPtr)); +EXTERN void Tk_PreserveColormap _ANSI_ARGS_((Display *display, + Colormap colormap)); +EXTERN void Tk_QueueWindowEvent _ANSI_ARGS_((XEvent *eventPtr, + Tcl_QueuePosition position)); +EXTERN void Tk_RedrawImage _ANSI_ARGS_((Tk_Image image, int imageX, + int imageY, int width, int height, + Drawable drawable, int drawableX, int drawableY)); +EXTERN void Tk_ResizeWindow _ANSI_ARGS_((Tk_Window tkwin, + int width, int height)); +EXTERN int Tk_RestackWindow _ANSI_ARGS_((Tk_Window tkwin, + int aboveBelow, Tk_Window other)); +EXTERN Tk_RestrictProc *Tk_RestrictEvents _ANSI_ARGS_((Tk_RestrictProc *proc, + ClientData arg, ClientData *prevArgPtr)); +EXTERN int Tk_SafeInit _ANSI_ARGS_((Tcl_Interp *interp)); +EXTERN char * Tk_SetAppName _ANSI_ARGS_((Tk_Window tkwin, + char *name)); +EXTERN void Tk_SetBackgroundFromBorder _ANSI_ARGS_(( + Tk_Window tkwin, Tk_3DBorder border)); +EXTERN void Tk_SetClass _ANSI_ARGS_((Tk_Window tkwin, + char *className)); +EXTERN void Tk_SetGrid _ANSI_ARGS_((Tk_Window tkwin, + int reqWidth, int reqHeight, int gridWidth, + int gridHeight)); +EXTERN void Tk_SetInternalBorder _ANSI_ARGS_((Tk_Window tkwin, + int width)); +EXTERN void Tk_SetWindowBackground _ANSI_ARGS_((Tk_Window tkwin, + unsigned long pixel)); +EXTERN void Tk_SetWindowBackgroundPixmap _ANSI_ARGS_(( + Tk_Window tkwin, Pixmap pixmap)); +EXTERN void Tk_SetWindowBorder _ANSI_ARGS_((Tk_Window tkwin, + unsigned long pixel)); +EXTERN void Tk_SetWindowBorderWidth _ANSI_ARGS_((Tk_Window tkwin, + int width)); +EXTERN void Tk_SetWindowBorderPixmap _ANSI_ARGS_((Tk_Window tkwin, + Pixmap pixmap)); +EXTERN void Tk_SetWindowColormap _ANSI_ARGS_((Tk_Window tkwin, + Colormap colormap)); +EXTERN int Tk_SetWindowVisual _ANSI_ARGS_((Tk_Window tkwin, + Visual *visual, int depth, + Colormap colormap)); +EXTERN void Tk_SizeOfBitmap _ANSI_ARGS_((Display *display, + Pixmap bitmap, int *widthPtr, + int *heightPtr)); +EXTERN void Tk_SizeOfImage _ANSI_ARGS_((Tk_Image image, + int *widthPtr, int *heightPtr)); +EXTERN int Tk_StrictMotif _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN void Tk_TextLayoutToPostscript _ANSI_ARGS_(( + Tcl_Interp *interp, Tk_TextLayout layout)); +EXTERN int Tk_TextWidth _ANSI_ARGS_((Tk_Font font, + CONST char *string, int numChars)); +EXTERN void Tk_UndefineCursor _ANSI_ARGS_((Tk_Window window)); +EXTERN void Tk_UnderlineChars _ANSI_ARGS_((Display *display, + Drawable drawable, GC gc, Tk_Font tkfont, + CONST char *source, int x, int y, int firstChar, + int lastChar)); +EXTERN void Tk_UnderlineTextLayout _ANSI_ARGS_(( + Display *display, Drawable drawable, GC gc, + Tk_TextLayout layout, int x, int y, + int underline)); +EXTERN void Tk_Ungrab _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN void Tk_UnmaintainGeometry _ANSI_ARGS_((Tk_Window slave, + Tk_Window master)); +EXTERN void Tk_UnmapWindow _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN void Tk_UnsetGrid _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN void Tk_UpdatePointer _ANSI_ARGS_((Tk_Window tkwin, + int x, int y, int state)); + +/* + * Tcl commands exported by Tk: + */ + +EXTERN int Tk_AfterCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_BellCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_BindCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_BindtagsCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_ButtonCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_CanvasCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_CheckbuttonCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_ClipboardCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_ChooseColorCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_ChooseFontCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_DestroyCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_EntryCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_EventCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_FileeventCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_FrameCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_FocusCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_FontObjCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int objc, + Tcl_Obj *CONST objv[])); +EXTERN int Tk_GetOpenFileCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_GetSaveFileCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_GrabCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_GridCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_ImageCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_LabelCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_ListboxCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_LowerCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_MenuCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_MenubuttonCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_MessageBoxCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_MessageCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_OptionCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_PackCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_PlaceCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_RadiobuttonCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_RaiseCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_ScaleCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_ScrollbarCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_SelectionCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_SendCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_TextCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_TkObjCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int objc, + Tcl_Obj *CONST objv[])); +EXTERN int Tk_TkwaitCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_ToplevelCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_UpdateCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int Tk_WinfoObjCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int objc, + Tcl_Obj *CONST objv[])); +EXTERN int Tk_WmCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); + +#endif /* RESOURCE_INCLUDED */ +#endif /* _TK */ diff --git a/generic/tk3d.c b/generic/tk3d.c new file mode 100644 index 0000000..53eec8b --- /dev/null +++ b/generic/tk3d.c @@ -0,0 +1,949 @@ +/* + * tk3d.c -- + * + * This module provides procedures to draw borders in + * the three-dimensional Motif style. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tk3d.c 1.60 97/01/13 17:23:10 + */ + +#include <tk3d.h> + +/* + * Hash table to map from a border's values (color, etc.) to a + * Border structure for those values. + */ + +static Tcl_HashTable borderTable; +typedef struct { + Tk_Uid colorName; /* Color for border. */ + Colormap colormap; /* Colormap used for allocating border + * colors. */ + Screen *screen; /* Screen on which border will be drawn. */ +} BorderKey; + +static int initialized = 0; /* 0 means static structures haven't + * been initialized yet. */ + +/* + * Forward declarations for procedures defined in this file: + */ + +static void BorderInit _ANSI_ARGS_((void)); +static int Intersect _ANSI_ARGS_((XPoint *a1Ptr, XPoint *a2Ptr, + XPoint *b1Ptr, XPoint *b2Ptr, XPoint *iPtr)); +static void ShiftLine _ANSI_ARGS_((XPoint *p1Ptr, XPoint *p2Ptr, + int distance, XPoint *p3Ptr)); + +/* + *-------------------------------------------------------------- + * + * Tk_Get3DBorder -- + * + * Create a data structure for displaying a 3-D border. + * + * Results: + * The return value is a token for a data structure + * describing a 3-D border. This token may be passed + * to Tk_Draw3DRectangle and Tk_Free3DBorder. If an + * error prevented the border from being created then + * NULL is returned and an error message will be left + * in interp->result. + * + * Side effects: + * Data structures, graphics contexts, etc. are allocated. + * It is the caller's responsibility to eventually call + * Tk_Free3DBorder to release the resources. + * + *-------------------------------------------------------------- + */ + +Tk_3DBorder +Tk_Get3DBorder(interp, tkwin, colorName) + Tcl_Interp *interp; /* Place to store an error message. */ + Tk_Window tkwin; /* Token for window in which border will + * be drawn. */ + Tk_Uid colorName; /* String giving name of color + * for window background. */ +{ + BorderKey key; + Tcl_HashEntry *hashPtr; + register TkBorder *borderPtr; + int new; + XGCValues gcValues; + + if (!initialized) { + BorderInit(); + } + + /* + * First, check to see if there's already a border that will work + * for this request. + */ + + key.colorName = colorName; + key.colormap = Tk_Colormap(tkwin); + key.screen = Tk_Screen(tkwin); + + hashPtr = Tcl_CreateHashEntry(&borderTable, (char *) &key, &new); + if (!new) { + borderPtr = (TkBorder *) Tcl_GetHashValue(hashPtr); + borderPtr->refCount++; + } else { + XColor *bgColorPtr; + + /* + * No satisfactory border exists yet. Initialize a new one. + */ + + bgColorPtr = Tk_GetColor(interp, tkwin, colorName); + if (bgColorPtr == NULL) { + Tcl_DeleteHashEntry(hashPtr); + return NULL; + } + + borderPtr = TkpGetBorder(); + borderPtr->screen = Tk_Screen(tkwin); + borderPtr->visual = Tk_Visual(tkwin); + borderPtr->depth = Tk_Depth(tkwin); + borderPtr->colormap = key.colormap; + borderPtr->refCount = 1; + borderPtr->bgColorPtr = bgColorPtr; + borderPtr->darkColorPtr = NULL; + borderPtr->lightColorPtr = NULL; + borderPtr->shadow = None; + borderPtr->bgGC = None; + borderPtr->darkGC = None; + borderPtr->lightGC = None; + borderPtr->hashPtr = hashPtr; + Tcl_SetHashValue(hashPtr, borderPtr); + + /* + * Create the information for displaying the background color, + * but delay the allocation of shadows until they are actually + * needed for drawing. + */ + + gcValues.foreground = borderPtr->bgColorPtr->pixel; + borderPtr->bgGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + } + return (Tk_3DBorder) borderPtr; +} + +/* + *-------------------------------------------------------------- + * + * Tk_Draw3DRectangle -- + * + * Draw a 3-D border at a given place in a given window. + * + * Results: + * None. + * + * Side effects: + * A 3-D border will be drawn in the indicated drawable. + * The outside edges of the border will be determined by x, + * y, width, and height. The inside edges of the border + * will be determined by the borderWidth argument. + * + *-------------------------------------------------------------- + */ + +void +Tk_Draw3DRectangle(tkwin, drawable, border, x, y, width, height, + borderWidth, relief) + Tk_Window tkwin; /* Window for which border was allocated. */ + Drawable drawable; /* X window or pixmap in which to draw. */ + Tk_3DBorder border; /* Token for border to draw. */ + int x, y, width, height; /* Outside area of region in + * which border will be drawn. */ + int borderWidth; /* Desired width for border, in + * pixels. */ + int relief; /* Type of relief: TK_RELIEF_RAISED, + * TK_RELIEF_SUNKEN, TK_RELIEF_GROOVE, etc. */ +{ + if (width < 2*borderWidth) { + borderWidth = width/2; + } + if (height < 2*borderWidth) { + borderWidth = height/2; + } + Tk_3DVerticalBevel(tkwin, drawable, border, x, y, borderWidth, height, + 1, relief); + Tk_3DVerticalBevel(tkwin, drawable, border, x+width-borderWidth, y, + borderWidth, height, 0, relief); + Tk_3DHorizontalBevel(tkwin, drawable, border, x, y, width, borderWidth, + 1, 1, 1, relief); + Tk_3DHorizontalBevel(tkwin, drawable, border, x, y+height-borderWidth, + width, borderWidth, 0, 0, 0, relief); +} + +/* + *-------------------------------------------------------------- + * + * Tk_NameOf3DBorder -- + * + * Given a border, return a textual string identifying the + * border's color. + * + * Results: + * The return value is the string that was used to create + * the border. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_NameOf3DBorder(border) + Tk_3DBorder border; /* Token for border. */ +{ + TkBorder *borderPtr = (TkBorder *) border; + + return ((BorderKey *) borderPtr->hashPtr->key.words)->colorName; +} + +/* + *-------------------------------------------------------------------- + * + * Tk_3DBorderColor -- + * + * Given a 3D border, return the X color used for the "flat" + * surfaces. + * + * Results: + * Returns the color used drawing flat surfaces with the border. + * + * Side effects: + * None. + * + *-------------------------------------------------------------------- + */ +XColor * +Tk_3DBorderColor(border) + Tk_3DBorder border; /* Border whose color is wanted. */ +{ + return(((TkBorder *) border)->bgColorPtr); +} + +/* + *-------------------------------------------------------------------- + * + * Tk_3DBorderGC -- + * + * Given a 3D border, returns one of the graphics contexts used to + * draw the border. + * + * Results: + * Returns the graphics context given by the "which" argument. + * + * Side effects: + * None. + * + *-------------------------------------------------------------------- + */ +GC +Tk_3DBorderGC(tkwin, border, which) + Tk_Window tkwin; /* Window for which border was allocated. */ + Tk_3DBorder border; /* Border whose GC is wanted. */ + int which; /* Selects one of the border's 3 GC's: + * TK_3D_FLAT_GC, TK_3D_LIGHT_GC, or + * TK_3D_DARK_GC. */ +{ + TkBorder * borderPtr = (TkBorder *) border; + + if ((borderPtr->lightGC == None) && (which != TK_3D_FLAT_GC)) { + TkpGetShadows(borderPtr, tkwin); + } + if (which == TK_3D_FLAT_GC) { + return borderPtr->bgGC; + } else if (which == TK_3D_LIGHT_GC) { + return borderPtr->lightGC; + } else if (which == TK_3D_DARK_GC){ + return borderPtr->darkGC; + } + panic("bogus \"which\" value in Tk_3DBorderGC"); + + /* + * The code below will never be executed, but it's needed to + * keep compilers happy. + */ + + return (GC) None; +} + +/* + *-------------------------------------------------------------- + * + * Tk_Free3DBorder -- + * + * This procedure is called when a 3D border is no longer + * needed. It frees the resources associated with the + * border. After this call, the caller should never again + * use the "border" token. + * + * Results: + * None. + * + * Side effects: + * Resources are freed. + * + *-------------------------------------------------------------- + */ + +void +Tk_Free3DBorder(border) + Tk_3DBorder border; /* Token for border to be released. */ +{ + register TkBorder *borderPtr = (TkBorder *) border; + Display *display = DisplayOfScreen(borderPtr->screen); + + borderPtr->refCount--; + if (borderPtr->refCount == 0) { + TkpFreeBorder(borderPtr); + if (borderPtr->bgColorPtr != NULL) { + Tk_FreeColor(borderPtr->bgColorPtr); + } + if (borderPtr->darkColorPtr != NULL) { + Tk_FreeColor(borderPtr->darkColorPtr); + } + if (borderPtr->lightColorPtr != NULL) { + Tk_FreeColor(borderPtr->lightColorPtr); + } + if (borderPtr->shadow != None) { + Tk_FreeBitmap(display, borderPtr->shadow); + } + if (borderPtr->bgGC != None) { + Tk_FreeGC(display, borderPtr->bgGC); + } + if (borderPtr->darkGC != None) { + Tk_FreeGC(display, borderPtr->darkGC); + } + if (borderPtr->lightGC != None) { + Tk_FreeGC(display, borderPtr->lightGC); + } + Tcl_DeleteHashEntry(borderPtr->hashPtr); + ckfree((char *) borderPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_SetBackgroundFromBorder -- + * + * Change the background of a window to one appropriate for a given + * 3-D border. + * + * Results: + * None. + * + * Side effects: + * Tkwin's background gets modified. + * + *---------------------------------------------------------------------- + */ + +void +Tk_SetBackgroundFromBorder(tkwin, border) + Tk_Window tkwin; /* Window whose background is to be set. */ + Tk_3DBorder border; /* Token for border. */ +{ + register TkBorder *borderPtr = (TkBorder *) border; + + Tk_SetWindowBackground(tkwin, borderPtr->bgColorPtr->pixel); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetRelief -- + * + * Parse a relief description and return the corresponding + * relief value, or an error. + * + * Results: + * A standard Tcl return value. If all goes well then + * *reliefPtr is filled in with one of the values + * TK_RELIEF_RAISED, TK_RELIEF_FLAT, or TK_RELIEF_SUNKEN. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +Tk_GetRelief(interp, name, reliefPtr) + Tcl_Interp *interp; /* For error messages. */ + char *name; /* Name of a relief type. */ + int *reliefPtr; /* Where to store converted relief. */ +{ + char c; + size_t length; + + c = name[0]; + length = strlen(name); + if ((c == 'f') && (strncmp(name, "flat", length) == 0)) { + *reliefPtr = TK_RELIEF_FLAT; + } else if ((c == 'g') && (strncmp(name, "groove", length) == 0) + && (length >= 2)) { + *reliefPtr = TK_RELIEF_GROOVE; + } else if ((c == 'r') && (strncmp(name, "raised", length) == 0) + && (length >= 2)) { + *reliefPtr = TK_RELIEF_RAISED; + } else if ((c == 'r') && (strncmp(name, "ridge", length) == 0)) { + *reliefPtr = TK_RELIEF_RIDGE; + } else if ((c == 's') && (strncmp(name, "solid", length) == 0)) { + *reliefPtr = TK_RELIEF_SOLID; + } else if ((c == 's') && (strncmp(name, "sunken", length) == 0)) { + *reliefPtr = TK_RELIEF_SUNKEN; + } else { + sprintf(interp->result, "bad relief type \"%.50s\": must be %s", + name, "flat, groove, raised, ridge, solid, or sunken"); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * Tk_NameOfRelief -- + * + * Given a relief value, produce a string describing that + * relief value. + * + * Results: + * The return value is a static string that is equivalent + * to relief. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_NameOfRelief(relief) + int relief; /* One of TK_RELIEF_FLAT, TK_RELIEF_RAISED, + * or TK_RELIEF_SUNKEN. */ +{ + if (relief == TK_RELIEF_FLAT) { + return "flat"; + } else if (relief == TK_RELIEF_SUNKEN) { + return "sunken"; + } else if (relief == TK_RELIEF_RAISED) { + return "raised"; + } else if (relief == TK_RELIEF_GROOVE) { + return "groove"; + } else if (relief == TK_RELIEF_RIDGE) { + return "ridge"; + } else if (relief == TK_RELIEF_SOLID) { + return "solid"; + } else { + return "unknown relief"; + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_Draw3DPolygon -- + * + * Draw a border with 3-D appearance around the edge of a + * given polygon. + * + * Results: + * None. + * + * Side effects: + * Information is drawn in "drawable" in the form of a + * 3-D border borderWidth units width wide on the left + * of the trajectory given by pointPtr and numPoints (or + * -borderWidth units wide on the right side, if borderWidth + * is negative). + * + *-------------------------------------------------------------- + */ + +void +Tk_Draw3DPolygon(tkwin, drawable, border, pointPtr, numPoints, + borderWidth, leftRelief) + Tk_Window tkwin; /* Window for which border was allocated. */ + Drawable drawable; /* X window or pixmap in which to draw. */ + Tk_3DBorder border; /* Token for border to draw. */ + XPoint *pointPtr; /* Array of points describing + * polygon. All points must be + * absolute (CoordModeOrigin). */ + int numPoints; /* Number of points at *pointPtr. */ + int borderWidth; /* Width of border, measured in + * pixels to the left of the polygon's + * trajectory. May be negative. */ + int leftRelief; /* TK_RELIEF_RAISED or + * TK_RELIEF_SUNKEN: indicates how + * stuff to left of trajectory looks + * relative to stuff on right. */ +{ + XPoint poly[4], b1, b2, newB1, newB2; + XPoint perp, c, shift1, shift2; /* Used for handling parallel lines. */ + register XPoint *p1Ptr, *p2Ptr; + TkBorder *borderPtr = (TkBorder *) border; + GC gc; + int i, lightOnLeft, dx, dy, parallel, pointsSeen; + Display *display = Tk_Display(tkwin); + + if (borderPtr->lightGC == None) { + TkpGetShadows(borderPtr, tkwin); + } + + /* + * Handle grooves and ridges with recursive calls. + */ + + if ((leftRelief == TK_RELIEF_GROOVE) || (leftRelief == TK_RELIEF_RIDGE)) { + int halfWidth; + + halfWidth = borderWidth/2; + Tk_Draw3DPolygon(tkwin, drawable, border, pointPtr, numPoints, + halfWidth, (leftRelief == TK_RELIEF_GROOVE) ? TK_RELIEF_RAISED + : TK_RELIEF_SUNKEN); + Tk_Draw3DPolygon(tkwin, drawable, border, pointPtr, numPoints, + -halfWidth, (leftRelief == TK_RELIEF_GROOVE) ? TK_RELIEF_SUNKEN + : TK_RELIEF_RAISED); + return; + } + + /* + * If the polygon is already closed, drop the last point from it + * (we'll close it automatically). + */ + + p1Ptr = &pointPtr[numPoints-1]; + p2Ptr = &pointPtr[0]; + if ((p1Ptr->x == p2Ptr->x) && (p1Ptr->y == p2Ptr->y)) { + numPoints--; + } + + /* + * The loop below is executed once for each vertex in the polgon. + * At the beginning of each iteration things look like this: + * + * poly[1] / + * * / + * | / + * b1 * poly[0] (pointPtr[i-1]) + * | | + * | | + * | | + * | | + * | | + * | | *p1Ptr *p2Ptr + * b2 *--------------------* + * | + * | + * x------------------------- + * + * The job of this iteration is to do the following: + * (a) Compute x (the border corner corresponding to + * pointPtr[i]) and put it in poly[2]. As part of + * this, compute a new b1 and b2 value for the next + * side of the polygon. + * (b) Put pointPtr[i] into poly[3]. + * (c) Draw the polygon given by poly[0..3]. + * (d) Advance poly[0], poly[1], b1, and b2 for the + * next side of the polygon. + */ + + /* + * The above situation doesn't first come into existence until + * two points have been processed; the first two points are + * used to "prime the pump", so some parts of the processing + * are ommitted for these points. The variable "pointsSeen" + * keeps track of the priming process; it has to be separate + * from i in order to be able to ignore duplicate points in the + * polygon. + */ + + pointsSeen = 0; + for (i = -2, p1Ptr = &pointPtr[numPoints-2], p2Ptr = p1Ptr+1; + i < numPoints; i++, p1Ptr = p2Ptr, p2Ptr++) { + if ((i == -1) || (i == numPoints-1)) { + p2Ptr = pointPtr; + } + if ((p2Ptr->x == p1Ptr->x) && (p2Ptr->y == p1Ptr->y)) { + /* + * Ignore duplicate points (they'd cause core dumps in + * ShiftLine calls below). + */ + continue; + } + ShiftLine(p1Ptr, p2Ptr, borderWidth, &newB1); + newB2.x = newB1.x + (p2Ptr->x - p1Ptr->x); + newB2.y = newB1.y + (p2Ptr->y - p1Ptr->y); + poly[3] = *p1Ptr; + parallel = 0; + if (pointsSeen >= 1) { + parallel = Intersect(&newB1, &newB2, &b1, &b2, &poly[2]); + + /* + * If two consecutive segments of the polygon are parallel, + * then things get more complex. Consider the following + * diagram: + * + * poly[1] + * *----b1-----------b2------a + * \ + * \ + * *---------*----------* b + * poly[0] *p2Ptr *p1Ptr / + * / + * --*--------*----c + * newB1 newB2 + * + * Instead of using x and *p1Ptr for poly[2] and poly[3], as + * in the original diagram, use a and b as above. Then instead + * of using x and *p1Ptr for the new poly[0] and poly[1], use + * b and c as above. + * + * Do the computation in three stages: + * 1. Compute a point "perp" such that the line p1Ptr-perp + * is perpendicular to p1Ptr-p2Ptr. + * 2. Compute the points a and c by intersecting the lines + * b1-b2 and newB1-newB2 with p1Ptr-perp. + * 3. Compute b by shifting p1Ptr-perp to the right and + * intersecting it with p1Ptr-p2Ptr. + */ + + if (parallel) { + perp.x = p1Ptr->x + (p2Ptr->y - p1Ptr->y); + perp.y = p1Ptr->y - (p2Ptr->x - p1Ptr->x); + (void) Intersect(p1Ptr, &perp, &b1, &b2, &poly[2]); + (void) Intersect(p1Ptr, &perp, &newB1, &newB2, &c); + ShiftLine(p1Ptr, &perp, borderWidth, &shift1); + shift2.x = shift1.x + (perp.x - p1Ptr->x); + shift2.y = shift1.y + (perp.y - p1Ptr->y); + (void) Intersect(p1Ptr, p2Ptr, &shift1, &shift2, &poly[3]); + } + } + if (pointsSeen >= 2) { + dx = poly[3].x - poly[0].x; + dy = poly[3].y - poly[0].y; + if (dx > 0) { + lightOnLeft = (dy <= dx); + } else { + lightOnLeft = (dy < dx); + } + if (lightOnLeft ^ (leftRelief == TK_RELIEF_RAISED)) { + gc = borderPtr->lightGC; + } else { + gc = borderPtr->darkGC; + } + XFillPolygon(display, drawable, gc, poly, 4, Convex, + CoordModeOrigin); + } + b1.x = newB1.x; + b1.y = newB1.y; + b2.x = newB2.x; + b2.y = newB2.y; + poly[0].x = poly[3].x; + poly[0].y = poly[3].y; + if (parallel) { + poly[1].x = c.x; + poly[1].y = c.y; + } else if (pointsSeen >= 1) { + poly[1].x = poly[2].x; + poly[1].y = poly[2].y; + } + pointsSeen++; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_Fill3DRectangle -- + * + * Fill a rectangular area, supplying a 3D border if desired. + * + * Results: + * None. + * + * Side effects: + * Information gets drawn on the screen. + * + *---------------------------------------------------------------------- + */ + +void +Tk_Fill3DRectangle(tkwin, drawable, border, x, y, width, + height, borderWidth, relief) + Tk_Window tkwin; /* Window for which border was allocated. */ + Drawable drawable; /* X window or pixmap in which to draw. */ + Tk_3DBorder border; /* Token for border to draw. */ + int x, y, width, height; /* Outside area of rectangular region. */ + int borderWidth; /* Desired width for border, in + * pixels. Border will be *inside* region. */ + int relief; /* Indicates 3D effect: TK_RELIEF_FLAT, + * TK_RELIEF_RAISED, or TK_RELIEF_SUNKEN. */ +{ + register TkBorder *borderPtr = (TkBorder *) border; + int doubleBorder; + + /* + * This code is slightly tricky because it only draws the background + * in areas not covered by the 3D border. This avoids flashing + * effects on the screen for the border region. + */ + + if (relief == TK_RELIEF_FLAT) { + borderWidth = 0; + } + doubleBorder = 2*borderWidth; + + if ((width > doubleBorder) && (height > doubleBorder)) { + XFillRectangle(Tk_Display(tkwin), drawable, borderPtr->bgGC, + x + borderWidth, y + borderWidth, + (unsigned int) (width - doubleBorder), + (unsigned int) (height - doubleBorder)); + } + if (borderWidth) { + Tk_Draw3DRectangle(tkwin, drawable, border, x, y, width, + height, borderWidth, relief); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_Fill3DPolygon -- + * + * Fill a polygonal area, supplying a 3D border if desired. + * + * Results: + * None. + * + * Side effects: + * Information gets drawn on the screen. + * + *---------------------------------------------------------------------- + */ + +void +Tk_Fill3DPolygon(tkwin, drawable, border, pointPtr, numPoints, + borderWidth, leftRelief) + Tk_Window tkwin; /* Window for which border was allocated. */ + Drawable drawable; /* X window or pixmap in which to draw. */ + Tk_3DBorder border; /* Token for border to draw. */ + XPoint *pointPtr; /* Array of points describing + * polygon. All points must be + * absolute (CoordModeOrigin). */ + int numPoints; /* Number of points at *pointPtr. */ + int borderWidth; /* Width of border, measured in + * pixels to the left of the polygon's + * trajectory. May be negative. */ + int leftRelief; /* Indicates 3D effect of left side of + * trajectory relative to right: + * TK_RELIEF_FLAT, TK_RELIEF_RAISED, + * or TK_RELIEF_SUNKEN. */ +{ + register TkBorder *borderPtr = (TkBorder *) border; + + XFillPolygon(Tk_Display(tkwin), drawable, borderPtr->bgGC, + pointPtr, numPoints, Complex, CoordModeOrigin); + if (leftRelief != TK_RELIEF_FLAT) { + Tk_Draw3DPolygon(tkwin, drawable, border, pointPtr, numPoints, + borderWidth, leftRelief); + } +} + +/* + *-------------------------------------------------------------- + * + * BorderInit -- + * + * Initialize the structures used for border management. + * + * Results: + * None. + * + * Side effects: + * Read the code. + * + *------------------------------------------------------------- + */ + +static void +BorderInit() +{ + initialized = 1; + Tcl_InitHashTable(&borderTable, sizeof(BorderKey)/sizeof(int)); +} + +/* + *-------------------------------------------------------------- + * + * ShiftLine -- + * + * Given two points on a line, compute a point on a + * new line that is parallel to the given line and + * a given distance away from it. + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static void +ShiftLine(p1Ptr, p2Ptr, distance, p3Ptr) + XPoint *p1Ptr; /* First point on line. */ + XPoint *p2Ptr; /* Second point on line. */ + int distance; /* New line is to be this many + * units to the left of original + * line, when looking from p1 to + * p2. May be negative. */ + XPoint *p3Ptr; /* Store coords of point on new + * line here. */ +{ + int dx, dy, dxNeg, dyNeg; + + /* + * The table below is used for a quick approximation in + * computing the new point. An index into the table + * is 128 times the slope of the original line (the slope + * must always be between 0 and 1). The value of the table + * entry is 128 times the amount to displace the new line + * in y for each unit of perpendicular distance. In other + * words, the table maps from the tangent of an angle to + * the inverse of its cosine. If the slope of the original + * line is greater than 1, then the displacement is done in + * x rather than in y. + */ + + static int shiftTable[129]; + + /* + * Initialize the table if this is the first time it is + * used. + */ + + if (shiftTable[0] == 0) { + int i; + double tangent, cosine; + + for (i = 0; i <= 128; i++) { + tangent = i/128.0; + cosine = 128/cos(atan(tangent)) + .5; + shiftTable[i] = (int) cosine; + } + } + + *p3Ptr = *p1Ptr; + dx = p2Ptr->x - p1Ptr->x; + dy = p2Ptr->y - p1Ptr->y; + if (dy < 0) { + dyNeg = 1; + dy = -dy; + } else { + dyNeg = 0; + } + if (dx < 0) { + dxNeg = 1; + dx = -dx; + } else { + dxNeg = 0; + } + if (dy <= dx) { + dy = ((distance * shiftTable[(dy<<7)/dx]) + 64) >> 7; + if (!dxNeg) { + dy = -dy; + } + p3Ptr->y += dy; + } else { + dx = ((distance * shiftTable[(dx<<7)/dy]) + 64) >> 7; + if (dyNeg) { + dx = -dx; + } + p3Ptr->x += dx; + } +} + +/* + *-------------------------------------------------------------- + * + * Intersect -- + * + * Find the intersection point between two lines. + * + * Results: + * Under normal conditions 0 is returned and the point + * at *iPtr is filled in with the intersection between + * the two lines. If the two lines are parallel, then + * -1 is returned and *iPtr isn't modified. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +Intersect(a1Ptr, a2Ptr, b1Ptr, b2Ptr, iPtr) + XPoint *a1Ptr; /* First point of first line. */ + XPoint *a2Ptr; /* Second point of first line. */ + XPoint *b1Ptr; /* First point of second line. */ + XPoint *b2Ptr; /* Second point of second line. */ + XPoint *iPtr; /* Filled in with intersection point. */ +{ + int dxadyb, dxbdya, dxadxb, dyadyb, p, q; + + /* + * The code below is just a straightforward manipulation of two + * equations of the form y = (x-x1)*(y2-y1)/(x2-x1) + y1 to solve + * for the x-coordinate of intersection, then the y-coordinate. + */ + + dxadyb = (a2Ptr->x - a1Ptr->x)*(b2Ptr->y - b1Ptr->y); + dxbdya = (b2Ptr->x - b1Ptr->x)*(a2Ptr->y - a1Ptr->y); + dxadxb = (a2Ptr->x - a1Ptr->x)*(b2Ptr->x - b1Ptr->x); + dyadyb = (a2Ptr->y - a1Ptr->y)*(b2Ptr->y - b1Ptr->y); + + if (dxadyb == dxbdya) { + return -1; + } + p = (a1Ptr->x*dxbdya - b1Ptr->x*dxadyb + (b1Ptr->y - a1Ptr->y)*dxadxb); + q = dxbdya - dxadyb; + if (q < 0) { + p = -p; + q = -q; + } + if (p < 0) { + iPtr->x = - ((-p + q/2)/q); + } else { + iPtr->x = (p + q/2)/q; + } + p = (a1Ptr->y*dxadyb - b1Ptr->y*dxbdya + (b1Ptr->x - a1Ptr->x)*dyadyb); + q = dxadyb - dxbdya; + if (q < 0) { + p = -p; + q = -q; + } + if (p < 0) { + iPtr->y = - ((-p + q/2)/q); + } else { + iPtr->y = (p + q/2)/q; + } + return 0; +} diff --git a/generic/tk3d.h b/generic/tk3d.h new file mode 100644 index 0000000..cd9ecd5 --- /dev/null +++ b/generic/tk3d.h @@ -0,0 +1,79 @@ +/* + * tk3d.h -- + * + * Declarations of types and functions shared by the 3d border + * module. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tk3d.h 1.1 96/11/04 13:52:59 + */ + +#ifndef _TK3D +#define _TK3D + +#include <tkInt.h> + +/* + * One of the following data structures is allocated for + * each 3-D border currently in use. Structures of this + * type are indexed by borderTable, so that a single + * structure can be shared for several uses. + */ + +typedef struct { + Screen *screen; /* Screen on which the border will be used. */ + Visual *visual; /* Visual for all windows and pixmaps using + * the border. */ + int depth; /* Number of bits per pixel of drawables where + * the border will be used. */ + Colormap colormap; /* Colormap out of which pixels are + * allocated. */ + int refCount; /* Number of different users of + * this border. */ + XColor *bgColorPtr; /* Background color (intensity + * between lightColorPtr and + * darkColorPtr). */ + XColor *darkColorPtr; /* Color for darker areas (must free when + * deleting structure). NULL means shadows + * haven't been allocated yet.*/ + XColor *lightColorPtr; /* Color used for lighter areas of border + * (must free this when deleting structure). + * NULL means shadows haven't been allocated + * yet. */ + Pixmap shadow; /* Stipple pattern to use for drawing + * shadows areas. Used for displays with + * <= 64 colors or where colormap has filled + * up. */ + GC bgGC; /* Used (if necessary) to draw areas in + * the background color. */ + GC darkGC; /* Used to draw darker parts of the + * border. None means the shadow colors + * haven't been allocated yet.*/ + GC lightGC; /* Used to draw lighter parts of + * the border. None means the shadow colors + * haven't been allocated yet. */ + Tcl_HashEntry *hashPtr; /* Entry in borderTable (needed in + * order to delete structure). */ +} TkBorder; + + +/* + * Maximum intensity for a color: + */ + +#define MAX_INTENSITY 65535 + +/* + * Declarations for platform specific interfaces used by this module. + */ + +EXTERN TkBorder * TkpGetBorder _ANSI_ARGS_((void)); +EXTERN void TkpGetShadows _ANSI_ARGS_((TkBorder *borderPtr, + Tk_Window tkwin)); +EXTERN void TkpFreeBorder _ANSI_ARGS_((TkBorder *borderPtr)); + +#endif /* _TK3D */ diff --git a/generic/tkArgv.c b/generic/tkArgv.c new file mode 100644 index 0000000..5842687 --- /dev/null +++ b/generic/tkArgv.c @@ -0,0 +1,433 @@ +/* + * tkArgv.c -- + * + * This file contains a procedure that handles table-based + * argv-argc parsing. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkArgv.c 1.21 97/04/25 16:50:27 + */ + +#include "tkPort.h" +#include "tk.h" + +/* + * Default table of argument descriptors. These are normally available + * in every application. + */ + +static Tk_ArgvInfo defaultTable[] = { + {"-help", TK_ARGV_HELP, (char *) NULL, (char *) NULL, + "Print summary of command-line options and abort"}, + {NULL, TK_ARGV_END, (char *) NULL, (char *) NULL, + (char *) NULL} +}; + +/* + * Forward declarations for procedures defined in this file: + */ + +static void PrintUsage _ANSI_ARGS_((Tcl_Interp *interp, + Tk_ArgvInfo *argTable, int flags)); + +/* + *---------------------------------------------------------------------- + * + * Tk_ParseArgv -- + * + * Process an argv array according to a table of expected + * command-line options. See the manual page for more details. + * + * Results: + * The return value is a standard Tcl return value. If an + * error occurs then an error message is left in interp->result. + * Under normal conditions, both *argcPtr and *argv are modified + * to return the arguments that couldn't be processed here (they + * didn't match the option table, or followed an TK_ARGV_REST + * argument). + * + * Side effects: + * Variables may be modified, resources may be entered for tkwin, + * or procedures may be called. It all depends on the arguments + * and their entries in argTable. See the user documentation + * for details. + * + *---------------------------------------------------------------------- + */ + +int +Tk_ParseArgv(interp, tkwin, argcPtr, argv, argTable, flags) + Tcl_Interp *interp; /* Place to store error message. */ + Tk_Window tkwin; /* Window to use for setting Tk options. + * NULL means ignore Tk option specs. */ + int *argcPtr; /* Number of arguments in argv. Modified + * to hold # args left in argv at end. */ + char **argv; /* Array of arguments. Modified to hold + * those that couldn't be processed here. */ + Tk_ArgvInfo *argTable; /* Array of option descriptions */ + int flags; /* Or'ed combination of various flag bits, + * such as TK_ARGV_NO_DEFAULTS. */ +{ + register Tk_ArgvInfo *infoPtr; + /* Pointer to the current entry in the + * table of argument descriptions. */ + Tk_ArgvInfo *matchPtr; /* Descriptor that matches current argument. */ + char *curArg; /* Current argument */ + register char c; /* Second character of current arg (used for + * quick check for matching; use 2nd char. + * because first char. will almost always + * be '-'). */ + int srcIndex; /* Location from which to read next argument + * from argv. */ + int dstIndex; /* Index into argv to which next unused + * argument should be copied (never greater + * than srcIndex). */ + int argc; /* # arguments in argv still to process. */ + size_t length; /* Number of characters in current argument. */ + int i; + + if (flags & TK_ARGV_DONT_SKIP_FIRST_ARG) { + srcIndex = dstIndex = 0; + argc = *argcPtr; + } else { + srcIndex = dstIndex = 1; + argc = *argcPtr-1; + } + + while (argc > 0) { + curArg = argv[srcIndex]; + srcIndex++; + argc--; + length = strlen(curArg); + if (length > 0) { + c = curArg[1]; + } else { + c = 0; + } + + /* + * Loop throught the argument descriptors searching for one with + * the matching key string. If found, leave a pointer to it in + * matchPtr. + */ + + matchPtr = NULL; + for (i = 0; i < 2; i++) { + if (i == 0) { + infoPtr = argTable; + } else { + infoPtr = defaultTable; + } + for (; (infoPtr != NULL) && (infoPtr->type != TK_ARGV_END); + infoPtr++) { + if (infoPtr->key == NULL) { + continue; + } + if ((infoPtr->key[1] != c) + || (strncmp(infoPtr->key, curArg, length) != 0)) { + continue; + } + if ((tkwin == NULL) + && ((infoPtr->type == TK_ARGV_CONST_OPTION) + || (infoPtr->type == TK_ARGV_OPTION_VALUE) + || (infoPtr->type == TK_ARGV_OPTION_NAME_VALUE))) { + continue; + } + if (infoPtr->key[length] == 0) { + matchPtr = infoPtr; + goto gotMatch; + } + if (flags & TK_ARGV_NO_ABBREV) { + continue; + } + if (matchPtr != NULL) { + Tcl_AppendResult(interp, "ambiguous option \"", curArg, + "\"", (char *) NULL); + return TCL_ERROR; + } + matchPtr = infoPtr; + } + } + if (matchPtr == NULL) { + + /* + * Unrecognized argument. Just copy it down, unless the caller + * prefers an error to be registered. + */ + + if (flags & TK_ARGV_NO_LEFTOVERS) { + Tcl_AppendResult(interp, "unrecognized argument \"", + curArg, "\"", (char *) NULL); + return TCL_ERROR; + } + argv[dstIndex] = curArg; + dstIndex++; + continue; + } + + /* + * Take the appropriate action based on the option type + */ + + gotMatch: + infoPtr = matchPtr; + switch (infoPtr->type) { + case TK_ARGV_CONSTANT: + *((int *) infoPtr->dst) = (int) infoPtr->src; + break; + case TK_ARGV_INT: + if (argc == 0) { + goto missingArg; + } else { + char *endPtr; + + *((int *) infoPtr->dst) = + strtol(argv[srcIndex], &endPtr, 0); + if ((endPtr == argv[srcIndex]) || (*endPtr != 0)) { + Tcl_AppendResult(interp, "expected integer argument ", + "for \"", infoPtr->key, "\" but got \"", + argv[srcIndex], "\"", (char *) NULL); + return TCL_ERROR; + } + srcIndex++; + argc--; + } + break; + case TK_ARGV_STRING: + if (argc == 0) { + goto missingArg; + } else { + *((char **)infoPtr->dst) = argv[srcIndex]; + srcIndex++; + argc--; + } + break; + case TK_ARGV_UID: + if (argc == 0) { + goto missingArg; + } else { + *((Tk_Uid *)infoPtr->dst) = Tk_GetUid(argv[srcIndex]); + srcIndex++; + argc--; + } + break; + case TK_ARGV_REST: + *((int *) infoPtr->dst) = dstIndex; + goto argsDone; + case TK_ARGV_FLOAT: + if (argc == 0) { + goto missingArg; + } else { + char *endPtr; + + *((double *) infoPtr->dst) = + strtod(argv[srcIndex], &endPtr); + if ((endPtr == argv[srcIndex]) || (*endPtr != 0)) { + Tcl_AppendResult(interp, "expected floating-point ", + "argument for \"", infoPtr->key, + "\" but got \"", argv[srcIndex], "\"", + (char *) NULL); + return TCL_ERROR; + } + srcIndex++; + argc--; + } + break; + case TK_ARGV_FUNC: { + typedef int (ArgvFunc)_ANSI_ARGS_((char *, char *, char *)); + ArgvFunc *handlerProc; + + handlerProc = (ArgvFunc *) infoPtr->src; + if ((*handlerProc)(infoPtr->dst, infoPtr->key, + argv[srcIndex])) { + srcIndex += 1; + argc -= 1; + } + break; + } + case TK_ARGV_GENFUNC: { + typedef int (ArgvGenFunc)_ANSI_ARGS_((char *, Tcl_Interp *, + char *, int, char **)); + ArgvGenFunc *handlerProc; + + handlerProc = (ArgvGenFunc *) infoPtr->src; + argc = (*handlerProc)(infoPtr->dst, interp, infoPtr->key, + argc, argv+srcIndex); + if (argc < 0) { + return TCL_ERROR; + } + break; + } + case TK_ARGV_HELP: + PrintUsage (interp, argTable, flags); + return TCL_ERROR; + case TK_ARGV_CONST_OPTION: + Tk_AddOption(tkwin, infoPtr->dst, infoPtr->src, + TK_INTERACTIVE_PRIO); + break; + case TK_ARGV_OPTION_VALUE: + if (argc < 1) { + goto missingArg; + } + Tk_AddOption(tkwin, infoPtr->dst, argv[srcIndex], + TK_INTERACTIVE_PRIO); + srcIndex++; + argc--; + break; + case TK_ARGV_OPTION_NAME_VALUE: + if (argc < 2) { + Tcl_AppendResult(interp, "\"", curArg, + "\" option requires two following arguments", + (char *) NULL); + return TCL_ERROR; + } + Tk_AddOption(tkwin, argv[srcIndex], argv[srcIndex+1], + TK_INTERACTIVE_PRIO); + srcIndex += 2; + argc -= 2; + break; + default: + sprintf(interp->result, "bad argument type %d in Tk_ArgvInfo", + infoPtr->type); + return TCL_ERROR; + } + } + + /* + * If we broke out of the loop because of an OPT_REST argument, + * copy the remaining arguments down. + */ + + argsDone: + while (argc) { + argv[dstIndex] = argv[srcIndex]; + srcIndex++; + dstIndex++; + argc--; + } + argv[dstIndex] = (char *) NULL; + *argcPtr = dstIndex; + return TCL_OK; + + missingArg: + Tcl_AppendResult(interp, "\"", curArg, + "\" option requires an additional argument", (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * PrintUsage -- + * + * Generate a help string describing command-line options. + * + * Results: + * Interp->result will be modified to hold a help string + * describing all the options in argTable, plus all those + * in the default table unless TK_ARGV_NO_DEFAULTS is + * specified in flags. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +PrintUsage(interp, argTable, flags) + Tcl_Interp *interp; /* Place information in this interp's + * result area. */ + Tk_ArgvInfo *argTable; /* Array of command-specific argument + * descriptions. */ + int flags; /* If the TK_ARGV_NO_DEFAULTS bit is set + * in this word, then don't generate + * information for default options. */ +{ + register Tk_ArgvInfo *infoPtr; + int width, i, numSpaces; +#define NUM_SPACES 20 + static char spaces[] = " "; + char tmp[30]; + + /* + * First, compute the width of the widest option key, so that we + * can make everything line up. + */ + + width = 4; + for (i = 0; i < 2; i++) { + for (infoPtr = i ? defaultTable : argTable; + infoPtr->type != TK_ARGV_END; infoPtr++) { + int length; + if (infoPtr->key == NULL) { + continue; + } + length = strlen(infoPtr->key); + if (length > width) { + width = length; + } + } + } + + Tcl_AppendResult(interp, "Command-specific options:", (char *) NULL); + for (i = 0; ; i++) { + for (infoPtr = i ? defaultTable : argTable; + infoPtr->type != TK_ARGV_END; infoPtr++) { + if ((infoPtr->type == TK_ARGV_HELP) && (infoPtr->key == NULL)) { + Tcl_AppendResult(interp, "\n", infoPtr->help, (char *) NULL); + continue; + } + Tcl_AppendResult(interp, "\n ", infoPtr->key, ":", (char *) NULL); + numSpaces = width + 1 - strlen(infoPtr->key); + while (numSpaces > 0) { + if (numSpaces >= NUM_SPACES) { + Tcl_AppendResult(interp, spaces, (char *) NULL); + } else { + Tcl_AppendResult(interp, spaces+NUM_SPACES-numSpaces, + (char *) NULL); + } + numSpaces -= NUM_SPACES; + } + Tcl_AppendResult(interp, infoPtr->help, (char *) NULL); + switch (infoPtr->type) { + case TK_ARGV_INT: { + sprintf(tmp, "%d", *((int *) infoPtr->dst)); + Tcl_AppendResult(interp, "\n\t\tDefault value: ", + tmp, (char *) NULL); + break; + } + case TK_ARGV_FLOAT: { + sprintf(tmp, "%g", *((double *) infoPtr->dst)); + Tcl_AppendResult(interp, "\n\t\tDefault value: ", + tmp, (char *) NULL); + break; + } + case TK_ARGV_STRING: { + char *string; + + string = *((char **) infoPtr->dst); + if (string != NULL) { + Tcl_AppendResult(interp, "\n\t\tDefault value: \"", + string, "\"", (char *) NULL); + } + break; + } + default: { + break; + } + } + } + + if ((flags & TK_ARGV_NO_DEFAULTS) || (i > 0)) { + break; + } + Tcl_AppendResult(interp, "\nGeneric options for all commands:", + (char *) NULL); + } +} diff --git a/generic/tkAtom.c b/generic/tkAtom.c new file mode 100644 index 0000000..9d35f6b --- /dev/null +++ b/generic/tkAtom.c @@ -0,0 +1,217 @@ +/* + * tkAtom.c -- + * + * This file manages a cache of X Atoms in order to avoid + * interactions with the X server. It's much like the Xmu + * routines, except it has a cleaner interface (caller + * doesn't have to provide permanent storage for atom names, + * for example). + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkAtom.c 1.13 96/02/15 18:51:34 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * The following are a list of the predefined atom strings. + * They should match those found in xatom.h + */ + +static char * atomNameArray[] = { + "PRIMARY", "SECONDARY", "ARC", + "ATOM", "BITMAP", "CARDINAL", + "COLORMAP", "CURSOR", "CUT_BUFFER0", + "CUT_BUFFER1", "CUT_BUFFER2", "CUT_BUFFER3", + "CUT_BUFFER4", "CUT_BUFFER5", "CUT_BUFFER6", + "CUT_BUFFER7", "DRAWABLE", "FONT", + "INTEGER", "PIXMAP", "POINT", + "RECTANGLE", "RESOURCE_MANAGER", "RGB_COLOR_MAP", + "RGB_BEST_MAP", "RGB_BLUE_MAP", "RGB_DEFAULT_MAP", + "RGB_GRAY_MAP", "RGB_GREEN_MAP", "RGB_RED_MAP", + "STRING", "VISUALID", "WINDOW", + "WM_COMMAND", "WM_HINTS", "WM_CLIENT_MACHINE", + "WM_ICON_NAME", "WM_ICON_SIZE", "WM_NAME", + "WM_NORMAL_HINTS", "WM_SIZE_HINTS", "WM_ZOOM_HINTS", + "MIN_SPACE", "NORM_SPACE", "MAX_SPACE", + "END_SPACE", "SUPERSCRIPT_X", "SUPERSCRIPT_Y", + "SUBSCRIPT_X", "SUBSCRIPT_Y", "UNDERLINE_POSITION", + "UNDERLINE_THICKNESS", "STRIKEOUT_ASCENT", "STRIKEOUT_DESCENT", + "ITALIC_ANGLE", "X_HEIGHT", "QUAD_WIDTH", + "WEIGHT", "POINT_SIZE", "RESOLUTION", + "COPYRIGHT", "NOTICE", "FONT_NAME", + "FAMILY_NAME", "FULL_NAME", "CAP_HEIGHT", + "WM_CLASS", "WM_TRANSIENT_FOR", + (char *) NULL +}; + +/* + * Forward references to procedures defined in this file: + */ + +static void AtomInit _ANSI_ARGS_((TkDisplay *dispPtr)); + +/* + *-------------------------------------------------------------- + * + * Tk_InternAtom -- + * + * Given a string, produce the equivalent X atom. This + * procedure is equivalent to XInternAtom, except that it + * keeps a local cache of atoms. Once a name is known, + * the server need not be contacted again for that name. + * + * Results: + * The return value is the Atom corresponding to name. + * + * Side effects: + * A new entry may be added to the local atom cache. + * + *-------------------------------------------------------------- + */ + +Atom +Tk_InternAtom(tkwin, name) + Tk_Window tkwin; /* Window token; map name to atom + * for this window's display. */ + char *name; /* Name to turn into atom. */ +{ + register TkDisplay *dispPtr; + register Tcl_HashEntry *hPtr; + int new; + + dispPtr = ((TkWindow *) tkwin)->dispPtr; + if (!dispPtr->atomInit) { + AtomInit(dispPtr); + } + + hPtr = Tcl_CreateHashEntry(&dispPtr->nameTable, name, &new); + if (new) { + Tcl_HashEntry *hPtr2; + Atom atom; + + atom = XInternAtom(dispPtr->display, name, False); + Tcl_SetHashValue(hPtr, atom); + hPtr2 = Tcl_CreateHashEntry(&dispPtr->atomTable, (char *) atom, + &new); + Tcl_SetHashValue(hPtr2, Tcl_GetHashKey(&dispPtr->nameTable, hPtr)); + } + return (Atom) Tcl_GetHashValue(hPtr); +} + +/* + *-------------------------------------------------------------- + * + * Tk_GetAtomName -- + * + * This procedure is equivalent to XGetAtomName except that + * it uses the local atom cache to avoid contacting the + * server. + * + * Results: + * The return value is a character string corresponding to + * the atom given by "atom". This string's storage space + * is static: it need not be freed by the caller, and should + * not be modified by the caller. If "atom" doesn't exist + * on tkwin's display, then the string "?bad atom?" is returned. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_GetAtomName(tkwin, atom) + Tk_Window tkwin; /* Window token; map atom to name + * relative to this window's + * display. */ + Atom atom; /* Atom whose name is wanted. */ +{ + register TkDisplay *dispPtr; + register Tcl_HashEntry *hPtr; + + dispPtr = ((TkWindow *) tkwin)->dispPtr; + if (!dispPtr->atomInit) { + AtomInit(dispPtr); + } + + hPtr = Tcl_FindHashEntry(&dispPtr->atomTable, (char *) atom); + if (hPtr == NULL) { + char *name; + Tk_ErrorHandler handler; + int new, mustFree; + + handler= Tk_CreateErrorHandler(dispPtr->display, BadAtom, + -1, -1, (Tk_ErrorProc *) NULL, (ClientData) NULL); + name = XGetAtomName(dispPtr->display, atom); + mustFree = 1; + if (name == NULL) { + name = "?bad atom?"; + mustFree = 0; + } + Tk_DeleteErrorHandler(handler); + hPtr = Tcl_CreateHashEntry(&dispPtr->nameTable, (char *) name, + &new); + Tcl_SetHashValue(hPtr, atom); + if (mustFree) { + XFree(name); + } + name = Tcl_GetHashKey(&dispPtr->nameTable, hPtr); + hPtr = Tcl_CreateHashEntry(&dispPtr->atomTable, (char *) atom, + &new); + Tcl_SetHashValue(hPtr, name); + } + return (char *) Tcl_GetHashValue(hPtr); +} + +/* + *-------------------------------------------------------------- + * + * AtomInit -- + * + * Initialize atom-related information for a display. + * + * Results: + * None. + * + * Side effects: + * Tables get initialized, etc. etc.. + * + *-------------------------------------------------------------- + */ + +static void +AtomInit(dispPtr) + register TkDisplay *dispPtr; /* Display to initialize. */ +{ + Tcl_HashEntry *hPtr; + Atom atom; + + dispPtr->atomInit = 1; + Tcl_InitHashTable(&dispPtr->nameTable, TCL_STRING_KEYS); + Tcl_InitHashTable(&dispPtr->atomTable, TCL_ONE_WORD_KEYS); + + for (atom = 1; atom <= XA_LAST_PREDEFINED; atom++) { + hPtr = Tcl_FindHashEntry(&dispPtr->atomTable, (char *) atom); + if (hPtr == NULL) { + char *name; + int new; + + name = atomNameArray[atom - 1]; + hPtr = Tcl_CreateHashEntry(&dispPtr->nameTable, (char *) name, + &new); + Tcl_SetHashValue(hPtr, atom); + name = Tcl_GetHashKey(&dispPtr->nameTable, hPtr); + hPtr = Tcl_CreateHashEntry(&dispPtr->atomTable, (char *) atom, + &new); + Tcl_SetHashValue(hPtr, name); + } + } +} diff --git a/generic/tkBind.c b/generic/tkBind.c new file mode 100644 index 0000000..bb37b00 --- /dev/null +++ b/generic/tkBind.c @@ -0,0 +1,4533 @@ +/* + * tkBind.c -- + * + * This file provides procedures that associate Tcl commands + * with X events or sequences of X events. + * + * Copyright (c) 1989-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkBind.c 1.133 97/07/01 17:59:53 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * File structure: + * + * Structure definitions and static variables. + * + * Init/Free this package. + * + * Tcl "bind" command (actually located in tkCmds.c). + * "bind" command implementation. + * "bind" implementation helpers. + * + * Tcl "event" command. + * "event" command implementation. + * "event" implementation helpers. + * + * Package-specific common helpers. + * + * Non-package-specific helpers. + */ + + +/* + * The following union is used to hold the detail information from an + * XEvent (including Tk's XVirtualEvent extension). + */ +typedef union { + KeySym keySym; /* KeySym that corresponds to xkey.keycode. */ + int button; /* Button that was pressed (xbutton.button). */ + Tk_Uid name; /* Tk_Uid of virtual event. */ + ClientData clientData; /* Used when type of Detail is unknown, and to + * ensure that all bytes of Detail are initialized + * when this structure is used in a hash key. */ +} Detail; + +/* + * The structure below represents a binding table. A binding table + * represents a domain in which event bindings may occur. It includes + * a space of objects relative to which events occur (usually windows, + * but not always), a history of recent events in the domain, and + * a set of mappings that associate particular Tcl commands with sequences + * of events in the domain. Multiple binding tables may exist at once, + * either because there are multiple applications open, or because there + * are multiple domains within an application with separate event + * bindings for each (for example, each canvas widget has a separate + * binding table for associating events with the items in the canvas). + * + * Note: it is probably a bad idea to reduce EVENT_BUFFER_SIZE much + * below 30. To see this, consider a triple mouse button click while + * the Shift key is down (and auto-repeating). There may be as many + * as 3 auto-repeat events after each mouse button press or release + * (see the first large comment block within Tk_BindEvent for more on + * this), for a total of 20 events to cover the three button presses + * and two intervening releases. If you reduce EVENT_BUFFER_SIZE too + * much, shift multi-clicks will be lost. + * + */ + +#define EVENT_BUFFER_SIZE 30 +typedef struct BindingTable { + XEvent eventRing[EVENT_BUFFER_SIZE];/* Circular queue of recent events + * (higher indices are for more recent + * events). */ + Detail detailRing[EVENT_BUFFER_SIZE];/* "Detail" information (keySym, + * button, Tk_Uid, or 0) for each + * entry in eventRing. */ + int curEvent; /* Index in eventRing of most recent + * event. Newer events have higher + * indices. */ + Tcl_HashTable patternTable; /* Used to map from an event to a + * list of patterns that may match that + * event. Keys are PatternTableKey + * structs, values are (PatSeq *). */ + Tcl_HashTable objectTable; /* Used to map from an object to a + * list of patterns associated with + * that object. Keys are ClientData, + * values are (PatSeq *). */ + Tcl_Interp *interp; /* Interpreter in which commands are + * executed. */ +} BindingTable; + +/* + * The following structure represents virtual event table. A virtual event + * table provides a way to map from platform-specific physical events such + * as button clicks or key presses to virtual events such as <<Paste>>, + * <<Close>>, or <<ScrollWindow>>. + * + * A virtual event is usually never part of the event stream, but instead is + * synthesized inline by matching low-level events. However, a virtual + * event may be generated by platform-specific code or by Tcl scripts. In + * that case, no lookup of the virtual event will need to be done using + * this table, because the virtual event is actually in the event stream. + */ + +typedef struct VirtualEventTable { + Tcl_HashTable patternTable; /* Used to map from a physical event to + * a list of patterns that may match that + * event. Keys are PatternTableKey + * structs, values are (PatSeq *). */ + Tcl_HashTable nameTable; /* Used to map a virtual event name to + * the array of physical events that can + * trigger it. Keys are the Tk_Uid names + * of the virtual events, values are + * PhysicalsOwned structs. */ +} VirtualEventTable; + +/* + * The following structure is used as a key in a patternTable for both + * binding tables and a virtual event tables. + * + * In a binding table, the object field corresponds to the binding tag + * for the widget whose bindings are being accessed. + * + * In a virtual event table, the object field is always NULL. Virtual + * events are a global definiton and are not tied to a particular + * binding tag. + * + * The same key is used for both types of pattern tables so that the + * helper functions that traverse and match patterns will work for both + * binding tables and virtual event tables. + */ +typedef struct PatternTableKey { + ClientData object; /* For binding table, identifies the binding + * tag of the object (or class of objects) + * relative to which the event occurred. + * For virtual event table, always NULL. */ + int type; /* Type of event (from X). */ + Detail detail; /* Additional information, such as keysym, + * button, Tk_Uid, or 0 if nothing + * additional. */ +} PatternTableKey; + +/* + * The following structure defines a pattern, which is matched against X + * events as part of the process of converting X events into Tcl commands. + */ + +typedef struct Pattern { + int eventType; /* Type of X event, e.g. ButtonPress. */ + int needMods; /* Mask of modifiers that must be + * present (0 means no modifiers are + * required). */ + Detail detail; /* Additional information that must + * match event. Normally this is 0, + * meaning no additional information + * must match. For KeyPress and + * KeyRelease events, a keySym may + * be specified to select a + * particular keystroke (0 means any + * keystrokes). For button events, + * specifies a particular button (0 + * means any buttons are OK). For virtual + * events, specifies the Tk_Uid of the + * virtual event name (never 0). */ +} Pattern; + +/* + * The following structure defines a pattern sequence, which consists of one + * or more patterns. In order to trigger, a pattern sequence must match + * the most recent X events (first pattern to most recent event, next + * pattern to next event, and so on). It is used as the hash value in a + * patternTable for both binding tables and virtual event tables. + * + * In a binding table, it is the sequence of physical events that make up + * a binding for an object. + * + * In a virtual event table, it is the sequence of physical events that + * define a virtual event. + * + * The same structure is used for both types of pattern tables so that the + * helper functions that traverse and match patterns will work for both + * binding tables and virtual event tables. + */ + +typedef struct PatSeq { + int numPats; /* Number of patterns in sequence (usually + * 1). */ + TkBindEvalProc *eventProc; /* The procedure that will be invoked on + * the clientData when this pattern sequence + * matches. */ + TkBindFreeProc *freeProc; /* The procedure that will be invoked to + * release the clientData when this pattern + * sequence is freed. */ + ClientData clientData; /* Arbitray data passed to eventProc and + * freeProc when sequence matches. */ + int flags; /* Miscellaneous flag values; see below for + * definitions. */ + int refCount; /* Number of times that this binding is in + * the midst of executing. If greater than 1, + * then a recursive invocation is happening. + * Only when this is zero can the binding + * actually be freed. */ + struct PatSeq *nextSeqPtr; /* Next in list of all pattern sequences + * that have the same initial pattern. NULL + * means end of list. */ + Tcl_HashEntry *hPtr; /* Pointer to hash table entry for the + * initial pattern. This is the head of the + * list of which nextSeqPtr forms a part. */ + struct VirtualOwners *voPtr;/* In a binding table, always NULL. In a + * virtual event table, identifies the array + * of virtual events that can be triggered by + * this event. */ + struct PatSeq *nextObjPtr; /* In a binding table, next in list of all + * pattern sequences for the same object (NULL + * for end of list). Needed to implement + * Tk_DeleteAllBindings. In a virtual event + * table, always NULL. */ + Pattern pats[1]; /* Array of "numPats" patterns. Only one + * element is declared here but in actuality + * enough space will be allocated for "numPats" + * patterns. To match, pats[0] must match + * event n, pats[1] must match event n-1, etc. + */ +} PatSeq; + +/* + * Flag values for PatSeq structures: + * + * PAT_NEARBY 1 means that all of the events matching + * this sequence must occur with nearby X + * and Y mouse coordinates and close in time. + * This is typically used to restrict multiple + * button presses. + * MARKED_DELETED 1 means that this binding has been marked as deleted + * and removed from the binding table, but its memory + * could not be released because it was already queued for + * execution. When the binding is actually about to be + * executed, this flag will be checked and the binding + * skipped if set. + */ + +#define PAT_NEARBY 0x1 +#define MARKED_DELETED 0x2 + +/* + * Constants that define how close together two events must be + * in milliseconds or pixels to meet the PAT_NEARBY constraint: + */ + +#define NEARBY_PIXELS 5 +#define NEARBY_MS 500 + + +/* + * The following structure keeps track of all the virtual events that are + * associated with a particular physical event. It is pointed to by the + * voPtr field in a PatSeq in the patternTable of a virtual event table. + */ + +typedef struct VirtualOwners { + int numOwners; /* Number of virtual events to trigger. */ + Tcl_HashEntry *owners[1]; /* Array of pointers to entries in + * nameTable. Enough space will + * actually be allocated for numOwners + * hash entries. */ +} VirtualOwners; + +/* + * The following structure is used in the nameTable of a virtual event + * table to associate a virtual event with all the physical events that can + * trigger it. + */ +typedef struct PhysicalsOwned { + int numOwned; /* Number of physical events owned. */ + PatSeq *patSeqs[1]; /* Array of pointers to physical event + * patterns. Enough space will actually + * be allocated to hold numOwned. */ +} PhysicalsOwned; + +/* + * One of the following structures exists for each interpreter. This + * structure keeps track of the current display and screen in the + * interpreter, so that a script can be invoked whenever the display/screen + * changes (the script does things like point tkPriv at a display-specific + * structure). + */ + +typedef struct { + TkDisplay *curDispPtr; /* Display for last binding command invoked + * in this application. */ + int curScreenIndex; /* Index of screen for last binding command. */ + int bindingDepth; /* Number of active instances of Tk_BindEvent + * in this application. */ +} ScreenInfo; + +/* + * The following structure is used to keep track of all the C bindings that + * are awaiting invocation and whether the window they refer to has been + * destroyed. If the window is destroyed, then all pending callbacks for + * that window will be cancelled. The Tcl bindings will still all be + * invoked, however. + */ + +typedef struct PendingBinding { + struct PendingBinding *nextPtr; + /* Next in chain of pending bindings, in + * case a recursive binding evaluation is in + * progress. */ + Tk_Window tkwin; /* The window that the following bindings + * depend upon. */ + int deleted; /* Set to non-zero by window cleanup code + * if tkwin is deleted. */ + PatSeq *matchArray[5]; /* Array of pending C bindings. The actual + * size of this depends on how many C bindings + * matched the event passed to Tk_BindEvent. + * THIS FIELD MUST BE THE LAST IN THE + * STRUCTURE. */ +} PendingBinding; + +/* + * The following structure keeps track of all the information local to + * the binding package on a per interpreter basis. + */ + +typedef struct BindInfo { + VirtualEventTable virtualEventTable; + /* The virtual events that exist in this + * interpreter. */ + ScreenInfo screenInfo; /* Keeps track of the current display and + * screen, so it can be restored after + * a binding has executed. */ + PendingBinding *pendingList;/* The list of pending C bindings, kept in + * case a C or Tcl binding causes the target + * window to be deleted. */ +} BindInfo; + +/* + * In X11R4 and earlier versions, XStringToKeysym is ridiculously + * slow. The data structure and hash table below, along with the + * code that uses them, implement a fast mapping from strings to + * keysyms. In X11R5 and later releases XStringToKeysym is plenty + * fast so this stuff isn't needed. The #define REDO_KEYSYM_LOOKUP + * is normally undefined, so that XStringToKeysym gets used. It + * can be set in the Makefile to enable the use of the hash table + * below. + */ + +#ifdef REDO_KEYSYM_LOOKUP +typedef struct { + char *name; /* Name of keysym. */ + KeySym value; /* Numeric identifier for keysym. */ +} KeySymInfo; +static KeySymInfo keyArray[] = { +#ifndef lint +#include "ks_names.h" +#endif + {(char *) NULL, 0} +}; +static Tcl_HashTable keySymTable; /* keyArray hashed by keysym value. */ +static Tcl_HashTable nameTable; /* keyArray hashed by keysym name. */ +#endif /* REDO_KEYSYM_LOOKUP */ + +/* + * Set to non-zero when the package-wide static variables have been + * initialized. + */ + +static int initialized = 0; + +/* + * A hash table is kept to map from the string names of event + * modifiers to information about those modifiers. The structure + * for storing this information, and the hash table built at + * initialization time, are defined below. + */ + +typedef struct { + char *name; /* Name of modifier. */ + int mask; /* Button/modifier mask value, * such as Button1Mask. */ + int flags; /* Various flags; see below for + * definitions. */ +} ModInfo; + +/* + * Flags for ModInfo structures: + * + * DOUBLE - Non-zero means duplicate this event, + * e.g. for double-clicks. + * TRIPLE - Non-zero means triplicate this event, + * e.g. for triple-clicks. + */ + +#define DOUBLE 1 +#define TRIPLE 2 + +/* + * The following special modifier mask bits are defined, to indicate + * logical modifiers such as Meta and Alt that may float among the + * actual modifier bits. + */ + +#define META_MASK (AnyModifier<<1) +#define ALT_MASK (AnyModifier<<2) + +static ModInfo modArray[] = { + {"Control", ControlMask, 0}, + {"Shift", ShiftMask, 0}, + {"Lock", LockMask, 0}, + {"Meta", META_MASK, 0}, + {"M", META_MASK, 0}, + {"Alt", ALT_MASK, 0}, + {"B1", Button1Mask, 0}, + {"Button1", Button1Mask, 0}, + {"B2", Button2Mask, 0}, + {"Button2", Button2Mask, 0}, + {"B3", Button3Mask, 0}, + {"Button3", Button3Mask, 0}, + {"B4", Button4Mask, 0}, + {"Button4", Button4Mask, 0}, + {"B5", Button5Mask, 0}, + {"Button5", Button5Mask, 0}, + {"Mod1", Mod1Mask, 0}, + {"M1", Mod1Mask, 0}, + {"Command", Mod1Mask, 0}, + {"Mod2", Mod2Mask, 0}, + {"M2", Mod2Mask, 0}, + {"Option", Mod2Mask, 0}, + {"Mod3", Mod3Mask, 0}, + {"M3", Mod3Mask, 0}, + {"Mod4", Mod4Mask, 0}, + {"M4", Mod4Mask, 0}, + {"Mod5", Mod5Mask, 0}, + {"M5", Mod5Mask, 0}, + {"Double", 0, DOUBLE}, + {"Triple", 0, TRIPLE}, + {"Any", 0, 0}, /* Ignored: historical relic. */ + {NULL, 0, 0} +}; +static Tcl_HashTable modTable; + +/* + * This module also keeps a hash table mapping from event names + * to information about those events. The structure, an array + * to use to initialize the hash table, and the hash table are + * all defined below. + */ + +typedef struct { + char *name; /* Name of event. */ + int type; /* Event type for X, such as + * ButtonPress. */ + int eventMask; /* Mask bits (for XSelectInput) + * for this event type. */ +} EventInfo; + +/* + * Note: some of the masks below are an OR-ed combination of + * several masks. This is necessary because X doesn't report + * up events unless you also ask for down events. Also, X + * doesn't report button state in motion events unless you've + * asked about button events. + */ + +static EventInfo eventArray[] = { + {"Key", KeyPress, KeyPressMask}, + {"KeyPress", KeyPress, KeyPressMask}, + {"KeyRelease", KeyRelease, KeyPressMask|KeyReleaseMask}, + {"Button", ButtonPress, ButtonPressMask}, + {"ButtonPress", ButtonPress, ButtonPressMask}, + {"ButtonRelease", ButtonRelease, + ButtonPressMask|ButtonReleaseMask}, + {"Motion", MotionNotify, + ButtonPressMask|PointerMotionMask}, + {"Enter", EnterNotify, EnterWindowMask}, + {"Leave", LeaveNotify, LeaveWindowMask}, + {"FocusIn", FocusIn, FocusChangeMask}, + {"FocusOut", FocusOut, FocusChangeMask}, + {"Expose", Expose, ExposureMask}, + {"Visibility", VisibilityNotify, VisibilityChangeMask}, + {"Destroy", DestroyNotify, StructureNotifyMask}, + {"Unmap", UnmapNotify, StructureNotifyMask}, + {"Map", MapNotify, StructureNotifyMask}, + {"Reparent", ReparentNotify, StructureNotifyMask}, + {"Configure", ConfigureNotify, StructureNotifyMask}, + {"Gravity", GravityNotify, StructureNotifyMask}, + {"Circulate", CirculateNotify, StructureNotifyMask}, + {"Property", PropertyNotify, PropertyChangeMask}, + {"Colormap", ColormapNotify, ColormapChangeMask}, + {"Activate", ActivateNotify, ActivateMask}, + {"Deactivate", DeactivateNotify, ActivateMask}, + {(char *) NULL, 0, 0} +}; +static Tcl_HashTable eventTable; + +/* + * The defines and table below are used to classify events into + * various groups. The reason for this is that logically identical + * fields (e.g. "state") appear at different places in different + * types of events. The classification masks can be used to figure + * out quickly where to extract information from events. + */ + +#define KEY 0x1 +#define BUTTON 0x2 +#define MOTION 0x4 +#define CROSSING 0x8 +#define FOCUS 0x10 +#define EXPOSE 0x20 +#define VISIBILITY 0x40 +#define CREATE 0x80 +#define DESTROY 0x100 +#define UNMAP 0x200 +#define MAP 0x400 +#define REPARENT 0x800 +#define CONFIG 0x1000 +#define GRAVITY 0x2000 +#define CIRC 0x4000 +#define PROP 0x8000 +#define COLORMAP 0x10000 +#define VIRTUAL 0x20000 +#define ACTIVATE 0x40000 + +#define KEY_BUTTON_MOTION_VIRTUAL (KEY|BUTTON|MOTION|VIRTUAL) + +static int flagArray[TK_LASTEVENT] = { + /* Not used */ 0, + /* Not used */ 0, + /* KeyPress */ KEY, + /* KeyRelease */ KEY, + /* ButtonPress */ BUTTON, + /* ButtonRelease */ BUTTON, + /* MotionNotify */ MOTION, + /* EnterNotify */ CROSSING, + /* LeaveNotify */ CROSSING, + /* FocusIn */ FOCUS, + /* FocusOut */ FOCUS, + /* KeymapNotify */ 0, + /* Expose */ EXPOSE, + /* GraphicsExpose */ EXPOSE, + /* NoExpose */ 0, + /* VisibilityNotify */ VISIBILITY, + /* CreateNotify */ CREATE, + /* DestroyNotify */ DESTROY, + /* UnmapNotify */ UNMAP, + /* MapNotify */ MAP, + /* MapRequest */ 0, + /* ReparentNotify */ REPARENT, + /* ConfigureNotify */ CONFIG, + /* ConfigureRequest */ 0, + /* GravityNotify */ GRAVITY, + /* ResizeRequest */ 0, + /* CirculateNotify */ CIRC, + /* CirculateRequest */ 0, + /* PropertyNotify */ PROP, + /* SelectionClear */ 0, + /* SelectionRequest */ 0, + /* SelectionNotify */ 0, + /* ColormapNotify */ COLORMAP, + /* ClientMessage */ 0, + /* MappingNotify */ 0, + /* VirtualEvent */ VIRTUAL, + /* Activate */ ACTIVATE, + /* Deactivate */ ACTIVATE +}; + +/* + * The following tables are used as a two-way map between X's internal + * numeric values for fields in an XEvent and the strings used in Tcl. The + * tables are used both when constructing an XEvent from user input and + * when providing data from an XEvent to the user. + */ + +static TkStateMap notifyMode[] = { + {NotifyNormal, "NotifyNormal"}, + {NotifyGrab, "NotifyGrab"}, + {NotifyUngrab, "NotifyUngrab"}, + {NotifyWhileGrabbed, "NotifyWhileGrabbed"}, + {-1, NULL} +}; + +static TkStateMap notifyDetail[] = { + {NotifyAncestor, "NotifyAncestor"}, + {NotifyVirtual, "NotifyVirtual"}, + {NotifyInferior, "NotifyInferior"}, + {NotifyNonlinear, "NotifyNonlinear"}, + {NotifyNonlinearVirtual, "NotifyNonlinearVirtual"}, + {NotifyPointer, "NotifyPointer"}, + {NotifyPointerRoot, "NotifyPointerRoot"}, + {NotifyDetailNone, "NotifyDetailNone"}, + {-1, NULL} +}; + +static TkStateMap circPlace[] = { + {PlaceOnTop, "PlaceOnTop"}, + {PlaceOnBottom, "PlaceOnBottom"}, + {-1, NULL} +}; + +static TkStateMap visNotify[] = { + {VisibilityUnobscured, "VisibilityUnobscured"}, + {VisibilityPartiallyObscured, "VisibilityPartiallyObscured"}, + {VisibilityFullyObscured, "VisibilityFullyObscured"}, + {-1, NULL} +}; + +/* + * Prototypes for local procedures defined in this file: + */ + +static void ChangeScreen _ANSI_ARGS_((Tcl_Interp *interp, + char *dispName, int screenIndex)); +static int CreateVirtualEvent _ANSI_ARGS_((Tcl_Interp *interp, + VirtualEventTable *vetPtr, char *virtString, + char *eventString)); +static int DeleteVirtualEvent _ANSI_ARGS_((Tcl_Interp *interp, + VirtualEventTable *vetPtr, char *virtString, + char *eventString)); +static void DeleteVirtualEventTable _ANSI_ARGS_(( + VirtualEventTable *vetPtr)); +static void ExpandPercents _ANSI_ARGS_((TkWindow *winPtr, + char *before, XEvent *eventPtr, KeySym keySym, + Tcl_DString *dsPtr)); +static void FreeTclBinding _ANSI_ARGS_((ClientData clientData)); +static PatSeq * FindSequence _ANSI_ARGS_((Tcl_Interp *interp, + Tcl_HashTable *patternTablePtr, ClientData object, + char *eventString, int create, int allowVirtual, + unsigned long *maskPtr)); +static void GetAllVirtualEvents _ANSI_ARGS_((Tcl_Interp *interp, + VirtualEventTable *vetPtr)); +static char * GetField _ANSI_ARGS_((char *p, char *copy, int size)); +static KeySym GetKeySym _ANSI_ARGS_((TkDisplay *dispPtr, + XEvent *eventPtr)); +static void GetPatternString _ANSI_ARGS_((PatSeq *psPtr, + Tcl_DString *dsPtr)); +static int GetVirtualEvent _ANSI_ARGS_((Tcl_Interp *interp, + VirtualEventTable *vetPtr, char *virtString)); +static Tk_Uid GetVirtualEventUid _ANSI_ARGS_((Tcl_Interp *interp, + char *virtString)); +static int HandleEventGenerate _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window main, int argc, char **argv)); +static void InitKeymapInfo _ANSI_ARGS_((TkDisplay *dispPtr)); +static void InitVirtualEventTable _ANSI_ARGS_(( + VirtualEventTable *vetPtr)); +static PatSeq * MatchPatterns _ANSI_ARGS_((TkDisplay *dispPtr, + BindingTable *bindPtr, PatSeq *psPtr, + PatSeq *bestPtr, ClientData *objectPtr, + PatSeq **sourcePtrPtr)); +static int ParseEventDescription _ANSI_ARGS_((Tcl_Interp *interp, + char **eventStringPtr, Pattern *patPtr, + unsigned long *eventMaskPtr)); + +/* + * The following define is used as a short circuit for the callback + * procedure to evaluate a TclBinding. The actual evaluation of the + * binding is handled inline, because special things have to be done + * with a Tcl binding before evaluation time. + */ + +#define EvalTclBinding ((TkBindEvalProc *) 1) + + +/* + *--------------------------------------------------------------------------- + * + * TkBindInit -- + * + * This procedure is called when an application is created. It + * initializes all the structures used by bindings and virtual + * events. It must be called before any other functions in this + * file are called. + * + * Results: + * None. + * + * Side effects: + * Memory allocated. + * + *--------------------------------------------------------------------------- + */ + +void +TkBindInit(mainPtr) + TkMainInfo *mainPtr; /* The newly created application. */ +{ + BindInfo *bindInfoPtr; + + if (sizeof(XEvent) < sizeof(XVirtualEvent)) { + panic("TkBindInit: virtual events can't be supported"); + } + + /* + * Initialize the static data structures used by the binding package. + * They are only initialized once, no matter how many interps are + * created. + */ + + if (!initialized) { + Tcl_HashEntry *hPtr; + ModInfo *modPtr; + EventInfo *eiPtr; + int dummy; + +#ifdef REDO_KEYSYM_LOOKUP + KeySymInfo *kPtr; + + Tcl_InitHashTable(&keySymTable, TCL_STRING_KEYS); + Tcl_InitHashTable(&nameTable, TCL_ONE_WORD_KEYS); + for (kPtr = keyArray; kPtr->name != NULL; kPtr++) { + hPtr = Tcl_CreateHashEntry(&keySymTable, kPtr->name, &dummy); + Tcl_SetHashValue(hPtr, kPtr->value); + hPtr = Tcl_CreateHashEntry(&nameTable, (char *) kPtr->value, + &dummy); + Tcl_SetHashValue(hPtr, kPtr->name); + } +#endif /* REDO_KEYSYM_LOOKUP */ + + Tcl_InitHashTable(&modTable, TCL_STRING_KEYS); + for (modPtr = modArray; modPtr->name != NULL; modPtr++) { + hPtr = Tcl_CreateHashEntry(&modTable, modPtr->name, &dummy); + Tcl_SetHashValue(hPtr, modPtr); + } + + Tcl_InitHashTable(&eventTable, TCL_STRING_KEYS); + for (eiPtr = eventArray; eiPtr->name != NULL; eiPtr++) { + hPtr = Tcl_CreateHashEntry(&eventTable, eiPtr->name, &dummy); + Tcl_SetHashValue(hPtr, eiPtr); + } + initialized = 1; + } + + mainPtr->bindingTable = Tk_CreateBindingTable(mainPtr->interp); + + bindInfoPtr = (BindInfo *) ckalloc(sizeof(BindInfo)); + InitVirtualEventTable(&bindInfoPtr->virtualEventTable); + bindInfoPtr->screenInfo.curDispPtr = NULL; + bindInfoPtr->screenInfo.curScreenIndex = -1; + bindInfoPtr->screenInfo.bindingDepth = 0; + bindInfoPtr->pendingList = NULL; + mainPtr->bindInfo = (TkBindInfo) bindInfoPtr; + + TkpInitializeMenuBindings(mainPtr->interp, mainPtr->bindingTable); +} + +/* + *--------------------------------------------------------------------------- + * + * TkBindFree -- + * + * This procedure is called when an application is deleted. It + * deletes all the structures used by bindings and virtual events. + * + * Results: + * None. + * + * Side effects: + * Memory freed. + * + *--------------------------------------------------------------------------- + */ + +void +TkBindFree(mainPtr) + TkMainInfo *mainPtr; /* The newly created application. */ +{ + BindInfo *bindInfoPtr; + + Tk_DeleteBindingTable(mainPtr->bindingTable); + mainPtr->bindingTable = NULL; + + bindInfoPtr = (BindInfo *) mainPtr->bindInfo; + DeleteVirtualEventTable(&bindInfoPtr->virtualEventTable); + mainPtr->bindInfo = NULL; +} + +/* + *-------------------------------------------------------------- + * + * Tk_CreateBindingTable -- + * + * Set up a new domain in which event bindings may be created. + * + * Results: + * The return value is a token for the new table, which must + * be passed to procedures like Tk_CreatBinding. + * + * Side effects: + * Memory is allocated for the new table. + * + *-------------------------------------------------------------- + */ + +Tk_BindingTable +Tk_CreateBindingTable(interp) + Tcl_Interp *interp; /* Interpreter to associate with the binding + * table: commands are executed in this + * interpreter. */ +{ + BindingTable *bindPtr; + int i; + + /* + * Create and initialize a new binding table. + */ + + bindPtr = (BindingTable *) ckalloc(sizeof(BindingTable)); + for (i = 0; i < EVENT_BUFFER_SIZE; i++) { + bindPtr->eventRing[i].type = -1; + } + bindPtr->curEvent = 0; + Tcl_InitHashTable(&bindPtr->patternTable, + sizeof(PatternTableKey)/sizeof(int)); + Tcl_InitHashTable(&bindPtr->objectTable, TCL_ONE_WORD_KEYS); + bindPtr->interp = interp; + return (Tk_BindingTable) bindPtr; +} + +/* + *-------------------------------------------------------------- + * + * Tk_DeleteBindingTable -- + * + * Destroy a binding table and free up all its memory. + * The caller should not use bindingTable again after + * this procedure returns. + * + * Results: + * None. + * + * Side effects: + * Memory is freed. + * + *-------------------------------------------------------------- + */ + +void +Tk_DeleteBindingTable(bindingTable) + Tk_BindingTable bindingTable; /* Token for the binding table to + * destroy. */ +{ + BindingTable *bindPtr = (BindingTable *) bindingTable; + PatSeq *psPtr, *nextPtr; + Tcl_HashEntry *hPtr; + Tcl_HashSearch search; + + /* + * Find and delete all of the patterns associated with the binding + * table. + */ + + for (hPtr = Tcl_FirstHashEntry(&bindPtr->patternTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + for (psPtr = (PatSeq *) Tcl_GetHashValue(hPtr); + psPtr != NULL; psPtr = nextPtr) { + nextPtr = psPtr->nextSeqPtr; + psPtr->flags |= MARKED_DELETED; + if (psPtr->refCount == 0) { + if (psPtr->freeProc != NULL) { + (*psPtr->freeProc)(psPtr->clientData); + } + ckfree((char *) psPtr); + } + } + } + + /* + * Clean up the rest of the information associated with the + * binding table. + */ + + Tcl_DeleteHashTable(&bindPtr->patternTable); + Tcl_DeleteHashTable(&bindPtr->objectTable); + ckfree((char *) bindPtr); +} + +/* + *-------------------------------------------------------------- + * + * Tk_CreateBinding -- + * + * Add a binding to a binding table, so that future calls to + * Tk_BindEvent may execute the command in the binding. + * + * Results: + * The return value is 0 if an error occurred while setting + * up the binding. In this case, an error message will be + * left in interp->result. If all went well then the return + * value is a mask of the event types that must be made + * available to Tk_BindEvent in order to properly detect when + * this binding triggers. This value can be used to determine + * what events to select for in a window, for example. + * + * Side effects: + * An existing binding on the same event sequence may be + * replaced. + * The new binding may cause future calls to Tk_BindEvent to + * behave differently than they did previously. + * + *-------------------------------------------------------------- + */ + +unsigned long +Tk_CreateBinding(interp, bindingTable, object, eventString, command, append) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_BindingTable bindingTable; + /* Table in which to create binding. */ + ClientData object; /* Token for object with which binding is + * associated. */ + char *eventString; /* String describing event sequence that + * triggers binding. */ + char *command; /* Contains Tcl command to execute when + * binding triggers. */ + int append; /* 0 means replace any existing binding for + * eventString; 1 means append to that + * binding. If the existing binding is for a + * callback function and not a Tcl command + * string, the existing binding will always be + * replaced. */ +{ + BindingTable *bindPtr = (BindingTable *) bindingTable; + PatSeq *psPtr; + unsigned long eventMask; + char *new, *old; + + psPtr = FindSequence(interp, &bindPtr->patternTable, object, eventString, + 1, 1, &eventMask); + if (psPtr == NULL) { + return 0; + } + if (psPtr->eventProc == NULL) { + int new; + Tcl_HashEntry *hPtr; + + /* + * This pattern sequence was just created. + * Link the pattern into the list associated with the object, so + * that if the object goes away, these bindings will all + * automatically be deleted. + */ + + hPtr = Tcl_CreateHashEntry(&bindPtr->objectTable, (char *) object, + &new); + if (new) { + psPtr->nextObjPtr = NULL; + } else { + psPtr->nextObjPtr = (PatSeq *) Tcl_GetHashValue(hPtr); + } + Tcl_SetHashValue(hPtr, psPtr); + } else if (psPtr->eventProc != EvalTclBinding) { + /* + * Free existing procedural binding. + */ + + if (psPtr->freeProc != NULL) { + (*psPtr->freeProc)(psPtr->clientData); + } + psPtr->clientData = NULL; + append = 0; + } + + old = (char *) psPtr->clientData; + if ((append != 0) && (old != NULL)) { + int length; + + length = strlen(old) + strlen(command) + 2; + new = (char *) ckalloc((unsigned) length); + sprintf(new, "%s\n%s", old, command); + } else { + new = (char *) ckalloc((unsigned) strlen(command) + 1); + strcpy(new, command); + } + if (old != NULL) { + ckfree(old); + } + psPtr->eventProc = EvalTclBinding; + psPtr->freeProc = FreeTclBinding; + psPtr->clientData = (ClientData) new; + return eventMask; +} + +/* + *--------------------------------------------------------------------------- + * + * TkCreateBindingProcedure -- + * + * Add a C binding to a binding table, so that future calls to + * Tk_BindEvent may callback the procedure in the binding. + * + * Results: + * The return value is 0 if an error occurred while setting + * up the binding. In this case, an error message will be + * left in interp->result. If all went well then the return + * value is a mask of the event types that must be made + * available to Tk_BindEvent in order to properly detect when + * this binding triggers. This value can be used to determine + * what events to select for in a window, for example. + * + * Side effects: + * Any existing binding on the same event sequence will be + * replaced. + * + *--------------------------------------------------------------------------- + */ + +unsigned long +TkCreateBindingProcedure(interp, bindingTable, object, eventString, + eventProc, freeProc, clientData) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_BindingTable bindingTable; + /* Table in which to create binding. */ + ClientData object; /* Token for object with which binding is + * associated. */ + char *eventString; /* String describing event sequence that + * triggers binding. */ + TkBindEvalProc *eventProc; /* Procedure to invoke when binding + * triggers. Must not be NULL. */ + TkBindFreeProc *freeProc; /* Procedure to invoke when binding is + * freed. May be NULL for no procedure. */ + ClientData clientData; /* Arbitrary ClientData to pass to eventProc + * and freeProc. */ +{ + BindingTable *bindPtr = (BindingTable *) bindingTable; + PatSeq *psPtr; + unsigned long eventMask; + + psPtr = FindSequence(interp, &bindPtr->patternTable, object, eventString, + 1, 1, &eventMask); + if (psPtr == NULL) { + return 0; + } + if (psPtr->eventProc == NULL) { + int new; + Tcl_HashEntry *hPtr; + + /* + * This pattern sequence was just created. + * Link the pattern into the list associated with the object, so + * that if the object goes away, these bindings will all + * automatically be deleted. + */ + + hPtr = Tcl_CreateHashEntry(&bindPtr->objectTable, (char *) object, + &new); + if (new) { + psPtr->nextObjPtr = NULL; + } else { + psPtr->nextObjPtr = (PatSeq *) Tcl_GetHashValue(hPtr); + } + Tcl_SetHashValue(hPtr, psPtr); + } else { + + /* + * Free existing callback. + */ + + if (psPtr->freeProc != NULL) { + (*psPtr->freeProc)(psPtr->clientData); + } + } + + psPtr->eventProc = eventProc; + psPtr->freeProc = freeProc; + psPtr->clientData = clientData; + return eventMask; +} + +/* + *-------------------------------------------------------------- + * + * Tk_DeleteBinding -- + * + * Remove an event binding from a binding table. + * + * Results: + * The result is a standard Tcl return value. If an error + * occurs then interp->result will contain an error message. + * + * Side effects: + * The binding given by object and eventString is removed + * from bindingTable. + * + *-------------------------------------------------------------- + */ + +int +Tk_DeleteBinding(interp, bindingTable, object, eventString) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_BindingTable bindingTable; /* Table in which to delete binding. */ + ClientData object; /* Token for object with which binding + * is associated. */ + char *eventString; /* String describing event sequence + * that triggers binding. */ +{ + BindingTable *bindPtr = (BindingTable *) bindingTable; + PatSeq *psPtr, *prevPtr; + unsigned long eventMask; + Tcl_HashEntry *hPtr; + + psPtr = FindSequence(interp, &bindPtr->patternTable, object, eventString, + 0, 1, &eventMask); + if (psPtr == NULL) { + Tcl_ResetResult(interp); + return TCL_OK; + } + + /* + * Unlink the binding from the list for its object, then from the + * list for its pattern. + */ + + hPtr = Tcl_FindHashEntry(&bindPtr->objectTable, (char *) object); + if (hPtr == NULL) { + panic("Tk_DeleteBinding couldn't find object table entry"); + } + prevPtr = (PatSeq *) Tcl_GetHashValue(hPtr); + if (prevPtr == psPtr) { + Tcl_SetHashValue(hPtr, psPtr->nextObjPtr); + } else { + for ( ; ; prevPtr = prevPtr->nextObjPtr) { + if (prevPtr == NULL) { + panic("Tk_DeleteBinding couldn't find on object list"); + } + if (prevPtr->nextObjPtr == psPtr) { + prevPtr->nextObjPtr = psPtr->nextObjPtr; + break; + } + } + } + prevPtr = (PatSeq *) Tcl_GetHashValue(psPtr->hPtr); + if (prevPtr == psPtr) { + if (psPtr->nextSeqPtr == NULL) { + Tcl_DeleteHashEntry(psPtr->hPtr); + } else { + Tcl_SetHashValue(psPtr->hPtr, psPtr->nextSeqPtr); + } + } else { + for ( ; ; prevPtr = prevPtr->nextSeqPtr) { + if (prevPtr == NULL) { + panic("Tk_DeleteBinding couldn't find on hash chain"); + } + if (prevPtr->nextSeqPtr == psPtr) { + prevPtr->nextSeqPtr = psPtr->nextSeqPtr; + break; + } + } + } + + psPtr->flags |= MARKED_DELETED; + if (psPtr->refCount == 0) { + if (psPtr->freeProc != NULL) { + (*psPtr->freeProc)(psPtr->clientData); + } + ckfree((char *) psPtr); + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * Tk_GetBinding -- + * + * Return the command associated with a given event string. + * + * Results: + * The return value is a pointer to the command string + * associated with eventString for object in the domain + * given by bindingTable. If there is no binding for + * eventString, or if eventString is improperly formed, + * then NULL is returned and an error message is left in + * interp->result. The return value is semi-static: it + * will persist until the binding is changed or deleted. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_GetBinding(interp, bindingTable, object, eventString) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_BindingTable bindingTable; /* Table in which to look for + * binding. */ + ClientData object; /* Token for object with which binding + * is associated. */ + char *eventString; /* String describing event sequence + * that triggers binding. */ +{ + BindingTable *bindPtr = (BindingTable *) bindingTable; + PatSeq *psPtr; + unsigned long eventMask; + + psPtr = FindSequence(interp, &bindPtr->patternTable, object, eventString, + 0, 1, &eventMask); + if (psPtr == NULL) { + return NULL; + } + if (psPtr->eventProc == EvalTclBinding) { + return (char *) psPtr->clientData; + } + return ""; +} + +/* + *-------------------------------------------------------------- + * + * Tk_GetAllBindings -- + * + * Return a list of event strings for all the bindings + * associated with a given object. + * + * Results: + * There is no return value. Interp->result is modified to + * hold a Tcl list with one entry for each binding associated + * with object in bindingTable. Each entry in the list + * contains the event string associated with one binding. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +Tk_GetAllBindings(interp, bindingTable, object) + Tcl_Interp *interp; /* Interpreter returning result or + * error. */ + Tk_BindingTable bindingTable; /* Table in which to look for + * bindings. */ + ClientData object; /* Token for object. */ + +{ + BindingTable *bindPtr = (BindingTable *) bindingTable; + PatSeq *psPtr; + Tcl_HashEntry *hPtr; + Tcl_DString ds; + + hPtr = Tcl_FindHashEntry(&bindPtr->objectTable, (char *) object); + if (hPtr == NULL) { + return; + } + Tcl_DStringInit(&ds); + for (psPtr = (PatSeq *) Tcl_GetHashValue(hPtr); psPtr != NULL; + psPtr = psPtr->nextObjPtr) { + /* + * For each binding, output information about each of the + * patterns in its sequence. + */ + + Tcl_DStringSetLength(&ds, 0); + GetPatternString(psPtr, &ds); + Tcl_AppendElement(interp, Tcl_DStringValue(&ds)); + } + Tcl_DStringFree(&ds); +} + +/* + *-------------------------------------------------------------- + * + * Tk_DeleteAllBindings -- + * + * Remove all bindings associated with a given object in a + * given binding table. + * + * Results: + * All bindings associated with object are removed from + * bindingTable. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +Tk_DeleteAllBindings(bindingTable, object) + Tk_BindingTable bindingTable; /* Table in which to delete + * bindings. */ + ClientData object; /* Token for object. */ +{ + BindingTable *bindPtr = (BindingTable *) bindingTable; + PatSeq *psPtr, *prevPtr; + PatSeq *nextPtr; + Tcl_HashEntry *hPtr; + + hPtr = Tcl_FindHashEntry(&bindPtr->objectTable, (char *) object); + if (hPtr == NULL) { + return; + } + for (psPtr = (PatSeq *) Tcl_GetHashValue(hPtr); psPtr != NULL; + psPtr = nextPtr) { + nextPtr = psPtr->nextObjPtr; + + /* + * Be sure to remove each binding from its hash chain in the + * pattern table. If this is the last pattern in the chain, + * then delete the hash entry too. + */ + + prevPtr = (PatSeq *) Tcl_GetHashValue(psPtr->hPtr); + if (prevPtr == psPtr) { + if (psPtr->nextSeqPtr == NULL) { + Tcl_DeleteHashEntry(psPtr->hPtr); + } else { + Tcl_SetHashValue(psPtr->hPtr, psPtr->nextSeqPtr); + } + } else { + for ( ; ; prevPtr = prevPtr->nextSeqPtr) { + if (prevPtr == NULL) { + panic("Tk_DeleteAllBindings couldn't find on hash chain"); + } + if (prevPtr->nextSeqPtr == psPtr) { + prevPtr->nextSeqPtr = psPtr->nextSeqPtr; + break; + } + } + } + psPtr->flags |= MARKED_DELETED; + + if (psPtr->refCount == 0) { + if (psPtr->freeProc != NULL) { + (*psPtr->freeProc)(psPtr->clientData); + } + ckfree((char *) psPtr); + } + } + Tcl_DeleteHashEntry(hPtr); +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_BindEvent -- + * + * This procedure is invoked to process an X event. The + * event is added to those recorded for the binding table. + * Then each of the objects at *objectPtr is checked in + * order to see if it has a binding that matches the recent + * events. If so, the most specific binding is invoked for + * each object. + * + * Results: + * None. + * + * Side effects: + * Depends on the command associated with the matching binding. + * + * All Tcl bindings scripts for each object are accumulated before + * the first binding is evaluated. If the action of a Tcl binding + * is to change or delete a binding, or delete the window associated + * with the binding, all the original Tcl binding scripts will still + * fire. Contrast this with C binding procedures. If a pending C + * binding (one that hasn't fired yet, but is queued to be fired for + * this window) is deleted, it will not be called, and if it is + * changed, then the new binding procedure will be called. If the + * window itself is deleted, no further C binding procedures will be + * called for this window. When both Tcl binding scripts and C binding + * procedures are interleaved, the above rules still apply. + * + *--------------------------------------------------------------------------- + */ + +void +Tk_BindEvent(bindingTable, eventPtr, tkwin, numObjects, objectPtr) + Tk_BindingTable bindingTable; /* Table in which to look for + * bindings. */ + XEvent *eventPtr; /* What actually happened. */ + Tk_Window tkwin; /* Window on display where event + * occurred (needed in order to + * locate display information). */ + int numObjects; /* Number of objects at *objectPtr. */ + ClientData *objectPtr; /* Array of one or more objects + * to check for a matching binding. */ +{ + BindingTable *bindPtr; + TkDisplay *dispPtr; + BindInfo *bindInfoPtr; + TkDisplay *oldDispPtr; + ScreenInfo *screenPtr; + XEvent *ringPtr; + PatSeq *vMatchDetailList, *vMatchNoDetailList; + int flags, oldScreen, i, deferModal; + unsigned int matchCount, matchSpace; + Tcl_Interp *interp; + Tcl_DString scripts, savedResult; + Detail detail; + char *p, *end; + PendingBinding *pendingPtr; + PendingBinding staticPending; + TkWindow *winPtr = (TkWindow *)tkwin; + PatternTableKey key; + + /* + * Ignore events on windows that don't have names: these are windows + * like wrapper windows that shouldn't be visible to the + * application. + */ + + if (winPtr->pathName == NULL) { + return; + } + + /* + * Ignore the event completely if it is an Enter, Leave, FocusIn, + * or FocusOut event with detail NotifyInferior. The reason for + * ignoring these events is that we don't want transitions between + * a window and its children to visible to bindings on the parent: + * this would cause problems for mega-widgets, since the internal + * structure of a mega-widget isn't supposed to be visible to + * people watching the parent. + */ + + if ((eventPtr->type == EnterNotify) || (eventPtr->type == LeaveNotify)) { + if (eventPtr->xcrossing.detail == NotifyInferior) { + return; + } + } + if ((eventPtr->type == FocusIn) || (eventPtr->type == FocusOut)) { + if (eventPtr->xfocus.detail == NotifyInferior) { + return; + } + } + + bindPtr = (BindingTable *) bindingTable; + dispPtr = ((TkWindow *) tkwin)->dispPtr; + bindInfoPtr = (BindInfo *) winPtr->mainPtr->bindInfo; + + /* + * Add the new event to the ring of saved events for the + * binding table. Two tricky points: + * + * 1. Combine consecutive MotionNotify events. Do this by putting + * the new event *on top* of the previous event. + * 2. If a modifier key is held down, it auto-repeats to generate + * continuous KeyPress and KeyRelease events. These can flush + * the event ring so that valuable information is lost (such + * as repeated button clicks). To handle this, check for the + * special case of a modifier KeyPress arriving when the previous + * two events are a KeyRelease and KeyPress of the same key. + * If this happens, mark the most recent event (the KeyRelease) + * invalid and put the new event on top of the event before that + * (the KeyPress). + */ + + if ((eventPtr->type == MotionNotify) + && (bindPtr->eventRing[bindPtr->curEvent].type == MotionNotify)) { + /* + * Don't advance the ring pointer. + */ + } else if (eventPtr->type == KeyPress) { + int i; + for (i = 0; ; i++) { + if (i >= dispPtr->numModKeyCodes) { + goto advanceRingPointer; + } + if (dispPtr->modKeyCodes[i] == eventPtr->xkey.keycode) { + break; + } + } + ringPtr = &bindPtr->eventRing[bindPtr->curEvent]; + if ((ringPtr->type != KeyRelease) + || (ringPtr->xkey.keycode != eventPtr->xkey.keycode)) { + goto advanceRingPointer; + } + if (bindPtr->curEvent <= 0) { + i = EVENT_BUFFER_SIZE - 1; + } else { + i = bindPtr->curEvent - 1; + } + ringPtr = &bindPtr->eventRing[i]; + if ((ringPtr->type != KeyPress) + || (ringPtr->xkey.keycode != eventPtr->xkey.keycode)) { + goto advanceRingPointer; + } + bindPtr->eventRing[bindPtr->curEvent].type = -1; + bindPtr->curEvent = i; + } else { + advanceRingPointer: + bindPtr->curEvent++; + if (bindPtr->curEvent >= EVENT_BUFFER_SIZE) { + bindPtr->curEvent = 0; + } + } + ringPtr = &bindPtr->eventRing[bindPtr->curEvent]; + memcpy((VOID *) ringPtr, (VOID *) eventPtr, sizeof(XEvent)); + detail.clientData = 0; + flags = flagArray[ringPtr->type]; + if (flags & KEY) { + detail.keySym = GetKeySym(dispPtr, ringPtr); + if (detail.keySym == NoSymbol) { + detail.keySym = 0; + } + } else if (flags & BUTTON) { + detail.button = ringPtr->xbutton.button; + } else if (flags & VIRTUAL) { + detail.name = ((XVirtualEvent *) ringPtr)->name; + } + bindPtr->detailRing[bindPtr->curEvent] = detail; + + /* + * Find out if there are any virtual events that correspond to this + * physical event (or sequence of physical events). + */ + + vMatchDetailList = NULL; + vMatchNoDetailList = NULL; + memset(&key, 0, sizeof(key)); + + if (ringPtr->type != VirtualEvent) { + Tcl_HashTable *veptPtr; + Tcl_HashEntry *hPtr; + + veptPtr = &bindInfoPtr->virtualEventTable.patternTable; + + key.object = NULL; + key.type = ringPtr->type; + key.detail = detail; + + hPtr = Tcl_FindHashEntry(veptPtr, (char *) &key); + if (hPtr != NULL) { + vMatchDetailList = (PatSeq *) Tcl_GetHashValue(hPtr); + } + + if (key.detail.clientData != 0) { + key.detail.clientData = 0; + hPtr = Tcl_FindHashEntry(veptPtr, (char *) &key); + if (hPtr != NULL) { + vMatchNoDetailList = (PatSeq *) Tcl_GetHashValue(hPtr); + } + } + } + + /* + * Loop over all the binding tags, finding the binding script or + * callback for each one. Append all of the binding scripts, with + * %-sequences expanded, to "scripts", with null characters separating + * the scripts for each object. Append all the callbacks to the array + * of pending callbacks. + */ + + pendingPtr = &staticPending; + matchCount = 0; + matchSpace = sizeof(staticPending.matchArray) / sizeof(PatSeq *); + Tcl_DStringInit(&scripts); + + for ( ; numObjects > 0; numObjects--, objectPtr++) { + PatSeq *matchPtr, *sourcePtr; + Tcl_HashEntry *hPtr; + + matchPtr = NULL; + sourcePtr = NULL; + + /* + * Match the new event against those recorded in the pattern table, + * saving the longest matching pattern. For events with details + * (button and key events), look for a binding for the specific + * key or button. First see if the event matches a physical event + * that the object is interested in, then look for a virtual event. + */ + + key.object = *objectPtr; + key.type = ringPtr->type; + key.detail = detail; + hPtr = Tcl_FindHashEntry(&bindPtr->patternTable, (char *) &key); + if (hPtr != NULL) { + matchPtr = MatchPatterns(dispPtr, bindPtr, + (PatSeq *) Tcl_GetHashValue(hPtr), matchPtr, NULL, + &sourcePtr); + } + + if (vMatchDetailList != NULL) { + matchPtr = MatchPatterns(dispPtr, bindPtr, vMatchDetailList, + matchPtr, objectPtr, &sourcePtr); + } + + /* + * If no match was found, look for a binding for all keys or buttons + * (detail of 0). Again, first match on a virtual event. + */ + + if ((detail.clientData != 0) && (matchPtr == NULL)) { + key.detail.clientData = 0; + hPtr = Tcl_FindHashEntry(&bindPtr->patternTable, (char *) &key); + if (hPtr != NULL) { + matchPtr = MatchPatterns(dispPtr, bindPtr, + (PatSeq *) Tcl_GetHashValue(hPtr), matchPtr, NULL, + &sourcePtr); + } + + if (vMatchNoDetailList != NULL) { + matchPtr = MatchPatterns(dispPtr, bindPtr, vMatchNoDetailList, + matchPtr, objectPtr, &sourcePtr); + } + + } + + if (matchPtr != NULL) { + if (sourcePtr->eventProc == NULL) { + panic("Tk_BindEvent: missing command"); + } + if (sourcePtr->eventProc == EvalTclBinding) { + ExpandPercents(winPtr, (char *) sourcePtr->clientData, + eventPtr, detail.keySym, &scripts); + } else { + if (matchCount >= matchSpace) { + PendingBinding *new; + unsigned int oldSize, newSize; + + oldSize = sizeof(staticPending) + - sizeof(staticPending.matchArray) + + matchSpace * sizeof(PatSeq*); + matchSpace *= 2; + newSize = sizeof(staticPending) + - sizeof(staticPending.matchArray) + + matchSpace * sizeof(PatSeq*); + new = (PendingBinding *) ckalloc(newSize); + memcpy((VOID *) new, (VOID *) pendingPtr, oldSize); + if (pendingPtr != &staticPending) { + ckfree((char *) pendingPtr); + } + pendingPtr = new; + } + sourcePtr->refCount++; + pendingPtr->matchArray[matchCount] = sourcePtr; + matchCount++; + } + /* + * A "" is added to the scripts string to separate the + * various scripts that should be invoked. + */ + + Tcl_DStringAppend(&scripts, "", 1); + } + } + if (Tcl_DStringLength(&scripts) == 0) { + return; + } + + /* + * Now go back through and evaluate the binding for each object, + * in order, dealing with "break" and "continue" exceptions + * appropriately. + * + * There are two tricks here: + * 1. Bindings can be invoked from in the middle of Tcl commands, + * where interp->result is significant (for example, a widget + * might be deleted because of an error in creating it, so the + * result contains an error message that is eventually going to + * be returned by the creating command). To preserve the result, + * we save it in a dynamic string. + * 2. The binding's action can potentially delete the binding, + * so bindPtr may not point to anything valid once the action + * completes. Thus we have to save bindPtr->interp in a + * local variable in order to restore the result. + */ + + interp = bindPtr->interp; + Tcl_DStringInit(&savedResult); + + /* + * Save information about the current screen, then invoke a script + * if the screen has changed. + */ + + Tcl_DStringGetResult(interp, &savedResult); + screenPtr = &bindInfoPtr->screenInfo; + oldDispPtr = screenPtr->curDispPtr; + oldScreen = screenPtr->curScreenIndex; + if ((dispPtr != screenPtr->curDispPtr) + || (Tk_ScreenNumber(tkwin) != screenPtr->curScreenIndex)) { + screenPtr->curDispPtr = dispPtr; + screenPtr->curScreenIndex = Tk_ScreenNumber(tkwin); + ChangeScreen(interp, dispPtr->name, screenPtr->curScreenIndex); + } + + if (matchCount > 0) { + pendingPtr->nextPtr = bindInfoPtr->pendingList; + pendingPtr->tkwin = tkwin; + pendingPtr->deleted = 0; + bindInfoPtr->pendingList = pendingPtr; + } + + /* + * Save the current value of the TK_DEFER_MODAL flag so we can + * restore it at the end of the loop. Clear the flag so we can + * detect any recursive requests for a modal loop. + */ + + flags = winPtr->flags; + winPtr->flags &= ~TK_DEFER_MODAL; + + p = Tcl_DStringValue(&scripts); + end = p + Tcl_DStringLength(&scripts); + i = 0; + + while (p < end) { + int code; + + screenPtr->bindingDepth++; + Tcl_AllowExceptions(interp); + + if (*p == '\0') { + PatSeq *psPtr; + + psPtr = pendingPtr->matchArray[i]; + i++; + code = TCL_OK; + if ((pendingPtr->deleted == 0) + && ((psPtr->flags & MARKED_DELETED) == 0)) { + code = (*psPtr->eventProc)(psPtr->clientData, interp, eventPtr, + tkwin, detail.keySym); + } + psPtr->refCount--; + if ((psPtr->refCount == 0) && (psPtr->flags & MARKED_DELETED)) { + if (psPtr->freeProc != NULL) { + (*psPtr->freeProc)(psPtr->clientData); + } + ckfree((char *) psPtr); + } + } else { + code = Tcl_GlobalEval(interp, p); + p += strlen(p); + } + p++; + screenPtr->bindingDepth--; + if (code != TCL_OK) { + if (code == TCL_CONTINUE) { + /* + * Do nothing: just go on to the next command. + */ + } else if (code == TCL_BREAK) { + break; + } else { + Tcl_AddErrorInfo(interp, "\n (command bound to event)"); + Tcl_BackgroundError(interp); + break; + } + } + } + + if (matchCount > 0 && !pendingPtr->deleted) { + /* + * Restore the original modal flag value and invoke the modal loop + * if needed. + */ + + deferModal = winPtr->flags & TK_DEFER_MODAL; + winPtr->flags = (winPtr->flags & (unsigned int) ~TK_DEFER_MODAL) + | (flags & TK_DEFER_MODAL); + if (deferModal) { + (*winPtr->classProcsPtr->modalProc)(tkwin, eventPtr); + } + } + + if ((screenPtr->bindingDepth != 0) && + ((oldDispPtr != screenPtr->curDispPtr) + || (oldScreen != screenPtr->curScreenIndex))) { + + /* + * Some other binding script is currently executing, but its + * screen is no longer current. Change the current display + * back again. + */ + + screenPtr->curDispPtr = oldDispPtr; + screenPtr->curScreenIndex = oldScreen; + ChangeScreen(interp, oldDispPtr->name, oldScreen); + } + Tcl_DStringResult(interp, &savedResult); + Tcl_DStringFree(&scripts); + + if (matchCount > 0) { + PendingBinding **curPtrPtr; + + for (curPtrPtr = &bindInfoPtr->pendingList; ; ) { + if (*curPtrPtr == pendingPtr) { + *curPtrPtr = pendingPtr->nextPtr; + break; + } + curPtrPtr = &(*curPtrPtr)->nextPtr; + } + if (pendingPtr != &staticPending) { + ckfree((char *) pendingPtr); + } + } +} + +/* + *--------------------------------------------------------------------------- + * + * TkBindDeadWindow -- + * + * This procedure is invoked when it is determined that a window is + * dead. It cleans up bind-related information about the window + * + * Results: + * None. + * + * Side effects: + * Any pending C bindings for this window are cancelled. + * + *--------------------------------------------------------------------------- + */ + +void +TkBindDeadWindow(winPtr) + TkWindow *winPtr; /* The window that is being deleted. */ +{ + BindInfo *bindInfoPtr; + PendingBinding *curPtr; + + bindInfoPtr = (BindInfo *) winPtr->mainPtr->bindInfo; + curPtr = bindInfoPtr->pendingList; + while (curPtr != NULL) { + if (curPtr->tkwin == (Tk_Window) winPtr) { + curPtr->deleted = 1; + } + curPtr = curPtr->nextPtr; + } +} + +/* + *---------------------------------------------------------------------- + * + * MatchPatterns -- + * + * Given a list of pattern sequences and a list of recent events, + * return the pattern sequence that best matches the event list, + * if there is one. + * + * This procedure is used in two different ways. In the simplest + * use, "object" is NULL and psPtr is a list of pattern sequences, + * each of which corresponds to a binding. In this case, the + * procedure finds the pattern sequences that match the event list + * and returns the most specific of those, if there is more than one. + * + * In the second case, psPtr is a list of pattern sequences, each + * of which corresponds to a definition for a virtual binding. + * In order for one of these sequences to "match", it must match + * the events (as above) but in addition there must be a binding + * for its associated virtual event on the current object. The + * "object" argument indicates which object the binding must be for. + * + * Results: + * The return value is NULL if bestPtr is NULL and no pattern matches + * the recent events from bindPtr. Otherwise the return value is + * the most specific pattern sequence among bestPtr and all those + * at psPtr that match the event list and object. If a pattern + * sequence other than bestPtr is returned, then *bestCommandPtr + * is filled in with a pointer to the command from the best sequence. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ +static PatSeq * +MatchPatterns(dispPtr, bindPtr, psPtr, bestPtr, objectPtr, sourcePtrPtr) + TkDisplay *dispPtr; /* Display from which the event came. */ + BindingTable *bindPtr; /* Information about binding table, such as + * ring of recent events. */ + PatSeq *psPtr; /* List of pattern sequences. */ + PatSeq *bestPtr; /* The best match seen so far, from a + * previous call to this procedure. NULL + * means no prior best match. */ + ClientData *objectPtr; /* If NULL, the sequences at psPtr + * correspond to "normal" bindings. If + * non-NULL, the sequences at psPtr correspond + * to virtual bindings; in order to match each + * sequence must correspond to a virtual + * binding for which a binding exists for + * object in bindPtr. */ + PatSeq **sourcePtrPtr; /* Filled with the pattern sequence that + * contains the eventProc and clientData + * associated with the best match. If this + * differs from the return value, it is the + * virtual event that most closely matched the + * return value (a physical event). Not + * modified unless a result other than bestPtr + * is returned. */ +{ + PatSeq *matchPtr, *bestSourcePtr, *sourcePtr; + + bestSourcePtr = *sourcePtrPtr; + + /* + * Iterate over all the pattern sequences. + */ + + for ( ; psPtr != NULL; psPtr = psPtr->nextSeqPtr) { + XEvent *eventPtr; + Pattern *patPtr; + Window window; + Detail *detailPtr; + int patCount, ringCount, flags, state; + int modMask; + + /* + * Iterate over all the patterns in a sequence to be + * sure that they all match. + */ + + eventPtr = &bindPtr->eventRing[bindPtr->curEvent]; + detailPtr = &bindPtr->detailRing[bindPtr->curEvent]; + window = eventPtr->xany.window; + patPtr = psPtr->pats; + patCount = psPtr->numPats; + ringCount = EVENT_BUFFER_SIZE; + while (patCount > 0) { + if (ringCount <= 0) { + goto nextSequence; + } + if (eventPtr->xany.type != patPtr->eventType) { + /* + * Most of the event types are considered superfluous + * in that they are ignored if they occur in the middle + * of a pattern sequence and have mismatching types. The + * only ones that cannot be ignored are ButtonPress and + * ButtonRelease events (if the next event in the pattern + * is a KeyPress or KeyRelease) and KeyPress and KeyRelease + * events (if the next pattern event is a ButtonPress or + * ButtonRelease). Here are some tricky cases to consider: + * 1. Double-Button or Double-Key events. + * 2. Double-ButtonRelease or Double-KeyRelease events. + * 3. The arrival of various events like Enter and Leave + * and FocusIn and GraphicsExpose between two button + * presses or key presses. + * 4. Modifier keys like Shift and Control shouldn't + * generate conflicts with button events. + */ + + if ((patPtr->eventType == KeyPress) + || (patPtr->eventType == KeyRelease)) { + if ((eventPtr->xany.type == ButtonPress) + || (eventPtr->xany.type == ButtonRelease)) { + goto nextSequence; + } + } else if ((patPtr->eventType == ButtonPress) + || (patPtr->eventType == ButtonRelease)) { + if ((eventPtr->xany.type == KeyPress) + || (eventPtr->xany.type == KeyRelease)) { + int i; + + /* + * Ignore key events if they are modifier keys. + */ + + for (i = 0; i < dispPtr->numModKeyCodes; i++) { + if (dispPtr->modKeyCodes[i] + == eventPtr->xkey.keycode) { + /* + * This key is a modifier key, so ignore it. + */ + goto nextEvent; + } + } + goto nextSequence; + } + } + goto nextEvent; + } + if (eventPtr->xany.window != window) { + goto nextSequence; + } + + /* + * Note: it's important for the keysym check to go before + * the modifier check, so we can ignore unwanted modifier + * keys before choking on the modifier check. + */ + + if ((patPtr->detail.clientData != 0) + && (patPtr->detail.clientData != detailPtr->clientData)) { + /* + * The detail appears not to match. However, if the event + * is a KeyPress for a modifier key then just ignore the + * event. Otherwise event sequences like "aD" never match + * because the shift key goes down between the "a" and the + * "D". + */ + + if (eventPtr->xany.type == KeyPress) { + int i; + + for (i = 0; i < dispPtr->numModKeyCodes; i++) { + if (dispPtr->modKeyCodes[i] == eventPtr->xkey.keycode) { + goto nextEvent; + } + } + } + goto nextSequence; + } + flags = flagArray[eventPtr->type]; + if (flags & (KEY_BUTTON_MOTION_VIRTUAL)) { + state = eventPtr->xkey.state; + } else if (flags & CROSSING) { + state = eventPtr->xcrossing.state; + } else { + state = 0; + } + if (patPtr->needMods != 0) { + modMask = patPtr->needMods; + if ((modMask & META_MASK) && (dispPtr->metaModMask != 0)) { + modMask = (modMask & ~META_MASK) | dispPtr->metaModMask; + } + if ((modMask & ALT_MASK) && (dispPtr->altModMask != 0)) { + modMask = (modMask & ~ALT_MASK) | dispPtr->altModMask; + } + if ((state & modMask) != modMask) { + goto nextSequence; + } + } + if (psPtr->flags & PAT_NEARBY) { + XEvent *firstPtr; + int timeDiff; + + firstPtr = &bindPtr->eventRing[bindPtr->curEvent]; + timeDiff = (Time) firstPtr->xkey.time - eventPtr->xkey.time; + if ((firstPtr->xkey.x_root + < (eventPtr->xkey.x_root - NEARBY_PIXELS)) + || (firstPtr->xkey.x_root + > (eventPtr->xkey.x_root + NEARBY_PIXELS)) + || (firstPtr->xkey.y_root + < (eventPtr->xkey.y_root - NEARBY_PIXELS)) + || (firstPtr->xkey.y_root + > (eventPtr->xkey.y_root + NEARBY_PIXELS)) + || (timeDiff > NEARBY_MS)) { + goto nextSequence; + } + } + patPtr++; + patCount--; + nextEvent: + if (eventPtr == bindPtr->eventRing) { + eventPtr = &bindPtr->eventRing[EVENT_BUFFER_SIZE-1]; + detailPtr = &bindPtr->detailRing[EVENT_BUFFER_SIZE-1]; + } else { + eventPtr--; + detailPtr--; + } + ringCount--; + } + + matchPtr = psPtr; + sourcePtr = psPtr; + + if (objectPtr != NULL) { + int iVirt; + VirtualOwners *voPtr; + PatternTableKey key; + + /* + * The sequence matches the physical constraints. + * Is this object interested in any of the virtual events + * that correspond to this sequence? + */ + + voPtr = psPtr->voPtr; + + memset(&key, 0, sizeof(key)); + key.object = *objectPtr; + key.type = VirtualEvent; + key.detail.clientData = 0; + + for (iVirt = 0; iVirt < voPtr->numOwners; iVirt++) { + Tcl_HashEntry *hPtr = voPtr->owners[iVirt]; + + key.detail.name = (Tk_Uid) Tcl_GetHashKey(hPtr->tablePtr, + hPtr); + hPtr = Tcl_FindHashEntry(&bindPtr->patternTable, + (char *) &key); + if (hPtr != NULL) { + + /* + * This tag is interested in this virtual event and its + * corresponding physical event is a good match with the + * virtual event's definition. + */ + + PatSeq *virtMatchPtr; + + virtMatchPtr = (PatSeq *) Tcl_GetHashValue(hPtr); + if ((virtMatchPtr->numPats != 1) + || (virtMatchPtr->nextSeqPtr != NULL)) { + panic("MatchPattern: badly constructed virtual event"); + } + sourcePtr = virtMatchPtr; + goto match; + } + } + + /* + * The physical event matches a virtual event's definition, but + * the tag isn't interested in it. + */ + goto nextSequence; + } + match: + + /* + * This sequence matches. If we've already got another match, + * pick whichever is most specific. Detail is most important, + * then needMods. + */ + + if (bestPtr != NULL) { + Pattern *patPtr2; + int i; + + if (matchPtr->numPats != bestPtr->numPats) { + if (bestPtr->numPats > matchPtr->numPats) { + goto nextSequence; + } else { + goto newBest; + } + } + for (i = 0, patPtr = matchPtr->pats, patPtr2 = bestPtr->pats; + i < matchPtr->numPats; i++, patPtr++, patPtr2++) { + if (patPtr->detail.clientData != patPtr2->detail.clientData) { + if (patPtr->detail.clientData == 0) { + goto nextSequence; + } else { + goto newBest; + } + } + if (patPtr->needMods != patPtr2->needMods) { + if ((patPtr->needMods & patPtr2->needMods) + == patPtr->needMods) { + goto nextSequence; + } else if ((patPtr->needMods & patPtr2->needMods) + == patPtr2->needMods) { + goto newBest; + } + } + } + /* + * Tie goes to current best pattern. + * + * (1) For virtual vs. virtual, the least recently defined + * virtual wins, because virtuals are examined in order of + * definition. This order is _not_ guaranteed in the + * documentation. + * + * (2) For virtual vs. physical, the physical wins because all + * the physicals are examined before the virtuals. This order + * is guaranteed in the documentation. + * + * (3) For physical vs. physical pattern, the most recently + * defined physical wins, because physicals are examined in + * reverse order of definition. This order is guaranteed in + * the documentation. + */ + + goto nextSequence; + } + newBest: + bestPtr = matchPtr; + bestSourcePtr = sourcePtr; + + nextSequence: continue; + } + + *sourcePtrPtr = bestSourcePtr; + return bestPtr; +} + +/* + *-------------------------------------------------------------- + * + * ExpandPercents -- + * + * Given a command and an event, produce a new command + * by replacing % constructs in the original command + * with information from the X event. + * + * Results: + * The new expanded command is appended to the dynamic string + * given by dsPtr. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static void +ExpandPercents(winPtr, before, eventPtr, keySym, dsPtr) + TkWindow *winPtr; /* Window where event occurred: needed to + * get input context. */ + char *before; /* Command containing percent expressions + * to be replaced. */ + XEvent *eventPtr; /* X event containing information to be + * used in % replacements. */ + KeySym keySym; /* KeySym: only relevant for KeyPress and + * KeyRelease events). */ + Tcl_DString *dsPtr; /* Dynamic string in which to append new + * command. */ +{ + int spaceNeeded, cvtFlags; /* Used to substitute string as proper Tcl + * list element. */ + int number, flags, length; +#define NUM_SIZE 40 + char *string; + char numStorage[NUM_SIZE+1]; + + if (eventPtr->type < TK_LASTEVENT) { + flags = flagArray[eventPtr->type]; + } else { + flags = 0; + } + while (1) { + /* + * Find everything up to the next % character and append it + * to the result string. + */ + + for (string = before; (*string != 0) && (*string != '%'); string++) { + /* Empty loop body. */ + } + if (string != before) { + Tcl_DStringAppend(dsPtr, before, string-before); + before = string; + } + if (*before == 0) { + break; + } + + /* + * There's a percent sequence here. Process it. + */ + + number = 0; + string = "??"; + switch (before[1]) { + case '#': + number = eventPtr->xany.serial; + goto doNumber; + case 'a': + TkpPrintWindowId(numStorage, eventPtr->xconfigure.above); + string = numStorage; + goto doString; + case 'b': + number = eventPtr->xbutton.button; + goto doNumber; + case 'c': + if (flags & EXPOSE) { + number = eventPtr->xexpose.count; + } + goto doNumber; + case 'd': + if (flags & (CROSSING|FOCUS)) { + if (flags & FOCUS) { + number = eventPtr->xfocus.detail; + } else { + number = eventPtr->xcrossing.detail; + } + string = TkFindStateString(notifyDetail, number); + } + goto doString; + case 'f': + number = eventPtr->xcrossing.focus; + goto doNumber; + case 'h': + if (flags & EXPOSE) { + number = eventPtr->xexpose.height; + } else if (flags & (CONFIG)) { + number = eventPtr->xconfigure.height; + } + goto doNumber; + case 'k': + number = eventPtr->xkey.keycode; + goto doNumber; + case 'm': + if (flags & CROSSING) { + number = eventPtr->xcrossing.mode; + } else if (flags & FOCUS) { + number = eventPtr->xfocus.mode; + } + string = TkFindStateString(notifyMode, number); + goto doString; + case 'o': + if (flags & CREATE) { + number = eventPtr->xcreatewindow.override_redirect; + } else if (flags & MAP) { + number = eventPtr->xmap.override_redirect; + } else if (flags & REPARENT) { + number = eventPtr->xreparent.override_redirect; + } else if (flags & CONFIG) { + number = eventPtr->xconfigure.override_redirect; + } + goto doNumber; + case 'p': + string = TkFindStateString(circPlace, eventPtr->xcirculate.place); + goto doString; + case 's': + if (flags & (KEY_BUTTON_MOTION_VIRTUAL)) { + number = eventPtr->xkey.state; + } else if (flags & CROSSING) { + number = eventPtr->xcrossing.state; + } else if (flags & VISIBILITY) { + string = TkFindStateString(visNotify, + eventPtr->xvisibility.state); + goto doString; + } + goto doNumber; + case 't': + if (flags & (KEY_BUTTON_MOTION_VIRTUAL)) { + number = (int) eventPtr->xkey.time; + } else if (flags & CROSSING) { + number = (int) eventPtr->xcrossing.time; + } else if (flags & PROP) { + number = (int) eventPtr->xproperty.time; + } + goto doNumber; + case 'v': + number = eventPtr->xconfigurerequest.value_mask; + goto doNumber; + case 'w': + if (flags & EXPOSE) { + number = eventPtr->xexpose.width; + } else if (flags & CONFIG) { + number = eventPtr->xconfigure.width; + } + goto doNumber; + case 'x': + if (flags & (KEY_BUTTON_MOTION_VIRTUAL)) { + number = eventPtr->xkey.x; + } else if (flags & CROSSING) { + number = eventPtr->xcrossing.x; + } else if (flags & EXPOSE) { + number = eventPtr->xexpose.x; + } else if (flags & (CREATE|CONFIG|GRAVITY)) { + number = eventPtr->xcreatewindow.x; + } else if (flags & REPARENT) { + number = eventPtr->xreparent.x; + } + goto doNumber; + case 'y': + if (flags & (KEY_BUTTON_MOTION_VIRTUAL)) { + number = eventPtr->xkey.y; + } else if (flags & EXPOSE) { + number = eventPtr->xexpose.y; + } else if (flags & (CREATE|CONFIG|GRAVITY)) { + number = eventPtr->xcreatewindow.y; + } else if (flags & REPARENT) { + number = eventPtr->xreparent.y; + } else if (flags & CROSSING) { + number = eventPtr->xcrossing.y; + + } + goto doNumber; + case 'A': + if (flags & KEY) { + int numChars; + + /* + * If we're using input methods and this is a keypress + * event, invoke XmbTkFindStateString. Otherwise just use + * the older XTkFindStateString. + */ + +#ifdef TK_USE_INPUT_METHODS + Status status; + if ((winPtr->inputContext != NULL) + && (eventPtr->type == KeyPress)) { + numChars = XmbLookupString(winPtr->inputContext, + &eventPtr->xkey, numStorage, NUM_SIZE, + (KeySym *) NULL, &status); + if ((status != XLookupChars) + && (status != XLookupBoth)) { + numChars = 0; + } + } else { + numChars = XLookupString(&eventPtr->xkey, numStorage, + NUM_SIZE, (KeySym *) NULL, + (XComposeStatus *) NULL); + } +#else /* TK_USE_INPUT_METHODS */ + numChars = XLookupString(&eventPtr->xkey, numStorage, + NUM_SIZE, (KeySym *) NULL, + (XComposeStatus *) NULL); +#endif /* TK_USE_INPUT_METHODS */ + numStorage[numChars] = '\0'; + string = numStorage; + } + goto doString; + case 'B': + number = eventPtr->xcreatewindow.border_width; + goto doNumber; + case 'E': + number = (int) eventPtr->xany.send_event; + goto doNumber; + case 'K': + if (flags & KEY) { + char *name; + + name = TkKeysymToString(keySym); + if (name != NULL) { + string = name; + } + } + goto doString; + case 'N': + number = (int) keySym; + goto doNumber; + case 'R': + TkpPrintWindowId(numStorage, eventPtr->xkey.root); + string = numStorage; + goto doString; + case 'S': + TkpPrintWindowId(numStorage, eventPtr->xkey.subwindow); + string = numStorage; + goto doString; + case 'T': + number = eventPtr->type; + goto doNumber; + case 'W': { + Tk_Window tkwin; + + tkwin = Tk_IdToWindow(eventPtr->xany.display, + eventPtr->xany.window); + if (tkwin != NULL) { + string = Tk_PathName(tkwin); + } else { + string = "??"; + } + goto doString; + } + case 'X': { + Tk_Window tkwin; + int x, y; + int width, height; + + number = eventPtr->xkey.x_root; + tkwin = Tk_IdToWindow(eventPtr->xany.display, + eventPtr->xany.window); + if (tkwin != NULL) { + Tk_GetVRootGeometry(tkwin, &x, &y, &width, &height); + number -= x; + } + goto doNumber; + } + case 'Y': { + Tk_Window tkwin; + int x, y; + int width, height; + + number = eventPtr->xkey.y_root; + tkwin = Tk_IdToWindow(eventPtr->xany.display, + eventPtr->xany.window); + if (tkwin != NULL) { + Tk_GetVRootGeometry(tkwin, &x, &y, &width, &height); + number -= y; + } + goto doNumber; + } + default: + numStorage[0] = before[1]; + numStorage[1] = '\0'; + string = numStorage; + goto doString; + } + + doNumber: + sprintf(numStorage, "%d", number); + string = numStorage; + + doString: + spaceNeeded = Tcl_ScanElement(string, &cvtFlags); + length = Tcl_DStringLength(dsPtr); + Tcl_DStringSetLength(dsPtr, length + spaceNeeded); + spaceNeeded = Tcl_ConvertElement(string, + Tcl_DStringValue(dsPtr) + length, + cvtFlags | TCL_DONT_USE_BRACES); + Tcl_DStringSetLength(dsPtr, length + spaceNeeded); + before += 2; + } +} + +/* + *---------------------------------------------------------------------- + * + * ChangeScreen -- + * + * This procedure is invoked whenever the current screen changes + * in an application. It invokes a Tcl procedure named + * "tkScreenChanged", passing it the screen name as argument. + * tkScreenChanged does things like making the tkPriv variable + * point to an array for the current display. + * + * Results: + * None. + * + * Side effects: + * Depends on what tkScreenChanged does. If an error occurs + * them tkError will be invoked. + * + *---------------------------------------------------------------------- + */ + +static void +ChangeScreen(interp, dispName, screenIndex) + Tcl_Interp *interp; /* Interpreter in which to invoke + * command. */ + char *dispName; /* Name of new display. */ + int screenIndex; /* Index of new screen. */ +{ + Tcl_DString cmd; + int code; + char screen[30]; + + Tcl_DStringInit(&cmd); + Tcl_DStringAppend(&cmd, "tkScreenChanged ", 16); + Tcl_DStringAppend(&cmd, dispName, -1); + sprintf(screen, ".%d", screenIndex); + Tcl_DStringAppend(&cmd, screen, -1); + code = Tcl_GlobalEval(interp, Tcl_DStringValue(&cmd)); + if (code != TCL_OK) { + Tcl_AddErrorInfo(interp, + "\n (changing screen in event binding)"); + Tcl_BackgroundError(interp); + } +} + + +/* + *---------------------------------------------------------------------- + * + * Tk_EventCmd -- + * + * This procedure is invoked to process the "event" Tcl command. + * It is used to define and generate events. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_EventCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + int i; + size_t length; + char *option; + Tk_Window tkwin; + VirtualEventTable *vetPtr; + TkBindInfo bindInfo; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option ?arg1?\"", (char *) NULL); + return TCL_ERROR; + } + + option = argv[1]; + length = strlen(option); + if (length == 0) { + goto badopt; + } + + tkwin = (Tk_Window) clientData; + bindInfo = ((TkWindow *) tkwin)->mainPtr->bindInfo; + vetPtr = &((BindInfo *) bindInfo)->virtualEventTable; + + if (strncmp(option, "add", length) == 0) { + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " add virtual sequence ?sequence ...?\"", (char *) NULL); + return TCL_ERROR; + } + for (i = 3; i < argc; i++) { + if (CreateVirtualEvent(interp, vetPtr, argv[2], argv[i]) + != TCL_OK) { + return TCL_ERROR; + } + } + } else if (strncmp(option, "delete", length) == 0) { + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " delete virtual ?sequence sequence ...?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + return DeleteVirtualEvent(interp, vetPtr, argv[2], NULL); + } + for (i = 3; i < argc; i++) { + if (DeleteVirtualEvent(interp, vetPtr, argv[2], argv[i]) + != TCL_OK) { + return TCL_ERROR; + } + } + } else if (strncmp(option, "generate", length) == 0) { + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " generate window event ?options?\"", (char *) NULL); + return TCL_ERROR; + } + return HandleEventGenerate(interp, tkwin, argc - 2, argv + 2); + } else if (strncmp(option, "info", length) == 0) { + if (argc == 2) { + GetAllVirtualEvents(interp, vetPtr); + return TCL_OK; + } else if (argc == 3) { + return GetVirtualEvent(interp, vetPtr, argv[2]); + } else { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " info ?virtual?\"", (char *) NULL); + return TCL_ERROR; + } + } else { + badopt: + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": should be add, delete, generate, info", (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * InitVirtualEventTable -- + * + * Given storage for a virtual event table, set up the fields to + * prepare a new domain in which virtual events may be defined. + * + * Results: + * None. + * + * Side effects: + * *vetPtr is now initialized. + * + *--------------------------------------------------------------------------- + */ + +static void +InitVirtualEventTable(vetPtr) + VirtualEventTable *vetPtr; /* Pointer to virtual event table. Memory + * is supplied by the caller. */ +{ + Tcl_InitHashTable(&vetPtr->patternTable, + sizeof(PatternTableKey) / sizeof(int)); + Tcl_InitHashTable(&vetPtr->nameTable, TCL_ONE_WORD_KEYS); +} + +/* + *--------------------------------------------------------------------------- + * + * DeleteVirtualEventTable -- + * + * Delete the contents of a virtual event table. The caller is + * responsible for freeing any memory used by the table itself. + * + * Results: + * None. + * + * Side effects: + * Memory is freed. + * + *--------------------------------------------------------------------------- + */ + +static void +DeleteVirtualEventTable(vetPtr) + VirtualEventTable *vetPtr; /* The virtual event table to delete. */ +{ + Tcl_HashEntry *hPtr; + Tcl_HashSearch search; + PatSeq *psPtr, *nextPtr; + + hPtr = Tcl_FirstHashEntry(&vetPtr->patternTable, &search); + for ( ; hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + psPtr = (PatSeq *) Tcl_GetHashValue(hPtr); + for ( ; psPtr != NULL; psPtr = nextPtr) { + nextPtr = psPtr->nextSeqPtr; + ckfree((char *) psPtr->voPtr); + ckfree((char *) psPtr); + } + } + Tcl_DeleteHashTable(&vetPtr->patternTable); + + hPtr = Tcl_FirstHashEntry(&vetPtr->nameTable, &search); + for ( ; hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + ckfree((char *) Tcl_GetHashValue(hPtr)); + } + Tcl_DeleteHashTable(&vetPtr->nameTable); +} + +/* + *---------------------------------------------------------------------- + * + * CreateVirtualEvent -- + * + * Add a new definition for a virtual event. If the virtual event + * is already defined, the new definition augments those that + * already exist. + * + * Results: + * The return value is TCL_ERROR if an error occured while + * creating the virtual binding. In this case, an error message + * will be left in interp->result. If all went well then the return + * value is TCL_OK. + * + * Side effects: + * The virtual event may cause future calls to Tk_BindEvent to + * behave differently than they did previously. + * + *---------------------------------------------------------------------- + */ + +static int +CreateVirtualEvent(interp, vetPtr, virtString, eventString) + Tcl_Interp *interp; /* Used for error reporting. */ + VirtualEventTable *vetPtr;/* Table in which to augment virtual event. */ + char *virtString; /* Name of new virtual event. */ + char *eventString; /* String describing physical event that + * triggers virtual event. */ +{ + PatSeq *psPtr; + int dummy; + Tcl_HashEntry *vhPtr; + unsigned long eventMask; + PhysicalsOwned *poPtr; + VirtualOwners *voPtr; + Tk_Uid virtUid; + + virtUid = GetVirtualEventUid(interp, virtString); + if (virtUid == NULL) { + return TCL_ERROR; + } + + /* + * Find/create physical event + */ + + psPtr = FindSequence(interp, &vetPtr->patternTable, NULL, eventString, + 1, 0, &eventMask); + if (psPtr == NULL) { + return TCL_ERROR; + } + + /* + * Find/create virtual event. + */ + + vhPtr = Tcl_CreateHashEntry(&vetPtr->nameTable, virtUid, &dummy); + + /* + * Make virtual event own the physical event. + */ + + poPtr = (PhysicalsOwned *) Tcl_GetHashValue(vhPtr); + if (poPtr == NULL) { + poPtr = (PhysicalsOwned *) ckalloc(sizeof(PhysicalsOwned)); + poPtr->numOwned = 0; + } else { + /* + * See if this virtual event is already defined for this physical + * event and just return if it is. + */ + + int i; + for (i = 0; i < poPtr->numOwned; i++) { + if (poPtr->patSeqs[i] == psPtr) { + return TCL_OK; + } + } + poPtr = (PhysicalsOwned *) ckrealloc((char *) poPtr, + sizeof(PhysicalsOwned) + poPtr->numOwned * sizeof(PatSeq *)); + } + Tcl_SetHashValue(vhPtr, (ClientData) poPtr); + poPtr->patSeqs[poPtr->numOwned] = psPtr; + poPtr->numOwned++; + + /* + * Make physical event so it can trigger the virtual event. + */ + + voPtr = psPtr->voPtr; + if (voPtr == NULL) { + voPtr = (VirtualOwners *) ckalloc(sizeof(VirtualOwners)); + voPtr->numOwners = 0; + } else { + voPtr = (VirtualOwners *) ckrealloc((char *) voPtr, + sizeof(VirtualOwners) + + voPtr->numOwners * sizeof(Tcl_HashEntry *)); + } + psPtr->voPtr = voPtr; + voPtr->owners[voPtr->numOwners] = vhPtr; + voPtr->numOwners++; + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * DeleteVirtualEvent -- + * + * Remove the definition of a given virtual event. If the + * event string is NULL, all definitions of the virtual event + * will be removed. Otherwise, just the specified definition + * of the virtual event will be removed. + * + * Results: + * The result is a standard Tcl return value. If an error + * occurs then interp->result will contain an error message. + * It is not an error to attempt to delete a virtual event that + * does not exist or a definition that does not exist. + * + * Side effects: + * The virtual event given by virtString may be removed from the + * virtual event table. + * + *-------------------------------------------------------------- + */ + +static int +DeleteVirtualEvent(interp, vetPtr, virtString, eventString) + Tcl_Interp *interp; /* Used for error reporting. */ + VirtualEventTable *vetPtr;/* Table in which to delete event. */ + char *virtString; /* String describing event sequence that + * triggers binding. */ + char *eventString; /* The event sequence that should be deleted, + * or NULL to delete all event sequences for + * the entire virtual event. */ +{ + int iPhys; + Tk_Uid virtUid; + Tcl_HashEntry *vhPtr; + PhysicalsOwned *poPtr; + PatSeq *eventPSPtr; + + virtUid = GetVirtualEventUid(interp, virtString); + if (virtUid == NULL) { + return TCL_ERROR; + } + + vhPtr = Tcl_FindHashEntry(&vetPtr->nameTable, virtUid); + if (vhPtr == NULL) { + return TCL_OK; + } + poPtr = (PhysicalsOwned *) Tcl_GetHashValue(vhPtr); + + eventPSPtr = NULL; + if (eventString != NULL) { + unsigned long eventMask; + + /* + * Delete only the specific physical event associated with the + * virtual event. If the physical event doesn't already exist, or + * the virtual event doesn't own that physical event, return w/o + * doing anything. + */ + + eventPSPtr = FindSequence(interp, &vetPtr->patternTable, NULL, + eventString, 0, 0, &eventMask); + if (eventPSPtr == NULL) { + return (interp->result[0] != '\0') ? TCL_ERROR : TCL_OK; + } + } + + for (iPhys = poPtr->numOwned; --iPhys >= 0; ) { + PatSeq *psPtr = poPtr->patSeqs[iPhys]; + if ((eventPSPtr == NULL) || (psPtr == eventPSPtr)) { + int iVirt; + VirtualOwners *voPtr; + + /* + * Remove association between this physical event and the given + * virtual event that it triggers. + */ + + voPtr = psPtr->voPtr; + for (iVirt = 0; iVirt < voPtr->numOwners; iVirt++) { + if (voPtr->owners[iVirt] == vhPtr) { + break; + } + } + if (iVirt == voPtr->numOwners) { + panic("DeleteVirtualEvent: couldn't find owner"); + } + voPtr->numOwners--; + if (voPtr->numOwners == 0) { + /* + * Removed last reference to this physical event, so + * remove it from physical->virtual map. + */ + PatSeq *prevPtr = (PatSeq *) Tcl_GetHashValue(psPtr->hPtr); + if (prevPtr == psPtr) { + if (psPtr->nextSeqPtr == NULL) { + Tcl_DeleteHashEntry(psPtr->hPtr); + } else { + Tcl_SetHashValue(psPtr->hPtr, + psPtr->nextSeqPtr); + } + } else { + for ( ; ; prevPtr = prevPtr->nextSeqPtr) { + if (prevPtr == NULL) { + panic("Tk_DeleteVirtualEvent couldn't find on hash chain"); + } + if (prevPtr->nextSeqPtr == psPtr) { + prevPtr->nextSeqPtr = psPtr->nextSeqPtr; + break; + } + } + } + ckfree((char *) psPtr->voPtr); + ckfree((char *) psPtr); + } else { + /* + * This physical event still triggers some other virtual + * event(s). Consolidate the list of virtual owners for + * this physical event so it no longer triggers the + * given virtual event. + */ + voPtr->owners[iVirt] = voPtr->owners[voPtr->numOwners]; + } + + /* + * Now delete the virtual event's reference to the physical + * event. + */ + + poPtr->numOwned--; + if (eventPSPtr != NULL && poPtr->numOwned != 0) { + /* + * Just deleting this one physical event. Consolidate list + * of owned physical events and return. + */ + + poPtr->patSeqs[iPhys] = poPtr->patSeqs[poPtr->numOwned]; + return TCL_OK; + } + } + } + + if (poPtr->numOwned == 0) { + /* + * All the physical events for this virtual event were deleted, + * either because there was only one associated physical event or + * because the caller was deleting the entire virtual event. Now + * the virtual event itself should be deleted. + */ + + ckfree((char *) poPtr); + Tcl_DeleteHashEntry(vhPtr); + } + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * GetVirtualEvent -- + * + * Return the list of physical events that can invoke the + * given virtual event. + * + * Results: + * The return value is TCL_OK and interp->result is filled with the + * string representation of the physical events associated with the + * virtual event; if there are no physical events for the given virtual + * event, interp->result is filled with and empty string. If the + * virtual event string is improperly formed, then TCL_ERROR is + * returned and an error message is left in interp->result. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +static int +GetVirtualEvent(interp, vetPtr, virtString) + Tcl_Interp *interp; /* Interpreter for reporting. */ + VirtualEventTable *vetPtr;/* Table in which to look for event. */ + char *virtString; /* String describing virtual event. */ +{ + Tcl_HashEntry *vhPtr; + Tcl_DString ds; + int iPhys; + PhysicalsOwned *poPtr; + Tk_Uid virtUid; + + virtUid = GetVirtualEventUid(interp, virtString); + if (virtUid == NULL) { + return TCL_ERROR; + } + + vhPtr = Tcl_FindHashEntry(&vetPtr->nameTable, virtUid); + if (vhPtr == NULL) { + return TCL_OK; + } + + Tcl_DStringInit(&ds); + + poPtr = (PhysicalsOwned *) Tcl_GetHashValue(vhPtr); + for (iPhys = 0; iPhys < poPtr->numOwned; iPhys++) { + Tcl_DStringSetLength(&ds, 0); + GetPatternString(poPtr->patSeqs[iPhys], &ds); + Tcl_AppendElement(interp, Tcl_DStringValue(&ds)); + } + Tcl_DStringFree(&ds); + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * GetAllVirtualEvents -- + * + * Return a list that contains the names of all the virtual + * event defined. + * + * Results: + * There is no return value. Interp->result is modified to + * hold a Tcl list with one entry for each virtual event in + * nameTable. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static void +GetAllVirtualEvents(interp, vetPtr) + Tcl_Interp *interp; /* Interpreter returning result. */ + VirtualEventTable *vetPtr;/* Table containing events. */ +{ + Tcl_HashEntry *hPtr; + Tcl_HashSearch search; + Tcl_DString ds; + + Tcl_DStringInit(&ds); + + hPtr = Tcl_FirstHashEntry(&vetPtr->nameTable, &search); + for ( ; hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + Tcl_DStringSetLength(&ds, 0); + Tcl_DStringAppend(&ds, "<<", 2); + Tcl_DStringAppend(&ds, Tcl_GetHashKey(hPtr->tablePtr, hPtr), -1); + Tcl_DStringAppend(&ds, ">>", 2); + Tcl_AppendElement(interp, Tcl_DStringValue(&ds)); + } + + Tcl_DStringFree(&ds); +} + +/* + *--------------------------------------------------------------------------- + * + * HandleEventGenerate -- + * + * Helper function for the "event generate" command. Generate and + * process an XEvent, constructed from information parsed from the + * event description string and its optional arguments. + * + * argv[0] contains name of the target window. + * argv[1] contains pattern string for one event (e.g, <Control-v>). + * argv[2..argc-1] contains -field/option pairs for specifying + * additional detail in the generated event. + * + * Either virtual or physical events can be generated this way. + * The event description string must contain the specification + * for only one event. + * + * Results: + * None. + * + * Side effects: + * When constructing the event, + * event.xany.serial is filled with the current X serial number. + * event.xany.window is filled with the target window. + * event.xany.display is filled with the target window's display. + * Any other fields in eventPtr which are not specified by the pattern + * string or the optional arguments, are set to 0. + * + * The event may be handled sychronously or asynchronously, depending + * on the value specified by the optional "-when" option. The + * default setting is synchronous. + * + *--------------------------------------------------------------------------- + */ +static int +HandleEventGenerate(interp, main, argc, argv) + Tcl_Interp *interp; /* Interp for error messages and name lookup. */ + Tk_Window main; /* Main window associated with interp. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Pattern pat; + Tk_Window tkwin; + char *p; + unsigned long eventMask; + int count, i, state, flags, synch; + Tcl_QueuePosition pos; + XEvent event; + + if (argv[0][0] == '.') { + tkwin = Tk_NameToWindow(interp, argv[0], main); + if (tkwin == NULL) { + return TCL_ERROR; + } + } else { + if (TkpScanWindowId(NULL, argv[0], &i) != TCL_OK) { + Tcl_AppendResult(interp, "bad window name/identifier \"", + argv[0], "\"", (char *) NULL); + return TCL_ERROR; + } + tkwin = Tk_IdToWindow(Tk_Display(main), (Window) i); + if ((tkwin == NULL) || (((TkWindow *) main)->mainPtr + != ((TkWindow *) tkwin)->mainPtr)) { + Tcl_AppendResult(interp, "window id \"", argv[0], + "\" doesn't exist in this application", (char *) NULL); + return TCL_ERROR; + } + } + + p = argv[1]; + count = ParseEventDescription(interp, &p, &pat, &eventMask); + if (count == 0) { + return TCL_ERROR; + } + if (count != 1) { + interp->result = "Double or Triple modifier not allowed"; + return TCL_ERROR; + } + if (*p != '\0') { + interp->result = "only one event specification allowed"; + return TCL_ERROR; + } + if (argc & 1) { + Tcl_AppendResult(interp, "value for \"", argv[argc - 1], + "\" missing", (char *) NULL); + return TCL_ERROR; + } + + memset((VOID *) &event, 0, sizeof(event)); + event.xany.type = pat.eventType; + event.xany.serial = NextRequest(Tk_Display(tkwin)); + event.xany.send_event = False; + event.xany.window = Tk_WindowId(tkwin); + event.xany.display = Tk_Display(tkwin); + + flags = flagArray[event.xany.type]; + if (flags & (KEY_BUTTON_MOTION_VIRTUAL)) { + event.xkey.state = pat.needMods; + if (flags & KEY) { + /* + * When mapping from a keysym to a keycode, need information about + * the modifier state that should be used so that when they call + * XKeycodeToKeysym taking into account the xkey.state, they will + * get back the original keysym. + */ + + if (pat.detail.keySym == NoSymbol) { + event.xkey.keycode = 0; + } else { + event.xkey.keycode = XKeysymToKeycode(event.xany.display, + pat.detail.keySym); + } + if (event.xkey.keycode != 0) { + for (state = 0; state < 4; state++) { + if (XKeycodeToKeysym(event.xany.display, + event.xkey.keycode, state) == pat.detail.keySym) { + if (state & 1) { + event.xkey.state |= ShiftMask; + } + if (state & 2) { + TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr; + event.xkey.state |= dispPtr->modeModMask; + } + break; + } + } + } + } else if (flags & BUTTON) { + event.xbutton.button = pat.detail.button; + } else if (flags & VIRTUAL) { + ((XVirtualEvent *) &event)->name = pat.detail.name; + } + } + if (flags & (CREATE|DESTROY|UNMAP|MAP|REPARENT|CONFIG|GRAVITY|CIRC)) { + event.xcreatewindow.window = event.xany.window; + } + + /* + * Process the remaining arguments to fill in additional fields + * of the event. + */ + + synch = 1; + pos = TCL_QUEUE_TAIL; + for (i = 2; i < argc; i += 2) { + char *field, *value; + Tk_Window tkwin2; + int number; + KeySym keysym; + + field = argv[i]; + value = argv[i+1]; + + if (strcmp(field, "-when") == 0) { + if (strcmp(value, "now") == 0) { + synch = 1; + } else if (strcmp(value, "head") == 0) { + pos = TCL_QUEUE_HEAD; + synch = 0; + } else if (strcmp(value, "mark") == 0) { + pos = TCL_QUEUE_MARK; + synch = 0; + } else if (strcmp(value, "tail") == 0) { + pos = TCL_QUEUE_TAIL; + synch = 0; + } else { + Tcl_AppendResult(interp, "bad position \"", value, + "\": should be now, head, mark, tail", (char *) NULL); + return TCL_ERROR; + } + } else if (strcmp(field, "-above") == 0) { + if (value[0] == '.') { + tkwin2 = Tk_NameToWindow(interp, value, main); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + number = Tk_WindowId(tkwin2); + } else if (TkpScanWindowId(interp, value, &number) + != TCL_OK) { + return TCL_ERROR; + } + if (flags & CONFIG) { + event.xconfigure.above = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-borderwidth") == 0) { + if (Tk_GetPixels(interp, tkwin, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & (CREATE|CONFIG)) { + event.xcreatewindow.border_width = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-button") == 0) { + if (Tcl_GetInt(interp, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & BUTTON) { + event.xbutton.button = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-count") == 0) { + if (Tcl_GetInt(interp, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & EXPOSE) { + event.xexpose.count = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-detail") == 0) { + number = TkFindStateNum(interp, field, notifyDetail, value); + if (number < 0) { + return TCL_ERROR; + } + if (flags & FOCUS) { + event.xfocus.detail = number; + } else if (flags & CROSSING) { + event.xcrossing.detail = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-focus") == 0) { + if (Tcl_GetBoolean(interp, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & CROSSING) { + event.xcrossing.focus = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-height") == 0) { + if (Tk_GetPixels(interp, tkwin, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & EXPOSE) { + event.xexpose.height = number; + } else if (flags & CONFIG) { + event.xconfigure.height = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-keycode") == 0) { + if (Tcl_GetInt(interp, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & KEY) { + event.xkey.keycode = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-keysym") == 0) { + keysym = TkStringToKeysym(value); + if (keysym == NoSymbol) { + Tcl_AppendResult(interp, "unknown keysym \"", value, + "\"", (char *) NULL); + return TCL_ERROR; + } + /* + * When mapping from a keysym to a keycode, need information about + * the modifier state that should be used so that when they call + * XKeycodeToKeysym taking into account the xkey.state, they will + * get back the original keysym. + */ + + number = XKeysymToKeycode(event.xany.display, keysym); + if (number == 0) { + Tcl_AppendResult(interp, "no keycode for keysym \"", value, + "\"", (char *) NULL); + return TCL_ERROR; + } + for (state = 0; state < 4; state++) { + if (XKeycodeToKeysym(event.xany.display, (unsigned) number, + state) == keysym) { + if (state & 1) { + event.xkey.state |= ShiftMask; + } + if (state & 2) { + TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr; + event.xkey.state |= dispPtr->modeModMask; + } + break; + } + } + if (flags & KEY) { + event.xkey.keycode = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-mode") == 0) { + number = TkFindStateNum(interp, field, notifyMode, value); + if (number < 0) { + return TCL_ERROR; + } + if (flags & CROSSING) { + event.xcrossing.mode = number; + } else if (flags & FOCUS) { + event.xfocus.mode = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-override") == 0) { + if (Tcl_GetBoolean(interp, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & CREATE) { + event.xcreatewindow.override_redirect = number; + } else if (flags & MAP) { + event.xmap.override_redirect = number; + } else if (flags & REPARENT) { + event.xreparent.override_redirect = number; + } else if (flags & CONFIG) { + event.xconfigure.override_redirect = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-place") == 0) { + number = TkFindStateNum(interp, field, circPlace, value); + if (number < 0) { + return TCL_ERROR; + } + if (flags & CIRC) { + event.xcirculate.place = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-root") == 0) { + if (value[0] == '.') { + tkwin2 = Tk_NameToWindow(interp, value, main); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + number = Tk_WindowId(tkwin2); + } else if (TkpScanWindowId(interp, value, &number) + != TCL_OK) { + return TCL_ERROR; + } + if (flags & (KEY_BUTTON_MOTION_VIRTUAL|CROSSING)) { + event.xkey.root = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-rootx") == 0) { + if (Tk_GetPixels(interp, tkwin, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & (KEY_BUTTON_MOTION_VIRTUAL|CROSSING)) { + event.xkey.x_root = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-rooty") == 0) { + if (Tk_GetPixels(interp, tkwin, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & (KEY_BUTTON_MOTION_VIRTUAL|CROSSING)) { + event.xkey.y_root = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-sendevent") == 0) { + if (isdigit(UCHAR(value[0]))) { + /* + * Allow arbitrary integer values for the field; they + * are needed by a few of the tests in the Tk test suite. + */ + + if (Tcl_GetInt(interp, value, &number) != TCL_OK) { + return TCL_ERROR; + } + } else { + if (Tcl_GetBoolean(interp, value, &number) != TCL_OK) { + return TCL_ERROR; + } + } + event.xany.send_event = number; + } else if (strcmp(field, "-serial") == 0) { + if (Tcl_GetInt(interp, value, &number) != TCL_OK) { + return TCL_ERROR; + } + event.xany.serial = number; + } else if (strcmp(field, "-state") == 0) { + if (flags & (KEY_BUTTON_MOTION_VIRTUAL|CROSSING)) { + if (Tcl_GetInt(interp, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & (KEY_BUTTON_MOTION_VIRTUAL)) { + event.xkey.state = number; + } else { + event.xcrossing.state = number; + } + } else if (flags & VISIBILITY) { + number = TkFindStateNum(interp, field, visNotify, value); + if (number < 0) { + return TCL_ERROR; + } + event.xvisibility.state = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-subwindow") == 0) { + if (value[0] == '.') { + tkwin2 = Tk_NameToWindow(interp, value, main); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + number = Tk_WindowId(tkwin2); + } else if (TkpScanWindowId(interp, value, &number) + != TCL_OK) { + return TCL_ERROR; + } + if (flags & (KEY_BUTTON_MOTION_VIRTUAL|CROSSING)) { + event.xkey.subwindow = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-time") == 0) { + if (Tcl_GetInt(interp, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & (KEY_BUTTON_MOTION_VIRTUAL|CROSSING)) { + event.xkey.time = (Time) number; + } else if (flags & PROP) { + event.xproperty.time = (Time) number; + } else { + goto badopt; + } + } else if (strcmp(field, "-width") == 0) { + if (Tk_GetPixels(interp, tkwin, value, &number) != TCL_OK) { + return TCL_ERROR; + } + if (flags & EXPOSE) { + event.xexpose.width = number; + } else if (flags & (CREATE|CONFIG)) { + event.xcreatewindow.width = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-window") == 0) { + if (value[0] == '.') { + tkwin2 = Tk_NameToWindow(interp, value, main); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + number = Tk_WindowId(tkwin2); + } else if (TkpScanWindowId(interp, value, &number) + != TCL_OK) { + return TCL_ERROR; + } + if (flags & (CREATE|DESTROY|UNMAP|MAP|REPARENT|CONFIG + |GRAVITY|CIRC)) { + event.xcreatewindow.window = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-x") == 0) { + int rootX, rootY; + if (Tk_GetPixels(interp, tkwin, value, &number) != TCL_OK) { + return TCL_ERROR; + } + Tk_GetRootCoords(tkwin, &rootX, &rootY); + rootX += number; + if (flags & (KEY_BUTTON_MOTION_VIRTUAL|CROSSING)) { + event.xkey.x = number; + event.xkey.x_root = rootX; + } else if (flags & EXPOSE) { + event.xexpose.x = number; + } else if (flags & (CREATE|CONFIG|GRAVITY)) { + event.xcreatewindow.x = number; + } else if (flags & REPARENT) { + event.xreparent.x = number; + } else { + goto badopt; + } + } else if (strcmp(field, "-y") == 0) { + int rootX, rootY; + if (Tk_GetPixels(interp, tkwin, value, &number) != TCL_OK) { + return TCL_ERROR; + } + Tk_GetRootCoords(tkwin, &rootX, &rootY); + rootY += number; + if (flags & (KEY_BUTTON_MOTION_VIRTUAL|CROSSING)) { + event.xkey.y = number; + event.xkey.y_root = rootY; + } else if (flags & EXPOSE) { + event.xexpose.y = number; + } else if (flags & (CREATE|CONFIG|GRAVITY)) { + event.xcreatewindow.y = number; + } else if (flags & REPARENT) { + event.xreparent.y = number; + } else { + goto badopt; + } + } else { + badopt: + Tcl_AppendResult(interp, "bad option to ", argv[1], + " event: \"", field, "\"", (char *) NULL); + return TCL_ERROR; + } + } + + if (synch != 0) { + Tk_HandleEvent(&event); + } else { + Tk_QueueWindowEvent(&event, pos); + } + Tcl_ResetResult(interp); + return TCL_OK; +} + +/* + *------------------------------------------------------------------------- + * + * GetVirtualEventUid -- + * + * Determine if the given string is in the proper format for a + * virtual event. + * + * Results: + * The return value is NULL if the virtual event string was + * not in the proper format. In this case, an error message + * will be left in interp->result. Otherwise the return + * value is a Tk_Uid that represents the virtual event. + * + * Side effects: + * None. + * + *------------------------------------------------------------------------- + */ +static Tk_Uid +GetVirtualEventUid(interp, virtString) + Tcl_Interp *interp; + char *virtString; +{ + Tk_Uid uid; + int length; + + length = strlen(virtString); + + if (length < 5 || virtString[0] != '<' || virtString[1] != '<' || + virtString[length - 2] != '>' || virtString[length - 1] != '>') { + Tcl_AppendResult(interp, "virtual event \"", virtString, + "\" is badly formed", (char *) NULL); + return NULL; + } + virtString[length - 2] = '\0'; + uid = Tk_GetUid(virtString + 2); + virtString[length - 2] = '>'; + + return uid; +} + + +/* + *---------------------------------------------------------------------- + * + * FindSequence -- + * + * Find the entry in the pattern table that corresponds to a + * particular pattern string, and return a pointer to that + * entry. + * + * Results: + * The return value is normally a pointer to the PatSeq + * in patternTable that corresponds to eventString. If an error + * was found while parsing eventString, or if "create" is 0 and + * no pattern sequence previously existed, then NULL is returned + * and interp->result contains a message describing the problem. + * If no pattern sequence previously existed for eventString, then + * a new one is created with a NULL command field. In a successful + * return, *maskPtr is filled in with a mask of the event types + * on which the pattern sequence depends. + * + * Side effects: + * A new pattern sequence may be allocated. + * + *---------------------------------------------------------------------- + */ + +static PatSeq * +FindSequence(interp, patternTablePtr, object, eventString, create, + allowVirtual, maskPtr) + Tcl_Interp *interp; /* Interpreter to use for error + * reporting. */ + Tcl_HashTable *patternTablePtr; /* Table to use for lookup. */ + ClientData object; /* For binding table, token for object with + * which binding is associated. + * For virtual event table, NULL. */ + char *eventString; /* String description of pattern to + * match on. See user documentation + * for details. */ + int create; /* 0 means don't create the entry if + * it doesn't already exist. Non-zero + * means create. */ + int allowVirtual; /* 0 means that virtual events are not + * allowed in the sequence. Non-zero + * otherwise. */ + unsigned long *maskPtr; /* *maskPtr is filled in with the event + * types on which this pattern sequence + * depends. */ +{ + + Pattern pats[EVENT_BUFFER_SIZE]; + int numPats, virtualFound; + char *p; + Pattern *patPtr; + PatSeq *psPtr; + Tcl_HashEntry *hPtr; + int flags, count, new; + size_t sequenceSize; + unsigned long eventMask; + PatternTableKey key; + + /* + *------------------------------------------------------------- + * Step 1: parse the pattern string to produce an array + * of Patterns. The array is generated backwards, so + * that the lowest-indexed pattern corresponds to the last + * event that must occur. + *------------------------------------------------------------- + */ + + p = eventString; + flags = 0; + eventMask = 0; + virtualFound = 0; + + patPtr = &pats[EVENT_BUFFER_SIZE-1]; + for (numPats = 0; numPats < EVENT_BUFFER_SIZE; numPats++, patPtr--) { + while (isspace(UCHAR(*p))) { + p++; + } + if (*p == '\0') { + break; + } + + count = ParseEventDescription(interp, &p, patPtr, &eventMask); + if (count == 0) { + return NULL; + } + + if (eventMask & VirtualEventMask) { + if (allowVirtual == 0) { + interp->result = + "virtual event not allowed in definition of another virtual event"; + return NULL; + } + virtualFound = 1; + } + + /* + * Replicate events for DOUBLE and TRIPLE. + */ + + if ((count > 1) && (numPats < EVENT_BUFFER_SIZE-1)) { + flags |= PAT_NEARBY; + patPtr[-1] = patPtr[0]; + patPtr--; + numPats++; + if ((count == 3) && (numPats < EVENT_BUFFER_SIZE-1)) { + patPtr[-1] = patPtr[0]; + patPtr--; + numPats++; + } + } + } + + /* + *------------------------------------------------------------- + * Step 2: find the sequence in the binding table if it exists, + * and add a new sequence to the table if it doesn't. + *------------------------------------------------------------- + */ + + if (numPats == 0) { + interp->result = "no events specified in binding"; + return NULL; + } + if ((numPats > 1) && (virtualFound != 0)) { + interp->result = "virtual events may not be composed"; + return NULL; + } + + patPtr = &pats[EVENT_BUFFER_SIZE-numPats]; + memset(&key, 0, sizeof(key)); + key.object = object; + key.type = patPtr->eventType; + key.detail = patPtr->detail; + hPtr = Tcl_CreateHashEntry(patternTablePtr, (char *) &key, &new); + sequenceSize = numPats*sizeof(Pattern); + if (!new) { + for (psPtr = (PatSeq *) Tcl_GetHashValue(hPtr); psPtr != NULL; + psPtr = psPtr->nextSeqPtr) { + if ((numPats == psPtr->numPats) + && ((flags & PAT_NEARBY) == (psPtr->flags & PAT_NEARBY)) + && (memcmp((char *) patPtr, (char *) psPtr->pats, + sequenceSize) == 0)) { + goto done; + } + } + } + if (!create) { + if (new) { + Tcl_DeleteHashEntry(hPtr); + } + return NULL; + } + psPtr = (PatSeq *) ckalloc((unsigned) (sizeof(PatSeq) + + (numPats-1)*sizeof(Pattern))); + psPtr->numPats = numPats; + psPtr->eventProc = NULL; + psPtr->freeProc = NULL; + psPtr->clientData = NULL; + psPtr->flags = flags; + psPtr->refCount = 0; + psPtr->nextSeqPtr = (PatSeq *) Tcl_GetHashValue(hPtr); + psPtr->hPtr = hPtr; + psPtr->voPtr = NULL; + psPtr->nextObjPtr = NULL; + Tcl_SetHashValue(hPtr, psPtr); + + memcpy((VOID *) psPtr->pats, (VOID *) patPtr, sequenceSize); + + done: + *maskPtr = eventMask; + return psPtr; +} + +/* + *--------------------------------------------------------------------------- + * + * ParseEventDescription -- + * + * Fill Pattern buffer with information about event from + * event string. + * + * Results: + * Leaves error message in interp and returns 0 if there was an + * error due to a badly formed event string. Returns 1 if proper + * event was specified, 2 if Double modifier was used in event + * string, or 3 if Triple was used. + * + * Side effects: + * On exit, eventStringPtr points to rest of event string (after the + * closing '>', so that this procedure can be called repeatedly to + * parse all the events in the entire sequence. + * + *--------------------------------------------------------------------------- + */ + +static int +ParseEventDescription(interp, eventStringPtr, patPtr, + eventMaskPtr) + Tcl_Interp *interp; /* For error messages. */ + char **eventStringPtr; /* On input, holds a pointer to start of + * event string. On exit, gets pointer to + * rest of string after parsed event. */ + Pattern *patPtr; /* Filled with the pattern parsed from the + * event string. */ + unsigned long *eventMaskPtr;/* Filled with event mask of matched event. */ + +{ + char *p; + unsigned long eventMask; + int count, eventFlags; +#define FIELD_SIZE 48 + char field[FIELD_SIZE]; + Tcl_HashEntry *hPtr; + + p = *eventStringPtr; + + patPtr->eventType = -1; + patPtr->needMods = 0; + patPtr->detail.clientData = 0; + + eventMask = 0; + count = 1; + + /* + * Handle simple ASCII characters. + */ + + if (*p != '<') { + char string[2]; + + patPtr->eventType = KeyPress; + eventMask = KeyPressMask; + string[0] = *p; + string[1] = 0; + patPtr->detail.keySym = TkStringToKeysym(string); + if (patPtr->detail.keySym == NoSymbol) { + if (isprint(UCHAR(*p))) { + patPtr->detail.keySym = *p; + } else { + sprintf(interp->result, + "bad ASCII character 0x%x", (unsigned char) *p); + return 0; + } + } + p++; + goto end; + } + + /* + * A fancier event description. This can be either a virtual event + * or a physical event. + * + * A virtual event description consists of: + * + * 1. double open angle brackets. + * 2. virtual event name. + * 3. double close angle brackets. + * + * A physical event description consists of: + * + * 1. open angle bracket. + * 2. any number of modifiers, each followed by spaces + * or dashes. + * 3. an optional event name. + * 4. an option button or keysym name. Either this or + * item 3 *must* be present; if both are present + * then they are separated by spaces or dashes. + * 5. a close angle bracket. + */ + + p++; + if (*p == '<') { + /* + * This is a virtual event: soak up all the characters up to + * the next '>'. + */ + + char *field = p + 1; + p = strchr(field, '>'); + if (p == field) { + interp->result = "virtual event \"<<>>\" is badly formed"; + return 0; + } + if ((p == NULL) || (p[1] != '>')) { + interp->result = "missing \">\" in virtual binding"; + return 0; + } + *p = '\0'; + patPtr->eventType = VirtualEvent; + eventMask = VirtualEventMask; + patPtr->detail.name = Tk_GetUid(field); + *p = '>'; + + p += 2; + goto end; + } + + while (1) { + ModInfo *modPtr; + p = GetField(p, field, FIELD_SIZE); + if (*p == '>') { + /* + * This solves the problem of, e.g., <Control-M> being + * misinterpreted as Control + Meta + missing keysym + * instead of Control + KeyPress + M. + */ + break; + } + hPtr = Tcl_FindHashEntry(&modTable, field); + if (hPtr == NULL) { + break; + } + modPtr = (ModInfo *) Tcl_GetHashValue(hPtr); + patPtr->needMods |= modPtr->mask; + if (modPtr->flags & (DOUBLE|TRIPLE)) { + if (modPtr->flags & DOUBLE) { + count = 2; + } else { + count = 3; + } + } + while ((*p == '-') || isspace(UCHAR(*p))) { + p++; + } + } + + eventFlags = 0; + hPtr = Tcl_FindHashEntry(&eventTable, field); + if (hPtr != NULL) { + EventInfo *eiPtr; + eiPtr = (EventInfo *) Tcl_GetHashValue(hPtr); + + patPtr->eventType = eiPtr->type; + eventFlags = flagArray[eiPtr->type]; + eventMask = eiPtr->eventMask; + while ((*p == '-') || isspace(UCHAR(*p))) { + p++; + } + p = GetField(p, field, FIELD_SIZE); + } + if (*field != '\0') { + if ((*field >= '1') && (*field <= '5') && (field[1] == '\0')) { + if (eventFlags == 0) { + patPtr->eventType = ButtonPress; + eventMask = ButtonPressMask; + } else if (eventFlags & KEY) { + goto getKeysym; + } else if ((eventFlags & BUTTON) == 0) { + Tcl_AppendResult(interp, "specified button \"", field, + "\" for non-button event", (char *) NULL); + return 0; + } + patPtr->detail.button = (*field - '0'); + } else { + getKeysym: + patPtr->detail.keySym = TkStringToKeysym(field); + if (patPtr->detail.keySym == NoSymbol) { + Tcl_AppendResult(interp, "bad event type or keysym \"", + field, "\"", (char *) NULL); + return 0; + } + if (eventFlags == 0) { + patPtr->eventType = KeyPress; + eventMask = KeyPressMask; + } else if ((eventFlags & KEY) == 0) { + Tcl_AppendResult(interp, "specified keysym \"", field, + "\" for non-key event", (char *) NULL); + return 0; + } + } + } else if (eventFlags == 0) { + interp->result = "no event type or button # or keysym"; + return 0; + } + + while ((*p == '-') || isspace(UCHAR(*p))) { + p++; + } + if (*p != '>') { + while (*p != '\0') { + p++; + if (*p == '>') { + interp->result = "extra characters after detail in binding"; + return 0; + } + } + interp->result = "missing \">\" in binding"; + return 0; + } + p++; + +end: + *eventStringPtr = p; + *eventMaskPtr |= eventMask; + return count; +} + +/* + *---------------------------------------------------------------------- + * + * GetField -- + * + * Used to parse pattern descriptions. Copies up to + * size characters from p to copy, stopping at end of + * string, space, "-", ">", or whenever size is + * exceeded. + * + * Results: + * The return value is a pointer to the character just + * after the last one copied (usually "-" or space or + * ">", but could be anything if size was exceeded). + * Also places NULL-terminated string (up to size + * character, including NULL), at copy. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static char * +GetField(p, copy, size) + char *p; /* Pointer to part of pattern. */ + char *copy; /* Place to copy field. */ + int size; /* Maximum number of characters to + * copy. */ +{ + while ((*p != '\0') && !isspace(UCHAR(*p)) && (*p != '>') + && (*p != '-') && (size > 1)) { + *copy = *p; + p++; + copy++; + size--; + } + *copy = '\0'; + return p; +} + +/* + *--------------------------------------------------------------------------- + * + * GetPatternString -- + * + * Produce a string version of the given event, for displaying to + * the user. + * + * Results: + * The string is left in dsPtr. + * + * Side effects: + * It is the caller's responsibility to initialize the DString before + * and to free it after calling this procedure. + * + *--------------------------------------------------------------------------- + */ +static void +GetPatternString(psPtr, dsPtr) + PatSeq *psPtr; + Tcl_DString *dsPtr; +{ + Pattern *patPtr; + char c, buffer[10]; + int patsLeft, needMods; + ModInfo *modPtr; + EventInfo *eiPtr; + + /* + * The order of the patterns in the sequence is backwards from the order + * in which they must be output. + */ + + for (patsLeft = psPtr->numPats, patPtr = &psPtr->pats[psPtr->numPats - 1]; + patsLeft > 0; patsLeft--, patPtr--) { + + /* + * Check for simple case of an ASCII character. + */ + + if ((patPtr->eventType == KeyPress) + && ((psPtr->flags & PAT_NEARBY) == 0) + && (patPtr->needMods == 0) + && (patPtr->detail.keySym < 128) + && isprint(UCHAR(patPtr->detail.keySym)) + && (patPtr->detail.keySym != '<') + && (patPtr->detail.keySym != ' ')) { + + c = (char) patPtr->detail.keySym; + Tcl_DStringAppend(dsPtr, &c, 1); + continue; + } + + /* + * Check for virtual event. + */ + + if (patPtr->eventType == VirtualEvent) { + Tcl_DStringAppend(dsPtr, "<<", 2); + Tcl_DStringAppend(dsPtr, patPtr->detail.name, -1); + Tcl_DStringAppend(dsPtr, ">>", 2); + continue; + } + + /* + * It's a more general event specification. First check + * for "Double" or "Triple", then modifiers, then event type, + * then keysym or button detail. + */ + + Tcl_DStringAppend(dsPtr, "<", 1); + if ((psPtr->flags & PAT_NEARBY) && (patsLeft > 1) + && (memcmp((char *) patPtr, (char *) (patPtr-1), + sizeof(Pattern)) == 0)) { + patsLeft--; + patPtr--; + if ((patsLeft > 1) && (memcmp((char *) patPtr, + (char *) (patPtr-1), sizeof(Pattern)) == 0)) { + patsLeft--; + patPtr--; + Tcl_DStringAppend(dsPtr, "Triple-", 7); + } else { + Tcl_DStringAppend(dsPtr, "Double-", 7); + } + } + for (needMods = patPtr->needMods, modPtr = modArray; + needMods != 0; modPtr++) { + if (modPtr->mask & needMods) { + needMods &= ~modPtr->mask; + Tcl_DStringAppend(dsPtr, modPtr->name, -1); + Tcl_DStringAppend(dsPtr, "-", 1); + } + } + for (eiPtr = eventArray; eiPtr->name != NULL; eiPtr++) { + if (eiPtr->type == patPtr->eventType) { + Tcl_DStringAppend(dsPtr, eiPtr->name, -1); + if (patPtr->detail.clientData != 0) { + Tcl_DStringAppend(dsPtr, "-", 1); + } + break; + } + } + + if (patPtr->detail.clientData != 0) { + if ((patPtr->eventType == KeyPress) + || (patPtr->eventType == KeyRelease)) { + char *string; + + string = TkKeysymToString(patPtr->detail.keySym); + if (string != NULL) { + Tcl_DStringAppend(dsPtr, string, -1); + } + } else { + sprintf(buffer, "%d", patPtr->detail.button); + Tcl_DStringAppend(dsPtr, buffer, -1); + } + } + Tcl_DStringAppend(dsPtr, ">", 1); + } +} + +/* + *---------------------------------------------------------------------- + * + * GetKeySym -- + * + * Given an X KeyPress or KeyRelease event, map the + * keycode in the event into a KeySym. + * + * Results: + * The return value is the KeySym corresponding to + * eventPtr, or NoSymbol if no matching Keysym could be + * found. + * + * Side effects: + * In the first call for a given display, keycode-to- + * KeySym maps get loaded. + * + *---------------------------------------------------------------------- + */ + +static KeySym +GetKeySym(dispPtr, eventPtr) + TkDisplay *dispPtr; /* Display in which to + * map keycode. */ + XEvent *eventPtr; /* Description of X event. */ +{ + KeySym sym; + int index; + + /* + * Refresh the mapping information if it's stale + */ + + if (dispPtr->bindInfoStale) { + InitKeymapInfo(dispPtr); + } + + /* + * Figure out which of the four slots in the keymap vector to + * use for this key. Refer to Xlib documentation for more info + * on how this computation works. + */ + + index = 0; + if (eventPtr->xkey.state & dispPtr->modeModMask) { + index = 2; + } + if ((eventPtr->xkey.state & ShiftMask) + || ((dispPtr->lockUsage != LU_IGNORE) + && (eventPtr->xkey.state & LockMask))) { + index += 1; + } + sym = XKeycodeToKeysym(dispPtr->display, eventPtr->xkey.keycode, index); + + /* + * Special handling: if the key was shifted because of Lock, but + * lock is only caps lock, not shift lock, and the shifted keysym + * isn't upper-case alphabetic, then switch back to the unshifted + * keysym. + */ + + if ((index & 1) && !(eventPtr->xkey.state & ShiftMask) + && (dispPtr->lockUsage == LU_CAPS)) { + if (!(((sym >= XK_A) && (sym <= XK_Z)) + || ((sym >= XK_Agrave) && (sym <= XK_Odiaeresis)) + || ((sym >= XK_Ooblique) && (sym <= XK_Thorn)))) { + index &= ~1; + sym = XKeycodeToKeysym(dispPtr->display, eventPtr->xkey.keycode, + index); + } + } + + /* + * Another bit of special handling: if this is a shifted key and there + * is no keysym defined, then use the keysym for the unshifted key. + */ + + if ((index & 1) && (sym == NoSymbol)) { + sym = XKeycodeToKeysym(dispPtr->display, eventPtr->xkey.keycode, + index & ~1); + } + return sym; +} + +/* + *-------------------------------------------------------------- + * + * InitKeymapInfo -- + * + * This procedure is invoked to scan keymap information + * to recompute stuff that's important for binding, such + * as the modifier key (if any) that corresponds to "mode + * switch". + * + * Results: + * None. + * + * Side effects: + * Keymap-related information in dispPtr is updated. + * + *-------------------------------------------------------------- + */ + +static void +InitKeymapInfo(dispPtr) + TkDisplay *dispPtr; /* Display for which to recompute keymap + * information. */ +{ + XModifierKeymap *modMapPtr; + KeyCode *codePtr; + KeySym keysym; + int count, i, j, max, arraySize; +#define KEYCODE_ARRAY_SIZE 20 + + dispPtr->bindInfoStale = 0; + modMapPtr = XGetModifierMapping(dispPtr->display); + + /* + * Check the keycodes associated with the Lock modifier. If + * any of them is associated with the XK_Shift_Lock modifier, + * then Lock has to be interpreted as Shift Lock, not Caps Lock. + */ + + dispPtr->lockUsage = LU_IGNORE; + codePtr = modMapPtr->modifiermap + modMapPtr->max_keypermod*LockMapIndex; + for (count = modMapPtr->max_keypermod; count > 0; count--, codePtr++) { + if (*codePtr == 0) { + continue; + } + keysym = XKeycodeToKeysym(dispPtr->display, *codePtr, 0); + if (keysym == XK_Shift_Lock) { + dispPtr->lockUsage = LU_SHIFT; + break; + } + if (keysym == XK_Caps_Lock) { + dispPtr->lockUsage = LU_CAPS; + break; + } + } + + /* + * Look through the keycodes associated with modifiers to see if + * the the "mode switch", "meta", or "alt" keysyms are associated + * with any modifiers. If so, remember their modifier mask bits. + */ + + dispPtr->modeModMask = 0; + dispPtr->metaModMask = 0; + dispPtr->altModMask = 0; + codePtr = modMapPtr->modifiermap; + max = 8*modMapPtr->max_keypermod; + for (i = 0; i < max; i++, codePtr++) { + if (*codePtr == 0) { + continue; + } + keysym = XKeycodeToKeysym(dispPtr->display, *codePtr, 0); + if (keysym == XK_Mode_switch) { + dispPtr->modeModMask |= ShiftMask << (i/modMapPtr->max_keypermod); + } + if ((keysym == XK_Meta_L) || (keysym == XK_Meta_R)) { + dispPtr->metaModMask |= ShiftMask << (i/modMapPtr->max_keypermod); + } + if ((keysym == XK_Alt_L) || (keysym == XK_Alt_R)) { + dispPtr->altModMask |= ShiftMask << (i/modMapPtr->max_keypermod); + } + } + + /* + * Create an array of the keycodes for all modifier keys. + */ + + if (dispPtr->modKeyCodes != NULL) { + ckfree((char *) dispPtr->modKeyCodes); + } + dispPtr->numModKeyCodes = 0; + arraySize = KEYCODE_ARRAY_SIZE; + dispPtr->modKeyCodes = (KeyCode *) ckalloc((unsigned) + (KEYCODE_ARRAY_SIZE * sizeof(KeyCode))); + for (i = 0, codePtr = modMapPtr->modifiermap; i < max; i++, codePtr++) { + if (*codePtr == 0) { + continue; + } + + /* + * Make sure that the keycode isn't already in the array. + */ + + for (j = 0; j < dispPtr->numModKeyCodes; j++) { + if (dispPtr->modKeyCodes[j] == *codePtr) { + goto nextModCode; + } + } + if (dispPtr->numModKeyCodes >= arraySize) { + KeyCode *new; + + /* + * Ran out of space in the array; grow it. + */ + + arraySize *= 2; + new = (KeyCode *) ckalloc((unsigned) + (arraySize * sizeof(KeyCode))); + memcpy((VOID *) new, (VOID *) dispPtr->modKeyCodes, + (dispPtr->numModKeyCodes * sizeof(KeyCode))); + ckfree((char *) dispPtr->modKeyCodes); + dispPtr->modKeyCodes = new; + } + dispPtr->modKeyCodes[dispPtr->numModKeyCodes] = *codePtr; + dispPtr->numModKeyCodes++; + nextModCode: continue; + } + XFreeModifiermap(modMapPtr); +} + +/* + *--------------------------------------------------------------------------- + * + * EvalTclBinding -- + * + * The procedure that is invoked by Tk_BindEvent when a Tcl binding + * is fired. + * + * Results: + * A standard Tcl result code, the result of globally evaluating the + * percent-substitued binding string. + * + * Side effects: + * Normal side effects due to eval. + * + *--------------------------------------------------------------------------- + */ + +static void +FreeTclBinding(clientData) + ClientData clientData; +{ + ckfree((char *) clientData); +} + +/* + *---------------------------------------------------------------------- + * + * TkStringToKeysym -- + * + * This procedure finds the keysym associated with a given keysym + * name. + * + * Results: + * The return value is the keysym that corresponds to name, or + * NoSymbol if there is no such keysym. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +KeySym +TkStringToKeysym(name) + char *name; /* Name of a keysym. */ +{ +#ifdef REDO_KEYSYM_LOOKUP + Tcl_HashEntry *hPtr; + KeySym keysym; + + hPtr = Tcl_FindHashEntry(&keySymTable, name); + if (hPtr != NULL) { + return (KeySym) Tcl_GetHashValue(hPtr); + } + if (strlen(name) == 1) { + keysym = (KeySym) (unsigned char) name[0]; + if (TkKeysymToString(keysym) != NULL) { + return keysym; + } + } +#endif /* REDO_KEYSYM_LOOKUP */ + return XStringToKeysym(name); +} + +/* + *---------------------------------------------------------------------- + * + * TkKeysymToString -- + * + * This procedure finds the keysym name associated with a given + * keysym. + * + * Results: + * The return value is a pointer to a static string containing + * the name of the given keysym, or NULL if there is no known name. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +char * +TkKeysymToString(keysym) + KeySym keysym; +{ +#ifdef REDO_KEYSYM_LOOKUP + Tcl_HashEntry *hPtr; + + hPtr = Tcl_FindHashEntry(&nameTable, (char *)keysym); + if (hPtr != NULL) { + return (char *) Tcl_GetHashValue(hPtr); + } +#endif /* REDO_KEYSYM_LOOKUP */ + return XKeysymToString(keysym); +} + +/* + *---------------------------------------------------------------------- + * + * TkCopyAndGlobalEval -- + * + * This procedure makes a copy of a script then calls Tcl_GlobalEval + * to evaluate it. It's used in situations where the execution of + * a command may cause the original command string to be reallocated. + * + * Results: + * Returns the result of evaluating script, including both a standard + * Tcl completion code and a string in interp->result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkCopyAndGlobalEval(interp, script) + Tcl_Interp *interp; /* Interpreter in which to evaluate + * script. */ + char *script; /* Script to evaluate. */ +{ + Tcl_DString buffer; + int code; + + Tcl_DStringInit(&buffer); + Tcl_DStringAppend(&buffer, script, -1); + code = Tcl_GlobalEval(interp, Tcl_DStringValue(&buffer)); + Tcl_DStringFree(&buffer); + return code; +} + + diff --git a/generic/tkBitmap.c b/generic/tkBitmap.c new file mode 100644 index 0000000..fe46b35 --- /dev/null +++ b/generic/tkBitmap.c @@ -0,0 +1,585 @@ +/* + * tkBitmap.c -- + * + * This file maintains a database of read-only bitmaps for the Tk + * toolkit. This allows bitmaps to be shared between widgets and + * also avoids interactions with the X server. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkBitmap.c 1.45 97/07/24 17:27:38 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * The includes below are for pre-defined bitmaps. + * + * Platform-specific issue: Windows complains when the bitmaps are + * included, because an array of characters is being initialized with + * integers as elements. For lint purposes, the following pragmas + * temporarily turn off that warning message. + */ + +#if defined(__WIN32__) || defined(_WIN32) +#pragma warning (disable : 4305) +#endif + +#include "error.bmp" +#include "gray12.bmp" +#include "gray25.bmp" +#include "gray50.bmp" +#include "gray75.bmp" +#include "hourglass.bmp" +#include "info.bmp" +#include "questhead.bmp" +#include "question.bmp" +#include "warning.bmp" + +#if defined(__WIN32__) || defined(_WIN32) +#pragma warning (default : 4305) +#endif + +/* + * One of the following data structures exists for each bitmap that is + * currently in use. Each structure is indexed with both "idTable" and + * "nameTable". + */ + +typedef struct { + Pixmap bitmap; /* X identifier for bitmap. None means this + * bitmap was created by Tk_DefineBitmap + * and it isn't currently in use. */ + int width, height; /* Dimensions of bitmap. */ + Display *display; /* Display for which bitmap is valid. */ + int refCount; /* Number of active uses of bitmap. */ + Tcl_HashEntry *hashPtr; /* Entry in nameTable for this structure + * (needed when deleting). */ +} TkBitmap; + +/* + * Hash table to map from a textual description of a bitmap to the + * TkBitmap record for the bitmap, and key structure used in that + * hash table: + */ + +static Tcl_HashTable nameTable; +typedef struct { + Tk_Uid name; /* Textual name for desired bitmap. */ + Screen *screen; /* Screen on which bitmap will be used. */ +} NameKey; + +/* + * Hash table that maps from <display + bitmap id> to the TkBitmap structure + * for the bitmap. This table is used by Tk_FreeBitmap. + */ + +static Tcl_HashTable idTable; +typedef struct { + Display *display; /* Display for which bitmap was allocated. */ + Pixmap pixmap; /* X identifier for pixmap. */ +} IdKey; + +/* + * Hash table create by Tk_DefineBitmap to map from a name to a + * collection of in-core data about a bitmap. The table is + * indexed by the address of the data for the bitmap, and the entries + * contain pointers to TkPredefBitmap structures. + */ + +Tcl_HashTable tkPredefBitmapTable; + +/* + * Hash table used by Tk_GetBitmapFromData to map from a collection + * of in-core data about a bitmap to a Tk_Uid giving an automatically- + * generated name for the bitmap: + */ + +static Tcl_HashTable dataTable; +typedef struct { + char *source; /* Bitmap bits. */ + int width, height; /* Dimensions of bitmap. */ +} DataKey; + +static int initialized = 0; /* 0 means static structures haven't been + * initialized yet. */ + +/* + * Forward declarations for procedures defined in this file: + */ + +static void BitmapInit _ANSI_ARGS_((void)); + +/* + *---------------------------------------------------------------------- + * + * Tk_GetBitmap -- + * + * Given a string describing a bitmap, locate (or create if necessary) + * a bitmap that fits the description. + * + * Results: + * The return value is the X identifer for the desired bitmap + * (i.e. a Pixmap with a single plane), unless string couldn't be + * parsed correctly. In this case, None is returned and an error + * message is left in interp->result. The caller should never + * modify the bitmap that is returned, and should eventually call + * Tk_FreeBitmap when the bitmap is no longer needed. + * + * Side effects: + * The bitmap is added to an internal database with a reference count. + * For each call to this procedure, there should eventually be a call + * to Tk_FreeBitmap, so that the database can be cleaned up when bitmaps + * aren't needed anymore. + * + *---------------------------------------------------------------------- + */ + +Pixmap +Tk_GetBitmap(interp, tkwin, string) + Tcl_Interp *interp; /* Interpreter to use for error reporting, + * this may be NULL. */ + Tk_Window tkwin; /* Window in which bitmap will be used. */ + Tk_Uid string; /* Description of bitmap. See manual entry + * for details on legal syntax. */ +{ + NameKey nameKey; + IdKey idKey; + Tcl_HashEntry *nameHashPtr, *idHashPtr, *predefHashPtr; + register TkBitmap *bitmapPtr; + TkPredefBitmap *predefPtr; + int new; + Pixmap bitmap; + int width, height; + int dummy2; + + if (!initialized) { + BitmapInit(); + } + + nameKey.name = string; + nameKey.screen = Tk_Screen(tkwin); + nameHashPtr = Tcl_CreateHashEntry(&nameTable, (char *) &nameKey, &new); + if (!new) { + bitmapPtr = (TkBitmap *) Tcl_GetHashValue(nameHashPtr); + bitmapPtr->refCount++; + return bitmapPtr->bitmap; + } + + /* + * No suitable bitmap exists. Create a new bitmap from the + * information contained in the string. If the string starts + * with "@" then the rest of the string is a file name containing + * the bitmap. Otherwise the string must refer to a bitmap + * defined by a call to Tk_DefineBitmap. + */ + + if (*string == '@') { + Tcl_DString buffer; + int result; + + if (Tcl_IsSafe(interp)) { + Tcl_AppendResult(interp, "can't specify bitmap with '@' in a", + " safe interpreter", (char *) NULL); + goto error; + } + + string = Tcl_TranslateFileName(interp, string + 1, &buffer); + if (string == NULL) { + goto error; + } + result = XReadBitmapFile(Tk_Display(tkwin), + RootWindowOfScreen(nameKey.screen), string, + (unsigned int *) &width, (unsigned int *) &height, + &bitmap, &dummy2, &dummy2); + if (result != BitmapSuccess) { + if (interp != NULL) { + Tcl_AppendResult(interp, "error reading bitmap file \"", string, + "\"", (char *) NULL); + } + Tcl_DStringFree(&buffer); + goto error; + } + Tcl_DStringFree(&buffer); + } else { + predefHashPtr = Tcl_FindHashEntry(&tkPredefBitmapTable, string); + if (predefHashPtr == NULL) { + /* + * The following platform specific call allows the user to + * define bitmaps that may only exist during run time. If + * it returns None nothing was found and we return the error. + */ + bitmap = TkpGetNativeAppBitmap(Tk_Display(tkwin), string, + &width, &height); + + if (bitmap == None) { + if (interp != NULL) { + Tcl_AppendResult(interp, "bitmap \"", string, + "\" not defined", (char *) NULL); + } + goto error; + } + } else { + predefPtr = (TkPredefBitmap *) Tcl_GetHashValue(predefHashPtr); + width = predefPtr->width; + height = predefPtr->height; + if (predefPtr->native) { + bitmap = TkpCreateNativeBitmap(Tk_Display(tkwin), + predefPtr->source); + if (bitmap == None) { + panic("native bitmap creation failed"); + } + } else { + bitmap = XCreateBitmapFromData(Tk_Display(tkwin), + RootWindowOfScreen(nameKey.screen), predefPtr->source, + (unsigned) width, (unsigned) height); + } + } + } + + /* + * Add information about this bitmap to our database. + */ + + bitmapPtr = (TkBitmap *) ckalloc(sizeof(TkBitmap)); + bitmapPtr->bitmap = bitmap; + bitmapPtr->width = width; + bitmapPtr->height = height; + bitmapPtr->display = Tk_Display(tkwin); + bitmapPtr->refCount = 1; + bitmapPtr->hashPtr = nameHashPtr; + idKey.display = bitmapPtr->display; + idKey.pixmap = bitmap; + idHashPtr = Tcl_CreateHashEntry(&idTable, (char *) &idKey, + &new); + if (!new) { + panic("bitmap already registered in Tk_GetBitmap"); + } + Tcl_SetHashValue(nameHashPtr, bitmapPtr); + Tcl_SetHashValue(idHashPtr, bitmapPtr); + return bitmapPtr->bitmap; + + error: + Tcl_DeleteHashEntry(nameHashPtr); + return None; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_DefineBitmap -- + * + * This procedure associates a textual name with a binary bitmap + * description, so that the name may be used to refer to the + * bitmap in future calls to Tk_GetBitmap. + * + * Results: + * A standard Tcl result. If an error occurs then TCL_ERROR is + * returned and a message is left in interp->result. + * + * Side effects: + * "Name" is entered into the bitmap table and may be used from + * here on to refer to the given bitmap. + * + *---------------------------------------------------------------------- + */ + +int +Tk_DefineBitmap(interp, name, source, width, height) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + Tk_Uid name; /* Name to use for bitmap. Must not already + * be defined as a bitmap. */ + char *source; /* Address of bits for bitmap. */ + int width; /* Width of bitmap. */ + int height; /* Height of bitmap. */ +{ + int new; + Tcl_HashEntry *predefHashPtr; + TkPredefBitmap *predefPtr; + + if (!initialized) { + BitmapInit(); + } + + predefHashPtr = Tcl_CreateHashEntry(&tkPredefBitmapTable, name, &new); + if (!new) { + Tcl_AppendResult(interp, "bitmap \"", name, + "\" is already defined", (char *) NULL); + return TCL_ERROR; + } + predefPtr = (TkPredefBitmap *) ckalloc(sizeof(TkPredefBitmap)); + predefPtr->source = source; + predefPtr->width = width; + predefPtr->height = height; + predefPtr->native = 0; + Tcl_SetHashValue(predefHashPtr, predefPtr); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * Tk_NameOfBitmap -- + * + * Given a bitmap, return a textual string identifying the + * bitmap. + * + * Results: + * The return value is the string name associated with bitmap. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +Tk_Uid +Tk_NameOfBitmap(display, bitmap) + Display *display; /* Display for which bitmap was + * allocated. */ + Pixmap bitmap; /* Bitmap whose name is wanted. */ +{ + IdKey idKey; + Tcl_HashEntry *idHashPtr; + TkBitmap *bitmapPtr; + + if (!initialized) { + unknown: + panic("Tk_NameOfBitmap received unknown bitmap argument"); + } + + idKey.display = display; + idKey.pixmap = bitmap; + idHashPtr = Tcl_FindHashEntry(&idTable, (char *) &idKey); + if (idHashPtr == NULL) { + goto unknown; + } + bitmapPtr = (TkBitmap *) Tcl_GetHashValue(idHashPtr); + return ((NameKey *) bitmapPtr->hashPtr->key.words)->name; +} + +/* + *-------------------------------------------------------------- + * + * Tk_SizeOfBitmap -- + * + * Given a bitmap managed by this module, returns the width + * and height of the bitmap. + * + * Results: + * The words at *widthPtr and *heightPtr are filled in with + * the dimenstions of bitmap. + * + * Side effects: + * If bitmap isn't managed by this module then the procedure + * panics.. + * + *-------------------------------------------------------------- + */ + +void +Tk_SizeOfBitmap(display, bitmap, widthPtr, heightPtr) + Display *display; /* Display for which bitmap was + * allocated. */ + Pixmap bitmap; /* Bitmap whose size is wanted. */ + int *widthPtr; /* Store bitmap width here. */ + int *heightPtr; /* Store bitmap height here. */ +{ + IdKey idKey; + Tcl_HashEntry *idHashPtr; + TkBitmap *bitmapPtr; + + if (!initialized) { + unknownBitmap: + panic("Tk_SizeOfBitmap received unknown bitmap argument"); + } + + idKey.display = display; + idKey.pixmap = bitmap; + idHashPtr = Tcl_FindHashEntry(&idTable, (char *) &idKey); + if (idHashPtr == NULL) { + goto unknownBitmap; + } + bitmapPtr = (TkBitmap *) Tcl_GetHashValue(idHashPtr); + *widthPtr = bitmapPtr->width; + *heightPtr = bitmapPtr->height; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreeBitmap -- + * + * This procedure is called to release a bitmap allocated by + * Tk_GetBitmap or TkGetBitmapFromData. + * + * Results: + * None. + * + * Side effects: + * The reference count associated with bitmap is decremented, and + * it is officially deallocated if no-one is using it anymore. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreeBitmap(display, bitmap) + Display *display; /* Display for which bitmap was + * allocated. */ + Pixmap bitmap; /* Bitmap to be released. */ +{ + Tcl_HashEntry *idHashPtr; + register TkBitmap *bitmapPtr; + IdKey idKey; + + if (!initialized) { + panic("Tk_FreeBitmap called before Tk_GetBitmap"); + } + + idKey.display = display; + idKey.pixmap = bitmap; + idHashPtr = Tcl_FindHashEntry(&idTable, (char *) &idKey); + if (idHashPtr == NULL) { + panic("Tk_FreeBitmap received unknown bitmap argument"); + } + bitmapPtr = (TkBitmap *) Tcl_GetHashValue(idHashPtr); + bitmapPtr->refCount--; + if (bitmapPtr->refCount == 0) { + Tk_FreePixmap(bitmapPtr->display, bitmapPtr->bitmap); + Tcl_DeleteHashEntry(idHashPtr); + Tcl_DeleteHashEntry(bitmapPtr->hashPtr); + ckfree((char *) bitmapPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetBitmapFromData -- + * + * Given a description of the bits for a bitmap, make a bitmap that + * has the given properties. *** NOTE: this procedure is obsolete + * and really shouldn't be used anymore. *** + * + * Results: + * The return value is the X identifer for the desired bitmap + * (a one-plane Pixmap), unless it couldn't be created properly. + * In this case, None is returned and an error message is left in + * interp->result. The caller should never modify the bitmap that + * is returned, and should eventually call Tk_FreeBitmap when the + * bitmap is no longer needed. + * + * Side effects: + * The bitmap is added to an internal database with a reference count. + * For each call to this procedure, there should eventually be a call + * to Tk_FreeBitmap, so that the database can be cleaned up when bitmaps + * aren't needed anymore. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +Pixmap +Tk_GetBitmapFromData(interp, tkwin, source, width, height) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + Tk_Window tkwin; /* Window in which bitmap will be used. */ + char *source; /* Bitmap data for bitmap shape. */ + int width, height; /* Dimensions of bitmap. */ +{ + DataKey nameKey; + Tcl_HashEntry *dataHashPtr; + Tk_Uid name; + int new; + char string[20]; + static int autoNumber = 0; + + if (!initialized) { + BitmapInit(); + } + + nameKey.source = source; + nameKey.width = width; + nameKey.height = height; + dataHashPtr = Tcl_CreateHashEntry(&dataTable, (char *) &nameKey, &new); + if (!new) { + name = (Tk_Uid) Tcl_GetHashValue(dataHashPtr); + } else { + autoNumber++; + sprintf(string, "_tk%d", autoNumber); + name = Tk_GetUid(string); + Tcl_SetHashValue(dataHashPtr, name); + if (Tk_DefineBitmap(interp, name, source, width, height) != TCL_OK) { + Tcl_DeleteHashEntry(dataHashPtr); + return TCL_ERROR; + } + } + return Tk_GetBitmap(interp, tkwin, name); +} + +/* + *---------------------------------------------------------------------- + * + * BitmapInit -- + * + * Initialize the structures used for bitmap management. + * + * Results: + * None. + * + * Side effects: + * Read the code. + * + *---------------------------------------------------------------------- + */ + +static void +BitmapInit() +{ + Tcl_Interp *dummy; + + dummy = Tcl_CreateInterp(); + initialized = 1; + Tcl_InitHashTable(&nameTable, sizeof(NameKey)/sizeof(int)); + Tcl_InitHashTable(&dataTable, sizeof(DataKey)/sizeof(int)); + Tcl_InitHashTable(&tkPredefBitmapTable, TCL_ONE_WORD_KEYS); + + /* + * The call below is tricky: can't use sizeof(IdKey) because it + * gets padded with extra unpredictable bytes on some 64-bit + * machines. + */ + + Tcl_InitHashTable(&idTable, (sizeof(Display *) + sizeof(Pixmap)) + /sizeof(int)); + + Tk_DefineBitmap(dummy, Tk_GetUid("error"), (char *) error_bits, + error_width, error_height); + Tk_DefineBitmap(dummy, Tk_GetUid("gray75"), (char *) gray75_bits, + gray75_width, gray75_height); + Tk_DefineBitmap(dummy, Tk_GetUid("gray50"), (char *) gray50_bits, + gray50_width, gray50_height); + Tk_DefineBitmap(dummy, Tk_GetUid("gray25"), (char *) gray25_bits, + gray25_width, gray25_height); + Tk_DefineBitmap(dummy, Tk_GetUid("gray12"), (char *) gray12_bits, + gray12_width, gray12_height); + Tk_DefineBitmap(dummy, Tk_GetUid("hourglass"), (char *) hourglass_bits, + hourglass_width, hourglass_height); + Tk_DefineBitmap(dummy, Tk_GetUid("info"), (char *) info_bits, + info_width, info_height); + Tk_DefineBitmap(dummy, Tk_GetUid("questhead"), (char *) questhead_bits, + questhead_width, questhead_height); + Tk_DefineBitmap(dummy, Tk_GetUid("question"), (char *) question_bits, + question_width, question_height); + Tk_DefineBitmap(dummy, Tk_GetUid("warning"), (char *) warning_bits, + warning_width, warning_height); + + TkpDefineNativeBitmaps(); + + Tcl_DeleteInterp(dummy); +} diff --git a/generic/tkButton.c b/generic/tkButton.c new file mode 100644 index 0000000..c9c25c2 --- /dev/null +++ b/generic/tkButton.c @@ -0,0 +1,1347 @@ +/* + * tkButton.c -- + * + * This module implements a collection of button-like + * widgets for the Tk toolkit. The widgets implemented + * include labels, buttons, check buttons, and radio + * buttons. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkButton.c 1.144 97/07/31 09:04:57 + */ + +#include "tkButton.h" +#include "default.h" + +/* + * Class names for buttons, indexed by one of the type values above. + */ + +static char *classNames[] = {"Label", "Button", "Checkbutton", "Radiobutton"}; + +/* + * The class procedure table for the button widget. + */ + +static int configFlags[] = {LABEL_MASK, BUTTON_MASK, + CHECK_BUTTON_MASK, RADIO_BUTTON_MASK}; + +/* + * Information used for parsing configuration specs: + */ + +Tk_ConfigSpec tkpButtonConfigSpecs[] = { + {TK_CONFIG_BORDER, "-activebackground", "activeBackground", "Foreground", + DEF_BUTTON_ACTIVE_BG_COLOR, Tk_Offset(TkButton, activeBorder), + BUTTON_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK + |TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-activebackground", "activeBackground", "Foreground", + DEF_BUTTON_ACTIVE_BG_MONO, Tk_Offset(TkButton, activeBorder), + BUTTON_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK + |TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_COLOR, "-activeforeground", "activeForeground", "Background", + DEF_BUTTON_ACTIVE_FG_COLOR, Tk_Offset(TkButton, activeFg), + BUTTON_MASK|TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-activeforeground", "activeForeground", "Background", + DEF_CHKRAD_ACTIVE_FG_COLOR, Tk_Offset(TkButton, activeFg), + CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-activeforeground", "activeForeground", "Background", + DEF_BUTTON_ACTIVE_FG_MONO, Tk_Offset(TkButton, activeFg), + BUTTON_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK + |TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_ANCHOR, "-anchor", "anchor", "Anchor", + DEF_BUTTON_ANCHOR, Tk_Offset(TkButton, anchor), ALL_MASK}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_BUTTON_BG_COLOR, Tk_Offset(TkButton, normalBorder), + ALL_MASK | TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_BUTTON_BG_MONO, Tk_Offset(TkButton, normalBorder), + ALL_MASK | TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, ALL_MASK}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, ALL_MASK}, + {TK_CONFIG_BITMAP, "-bitmap", "bitmap", "Bitmap", + DEF_BUTTON_BITMAP, Tk_Offset(TkButton, bitmap), + ALL_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_BUTTON_BORDER_WIDTH, Tk_Offset(TkButton, borderWidth), ALL_MASK}, + {TK_CONFIG_STRING, "-command", "command", "Command", + DEF_BUTTON_COMMAND, Tk_Offset(TkButton, command), + BUTTON_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_BUTTON_CURSOR, Tk_Offset(TkButton, cursor), + ALL_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_UID, "-default", "default", "Default", + DEF_BUTTON_DEFAULT, Tk_Offset(TkButton, defaultState), BUTTON_MASK}, + {TK_CONFIG_COLOR, "-disabledforeground", "disabledForeground", + "DisabledForeground", DEF_BUTTON_DISABLED_FG_COLOR, + Tk_Offset(TkButton, disabledFg), BUTTON_MASK|CHECK_BUTTON_MASK + |RADIO_BUTTON_MASK|TK_CONFIG_COLOR_ONLY|TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-disabledforeground", "disabledForeground", + "DisabledForeground", DEF_BUTTON_DISABLED_FG_MONO, + Tk_Offset(TkButton, disabledFg), BUTTON_MASK|CHECK_BUTTON_MASK + |RADIO_BUTTON_MASK|TK_CONFIG_MONO_ONLY|TK_CONFIG_NULL_OK}, + {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, + (char *) NULL, 0, ALL_MASK}, + {TK_CONFIG_FONT, "-font", "font", "Font", + DEF_BUTTON_FONT, Tk_Offset(TkButton, tkfont), + ALL_MASK}, + {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground", + DEF_BUTTON_FG, Tk_Offset(TkButton, normalFg), LABEL_MASK|BUTTON_MASK}, + {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground", + DEF_CHKRAD_FG, Tk_Offset(TkButton, normalFg), CHECK_BUTTON_MASK + |RADIO_BUTTON_MASK}, + {TK_CONFIG_STRING, "-height", "height", "Height", + DEF_BUTTON_HEIGHT, Tk_Offset(TkButton, heightString), ALL_MASK}, + {TK_CONFIG_BORDER, "-highlightbackground", "highlightBackground", + "HighlightBackground", DEF_BUTTON_HIGHLIGHT_BG, + Tk_Offset(TkButton, highlightBorder), ALL_MASK}, + {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor", + DEF_BUTTON_HIGHLIGHT, Tk_Offset(TkButton, highlightColorPtr), + ALL_MASK}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", + DEF_LABEL_HIGHLIGHT_WIDTH, Tk_Offset(TkButton, highlightWidth), + LABEL_MASK}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", + DEF_BUTTON_HIGHLIGHT_WIDTH, Tk_Offset(TkButton, highlightWidth), + BUTTON_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK}, + {TK_CONFIG_STRING, "-image", "image", "Image", + DEF_BUTTON_IMAGE, Tk_Offset(TkButton, imageString), + ALL_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-indicatoron", "indicatorOn", "IndicatorOn", + DEF_BUTTON_INDICATOR, Tk_Offset(TkButton, indicatorOn), + CHECK_BUTTON_MASK|RADIO_BUTTON_MASK}, + {TK_CONFIG_JUSTIFY, "-justify", "justify", "Justify", + DEF_BUTTON_JUSTIFY, Tk_Offset(TkButton, justify), ALL_MASK}, + {TK_CONFIG_STRING, "-offvalue", "offValue", "Value", + DEF_BUTTON_OFF_VALUE, Tk_Offset(TkButton, offValue), + CHECK_BUTTON_MASK}, + {TK_CONFIG_STRING, "-onvalue", "onValue", "Value", + DEF_BUTTON_ON_VALUE, Tk_Offset(TkButton, onValue), + CHECK_BUTTON_MASK}, + {TK_CONFIG_PIXELS, "-padx", "padX", "Pad", + DEF_BUTTON_PADX, Tk_Offset(TkButton, padX), BUTTON_MASK}, + {TK_CONFIG_PIXELS, "-padx", "padX", "Pad", + DEF_LABCHKRAD_PADX, Tk_Offset(TkButton, padX), + LABEL_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK}, + {TK_CONFIG_PIXELS, "-pady", "padY", "Pad", + DEF_BUTTON_PADY, Tk_Offset(TkButton, padY), BUTTON_MASK}, + {TK_CONFIG_PIXELS, "-pady", "padY", "Pad", + DEF_LABCHKRAD_PADY, Tk_Offset(TkButton, padY), + LABEL_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_BUTTON_RELIEF, Tk_Offset(TkButton, relief), BUTTON_MASK}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_LABCHKRAD_RELIEF, Tk_Offset(TkButton, relief), + LABEL_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK}, + {TK_CONFIG_BORDER, "-selectcolor", "selectColor", "Background", + DEF_BUTTON_SELECT_COLOR, Tk_Offset(TkButton, selectBorder), + CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|TK_CONFIG_COLOR_ONLY + |TK_CONFIG_NULL_OK}, + {TK_CONFIG_BORDER, "-selectcolor", "selectColor", "Background", + DEF_BUTTON_SELECT_MONO, Tk_Offset(TkButton, selectBorder), + CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|TK_CONFIG_MONO_ONLY + |TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-selectimage", "selectImage", "SelectImage", + DEF_BUTTON_SELECT_IMAGE, Tk_Offset(TkButton, selectImageString), + CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_UID, "-state", "state", "State", + DEF_BUTTON_STATE, Tk_Offset(TkButton, state), + BUTTON_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_LABEL_TAKE_FOCUS, Tk_Offset(TkButton, takeFocus), + LABEL_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_BUTTON_TAKE_FOCUS, Tk_Offset(TkButton, takeFocus), + BUTTON_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-text", "text", "Text", + DEF_BUTTON_TEXT, Tk_Offset(TkButton, text), ALL_MASK}, + {TK_CONFIG_STRING, "-textvariable", "textVariable", "Variable", + DEF_BUTTON_TEXT_VARIABLE, Tk_Offset(TkButton, textVarName), + ALL_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_INT, "-underline", "underline", "Underline", + DEF_BUTTON_UNDERLINE, Tk_Offset(TkButton, underline), ALL_MASK}, + {TK_CONFIG_STRING, "-value", "value", "Value", + DEF_BUTTON_VALUE, Tk_Offset(TkButton, onValue), + RADIO_BUTTON_MASK}, + {TK_CONFIG_STRING, "-variable", "variable", "Variable", + DEF_RADIOBUTTON_VARIABLE, Tk_Offset(TkButton, selVarName), + RADIO_BUTTON_MASK}, + {TK_CONFIG_STRING, "-variable", "variable", "Variable", + DEF_CHECKBUTTON_VARIABLE, Tk_Offset(TkButton, selVarName), + CHECK_BUTTON_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-width", "width", "Width", + DEF_BUTTON_WIDTH, Tk_Offset(TkButton, widthString), ALL_MASK}, + {TK_CONFIG_PIXELS, "-wraplength", "wrapLength", "WrapLength", + DEF_BUTTON_WRAP_LENGTH, Tk_Offset(TkButton, wrapLength), ALL_MASK}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * String to print out in error messages, identifying options for + * widget commands for different types of labels or buttons: + */ + +static char *optionStrings[] = { + "cget or configure", + "cget, configure, flash, or invoke", + "cget, configure, deselect, flash, invoke, select, or toggle", + "cget, configure, deselect, flash, invoke, or select" +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void ButtonCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static int ButtonCreate _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv, + int type)); +static void ButtonEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void ButtonImageProc _ANSI_ARGS_((ClientData clientData, + int x, int y, int width, int height, + int imgWidth, int imgHeight)); +static void ButtonSelectImageProc _ANSI_ARGS_(( + ClientData clientData, int x, int y, int width, + int height, int imgWidth, int imgHeight)); +static char * ButtonTextVarProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, char *name1, char *name2, + int flags)); +static char * ButtonVarProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, char *name1, char *name2, + int flags)); +static int ButtonWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static int ConfigureButton _ANSI_ARGS_((Tcl_Interp *interp, + TkButton *butPtr, int argc, char **argv, + int flags)); +static void DestroyButton _ANSI_ARGS_((TkButton *butPtr)); + + +/* + *-------------------------------------------------------------- + * + * Tk_ButtonCmd, Tk_CheckbuttonCmd, Tk_LabelCmd, Tk_RadiobuttonCmd -- + * + * These procedures are invoked to process the "button", "label", + * "radiobutton", and "checkbutton" Tcl commands. See the + * user documentation for details on what they do. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. These procedures are just wrappers; + * they call ButtonCreate to do all of the real work. + * + *-------------------------------------------------------------- + */ + +int +Tk_ButtonCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + return ButtonCreate(clientData, interp, argc, argv, TYPE_BUTTON); +} + +int +Tk_CheckbuttonCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + return ButtonCreate(clientData, interp, argc, argv, TYPE_CHECK_BUTTON); +} + +int +Tk_LabelCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + return ButtonCreate(clientData, interp, argc, argv, TYPE_LABEL); +} + +int +Tk_RadiobuttonCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + return ButtonCreate(clientData, interp, argc, argv, TYPE_RADIO_BUTTON); +} + +/* + *-------------------------------------------------------------- + * + * ButtonCreate -- + * + * This procedure does all the real work of implementing the + * "button", "label", "radiobutton", and "checkbutton" Tcl + * commands. See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +ButtonCreate(clientData, interp, argc, argv, type) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ + int type; /* Type of button to create: TYPE_LABEL, + * TYPE_BUTTON, TYPE_CHECK_BUTTON, or + * TYPE_RADIO_BUTTON. */ +{ + register TkButton *butPtr; + Tk_Window tkwin = (Tk_Window) clientData; + Tk_Window new; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + /* + * Create the new window. + */ + + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *) NULL); + if (new == NULL) { + return TCL_ERROR; + } + + Tk_SetClass(new, classNames[type]); + butPtr = TkpCreateButton(new); + + TkSetClassProcs(new, &tkpButtonProcs, (ClientData) butPtr); + + /* + * Initialize the data structure for the button. + */ + + butPtr->tkwin = new; + butPtr->display = Tk_Display(new); + butPtr->widgetCmd = Tcl_CreateCommand(interp, Tk_PathName(butPtr->tkwin), + ButtonWidgetCmd, (ClientData) butPtr, ButtonCmdDeletedProc); + butPtr->interp = interp; + butPtr->type = type; + butPtr->text = NULL; + butPtr->underline = -1; + butPtr->textVarName = NULL; + butPtr->bitmap = None; + butPtr->imageString = NULL; + butPtr->image = NULL; + butPtr->selectImageString = NULL; + butPtr->selectImage = NULL; + butPtr->state = tkNormalUid; + butPtr->normalBorder = NULL; + butPtr->activeBorder = NULL; + butPtr->borderWidth = 0; + butPtr->relief = TK_RELIEF_FLAT; + butPtr->highlightWidth = 0; + butPtr->highlightBorder = NULL; + butPtr->highlightColorPtr = NULL; + butPtr->inset = 0; + butPtr->tkfont = NULL; + butPtr->normalFg = NULL; + butPtr->activeFg = NULL; + butPtr->disabledFg = NULL; + butPtr->normalTextGC = None; + butPtr->activeTextGC = None; + butPtr->gray = None; + butPtr->disabledGC = None; + butPtr->copyGC = None; + butPtr->widthString = NULL; + butPtr->heightString = NULL; + butPtr->width = 0; + butPtr->height = 0; + butPtr->wrapLength = 0; + butPtr->padX = 0; + butPtr->padY = 0; + butPtr->anchor = TK_ANCHOR_CENTER; + butPtr->justify = TK_JUSTIFY_CENTER; + butPtr->textLayout = NULL; + butPtr->indicatorOn = 0; + butPtr->selectBorder = NULL; + butPtr->indicatorSpace = 0; + butPtr->indicatorDiameter = 0; + butPtr->defaultState = tkDisabledUid; + butPtr->selVarName = NULL; + butPtr->onValue = NULL; + butPtr->offValue = NULL; + butPtr->cursor = None; + butPtr->command = NULL; + butPtr->takeFocus = NULL; + butPtr->flags = 0; + + Tk_CreateEventHandler(butPtr->tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + ButtonEventProc, (ClientData) butPtr); + + if (ConfigureButton(interp, butPtr, argc - 2, argv + 2, + configFlags[type]) != TCL_OK) { + Tk_DestroyWindow(butPtr->tkwin); + return TCL_ERROR; + } + + interp->result = Tk_PathName(butPtr->tkwin); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ButtonWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a widget managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +ButtonWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about button widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register TkButton *butPtr = (TkButton *) clientData; + int result = TCL_OK; + size_t length; + int c; + + if (argc < 2) { + sprintf(interp->result, + "wrong # args: should be \"%.50s option ?arg arg ...?\"", + argv[0]); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) butPtr); + c = argv[1][0]; + length = strlen(argv[1]); + + if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + goto error; + } + result = Tk_ConfigureValue(interp, butPtr->tkwin, tkpButtonConfigSpecs, + (char *) butPtr, argv[2], configFlags[butPtr->type]); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 2)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, butPtr->tkwin, + tkpButtonConfigSpecs, (char *) butPtr, (char *) NULL, + configFlags[butPtr->type]); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, butPtr->tkwin, + tkpButtonConfigSpecs, (char *) butPtr, argv[2], + configFlags[butPtr->type]); + } else { + result = ConfigureButton(interp, butPtr, argc-2, argv+2, + configFlags[butPtr->type] | TK_CONFIG_ARGV_ONLY); + } + } else if ((c == 'd') && (strncmp(argv[1], "deselect", length) == 0) + && (butPtr->type >= TYPE_CHECK_BUTTON)) { + if (argc > 2) { + sprintf(interp->result, + "wrong # args: should be \"%.50s deselect\"", + argv[0]); + goto error; + } + if (butPtr->type == TYPE_CHECK_BUTTON) { + if (Tcl_SetVar(interp, butPtr->selVarName, butPtr->offValue, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + result = TCL_ERROR; + } + } else if (butPtr->flags & SELECTED) { + if (Tcl_SetVar(interp, butPtr->selVarName, "", + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + result = TCL_ERROR; + }; + } + } else if ((c == 'f') && (strncmp(argv[1], "flash", length) == 0) + && (butPtr->type != TYPE_LABEL)) { + int i; + + if (argc > 2) { + sprintf(interp->result, + "wrong # args: should be \"%.50s flash\"", + argv[0]); + goto error; + } + if (butPtr->state != tkDisabledUid) { + for (i = 0; i < 4; i++) { + butPtr->state = (butPtr->state == tkNormalUid) + ? tkActiveUid : tkNormalUid; + Tk_SetBackgroundFromBorder(butPtr->tkwin, + (butPtr->state == tkActiveUid) ? butPtr->activeBorder + : butPtr->normalBorder); + TkpDisplayButton((ClientData) butPtr); + + /* + * Special note: must cancel any existing idle handler + * for TkpDisplayButton; it's no longer needed, and TkpDisplayButton + * cleared the REDRAW_PENDING flag. + */ + + Tcl_CancelIdleCall(TkpDisplayButton, (ClientData) butPtr); + XFlush(butPtr->display); + Tcl_Sleep(50); + } + } + } else if ((c == 'i') && (strncmp(argv[1], "invoke", length) == 0) + && (butPtr->type > TYPE_LABEL)) { + if (argc > 2) { + sprintf(interp->result, + "wrong # args: should be \"%.50s invoke\"", + argv[0]); + goto error; + } + if (butPtr->state != tkDisabledUid) { + result = TkInvokeButton(butPtr); + } + } else if ((c == 's') && (strncmp(argv[1], "select", length) == 0) + && (butPtr->type >= TYPE_CHECK_BUTTON)) { + if (argc > 2) { + sprintf(interp->result, + "wrong # args: should be \"%.50s select\"", + argv[0]); + goto error; + } + if (Tcl_SetVar(interp, butPtr->selVarName, butPtr->onValue, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + result = TCL_ERROR; + } + } else if ((c == 't') && (strncmp(argv[1], "toggle", length) == 0) + && (length >= 2) && (butPtr->type == TYPE_CHECK_BUTTON)) { + if (argc > 2) { + sprintf(interp->result, + "wrong # args: should be \"%.50s toggle\"", + argv[0]); + goto error; + } + if (butPtr->flags & SELECTED) { + if (Tcl_SetVar(interp, butPtr->selVarName, butPtr->offValue, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + result = TCL_ERROR; + } + } else { + if (Tcl_SetVar(interp, butPtr->selVarName, butPtr->onValue, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + result = TCL_ERROR; + } + } + } else { + sprintf(interp->result, + "bad option \"%.50s\": must be %s", argv[1], + optionStrings[butPtr->type]); + goto error; + } + Tcl_Release((ClientData) butPtr); + return result; + + error: + Tcl_Release((ClientData) butPtr); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyButton -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a button at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the widget is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyButton(butPtr) + TkButton *butPtr; /* Info about button widget. */ +{ + /* + * Free up all the stuff that requires special handling, then + * let Tk_FreeOptions handle all the standard option-related + * stuff. + */ + + if (butPtr->textVarName != NULL) { + Tcl_UntraceVar(butPtr->interp, butPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ButtonTextVarProc, (ClientData) butPtr); + } + if (butPtr->image != NULL) { + Tk_FreeImage(butPtr->image); + } + if (butPtr->selectImage != NULL) { + Tk_FreeImage(butPtr->selectImage); + } + if (butPtr->normalTextGC != None) { + Tk_FreeGC(butPtr->display, butPtr->normalTextGC); + } + if (butPtr->activeTextGC != None) { + Tk_FreeGC(butPtr->display, butPtr->activeTextGC); + } + if (butPtr->gray != None) { + Tk_FreeBitmap(butPtr->display, butPtr->gray); + } + if (butPtr->disabledGC != None) { + Tk_FreeGC(butPtr->display, butPtr->disabledGC); + } + if (butPtr->copyGC != None) { + Tk_FreeGC(butPtr->display, butPtr->copyGC); + } + if (butPtr->selVarName != NULL) { + Tcl_UntraceVar(butPtr->interp, butPtr->selVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ButtonVarProc, (ClientData) butPtr); + } + Tk_FreeTextLayout(butPtr->textLayout); + Tk_FreeOptions(tkpButtonConfigSpecs, (char *) butPtr, butPtr->display, + configFlags[butPtr->type]); + Tcl_EventuallyFree((ClientData)butPtr, TCL_DYNAMIC); +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureButton -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or + * reconfigure) a button widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as text string, colors, font, + * etc. get set for butPtr; old resources get freed, if there + * were any. The button is redisplayed. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureButton(interp, butPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + register TkButton *butPtr; /* Information about widget; may or may + * not already have values for some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + Tk_Image image; + + /* + * Eliminate any existing trace on variables monitored by the button. + */ + + if (butPtr->textVarName != NULL) { + Tcl_UntraceVar(interp, butPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ButtonTextVarProc, (ClientData) butPtr); + } + if (butPtr->selVarName != NULL) { + Tcl_UntraceVar(interp, butPtr->selVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ButtonVarProc, (ClientData) butPtr); + } + + + + if (Tk_ConfigureWidget(interp, butPtr->tkwin, tkpButtonConfigSpecs, + argc, argv, (char *) butPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few options need special processing, such as setting the + * background from a 3-D border, or filling in complicated + * defaults that couldn't be specified to Tk_ConfigureWidget. + */ + + if ((butPtr->state == tkActiveUid) && !Tk_StrictMotif(butPtr->tkwin)) { + Tk_SetBackgroundFromBorder(butPtr->tkwin, butPtr->activeBorder); + } else { + Tk_SetBackgroundFromBorder(butPtr->tkwin, butPtr->normalBorder); + if ((butPtr->state != tkNormalUid) && (butPtr->state != tkActiveUid) + && (butPtr->state != tkDisabledUid)) { + Tcl_AppendResult(interp, "bad state value \"", butPtr->state, + "\": must be normal, active, or disabled", (char *) NULL); + butPtr->state = tkNormalUid; + return TCL_ERROR; + } + } + + if ((butPtr->defaultState != tkActiveUid) + && (butPtr->defaultState != tkDisabledUid) + && (butPtr->defaultState != tkNormalUid)) { + Tcl_AppendResult(interp, "bad -default value \"", butPtr->defaultState, + "\": must be normal, active, or disabled", (char *) NULL); + butPtr->defaultState = tkDisabledUid; + return TCL_ERROR; + } + + if (butPtr->highlightWidth < 0) { + butPtr->highlightWidth = 0; + } + + if (butPtr->padX < 0) { + butPtr->padX = 0; + } + if (butPtr->padY < 0) { + butPtr->padY = 0; + } + + if (butPtr->type >= TYPE_CHECK_BUTTON) { + char *value; + + if (butPtr->selVarName == NULL) { + butPtr->selVarName = (char *) ckalloc((unsigned) + (strlen(Tk_Name(butPtr->tkwin)) + 1)); + strcpy(butPtr->selVarName, Tk_Name(butPtr->tkwin)); + } + + /* + * Select the button if the associated variable has the + * appropriate value, initialize the variable if it doesn't + * exist, then set a trace on the variable to monitor future + * changes to its value. + */ + + value = Tcl_GetVar(interp, butPtr->selVarName, TCL_GLOBAL_ONLY); + butPtr->flags &= ~SELECTED; + if (value != NULL) { + if (strcmp(value, butPtr->onValue) == 0) { + butPtr->flags |= SELECTED; + } + } else { + if (Tcl_SetVar(interp, butPtr->selVarName, + (butPtr->type == TYPE_CHECK_BUTTON) ? butPtr->offValue : "", + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + return TCL_ERROR; + } + } + Tcl_TraceVar(interp, butPtr->selVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ButtonVarProc, (ClientData) butPtr); + } + + /* + * Get the images for the widget, if there are any. Allocate the + * new images before freeing the old ones, so that the reference + * counts don't go to zero and cause image data to be discarded. + */ + + if (butPtr->imageString != NULL) { + image = Tk_GetImage(butPtr->interp, butPtr->tkwin, + butPtr->imageString, ButtonImageProc, (ClientData) butPtr); + if (image == NULL) { + return TCL_ERROR; + } + } else { + image = NULL; + } + if (butPtr->image != NULL) { + Tk_FreeImage(butPtr->image); + } + butPtr->image = image; + if (butPtr->selectImageString != NULL) { + image = Tk_GetImage(butPtr->interp, butPtr->tkwin, + butPtr->selectImageString, ButtonSelectImageProc, + (ClientData) butPtr); + if (image == NULL) { + return TCL_ERROR; + } + } else { + image = NULL; + } + if (butPtr->selectImage != NULL) { + Tk_FreeImage(butPtr->selectImage); + } + butPtr->selectImage = image; + + if ((butPtr->image == NULL) && (butPtr->bitmap == None) + && (butPtr->textVarName != NULL)) { + /* + * The button must display the value of a variable: set up a trace + * on the variable's value, create the variable if it doesn't + * exist, and fetch its current value. + */ + + char *value; + + value = Tcl_GetVar(interp, butPtr->textVarName, TCL_GLOBAL_ONLY); + if (value == NULL) { + if (Tcl_SetVar(interp, butPtr->textVarName, butPtr->text, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + return TCL_ERROR; + } + } else { + if (butPtr->text != NULL) { + ckfree(butPtr->text); + } + butPtr->text = (char *) ckalloc((unsigned) (strlen(value) + 1)); + strcpy(butPtr->text, value); + } + Tcl_TraceVar(interp, butPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ButtonTextVarProc, (ClientData) butPtr); + } + + if ((butPtr->bitmap != None) || (butPtr->image != NULL)) { + if (Tk_GetPixels(interp, butPtr->tkwin, butPtr->widthString, + &butPtr->width) != TCL_OK) { + widthError: + Tcl_AddErrorInfo(interp, "\n (processing -width option)"); + return TCL_ERROR; + } + if (Tk_GetPixels(interp, butPtr->tkwin, butPtr->heightString, + &butPtr->height) != TCL_OK) { + heightError: + Tcl_AddErrorInfo(interp, "\n (processing -height option)"); + return TCL_ERROR; + } + } else { + if (Tcl_GetInt(interp, butPtr->widthString, &butPtr->width) + != TCL_OK) { + goto widthError; + } + if (Tcl_GetInt(interp, butPtr->heightString, &butPtr->height) + != TCL_OK) { + goto heightError; + } + } + + TkButtonWorldChanged((ClientData) butPtr); + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * TkButtonWorldChanged -- + * + * This procedure is called when the world has changed in some + * way and the widget needs to recompute all its graphics contexts + * and determine its new geometry. + * + * Results: + * None. + * + * Side effects: + * Button will be relayed out and redisplayed. + * + *--------------------------------------------------------------------------- + */ + +void +TkButtonWorldChanged(instanceData) + ClientData instanceData; /* Information about widget. */ +{ + XGCValues gcValues; + GC newGC; + unsigned long mask; + TkButton *butPtr; + + butPtr = (TkButton *) instanceData; + + /* + * Recompute GCs. + */ + + gcValues.font = Tk_FontId(butPtr->tkfont); + gcValues.foreground = butPtr->normalFg->pixel; + gcValues.background = Tk_3DBorderColor(butPtr->normalBorder)->pixel; + + /* + * Note: GraphicsExpose events are disabled in normalTextGC because it's + * used to copy stuff from an off-screen pixmap onto the screen (we know + * that there's no problem with obscured areas). + */ + + gcValues.graphics_exposures = False; + mask = GCForeground | GCBackground | GCFont | GCGraphicsExposures; + newGC = Tk_GetGC(butPtr->tkwin, mask, &gcValues); + if (butPtr->normalTextGC != None) { + Tk_FreeGC(butPtr->display, butPtr->normalTextGC); + } + butPtr->normalTextGC = newGC; + + if (butPtr->activeFg != NULL) { + gcValues.font = Tk_FontId(butPtr->tkfont); + gcValues.foreground = butPtr->activeFg->pixel; + gcValues.background = Tk_3DBorderColor(butPtr->activeBorder)->pixel; + mask = GCForeground | GCBackground | GCFont; + newGC = Tk_GetGC(butPtr->tkwin, mask, &gcValues); + if (butPtr->activeTextGC != None) { + Tk_FreeGC(butPtr->display, butPtr->activeTextGC); + } + butPtr->activeTextGC = newGC; + } + + if (butPtr->type != TYPE_LABEL) { + gcValues.font = Tk_FontId(butPtr->tkfont); + gcValues.background = Tk_3DBorderColor(butPtr->normalBorder)->pixel; + if ((butPtr->disabledFg != NULL) && (butPtr->imageString == NULL)) { + gcValues.foreground = butPtr->disabledFg->pixel; + mask = GCForeground | GCBackground | GCFont; + } else { + gcValues.foreground = gcValues.background; + mask = GCForeground; + if (butPtr->gray == None) { + butPtr->gray = Tk_GetBitmap(NULL, butPtr->tkwin, + Tk_GetUid("gray50")); + } + if (butPtr->gray != None) { + gcValues.fill_style = FillStippled; + gcValues.stipple = butPtr->gray; + mask |= GCFillStyle | GCStipple; + } + } + newGC = Tk_GetGC(butPtr->tkwin, mask, &gcValues); + if (butPtr->disabledGC != None) { + Tk_FreeGC(butPtr->display, butPtr->disabledGC); + } + butPtr->disabledGC = newGC; + } + + if (butPtr->copyGC == None) { + butPtr->copyGC = Tk_GetGC(butPtr->tkwin, 0, &gcValues); + } + + TkpComputeButtonGeometry(butPtr); + + /* + * Lastly, arrange for the button to be redisplayed. + */ + + if (Tk_IsMapped(butPtr->tkwin) && !(butPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(TkpDisplayButton, (ClientData) butPtr); + butPtr->flags |= REDRAW_PENDING; + } +} + +/* + *-------------------------------------------------------------- + * + * ButtonEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on buttons. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +ButtonEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + TkButton *butPtr = (TkButton *) clientData; + if ((eventPtr->type == Expose) && (eventPtr->xexpose.count == 0)) { + goto redraw; + } else if (eventPtr->type == ConfigureNotify) { + /* + * Must redraw after size changes, since layout could have changed + * and borders will need to be redrawn. + */ + + goto redraw; + } else if (eventPtr->type == DestroyNotify) { + TkpDestroyButton(butPtr); + if (butPtr->tkwin != NULL) { + butPtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(butPtr->interp, butPtr->widgetCmd); + } + if (butPtr->flags & REDRAW_PENDING) { + Tcl_CancelIdleCall(TkpDisplayButton, (ClientData) butPtr); + } + DestroyButton(butPtr); + } else if (eventPtr->type == FocusIn) { + if (eventPtr->xfocus.detail != NotifyInferior) { + butPtr->flags |= GOT_FOCUS; + if (butPtr->highlightWidth > 0) { + goto redraw; + } + } + } else if (eventPtr->type == FocusOut) { + if (eventPtr->xfocus.detail != NotifyInferior) { + butPtr->flags &= ~GOT_FOCUS; + if (butPtr->highlightWidth > 0) { + goto redraw; + } + } + } + return; + + redraw: + if ((butPtr->tkwin != NULL) && !(butPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(TkpDisplayButton, (ClientData) butPtr); + butPtr->flags |= REDRAW_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * ButtonCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +ButtonCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + TkButton *butPtr = (TkButton *) clientData; + Tk_Window tkwin = butPtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + butPtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkInvokeButton -- + * + * This procedure is called to carry out the actions associated + * with a button, such as invoking a Tcl command or setting a + * variable. This procedure is invoked, for example, when the + * button is invoked via the mouse. + * + * Results: + * A standard Tcl return value. Information is also left in + * interp->result. + * + * Side effects: + * Depends on the button and its associated command. + * + *---------------------------------------------------------------------- + */ + +int +TkInvokeButton(butPtr) + register TkButton *butPtr; /* Information about button. */ +{ + if (butPtr->type == TYPE_CHECK_BUTTON) { + if (butPtr->flags & SELECTED) { + if (Tcl_SetVar(butPtr->interp, butPtr->selVarName, butPtr->offValue, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + return TCL_ERROR; + } + } else { + if (Tcl_SetVar(butPtr->interp, butPtr->selVarName, butPtr->onValue, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + return TCL_ERROR; + } + } + } else if (butPtr->type == TYPE_RADIO_BUTTON) { + if (Tcl_SetVar(butPtr->interp, butPtr->selVarName, butPtr->onValue, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + return TCL_ERROR; + } + } + if ((butPtr->type != TYPE_LABEL) && (butPtr->command != NULL)) { + return TkCopyAndGlobalEval(butPtr->interp, butPtr->command); + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ButtonVarProc -- + * + * This procedure is invoked when someone changes the + * state variable associated with a radio button. Depending + * on the new value of the button's variable, the button + * may be selected or deselected. + * + * Results: + * NULL is always returned. + * + * Side effects: + * The button may become selected or deselected. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static char * +ButtonVarProc(clientData, interp, name1, name2, flags) + ClientData clientData; /* Information about button. */ + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *name1; /* Name of variable. */ + char *name2; /* Second part of variable name. */ + int flags; /* Information about what happened. */ +{ + register TkButton *butPtr = (TkButton *) clientData; + char *value; + + /* + * If the variable is being unset, then just re-establish the + * trace unless the whole interpreter is going away. + */ + + if (flags & TCL_TRACE_UNSETS) { + butPtr->flags &= ~SELECTED; + if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + Tcl_TraceVar(interp, butPtr->selVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ButtonVarProc, clientData); + } + goto redisplay; + } + + /* + * Use the value of the variable to update the selected status of + * the button. + */ + + value = Tcl_GetVar(interp, butPtr->selVarName, TCL_GLOBAL_ONLY); + if (value == NULL) { + value = ""; + } + if (strcmp(value, butPtr->onValue) == 0) { + if (butPtr->flags & SELECTED) { + return (char *) NULL; + } + butPtr->flags |= SELECTED; + } else if (butPtr->flags & SELECTED) { + butPtr->flags &= ~SELECTED; + } else { + return (char *) NULL; + } + + redisplay: + if ((butPtr->tkwin != NULL) && Tk_IsMapped(butPtr->tkwin) + && !(butPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(TkpDisplayButton, (ClientData) butPtr); + butPtr->flags |= REDRAW_PENDING; + } + return (char *) NULL; +} + +/* + *-------------------------------------------------------------- + * + * ButtonTextVarProc -- + * + * This procedure is invoked when someone changes the variable + * whose contents are to be displayed in a button. + * + * Results: + * NULL is always returned. + * + * Side effects: + * The text displayed in the button will change to match the + * variable. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static char * +ButtonTextVarProc(clientData, interp, name1, name2, flags) + ClientData clientData; /* Information about button. */ + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *name1; /* Not used. */ + char *name2; /* Not used. */ + int flags; /* Information about what happened. */ +{ + register TkButton *butPtr = (TkButton *) clientData; + char *value; + + /* + * If the variable is unset, then immediately recreate it unless + * the whole interpreter is going away. + */ + + if (flags & TCL_TRACE_UNSETS) { + if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + Tcl_SetVar(interp, butPtr->textVarName, butPtr->text, + TCL_GLOBAL_ONLY); + Tcl_TraceVar(interp, butPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ButtonTextVarProc, clientData); + } + return (char *) NULL; + } + + value = Tcl_GetVar(interp, butPtr->textVarName, TCL_GLOBAL_ONLY); + if (value == NULL) { + value = ""; + } + if (butPtr->text != NULL) { + ckfree(butPtr->text); + } + butPtr->text = (char *) ckalloc((unsigned) (strlen(value) + 1)); + strcpy(butPtr->text, value); + TkpComputeButtonGeometry(butPtr); + + if ((butPtr->tkwin != NULL) && Tk_IsMapped(butPtr->tkwin) + && !(butPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(TkpDisplayButton, (ClientData) butPtr); + butPtr->flags |= REDRAW_PENDING; + } + return (char *) NULL; +} + +/* + *---------------------------------------------------------------------- + * + * ButtonImageProc -- + * + * This procedure is invoked by the image code whenever the manager + * for an image does something that affects the size of contents + * of an image displayed in a button. + * + * Results: + * None. + * + * Side effects: + * Arranges for the button to get redisplayed. + * + *---------------------------------------------------------------------- + */ + +static void +ButtonImageProc(clientData, x, y, width, height, imgWidth, imgHeight) + ClientData clientData; /* Pointer to widget record. */ + int x, y; /* Upper left pixel (within image) + * that must be redisplayed. */ + int width, height; /* Dimensions of area to redisplay + * (may be <= 0). */ + int imgWidth, imgHeight; /* New dimensions of image. */ +{ + register TkButton *butPtr = (TkButton *) clientData; + + if (butPtr->tkwin != NULL) { + TkpComputeButtonGeometry(butPtr); + if (Tk_IsMapped(butPtr->tkwin) && !(butPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(TkpDisplayButton, (ClientData) butPtr); + butPtr->flags |= REDRAW_PENDING; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * ButtonSelectImageProc -- + * + * This procedure is invoked by the image code whenever the manager + * for an image does something that affects the size of contents + * of the image displayed in a button when it is selected. + * + * Results: + * None. + * + * Side effects: + * May arrange for the button to get redisplayed. + * + *---------------------------------------------------------------------- + */ + +static void +ButtonSelectImageProc(clientData, x, y, width, height, imgWidth, imgHeight) + ClientData clientData; /* Pointer to widget record. */ + int x, y; /* Upper left pixel (within image) + * that must be redisplayed. */ + int width, height; /* Dimensions of area to redisplay + * (may be <= 0). */ + int imgWidth, imgHeight; /* New dimensions of image. */ +{ + register TkButton *butPtr = (TkButton *) clientData; + + /* + * Don't recompute geometry: it's controlled by the primary image. + */ + + if ((butPtr->flags & SELECTED) && (butPtr->tkwin != NULL) + && Tk_IsMapped(butPtr->tkwin) + && !(butPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(TkpDisplayButton, (ClientData) butPtr); + butPtr->flags |= REDRAW_PENDING; + } +} diff --git a/generic/tkButton.h b/generic/tkButton.h new file mode 100644 index 0000000..0d5b928 --- /dev/null +++ b/generic/tkButton.h @@ -0,0 +1,241 @@ +/* + * tkButton.h -- + * + * Declarations of types and functions used to implement + * button-like widgets. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkButton.h 1.5 97/06/06 11:19:24 + */ + +#ifndef _TKBUTTON +#define _TKBUTTON + +#ifndef _TKINT +#include "tkInt.h" +#endif + +/* + * A data structure of the following type is kept for each + * widget managed by this file: + */ + +typedef struct { + Tk_Window tkwin; /* Window that embodies the button. NULL + * means that the window has been destroyed. */ + Display *display; /* Display containing widget. Needed to + * free up resources after tkwin is gone. */ + Tcl_Interp *interp; /* Interpreter associated with button. */ + Tcl_Command widgetCmd; /* Token for button's widget command. */ + int type; /* Type of widget: restricts operations + * that may be performed on widget. See + * below for possible values. */ + + /* + * Information about what's in the button. + */ + + char *text; /* Text to display in button (malloc'ed) + * or NULL. */ + int underline; /* Index of character to underline. < 0 means + * don't underline anything. */ + char *textVarName; /* Name of variable (malloc'ed) or NULL. + * If non-NULL, button displays the contents + * of this variable. */ + Pixmap bitmap; /* Bitmap to display or None. If not None + * then text and textVar are ignored. */ + char *imageString; /* Name of image to display (malloc'ed), or + * NULL. If non-NULL, bitmap, text, and + * textVarName are ignored. */ + Tk_Image image; /* Image to display in window, or NULL if + * none. */ + char *selectImageString; /* Name of image to display when selected + * (malloc'ed), or NULL. */ + Tk_Image selectImage; /* Image to display in window when selected, + * or NULL if none. Ignored if image is + * NULL. */ + + /* + * Information used when displaying widget: + */ + + Tk_Uid state; /* State of button for display purposes: + * normal, active, or disabled. */ + Tk_3DBorder normalBorder; /* Structure used to draw 3-D + * border and background when window + * isn't active. NULL means no such + * border exists. */ + Tk_3DBorder activeBorder; /* Structure used to draw 3-D + * border and background when window + * is active. NULL means no such + * border exists. */ + int borderWidth; /* Width of border. */ + int relief; /* 3-d effect: TK_RELIEF_RAISED, etc. */ + int highlightWidth; /* Width in pixels of highlight to draw + * around widget when it has the focus. + * <= 0 means don't draw a highlight. */ + Tk_3DBorder highlightBorder; + /* Structure used to draw 3-D default ring + * and focus highlight area when highlight + * is off. */ + XColor *highlightColorPtr; /* Color for drawing traversal highlight. */ + + int inset; /* Total width of all borders, including + * traversal highlight and 3-D border. + * Indicates how much interior stuff must + * be offset from outside edges to leave + * room for borders. */ + Tk_Font tkfont; /* Information about text font, or NULL. */ + XColor *normalFg; /* Foreground color in normal mode. */ + XColor *activeFg; /* Foreground color in active mode. NULL + * means use normalFg instead. */ + XColor *disabledFg; /* Foreground color when disabled. NULL + * means use normalFg with a 50% stipple + * instead. */ + GC normalTextGC; /* GC for drawing text in normal mode. Also + * used to copy from off-screen pixmap onto + * screen. */ + GC activeTextGC; /* GC for drawing text in active mode (NULL + * means use normalTextGC). */ + Pixmap gray; /* Pixmap for displaying disabled text if + * disabledFg is NULL. */ + GC disabledGC; /* Used to produce disabled effect. If + * disabledFg isn't NULL, this GC is used to + * draw button text or icon. Otherwise + * text or icon is drawn with normalGC and + * this GC is used to stipple background + * across it. For labels this is None. */ + GC copyGC; /* Used for copying information from an + * off-screen pixmap to the screen. */ + char *widthString; /* Value of -width option. Malloc'ed. */ + char *heightString; /* Value of -height option. Malloc'ed. */ + int width, height; /* If > 0, these specify dimensions to request + * for window, in characters for text and in + * pixels for bitmaps. In this case the actual + * size of the text string or bitmap is + * ignored in computing desired window size. */ + int wrapLength; /* Line length (in pixels) at which to wrap + * onto next line. <= 0 means don't wrap + * except at newlines. */ + int padX, padY; /* Extra space around text (pixels to leave + * on each side). Ignored for bitmaps and + * images. */ + Tk_Anchor anchor; /* Where text/bitmap should be displayed + * inside button region. */ + Tk_Justify justify; /* Justification to use for multi-line text. */ + int indicatorOn; /* True means draw indicator, false means + * don't draw it. */ + Tk_3DBorder selectBorder; /* For drawing indicator background, or perhaps + * widget background, when selected. */ + int textWidth; /* Width needed to display text as requested, + * in pixels. */ + int textHeight; /* Height needed to display text as requested, + * in pixels. */ + Tk_TextLayout textLayout; /* Saved text layout information. */ + int indicatorSpace; /* Horizontal space (in pixels) allocated for + * display of indicator. */ + int indicatorDiameter; /* Diameter of indicator, in pixels. */ + Tk_Uid defaultState; /* State of default ring: normal, active, or + * disabled. */ + + /* + * For check and radio buttons, the fields below are used + * to manage the variable indicating the button's state. + */ + + char *selVarName; /* Name of variable used to control selected + * state of button. Malloc'ed (if + * not NULL). */ + char *onValue; /* Value to store in variable when + * this button is selected. Malloc'ed (if + * not NULL). */ + char *offValue; /* Value to store in variable when this + * button isn't selected. Malloc'ed + * (if not NULL). Valid only for check + * buttons. */ + + /* + * Miscellaneous information: + */ + + Tk_Cursor cursor; /* Current cursor for window, or None. */ + char *takeFocus; /* Value of -takefocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + char *command; /* Command to execute when button is + * invoked; valid for buttons only. + * If not NULL, it's malloc-ed. */ + int flags; /* Various flags; see below for + * definitions. */ +} TkButton; + +/* + * Possible "type" values for buttons. These are the kinds of + * widgets supported by this file. The ordering of the type + * numbers is significant: greater means more features and is + * used in the code. + */ + +#define TYPE_LABEL 0 +#define TYPE_BUTTON 1 +#define TYPE_CHECK_BUTTON 2 +#define TYPE_RADIO_BUTTON 3 + +/* + * Flag bits for buttons: + * + * REDRAW_PENDING: Non-zero means a DoWhenIdle handler + * has already been queued to redraw + * this window. + * SELECTED: Non-zero means this button is selected, + * so special highlight should be drawn. + * GOT_FOCUS: Non-zero means this button currently + * has the input focus. + */ + +#define REDRAW_PENDING 1 +#define SELECTED 2 +#define GOT_FOCUS 4 + +/* + * Mask values used to selectively enable entries in the + * configuration specs: + */ + +#define LABEL_MASK TK_CONFIG_USER_BIT +#define BUTTON_MASK TK_CONFIG_USER_BIT << 1 +#define CHECK_BUTTON_MASK TK_CONFIG_USER_BIT << 2 +#define RADIO_BUTTON_MASK TK_CONFIG_USER_BIT << 3 +#define ALL_MASK (LABEL_MASK | BUTTON_MASK \ + | CHECK_BUTTON_MASK | RADIO_BUTTON_MASK) + +/* + * Declaration of variables shared between the files in the button module. + */ + +extern TkClassProcs tkpButtonProcs; +extern Tk_ConfigSpec tkpButtonConfigSpecs[]; + +/* + * Declaration of procedures used in the implementation of the button + * widget. + */ + +EXTERN void TkButtonWorldChanged _ANSI_ARGS_(( + ClientData instanceData)); +EXTERN void TkpComputeButtonGeometry _ANSI_ARGS_(( + TkButton *butPtr)); +EXTERN TkButton * TkpCreateButton _ANSI_ARGS_((Tk_Window tkwin)); +#ifndef TkpDestroyButton +EXTERN void TkpDestroyButton _ANSI_ARGS_((TkButton *butPtr)); +#endif +#ifndef TkpDisplayButton +EXTERN void TkpDisplayButton _ANSI_ARGS_((ClientData clientData)); +#endif +EXTERN int TkInvokeButton _ANSI_ARGS_((TkButton *butPtr)); + +#endif /* _TKBUTTON */ diff --git a/generic/tkCanvArc.c b/generic/tkCanvArc.c new file mode 100644 index 0000000..26b62e7 --- /dev/null +++ b/generic/tkCanvArc.c @@ -0,0 +1,1716 @@ +/* + * tkCanvArc.c -- + * + * This file implements arc items for canvas widgets. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvArc.c 1.34 97/04/25 16:50:56 + */ + +#include <stdio.h> +#include "tkPort.h" +#include "tkInt.h" + +/* + * The structure below defines the record for each arc item. + */ + +typedef struct ArcItem { + Tk_Item header; /* Generic stuff that's the same for all + * types. MUST BE FIRST IN STRUCTURE. */ + double bbox[4]; /* Coordinates (x1, y1, x2, y2) of bounding + * box for oval of which arc is a piece. */ + double start; /* Angle at which arc begins, in degrees + * between 0 and 360. */ + double extent; /* Extent of arc (angular distance from + * start to end of arc) in degrees between + * -360 and 360. */ + double *outlinePtr; /* Points to (x,y) coordinates for points + * that define one or two closed polygons + * representing the portion of the outline + * that isn't part of the arc (the V-shape + * for a pie slice or a line-like segment + * for a chord). Malloc'ed. */ + int numOutlinePoints; /* Number of points at outlinePtr. Zero + * means no space allocated. */ + int width; /* Width of outline (in pixels). */ + XColor *outlineColor; /* Color for outline. NULL means don't + * draw outline. */ + XColor *fillColor; /* Color for filling arc (used for drawing + * outline too when style is "arc"). NULL + * means don't fill arc. */ + Pixmap fillStipple; /* Stipple bitmap for filling item. */ + Pixmap outlineStipple; /* Stipple bitmap for outline. */ + Tk_Uid style; /* How to draw arc: arc, chord, or pieslice. */ + GC outlineGC; /* Graphics context for outline. */ + GC fillGC; /* Graphics context for filling item. */ + double center1[2]; /* Coordinates of center of arc outline at + * start (see ComputeArcOutline). */ + double center2[2]; /* Coordinates of center of arc outline at + * start+extent (see ComputeArcOutline). */ +} ArcItem; + +/* + * The definitions below define the sizes of the polygons used to + * display outline information for various styles of arcs: + */ + +#define CHORD_OUTLINE_PTS 7 +#define PIE_OUTLINE1_PTS 6 +#define PIE_OUTLINE2_PTS 7 + +/* + * Information used for parsing configuration specs: + */ + +static Tk_CustomOption tagsOption = {Tk_CanvasTagsParseProc, + Tk_CanvasTagsPrintProc, (ClientData) NULL +}; + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_DOUBLE, "-extent", (char *) NULL, (char *) NULL, + "90", Tk_Offset(ArcItem, extent), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_COLOR, "-fill", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(ArcItem, fillColor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-outline", (char *) NULL, (char *) NULL, + "black", Tk_Offset(ArcItem, outlineColor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_BITMAP, "-outlinestipple", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(ArcItem, outlineStipple), TK_CONFIG_NULL_OK}, + {TK_CONFIG_DOUBLE, "-start", (char *) NULL, (char *) NULL, + "0", Tk_Offset(ArcItem, start), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_BITMAP, "-stipple", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(ArcItem, fillStipple), TK_CONFIG_NULL_OK}, + {TK_CONFIG_UID, "-style", (char *) NULL, (char *) NULL, + "pieslice", Tk_Offset(ArcItem, style), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_CUSTOM, "-tags", (char *) NULL, (char *) NULL, + (char *) NULL, 0, TK_CONFIG_NULL_OK, &tagsOption}, + {TK_CONFIG_PIXELS, "-width", (char *) NULL, (char *) NULL, + "1", Tk_Offset(ArcItem, width), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Prototypes for procedures defined in this file: + */ + +static void ComputeArcBbox _ANSI_ARGS_((Tk_Canvas canvas, + ArcItem *arcPtr)); +static int ConfigureArc _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv, int flags)); +static int CreateArc _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, struct Tk_Item *itemPtr, + int argc, char **argv)); +static void DeleteArc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display)); +static void DisplayArc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display, Drawable dst, + int x, int y, int width, int height)); +static int ArcCoords _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv)); +static int ArcToArea _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *rectPtr)); +static double ArcToPoint _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *coordPtr)); +static int ArcToPostscript _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int prepass)); +static void ScaleArc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double originX, double originY, + double scaleX, double scaleY)); +static void TranslateArc _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double deltaX, double deltaY)); +static int AngleInRange _ANSI_ARGS_((double x, double y, + double start, double extent)); +static void ComputeArcOutline _ANSI_ARGS_((ArcItem *arcPtr)); +static int HorizLineToArc _ANSI_ARGS_((double x1, double x2, + double y, double rx, double ry, + double start, double extent)); +static int VertLineToArc _ANSI_ARGS_((double x, double y1, + double y2, double rx, double ry, + double start, double extent)); + +/* + * The structures below defines the arc item types by means of procedures + * that can be invoked by generic item code. + */ + +Tk_ItemType tkArcType = { + "arc", /* name */ + sizeof(ArcItem), /* itemSize */ + CreateArc, /* createProc */ + configSpecs, /* configSpecs */ + ConfigureArc, /* configureProc */ + ArcCoords, /* coordProc */ + DeleteArc, /* deleteProc */ + DisplayArc, /* displayProc */ + 0, /* alwaysRedraw */ + ArcToPoint, /* pointProc */ + ArcToArea, /* areaProc */ + ArcToPostscript, /* postscriptProc */ + ScaleArc, /* scaleProc */ + TranslateArc, /* translateProc */ + (Tk_ItemIndexProc *) NULL, /* indexProc */ + (Tk_ItemCursorProc *) NULL, /* icursorProc */ + (Tk_ItemSelectionProc *) NULL, /* selectionProc */ + (Tk_ItemInsertProc *) NULL, /* insertProc */ + (Tk_ItemDCharsProc *) NULL, /* dTextProc */ + (Tk_ItemType *) NULL /* nextPtr */ +}; + +#ifndef PI +# define PI 3.14159265358979323846 +#endif + +/* + * The uid's below comprise the legal values for the "-style" + * option for arcs. + */ + +static Tk_Uid arcUid = NULL; +static Tk_Uid chordUid = NULL; +static Tk_Uid pieSliceUid = NULL; + +/* + *-------------------------------------------------------------- + * + * CreateArc -- + * + * This procedure is invoked to create a new arc item in + * a canvas. + * + * Results: + * A standard Tcl return value. If an error occurred in + * creating the item, then an error message is left in + * interp->result; in this case itemPtr is + * left uninitialized, so it can be safely freed by the + * caller. + * + * Side effects: + * A new arc item is created. + * + *-------------------------------------------------------------- + */ + +static int +CreateArc(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Canvas to hold new item. */ + Tk_Item *itemPtr; /* Record to hold new item; header + * has been initialized by caller. */ + int argc; /* Number of arguments in argv. */ + char **argv; /* Arguments describing arc. */ +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tk_PathName(Tk_CanvasTkwin(canvas)), " create ", + itemPtr->typePtr->name, " x1 y1 x2 y2 ?options?\"", + (char *) NULL); + return TCL_ERROR; + } + + /* + * Carry out once-only initialization. + */ + + if (arcUid == NULL) { + arcUid = Tk_GetUid("arc"); + chordUid = Tk_GetUid("chord"); + pieSliceUid = Tk_GetUid("pieslice"); + } + + /* + * Carry out initialization that is needed in order to clean + * up after errors during the the remainder of this procedure. + */ + + arcPtr->start = 0; + arcPtr->extent = 90; + arcPtr->outlinePtr = NULL; + arcPtr->numOutlinePoints = 0; + arcPtr->width = 1; + arcPtr->outlineColor = NULL; + arcPtr->fillColor = NULL; + arcPtr->fillStipple = None; + arcPtr->outlineStipple = None; + arcPtr->style = pieSliceUid; + arcPtr->outlineGC = None; + arcPtr->fillGC = None; + + /* + * Process the arguments to fill in the item record. + */ + + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], &arcPtr->bbox[0]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], + &arcPtr->bbox[1]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[2], + &arcPtr->bbox[2]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[3], + &arcPtr->bbox[3]) != TCL_OK)) { + return TCL_ERROR; + } + + if (ConfigureArc(interp, canvas, itemPtr, argc-4, argv+4, 0) != TCL_OK) { + DeleteArc(canvas, itemPtr, Tk_Display(Tk_CanvasTkwin(canvas))); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ArcCoords -- + * + * This procedure is invoked to process the "coords" widget + * command on arcs. See the user documentation for details + * on what it does. + * + * Results: + * Returns TCL_OK or TCL_ERROR, and sets interp->result. + * + * Side effects: + * The coordinates for the given item may be changed. + * + *-------------------------------------------------------------- + */ + +static int +ArcCoords(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item whose coordinates are to be + * read or modified. */ + int argc; /* Number of coordinates supplied in + * argv. */ + char **argv; /* Array of coordinates: x1, y1, + * x2, y2, ... */ +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + char c0[TCL_DOUBLE_SPACE], c1[TCL_DOUBLE_SPACE]; + char c2[TCL_DOUBLE_SPACE], c3[TCL_DOUBLE_SPACE]; + + if (argc == 0) { + Tcl_PrintDouble(interp, arcPtr->bbox[0], c0); + Tcl_PrintDouble(interp, arcPtr->bbox[1], c1); + Tcl_PrintDouble(interp, arcPtr->bbox[2], c2); + Tcl_PrintDouble(interp, arcPtr->bbox[3], c3); + Tcl_AppendResult(interp, c0, " ", c1, " ", c2, " ", c3, + (char *) NULL); + } else if (argc == 4) { + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], + &arcPtr->bbox[0]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], + &arcPtr->bbox[1]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[2], + &arcPtr->bbox[2]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[3], + &arcPtr->bbox[3]) != TCL_OK)) { + return TCL_ERROR; + } + ComputeArcBbox(canvas, arcPtr); + } else { + sprintf(interp->result, + "wrong # coordinates: expected 0 or 4, got %d", + argc); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ConfigureArc -- + * + * This procedure is invoked to configure various aspects + * of a arc item, such as its outline and fill colors. + * + * Results: + * A standard Tcl result code. If an error occurs, then + * an error message is left in interp->result. + * + * Side effects: + * Configuration information, such as colors and stipple + * patterns, may be set for itemPtr. + * + *-------------------------------------------------------------- + */ + +static int +ConfigureArc(interp, canvas, itemPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Arc item to reconfigure. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Arguments describing things to configure. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + XGCValues gcValues; + GC newGC; + unsigned long mask; + int i; + Tk_Window tkwin; + + tkwin = Tk_CanvasTkwin(canvas); + if (Tk_ConfigureWidget(interp, tkwin, configSpecs, argc, argv, + (char *) arcPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few of the options require additional processing, such as + * style and graphics contexts. + */ + + i = (int) (arcPtr->start/360.0); + arcPtr->start -= i*360.0; + if (arcPtr->start < 0) { + arcPtr->start += 360.0; + } + i = (int) (arcPtr->extent/360.0); + arcPtr->extent -= i*360.0; + + if ((arcPtr->style != arcUid) && (arcPtr->style != chordUid) + && (arcPtr->style != pieSliceUid)) { + Tcl_AppendResult(interp, "bad -style option \"", + arcPtr->style, "\": must be arc, chord, or pieslice", + (char *) NULL); + arcPtr->style = pieSliceUid; + return TCL_ERROR; + } + + if (arcPtr->width < 0) { + arcPtr->width = 1; + } + if (arcPtr->outlineColor == NULL) { + newGC = None; + } else { + gcValues.foreground = arcPtr->outlineColor->pixel; + gcValues.cap_style = CapButt; + gcValues.line_width = arcPtr->width; + mask = GCForeground|GCCapStyle|GCLineWidth; + if (arcPtr->outlineStipple != None) { + gcValues.stipple = arcPtr->outlineStipple; + gcValues.fill_style = FillStippled; + mask |= GCStipple|GCFillStyle; + } + newGC = Tk_GetGC(tkwin, mask, &gcValues); + } + if (arcPtr->outlineGC != None) { + Tk_FreeGC(Tk_Display(tkwin), arcPtr->outlineGC); + } + arcPtr->outlineGC = newGC; + + if ((arcPtr->fillColor == NULL) || (arcPtr->style == arcUid)) { + newGC = None; + } else { + gcValues.foreground = arcPtr->fillColor->pixel; + if (arcPtr->style == chordUid) { + gcValues.arc_mode = ArcChord; + } else { + gcValues.arc_mode = ArcPieSlice; + } + mask = GCForeground|GCArcMode; + if (arcPtr->fillStipple != None) { + gcValues.stipple = arcPtr->fillStipple; + gcValues.fill_style = FillStippled; + mask |= GCStipple|GCFillStyle; + } + newGC = Tk_GetGC(tkwin, mask, &gcValues); + } + if (arcPtr->fillGC != None) { + Tk_FreeGC(Tk_Display(tkwin), arcPtr->fillGC); + } + arcPtr->fillGC = newGC; + + ComputeArcBbox(canvas, arcPtr); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * DeleteArc -- + * + * This procedure is called to clean up the data structure + * associated with a arc item. + * + * Results: + * None. + * + * Side effects: + * Resources associated with itemPtr are released. + * + *-------------------------------------------------------------- + */ + +static void +DeleteArc(canvas, itemPtr, display) + Tk_Canvas canvas; /* Info about overall canvas. */ + Tk_Item *itemPtr; /* Item that is being deleted. */ + Display *display; /* Display containing window for + * canvas. */ +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + + if (arcPtr->numOutlinePoints != 0) { + ckfree((char *) arcPtr->outlinePtr); + } + if (arcPtr->outlineColor != NULL) { + Tk_FreeColor(arcPtr->outlineColor); + } + if (arcPtr->fillColor != NULL) { + Tk_FreeColor(arcPtr->fillColor); + } + if (arcPtr->fillStipple != None) { + Tk_FreeBitmap(display, arcPtr->fillStipple); + } + if (arcPtr->outlineStipple != None) { + Tk_FreeBitmap(display, arcPtr->outlineStipple); + } + if (arcPtr->outlineGC != None) { + Tk_FreeGC(display, arcPtr->outlineGC); + } + if (arcPtr->fillGC != None) { + Tk_FreeGC(display, arcPtr->fillGC); + } +} + +/* + *-------------------------------------------------------------- + * + * ComputeArcBbox -- + * + * This procedure is invoked to compute the bounding box of + * all the pixels that may be drawn as part of an arc. + * + * Results: + * None. + * + * Side effects: + * The fields x1, y1, x2, and y2 are updated in the header + * for itemPtr. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +ComputeArcBbox(canvas, arcPtr) + Tk_Canvas canvas; /* Canvas that contains item. */ + ArcItem *arcPtr; /* Item whose bbox is to be + * recomputed. */ +{ + double tmp, center[2], point[2]; + + /* + * Make sure that the first coordinates are the lowest ones. + */ + + if (arcPtr->bbox[1] > arcPtr->bbox[3]) { + double tmp; + tmp = arcPtr->bbox[3]; + arcPtr->bbox[3] = arcPtr->bbox[1]; + arcPtr->bbox[1] = tmp; + } + if (arcPtr->bbox[0] > arcPtr->bbox[2]) { + double tmp; + tmp = arcPtr->bbox[2]; + arcPtr->bbox[2] = arcPtr->bbox[0]; + arcPtr->bbox[0] = tmp; + } + + ComputeArcOutline(arcPtr); + + /* + * To compute the bounding box, start with the the bbox formed + * by the two endpoints of the arc. Then add in the center of + * the arc's oval (if relevant) and the 3-o'clock, 6-o'clock, + * 9-o'clock, and 12-o'clock positions, if they are relevant. + */ + + arcPtr->header.x1 = arcPtr->header.x2 = (int) arcPtr->center1[0]; + arcPtr->header.y1 = arcPtr->header.y2 = (int) arcPtr->center1[1]; + TkIncludePoint((Tk_Item *) arcPtr, arcPtr->center2); + center[0] = (arcPtr->bbox[0] + arcPtr->bbox[2])/2; + center[1] = (arcPtr->bbox[1] + arcPtr->bbox[3])/2; + if (arcPtr->style != arcUid) { + TkIncludePoint((Tk_Item *) arcPtr, center); + } + + tmp = -arcPtr->start; + if (tmp < 0) { + tmp += 360.0; + } + if ((tmp < arcPtr->extent) || ((tmp-360) > arcPtr->extent)) { + point[0] = arcPtr->bbox[2]; + point[1] = center[1]; + TkIncludePoint((Tk_Item *) arcPtr, point); + } + tmp = 90.0 - arcPtr->start; + if (tmp < 0) { + tmp += 360.0; + } + if ((tmp < arcPtr->extent) || ((tmp-360) > arcPtr->extent)) { + point[0] = center[0]; + point[1] = arcPtr->bbox[1]; + TkIncludePoint((Tk_Item *) arcPtr, point); + } + tmp = 180.0 - arcPtr->start; + if (tmp < 0) { + tmp += 360.0; + } + if ((tmp < arcPtr->extent) || ((tmp-360) > arcPtr->extent)) { + point[0] = arcPtr->bbox[0]; + point[1] = center[1]; + TkIncludePoint((Tk_Item *) arcPtr, point); + } + tmp = 270.0 - arcPtr->start; + if (tmp < 0) { + tmp += 360.0; + } + if ((tmp < arcPtr->extent) || ((tmp-360) > arcPtr->extent)) { + point[0] = center[0]; + point[1] = arcPtr->bbox[3]; + TkIncludePoint((Tk_Item *) arcPtr, point); + } + + /* + * Lastly, expand by the width of the arc (if the arc's outline is + * being drawn) and add one extra pixel just for safety. + */ + + if (arcPtr->outlineColor == NULL) { + tmp = 1; + } else { + tmp = (arcPtr->width + 1)/2 + 1; + } + arcPtr->header.x1 -= (int) tmp; + arcPtr->header.y1 -= (int) tmp; + arcPtr->header.x2 += (int) tmp; + arcPtr->header.y2 += (int) tmp; +} + +/* + *-------------------------------------------------------------- + * + * DisplayArc -- + * + * This procedure is invoked to draw an arc item in a given + * drawable. + * + * Results: + * None. + * + * Side effects: + * ItemPtr is drawn in drawable using the transformation + * information in canvas. + * + *-------------------------------------------------------------- + */ + +static void +DisplayArc(canvas, itemPtr, display, drawable, x, y, width, height) + Tk_Canvas canvas; /* Canvas that contains item. */ + Tk_Item *itemPtr; /* Item to be displayed. */ + Display *display; /* Display on which to draw item. */ + Drawable drawable; /* Pixmap or window in which to draw + * item. */ + int x, y, width, height; /* Describes region of canvas that + * must be redisplayed (not used). */ +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + short x1, y1, x2, y2; + int start, extent; + + /* + * Compute the screen coordinates of the bounding box for the item, + * plus integer values for the angles. + */ + + Tk_CanvasDrawableCoords(canvas, arcPtr->bbox[0], arcPtr->bbox[1], + &x1, &y1); + Tk_CanvasDrawableCoords(canvas, arcPtr->bbox[2], arcPtr->bbox[3], + &x2, &y2); + if (x2 <= x1) { + x2 = x1+1; + } + if (y2 <= y1) { + y2 = y1+1; + } + start = (int) ((64*arcPtr->start) + 0.5); + extent = (int) ((64*arcPtr->extent) + 0.5); + + /* + * Display filled arc first (if wanted), then outline. If the extent + * is zero then don't invoke XFillArc or XDrawArc, since this causes + * some window servers to crash and should be a no-op anyway. + */ + + if ((arcPtr->fillGC != None) && (extent != 0)) { + if (arcPtr->fillStipple != None) { + Tk_CanvasSetStippleOrigin(canvas, arcPtr->fillGC); + } + XFillArc(display, drawable, arcPtr->fillGC, x1, y1, (unsigned) (x2-x1), + (unsigned) (y2-y1), start, extent); + if (arcPtr->fillStipple != None) { + XSetTSOrigin(display, arcPtr->fillGC, 0, 0); + } + } + if (arcPtr->outlineGC != None) { + if (arcPtr->outlineStipple != None) { + Tk_CanvasSetStippleOrigin(canvas, arcPtr->outlineGC); + } + if (extent != 0) { + XDrawArc(display, drawable, arcPtr->outlineGC, x1, y1, + (unsigned) (x2-x1), (unsigned) (y2-y1), start, extent); + } + + /* + * If the outline width is very thin, don't use polygons to draw + * the linear parts of the outline (this often results in nothing + * being displayed); just draw lines instead. + */ + + if (arcPtr->width <= 2) { + Tk_CanvasDrawableCoords(canvas, arcPtr->center1[0], + arcPtr->center1[1], &x1, &y1); + Tk_CanvasDrawableCoords(canvas, arcPtr->center2[0], + arcPtr->center2[1], &x2, &y2); + + if (arcPtr->style == chordUid) { + XDrawLine(display, drawable, arcPtr->outlineGC, + x1, y1, x2, y2); + } else if (arcPtr->style == pieSliceUid) { + short cx, cy; + + Tk_CanvasDrawableCoords(canvas, + (arcPtr->bbox[0] + arcPtr->bbox[2])/2.0, + (arcPtr->bbox[1] + arcPtr->bbox[3])/2.0, &cx, &cy); + XDrawLine(display, drawable, arcPtr->outlineGC, + cx, cy, x1, y1); + XDrawLine(display, drawable, arcPtr->outlineGC, + cx, cy, x2, y2); + } + } else { + if (arcPtr->style == chordUid) { + TkFillPolygon(canvas, arcPtr->outlinePtr, CHORD_OUTLINE_PTS, + display, drawable, arcPtr->outlineGC, None); + } else if (arcPtr->style == pieSliceUid) { + TkFillPolygon(canvas, arcPtr->outlinePtr, PIE_OUTLINE1_PTS, + display, drawable, arcPtr->outlineGC, None); + TkFillPolygon(canvas, arcPtr->outlinePtr + 2*PIE_OUTLINE1_PTS, + PIE_OUTLINE2_PTS, display, drawable, arcPtr->outlineGC, + None); + } + } + if (arcPtr->outlineStipple != None) { + XSetTSOrigin(display, arcPtr->outlineGC, 0, 0); + } + } +} + +/* + *-------------------------------------------------------------- + * + * ArcToPoint -- + * + * Computes the distance from a given point to a given + * arc, in canvas units. + * + * Results: + * The return value is 0 if the point whose x and y coordinates + * are coordPtr[0] and coordPtr[1] is inside the arc. If the + * point isn't inside the arc then the return value is the + * distance from the point to the arc. If itemPtr is filled, + * then anywhere in the interior is considered "inside"; if + * itemPtr isn't filled, then "inside" means only the area + * occupied by the outline. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static double +ArcToPoint(canvas, itemPtr, pointPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against point. */ + double *pointPtr; /* Pointer to x and y coordinates. */ +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + double vertex[2], pointAngle, diff, dist, newDist; + double poly[8], polyDist, width, t1, t2; + int filled, angleInRange; + + /* + * See if the point is within the angular range of the arc. + * Remember, X angles are backwards from the way we'd normally + * think of them. Also, compensate for any eccentricity of + * the oval. + */ + + vertex[0] = (arcPtr->bbox[0] + arcPtr->bbox[2])/2.0; + vertex[1] = (arcPtr->bbox[1] + arcPtr->bbox[3])/2.0; + t1 = (pointPtr[1] - vertex[1])/(arcPtr->bbox[3] - arcPtr->bbox[1]); + t2 = (pointPtr[0] - vertex[0])/(arcPtr->bbox[2] - arcPtr->bbox[0]); + if ((t1 == 0.0) && (t2 == 0.0)) { + pointAngle = 0; + } else { + pointAngle = -atan2(t1, t2)*180/PI; + } + diff = pointAngle - arcPtr->start; + diff -= ((int) (diff/360.0) * 360.0); + if (diff < 0) { + diff += 360.0; + } + angleInRange = (diff <= arcPtr->extent) || + ((arcPtr->extent < 0) && ((diff - 360.0) >= arcPtr->extent)); + + /* + * Now perform different tests depending on what kind of arc + * we're dealing with. + */ + + if (arcPtr->style == arcUid) { + if (angleInRange) { + return TkOvalToPoint(arcPtr->bbox, (double) arcPtr->width, + 0, pointPtr); + } + dist = hypot(pointPtr[0] - arcPtr->center1[0], + pointPtr[1] - arcPtr->center1[1]); + newDist = hypot(pointPtr[0] - arcPtr->center2[0], + pointPtr[1] - arcPtr->center2[1]); + if (newDist < dist) { + return newDist; + } + return dist; + } + + if ((arcPtr->fillGC != None) || (arcPtr->outlineGC == None)) { + filled = 1; + } else { + filled = 0; + } + if (arcPtr->outlineGC == None) { + width = 0.0; + } else { + width = arcPtr->width; + } + + if (arcPtr->style == pieSliceUid) { + if (width > 1.0) { + dist = TkPolygonToPoint(arcPtr->outlinePtr, PIE_OUTLINE1_PTS, + pointPtr); + newDist = TkPolygonToPoint(arcPtr->outlinePtr + 2*PIE_OUTLINE1_PTS, + PIE_OUTLINE2_PTS, pointPtr); + } else { + dist = TkLineToPoint(vertex, arcPtr->center1, pointPtr); + newDist = TkLineToPoint(vertex, arcPtr->center2, pointPtr); + } + if (newDist < dist) { + dist = newDist; + } + if (angleInRange) { + newDist = TkOvalToPoint(arcPtr->bbox, width, filled, pointPtr); + if (newDist < dist) { + dist = newDist; + } + } + return dist; + } + + /* + * This is a chord-style arc. We have to deal specially with the + * triangular piece that represents the difference between a + * chord-style arc and a pie-slice arc (for small angles this piece + * is excluded here where it would be included for pie slices; + * for large angles the piece is included here but would be + * excluded for pie slices). + */ + + if (width > 1.0) { + dist = TkPolygonToPoint(arcPtr->outlinePtr, CHORD_OUTLINE_PTS, + pointPtr); + } else { + dist = TkLineToPoint(arcPtr->center1, arcPtr->center2, pointPtr); + } + poly[0] = poly[6] = vertex[0]; + poly[1] = poly[7] = vertex[1]; + poly[2] = arcPtr->center1[0]; + poly[3] = arcPtr->center1[1]; + poly[4] = arcPtr->center2[0]; + poly[5] = arcPtr->center2[1]; + polyDist = TkPolygonToPoint(poly, 4, pointPtr); + if (angleInRange) { + if ((arcPtr->extent < -180.0) || (arcPtr->extent > 180.0) + || (polyDist > 0.0)) { + newDist = TkOvalToPoint(arcPtr->bbox, width, filled, pointPtr); + if (newDist < dist) { + dist = newDist; + } + } + } else { + if ((arcPtr->extent < -180.0) || (arcPtr->extent > 180.0)) { + if (filled && (polyDist < dist)) { + dist = polyDist; + } + } + } + return dist; +} + +/* + *-------------------------------------------------------------- + * + * ArcToArea -- + * + * This procedure is called to determine whether an item + * lies entirely inside, entirely outside, or overlapping + * a given area. + * + * Results: + * -1 is returned if the item is entirely outside the area + * given by rectPtr, 0 if it overlaps, and 1 if it is entirely + * inside the given area. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +ArcToArea(canvas, itemPtr, rectPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against arc. */ + double *rectPtr; /* Pointer to array of four coordinates + * (x1, y1, x2, y2) describing rectangular + * area. */ +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + double rx, ry; /* Radii for transformed oval: these define + * an oval centered at the origin. */ + double tRect[4]; /* Transformed version of x1, y1, x2, y2, + * for coord. system where arc is centered + * on the origin. */ + double center[2], width, angle, tmp; + double points[20], *pointPtr; + int numPoints, filled; + int inside; /* Non-zero means every test so far suggests + * that arc is inside rectangle. 0 means + * every test so far shows arc to be outside + * of rectangle. */ + int newInside; + + if ((arcPtr->fillGC != None) || (arcPtr->outlineGC == None)) { + filled = 1; + } else { + filled = 0; + } + if (arcPtr->outlineGC == None) { + width = 0.0; + } else { + width = arcPtr->width; + } + + /* + * Transform both the arc and the rectangle so that the arc's oval + * is centered on the origin. + */ + + center[0] = (arcPtr->bbox[0] + arcPtr->bbox[2])/2.0; + center[1] = (arcPtr->bbox[1] + arcPtr->bbox[3])/2.0; + tRect[0] = rectPtr[0] - center[0]; + tRect[1] = rectPtr[1] - center[1]; + tRect[2] = rectPtr[2] - center[0]; + tRect[3] = rectPtr[3] - center[1]; + rx = arcPtr->bbox[2] - center[0] + width/2.0; + ry = arcPtr->bbox[3] - center[1] + width/2.0; + + /* + * Find the extreme points of the arc and see whether these are all + * inside the rectangle (in which case we're done), partly in and + * partly out (in which case we're done), or all outside (in which + * case we have more work to do). The extreme points include the + * following, which are checked in order: + * + * 1. The outside points of the arc, corresponding to start and + * extent. + * 2. The center of the arc (but only in pie-slice mode). + * 3. The 12, 3, 6, and 9-o'clock positions (but only if the arc + * includes those angles). + */ + + pointPtr = points; + angle = -arcPtr->start*(PI/180.0); + pointPtr[0] = rx*cos(angle); + pointPtr[1] = ry*sin(angle); + angle += -arcPtr->extent*(PI/180.0); + pointPtr[2] = rx*cos(angle); + pointPtr[3] = ry*sin(angle); + numPoints = 2; + pointPtr += 4; + + if ((arcPtr->style == pieSliceUid) && (arcPtr->extent < 180.0)) { + pointPtr[0] = 0.0; + pointPtr[1] = 0.0; + numPoints++; + pointPtr += 2; + } + + tmp = -arcPtr->start; + if (tmp < 0) { + tmp += 360.0; + } + if ((tmp < arcPtr->extent) || ((tmp-360) > arcPtr->extent)) { + pointPtr[0] = rx; + pointPtr[1] = 0.0; + numPoints++; + pointPtr += 2; + } + tmp = 90.0 - arcPtr->start; + if (tmp < 0) { + tmp += 360.0; + } + if ((tmp < arcPtr->extent) || ((tmp-360) > arcPtr->extent)) { + pointPtr[0] = 0.0; + pointPtr[1] = -ry; + numPoints++; + pointPtr += 2; + } + tmp = 180.0 - arcPtr->start; + if (tmp < 0) { + tmp += 360.0; + } + if ((tmp < arcPtr->extent) || ((tmp-360) > arcPtr->extent)) { + pointPtr[0] = -rx; + pointPtr[1] = 0.0; + numPoints++; + pointPtr += 2; + } + tmp = 270.0 - arcPtr->start; + if (tmp < 0) { + tmp += 360.0; + } + if ((tmp < arcPtr->extent) || ((tmp-360) > arcPtr->extent)) { + pointPtr[0] = 0.0; + pointPtr[1] = ry; + numPoints++; + } + + /* + * Now that we've located the extreme points, loop through them all + * to see which are inside the rectangle. + */ + + inside = (points[0] > tRect[0]) && (points[0] < tRect[2]) + && (points[1] > tRect[1]) && (points[1] < tRect[3]); + for (pointPtr = points+2; numPoints > 1; pointPtr += 2, numPoints--) { + newInside = (pointPtr[0] > tRect[0]) && (pointPtr[0] < tRect[2]) + && (pointPtr[1] > tRect[1]) && (pointPtr[1] < tRect[3]); + if (newInside != inside) { + return 0; + } + } + + if (inside) { + return 1; + } + + /* + * So far, oval appears to be outside rectangle, but can't yet tell + * for sure. Next, test each of the four sides of the rectangle + * against the bounding region for the arc. If any intersections + * are found, then return "overlapping". First, test against the + * polygon(s) forming the sides of a chord or pie-slice. + */ + + if (arcPtr->style == pieSliceUid) { + if (width >= 1.0) { + if (TkPolygonToArea(arcPtr->outlinePtr, PIE_OUTLINE1_PTS, + rectPtr) != -1) { + return 0; + } + if (TkPolygonToArea(arcPtr->outlinePtr + 2*PIE_OUTLINE1_PTS, + PIE_OUTLINE2_PTS, rectPtr) != -1) { + return 0; + } + } else { + if ((TkLineToArea(center, arcPtr->center1, rectPtr) != -1) || + (TkLineToArea(center, arcPtr->center2, rectPtr) != -1)) { + return 0; + } + } + } else if (arcPtr->style == chordUid) { + if (width >= 1.0) { + if (TkPolygonToArea(arcPtr->outlinePtr, CHORD_OUTLINE_PTS, + rectPtr) != -1) { + return 0; + } + } else { + if (TkLineToArea(arcPtr->center1, arcPtr->center2, + rectPtr) != -1) { + return 0; + } + } + } + + /* + * Next check for overlap between each of the four sides and the + * outer perimiter of the arc. If the arc isn't filled, then also + * check the inner perimeter of the arc. + */ + + if (HorizLineToArc(tRect[0], tRect[2], tRect[1], rx, ry, arcPtr->start, + arcPtr->extent) + || HorizLineToArc(tRect[0], tRect[2], tRect[3], rx, ry, + arcPtr->start, arcPtr->extent) + || VertLineToArc(tRect[0], tRect[1], tRect[3], rx, ry, + arcPtr->start, arcPtr->extent) + || VertLineToArc(tRect[2], tRect[1], tRect[3], rx, ry, + arcPtr->start, arcPtr->extent)) { + return 0; + } + if ((width > 1.0) && !filled) { + rx -= width; + ry -= width; + if (HorizLineToArc(tRect[0], tRect[2], tRect[1], rx, ry, arcPtr->start, + arcPtr->extent) + || HorizLineToArc(tRect[0], tRect[2], tRect[3], rx, ry, + arcPtr->start, arcPtr->extent) + || VertLineToArc(tRect[0], tRect[1], tRect[3], rx, ry, + arcPtr->start, arcPtr->extent) + || VertLineToArc(tRect[2], tRect[1], tRect[3], rx, ry, + arcPtr->start, arcPtr->extent)) { + return 0; + } + } + + /* + * The arc still appears to be totally disjoint from the rectangle, + * but it's also possible that the rectangle is totally inside the arc. + * Do one last check, which is to check one point of the rectangle + * to see if it's inside the arc. If it is, we've got overlap. If + * it isn't, the arc's really outside the rectangle. + */ + + if (ArcToPoint(canvas, itemPtr, rectPtr) == 0.0) { + return 0; + } + return -1; +} + +/* + *-------------------------------------------------------------- + * + * ScaleArc -- + * + * This procedure is invoked to rescale an arc item. + * + * Results: + * None. + * + * Side effects: + * The arc referred to by itemPtr is rescaled so that the + * following transformation is applied to all point + * coordinates: + * x' = originX + scaleX*(x-originX) + * y' = originY + scaleY*(y-originY) + * + *-------------------------------------------------------------- + */ + +static void +ScaleArc(canvas, itemPtr, originX, originY, scaleX, scaleY) + Tk_Canvas canvas; /* Canvas containing arc. */ + Tk_Item *itemPtr; /* Arc to be scaled. */ + double originX, originY; /* Origin about which to scale rect. */ + double scaleX; /* Amount to scale in X direction. */ + double scaleY; /* Amount to scale in Y direction. */ +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + + arcPtr->bbox[0] = originX + scaleX*(arcPtr->bbox[0] - originX); + arcPtr->bbox[1] = originY + scaleY*(arcPtr->bbox[1] - originY); + arcPtr->bbox[2] = originX + scaleX*(arcPtr->bbox[2] - originX); + arcPtr->bbox[3] = originY + scaleY*(arcPtr->bbox[3] - originY); + ComputeArcBbox(canvas, arcPtr); +} + +/* + *-------------------------------------------------------------- + * + * TranslateArc -- + * + * This procedure is called to move an arc by a given amount. + * + * Results: + * None. + * + * Side effects: + * The position of the arc is offset by (xDelta, yDelta), and + * the bounding box is updated in the generic part of the item + * structure. + * + *-------------------------------------------------------------- + */ + +static void +TranslateArc(canvas, itemPtr, deltaX, deltaY) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item that is being moved. */ + double deltaX, deltaY; /* Amount by which item is to be + * moved. */ +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + + arcPtr->bbox[0] += deltaX; + arcPtr->bbox[1] += deltaY; + arcPtr->bbox[2] += deltaX; + arcPtr->bbox[3] += deltaY; + ComputeArcBbox(canvas, arcPtr); +} + +/* + *-------------------------------------------------------------- + * + * ComputeArcOutline -- + * + * This procedure creates a polygon describing everything in + * the outline for an arc except what's in the curved part. + * For a "pie slice" arc this is a V-shaped chunk, and for + * a "chord" arc this is a linear chunk (with cutaway corners). + * For "arc" arcs, this stuff isn't relevant. + * + * Results: + * None. + * + * Side effects: + * The information at arcPtr->outlinePtr gets modified, and + * storage for arcPtr->outlinePtr may be allocated or freed. + * + *-------------------------------------------------------------- + */ + +static void +ComputeArcOutline(arcPtr) + ArcItem *arcPtr; /* Information about arc. */ +{ + double sin1, cos1, sin2, cos2, angle, halfWidth; + double boxWidth, boxHeight; + double vertex[2], corner1[2], corner2[2]; + double *outlinePtr; + + /* + * Make sure that the outlinePtr array is large enough to hold + * either a chord or pie-slice outline. + */ + + if (arcPtr->numOutlinePoints == 0) { + arcPtr->outlinePtr = (double *) ckalloc((unsigned) + (26 * sizeof(double))); + arcPtr->numOutlinePoints = 22; + } + outlinePtr = arcPtr->outlinePtr; + + /* + * First compute the two points that lie at the centers of + * the ends of the curved arc segment, which are marked with + * X's in the figure below: + * + * + * * * * + * * * + * * * * * + * * * * * + * * * * * + * X * * X + * + * The code is tricky because the arc can be ovular in shape. + * It computes the position for a unit circle, and then + * scales to fit the shape of the arc's bounding box. + * + * Also, watch out because angles go counter-clockwise like you + * might expect, but the y-coordinate system is inverted. To + * handle this, just negate the angles in all the computations. + */ + + boxWidth = arcPtr->bbox[2] - arcPtr->bbox[0]; + boxHeight = arcPtr->bbox[3] - arcPtr->bbox[1]; + angle = -arcPtr->start*PI/180.0; + sin1 = sin(angle); + cos1 = cos(angle); + angle -= arcPtr->extent*PI/180.0; + sin2 = sin(angle); + cos2 = cos(angle); + vertex[0] = (arcPtr->bbox[0] + arcPtr->bbox[2])/2.0; + vertex[1] = (arcPtr->bbox[1] + arcPtr->bbox[3])/2.0; + arcPtr->center1[0] = vertex[0] + cos1*boxWidth/2.0; + arcPtr->center1[1] = vertex[1] + sin1*boxHeight/2.0; + arcPtr->center2[0] = vertex[0] + cos2*boxWidth/2.0; + arcPtr->center2[1] = vertex[1] + sin2*boxHeight/2.0; + + /* + * Next compute the "outermost corners" of the arc, which are + * marked with X's in the figure below: + * + * * * * + * * * + * * * * * + * * * * * + * X * * X + * * * + * + * The code below is tricky because it has to handle eccentricity + * in the shape of the oval. The key in the code below is to + * realize that the slope of the line from arcPtr->center1 to corner1 + * is (boxWidth*sin1)/(boxHeight*cos1), and similarly for arcPtr->center2 + * and corner2. These formulas can be computed from the formula for + * the oval. + */ + + halfWidth = arcPtr->width/2.0; + if (((boxWidth*sin1) == 0.0) && ((boxHeight*cos1) == 0.0)) { + angle = 0.0; + } else { + angle = atan2(boxWidth*sin1, boxHeight*cos1); + } + corner1[0] = arcPtr->center1[0] + cos(angle)*halfWidth; + corner1[1] = arcPtr->center1[1] + sin(angle)*halfWidth; + if (((boxWidth*sin2) == 0.0) && ((boxHeight*cos2) == 0.0)) { + angle = 0.0; + } else { + angle = atan2(boxWidth*sin2, boxHeight*cos2); + } + corner2[0] = arcPtr->center2[0] + cos(angle)*halfWidth; + corner2[1] = arcPtr->center2[1] + sin(angle)*halfWidth; + + /* + * For a chord outline, generate a six-sided polygon with three + * points for each end of the chord. The first and third points + * for each end are butt points generated on either side of the + * center point. The second point is the corner point. + */ + + if (arcPtr->style == chordUid) { + outlinePtr[0] = outlinePtr[12] = corner1[0]; + outlinePtr[1] = outlinePtr[13] = corner1[1]; + TkGetButtPoints(arcPtr->center2, arcPtr->center1, + (double) arcPtr->width, 0, outlinePtr+10, outlinePtr+2); + outlinePtr[4] = arcPtr->center2[0] + outlinePtr[2] + - arcPtr->center1[0]; + outlinePtr[5] = arcPtr->center2[1] + outlinePtr[3] + - arcPtr->center1[1]; + outlinePtr[6] = corner2[0]; + outlinePtr[7] = corner2[1]; + outlinePtr[8] = arcPtr->center2[0] + outlinePtr[10] + - arcPtr->center1[0]; + outlinePtr[9] = arcPtr->center2[1] + outlinePtr[11] + - arcPtr->center1[1]; + } else if (arcPtr->style == pieSliceUid) { + /* + * For pie slices, generate two polygons, one for each side + * of the pie slice. The first arm has a shape like this, + * where the center of the oval is X, arcPtr->center1 is at Y, and + * corner1 is at Z: + * + * _____________________ + * | \ + * | \ + * X Y Z + * | / + * |_____________________/ + * + */ + + TkGetButtPoints(arcPtr->center1, vertex, (double) arcPtr->width, 0, + outlinePtr, outlinePtr+2); + outlinePtr[4] = arcPtr->center1[0] + outlinePtr[2] - vertex[0]; + outlinePtr[5] = arcPtr->center1[1] + outlinePtr[3] - vertex[1]; + outlinePtr[6] = corner1[0]; + outlinePtr[7] = corner1[1]; + outlinePtr[8] = arcPtr->center1[0] + outlinePtr[0] - vertex[0]; + outlinePtr[9] = arcPtr->center1[1] + outlinePtr[1] - vertex[1]; + outlinePtr[10] = outlinePtr[0]; + outlinePtr[11] = outlinePtr[1]; + + /* + * The second arm has a shape like this: + * + * + * ______________________ + * / \ + * / \ + * Z Y X / + * \ / + * \______________________/ + * + * Similar to above X is the center of the oval/circle, Y is + * arcPtr->center2, and Z is corner2. The extra jog out to the left + * of X is needed in or to produce a butted joint with the + * first arm; the corner to the right of X is one of the + * first two points of the first arm, depending on extent. + */ + + TkGetButtPoints(arcPtr->center2, vertex, (double) arcPtr->width, 0, + outlinePtr+12, outlinePtr+16); + if ((arcPtr->extent > 180) || + ((arcPtr->extent < 0) && (arcPtr->extent > -180))) { + outlinePtr[14] = outlinePtr[0]; + outlinePtr[15] = outlinePtr[1]; + } else { + outlinePtr[14] = outlinePtr[2]; + outlinePtr[15] = outlinePtr[3]; + } + outlinePtr[18] = arcPtr->center2[0] + outlinePtr[16] - vertex[0]; + outlinePtr[19] = arcPtr->center2[1] + outlinePtr[17] - vertex[1]; + outlinePtr[20] = corner2[0]; + outlinePtr[21] = corner2[1]; + outlinePtr[22] = arcPtr->center2[0] + outlinePtr[12] - vertex[0]; + outlinePtr[23] = arcPtr->center2[1] + outlinePtr[13] - vertex[1]; + outlinePtr[24] = outlinePtr[12]; + outlinePtr[25] = outlinePtr[13]; + } +} + +/* + *-------------------------------------------------------------- + * + * HorizLineToArc -- + * + * Determines whether a horizontal line segment intersects + * a given arc. + * + * Results: + * The return value is 1 if the given line intersects the + * infinitely-thin arc section defined by rx, ry, start, + * and extent, and 0 otherwise. Only the perimeter of the + * arc is checked: interior areas (e.g. pie-slice or chord) + * are not checked. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +HorizLineToArc(x1, x2, y, rx, ry, start, extent) + double x1, x2; /* X-coords of endpoints of line segment. + * X1 must be <= x2. */ + double y; /* Y-coordinate of line segment. */ + double rx, ry; /* These x- and y-radii define an oval + * centered at the origin. */ + double start, extent; /* Angles that define extent of arc, in + * the standard fashion for this module. */ +{ + double tmp; + double tx, ty; /* Coordinates of intersection point in + * transformed coordinate system. */ + double x; + + /* + * Compute the x-coordinate of one possible intersection point + * between the arc and the line. Use a transformed coordinate + * system where the oval is a unit circle centered at the origin. + * Then scale back to get actual x-coordinate. + */ + + ty = y/ry; + tmp = 1 - ty*ty; + if (tmp < 0) { + return 0; + } + tx = sqrt(tmp); + x = tx*rx; + + /* + * Test both intersection points. + */ + + if ((x >= x1) && (x <= x2) && AngleInRange(tx, ty, start, extent)) { + return 1; + } + if ((-x >= x1) && (-x <= x2) && AngleInRange(-tx, ty, start, extent)) { + return 1; + } + return 0; +} + +/* + *-------------------------------------------------------------- + * + * VertLineToArc -- + * + * Determines whether a vertical line segment intersects + * a given arc. + * + * Results: + * The return value is 1 if the given line intersects the + * infinitely-thin arc section defined by rx, ry, start, + * and extent, and 0 otherwise. Only the perimeter of the + * arc is checked: interior areas (e.g. pie-slice or chord) + * are not checked. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +VertLineToArc(x, y1, y2, rx, ry, start, extent) + double x; /* X-coordinate of line segment. */ + double y1, y2; /* Y-coords of endpoints of line segment. + * Y1 must be <= y2. */ + double rx, ry; /* These x- and y-radii define an oval + * centered at the origin. */ + double start, extent; /* Angles that define extent of arc, in + * the standard fashion for this module. */ +{ + double tmp; + double tx, ty; /* Coordinates of intersection point in + * transformed coordinate system. */ + double y; + + /* + * Compute the y-coordinate of one possible intersection point + * between the arc and the line. Use a transformed coordinate + * system where the oval is a unit circle centered at the origin. + * Then scale back to get actual y-coordinate. + */ + + tx = x/rx; + tmp = 1 - tx*tx; + if (tmp < 0) { + return 0; + } + ty = sqrt(tmp); + y = ty*ry; + + /* + * Test both intersection points. + */ + + if ((y > y1) && (y < y2) && AngleInRange(tx, ty, start, extent)) { + return 1; + } + if ((-y > y1) && (-y < y2) && AngleInRange(tx, -ty, start, extent)) { + return 1; + } + return 0; +} + +/* + *-------------------------------------------------------------- + * + * AngleInRange -- + * + * Determine whether the angle from the origin to a given + * point is within a given range. + * + * Results: + * The return value is 1 if the angle from (0,0) to (x,y) + * is in the range given by start and extent, where angles + * are interpreted in the standard way for ovals (meaning + * backwards from normal interpretation). Otherwise the + * return value is 0. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +AngleInRange(x, y, start, extent) + double x, y; /* Coordinate of point; angle measured + * from origin to here, relative to x-axis. */ + double start; /* First angle, degrees, >=0, <=360. */ + double extent; /* Size of arc in degrees >=-360, <=360. */ +{ + double diff; + + if ((x == 0.0) && (y == 0.0)) { + return 1; + } + diff = -atan2(y, x); + diff = diff*(180.0/PI) - start; + while (diff > 360.0) { + diff -= 360.0; + } + while (diff < 0.0) { + diff += 360.0; + } + if (extent >= 0) { + return diff <= extent; + } + return (diff-360.0) >= extent; +} + +/* + *-------------------------------------------------------------- + * + * ArcToPostscript -- + * + * This procedure is called to generate Postscript for + * arc items. + * + * Results: + * The return value is a standard Tcl result. If an error + * occurs in generating Postscript then an error message is + * left in interp->result, replacing whatever used + * to be there. If no error occurs, then Postscript for the + * item is appended to the result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +ArcToPostscript(interp, canvas, itemPtr, prepass) + Tcl_Interp *interp; /* Leave Postscript or error message + * here. */ + Tk_Canvas canvas; /* Information about overall canvas. */ + Tk_Item *itemPtr; /* Item for which Postscript is + * wanted. */ + int prepass; /* 1 means this is a prepass to + * collect font information; 0 means + * final Postscript is being created. */ +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + char buffer[400]; + double y1, y2, ang1, ang2; + + y1 = Tk_CanvasPsY(canvas, arcPtr->bbox[1]); + y2 = Tk_CanvasPsY(canvas, arcPtr->bbox[3]); + ang1 = arcPtr->start; + ang2 = ang1 + arcPtr->extent; + if (ang2 < ang1) { + ang1 = ang2; + ang2 = arcPtr->start; + } + + /* + * If the arc is filled, output Postscript for the interior region + * of the arc. + */ + + if (arcPtr->fillGC != None) { + sprintf(buffer, "matrix currentmatrix\n%.15g %.15g translate %.15g %.15g scale\n", + (arcPtr->bbox[0] + arcPtr->bbox[2])/2, (y1 + y2)/2, + (arcPtr->bbox[2] - arcPtr->bbox[0])/2, (y1 - y2)/2); + Tcl_AppendResult(interp, buffer, (char *) NULL); + if (arcPtr->style == chordUid) { + sprintf(buffer, "0 0 1 %.15g %.15g arc closepath\nsetmatrix\n", + ang1, ang2); + } else { + sprintf(buffer, + "0 0 moveto 0 0 1 %.15g %.15g arc closepath\nsetmatrix\n", + ang1, ang2); + } + Tcl_AppendResult(interp, buffer, (char *) NULL); + if (Tk_CanvasPsColor(interp, canvas, arcPtr->fillColor) != TCL_OK) { + return TCL_ERROR; + }; + if (arcPtr->fillStipple != None) { + Tcl_AppendResult(interp, "clip ", (char *) NULL); + if (Tk_CanvasPsStipple(interp, canvas, arcPtr->fillStipple) + != TCL_OK) { + return TCL_ERROR; + } + if (arcPtr->outlineGC != None) { + Tcl_AppendResult(interp, "grestore gsave\n", (char *) NULL); + } + } else { + Tcl_AppendResult(interp, "fill\n", (char *) NULL); + } + } + + /* + * If there's an outline for the arc, draw it. + */ + + if (arcPtr->outlineGC != None) { + sprintf(buffer, "matrix currentmatrix\n%.15g %.15g translate %.15g %.15g scale\n", + (arcPtr->bbox[0] + arcPtr->bbox[2])/2, (y1 + y2)/2, + (arcPtr->bbox[2] - arcPtr->bbox[0])/2, (y1 - y2)/2); + Tcl_AppendResult(interp, buffer, (char *) NULL); + sprintf(buffer, "0 0 1 %.15g %.15g arc\nsetmatrix\n", ang1, ang2); + Tcl_AppendResult(interp, buffer, (char *) NULL); + sprintf(buffer, "%d setlinewidth\n0 setlinecap\n", arcPtr->width); + Tcl_AppendResult(interp, buffer, (char *) NULL); + if (Tk_CanvasPsColor(interp, canvas, arcPtr->outlineColor) + != TCL_OK) { + return TCL_ERROR; + } + if (arcPtr->outlineStipple != None) { + Tcl_AppendResult(interp, "StrokeClip ", (char *) NULL); + if (Tk_CanvasPsStipple(interp, canvas, + arcPtr->outlineStipple) != TCL_OK) { + return TCL_ERROR; + } + } else { + Tcl_AppendResult(interp, "stroke\n", (char *) NULL); + } + if (arcPtr->style != arcUid) { + Tcl_AppendResult(interp, "grestore gsave\n", (char *) NULL); + if (arcPtr->style == chordUid) { + Tk_CanvasPsPath(interp, canvas, arcPtr->outlinePtr, + CHORD_OUTLINE_PTS); + } else { + Tk_CanvasPsPath(interp, canvas, arcPtr->outlinePtr, + PIE_OUTLINE1_PTS); + if (Tk_CanvasPsColor(interp, canvas, arcPtr->outlineColor) + != TCL_OK) { + return TCL_ERROR; + } + if (arcPtr->outlineStipple != None) { + Tcl_AppendResult(interp, "clip ", (char *) NULL); + if (Tk_CanvasPsStipple(interp, canvas, + arcPtr->outlineStipple) != TCL_OK) { + return TCL_ERROR; + } + } else { + Tcl_AppendResult(interp, "fill\n", (char *) NULL); + } + Tcl_AppendResult(interp, "grestore gsave\n", (char *) NULL); + Tk_CanvasPsPath(interp, canvas, + arcPtr->outlinePtr + 2*PIE_OUTLINE1_PTS, + PIE_OUTLINE2_PTS); + } + if (Tk_CanvasPsColor(interp, canvas, arcPtr->outlineColor) + != TCL_OK) { + return TCL_ERROR; + } + if (arcPtr->outlineStipple != None) { + Tcl_AppendResult(interp, "clip ", (char *) NULL); + if (Tk_CanvasPsStipple(interp, canvas, + arcPtr->outlineStipple) != TCL_OK) { + return TCL_ERROR; + } + } else { + Tcl_AppendResult(interp, "fill\n", (char *) NULL); + } + } + } + + return TCL_OK; +} diff --git a/generic/tkCanvBmap.c b/generic/tkCanvBmap.c new file mode 100644 index 0000000..fff0638 --- /dev/null +++ b/generic/tkCanvBmap.c @@ -0,0 +1,800 @@ +/* + * tkCanvBmap.c -- + * + * This file implements bitmap items for canvas widgets. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvBmap.c 1.30 96/05/03 10:49:00 + */ + +#include <stdio.h> +#include "tkInt.h" +#include "tkPort.h" +#include "tkCanvas.h" + +/* + * The structure below defines the record for each bitmap item. + */ + +typedef struct BitmapItem { + Tk_Item header; /* Generic stuff that's the same for all + * types. MUST BE FIRST IN STRUCTURE. */ + double x, y; /* Coordinates of positioning point for + * bitmap. */ + Tk_Anchor anchor; /* Where to anchor bitmap relative to + * (x,y). */ + Pixmap bitmap; /* Bitmap to display in window. */ + XColor *fgColor; /* Foreground color to use for bitmap. */ + XColor *bgColor; /* Background color to use for bitmap. */ + GC gc; /* Graphics context to use for drawing + * bitmap on screen. */ +} BitmapItem; + +/* + * Information used for parsing configuration specs: + */ + +static Tk_CustomOption tagsOption = {Tk_CanvasTagsParseProc, + Tk_CanvasTagsPrintProc, (ClientData) NULL +}; + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_ANCHOR, "-anchor", (char *) NULL, (char *) NULL, + "center", Tk_Offset(BitmapItem, anchor), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_COLOR, "-background", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(BitmapItem, bgColor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_BITMAP, "-bitmap", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(BitmapItem, bitmap), TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-foreground", (char *) NULL, (char *) NULL, + "black", Tk_Offset(BitmapItem, fgColor), 0}, + {TK_CONFIG_CUSTOM, "-tags", (char *) NULL, (char *) NULL, + (char *) NULL, 0, TK_CONFIG_NULL_OK, &tagsOption}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Prototypes for procedures defined in this file: + */ + +static int BitmapCoords _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv)); +static int BitmapToArea _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *rectPtr)); +static double BitmapToPoint _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *coordPtr)); +static int BitmapToPostscript _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int prepass)); +static void ComputeBitmapBbox _ANSI_ARGS_((Tk_Canvas canvas, + BitmapItem *bmapPtr)); +static int ConfigureBitmap _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv, int flags)); +static int CreateBitmap _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, struct Tk_Item *itemPtr, + int argc, char **argv)); +static void DeleteBitmap _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display)); +static void DisplayBitmap _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display, Drawable dst, + int x, int y, int width, int height)); +static void ScaleBitmap _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double originX, double originY, + double scaleX, double scaleY)); +static void TranslateBitmap _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double deltaX, double deltaY)); + +/* + * The structures below defines the bitmap item type in terms of + * procedures that can be invoked by generic item code. + */ + +Tk_ItemType tkBitmapType = { + "bitmap", /* name */ + sizeof(BitmapItem), /* itemSize */ + CreateBitmap, /* createProc */ + configSpecs, /* configSpecs */ + ConfigureBitmap, /* configureProc */ + BitmapCoords, /* coordProc */ + DeleteBitmap, /* deleteProc */ + DisplayBitmap, /* displayProc */ + 0, /* alwaysRedraw */ + BitmapToPoint, /* pointProc */ + BitmapToArea, /* areaProc */ + BitmapToPostscript, /* postscriptProc */ + ScaleBitmap, /* scaleProc */ + TranslateBitmap, /* translateProc */ + (Tk_ItemIndexProc *) NULL, /* indexProc */ + (Tk_ItemCursorProc *) NULL, /* icursorProc */ + (Tk_ItemSelectionProc *) NULL, /* selectionProc */ + (Tk_ItemInsertProc *) NULL, /* insertProc */ + (Tk_ItemDCharsProc *) NULL, /* dTextProc */ + (Tk_ItemType *) NULL /* nextPtr */ +}; + +/* + *-------------------------------------------------------------- + * + * CreateBitmap -- + * + * This procedure is invoked to create a new bitmap + * item in a canvas. + * + * Results: + * A standard Tcl return value. If an error occurred in + * creating the item, then an error message is left in + * interp->result; in this case itemPtr is left uninitialized, + * so it can be safely freed by the caller. + * + * Side effects: + * A new bitmap item is created. + * + *-------------------------------------------------------------- + */ + +static int +CreateBitmap(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Canvas to hold new item. */ + Tk_Item *itemPtr; /* Record to hold new item; header + * has been initialized by caller. */ + int argc; /* Number of arguments in argv. */ + char **argv; /* Arguments describing rectangle. */ +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tk_PathName(Tk_CanvasTkwin(canvas)), " create ", + itemPtr->typePtr->name, " x y ?options?\"", + (char *) NULL); + return TCL_ERROR; + } + + /* + * Initialize item's record. + */ + + bmapPtr->anchor = TK_ANCHOR_CENTER; + bmapPtr->bitmap = None; + bmapPtr->fgColor = NULL; + bmapPtr->bgColor = NULL; + bmapPtr->gc = None; + + /* + * Process the arguments to fill in the item record. + */ + + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], &bmapPtr->x) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], &bmapPtr->y) + != TCL_OK)) { + return TCL_ERROR; + } + + if (ConfigureBitmap(interp, canvas, itemPtr, argc-2, argv+2, 0) != TCL_OK) { + DeleteBitmap(canvas, itemPtr, Tk_Display(Tk_CanvasTkwin(canvas))); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * BitmapCoords -- + * + * This procedure is invoked to process the "coords" widget + * command on bitmap items. See the user documentation for + * details on what it does. + * + * Results: + * Returns TCL_OK or TCL_ERROR, and sets interp->result. + * + * Side effects: + * The coordinates for the given item may be changed. + * + *-------------------------------------------------------------- + */ + +static int +BitmapCoords(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item whose coordinates are to be + * read or modified. */ + int argc; /* Number of coordinates supplied in + * argv. */ + char **argv; /* Array of coordinates: x1, y1, + * x2, y2, ... */ +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + char x[TCL_DOUBLE_SPACE], y[TCL_DOUBLE_SPACE]; + + if (argc == 0) { + Tcl_PrintDouble(interp, bmapPtr->x, x); + Tcl_PrintDouble(interp, bmapPtr->y, y); + Tcl_AppendResult(interp, x, " ", y, (char *) NULL); + } else if (argc == 2) { + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], &bmapPtr->x) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], &bmapPtr->y) + != TCL_OK)) { + return TCL_ERROR; + } + ComputeBitmapBbox(canvas, bmapPtr); + } else { + sprintf(interp->result, + "wrong # coordinates: expected 0 or 2, got %d", argc); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ConfigureBitmap -- + * + * This procedure is invoked to configure various aspects + * of a bitmap item, such as its anchor position. + * + * Results: + * A standard Tcl result code. If an error occurs, then + * an error message is left in interp->result. + * + * Side effects: + * Configuration information may be set for itemPtr. + * + *-------------------------------------------------------------- + */ + +static int +ConfigureBitmap(interp, canvas, itemPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Bitmap item to reconfigure. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Arguments describing things to configure. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + XGCValues gcValues; + GC newGC; + Tk_Window tkwin; + unsigned long mask; + + tkwin = Tk_CanvasTkwin(canvas); + if (Tk_ConfigureWidget(interp, tkwin, configSpecs, argc, argv, + (char *) bmapPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few of the options require additional processing, such as those + * that determine the graphics context. + */ + + gcValues.foreground = bmapPtr->fgColor->pixel; + mask = GCForeground; + if (bmapPtr->bgColor != NULL) { + gcValues.background = bmapPtr->bgColor->pixel; + mask |= GCBackground; + } else { + gcValues.clip_mask = bmapPtr->bitmap; + mask |= GCClipMask; + } + newGC = Tk_GetGC(tkwin, mask, &gcValues); + if (bmapPtr->gc != None) { + Tk_FreeGC(Tk_Display(tkwin), bmapPtr->gc); + } + bmapPtr->gc = newGC; + + ComputeBitmapBbox(canvas, bmapPtr); + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * DeleteBitmap -- + * + * This procedure is called to clean up the data structure + * associated with a bitmap item. + * + * Results: + * None. + * + * Side effects: + * Resources associated with itemPtr are released. + * + *-------------------------------------------------------------- + */ + +static void +DeleteBitmap(canvas, itemPtr, display) + Tk_Canvas canvas; /* Info about overall canvas widget. */ + Tk_Item *itemPtr; /* Item that is being deleted. */ + Display *display; /* Display containing window for + * canvas. */ +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + + if (bmapPtr->bitmap != None) { + Tk_FreeBitmap(display, bmapPtr->bitmap); + } + if (bmapPtr->fgColor != NULL) { + Tk_FreeColor(bmapPtr->fgColor); + } + if (bmapPtr->bgColor != NULL) { + Tk_FreeColor(bmapPtr->bgColor); + } + if (bmapPtr->gc != NULL) { + Tk_FreeGC(display, bmapPtr->gc); + } +} + +/* + *-------------------------------------------------------------- + * + * ComputeBitmapBbox -- + * + * This procedure is invoked to compute the bounding box of + * all the pixels that may be drawn as part of a bitmap item. + * This procedure is where the child bitmap's placement is + * computed. + * + * Results: + * None. + * + * Side effects: + * The fields x1, y1, x2, and y2 are updated in the header + * for itemPtr. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +ComputeBitmapBbox(canvas, bmapPtr) + Tk_Canvas canvas; /* Canvas that contains item. */ + BitmapItem *bmapPtr; /* Item whose bbox is to be + * recomputed. */ +{ + int width, height; + int x, y; + + x = (int) (bmapPtr->x + ((bmapPtr->x >= 0) ? 0.5 : - 0.5)); + y = (int) (bmapPtr->y + ((bmapPtr->y >= 0) ? 0.5 : - 0.5)); + + if (bmapPtr->bitmap == None) { + bmapPtr->header.x1 = bmapPtr->header.x2 = x; + bmapPtr->header.y1 = bmapPtr->header.y2 = y; + return; + } + + /* + * Compute location and size of bitmap, using anchor information. + */ + + Tk_SizeOfBitmap(Tk_Display(Tk_CanvasTkwin(canvas)), bmapPtr->bitmap, + &width, &height); + switch (bmapPtr->anchor) { + case TK_ANCHOR_N: + x -= width/2; + break; + case TK_ANCHOR_NE: + x -= width; + break; + case TK_ANCHOR_E: + x -= width; + y -= height/2; + break; + case TK_ANCHOR_SE: + x -= width; + y -= height; + break; + case TK_ANCHOR_S: + x -= width/2; + y -= height; + break; + case TK_ANCHOR_SW: + y -= height; + break; + case TK_ANCHOR_W: + y -= height/2; + break; + case TK_ANCHOR_NW: + break; + case TK_ANCHOR_CENTER: + x -= width/2; + y -= height/2; + break; + } + + /* + * Store the information in the item header. + */ + + bmapPtr->header.x1 = x; + bmapPtr->header.y1 = y; + bmapPtr->header.x2 = x + width; + bmapPtr->header.y2 = y + height; +} + +/* + *-------------------------------------------------------------- + * + * DisplayBitmap -- + * + * This procedure is invoked to draw a bitmap item in a given + * drawable. + * + * Results: + * None. + * + * Side effects: + * ItemPtr is drawn in drawable using the transformation + * information in canvas. + * + *-------------------------------------------------------------- + */ + +static void +DisplayBitmap(canvas, itemPtr, display, drawable, x, y, width, height) + Tk_Canvas canvas; /* Canvas that contains item. */ + Tk_Item *itemPtr; /* Item to be displayed. */ + Display *display; /* Display on which to draw item. */ + Drawable drawable; /* Pixmap or window in which to draw + * item. */ + int x, y, width, height; /* Describes region of canvas that + * must be redisplayed (not used). */ +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + int bmapX, bmapY, bmapWidth, bmapHeight; + short drawableX, drawableY; + + /* + * If the area being displayed doesn't cover the whole bitmap, + * then only redisplay the part of the bitmap that needs + * redisplay. + */ + + if (bmapPtr->bitmap != None) { + if (x > bmapPtr->header.x1) { + bmapX = x - bmapPtr->header.x1; + bmapWidth = bmapPtr->header.x2 - x; + } else { + bmapX = 0; + if ((x+width) < bmapPtr->header.x2) { + bmapWidth = x + width - bmapPtr->header.x1; + } else { + bmapWidth = bmapPtr->header.x2 - bmapPtr->header.x1; + } + } + if (y > bmapPtr->header.y1) { + bmapY = y - bmapPtr->header.y1; + bmapHeight = bmapPtr->header.y2 - y; + } else { + bmapY = 0; + if ((y+height) < bmapPtr->header.y2) { + bmapHeight = y + height - bmapPtr->header.y1; + } else { + bmapHeight = bmapPtr->header.y2 - bmapPtr->header.y1; + } + } + Tk_CanvasDrawableCoords(canvas, + (double) (bmapPtr->header.x1 + bmapX), + (double) (bmapPtr->header.y1 + bmapY), + &drawableX, &drawableY); + + /* + * Must modify the mask origin within the graphics context + * to line up with the bitmap's origin (in order to make + * bitmaps with "-background {}" work right). + */ + + XSetClipOrigin(display, bmapPtr->gc, drawableX - bmapX, + drawableY - bmapY); + XCopyPlane(display, bmapPtr->bitmap, drawable, + bmapPtr->gc, bmapX, bmapY, (unsigned int) bmapWidth, + (unsigned int) bmapHeight, drawableX, drawableY, 1); + } +} + +/* + *-------------------------------------------------------------- + * + * BitmapToPoint -- + * + * Computes the distance from a given point to a given + * rectangle, in canvas units. + * + * Results: + * The return value is 0 if the point whose x and y coordinates + * are coordPtr[0] and coordPtr[1] is inside the bitmap. If the + * point isn't inside the bitmap then the return value is the + * distance from the point to the bitmap. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static double +BitmapToPoint(canvas, itemPtr, coordPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against point. */ + double *coordPtr; /* Pointer to x and y coordinates. */ +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + double x1, x2, y1, y2, xDiff, yDiff; + + x1 = bmapPtr->header.x1; + y1 = bmapPtr->header.y1; + x2 = bmapPtr->header.x2; + y2 = bmapPtr->header.y2; + + /* + * Point is outside rectangle. + */ + + if (coordPtr[0] < x1) { + xDiff = x1 - coordPtr[0]; + } else if (coordPtr[0] > x2) { + xDiff = coordPtr[0] - x2; + } else { + xDiff = 0; + } + + if (coordPtr[1] < y1) { + yDiff = y1 - coordPtr[1]; + } else if (coordPtr[1] > y2) { + yDiff = coordPtr[1] - y2; + } else { + yDiff = 0; + } + + return hypot(xDiff, yDiff); +} + +/* + *-------------------------------------------------------------- + * + * BitmapToArea -- + * + * This procedure is called to determine whether an item + * lies entirely inside, entirely outside, or overlapping + * a given rectangle. + * + * Results: + * -1 is returned if the item is entirely outside the area + * given by rectPtr, 0 if it overlaps, and 1 if it is entirely + * inside the given area. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +BitmapToArea(canvas, itemPtr, rectPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against rectangle. */ + double *rectPtr; /* Pointer to array of four coordinates + * (x1, y1, x2, y2) describing rectangular + * area. */ +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + + if ((rectPtr[2] <= bmapPtr->header.x1) + || (rectPtr[0] >= bmapPtr->header.x2) + || (rectPtr[3] <= bmapPtr->header.y1) + || (rectPtr[1] >= bmapPtr->header.y2)) { + return -1; + } + if ((rectPtr[0] <= bmapPtr->header.x1) + && (rectPtr[1] <= bmapPtr->header.y1) + && (rectPtr[2] >= bmapPtr->header.x2) + && (rectPtr[3] >= bmapPtr->header.y2)) { + return 1; + } + return 0; +} + +/* + *-------------------------------------------------------------- + * + * ScaleBitmap -- + * + * This procedure is invoked to rescale a bitmap item in a + * canvas. It is one of the standard item procedures for + * bitmap items, and is invoked by the generic canvas code. + * + * Results: + * None. + * + * Side effects: + * The item referred to by itemPtr is rescaled so that the + * following transformation is applied to all point coordinates: + * x' = originX + scaleX*(x-originX) + * y' = originY + scaleY*(y-originY) + * + *-------------------------------------------------------------- + */ + +static void +ScaleBitmap(canvas, itemPtr, originX, originY, scaleX, scaleY) + Tk_Canvas canvas; /* Canvas containing rectangle. */ + Tk_Item *itemPtr; /* Rectangle to be scaled. */ + double originX, originY; /* Origin about which to scale item. */ + double scaleX; /* Amount to scale in X direction. */ + double scaleY; /* Amount to scale in Y direction. */ +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + + bmapPtr->x = originX + scaleX*(bmapPtr->x - originX); + bmapPtr->y = originY + scaleY*(bmapPtr->y - originY); + ComputeBitmapBbox(canvas, bmapPtr); +} + +/* + *-------------------------------------------------------------- + * + * TranslateBitmap -- + * + * This procedure is called to move an item by a given amount. + * + * Results: + * None. + * + * Side effects: + * The position of the item is offset by (xDelta, yDelta), and + * the bounding box is updated in the generic part of the item + * structure. + * + *-------------------------------------------------------------- + */ + +static void +TranslateBitmap(canvas, itemPtr, deltaX, deltaY) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item that is being moved. */ + double deltaX, deltaY; /* Amount by which item is to be + * moved. */ +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + + bmapPtr->x += deltaX; + bmapPtr->y += deltaY; + ComputeBitmapBbox(canvas, bmapPtr); +} + +/* + *-------------------------------------------------------------- + * + * BitmapToPostscript -- + * + * This procedure is called to generate Postscript for + * bitmap items. + * + * Results: + * The return value is a standard Tcl result. If an error + * occurs in generating Postscript then an error message is + * left in interp->result, replacing whatever used to be there. + * If no error occurs, then Postscript for the item is appended + * to the result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +BitmapToPostscript(interp, canvas, itemPtr, prepass) + Tcl_Interp *interp; /* Leave Postscript or error message + * here. */ + Tk_Canvas canvas; /* Information about overall canvas. */ + Tk_Item *itemPtr; /* Item for which Postscript is + * wanted. */ + int prepass; /* 1 means this is a prepass to + * collect font information; 0 means + * final Postscript is being created. */ +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + double x, y; + int width, height, rowsAtOnce, rowsThisTime; + int curRow; + char buffer[200]; + + if (bmapPtr->bitmap == None) { + return TCL_OK; + } + + /* + * Compute the coordinates of the lower-left corner of the bitmap, + * taking into account the anchor position for the bitmp. + */ + + x = bmapPtr->x; + y = Tk_CanvasPsY(canvas, bmapPtr->y); + Tk_SizeOfBitmap(Tk_Display(Tk_CanvasTkwin(canvas)), bmapPtr->bitmap, + &width, &height); + switch (bmapPtr->anchor) { + case TK_ANCHOR_NW: y -= height; break; + case TK_ANCHOR_N: x -= width/2.0; y -= height; break; + case TK_ANCHOR_NE: x -= width; y -= height; break; + case TK_ANCHOR_E: x -= width; y -= height/2.0; break; + case TK_ANCHOR_SE: x -= width; break; + case TK_ANCHOR_S: x -= width/2.0; break; + case TK_ANCHOR_SW: break; + case TK_ANCHOR_W: y -= height/2.0; break; + case TK_ANCHOR_CENTER: x -= width/2.0; y -= height/2.0; break; + } + + /* + * Color the background, if there is one. + */ + + if (bmapPtr->bgColor != NULL) { + sprintf(buffer, + "%.15g %.15g moveto %d 0 rlineto 0 %d rlineto %d %s\n", + x, y, width, height, -width,"0 rlineto closepath"); + Tcl_AppendResult(interp, buffer, (char *) NULL); + if (Tk_CanvasPsColor(interp, canvas, bmapPtr->bgColor) != TCL_OK) { + return TCL_ERROR; + } + Tcl_AppendResult(interp, "fill\n", (char *) NULL); + } + + /* + * Draw the bitmap, if there is a foreground color. If the bitmap + * is very large, then chop it up into multiple bitmaps, each + * consisting of one or more rows. This is needed because Postscript + * can't handle single strings longer than 64 KBytes long. + */ + + if (bmapPtr->fgColor != NULL) { + if (Tk_CanvasPsColor(interp, canvas, bmapPtr->fgColor) != TCL_OK) { + return TCL_ERROR; + } + if (width > 60000) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "can't generate Postscript", + " for bitmaps more than 60000 pixels wide", + (char *) NULL); + return TCL_ERROR; + } + rowsAtOnce = 60000/width; + if (rowsAtOnce < 1) { + rowsAtOnce = 1; + } + sprintf(buffer, "%.15g %.15g translate\n", x, y+height); + Tcl_AppendResult(interp, buffer, (char *) NULL); + for (curRow = 0; curRow < height; curRow += rowsAtOnce) { + rowsThisTime = rowsAtOnce; + if (rowsThisTime > (height - curRow)) { + rowsThisTime = height - curRow; + } + sprintf(buffer, "0 -%.15g translate\n%d %d true matrix {\n", + (double) rowsThisTime, width, rowsThisTime); + Tcl_AppendResult(interp, buffer, (char *) NULL); + if (Tk_CanvasPsBitmap(interp, canvas, bmapPtr->bitmap, + 0, curRow, width, rowsThisTime) != TCL_OK) { + return TCL_ERROR; + } + Tcl_AppendResult(interp, "\n} imagemask\n", (char *) NULL); + } + } + return TCL_OK; +} diff --git a/generic/tkCanvImg.c b/generic/tkCanvImg.c new file mode 100644 index 0000000..55169f7 --- /dev/null +++ b/generic/tkCanvImg.c @@ -0,0 +1,677 @@ +/* + * tkCanvImg.c -- + * + * This file implements image items for canvas widgets. + * + * Copyright (c) 1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvImg.c 1.18 96/05/03 10:49:09 + */ + +#include <stdio.h> +#include "tkInt.h" +#include "tkPort.h" +#include "tkCanvas.h" + +/* + * The structure below defines the record for each image item. + */ + +typedef struct ImageItem { + Tk_Item header; /* Generic stuff that's the same for all + * types. MUST BE FIRST IN STRUCTURE. */ + Tk_Canvas canvas; /* Canvas containing the image. */ + double x, y; /* Coordinates of positioning point for + * image. */ + Tk_Anchor anchor; /* Where to anchor image relative to + * (x,y). */ + char *imageString; /* String describing -image option (malloc-ed). + * NULL means no image right now. */ + Tk_Image image; /* Image to display in window, or NULL if + * no image at present. */ +} ImageItem; + +/* + * Information used for parsing configuration specs: + */ + +static Tk_CustomOption tagsOption = {Tk_CanvasTagsParseProc, + Tk_CanvasTagsPrintProc, (ClientData) NULL +}; + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_ANCHOR, "-anchor", (char *) NULL, (char *) NULL, + "center", Tk_Offset(ImageItem, anchor), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_STRING, "-image", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(ImageItem, imageString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_CUSTOM, "-tags", (char *) NULL, (char *) NULL, + (char *) NULL, 0, TK_CONFIG_NULL_OK, &tagsOption}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Prototypes for procedures defined in this file: + */ + +static void ImageChangedProc _ANSI_ARGS_((ClientData clientData, + int x, int y, int width, int height, int imgWidth, + int imgHeight)); +static int ImageCoords _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv)); +static int ImageToArea _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *rectPtr)); +static double ImageToPoint _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *coordPtr)); +static void ComputeImageBbox _ANSI_ARGS_((Tk_Canvas canvas, + ImageItem *imgPtr)); +static int ConfigureImage _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv, int flags)); +static int CreateImage _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, struct Tk_Item *itemPtr, + int argc, char **argv)); +static void DeleteImage _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display)); +static void DisplayImage _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display, Drawable dst, + int x, int y, int width, int height)); +static void ScaleImage _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double originX, double originY, + double scaleX, double scaleY)); +static void TranslateImage _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double deltaX, double deltaY)); + +/* + * The structures below defines the image item type in terms of + * procedures that can be invoked by generic item code. + */ + +Tk_ItemType tkImageType = { + "image", /* name */ + sizeof(ImageItem), /* itemSize */ + CreateImage, /* createProc */ + configSpecs, /* configSpecs */ + ConfigureImage, /* configureProc */ + ImageCoords, /* coordProc */ + DeleteImage, /* deleteProc */ + DisplayImage, /* displayProc */ + 0, /* alwaysRedraw */ + ImageToPoint, /* pointProc */ + ImageToArea, /* areaProc */ + (Tk_ItemPostscriptProc *) NULL, /* postscriptProc */ + ScaleImage, /* scaleProc */ + TranslateImage, /* translateProc */ + (Tk_ItemIndexProc *) NULL, /* indexProc */ + (Tk_ItemCursorProc *) NULL, /* icursorProc */ + (Tk_ItemSelectionProc *) NULL, /* selectionProc */ + (Tk_ItemInsertProc *) NULL, /* insertProc */ + (Tk_ItemDCharsProc *) NULL, /* dTextProc */ + (Tk_ItemType *) NULL /* nextPtr */ +}; + +/* + *-------------------------------------------------------------- + * + * CreateImage -- + * + * This procedure is invoked to create a new image + * item in a canvas. + * + * Results: + * A standard Tcl return value. If an error occurred in + * creating the item, then an error message is left in + * interp->result; in this case itemPtr is left uninitialized, + * so it can be safely freed by the caller. + * + * Side effects: + * A new image item is created. + * + *-------------------------------------------------------------- + */ + +static int +CreateImage(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Canvas to hold new item. */ + Tk_Item *itemPtr; /* Record to hold new item; header + * has been initialized by caller. */ + int argc; /* Number of arguments in argv. */ + char **argv; /* Arguments describing rectangle. */ +{ + ImageItem *imgPtr = (ImageItem *) itemPtr; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tk_PathName(Tk_CanvasTkwin(canvas)), " create ", + itemPtr->typePtr->name, " x y ?options?\"", + (char *) NULL); + return TCL_ERROR; + } + + /* + * Initialize item's record. + */ + + imgPtr->canvas = canvas; + imgPtr->anchor = TK_ANCHOR_CENTER; + imgPtr->imageString = NULL; + imgPtr->image = NULL; + + /* + * Process the arguments to fill in the item record. + */ + + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], &imgPtr->x) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], &imgPtr->y) + != TCL_OK)) { + return TCL_ERROR; + } + + if (ConfigureImage(interp, canvas, itemPtr, argc-2, argv+2, 0) != TCL_OK) { + DeleteImage(canvas, itemPtr, Tk_Display(Tk_CanvasTkwin(canvas))); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ImageCoords -- + * + * This procedure is invoked to process the "coords" widget + * command on image items. See the user documentation for + * details on what it does. + * + * Results: + * Returns TCL_OK or TCL_ERROR, and sets interp->result. + * + * Side effects: + * The coordinates for the given item may be changed. + * + *-------------------------------------------------------------- + */ + +static int +ImageCoords(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item whose coordinates are to be + * read or modified. */ + int argc; /* Number of coordinates supplied in + * argv. */ + char **argv; /* Array of coordinates: x1, y1, + * x2, y2, ... */ +{ + ImageItem *imgPtr = (ImageItem *) itemPtr; + char x[TCL_DOUBLE_SPACE], y[TCL_DOUBLE_SPACE]; + + if (argc == 0) { + Tcl_PrintDouble(interp, imgPtr->x, x); + Tcl_PrintDouble(interp, imgPtr->y, y); + Tcl_AppendResult(interp, x, " ", y, (char *) NULL); + } else if (argc == 2) { + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], &imgPtr->x) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], + &imgPtr->y) != TCL_OK)) { + return TCL_ERROR; + } + ComputeImageBbox(canvas, imgPtr); + } else { + sprintf(interp->result, + "wrong # coordinates: expected 0 or 2, got %d", argc); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ConfigureImage -- + * + * This procedure is invoked to configure various aspects + * of an image item, such as its anchor position. + * + * Results: + * A standard Tcl result code. If an error occurs, then + * an error message is left in interp->result. + * + * Side effects: + * Configuration information may be set for itemPtr. + * + *-------------------------------------------------------------- + */ + +static int +ConfigureImage(interp, canvas, itemPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Image item to reconfigure. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Arguments describing things to configure. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + ImageItem *imgPtr = (ImageItem *) itemPtr; + Tk_Window tkwin; + Tk_Image image; + + tkwin = Tk_CanvasTkwin(canvas); + if (Tk_ConfigureWidget(interp, tkwin, configSpecs, argc, + argv, (char *) imgPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * Create the image. Save the old image around and don't free it + * until after the new one is allocated. This keeps the reference + * count from going to zero so the image doesn't have to be recreated + * if it hasn't changed. + */ + + if (imgPtr->imageString != NULL) { + image = Tk_GetImage(interp, tkwin, imgPtr->imageString, + ImageChangedProc, (ClientData) imgPtr); + if (image == NULL) { + return TCL_ERROR; + } + } else { + image = NULL; + } + if (imgPtr->image != NULL) { + Tk_FreeImage(imgPtr->image); + } + imgPtr->image = image; + ComputeImageBbox(canvas, imgPtr); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * DeleteImage -- + * + * This procedure is called to clean up the data structure + * associated with a image item. + * + * Results: + * None. + * + * Side effects: + * Resources associated with itemPtr are released. + * + *-------------------------------------------------------------- + */ + +static void +DeleteImage(canvas, itemPtr, display) + Tk_Canvas canvas; /* Info about overall canvas widget. */ + Tk_Item *itemPtr; /* Item that is being deleted. */ + Display *display; /* Display containing window for + * canvas. */ +{ + ImageItem *imgPtr = (ImageItem *) itemPtr; + + if (imgPtr->imageString != NULL) { + ckfree(imgPtr->imageString); + } + if (imgPtr->image != NULL) { + Tk_FreeImage(imgPtr->image); + } +} + +/* + *-------------------------------------------------------------- + * + * ComputeImageBbox -- + * + * This procedure is invoked to compute the bounding box of + * all the pixels that may be drawn as part of a image item. + * This procedure is where the child image's placement is + * computed. + * + * Results: + * None. + * + * Side effects: + * The fields x1, y1, x2, and y2 are updated in the header + * for itemPtr. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +ComputeImageBbox(canvas, imgPtr) + Tk_Canvas canvas; /* Canvas that contains item. */ + ImageItem *imgPtr; /* Item whose bbox is to be + * recomputed. */ +{ + int width, height; + int x, y; + + x = (int) (imgPtr->x + ((imgPtr->x >= 0) ? 0.5 : - 0.5)); + y = (int) (imgPtr->y + ((imgPtr->y >= 0) ? 0.5 : - 0.5)); + + if (imgPtr->image == None) { + imgPtr->header.x1 = imgPtr->header.x2 = x; + imgPtr->header.y1 = imgPtr->header.y2 = y; + return; + } + + /* + * Compute location and size of image, using anchor information. + */ + + Tk_SizeOfImage(imgPtr->image, &width, &height); + switch (imgPtr->anchor) { + case TK_ANCHOR_N: + x -= width/2; + break; + case TK_ANCHOR_NE: + x -= width; + break; + case TK_ANCHOR_E: + x -= width; + y -= height/2; + break; + case TK_ANCHOR_SE: + x -= width; + y -= height; + break; + case TK_ANCHOR_S: + x -= width/2; + y -= height; + break; + case TK_ANCHOR_SW: + y -= height; + break; + case TK_ANCHOR_W: + y -= height/2; + break; + case TK_ANCHOR_NW: + break; + case TK_ANCHOR_CENTER: + x -= width/2; + y -= height/2; + break; + } + + /* + * Store the information in the item header. + */ + + imgPtr->header.x1 = x; + imgPtr->header.y1 = y; + imgPtr->header.x2 = x + width; + imgPtr->header.y2 = y + height; +} + +/* + *-------------------------------------------------------------- + * + * DisplayImage -- + * + * This procedure is invoked to draw a image item in a given + * drawable. + * + * Results: + * None. + * + * Side effects: + * ItemPtr is drawn in drawable using the transformation + * information in canvas. + * + *-------------------------------------------------------------- + */ + +static void +DisplayImage(canvas, itemPtr, display, drawable, x, y, width, height) + Tk_Canvas canvas; /* Canvas that contains item. */ + Tk_Item *itemPtr; /* Item to be displayed. */ + Display *display; /* Display on which to draw item. */ + Drawable drawable; /* Pixmap or window in which to draw + * item. */ + int x, y, width, height; /* Describes region of canvas that + * must be redisplayed (not used). */ +{ + ImageItem *imgPtr = (ImageItem *) itemPtr; + short drawableX, drawableY; + + if (imgPtr->image == NULL) { + return; + } + + /* + * Translate the coordinates to those of the image, then redisplay it. + */ + + Tk_CanvasDrawableCoords(canvas, (double) x, (double) y, + &drawableX, &drawableY); + Tk_RedrawImage(imgPtr->image, x - imgPtr->header.x1, y - imgPtr->header.y1, + width, height, drawable, drawableX, drawableY); +} + +/* + *-------------------------------------------------------------- + * + * ImageToPoint -- + * + * Computes the distance from a given point to a given + * rectangle, in canvas units. + * + * Results: + * The return value is 0 if the point whose x and y coordinates + * are coordPtr[0] and coordPtr[1] is inside the image. If the + * point isn't inside the image then the return value is the + * distance from the point to the image. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static double +ImageToPoint(canvas, itemPtr, coordPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against point. */ + double *coordPtr; /* Pointer to x and y coordinates. */ +{ + ImageItem *imgPtr = (ImageItem *) itemPtr; + double x1, x2, y1, y2, xDiff, yDiff; + + x1 = imgPtr->header.x1; + y1 = imgPtr->header.y1; + x2 = imgPtr->header.x2; + y2 = imgPtr->header.y2; + + /* + * Point is outside rectangle. + */ + + if (coordPtr[0] < x1) { + xDiff = x1 - coordPtr[0]; + } else if (coordPtr[0] > x2) { + xDiff = coordPtr[0] - x2; + } else { + xDiff = 0; + } + + if (coordPtr[1] < y1) { + yDiff = y1 - coordPtr[1]; + } else if (coordPtr[1] > y2) { + yDiff = coordPtr[1] - y2; + } else { + yDiff = 0; + } + + return hypot(xDiff, yDiff); +} + +/* + *-------------------------------------------------------------- + * + * ImageToArea -- + * + * This procedure is called to determine whether an item + * lies entirely inside, entirely outside, or overlapping + * a given rectangle. + * + * Results: + * -1 is returned if the item is entirely outside the area + * given by rectPtr, 0 if it overlaps, and 1 if it is entirely + * inside the given area. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +ImageToArea(canvas, itemPtr, rectPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against rectangle. */ + double *rectPtr; /* Pointer to array of four coordinates + * (x1, y1, x2, y2) describing rectangular + * area. */ +{ + ImageItem *imgPtr = (ImageItem *) itemPtr; + + if ((rectPtr[2] <= imgPtr->header.x1) + || (rectPtr[0] >= imgPtr->header.x2) + || (rectPtr[3] <= imgPtr->header.y1) + || (rectPtr[1] >= imgPtr->header.y2)) { + return -1; + } + if ((rectPtr[0] <= imgPtr->header.x1) + && (rectPtr[1] <= imgPtr->header.y1) + && (rectPtr[2] >= imgPtr->header.x2) + && (rectPtr[3] >= imgPtr->header.y2)) { + return 1; + } + return 0; +} + +/* + *-------------------------------------------------------------- + * + * ScaleImage -- + * + * This procedure is invoked to rescale an item. + * + * Results: + * None. + * + * Side effects: + * The item referred to by itemPtr is rescaled so that the + * following transformation is applied to all point coordinates: + * x' = originX + scaleX*(x-originX) + * y' = originY + scaleY*(y-originY) + * + *-------------------------------------------------------------- + */ + +static void +ScaleImage(canvas, itemPtr, originX, originY, scaleX, scaleY) + Tk_Canvas canvas; /* Canvas containing rectangle. */ + Tk_Item *itemPtr; /* Rectangle to be scaled. */ + double originX, originY; /* Origin about which to scale rect. */ + double scaleX; /* Amount to scale in X direction. */ + double scaleY; /* Amount to scale in Y direction. */ +{ + ImageItem *imgPtr = (ImageItem *) itemPtr; + + imgPtr->x = originX + scaleX*(imgPtr->x - originX); + imgPtr->y = originY + scaleY*(imgPtr->y - originY); + ComputeImageBbox(canvas, imgPtr); +} + +/* + *-------------------------------------------------------------- + * + * TranslateImage -- + * + * This procedure is called to move an item by a given amount. + * + * Results: + * None. + * + * Side effects: + * The position of the item is offset by (xDelta, yDelta), and + * the bounding box is updated in the generic part of the item + * structure. + * + *-------------------------------------------------------------- + */ + +static void +TranslateImage(canvas, itemPtr, deltaX, deltaY) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item that is being moved. */ + double deltaX, deltaY; /* Amount by which item is to be + * moved. */ +{ + ImageItem *imgPtr = (ImageItem *) itemPtr; + + imgPtr->x += deltaX; + imgPtr->y += deltaY; + ComputeImageBbox(canvas, imgPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ImageChangedProc -- + * + * This procedure is invoked by the image code whenever the manager + * for an image does something that affects the image's size or + * how it is displayed. + * + * Results: + * None. + * + * Side effects: + * Arranges for the canvas to get redisplayed. + * + *---------------------------------------------------------------------- + */ + +static void +ImageChangedProc(clientData, x, y, width, height, imgWidth, imgHeight) + ClientData clientData; /* Pointer to canvas item for image. */ + int x, y; /* Upper left pixel (within image) + * that must be redisplayed. */ + int width, height; /* Dimensions of area to redisplay + * (may be <= 0). */ + int imgWidth, imgHeight; /* New dimensions of image. */ +{ + ImageItem *imgPtr = (ImageItem *) clientData; + + /* + * If the image's size changed and it's not anchored at its + * northwest corner then just redisplay the entire area of the + * image. This is a bit over-conservative, but we need to do + * something because a size change also means a position change. + */ + + if (((imgPtr->header.x2 - imgPtr->header.x1) != imgWidth) + || ((imgPtr->header.y2 - imgPtr->header.y1) != imgHeight)) { + x = y = 0; + width = imgWidth; + height = imgHeight; + Tk_CanvasEventuallyRedraw(imgPtr->canvas, imgPtr->header.x1, + imgPtr->header.y1, imgPtr->header.x2, imgPtr->header.y2); + } + ComputeImageBbox(imgPtr->canvas, imgPtr); + Tk_CanvasEventuallyRedraw(imgPtr->canvas, imgPtr->header.x1 + x, + imgPtr->header.y1 + y, (int) (imgPtr->header.x1 + x + width), + (int) (imgPtr->header.y1 + y + height)); +} diff --git a/generic/tkCanvLine.c b/generic/tkCanvLine.c new file mode 100644 index 0000000..97cd1f5 --- /dev/null +++ b/generic/tkCanvLine.c @@ -0,0 +1,1623 @@ +/* + * tkCanvLine.c -- + * + * This file implements line items for canvas widgets. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvLine.c 1.46 97/04/25 16:51:02 + */ + +#include <stdio.h> +#include "tkInt.h" +#include "tkPort.h" + +/* + * The structure below defines the record for each line item. + */ + +typedef struct LineItem { + Tk_Item header; /* Generic stuff that's the same for all + * types. MUST BE FIRST IN STRUCTURE. */ + Tk_Canvas canvas; /* Canvas containing item. Needed for + * parsing arrow shapes. */ + int numPoints; /* Number of points in line (always >= 2). */ + double *coordPtr; /* Pointer to malloc-ed array containing + * x- and y-coords of all points in line. + * X-coords are even-valued indices, y-coords + * are corresponding odd-valued indices. If + * the line has arrowheads then the first + * and last points have been adjusted to refer + * to the necks of the arrowheads rather than + * their tips. The actual endpoints are + * stored in the *firstArrowPtr and + * *lastArrowPtr, if they exist. */ + int width; /* Width of line. */ + XColor *fg; /* Foreground color for line. */ + Pixmap fillStipple; /* Stipple bitmap for filling line. */ + int capStyle; /* Cap style for line. */ + int joinStyle; /* Join style for line. */ + GC gc; /* Graphics context for filling line. */ + GC arrowGC; /* Graphics context for drawing arrowheads. */ + Tk_Uid arrow; /* Indicates whether or not to draw arrowheads: + * "none", "first", "last", or "both". */ + float arrowShapeA; /* Distance from tip of arrowhead to center. */ + float arrowShapeB; /* Distance from tip of arrowhead to trailing + * point, measured along shaft. */ + float arrowShapeC; /* Distance of trailing points from outside + * edge of shaft. */ + double *firstArrowPtr; /* Points to array of PTS_IN_ARROW points + * describing polygon for arrowhead at first + * point in line. First point of arrowhead + * is tip. Malloc'ed. NULL means no arrowhead + * at first point. */ + double *lastArrowPtr; /* Points to polygon for arrowhead at last + * point in line (PTS_IN_ARROW points, first + * of which is tip). Malloc'ed. NULL means + * no arrowhead at last point. */ + int smooth; /* Non-zero means draw line smoothed (i.e. + * with Bezier splines). */ + int splineSteps; /* Number of steps in each spline segment. */ +} LineItem; + +/* + * Number of points in an arrowHead: + */ + +#define PTS_IN_ARROW 6 + +/* + * Prototypes for procedures defined in this file: + */ + +static int ArrowheadPostscript _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, LineItem *linePtr, + double *arrowPtr)); +static void ComputeLineBbox _ANSI_ARGS_((Tk_Canvas canvas, + LineItem *linePtr)); +static int ConfigureLine _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv, int flags)); +static int ConfigureArrows _ANSI_ARGS_((Tk_Canvas canvas, + LineItem *linePtr)); +static int CreateLine _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, struct Tk_Item *itemPtr, + int argc, char **argv)); +static void DeleteLine _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display)); +static void DisplayLine _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display, Drawable dst, + int x, int y, int width, int height)); +static int LineCoords _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, + int argc, char **argv)); +static int LineToArea _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *rectPtr)); +static double LineToPoint _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *coordPtr)); +static int LineToPostscript _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int prepass)); +static int ParseArrowShape _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, Tk_Window tkwin, char *value, + char *recordPtr, int offset)); +static char * PrintArrowShape _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin, char *recordPtr, int offset, + Tcl_FreeProc **freeProcPtr)); +static void ScaleLine _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double originX, double originY, + double scaleX, double scaleY)); +static void TranslateLine _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double deltaX, double deltaY)); + +/* + * Information used for parsing configuration specs. If you change any + * of the default strings, be sure to change the corresponding default + * values in CreateLine. + */ + +static Tk_CustomOption arrowShapeOption = {ParseArrowShape, + PrintArrowShape, (ClientData) NULL}; +static Tk_CustomOption tagsOption = {Tk_CanvasTagsParseProc, + Tk_CanvasTagsPrintProc, (ClientData) NULL +}; + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_UID, "-arrow", (char *) NULL, (char *) NULL, + "none", Tk_Offset(LineItem, arrow), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_CUSTOM, "-arrowshape", (char *) NULL, (char *) NULL, + "8 10 3", Tk_Offset(LineItem, arrowShapeA), + TK_CONFIG_DONT_SET_DEFAULT, &arrowShapeOption}, + {TK_CONFIG_CAP_STYLE, "-capstyle", (char *) NULL, (char *) NULL, + "butt", Tk_Offset(LineItem, capStyle), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_COLOR, "-fill", (char *) NULL, (char *) NULL, + "black", Tk_Offset(LineItem, fg), TK_CONFIG_NULL_OK}, + {TK_CONFIG_JOIN_STYLE, "-joinstyle", (char *) NULL, (char *) NULL, + "round", Tk_Offset(LineItem, joinStyle), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_BOOLEAN, "-smooth", (char *) NULL, (char *) NULL, + "0", Tk_Offset(LineItem, smooth), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_INT, "-splinesteps", (char *) NULL, (char *) NULL, + "12", Tk_Offset(LineItem, splineSteps), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_BITMAP, "-stipple", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(LineItem, fillStipple), TK_CONFIG_NULL_OK}, + {TK_CONFIG_CUSTOM, "-tags", (char *) NULL, (char *) NULL, + (char *) NULL, 0, TK_CONFIG_NULL_OK, &tagsOption}, + {TK_CONFIG_PIXELS, "-width", (char *) NULL, (char *) NULL, + "1", Tk_Offset(LineItem, width), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * The structures below defines the line item type by means + * of procedures that can be invoked by generic item code. + */ + +Tk_ItemType tkLineType = { + "line", /* name */ + sizeof(LineItem), /* itemSize */ + CreateLine, /* createProc */ + configSpecs, /* configSpecs */ + ConfigureLine, /* configureProc */ + LineCoords, /* coordProc */ + DeleteLine, /* deleteProc */ + DisplayLine, /* displayProc */ + 0, /* alwaysRedraw */ + LineToPoint, /* pointProc */ + LineToArea, /* areaProc */ + LineToPostscript, /* postscriptProc */ + ScaleLine, /* scaleProc */ + TranslateLine, /* translateProc */ + (Tk_ItemIndexProc *) NULL, /* indexProc */ + (Tk_ItemCursorProc *) NULL, /* icursorProc */ + (Tk_ItemSelectionProc *) NULL, /* selectionProc */ + (Tk_ItemInsertProc *) NULL, /* insertProc */ + (Tk_ItemDCharsProc *) NULL, /* dTextProc */ + (Tk_ItemType *) NULL /* nextPtr */ +}; + +/* + * The Tk_Uid's below refer to uids for the various arrow types: + */ + +static Tk_Uid noneUid = NULL; +static Tk_Uid firstUid = NULL; +static Tk_Uid lastUid = NULL; +static Tk_Uid bothUid = NULL; + +/* + * The definition below determines how large are static arrays + * used to hold spline points (splines larger than this have to + * have their arrays malloc-ed). + */ + +#define MAX_STATIC_POINTS 200 + +/* + *-------------------------------------------------------------- + * + * CreateLine -- + * + * This procedure is invoked to create a new line item in + * a canvas. + * + * Results: + * A standard Tcl return value. If an error occurred in + * creating the item, then an error message is left in + * interp->result; in this case itemPtr is left uninitialized, + * so it can be safely freed by the caller. + * + * Side effects: + * A new line item is created. + * + *-------------------------------------------------------------- + */ + +static int +CreateLine(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Canvas to hold new item. */ + Tk_Item *itemPtr; /* Record to hold new item; header + * has been initialized by caller. */ + int argc; /* Number of arguments in argv. */ + char **argv; /* Arguments describing line. */ +{ + LineItem *linePtr = (LineItem *) itemPtr; + int i; + + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tk_PathName(Tk_CanvasTkwin(canvas)), " create ", + itemPtr->typePtr->name, " x1 y1 x2 y2 ?x3 y3 ...? ?options?\"", + (char *) NULL); + return TCL_ERROR; + } + + /* + * Carry out initialization that is needed to set defaults and to + * allow proper cleanup after errors during the the remainder of + * this procedure. + */ + + linePtr->canvas = canvas; + linePtr->numPoints = 0; + linePtr->coordPtr = NULL; + linePtr->width = 1; + linePtr->fg = None; + linePtr->fillStipple = None; + linePtr->capStyle = CapButt; + linePtr->joinStyle = JoinRound; + linePtr->gc = None; + linePtr->arrowGC = None; + if (noneUid == NULL) { + noneUid = Tk_GetUid("none"); + firstUid = Tk_GetUid("first"); + lastUid = Tk_GetUid("last"); + bothUid = Tk_GetUid("both"); + } + linePtr->arrow = noneUid; + linePtr->arrowShapeA = (float)8.0; + linePtr->arrowShapeB = (float)10.0; + linePtr->arrowShapeC = (float)3.0; + linePtr->firstArrowPtr = NULL; + linePtr->lastArrowPtr = NULL; + linePtr->smooth = 0; + linePtr->splineSteps = 12; + + /* + * Count the number of points and then parse them into a point + * array. Leading arguments are assumed to be points if they + * start with a digit or a minus sign followed by a digit. + */ + + for (i = 4; i < (argc-1); i+=2) { + if ((!isdigit(UCHAR(argv[i][0]))) && + ((argv[i][0] != '-') + || ((argv[i][1] != '.') && !isdigit(UCHAR(argv[i][1]))))) { + break; + } + } + if (LineCoords(interp, canvas, itemPtr, i, argv) != TCL_OK) { + goto error; + } + if (ConfigureLine(interp, canvas, itemPtr, argc-i, argv+i, 0) == TCL_OK) { + return TCL_OK; + } + + error: + DeleteLine(canvas, itemPtr, Tk_Display(Tk_CanvasTkwin(canvas))); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * LineCoords -- + * + * This procedure is invoked to process the "coords" widget + * command on lines. See the user documentation for details + * on what it does. + * + * Results: + * Returns TCL_OK or TCL_ERROR, and sets interp->result. + * + * Side effects: + * The coordinates for the given item may be changed. + * + *-------------------------------------------------------------- + */ + +static int +LineCoords(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item whose coordinates are to be + * read or modified. */ + int argc; /* Number of coordinates supplied in + * argv. */ + char **argv; /* Array of coordinates: x1, y1, + * x2, y2, ... */ +{ + LineItem *linePtr = (LineItem *) itemPtr; + char buffer[TCL_DOUBLE_SPACE]; + int i, numPoints; + + if (argc == 0) { + double *coordPtr; + int numCoords; + + numCoords = 2*linePtr->numPoints; + if (linePtr->firstArrowPtr != NULL) { + coordPtr = linePtr->firstArrowPtr; + } else { + coordPtr = linePtr->coordPtr; + } + for (i = 0; i < numCoords; i++, coordPtr++) { + if (i == 2) { + coordPtr = linePtr->coordPtr+2; + } + if ((linePtr->lastArrowPtr != NULL) && (i == (numCoords-2))) { + coordPtr = linePtr->lastArrowPtr; + } + Tcl_PrintDouble(interp, *coordPtr, buffer); + Tcl_AppendElement(interp, buffer); + } + } else if (argc < 4) { + Tcl_AppendResult(interp, + "too few coordinates for line: must have at least 4", + (char *) NULL); + return TCL_ERROR; + } else if (argc & 1) { + Tcl_AppendResult(interp, + "odd number of coordinates specified for line", + (char *) NULL); + return TCL_ERROR; + } else { + numPoints = argc/2; + if (linePtr->numPoints != numPoints) { + if (linePtr->coordPtr != NULL) { + ckfree((char *) linePtr->coordPtr); + } + linePtr->coordPtr = (double *) ckalloc((unsigned) + (sizeof(double) * argc)); + linePtr->numPoints = numPoints; + } + for (i = argc-1; i >= 0; i--) { + if (Tk_CanvasGetCoord(interp, canvas, argv[i], + &linePtr->coordPtr[i]) != TCL_OK) { + return TCL_ERROR; + } + } + + /* + * Update arrowheads by throwing away any existing arrow-head + * information and calling ConfigureArrows to recompute it. + */ + + if (linePtr->firstArrowPtr != NULL) { + ckfree((char *) linePtr->firstArrowPtr); + linePtr->firstArrowPtr = NULL; + } + if (linePtr->lastArrowPtr != NULL) { + ckfree((char *) linePtr->lastArrowPtr); + linePtr->lastArrowPtr = NULL; + } + if (linePtr->arrow != noneUid) { + ConfigureArrows(canvas, linePtr); + } + ComputeLineBbox(canvas, linePtr); + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ConfigureLine -- + * + * This procedure is invoked to configure various aspects + * of a line item such as its background color. + * + * Results: + * A standard Tcl result code. If an error occurs, then + * an error message is left in interp->result. + * + * Side effects: + * Configuration information, such as colors and stipple + * patterns, may be set for itemPtr. + * + *-------------------------------------------------------------- + */ + +static int +ConfigureLine(interp, canvas, itemPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Line item to reconfigure. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Arguments describing things to configure. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + LineItem *linePtr = (LineItem *) itemPtr; + XGCValues gcValues; + GC newGC, arrowGC; + unsigned long mask; + Tk_Window tkwin; + + tkwin = Tk_CanvasTkwin(canvas); + if (Tk_ConfigureWidget(interp, tkwin, configSpecs, argc, argv, + (char *) linePtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few of the options require additional processing, such as + * graphics contexts. + */ + + if (linePtr->fg == NULL) { + newGC = arrowGC = None; + } else { + gcValues.foreground = linePtr->fg->pixel; + gcValues.join_style = linePtr->joinStyle; + if (linePtr->width < 0) { + linePtr->width = 1; + } + gcValues.line_width = linePtr->width; + mask = GCForeground|GCJoinStyle|GCLineWidth; + if (linePtr->fillStipple != None) { + gcValues.stipple = linePtr->fillStipple; + gcValues.fill_style = FillStippled; + mask |= GCStipple|GCFillStyle; + } + if (linePtr->arrow == noneUid) { + gcValues.cap_style = linePtr->capStyle; + mask |= GCCapStyle; + } + newGC = Tk_GetGC(tkwin, mask, &gcValues); + gcValues.line_width = 0; + arrowGC = Tk_GetGC(tkwin, mask, &gcValues); + } + if (linePtr->gc != None) { + Tk_FreeGC(Tk_Display(tkwin), linePtr->gc); + } + if (linePtr->arrowGC != None) { + Tk_FreeGC(Tk_Display(tkwin), linePtr->arrowGC); + } + linePtr->gc = newGC; + linePtr->arrowGC = arrowGC; + + /* + * Keep spline parameters within reasonable limits. + */ + + if (linePtr->splineSteps < 1) { + linePtr->splineSteps = 1; + } else if (linePtr->splineSteps > 100) { + linePtr->splineSteps = 100; + } + + /* + * Setup arrowheads, if needed. If arrowheads are turned off, + * restore the line's endpoints (they were shortened when the + * arrowheads were added). + */ + + if ((linePtr->firstArrowPtr != NULL) && (linePtr->arrow != firstUid) + && (linePtr->arrow != bothUid)) { + linePtr->coordPtr[0] = linePtr->firstArrowPtr[0]; + linePtr->coordPtr[1] = linePtr->firstArrowPtr[1]; + ckfree((char *) linePtr->firstArrowPtr); + linePtr->firstArrowPtr = NULL; + } + if ((linePtr->lastArrowPtr != NULL) && (linePtr->arrow != lastUid) + && (linePtr->arrow != bothUid)) { + int i; + + i = 2*(linePtr->numPoints-1); + linePtr->coordPtr[i] = linePtr->lastArrowPtr[0]; + linePtr->coordPtr[i+1] = linePtr->lastArrowPtr[1]; + ckfree((char *) linePtr->lastArrowPtr); + linePtr->lastArrowPtr = NULL; + } + if (linePtr->arrow != noneUid) { + if ((linePtr->arrow != firstUid) && (linePtr->arrow != lastUid) + && (linePtr->arrow != bothUid)) { + Tcl_AppendResult(interp, "bad arrow spec \"", + linePtr->arrow, "\": must be none, first, last, or both", + (char *) NULL); + linePtr->arrow = noneUid; + return TCL_ERROR; + } + ConfigureArrows(canvas, linePtr); + } + + /* + * Recompute bounding box for line. + */ + + ComputeLineBbox(canvas, linePtr); + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * DeleteLine -- + * + * This procedure is called to clean up the data structure + * associated with a line item. + * + * Results: + * None. + * + * Side effects: + * Resources associated with itemPtr are released. + * + *-------------------------------------------------------------- + */ + +static void +DeleteLine(canvas, itemPtr, display) + Tk_Canvas canvas; /* Info about overall canvas widget. */ + Tk_Item *itemPtr; /* Item that is being deleted. */ + Display *display; /* Display containing window for + * canvas. */ +{ + LineItem *linePtr = (LineItem *) itemPtr; + + if (linePtr->coordPtr != NULL) { + ckfree((char *) linePtr->coordPtr); + } + if (linePtr->fg != NULL) { + Tk_FreeColor(linePtr->fg); + } + if (linePtr->fillStipple != None) { + Tk_FreeBitmap(display, linePtr->fillStipple); + } + if (linePtr->gc != None) { + Tk_FreeGC(display, linePtr->gc); + } + if (linePtr->arrowGC != None) { + Tk_FreeGC(display, linePtr->arrowGC); + } + if (linePtr->firstArrowPtr != NULL) { + ckfree((char *) linePtr->firstArrowPtr); + } + if (linePtr->lastArrowPtr != NULL) { + ckfree((char *) linePtr->lastArrowPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * ComputeLineBbox -- + * + * This procedure is invoked to compute the bounding box of + * all the pixels that may be drawn as part of a line. + * + * Results: + * None. + * + * Side effects: + * The fields x1, y1, x2, and y2 are updated in the header + * for itemPtr. + * + *-------------------------------------------------------------- + */ + +static void +ComputeLineBbox(canvas, linePtr) + Tk_Canvas canvas; /* Canvas that contains item. */ + LineItem *linePtr; /* Item whose bbos is to be + * recomputed. */ +{ + double *coordPtr; + int i, width; + + coordPtr = linePtr->coordPtr; + linePtr->header.x1 = linePtr->header.x2 = (int) *coordPtr; + linePtr->header.y1 = linePtr->header.y2 = (int) coordPtr[1]; + + /* + * Compute the bounding box of all the points in the line, + * then expand in all directions by the line's width to take + * care of butting or rounded corners and projecting or + * rounded caps. This expansion is an overestimate (worst-case + * is square root of two over two) but it's simple. Don't do + * anything special for curves. This causes an additional + * overestimate in the bounding box, but is faster. + */ + + for (i = 1, coordPtr = linePtr->coordPtr+2; i < linePtr->numPoints; + i++, coordPtr += 2) { + TkIncludePoint((Tk_Item *) linePtr, coordPtr); + } + width = linePtr->width; + if (width < 1) { + width = 1; + } + linePtr->header.x1 -= width; + linePtr->header.x2 += width; + linePtr->header.y1 -= width; + linePtr->header.y2 += width; + + /* + * For mitered lines, make a second pass through all the points. + * Compute the locations of the two miter vertex points and add + * those into the bounding box. + */ + + if (linePtr->joinStyle == JoinMiter) { + for (i = linePtr->numPoints, coordPtr = linePtr->coordPtr; i >= 3; + i--, coordPtr += 2) { + double miter[4]; + int j; + + if (TkGetMiterPoints(coordPtr, coordPtr+2, coordPtr+4, + (double) width, miter, miter+2)) { + for (j = 0; j < 4; j += 2) { + TkIncludePoint((Tk_Item *) linePtr, miter+j); + } + } + } + } + + /* + * Add in the sizes of arrowheads, if any. + */ + + if (linePtr->arrow != noneUid) { + if (linePtr->arrow != lastUid) { + for (i = 0, coordPtr = linePtr->firstArrowPtr; i < PTS_IN_ARROW; + i++, coordPtr += 2) { + TkIncludePoint((Tk_Item *) linePtr, coordPtr); + } + } + if (linePtr->arrow != firstUid) { + for (i = 0, coordPtr = linePtr->lastArrowPtr; i < PTS_IN_ARROW; + i++, coordPtr += 2) { + TkIncludePoint((Tk_Item *) linePtr, coordPtr); + } + } + } + + /* + * Add one more pixel of fudge factor just to be safe (e.g. + * X may round differently than we do). + */ + + linePtr->header.x1 -= 1; + linePtr->header.x2 += 1; + linePtr->header.y1 -= 1; + linePtr->header.y2 += 1; +} + +/* + *-------------------------------------------------------------- + * + * DisplayLine -- + * + * This procedure is invoked to draw a line item in a given + * drawable. + * + * Results: + * None. + * + * Side effects: + * ItemPtr is drawn in drawable using the transformation + * information in canvas. + * + *-------------------------------------------------------------- + */ + +static void +DisplayLine(canvas, itemPtr, display, drawable, x, y, width, height) + Tk_Canvas canvas; /* Canvas that contains item. */ + Tk_Item *itemPtr; /* Item to be displayed. */ + Display *display; /* Display on which to draw item. */ + Drawable drawable; /* Pixmap or window in which to draw + * item. */ + int x, y, width, height; /* Describes region of canvas that + * must be redisplayed (not used). */ +{ + LineItem *linePtr = (LineItem *) itemPtr; + XPoint staticPoints[MAX_STATIC_POINTS]; + XPoint *pointPtr; + XPoint *pPtr; + double *coordPtr; + int i, numPoints; + + if (linePtr->gc == None) { + return; + } + + /* + * Build up an array of points in screen coordinates. Use a + * static array unless the line has an enormous number of points; + * in this case, dynamically allocate an array. For smoothed lines, + * generate the curve points on each redisplay. + */ + + if ((linePtr->smooth) && (linePtr->numPoints > 2)) { + numPoints = 1 + linePtr->numPoints*linePtr->splineSteps; + } else { + numPoints = linePtr->numPoints; + } + + if (numPoints <= MAX_STATIC_POINTS) { + pointPtr = staticPoints; + } else { + pointPtr = (XPoint *) ckalloc((unsigned) (numPoints * sizeof(XPoint))); + } + + if ((linePtr->smooth) && (linePtr->numPoints > 2)) { + numPoints = TkMakeBezierCurve(canvas, linePtr->coordPtr, + linePtr->numPoints, linePtr->splineSteps, pointPtr, + (double *) NULL); + } else { + for (i = 0, coordPtr = linePtr->coordPtr, pPtr = pointPtr; + i < linePtr->numPoints; i += 1, coordPtr += 2, pPtr++) { + Tk_CanvasDrawableCoords(canvas, coordPtr[0], coordPtr[1], + &pPtr->x, &pPtr->y); + } + } + + /* + * Display line, the free up line storage if it was dynamically + * allocated. If we're stippling, then modify the stipple offset + * in the GC. Be sure to reset the offset when done, since the + * GC is supposed to be read-only. + */ + + if (linePtr->fillStipple != None) { + Tk_CanvasSetStippleOrigin(canvas, linePtr->gc); + Tk_CanvasSetStippleOrigin(canvas, linePtr->arrowGC); + } + XDrawLines(display, drawable, linePtr->gc, pointPtr, numPoints, + CoordModeOrigin); + if (pointPtr != staticPoints) { + ckfree((char *) pointPtr); + } + + /* + * Display arrowheads, if they are wanted. + */ + + if (linePtr->firstArrowPtr != NULL) { + TkFillPolygon(canvas, linePtr->firstArrowPtr, PTS_IN_ARROW, + display, drawable, linePtr->gc, NULL); + } + if (linePtr->lastArrowPtr != NULL) { + TkFillPolygon(canvas, linePtr->lastArrowPtr, PTS_IN_ARROW, + display, drawable, linePtr->gc, NULL); + } + if (linePtr->fillStipple != None) { + XSetTSOrigin(display, linePtr->gc, 0, 0); + XSetTSOrigin(display, linePtr->arrowGC, 0, 0); + } +} + +/* + *-------------------------------------------------------------- + * + * LineToPoint -- + * + * Computes the distance from a given point to a given + * line, in canvas units. + * + * Results: + * The return value is 0 if the point whose x and y coordinates + * are pointPtr[0] and pointPtr[1] is inside the line. If the + * point isn't inside the line then the return value is the + * distance from the point to the line. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static double +LineToPoint(canvas, itemPtr, pointPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against point. */ + double *pointPtr; /* Pointer to x and y coordinates. */ +{ + LineItem *linePtr = (LineItem *) itemPtr; + double *coordPtr, *linePoints; + double staticSpace[2*MAX_STATIC_POINTS]; + double poly[10]; + double bestDist, dist; + int numPoints, count; + int changedMiterToBevel; /* Non-zero means that a mitered corner + * had to be treated as beveled after all + * because the angle was < 11 degrees. */ + + bestDist = 1.0e36; + + /* + * Handle smoothed lines by generating an expanded set of points + * against which to do the check. + */ + + if ((linePtr->smooth) && (linePtr->numPoints > 2)) { + numPoints = 1 + linePtr->numPoints*linePtr->splineSteps; + if (numPoints <= MAX_STATIC_POINTS) { + linePoints = staticSpace; + } else { + linePoints = (double *) ckalloc((unsigned) + (2*numPoints*sizeof(double))); + } + numPoints = TkMakeBezierCurve(canvas, linePtr->coordPtr, + linePtr->numPoints, linePtr->splineSteps, (XPoint *) NULL, + linePoints); + } else { + numPoints = linePtr->numPoints; + linePoints = linePtr->coordPtr; + } + + /* + * The overall idea is to iterate through all of the edges of + * the line, computing a polygon for each edge and testing the + * point against that polygon. In addition, there are additional + * tests to deal with rounded joints and caps. + */ + + changedMiterToBevel = 0; + for (count = numPoints, coordPtr = linePoints; count >= 2; + count--, coordPtr += 2) { + + /* + * If rounding is done around the first point then compute + * the distance between the point and the point. + */ + + if (((linePtr->capStyle == CapRound) && (count == numPoints)) + || ((linePtr->joinStyle == JoinRound) + && (count != numPoints))) { + dist = hypot(coordPtr[0] - pointPtr[0], coordPtr[1] - pointPtr[1]) + - linePtr->width/2.0; + if (dist <= 0.0) { + bestDist = 0.0; + goto done; + } else if (dist < bestDist) { + bestDist = dist; + } + } + + /* + * Compute the polygonal shape corresponding to this edge, + * consisting of two points for the first point of the edge + * and two points for the last point of the edge. + */ + + if (count == numPoints) { + TkGetButtPoints(coordPtr+2, coordPtr, (double) linePtr->width, + linePtr->capStyle == CapProjecting, poly, poly+2); + } else if ((linePtr->joinStyle == JoinMiter) && !changedMiterToBevel) { + poly[0] = poly[6]; + poly[1] = poly[7]; + poly[2] = poly[4]; + poly[3] = poly[5]; + } else { + TkGetButtPoints(coordPtr+2, coordPtr, (double) linePtr->width, 0, + poly, poly+2); + + /* + * If this line uses beveled joints, then check the distance + * to a polygon comprising the last two points of the previous + * polygon and the first two from this polygon; this checks + * the wedges that fill the mitered joint. + */ + + if ((linePtr->joinStyle == JoinBevel) || changedMiterToBevel) { + poly[8] = poly[0]; + poly[9] = poly[1]; + dist = TkPolygonToPoint(poly, 5, pointPtr); + if (dist <= 0.0) { + bestDist = 0.0; + goto done; + } else if (dist < bestDist) { + bestDist = dist; + } + changedMiterToBevel = 0; + } + } + if (count == 2) { + TkGetButtPoints(coordPtr, coordPtr+2, (double) linePtr->width, + linePtr->capStyle == CapProjecting, poly+4, poly+6); + } else if (linePtr->joinStyle == JoinMiter) { + if (TkGetMiterPoints(coordPtr, coordPtr+2, coordPtr+4, + (double) linePtr->width, poly+4, poly+6) == 0) { + changedMiterToBevel = 1; + TkGetButtPoints(coordPtr, coordPtr+2, (double) linePtr->width, + 0, poly+4, poly+6); + } + } else { + TkGetButtPoints(coordPtr, coordPtr+2, (double) linePtr->width, 0, + poly+4, poly+6); + } + poly[8] = poly[0]; + poly[9] = poly[1]; + dist = TkPolygonToPoint(poly, 5, pointPtr); + if (dist <= 0.0) { + bestDist = 0.0; + goto done; + } else if (dist < bestDist) { + bestDist = dist; + } + } + + /* + * If caps are rounded, check the distance to the cap around the + * final end point of the line. + */ + + if (linePtr->capStyle == CapRound) { + dist = hypot(coordPtr[0] - pointPtr[0], coordPtr[1] - pointPtr[1]) + - linePtr->width/2.0; + if (dist <= 0.0) { + bestDist = 0.0; + goto done; + } else if (dist < bestDist) { + bestDist = dist; + } + } + + /* + * If there are arrowheads, check the distance to the arrowheads. + */ + + if (linePtr->arrow != noneUid) { + if (linePtr->arrow != lastUid) { + dist = TkPolygonToPoint(linePtr->firstArrowPtr, PTS_IN_ARROW, + pointPtr); + if (dist <= 0.0) { + bestDist = 0.0; + goto done; + } else if (dist < bestDist) { + bestDist = dist; + } + } + if (linePtr->arrow != firstUid) { + dist = TkPolygonToPoint(linePtr->lastArrowPtr, PTS_IN_ARROW, + pointPtr); + if (dist <= 0.0) { + bestDist = 0.0; + goto done; + } else if (dist < bestDist) { + bestDist = dist; + } + } + } + + done: + if ((linePoints != staticSpace) && (linePoints != linePtr->coordPtr)) { + ckfree((char *) linePoints); + } + return bestDist; +} + +/* + *-------------------------------------------------------------- + * + * LineToArea -- + * + * This procedure is called to determine whether an item + * lies entirely inside, entirely outside, or overlapping + * a given rectangular area. + * + * Results: + * -1 is returned if the item is entirely outside the + * area, 0 if it overlaps, and 1 if it is entirely + * inside the given area. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +LineToArea(canvas, itemPtr, rectPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against line. */ + double *rectPtr; +{ + LineItem *linePtr = (LineItem *) itemPtr; + double staticSpace[2*MAX_STATIC_POINTS]; + double *linePoints; + int numPoints, result; + + /* + * Handle smoothed lines by generating an expanded set of points + * against which to do the check. + */ + + if ((linePtr->smooth) && (linePtr->numPoints > 2)) { + numPoints = 1 + linePtr->numPoints*linePtr->splineSteps; + if (numPoints <= MAX_STATIC_POINTS) { + linePoints = staticSpace; + } else { + linePoints = (double *) ckalloc((unsigned) + (2*numPoints*sizeof(double))); + } + numPoints = TkMakeBezierCurve(canvas, linePtr->coordPtr, + linePtr->numPoints, linePtr->splineSteps, (XPoint *) NULL, + linePoints); + } else { + numPoints = linePtr->numPoints; + linePoints = linePtr->coordPtr; + } + + /* + * Check the segments of the line. + */ + + result = TkThickPolyLineToArea(linePoints, numPoints, + (double) linePtr->width, linePtr->capStyle, linePtr->joinStyle, + rectPtr); + if (result == 0) { + goto done; + } + + /* + * Check arrowheads, if any. + */ + + if (linePtr->arrow != noneUid) { + if (linePtr->arrow != lastUid) { + if (TkPolygonToArea(linePtr->firstArrowPtr, PTS_IN_ARROW, + rectPtr) != result) { + result = 0; + goto done; + } + } + if (linePtr->arrow != firstUid) { + if (TkPolygonToArea(linePtr->lastArrowPtr, PTS_IN_ARROW, + rectPtr) != result) { + result = 0; + goto done; + } + } + } + + done: + if ((linePoints != staticSpace) && (linePoints != linePtr->coordPtr)) { + ckfree((char *) linePoints); + } + return result; +} + +/* + *-------------------------------------------------------------- + * + * ScaleLine -- + * + * This procedure is invoked to rescale a line item. + * + * Results: + * None. + * + * Side effects: + * The line referred to by itemPtr is rescaled so that the + * following transformation is applied to all point + * coordinates: + * x' = originX + scaleX*(x-originX) + * y' = originY + scaleY*(y-originY) + * + *-------------------------------------------------------------- + */ + +static void +ScaleLine(canvas, itemPtr, originX, originY, scaleX, scaleY) + Tk_Canvas canvas; /* Canvas containing line. */ + Tk_Item *itemPtr; /* Line to be scaled. */ + double originX, originY; /* Origin about which to scale rect. */ + double scaleX; /* Amount to scale in X direction. */ + double scaleY; /* Amount to scale in Y direction. */ +{ + LineItem *linePtr = (LineItem *) itemPtr; + double *coordPtr; + int i; + + /* + * Delete any arrowheads before scaling all the points (so that + * the end-points of the line get restored). + */ + + if (linePtr->firstArrowPtr != NULL) { + linePtr->coordPtr[0] = linePtr->firstArrowPtr[0]; + linePtr->coordPtr[1] = linePtr->firstArrowPtr[1]; + ckfree((char *) linePtr->firstArrowPtr); + linePtr->firstArrowPtr = NULL; + } + if (linePtr->lastArrowPtr != NULL) { + int i; + + i = 2*(linePtr->numPoints-1); + linePtr->coordPtr[i] = linePtr->lastArrowPtr[0]; + linePtr->coordPtr[i+1] = linePtr->lastArrowPtr[1]; + ckfree((char *) linePtr->lastArrowPtr); + linePtr->lastArrowPtr = NULL; + } + for (i = 0, coordPtr = linePtr->coordPtr; i < linePtr->numPoints; + i++, coordPtr += 2) { + coordPtr[0] = originX + scaleX*(*coordPtr - originX); + coordPtr[1] = originY + scaleY*(coordPtr[1] - originY); + } + if (linePtr->arrow != noneUid) { + ConfigureArrows(canvas, linePtr); + } + ComputeLineBbox(canvas, linePtr); +} + +/* + *-------------------------------------------------------------- + * + * TranslateLine -- + * + * This procedure is called to move a line by a given amount. + * + * Results: + * None. + * + * Side effects: + * The position of the line is offset by (xDelta, yDelta), and + * the bounding box is updated in the generic part of the item + * structure. + * + *-------------------------------------------------------------- + */ + +static void +TranslateLine(canvas, itemPtr, deltaX, deltaY) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item that is being moved. */ + double deltaX, deltaY; /* Amount by which item is to be + * moved. */ +{ + LineItem *linePtr = (LineItem *) itemPtr; + double *coordPtr; + int i; + + for (i = 0, coordPtr = linePtr->coordPtr; i < linePtr->numPoints; + i++, coordPtr += 2) { + coordPtr[0] += deltaX; + coordPtr[1] += deltaY; + } + if (linePtr->firstArrowPtr != NULL) { + for (i = 0, coordPtr = linePtr->firstArrowPtr; i < PTS_IN_ARROW; + i++, coordPtr += 2) { + coordPtr[0] += deltaX; + coordPtr[1] += deltaY; + } + } + if (linePtr->lastArrowPtr != NULL) { + for (i = 0, coordPtr = linePtr->lastArrowPtr; i < PTS_IN_ARROW; + i++, coordPtr += 2) { + coordPtr[0] += deltaX; + coordPtr[1] += deltaY; + } + } + ComputeLineBbox(canvas, linePtr); +} + +/* + *-------------------------------------------------------------- + * + * ParseArrowShape -- + * + * This procedure is called back during option parsing to + * parse arrow shape information. + * + * Results: + * The return value is a standard Tcl result: TCL_OK means + * that the arrow shape information was parsed ok, and + * TCL_ERROR means it couldn't be parsed. + * + * Side effects: + * Arrow information in recordPtr is updated. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +ParseArrowShape(clientData, interp, tkwin, value, recordPtr, offset) + ClientData clientData; /* Not used. */ + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Window tkwin; /* Not used. */ + char *value; /* Textual specification of arrow shape. */ + char *recordPtr; /* Pointer to item record in which to + * store arrow information. */ + int offset; /* Offset of shape information in widget + * record. */ +{ + LineItem *linePtr = (LineItem *) recordPtr; + double a, b, c; + int argc; + char **argv = NULL; + + if (offset != Tk_Offset(LineItem, arrowShapeA)) { + panic("ParseArrowShape received bogus offset"); + } + + if (Tcl_SplitList(interp, value, &argc, &argv) != TCL_OK) { + syntaxError: + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad arrow shape \"", value, + "\": must be list with three numbers", (char *) NULL); + if (argv != NULL) { + ckfree((char *) argv); + } + return TCL_ERROR; + } + if (argc != 3) { + goto syntaxError; + } + if ((Tk_CanvasGetCoord(interp, linePtr->canvas, argv[0], &a) != TCL_OK) + || (Tk_CanvasGetCoord(interp, linePtr->canvas, argv[1], &b) + != TCL_OK) + || (Tk_CanvasGetCoord(interp, linePtr->canvas, argv[2], &c) + != TCL_OK)) { + goto syntaxError; + } + linePtr->arrowShapeA = (float)a; + linePtr->arrowShapeB = (float)b; + linePtr->arrowShapeC = (float)c; + ckfree((char *) argv); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * PrintArrowShape -- + * + * This procedure is a callback invoked by the configuration + * code to return a printable value describing an arrow shape. + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static char * +PrintArrowShape(clientData, tkwin, recordPtr, offset, freeProcPtr) + ClientData clientData; /* Not used. */ + Tk_Window tkwin; /* Window associated with linePtr's widget. */ + char *recordPtr; /* Pointer to item record containing current + * shape information. */ + int offset; /* Offset of arrow information in record. */ + Tcl_FreeProc **freeProcPtr; /* Store address of procedure to call to + * free string here. */ +{ + LineItem *linePtr = (LineItem *) recordPtr; + char *buffer; + + buffer = (char *) ckalloc(120); + sprintf(buffer, "%.5g %.5g %.5g", linePtr->arrowShapeA, + linePtr->arrowShapeB, linePtr->arrowShapeC); + *freeProcPtr = TCL_DYNAMIC; + return buffer; +} + +/* + *-------------------------------------------------------------- + * + * ConfigureArrows -- + * + * If arrowheads have been requested for a line, this + * procedure makes arrangements for the arrowheads. + * + * Results: + * Always returns TCL_OK. + * + * Side effects: + * Information in linePtr is set up for one or two arrowheads. + * the firstArrowPtr and lastArrowPtr polygons are allocated + * and initialized, if need be, and the end points of the line + * are adjusted so that a thick line doesn't stick out past + * the arrowheads. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +ConfigureArrows(canvas, linePtr) + Tk_Canvas canvas; /* Canvas in which arrows will be + * displayed (interp and tkwin + * fields are needed). */ + LineItem *linePtr; /* Item to configure for arrows. */ +{ + double *poly, *coordPtr; + double dx, dy, length, sinTheta, cosTheta, temp; + double fracHeight; /* Line width as fraction of + * arrowhead width. */ + double backup; /* Distance to backup end points + * so the line ends in the middle + * of the arrowhead. */ + double vertX, vertY; /* Position of arrowhead vertex. */ + double shapeA, shapeB, shapeC; /* Adjusted coordinates (see + * explanation below). */ + + /* + * The code below makes a tiny increase in the shape parameters + * for the line. This is a bit of a hack, but it seems to result + * in displays that more closely approximate the specified parameters. + * Without the adjustment, the arrows come out smaller than expected. + */ + + shapeA = linePtr->arrowShapeA + 0.001; + shapeB = linePtr->arrowShapeB + 0.001; + shapeC = linePtr->arrowShapeC + linePtr->width/2.0 + 0.001; + + /* + * If there's an arrowhead on the first point of the line, compute + * its polygon and adjust the first point of the line so that the + * line doesn't stick out past the leading edge of the arrowhead. + */ + + fracHeight = (linePtr->width/2.0)/shapeC; + backup = fracHeight*shapeB + shapeA*(1.0 - fracHeight)/2.0; + if (linePtr->arrow != lastUid) { + poly = linePtr->firstArrowPtr; + if (poly == NULL) { + poly = (double *) ckalloc((unsigned) + (2*PTS_IN_ARROW*sizeof(double))); + poly[0] = poly[10] = linePtr->coordPtr[0]; + poly[1] = poly[11] = linePtr->coordPtr[1]; + linePtr->firstArrowPtr = poly; + } + dx = poly[0] - linePtr->coordPtr[2]; + dy = poly[1] - linePtr->coordPtr[3]; + length = hypot(dx, dy); + if (length == 0) { + sinTheta = cosTheta = 0.0; + } else { + sinTheta = dy/length; + cosTheta = dx/length; + } + vertX = poly[0] - shapeA*cosTheta; + vertY = poly[1] - shapeA*sinTheta; + temp = shapeC*sinTheta; + poly[2] = poly[0] - shapeB*cosTheta + temp; + poly[8] = poly[2] - 2*temp; + temp = shapeC*cosTheta; + poly[3] = poly[1] - shapeB*sinTheta - temp; + poly[9] = poly[3] + 2*temp; + poly[4] = poly[2]*fracHeight + vertX*(1.0-fracHeight); + poly[5] = poly[3]*fracHeight + vertY*(1.0-fracHeight); + poly[6] = poly[8]*fracHeight + vertX*(1.0-fracHeight); + poly[7] = poly[9]*fracHeight + vertY*(1.0-fracHeight); + + /* + * Polygon done. Now move the first point towards the second so + * that the corners at the end of the line are inside the + * arrowhead. + */ + + linePtr->coordPtr[0] = poly[0] - backup*cosTheta; + linePtr->coordPtr[1] = poly[1] - backup*sinTheta; + } + + /* + * Similar arrowhead calculation for the last point of the line. + */ + + if (linePtr->arrow != firstUid) { + coordPtr = linePtr->coordPtr + 2*(linePtr->numPoints-2); + poly = linePtr->lastArrowPtr; + if (poly == NULL) { + poly = (double *) ckalloc((unsigned) + (2*PTS_IN_ARROW*sizeof(double))); + poly[0] = poly[10] = coordPtr[2]; + poly[1] = poly[11] = coordPtr[3]; + linePtr->lastArrowPtr = poly; + } + dx = poly[0] - coordPtr[0]; + dy = poly[1] - coordPtr[1]; + length = hypot(dx, dy); + if (length == 0) { + sinTheta = cosTheta = 0.0; + } else { + sinTheta = dy/length; + cosTheta = dx/length; + } + vertX = poly[0] - shapeA*cosTheta; + vertY = poly[1] - shapeA*sinTheta; + temp = shapeC*sinTheta; + poly[2] = poly[0] - shapeB*cosTheta + temp; + poly[8] = poly[2] - 2*temp; + temp = shapeC*cosTheta; + poly[3] = poly[1] - shapeB*sinTheta - temp; + poly[9] = poly[3] + 2*temp; + poly[4] = poly[2]*fracHeight + vertX*(1.0-fracHeight); + poly[5] = poly[3]*fracHeight + vertY*(1.0-fracHeight); + poly[6] = poly[8]*fracHeight + vertX*(1.0-fracHeight); + poly[7] = poly[9]*fracHeight + vertY*(1.0-fracHeight); + coordPtr[2] = poly[0] - backup*cosTheta; + coordPtr[3] = poly[1] - backup*sinTheta; + } + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * LineToPostscript -- + * + * This procedure is called to generate Postscript for + * line items. + * + * Results: + * The return value is a standard Tcl result. If an error + * occurs in generating Postscript then an error message is + * left in interp->result, replacing whatever used + * to be there. If no error occurs, then Postscript for the + * item is appended to the result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +LineToPostscript(interp, canvas, itemPtr, prepass) + Tcl_Interp *interp; /* Leave Postscript or error message + * here. */ + Tk_Canvas canvas; /* Information about overall canvas. */ + Tk_Item *itemPtr; /* Item for which Postscript is + * wanted. */ + int prepass; /* 1 means this is a prepass to + * collect font information; 0 means + * final Postscript is being created. */ +{ + LineItem *linePtr = (LineItem *) itemPtr; + char buffer[200]; + char *style; + + if (linePtr->fg == NULL) { + return TCL_OK; + } + + /* + * Generate a path for the line's center-line (do this differently + * for straight lines and smoothed lines). + */ + + if ((!linePtr->smooth) || (linePtr->numPoints <= 2)) { + Tk_CanvasPsPath(interp, canvas, linePtr->coordPtr, linePtr->numPoints); + } else { + if (linePtr->fillStipple == None) { + TkMakeBezierPostscript(interp, canvas, linePtr->coordPtr, + linePtr->numPoints); + } else { + /* + * Special hack: Postscript printers don't appear to be able + * to turn a path drawn with "curveto"s into a clipping path + * without exceeding resource limits, so TkMakeBezierPostscript + * won't work for stippled curves. Instead, generate all of + * the intermediate points here and output them into the + * Postscript file with "lineto"s instead. + */ + + double staticPoints[2*MAX_STATIC_POINTS]; + double *pointPtr; + int numPoints; + + numPoints = 1 + linePtr->numPoints*linePtr->splineSteps; + pointPtr = staticPoints; + if (numPoints > MAX_STATIC_POINTS) { + pointPtr = (double *) ckalloc((unsigned) + (numPoints * 2 * sizeof(double))); + } + numPoints = TkMakeBezierCurve(canvas, linePtr->coordPtr, + linePtr->numPoints, linePtr->splineSteps, (XPoint *) NULL, + pointPtr); + Tk_CanvasPsPath(interp, canvas, pointPtr, numPoints); + if (pointPtr != staticPoints) { + ckfree((char *) pointPtr); + } + } + } + + /* + * Set other line-drawing parameters and stroke out the line. + */ + + sprintf(buffer, "%d setlinewidth\n", linePtr->width); + Tcl_AppendResult(interp, buffer, (char *) NULL); + style = "0 setlinecap\n"; + if (linePtr->capStyle == CapRound) { + style = "1 setlinecap\n"; + } else if (linePtr->capStyle == CapProjecting) { + style = "2 setlinecap\n"; + } + Tcl_AppendResult(interp, style, (char *) NULL); + style = "0 setlinejoin\n"; + if (linePtr->joinStyle == JoinRound) { + style = "1 setlinejoin\n"; + } else if (linePtr->joinStyle == JoinBevel) { + style = "2 setlinejoin\n"; + } + Tcl_AppendResult(interp, style, (char *) NULL); + if (Tk_CanvasPsColor(interp, canvas, linePtr->fg) != TCL_OK) { + return TCL_ERROR; + }; + if (linePtr->fillStipple != None) { + Tcl_AppendResult(interp, "StrokeClip ", (char *) NULL); + if (Tk_CanvasPsStipple(interp, canvas, linePtr->fillStipple) + != TCL_OK) { + return TCL_ERROR; + } + } else { + Tcl_AppendResult(interp, "stroke\n", (char *) NULL); + } + + /* + * Output polygons for the arrowheads, if there are any. + */ + + if (linePtr->firstArrowPtr != NULL) { + if (linePtr->fillStipple != None) { + Tcl_AppendResult(interp, "grestore gsave\n", + (char *) NULL); + } + if (ArrowheadPostscript(interp, canvas, linePtr, + linePtr->firstArrowPtr) != TCL_OK) { + return TCL_ERROR; + } + } + if (linePtr->lastArrowPtr != NULL) { + if (linePtr->fillStipple != None) { + Tcl_AppendResult(interp, "grestore gsave\n", (char *) NULL); + } + if (ArrowheadPostscript(interp, canvas, linePtr, + linePtr->lastArrowPtr) != TCL_OK) { + return TCL_ERROR; + } + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ArrowheadPostscript -- + * + * This procedure is called to generate Postscript for + * an arrowhead for a line item. + * + * Results: + * The return value is a standard Tcl result. If an error + * occurs in generating Postscript then an error message is + * left in interp->result, replacing whatever used + * to be there. If no error occurs, then Postscript for the + * arrowhead is appended to the result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +ArrowheadPostscript(interp, canvas, linePtr, arrowPtr) + Tcl_Interp *interp; /* Leave Postscript or error message + * here. */ + Tk_Canvas canvas; /* Information about overall canvas. */ + LineItem *linePtr; /* Line item for which Postscript is + * being generated. */ + double *arrowPtr; /* Pointer to first of five points + * describing arrowhead polygon. */ +{ + Tk_CanvasPsPath(interp, canvas, arrowPtr, PTS_IN_ARROW); + if (linePtr->fillStipple != None) { + Tcl_AppendResult(interp, "clip ", (char *) NULL); + if (Tk_CanvasPsStipple(interp, canvas, linePtr->fillStipple) + != TCL_OK) { + return TCL_ERROR; + } + } else { + Tcl_AppendResult(interp, "fill\n", (char *) NULL); + } + return TCL_OK; +} diff --git a/generic/tkCanvPoly.c b/generic/tkCanvPoly.c new file mode 100644 index 0000000..1320438 --- /dev/null +++ b/generic/tkCanvPoly.c @@ -0,0 +1,998 @@ +/* + * tkCanvPoly.c -- + * + * This file implements polygon items for canvas widgets. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvPoly.c 1.37 97/04/29 15:39:16 + */ + +#include <stdio.h> +#include "tkInt.h" +#include "tkPort.h" + +/* + * The structure below defines the record for each polygon item. + */ + +typedef struct PolygonItem { + Tk_Item header; /* Generic stuff that's the same for all + * types. MUST BE FIRST IN STRUCTURE. */ + int numPoints; /* Number of points in polygon (always >= 3). + * Polygon is always closed. */ + int pointsAllocated; /* Number of points for which space is + * allocated at *coordPtr. */ + double *coordPtr; /* Pointer to malloc-ed array containing + * x- and y-coords of all points in polygon. + * X-coords are even-valued indices, y-coords + * are corresponding odd-valued indices. */ + int width; /* Width of outline. */ + XColor *outlineColor; /* Color for outline. */ + GC outlineGC; /* Graphics context for drawing outline. */ + XColor *fillColor; /* Foreground color for polygon. */ + Pixmap fillStipple; /* Stipple bitmap for filling polygon. */ + GC fillGC; /* Graphics context for filling polygon. */ + int smooth; /* Non-zero means draw shape smoothed (i.e. + * with Bezier splines). */ + int splineSteps; /* Number of steps in each spline segment. */ + int autoClosed; /* Zero means the given polygon was closed, + one means that we auto closed it. */ +} PolygonItem; + +/* + * Information used for parsing configuration specs: + */ + +static Tk_CustomOption tagsOption = {Tk_CanvasTagsParseProc, + Tk_CanvasTagsPrintProc, (ClientData) NULL +}; + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_COLOR, "-fill", (char *) NULL, (char *) NULL, + "black", Tk_Offset(PolygonItem, fillColor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-outline", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(PolygonItem, outlineColor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-smooth", (char *) NULL, (char *) NULL, + "0", Tk_Offset(PolygonItem, smooth), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_INT, "-splinesteps", (char *) NULL, (char *) NULL, + "12", Tk_Offset(PolygonItem, splineSteps), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_BITMAP, "-stipple", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(PolygonItem, fillStipple), TK_CONFIG_NULL_OK}, + {TK_CONFIG_CUSTOM, "-tags", (char *) NULL, (char *) NULL, + (char *) NULL, 0, TK_CONFIG_NULL_OK, &tagsOption}, + {TK_CONFIG_PIXELS, "-width", (char *) NULL, (char *) NULL, + "1", Tk_Offset(PolygonItem, width), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Prototypes for procedures defined in this file: + */ + +static void ComputePolygonBbox _ANSI_ARGS_((Tk_Canvas canvas, + PolygonItem *polyPtr)); +static int ConfigurePolygon _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv, int flags)); +static int CreatePolygon _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, struct Tk_Item *itemPtr, + int argc, char **argv)); +static void DeletePolygon _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display)); +static void DisplayPolygon _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display, Drawable dst, + int x, int y, int width, int height)); +static int PolygonCoords _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, + int argc, char **argv)); +static int PolygonToArea _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *rectPtr)); +static double PolygonToPoint _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *pointPtr)); +static int PolygonToPostscript _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int prepass)); +static void ScalePolygon _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double originX, double originY, + double scaleX, double scaleY)); +static void TranslatePolygon _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double deltaX, double deltaY)); + +/* + * The structures below defines the polygon item type by means + * of procedures that can be invoked by generic item code. + */ + +Tk_ItemType tkPolygonType = { + "polygon", /* name */ + sizeof(PolygonItem), /* itemSize */ + CreatePolygon, /* createProc */ + configSpecs, /* configSpecs */ + ConfigurePolygon, /* configureProc */ + PolygonCoords, /* coordProc */ + DeletePolygon, /* deleteProc */ + DisplayPolygon, /* displayProc */ + 0, /* alwaysRedraw */ + PolygonToPoint, /* pointProc */ + PolygonToArea, /* areaProc */ + PolygonToPostscript, /* postscriptProc */ + ScalePolygon, /* scaleProc */ + TranslatePolygon, /* translateProc */ + (Tk_ItemIndexProc *) NULL, /* indexProc */ + (Tk_ItemCursorProc *) NULL, /* icursorProc */ + (Tk_ItemSelectionProc *) NULL, /* selectionProc */ + (Tk_ItemInsertProc *) NULL, /* insertProc */ + (Tk_ItemDCharsProc *) NULL, /* dTextProc */ + (Tk_ItemType *) NULL /* nextPtr */ +}; + +/* + * The definition below determines how large are static arrays + * used to hold spline points (splines larger than this have to + * have their arrays malloc-ed). + */ + +#define MAX_STATIC_POINTS 200 + +/* + *-------------------------------------------------------------- + * + * CreatePolygon -- + * + * This procedure is invoked to create a new polygon item in + * a canvas. + * + * Results: + * A standard Tcl return value. If an error occurred in + * creating the item, then an error message is left in + * interp->result; in this case itemPtr is + * left uninitialized, so it can be safely freed by the + * caller. + * + * Side effects: + * A new polygon item is created. + * + *-------------------------------------------------------------- + */ + +static int +CreatePolygon(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Canvas to hold new item. */ + Tk_Item *itemPtr; /* Record to hold new item; header + * has been initialized by caller. */ + int argc; /* Number of arguments in argv. */ + char **argv; /* Arguments describing polygon. */ +{ + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + int i; + + if (argc < 6) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tk_PathName(Tk_CanvasTkwin(canvas)), " create ", + itemPtr->typePtr->name, + " x1 y1 x2 y2 x3 y3 ?x4 y4 ...? ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + /* + * Carry out initialization that is needed in order to clean + * up after errors during the the remainder of this procedure. + */ + + polyPtr->numPoints = 0; + polyPtr->pointsAllocated = 0; + polyPtr->coordPtr = NULL; + polyPtr->width = 1; + polyPtr->outlineColor = NULL; + polyPtr->outlineGC = None; + polyPtr->fillColor = NULL; + polyPtr->fillStipple = None; + polyPtr->fillGC = None; + polyPtr->smooth = 0; + polyPtr->splineSteps = 12; + polyPtr->autoClosed = 0; + + /* + * Count the number of points and then parse them into a point + * array. Leading arguments are assumed to be points if they + * start with a digit or a minus sign followed by a digit. + */ + + for (i = 4; i < (argc-1); i+=2) { + if ((!isdigit(UCHAR(argv[i][0]))) && + ((argv[i][0] != '-') || (!isdigit(UCHAR(argv[i][1]))))) { + break; + } + } + if (PolygonCoords(interp, canvas, itemPtr, i, argv) != TCL_OK) { + goto error; + } + + if (ConfigurePolygon(interp, canvas, itemPtr, argc-i, argv+i, 0) + == TCL_OK) { + return TCL_OK; + } + + error: + DeletePolygon(canvas, itemPtr, Tk_Display(Tk_CanvasTkwin(canvas))); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * PolygonCoords -- + * + * This procedure is invoked to process the "coords" widget + * command on polygons. See the user documentation for details + * on what it does. + * + * Results: + * Returns TCL_OK or TCL_ERROR, and sets interp->result. + * + * Side effects: + * The coordinates for the given item may be changed. + * + *-------------------------------------------------------------- + */ + +static int +PolygonCoords(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item whose coordinates are to be + * read or modified. */ + int argc; /* Number of coordinates supplied in + * argv. */ + char **argv; /* Array of coordinates: x1, y1, + * x2, y2, ... */ +{ + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + char buffer[TCL_DOUBLE_SPACE]; + int i, numPoints; + + if (argc == 0) { + /* + * Print the coords used to create the polygon. If we auto + * closed the polygon then we don't report the last point. + */ + for (i = 0; i < 2*(polyPtr->numPoints - polyPtr->autoClosed); i++) { + Tcl_PrintDouble(interp, polyPtr->coordPtr[i], buffer); + Tcl_AppendElement(interp, buffer); + } + } else if (argc < 6) { + Tcl_AppendResult(interp, + "too few coordinates for polygon: must have at least 6", + (char *) NULL); + return TCL_ERROR; + } else if (argc & 1) { + Tcl_AppendResult(interp, + "odd number of coordinates specified for polygon", + (char *) NULL); + return TCL_ERROR; + } else { + numPoints = argc/2; + if (polyPtr->pointsAllocated <= numPoints) { + if (polyPtr->coordPtr != NULL) { + ckfree((char *) polyPtr->coordPtr); + } + + /* + * One extra point gets allocated here, just in case we have + * to add another point to close the polygon. + */ + + polyPtr->coordPtr = (double *) ckalloc((unsigned) + (sizeof(double) * (argc+2))); + polyPtr->pointsAllocated = numPoints+1; + } + for (i = argc-1; i >= 0; i--) { + if (Tk_CanvasGetCoord(interp, canvas, argv[i], + &polyPtr->coordPtr[i]) != TCL_OK) { + return TCL_ERROR; + } + } + polyPtr->numPoints = numPoints; + polyPtr->autoClosed = 0; + + /* + * Close the polygon if it isn't already closed. + */ + + if ((polyPtr->coordPtr[argc-2] != polyPtr->coordPtr[0]) + || (polyPtr->coordPtr[argc-1] != polyPtr->coordPtr[1])) { + polyPtr->autoClosed = 1; + polyPtr->numPoints++; + polyPtr->coordPtr[argc] = polyPtr->coordPtr[0]; + polyPtr->coordPtr[argc+1] = polyPtr->coordPtr[1]; + } + ComputePolygonBbox(canvas, polyPtr); + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ConfigurePolygon -- + * + * This procedure is invoked to configure various aspects + * of a polygon item such as its background color. + * + * Results: + * A standard Tcl result code. If an error occurs, then + * an error message is left in interp->result. + * + * Side effects: + * Configuration information, such as colors and stipple + * patterns, may be set for itemPtr. + * + *-------------------------------------------------------------- + */ + +static int +ConfigurePolygon(interp, canvas, itemPtr, argc, argv, flags) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Polygon item to reconfigure. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Arguments describing things to configure. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + XGCValues gcValues; + GC newGC; + unsigned long mask; + Tk_Window tkwin; + + tkwin = Tk_CanvasTkwin(canvas); + if (Tk_ConfigureWidget(interp, tkwin, configSpecs, argc, argv, + (char *) polyPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few of the options require additional processing, such as + * graphics contexts. + */ + + if (polyPtr->width < 1) { + polyPtr->width = 1; + } + if (polyPtr->outlineColor == NULL) { + newGC = None; + } else { + gcValues.foreground = polyPtr->outlineColor->pixel; + gcValues.line_width = polyPtr->width; + gcValues.cap_style = CapRound; + gcValues.join_style = JoinRound; + mask = GCForeground|GCLineWidth|GCCapStyle|GCJoinStyle; + newGC = Tk_GetGC(tkwin, mask, &gcValues); + } + if (polyPtr->outlineGC != None) { + Tk_FreeGC(Tk_Display(tkwin), polyPtr->outlineGC); + } + polyPtr->outlineGC = newGC; + + if (polyPtr->fillColor == NULL) { + newGC = None; + } else { + gcValues.foreground = polyPtr->fillColor->pixel; + mask = GCForeground; + if (polyPtr->fillStipple != None) { + gcValues.stipple = polyPtr->fillStipple; + gcValues.fill_style = FillStippled; + mask |= GCStipple|GCFillStyle; + } + newGC = Tk_GetGC(tkwin, mask, &gcValues); + } + if (polyPtr->fillGC != None) { + Tk_FreeGC(Tk_Display(tkwin), polyPtr->fillGC); + } + polyPtr->fillGC = newGC; + + /* + * Keep spline parameters within reasonable limits. + */ + + if (polyPtr->splineSteps < 1) { + polyPtr->splineSteps = 1; + } else if (polyPtr->splineSteps > 100) { + polyPtr->splineSteps = 100; + } + + ComputePolygonBbox(canvas, polyPtr); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * DeletePolygon -- + * + * This procedure is called to clean up the data structure + * associated with a polygon item. + * + * Results: + * None. + * + * Side effects: + * Resources associated with itemPtr are released. + * + *-------------------------------------------------------------- + */ + +static void +DeletePolygon(canvas, itemPtr, display) + Tk_Canvas canvas; /* Info about overall canvas widget. */ + Tk_Item *itemPtr; /* Item that is being deleted. */ + Display *display; /* Display containing window for + * canvas. */ +{ + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + + if (polyPtr->coordPtr != NULL) { + ckfree((char *) polyPtr->coordPtr); + } + if (polyPtr->fillColor != NULL) { + Tk_FreeColor(polyPtr->fillColor); + } + if (polyPtr->fillStipple != None) { + Tk_FreeBitmap(display, polyPtr->fillStipple); + } + if (polyPtr->outlineColor != NULL) { + Tk_FreeColor(polyPtr->outlineColor); + } + if (polyPtr->outlineGC != None) { + Tk_FreeGC(display, polyPtr->outlineGC); + } + if (polyPtr->fillGC != None) { + Tk_FreeGC(display, polyPtr->fillGC); + } +} + +/* + *-------------------------------------------------------------- + * + * ComputePolygonBbox -- + * + * This procedure is invoked to compute the bounding box of + * all the pixels that may be drawn as part of a polygon. + * + * Results: + * None. + * + * Side effects: + * The fields x1, y1, x2, and y2 are updated in the header + * for itemPtr. + * + *-------------------------------------------------------------- + */ + +static void +ComputePolygonBbox(canvas, polyPtr) + Tk_Canvas canvas; /* Canvas that contains item. */ + PolygonItem *polyPtr; /* Item whose bbox is to be + * recomputed. */ +{ + double *coordPtr; + int i; + + coordPtr = polyPtr->coordPtr; + polyPtr->header.x1 = polyPtr->header.x2 = (int) *coordPtr; + polyPtr->header.y1 = polyPtr->header.y2 = (int) coordPtr[1]; + + for (i = 1, coordPtr = polyPtr->coordPtr+2; i < polyPtr->numPoints; + i++, coordPtr += 2) { + TkIncludePoint((Tk_Item *) polyPtr, coordPtr); + } + + /* + * Expand bounding box in all directions to account for the outline, + * which can stick out beyond the polygon. Add one extra pixel of + * fudge, just in case X rounds differently than we do. + */ + + i = (polyPtr->width+1)/2 + 1; + polyPtr->header.x1 -= i; + polyPtr->header.x2 += i; + polyPtr->header.y1 -= i; + polyPtr->header.y2 += i; +} + +/* + *-------------------------------------------------------------- + * + * TkFillPolygon -- + * + * This procedure is invoked to convert a polygon to screen + * coordinates and display it using a particular GC. + * + * Results: + * None. + * + * Side effects: + * ItemPtr is drawn in drawable using the transformation + * information in canvas. + * + *-------------------------------------------------------------- + */ + +void +TkFillPolygon(canvas, coordPtr, numPoints, display, drawable, gc, outlineGC) + Tk_Canvas canvas; /* Canvas whose coordinate system + * is to be used for drawing. */ + double *coordPtr; /* Array of coordinates for polygon: + * x1, y1, x2, y2, .... */ + int numPoints; /* Twice this many coordinates are + * present at *coordPtr. */ + Display *display; /* Display on which to draw polygon. */ + Drawable drawable; /* Pixmap or window in which to draw + * polygon. */ + GC gc; /* Graphics context for drawing. */ + GC outlineGC; /* If not None, use this to draw an + * outline around the polygon after + * filling it. */ +{ + XPoint staticPoints[MAX_STATIC_POINTS]; + XPoint *pointPtr; + XPoint *pPtr; + int i; + + /* + * Build up an array of points in screen coordinates. Use a + * static array unless the polygon has an enormous number of points; + * in this case, dynamically allocate an array. + */ + + if (numPoints <= MAX_STATIC_POINTS) { + pointPtr = staticPoints; + } else { + pointPtr = (XPoint *) ckalloc((unsigned) (numPoints * sizeof(XPoint))); + } + + for (i = 0, pPtr = pointPtr; i < numPoints; i += 1, coordPtr += 2, pPtr++) { + Tk_CanvasDrawableCoords(canvas, coordPtr[0], coordPtr[1], &pPtr->x, + &pPtr->y); + } + + /* + * Display polygon, then free up polygon storage if it was dynamically + * allocated. + */ + + if (gc != None) { + XFillPolygon(display, drawable, gc, pointPtr, numPoints, Complex, + CoordModeOrigin); + } + if (outlineGC != None) { + XDrawLines(display, drawable, outlineGC, pointPtr, + numPoints, CoordModeOrigin); + } + if (pointPtr != staticPoints) { + ckfree((char *) pointPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * DisplayPolygon -- + * + * This procedure is invoked to draw a polygon item in a given + * drawable. + * + * Results: + * None. + * + * Side effects: + * ItemPtr is drawn in drawable using the transformation + * information in canvas. + * + *-------------------------------------------------------------- + */ + +static void +DisplayPolygon(canvas, itemPtr, display, drawable, x, y, width, height) + Tk_Canvas canvas; /* Canvas that contains item. */ + Tk_Item *itemPtr; /* Item to be displayed. */ + Display *display; /* Display on which to draw item. */ + Drawable drawable; /* Pixmap or window in which to draw + * item. */ + int x, y, width, height; /* Describes region of canvas that + * must be redisplayed (not used). */ +{ + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + + if ((polyPtr->fillGC == None) && (polyPtr->outlineGC == None)) { + return; + } + + /* + * If we're stippling then modify the stipple offset in the GC. Be + * sure to reset the offset when done, since the GC is supposed to be + * read-only. + */ + + if ((polyPtr->fillStipple != None) && (polyPtr->fillGC != None)) { + Tk_CanvasSetStippleOrigin(canvas, polyPtr->fillGC); + } + + if (!polyPtr->smooth) { + TkFillPolygon(canvas, polyPtr->coordPtr, polyPtr->numPoints, + display, drawable, polyPtr->fillGC, polyPtr->outlineGC); + } else { + int numPoints; + XPoint staticPoints[MAX_STATIC_POINTS]; + XPoint *pointPtr; + + /* + * This is a smoothed polygon. Display using a set of generated + * spline points rather than the original points. + */ + + numPoints = 1 + polyPtr->numPoints*polyPtr->splineSteps; + if (numPoints <= MAX_STATIC_POINTS) { + pointPtr = staticPoints; + } else { + pointPtr = (XPoint *) ckalloc((unsigned) + (numPoints * sizeof(XPoint))); + } + numPoints = TkMakeBezierCurve(canvas, polyPtr->coordPtr, + polyPtr->numPoints, polyPtr->splineSteps, pointPtr, + (double *) NULL); + if (polyPtr->fillGC != None) { + XFillPolygon(display, drawable, polyPtr->fillGC, pointPtr, + numPoints, Complex, CoordModeOrigin); + } + if (polyPtr->outlineGC != None) { + XDrawLines(display, drawable, polyPtr->outlineGC, pointPtr, + numPoints, CoordModeOrigin); + } + if (pointPtr != staticPoints) { + ckfree((char *) pointPtr); + } + } + if ((polyPtr->fillStipple != None) && (polyPtr->fillGC != None)) { + XSetTSOrigin(display, polyPtr->fillGC, 0, 0); + } +} + +/* + *-------------------------------------------------------------- + * + * PolygonToPoint -- + * + * Computes the distance from a given point to a given + * polygon, in canvas units. + * + * Results: + * The return value is 0 if the point whose x and y coordinates + * are pointPtr[0] and pointPtr[1] is inside the polygon. If the + * point isn't inside the polygon then the return value is the + * distance from the point to the polygon. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static double +PolygonToPoint(canvas, itemPtr, pointPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against point. */ + double *pointPtr; /* Pointer to x and y coordinates. */ +{ + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + double *coordPtr, distance; + double staticSpace[2*MAX_STATIC_POINTS]; + int numPoints; + + if (!polyPtr->smooth) { + distance = TkPolygonToPoint(polyPtr->coordPtr, polyPtr->numPoints, + pointPtr); + } else { + /* + * Smoothed polygon. Generate a new set of points and use them + * for comparison. + */ + + numPoints = 1 + polyPtr->numPoints*polyPtr->splineSteps; + if (numPoints <= MAX_STATIC_POINTS) { + coordPtr = staticSpace; + } else { + coordPtr = (double *) ckalloc((unsigned) + (2*numPoints*sizeof(double))); + } + numPoints = TkMakeBezierCurve(canvas, polyPtr->coordPtr, + polyPtr->numPoints, polyPtr->splineSteps, (XPoint *) NULL, + coordPtr); + distance = TkPolygonToPoint(coordPtr, numPoints, pointPtr); + if (coordPtr != staticSpace) { + ckfree((char *) coordPtr); + } + } + if (polyPtr->outlineColor != NULL) { + distance -= polyPtr->width/2.0; + if (distance < 0) { + distance = 0; + } + } + return distance; +} + +/* + *-------------------------------------------------------------- + * + * PolygonToArea -- + * + * This procedure is called to determine whether an item + * lies entirely inside, entirely outside, or overlapping + * a given rectangular area. + * + * Results: + * -1 is returned if the item is entirely outside the area + * given by rectPtr, 0 if it overlaps, and 1 if it is entirely + * inside the given area. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +PolygonToArea(canvas, itemPtr, rectPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against polygon. */ + double *rectPtr; /* Pointer to array of four coordinates + * (x1, y1, x2, y2) describing rectangular + * area. */ +{ + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + double *coordPtr, rect2[4], halfWidth; + double staticSpace[2*MAX_STATIC_POINTS]; + int numPoints, result; + + /* + * Handle smoothed polygons by generating an expanded set of points + * against which to do the check. + */ + + if (polyPtr->smooth) { + numPoints = 1 + polyPtr->numPoints*polyPtr->splineSteps; + if (numPoints <= MAX_STATIC_POINTS) { + coordPtr = staticSpace; + } else { + coordPtr = (double *) ckalloc((unsigned) + (2*numPoints*sizeof(double))); + } + numPoints = TkMakeBezierCurve(canvas, polyPtr->coordPtr, + polyPtr->numPoints, polyPtr->splineSteps, (XPoint *) NULL, + coordPtr); + } else { + numPoints = polyPtr->numPoints; + coordPtr = polyPtr->coordPtr; + } + + if (polyPtr->width <= 1) { + /* + * The outline of the polygon doesn't stick out, so we can + * do a simple check. + */ + + result = TkPolygonToArea(coordPtr, numPoints, rectPtr); + } else { + /* + * The polygon has a wide outline, so the check is more complicated. + * First, check the line segments to see if they overlap the area. + */ + + result = TkThickPolyLineToArea(coordPtr, numPoints, + (double) polyPtr->width, CapRound, JoinRound, rectPtr); + if (result >= 0) { + goto done; + } + + /* + * There is no overlap between the polygon's outline and the + * rectangle. This means either the rectangle is entirely outside + * the polygon or entirely inside. To tell the difference, + * see whether the polygon (with 0 outline width) overlaps the + * rectangle bloated by half the outline width. + */ + + halfWidth = polyPtr->width/2.0; + rect2[0] = rectPtr[0] - halfWidth; + rect2[1] = rectPtr[1] - halfWidth; + rect2[2] = rectPtr[2] + halfWidth; + rect2[3] = rectPtr[3] + halfWidth; + if (TkPolygonToArea(coordPtr, numPoints, rect2) == -1) { + result = -1; + } else { + result = 0; + } + } + + done: + if ((coordPtr != staticSpace) && (coordPtr != polyPtr->coordPtr)) { + ckfree((char *) coordPtr); + } + return result; +} + +/* + *-------------------------------------------------------------- + * + * ScalePolygon -- + * + * This procedure is invoked to rescale a polygon item. + * + * Results: + * None. + * + * Side effects: + * The polygon referred to by itemPtr is rescaled so that the + * following transformation is applied to all point + * coordinates: + * x' = originX + scaleX*(x-originX) + * y' = originY + scaleY*(y-originY) + * + *-------------------------------------------------------------- + */ + +static void +ScalePolygon(canvas, itemPtr, originX, originY, scaleX, scaleY) + Tk_Canvas canvas; /* Canvas containing polygon. */ + Tk_Item *itemPtr; /* Polygon to be scaled. */ + double originX, originY; /* Origin about which to scale rect. */ + double scaleX; /* Amount to scale in X direction. */ + double scaleY; /* Amount to scale in Y direction. */ +{ + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + double *coordPtr; + int i; + + for (i = 0, coordPtr = polyPtr->coordPtr; i < polyPtr->numPoints; + i++, coordPtr += 2) { + *coordPtr = originX + scaleX*(*coordPtr - originX); + coordPtr[1] = originY + scaleY*(coordPtr[1] - originY); + } + ComputePolygonBbox(canvas, polyPtr); +} + +/* + *-------------------------------------------------------------- + * + * TranslatePolygon -- + * + * This procedure is called to move a polygon by a given + * amount. + * + * Results: + * None. + * + * Side effects: + * The position of the polygon is offset by (xDelta, yDelta), + * and the bounding box is updated in the generic part of the + * item structure. + * + *-------------------------------------------------------------- + */ + +static void +TranslatePolygon(canvas, itemPtr, deltaX, deltaY) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item that is being moved. */ + double deltaX, deltaY; /* Amount by which item is to be + * moved. */ +{ + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + double *coordPtr; + int i; + + for (i = 0, coordPtr = polyPtr->coordPtr; i < polyPtr->numPoints; + i++, coordPtr += 2) { + *coordPtr += deltaX; + coordPtr[1] += deltaY; + } + ComputePolygonBbox(canvas, polyPtr); +} + +/* + *-------------------------------------------------------------- + * + * PolygonToPostscript -- + * + * This procedure is called to generate Postscript for + * polygon items. + * + * Results: + * The return value is a standard Tcl result. If an error + * occurs in generating Postscript then an error message is + * left in interp->result, replacing whatever used + * to be there. If no error occurs, then Postscript for the + * item is appended to the result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +PolygonToPostscript(interp, canvas, itemPtr, prepass) + Tcl_Interp *interp; /* Leave Postscript or error message + * here. */ + Tk_Canvas canvas; /* Information about overall canvas. */ + Tk_Item *itemPtr; /* Item for which Postscript is + * wanted. */ + int prepass; /* 1 means this is a prepass to + * collect font information; 0 means + * final Postscript is being created. */ +{ + char string[100]; + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + + /* + * Fill the area of the polygon. + */ + + if (polyPtr->fillColor != NULL) { + if (!polyPtr->smooth) { + Tk_CanvasPsPath(interp, canvas, polyPtr->coordPtr, + polyPtr->numPoints); + } else { + TkMakeBezierPostscript(interp, canvas, polyPtr->coordPtr, + polyPtr->numPoints); + } + if (Tk_CanvasPsColor(interp, canvas, polyPtr->fillColor) != TCL_OK) { + return TCL_ERROR; + } + if (polyPtr->fillStipple != None) { + Tcl_AppendResult(interp, "eoclip ", (char *) NULL); + if (Tk_CanvasPsStipple(interp, canvas, polyPtr->fillStipple) + != TCL_OK) { + return TCL_ERROR; + } + if (polyPtr->outlineColor != NULL) { + Tcl_AppendResult(interp, "grestore gsave\n", (char *) NULL); + } + } else { + Tcl_AppendResult(interp, "eofill\n", (char *) NULL); + } + } + + /* + * Now draw the outline, if there is one. + */ + + if (polyPtr->outlineColor != NULL) { + if (!polyPtr->smooth) { + Tk_CanvasPsPath(interp, canvas, polyPtr->coordPtr, + polyPtr->numPoints); + } else { + TkMakeBezierPostscript(interp, canvas, polyPtr->coordPtr, + polyPtr->numPoints); + } + + sprintf(string, "%d setlinewidth\n", polyPtr->width); + Tcl_AppendResult(interp, string, + "1 setlinecap\n1 setlinejoin\n", (char *) NULL); + if (Tk_CanvasPsColor(interp, canvas, polyPtr->outlineColor) + != TCL_OK) { + return TCL_ERROR; + } + Tcl_AppendResult(interp, "stroke\n", (char *) NULL); + } + return TCL_OK; +} diff --git a/generic/tkCanvPs.c b/generic/tkCanvPs.c new file mode 100644 index 0000000..9bad194 --- /dev/null +++ b/generic/tkCanvPs.c @@ -0,0 +1,1163 @@ +/* + * tkCanvPs.c -- + * + * This module provides Postscript output support for canvases, + * including the "postscript" widget command plus a few utility + * procedures used for generating Postscript. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvPs.c 1.57 97/10/28 18:08:39 + */ + +#include "tkInt.h" +#include "tkCanvas.h" +#include "tkPort.h" + +/* + * See tkCanvas.h for key data structures used to implement canvases. + */ + +/* + * One of the following structures is created to keep track of Postscript + * output being generated. It consists mostly of information provided on + * the widget command line. + */ + +typedef struct TkPostscriptInfo { + int x, y, width, height; /* Area to print, in canvas pixel + * coordinates. */ + int x2, y2; /* x+width and y+height. */ + char *pageXString; /* String value of "-pagex" option or NULL. */ + char *pageYString; /* String value of "-pagey" option or NULL. */ + double pageX, pageY; /* Postscript coordinates (in points) + * corresponding to pageXString and + * pageYString. Don't forget that y-values + * grow upwards for Postscript! */ + char *pageWidthString; /* Printed width of output. */ + char *pageHeightString; /* Printed height of output. */ + double scale; /* Scale factor for conversion: each pixel + * maps into this many points. */ + Tk_Anchor pageAnchor; /* How to anchor bbox on Postscript page. */ + int rotate; /* Non-zero means output should be rotated + * on page (landscape mode). */ + char *fontVar; /* If non-NULL, gives name of global variable + * containing font mapping information. + * Malloc'ed. */ + char *colorVar; /* If non-NULL, give name of global variable + * containing color mapping information. + * Malloc'ed. */ + char *colorMode; /* Mode for handling colors: "monochrome", + * "gray", or "color". Malloc'ed. */ + int colorLevel; /* Numeric value corresponding to colorMode: + * 0 for mono, 1 for gray, 2 for color. */ + char *fileName; /* Name of file in which to write Postscript; + * NULL means return Postscript info as + * result. Malloc'ed. */ + char *channelName; /* If -channel is specified, the name of + * the channel to use. */ + Tcl_Channel chan; /* Open channel corresponding to fileName. */ + Tcl_HashTable fontTable; /* Hash table containing names of all font + * families used in output. The hash table + * values are not used. */ + int prepass; /* Non-zero means that we're currently in + * the pre-pass that collects font information, + * so the Postscript generated isn't + * relevant. */ +} TkPostscriptInfo; + +/* + * The table below provides a template that's used to process arguments + * to the canvas "postscript" command and fill in TkPostscriptInfo + * structures. + */ + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_STRING, "-colormap", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, colorVar), 0}, + {TK_CONFIG_STRING, "-colormode", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, colorMode), 0}, + {TK_CONFIG_STRING, "-file", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, fileName), 0}, + {TK_CONFIG_STRING, "-channel", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, channelName), 0}, + {TK_CONFIG_STRING, "-fontmap", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, fontVar), 0}, + {TK_CONFIG_PIXELS, "-height", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, height), 0}, + {TK_CONFIG_ANCHOR, "-pageanchor", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, pageAnchor), 0}, + {TK_CONFIG_STRING, "-pageheight", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, pageHeightString), 0}, + {TK_CONFIG_STRING, "-pagewidth", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, pageWidthString), 0}, + {TK_CONFIG_STRING, "-pagex", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, pageXString), 0}, + {TK_CONFIG_STRING, "-pagey", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, pageYString), 0}, + {TK_CONFIG_BOOLEAN, "-rotate", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, rotate), 0}, + {TK_CONFIG_PIXELS, "-width", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, width), 0}, + {TK_CONFIG_PIXELS, "-x", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, x), 0}, + {TK_CONFIG_PIXELS, "-y", (char *) NULL, (char *) NULL, + "", Tk_Offset(TkPostscriptInfo, y), 0}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int GetPostscriptPoints _ANSI_ARGS_((Tcl_Interp *interp, + char *string, double *doublePtr)); + +/* + *-------------------------------------------------------------- + * + * TkCanvPostscriptCmd -- + * + * This procedure is invoked to process the "postscript" options + * of the widget command for canvas widgets. See the user + * documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +TkCanvPostscriptCmd(canvasPtr, interp, argc, argv) + TkCanvas *canvasPtr; /* Information about canvas widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. Caller has + * already parsed this command enough + * to know that argv[1] is + * "postscript". */ +{ + TkPostscriptInfo psInfo, *oldInfoPtr; + int result; + Tk_Item *itemPtr; +#define STRING_LENGTH 400 + char string[STRING_LENGTH+1], *p; + time_t now; + size_t length; + int deltaX = 0, deltaY = 0; /* Offset of lower-left corner of + * area to be marked up, measured + * in canvas units from the positioning + * point on the page (reflects + * anchor position). Initial values + * needed only to stop compiler + * warnings. */ + Tcl_HashSearch search; + Tcl_HashEntry *hPtr; + Tcl_DString buffer; + + /* + *---------------------------------------------------------------- + * Initialize the data structure describing Postscript generation, + * then process all the arguments to fill the data structure in. + *---------------------------------------------------------------- + */ + + oldInfoPtr = canvasPtr->psInfoPtr; + canvasPtr->psInfoPtr = &psInfo; + psInfo.x = canvasPtr->xOrigin; + psInfo.y = canvasPtr->yOrigin; + psInfo.width = -1; + psInfo.height = -1; + psInfo.pageXString = NULL; + psInfo.pageYString = NULL; + psInfo.pageX = 72*4.25; + psInfo.pageY = 72*5.5; + psInfo.pageWidthString = NULL; + psInfo.pageHeightString = NULL; + psInfo.scale = 1.0; + psInfo.pageAnchor = TK_ANCHOR_CENTER; + psInfo.rotate = 0; + psInfo.fontVar = NULL; + psInfo.colorVar = NULL; + psInfo.colorMode = NULL; + psInfo.colorLevel = 0; + psInfo.fileName = NULL; + psInfo.channelName = NULL; + psInfo.chan = NULL; + psInfo.prepass = 0; + Tcl_InitHashTable(&psInfo.fontTable, TCL_STRING_KEYS); + result = Tk_ConfigureWidget(canvasPtr->interp, canvasPtr->tkwin, + configSpecs, argc-2, argv+2, (char *) &psInfo, + TK_CONFIG_ARGV_ONLY); + if (result != TCL_OK) { + goto cleanup; + } + + if (psInfo.width == -1) { + psInfo.width = Tk_Width(canvasPtr->tkwin); + } + if (psInfo.height == -1) { + psInfo.height = Tk_Height(canvasPtr->tkwin); + } + psInfo.x2 = psInfo.x + psInfo.width; + psInfo.y2 = psInfo.y + psInfo.height; + + if (psInfo.pageXString != NULL) { + if (GetPostscriptPoints(canvasPtr->interp, psInfo.pageXString, + &psInfo.pageX) != TCL_OK) { + goto cleanup; + } + } + if (psInfo.pageYString != NULL) { + if (GetPostscriptPoints(canvasPtr->interp, psInfo.pageYString, + &psInfo.pageY) != TCL_OK) { + goto cleanup; + } + } + if (psInfo.pageWidthString != NULL) { + if (GetPostscriptPoints(canvasPtr->interp, psInfo.pageWidthString, + &psInfo.scale) != TCL_OK) { + goto cleanup; + } + psInfo.scale /= psInfo.width; + } else if (psInfo.pageHeightString != NULL) { + if (GetPostscriptPoints(canvasPtr->interp, psInfo.pageHeightString, + &psInfo.scale) != TCL_OK) { + goto cleanup; + } + psInfo.scale /= psInfo.height; + } else { + psInfo.scale = (72.0/25.4)*WidthMMOfScreen(Tk_Screen(canvasPtr->tkwin)); + psInfo.scale /= WidthOfScreen(Tk_Screen(canvasPtr->tkwin)); + } + switch (psInfo.pageAnchor) { + case TK_ANCHOR_NW: + case TK_ANCHOR_W: + case TK_ANCHOR_SW: + deltaX = 0; + break; + case TK_ANCHOR_N: + case TK_ANCHOR_CENTER: + case TK_ANCHOR_S: + deltaX = -psInfo.width/2; + break; + case TK_ANCHOR_NE: + case TK_ANCHOR_E: + case TK_ANCHOR_SE: + deltaX = -psInfo.width; + break; + } + switch (psInfo.pageAnchor) { + case TK_ANCHOR_NW: + case TK_ANCHOR_N: + case TK_ANCHOR_NE: + deltaY = - psInfo.height; + break; + case TK_ANCHOR_W: + case TK_ANCHOR_CENTER: + case TK_ANCHOR_E: + deltaY = -psInfo.height/2; + break; + case TK_ANCHOR_SW: + case TK_ANCHOR_S: + case TK_ANCHOR_SE: + deltaY = 0; + break; + } + + if (psInfo.colorMode == NULL) { + psInfo.colorLevel = 2; + } else { + length = strlen(psInfo.colorMode); + if (strncmp(psInfo.colorMode, "monochrome", length) == 0) { + psInfo.colorLevel = 0; + } else if (strncmp(psInfo.colorMode, "gray", length) == 0) { + psInfo.colorLevel = 1; + } else if (strncmp(psInfo.colorMode, "color", length) == 0) { + psInfo.colorLevel = 2; + } else { + Tcl_AppendResult(canvasPtr->interp, "bad color mode \"", + psInfo.colorMode, "\": must be monochrome, ", + "gray, or color", (char *) NULL); + goto cleanup; + } + } + + if (psInfo.fileName != NULL) { + + /* + * Check that -file and -channel are not both specified. + */ + + if (psInfo.channelName != NULL) { + Tcl_AppendResult(canvasPtr->interp, "can't specify both -file", + " and -channel", (char *) NULL); + result = TCL_ERROR; + goto cleanup; + } + + /* + * Check that we are not in a safe interpreter. If we are, disallow + * the -file specification. + */ + + if (Tcl_IsSafe(canvasPtr->interp)) { + Tcl_AppendResult(canvasPtr->interp, "can't specify -file in a", + " safe interpreter", (char *) NULL); + result = TCL_ERROR; + goto cleanup; + } + + p = Tcl_TranslateFileName(canvasPtr->interp, psInfo.fileName, &buffer); + if (p == NULL) { + goto cleanup; + } + psInfo.chan = Tcl_OpenFileChannel(canvasPtr->interp, p, "w", 0666); + Tcl_DStringFree(&buffer); + if (psInfo.chan == NULL) { + goto cleanup; + } + } + + if (psInfo.channelName != NULL) { + int mode; + + /* + * Check that the channel is found in this interpreter and that it + * is open for writing. + */ + + psInfo.chan = Tcl_GetChannel(canvasPtr->interp, psInfo.channelName, + &mode); + if (psInfo.chan == (Tcl_Channel) NULL) { + result = TCL_ERROR; + goto cleanup; + } + if ((mode & TCL_WRITABLE) == 0) { + Tcl_AppendResult(canvasPtr->interp, "channel \"", + psInfo.channelName, "\" wasn't opened for writing", + (char *) NULL); + result = TCL_ERROR; + goto cleanup; + } + } + + /* + *-------------------------------------------------------- + * Make a pre-pass over all of the items, generating Postscript + * and then throwing it away. The purpose of this pass is just + * to collect information about all the fonts in use, so that + * we can output font information in the proper form required + * by the Document Structuring Conventions. + *-------------------------------------------------------- + */ + + psInfo.prepass = 1; + for (itemPtr = canvasPtr->firstItemPtr; itemPtr != NULL; + itemPtr = itemPtr->nextPtr) { + if ((itemPtr->x1 >= psInfo.x2) || (itemPtr->x2 < psInfo.x) + || (itemPtr->y1 >= psInfo.y2) || (itemPtr->y2 < psInfo.y)) { + continue; + } + if (itemPtr->typePtr->postscriptProc == NULL) { + continue; + } + result = (*itemPtr->typePtr->postscriptProc)(canvasPtr->interp, + (Tk_Canvas) canvasPtr, itemPtr, 1); + Tcl_ResetResult(canvasPtr->interp); + if (result != TCL_OK) { + /* + * An error just occurred. Just skip out of this loop. + * There's no need to report the error now; it can be + * reported later (errors can happen later that don't + * happen now, so we still have to check for errors later + * anyway). + */ + break; + } + } + psInfo.prepass = 0; + + /* + *-------------------------------------------------------- + * Generate the header and prolog for the Postscript. + *-------------------------------------------------------- + */ + + Tcl_AppendResult(canvasPtr->interp, "%!PS-Adobe-3.0 EPSF-3.0\n", + "%%Creator: Tk Canvas Widget\n", (char *) NULL); +#if !(defined(__WIN32__) || defined(MAC_TCL)) + if (!Tcl_IsSafe(interp)) { + struct passwd *pwPtr = getpwuid(getuid()); + Tcl_AppendResult(canvasPtr->interp, "%%For: ", + (pwPtr != NULL) ? pwPtr->pw_gecos : "Unknown", "\n", + (char *) NULL); + endpwent(); + } +#endif /* __WIN32__ || MAC_TCL */ + Tcl_AppendResult(canvasPtr->interp, "%%Title: Window ", + Tk_PathName(canvasPtr->tkwin), "\n", (char *) NULL); + time(&now); + Tcl_AppendResult(canvasPtr->interp, "%%CreationDate: ", + ctime(&now), (char *) NULL); + if (!psInfo.rotate) { + sprintf(string, "%d %d %d %d", + (int) (psInfo.pageX + psInfo.scale*deltaX), + (int) (psInfo.pageY + psInfo.scale*deltaY), + (int) (psInfo.pageX + psInfo.scale*(deltaX + psInfo.width) + + 1.0), + (int) (psInfo.pageY + psInfo.scale*(deltaY + psInfo.height) + + 1.0)); + } else { + sprintf(string, "%d %d %d %d", + (int) (psInfo.pageX - psInfo.scale*(deltaY + psInfo.height)), + (int) (psInfo.pageY + psInfo.scale*deltaX), + (int) (psInfo.pageX - psInfo.scale*deltaY + 1.0), + (int) (psInfo.pageY + psInfo.scale*(deltaX + psInfo.width) + + 1.0)); + } + Tcl_AppendResult(canvasPtr->interp, "%%BoundingBox: ", string, + "\n", (char *) NULL); + Tcl_AppendResult(canvasPtr->interp, "%%Pages: 1\n", + "%%DocumentData: Clean7Bit\n", (char *) NULL); + Tcl_AppendResult(canvasPtr->interp, "%%Orientation: ", + psInfo.rotate ? "Landscape\n" : "Portrait\n", (char *) NULL); + p = "%%DocumentNeededResources: font "; + for (hPtr = Tcl_FirstHashEntry(&psInfo.fontTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + Tcl_AppendResult(canvasPtr->interp, p, + Tcl_GetHashKey(&psInfo.fontTable, hPtr), + "\n", (char *) NULL); + p = "%%+ font "; + } + Tcl_AppendResult(canvasPtr->interp, "%%EndComments\n\n", (char *) NULL); + + /* + * Read a standard prolog file in a native way and insert it into + * the Postscript. + */ + + if (TkGetNativeProlog(canvasPtr->interp) != TCL_OK) { + result = TCL_ERROR; + goto cleanup; + } + if (psInfo.chan != NULL) { + Tcl_Write(psInfo.chan, canvasPtr->interp->result, -1); + Tcl_ResetResult(canvasPtr->interp); + } + + /* + *----------------------------------------------------------- + * Document setup: set the color level and include fonts. + *----------------------------------------------------------- + */ + + sprintf(string, "/CL %d def\n", psInfo.colorLevel); + Tcl_AppendResult(canvasPtr->interp, "%%BeginSetup\n", string, + (char *) NULL); + for (hPtr = Tcl_FirstHashEntry(&psInfo.fontTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + Tcl_AppendResult(canvasPtr->interp, "%%IncludeResource: font ", + Tcl_GetHashKey(&psInfo.fontTable, hPtr), "\n", (char *) NULL); + } + Tcl_AppendResult(canvasPtr->interp, "%%EndSetup\n\n", (char *) NULL); + + /* + *----------------------------------------------------------- + * Page setup: move to page positioning point, rotate if + * needed, set scale factor, offset for proper anchor position, + * and set clip region. + *----------------------------------------------------------- + */ + + Tcl_AppendResult(canvasPtr->interp, "%%Page: 1 1\n", "save\n", + (char *) NULL); + sprintf(string, "%.1f %.1f translate\n", psInfo.pageX, psInfo.pageY); + Tcl_AppendResult(canvasPtr->interp, string, (char *) NULL); + if (psInfo.rotate) { + Tcl_AppendResult(canvasPtr->interp, "90 rotate\n", (char *) NULL); + } + sprintf(string, "%.4g %.4g scale\n", psInfo.scale, psInfo.scale); + Tcl_AppendResult(canvasPtr->interp, string, (char *) NULL); + sprintf(string, "%d %d translate\n", deltaX - psInfo.x, deltaY); + Tcl_AppendResult(canvasPtr->interp, string, (char *) NULL); + sprintf(string, "%d %.15g moveto %d %.15g lineto %d %.15g lineto %d %.15g", + psInfo.x, Tk_CanvasPsY((Tk_Canvas) canvasPtr, (double) psInfo.y), + psInfo.x2, Tk_CanvasPsY((Tk_Canvas) canvasPtr, (double) psInfo.y), + psInfo.x2, Tk_CanvasPsY((Tk_Canvas) canvasPtr, (double) psInfo.y2), + psInfo.x, Tk_CanvasPsY((Tk_Canvas) canvasPtr, (double) psInfo.y2)); + Tcl_AppendResult(canvasPtr->interp, string, + " lineto closepath clip newpath\n", (char *) NULL); + if (psInfo.chan != NULL) { + Tcl_Write(psInfo.chan, canvasPtr->interp->result, -1); + Tcl_ResetResult(canvasPtr->interp); + } + + /* + *--------------------------------------------------------------------- + * Iterate through all the items, having each relevant one draw itself. + * Quit if any of the items returns an error. + *--------------------------------------------------------------------- + */ + + result = TCL_OK; + for (itemPtr = canvasPtr->firstItemPtr; itemPtr != NULL; + itemPtr = itemPtr->nextPtr) { + if ((itemPtr->x1 >= psInfo.x2) || (itemPtr->x2 < psInfo.x) + || (itemPtr->y1 >= psInfo.y2) || (itemPtr->y2 < psInfo.y)) { + continue; + } + if (itemPtr->typePtr->postscriptProc == NULL) { + continue; + } + Tcl_AppendResult(canvasPtr->interp, "gsave\n", (char *) NULL); + result = (*itemPtr->typePtr->postscriptProc)(canvasPtr->interp, + (Tk_Canvas) canvasPtr, itemPtr, 0); + if (result != TCL_OK) { + char msg[100]; + + sprintf(msg, "\n (generating Postscript for item %d)", + itemPtr->id); + Tcl_AddErrorInfo(canvasPtr->interp, msg); + goto cleanup; + } + Tcl_AppendResult(canvasPtr->interp, "grestore\n", (char *) NULL); + if (psInfo.chan != NULL) { + Tcl_Write(psInfo.chan, canvasPtr->interp->result, -1); + Tcl_ResetResult(canvasPtr->interp); + } + } + + /* + *--------------------------------------------------------------------- + * Output page-end information, such as commands to print the page + * and document trailer stuff. + *--------------------------------------------------------------------- + */ + + Tcl_AppendResult(canvasPtr->interp, "restore showpage\n\n", + "%%Trailer\nend\n%%EOF\n", (char *) NULL); + if (psInfo.chan != NULL) { + Tcl_Write(psInfo.chan, canvasPtr->interp->result, -1); + Tcl_ResetResult(canvasPtr->interp); + } + + /* + * Clean up psInfo to release malloc'ed stuff. + */ + + cleanup: + if (psInfo.pageXString != NULL) { + ckfree(psInfo.pageXString); + } + if (psInfo.pageYString != NULL) { + ckfree(psInfo.pageYString); + } + if (psInfo.pageWidthString != NULL) { + ckfree(psInfo.pageWidthString); + } + if (psInfo.pageHeightString != NULL) { + ckfree(psInfo.pageHeightString); + } + if (psInfo.fontVar != NULL) { + ckfree(psInfo.fontVar); + } + if (psInfo.colorVar != NULL) { + ckfree(psInfo.colorVar); + } + if (psInfo.colorMode != NULL) { + ckfree(psInfo.colorMode); + } + if (psInfo.fileName != NULL) { + ckfree(psInfo.fileName); + } + if ((psInfo.chan != NULL) && (psInfo.channelName == NULL)) { + Tcl_Close(canvasPtr->interp, psInfo.chan); + } + if (psInfo.channelName != NULL) { + ckfree(psInfo.channelName); + } + Tcl_DeleteHashTable(&psInfo.fontTable); + canvasPtr->psInfoPtr = oldInfoPtr; + return result; +} + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasPsColor -- + * + * This procedure is called by individual canvas items when + * they want to set a color value for output. Given information + * about an X color, this procedure will generate Postscript + * commands to set up an appropriate color in Postscript. + * + * Results: + * Returns a standard Tcl return value. If an error occurs + * then an error message will be left in interp->result. + * If no error occurs, then additional Postscript will be + * appended to interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_CanvasPsColor(interp, canvas, colorPtr) + Tcl_Interp *interp; /* Interpreter for returning Postscript + * or error message. */ + Tk_Canvas canvas; /* Information about canvas. */ + XColor *colorPtr; /* Information about color. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) canvas; + TkPostscriptInfo *psInfoPtr = canvasPtr->psInfoPtr; + int tmp; + double red, green, blue; + char string[200]; + + if (psInfoPtr->prepass) { + return TCL_OK; + } + + /* + * If there is a color map defined, then look up the color's name + * in the map and use the Postscript commands found there, if there + * are any. + */ + + if (psInfoPtr->colorVar != NULL) { + char *cmdString; + + cmdString = Tcl_GetVar2(interp, psInfoPtr->colorVar, + Tk_NameOfColor(colorPtr), 0); + if (cmdString != NULL) { + Tcl_AppendResult(interp, cmdString, "\n", (char *) NULL); + return TCL_OK; + } + } + + /* + * No color map entry for this color. Grab the color's intensities + * and output Postscript commands for them. Special note: X uses + * a range of 0-65535 for intensities, but most displays only use + * a range of 0-255, which maps to (0, 256, 512, ... 65280) in the + * X scale. This means that there's no way to get perfect white, + * since the highest intensity is only 65280 out of 65535. To + * work around this problem, rescale the X intensity to a 0-255 + * scale and use that as the basis for the Postscript colors. This + * scheme still won't work if the display only uses 4 bits per color, + * but most diplays use at least 8 bits. + */ + + tmp = colorPtr->red; + red = ((double) (tmp >> 8))/255.0; + tmp = colorPtr->green; + green = ((double) (tmp >> 8))/255.0; + tmp = colorPtr->blue; + blue = ((double) (tmp >> 8))/255.0; + sprintf(string, "%.3f %.3f %.3f setrgbcolor AdjustColor\n", + red, green, blue); + Tcl_AppendResult(interp, string, (char *) NULL); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasPsFont -- + * + * This procedure is called by individual canvas items when + * they want to output text. Given information about an X + * font, this procedure will generate Postscript commands + * to set up an appropriate font in Postscript. + * + * Results: + * Returns a standard Tcl return value. If an error occurs + * then an error message will be left in interp->result. + * If no error occurs, then additional Postscript will be + * appended to the interp->result. + * + * Side effects: + * The Postscript font name is entered into psInfoPtr->fontTable + * if it wasn't already there. + * + *-------------------------------------------------------------- + */ + +int +Tk_CanvasPsFont(interp, canvas, tkfont) + Tcl_Interp *interp; /* Interpreter for returning Postscript + * or error message. */ + Tk_Canvas canvas; /* Information about canvas. */ + Tk_Font tkfont; /* Information about font in which text + * is to be printed. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) canvas; + TkPostscriptInfo *psInfoPtr = canvasPtr->psInfoPtr; + char *end; + char pointString[20]; + Tcl_DString ds; + int i, points; + + /* + * First, look up the font's name in the font map, if there is one. + * If there is an entry for this font, it consists of a list + * containing font name and size. Use this information. + */ + + Tcl_DStringInit(&ds); + + if (psInfoPtr->fontVar != NULL) { + char *list, **argv; + int argc; + double size; + char *name; + + name = Tk_NameOfFont(tkfont); + list = Tcl_GetVar2(interp, psInfoPtr->fontVar, name, 0); + if (list != NULL) { + if (Tcl_SplitList(interp, list, &argc, &argv) != TCL_OK) { + badMapEntry: + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad font map entry for \"", name, + "\": \"", list, "\"", (char *) NULL); + return TCL_ERROR; + } + if (argc != 2) { + goto badMapEntry; + } + size = strtod(argv[1], &end); + if ((size <= 0) || (*end != 0)) { + goto badMapEntry; + } + + Tcl_DStringAppend(&ds, argv[0], -1); + points = (int) size; + + ckfree((char *) argv); + goto findfont; + } + } + + points = Tk_PostscriptFontName(tkfont, &ds); + + findfont: + sprintf(pointString, "%d", points); + Tcl_AppendResult(interp, "/", Tcl_DStringValue(&ds), " findfont ", + pointString, " scalefont ", (char *) NULL); + if (strncasecmp(Tcl_DStringValue(&ds), "Symbol", 7) != 0) { + Tcl_AppendResult(interp, "ISOEncode ", (char *) NULL); + } + Tcl_AppendResult(interp, "setfont\n", (char *) NULL); + Tcl_CreateHashEntry(&psInfoPtr->fontTable, Tcl_DStringValue(&ds), &i); + Tcl_DStringFree(&ds); + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasPsBitmap -- + * + * This procedure is called to output the contents of a + * sub-region of a bitmap in proper image data format for + * Postscript (i.e. data between angle brackets, one bit + * per pixel). + * + * Results: + * Returns a standard Tcl return value. If an error occurs + * then an error message will be left in interp->result. + * If no error occurs, then additional Postscript will be + * appended to interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_CanvasPsBitmap(interp, canvas, bitmap, startX, startY, width, height) + Tcl_Interp *interp; /* Interpreter for returning Postscript + * or error message. */ + Tk_Canvas canvas; /* Information about canvas. */ + Pixmap bitmap; /* Bitmap for which to generate + * Postscript. */ + int startX, startY; /* Coordinates of upper-left corner + * of rectangular region to output. */ + int width, height; /* Height of rectangular region. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) canvas; + TkPostscriptInfo *psInfoPtr = canvasPtr->psInfoPtr; + XImage *imagePtr; + int charsInLine, x, y, lastX, lastY, value, mask; + unsigned int totalWidth, totalHeight; + char string[100]; + Window dummyRoot; + int dummyX, dummyY; + unsigned dummyBorderwidth, dummyDepth; + + if (psInfoPtr->prepass) { + return TCL_OK; + } + + /* + * The following call should probably be a call to Tk_SizeOfBitmap + * instead, but it seems that we are occasionally invoked by custom + * item types that create their own bitmaps without registering them + * with Tk. XGetGeometry is a bit slower than Tk_SizeOfBitmap, but + * it shouldn't matter here. + */ + + XGetGeometry(Tk_Display(Tk_CanvasTkwin(canvas)), bitmap, &dummyRoot, + (int *) &dummyX, (int *) &dummyY, (unsigned int *) &totalWidth, + (unsigned int *) &totalHeight, &dummyBorderwidth, &dummyDepth); + imagePtr = XGetImage(Tk_Display(canvasPtr->tkwin), bitmap, 0, 0, + totalWidth, totalHeight, 1, XYPixmap); + Tcl_AppendResult(interp, "<", (char *) NULL); + mask = 0x80; + value = 0; + charsInLine = 0; + lastX = startX + width - 1; + lastY = startY + height - 1; + for (y = lastY; y >= startY; y--) { + for (x = startX; x <= lastX; x++) { + if (XGetPixel(imagePtr, x, y)) { + value |= mask; + } + mask >>= 1; + if (mask == 0) { + sprintf(string, "%02x", value); + Tcl_AppendResult(interp, string, (char *) NULL); + mask = 0x80; + value = 0; + charsInLine += 2; + if (charsInLine >= 60) { + Tcl_AppendResult(interp, "\n", (char *) NULL); + charsInLine = 0; + } + } + } + if (mask != 0x80) { + sprintf(string, "%02x", value); + Tcl_AppendResult(interp, string, (char *) NULL); + mask = 0x80; + value = 0; + charsInLine += 2; + } + } + Tcl_AppendResult(interp, ">", (char *) NULL); + XDestroyImage(imagePtr); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasPsStipple -- + * + * This procedure is called by individual canvas items when + * they have created a path that they'd like to be filled with + * a stipple pattern. Given information about an X bitmap, + * this procedure will generate Postscript commands to fill + * the current clip region using a stipple pattern defined by the + * bitmap. + * + * Results: + * Returns a standard Tcl return value. If an error occurs + * then an error message will be left in interp->result. + * If no error occurs, then additional Postscript will be + * appended to interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_CanvasPsStipple(interp, canvas, bitmap) + Tcl_Interp *interp; /* Interpreter for returning Postscript + * or error message. */ + Tk_Canvas canvas; /* Information about canvas. */ + Pixmap bitmap; /* Bitmap to use for stippling. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) canvas; + TkPostscriptInfo *psInfoPtr = canvasPtr->psInfoPtr; + int width, height; + char string[100]; + Window dummyRoot; + int dummyX, dummyY; + unsigned dummyBorderwidth, dummyDepth; + + if (psInfoPtr->prepass) { + return TCL_OK; + } + + /* + * The following call should probably be a call to Tk_SizeOfBitmap + * instead, but it seems that we are occasionally invoked by custom + * item types that create their own bitmaps without registering them + * with Tk. XGetGeometry is a bit slower than Tk_SizeOfBitmap, but + * it shouldn't matter here. + */ + + XGetGeometry(Tk_Display(Tk_CanvasTkwin(canvas)), bitmap, &dummyRoot, + (int *) &dummyX, (int *) &dummyY, (unsigned *) &width, + (unsigned *) &height, &dummyBorderwidth, &dummyDepth); + sprintf(string, "%d %d ", width, height); + Tcl_AppendResult(interp, string, (char *) NULL); + if (Tk_CanvasPsBitmap(interp, (Tk_Canvas) canvasPtr, bitmap, 0, 0, + width, height) != TCL_OK) { + return TCL_ERROR; + } + Tcl_AppendResult(interp, " StippleFill\n", (char *) NULL); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasPsY -- + * + * Given a y-coordinate in canvas coordinates, this procedure + * returns a y-coordinate to use for Postscript output. + * + * Results: + * Returns the Postscript coordinate that corresponds to + * "y". + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +double +Tk_CanvasPsY(canvas, y) + Tk_Canvas canvas; /* Token for canvas on whose behalf + * Postscript is being generated. */ + double y; /* Y-coordinate in canvas coords. */ +{ + TkPostscriptInfo *psInfoPtr = ((TkCanvas *) canvas)->psInfoPtr; + + return psInfoPtr->y2 - y; +} + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasPsPath -- + * + * Given an array of points for a path, generate Postscript + * commands to create the path. + * + * Results: + * Postscript commands get appended to what's in interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +Tk_CanvasPsPath(interp, canvas, coordPtr, numPoints) + Tcl_Interp *interp; /* Put generated Postscript in this + * interpreter's result field. */ + Tk_Canvas canvas; /* Canvas on whose behalf Postscript + * is being generated. */ + double *coordPtr; /* Pointer to first in array of + * 2*numPoints coordinates giving + * points for path. */ + int numPoints; /* Number of points at *coordPtr. */ +{ + TkPostscriptInfo *psInfoPtr = ((TkCanvas *) canvas)->psInfoPtr; + char buffer[200]; + + if (psInfoPtr->prepass) { + return; + } + sprintf(buffer, "%.15g %.15g moveto\n", coordPtr[0], + Tk_CanvasPsY(canvas, coordPtr[1])); + Tcl_AppendResult(interp, buffer, (char *) NULL); + for (numPoints--, coordPtr += 2; numPoints > 0; + numPoints--, coordPtr += 2) { + sprintf(buffer, "%.15g %.15g lineto\n", coordPtr[0], + Tk_CanvasPsY(canvas, coordPtr[1])); + Tcl_AppendResult(interp, buffer, (char *) NULL); + } +} + +/* + *-------------------------------------------------------------- + * + * GetPostscriptPoints -- + * + * Given a string, returns the number of Postscript points + * corresponding to that string. + * + * Results: + * The return value is a standard Tcl return result. If + * TCL_OK is returned, then everything went well and the + * screen distance is stored at *doublePtr; otherwise + * TCL_ERROR is returned and an error message is left in + * interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +GetPostscriptPoints(interp, string, doublePtr) + Tcl_Interp *interp; /* Use this for error reporting. */ + char *string; /* String describing a screen distance. */ + double *doublePtr; /* Place to store converted result. */ +{ + char *end; + double d; + + d = strtod(string, &end); + if (end == string) { + error: + Tcl_AppendResult(interp, "bad distance \"", string, + "\"", (char *) NULL); + return TCL_ERROR; + } + while ((*end != '\0') && isspace(UCHAR(*end))) { + end++; + } + switch (*end) { + case 'c': + d *= 72.0/2.54; + end++; + break; + case 'i': + d *= 72.0; + end++; + break; + case 'm': + d *= 72.0/25.4; + end++; + break; + case 0: + break; + case 'p': + end++; + break; + default: + goto error; + } + while ((*end != '\0') && isspace(UCHAR(*end))) { + end++; + } + if (*end != 0) { + goto error; + } + *doublePtr = d; + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * TkGetProlog -- + * + * Locate and load the postscript prolog. + * + * Results: + * A standard Tcl Result. If everything is OK the prolog + * will be located in the result string of the interpreter. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkGetProlog(interp) + Tcl_Interp *interp; /* Places the prolog in the result. */ +{ + char *libDir; + Tcl_Channel chan; + Tcl_DString buffer, buffer2; + char *prologPathParts[2]; + int bufferSize; + char *prologBuffer; + + libDir = Tcl_GetVar(interp, "tk_library", TCL_GLOBAL_ONLY); + if (libDir == NULL) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "couldn't find library directory: ", + "tk_library variable doesn't exist", (char *) NULL); + return TCL_ERROR; + } + Tcl_TranslateFileName(interp, libDir, &buffer); + prologPathParts[0] = buffer.string; + prologPathParts[1] = "prolog.ps"; + Tcl_DStringInit(&buffer2); + Tcl_JoinPath(2, prologPathParts, &buffer2); + Tcl_DStringFree(&buffer); + + /* + * Compute size of file by seeking to the end of the file. This will + * overallocate if we are performing CRLF translation. + */ + + chan = Tcl_OpenFileChannel(NULL, buffer2.string, "r", 0); + if (chan == NULL) { + /* + * We have to set the error message ourselves because the + * interp's result need to be reset. + */ + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "couldn't open \"", + buffer2.string, "\": ", Tcl_PosixError(interp), (char *) NULL); + Tcl_DStringFree(&buffer2); + return TCL_ERROR; + } + + bufferSize = Tcl_Seek(chan, 0L, SEEK_END); + (void) Tcl_Seek(chan, 0L, SEEK_SET); + if (bufferSize < 0) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "error seeking to end of file \"", + buffer2.string, "\": ", Tcl_PosixError(interp), (char *) NULL); + Tcl_Close(NULL, chan); + Tcl_DStringFree(&buffer2); + return TCL_ERROR; + + } + prologBuffer = (char *) ckalloc((unsigned) bufferSize+1); + bufferSize = Tcl_Read(chan, prologBuffer, bufferSize); + Tcl_Close(NULL, chan); + if (bufferSize < 0) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "error reading file \"", buffer2.string, + "\": ", Tcl_PosixError(interp), (char *) NULL); + Tcl_DStringFree(&buffer2); + return TCL_ERROR; + } + Tcl_DStringFree(&buffer2); + prologBuffer[bufferSize] = 0; + Tcl_AppendResult(interp, prologBuffer, (char *) NULL); + ckfree(prologBuffer); + + return TCL_OK; +} diff --git a/generic/tkCanvText.c b/generic/tkCanvText.c new file mode 100644 index 0000000..2938ba1 --- /dev/null +++ b/generic/tkCanvText.c @@ -0,0 +1,1313 @@ +/* + * tkCanvText.c -- + * + * This file implements text items for canvas widgets. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvText.c 1.68 97/10/09 17:44:53 + */ + +#include <stdio.h> +#include "tkInt.h" +#include "tkCanvas.h" +#include "tkPort.h" +#include "default.h" + +/* + * The structure below defines the record for each text item. + */ + +typedef struct TextItem { + Tk_Item header; /* Generic stuff that's the same for all + * types. MUST BE FIRST IN STRUCTURE. */ + Tk_CanvasTextInfo *textInfoPtr; + /* Pointer to a structure containing + * information about the selection and + * insertion cursor. The structure is owned + * by (and shared with) the generic canvas + * code. */ + /* + * Fields that are set by widget commands other than "configure". + */ + + double x, y; /* Positioning point for text. */ + int insertPos; /* Insertion cursor is displayed just to left + * of character with this index. */ + + /* + * Configuration settings that are updated by Tk_ConfigureWidget. + */ + + Tk_Anchor anchor; /* Where to anchor text relative to (x,y). */ + XColor *color; /* Color for text. */ + Tk_Font tkfont; /* Font for drawing text. */ + Tk_Justify justify; /* Justification mode for text. */ + Pixmap stipple; /* Stipple bitmap for text, or None. */ + char *text; /* Text for item (malloc-ed). */ + int width; /* Width of lines for word-wrap, pixels. + * Zero means no word-wrap. */ + + /* + * Fields whose values are derived from the current values of the + * configuration settings above. + */ + + int numChars; /* Number of non-NULL characters in text. */ + Tk_TextLayout textLayout; /* Cached text layout information. */ + int leftEdge; /* Pixel location of the left edge of the + * text item; where the left border of the + * text layout is drawn. */ + int rightEdge; /* Pixel just to right of right edge of + * area of text item. Used for selecting up + * to end of line. */ + GC gc; /* Graphics context for drawing text. */ + GC selTextGC; /* Graphics context for selected text. */ + GC cursorOffGC; /* If not None, this gives a graphics context + * to use to draw the insertion cursor when + * it's off. Used if the selection and + * insertion cursor colors are the same. */ +} TextItem; + +/* + * Information used for parsing configuration specs: + */ + +static Tk_CustomOption tagsOption = {Tk_CanvasTagsParseProc, + Tk_CanvasTagsPrintProc, (ClientData) NULL +}; + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_ANCHOR, "-anchor", (char *) NULL, (char *) NULL, + "center", Tk_Offset(TextItem, anchor), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_COLOR, "-fill", (char *) NULL, (char *) NULL, + "black", Tk_Offset(TextItem, color), 0}, + {TK_CONFIG_FONT, "-font", (char *) NULL, (char *) NULL, + DEF_CANVTEXT_FONT, Tk_Offset(TextItem, tkfont), 0}, + {TK_CONFIG_JUSTIFY, "-justify", (char *) NULL, (char *) NULL, + "left", Tk_Offset(TextItem, justify), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_BITMAP, "-stipple", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TextItem, stipple), TK_CONFIG_NULL_OK}, + {TK_CONFIG_CUSTOM, "-tags", (char *) NULL, (char *) NULL, + (char *) NULL, 0, TK_CONFIG_NULL_OK, &tagsOption}, + {TK_CONFIG_STRING, "-text", (char *) NULL, (char *) NULL, + "", Tk_Offset(TextItem, text), 0}, + {TK_CONFIG_PIXELS, "-width", (char *) NULL, (char *) NULL, + "0", Tk_Offset(TextItem, width), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Prototypes for procedures defined in this file: + */ + +static void ComputeTextBbox _ANSI_ARGS_((Tk_Canvas canvas, + TextItem *textPtr)); +static int ConfigureText _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv, int flags)); +static int CreateText _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, struct Tk_Item *itemPtr, + int argc, char **argv)); +static void DeleteText _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display)); +static void DisplayCanvText _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display, Drawable dst, + int x, int y, int width, int height)); +static int GetSelText _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, int offset, char *buffer, + int maxBytes)); +static int GetTextIndex _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, + char *indexString, int *indexPtr)); +static void ScaleText _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double originX, double originY, + double scaleX, double scaleY)); +static void SetTextCursor _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, int index)); +static int TextCoords _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, + int argc, char **argv)); +static void TextDeleteChars _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, int first, int last)); +static void TextInsert _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, int beforeThis, char *string)); +static int TextToArea _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *rectPtr)); +static double TextToPoint _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *pointPtr)); +static int TextToPostscript _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int prepass)); +static void TranslateText _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double deltaX, double deltaY)); + +/* + * The structures below defines the rectangle and oval item types + * by means of procedures that can be invoked by generic item code. + */ + +Tk_ItemType tkTextType = { + "text", /* name */ + sizeof(TextItem), /* itemSize */ + CreateText, /* createProc */ + configSpecs, /* configSpecs */ + ConfigureText, /* configureProc */ + TextCoords, /* coordProc */ + DeleteText, /* deleteProc */ + DisplayCanvText, /* displayProc */ + 0, /* alwaysRedraw */ + TextToPoint, /* pointProc */ + TextToArea, /* areaProc */ + TextToPostscript, /* postscriptProc */ + ScaleText, /* scaleProc */ + TranslateText, /* translateProc */ + GetTextIndex, /* indexProc */ + SetTextCursor, /* icursorProc */ + GetSelText, /* selectionProc */ + TextInsert, /* insertProc */ + TextDeleteChars, /* dTextProc */ + (Tk_ItemType *) NULL /* nextPtr */ +}; + +/* + *-------------------------------------------------------------- + * + * CreateText -- + * + * This procedure is invoked to create a new text item + * in a canvas. + * + * Results: + * A standard Tcl return value. If an error occurred in + * creating the item then an error message is left in + * interp->result; in this case itemPtr is left uninitialized + * so it can be safely freed by the caller. + * + * Side effects: + * A new text item is created. + * + *-------------------------------------------------------------- + */ + +static int +CreateText(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Canvas to hold new item. */ + Tk_Item *itemPtr; /* Record to hold new item; header + * has been initialized by caller. */ + int argc; /* Number of arguments in argv. */ + char **argv; /* Arguments describing rectangle. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tk_PathName(Tk_CanvasTkwin(canvas)), " create ", + itemPtr->typePtr->name, " x y ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + /* + * Carry out initialization that is needed in order to clean + * up after errors during the the remainder of this procedure. + */ + + textPtr->textInfoPtr = Tk_CanvasGetTextInfo(canvas); + + textPtr->insertPos = 0; + + textPtr->anchor = TK_ANCHOR_CENTER; + textPtr->color = NULL; + textPtr->tkfont = NULL; + textPtr->justify = TK_JUSTIFY_LEFT; + textPtr->stipple = None; + textPtr->text = NULL; + textPtr->width = 0; + + textPtr->numChars = 0; + textPtr->textLayout = NULL; + textPtr->leftEdge = 0; + textPtr->rightEdge = 0; + textPtr->gc = None; + textPtr->selTextGC = None; + textPtr->cursorOffGC = None; + + /* + * Process the arguments to fill in the item record. + */ + + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], &textPtr->x) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], &textPtr->y) + != TCL_OK)) { + return TCL_ERROR; + } + + if (ConfigureText(interp, canvas, itemPtr, argc-2, argv+2, 0) != TCL_OK) { + DeleteText(canvas, itemPtr, Tk_Display(Tk_CanvasTkwin(canvas))); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * TextCoords -- + * + * This procedure is invoked to process the "coords" widget + * command on text items. See the user documentation for + * details on what it does. + * + * Results: + * Returns TCL_OK or TCL_ERROR, and sets interp->result. + * + * Side effects: + * The coordinates for the given item may be changed. + * + *-------------------------------------------------------------- + */ + +static int +TextCoords(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item whose coordinates are to be + * read or modified. */ + int argc; /* Number of coordinates supplied in + * argv. */ + char **argv; /* Array of coordinates: x1, y1, + * x2, y2, ... */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + char x[TCL_DOUBLE_SPACE], y[TCL_DOUBLE_SPACE]; + + if (argc == 0) { + Tcl_PrintDouble(interp, textPtr->x, x); + Tcl_PrintDouble(interp, textPtr->y, y); + Tcl_AppendResult(interp, x, " ", y, (char *) NULL); + } else if (argc == 2) { + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], &textPtr->x) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], + &textPtr->y) != TCL_OK)) { + return TCL_ERROR; + } + ComputeTextBbox(canvas, textPtr); + } else { + sprintf(interp->result, + "wrong # coordinates: expected 0 or 2, got %d", argc); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ConfigureText -- + * + * This procedure is invoked to configure various aspects + * of a text item, such as its border and background colors. + * + * Results: + * A standard Tcl result code. If an error occurs, then + * an error message is left in interp->result. + * + * Side effects: + * Configuration information, such as colors and stipple + * patterns, may be set for itemPtr. + * + *-------------------------------------------------------------- + */ + +static int +ConfigureText(interp, canvas, itemPtr, argc, argv, flags) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Rectangle item to reconfigure. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Arguments describing things to configure. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + XGCValues gcValues; + GC newGC, newSelGC; + unsigned long mask; + Tk_Window tkwin; + Tk_CanvasTextInfo *textInfoPtr = textPtr->textInfoPtr; + XColor *selBgColorPtr; + + tkwin = Tk_CanvasTkwin(canvas); + if (Tk_ConfigureWidget(interp, tkwin, configSpecs, argc, argv, + (char *) textPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few of the options require additional processing, such as + * graphics contexts. + */ + + newGC = newSelGC = None; + if ((textPtr->color != NULL) && (textPtr->tkfont != NULL)) { + gcValues.foreground = textPtr->color->pixel; + gcValues.font = Tk_FontId(textPtr->tkfont); + mask = GCForeground|GCFont; + if (textPtr->stipple != None) { + gcValues.stipple = textPtr->stipple; + gcValues.fill_style = FillStippled; + mask |= GCForeground|GCStipple|GCFillStyle; + } + newGC = Tk_GetGC(tkwin, mask, &gcValues); + gcValues.foreground = textInfoPtr->selFgColorPtr->pixel; + newSelGC = Tk_GetGC(tkwin, mask, &gcValues); + } + if (textPtr->gc != None) { + Tk_FreeGC(Tk_Display(tkwin), textPtr->gc); + } + textPtr->gc = newGC; + if (textPtr->selTextGC != None) { + Tk_FreeGC(Tk_Display(tkwin), textPtr->selTextGC); + } + textPtr->selTextGC = newSelGC; + + selBgColorPtr = Tk_3DBorderColor(textInfoPtr->selBorder); + if (Tk_3DBorderColor(textInfoPtr->insertBorder)->pixel + == selBgColorPtr->pixel) { + if (selBgColorPtr->pixel == BlackPixelOfScreen(Tk_Screen(tkwin))) { + gcValues.foreground = WhitePixelOfScreen(Tk_Screen(tkwin)); + } else { + gcValues.foreground = BlackPixelOfScreen(Tk_Screen(tkwin)); + } + newGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + } else { + newGC = None; + } + if (textPtr->cursorOffGC != None) { + Tk_FreeGC(Tk_Display(tkwin), textPtr->cursorOffGC); + } + textPtr->cursorOffGC = newGC; + + + /* + * If the text was changed, move the selection and insertion indices + * to keep them inside the item. + */ + + textPtr->numChars = strlen(textPtr->text); + if (textInfoPtr->selItemPtr == itemPtr) { + if (textInfoPtr->selectFirst >= textPtr->numChars) { + textInfoPtr->selItemPtr = NULL; + } else { + if (textInfoPtr->selectLast >= textPtr->numChars) { + textInfoPtr->selectLast = textPtr->numChars-1; + } + if ((textInfoPtr->anchorItemPtr == itemPtr) + && (textInfoPtr->selectAnchor >= textPtr->numChars)) { + textInfoPtr->selectAnchor = textPtr->numChars-1; + } + } + } + if (textPtr->insertPos >= textPtr->numChars) { + textPtr->insertPos = textPtr->numChars; + } + + ComputeTextBbox(canvas, textPtr); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * DeleteText -- + * + * This procedure is called to clean up the data structure + * associated with a text item. + * + * Results: + * None. + * + * Side effects: + * Resources associated with itemPtr are released. + * + *-------------------------------------------------------------- + */ + +static void +DeleteText(canvas, itemPtr, display) + Tk_Canvas canvas; /* Info about overall canvas widget. */ + Tk_Item *itemPtr; /* Item that is being deleted. */ + Display *display; /* Display containing window for + * canvas. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + + if (textPtr->color != NULL) { + Tk_FreeColor(textPtr->color); + } + Tk_FreeFont(textPtr->tkfont); + if (textPtr->stipple != None) { + Tk_FreeBitmap(display, textPtr->stipple); + } + if (textPtr->text != NULL) { + ckfree(textPtr->text); + } + + Tk_FreeTextLayout(textPtr->textLayout); + if (textPtr->gc != None) { + Tk_FreeGC(display, textPtr->gc); + } + if (textPtr->selTextGC != None) { + Tk_FreeGC(display, textPtr->selTextGC); + } + if (textPtr->cursorOffGC != None) { + Tk_FreeGC(display, textPtr->cursorOffGC); + } +} + +/* + *-------------------------------------------------------------- + * + * ComputeTextBbox -- + * + * This procedure is invoked to compute the bounding box of + * all the pixels that may be drawn as part of a text item. + * In addition, it recomputes all of the geometry information + * used to display a text item or check for mouse hits. + * + * Results: + * None. + * + * Side effects: + * The fields x1, y1, x2, and y2 are updated in the header + * for itemPtr, and the linePtr structure is regenerated + * for itemPtr. + * + *-------------------------------------------------------------- + */ + +static void +ComputeTextBbox(canvas, textPtr) + Tk_Canvas canvas; /* Canvas that contains item. */ + TextItem *textPtr; /* Item whose bbos is to be + * recomputed. */ +{ + Tk_CanvasTextInfo *textInfoPtr; + int leftX, topY, width, height, fudge; + + Tk_FreeTextLayout(textPtr->textLayout); + textPtr->textLayout = Tk_ComputeTextLayout(textPtr->tkfont, + textPtr->text, textPtr->numChars, textPtr->width, + textPtr->justify, 0, &width, &height); + + /* + * Use overall geometry information to compute the top-left corner + * of the bounding box for the text item. + */ + + leftX = (int) (textPtr->x + 0.5); + topY = (int) (textPtr->y + 0.5); + switch (textPtr->anchor) { + case TK_ANCHOR_NW: + case TK_ANCHOR_N: + case TK_ANCHOR_NE: + break; + + case TK_ANCHOR_W: + case TK_ANCHOR_CENTER: + case TK_ANCHOR_E: + topY -= height / 2; + break; + + case TK_ANCHOR_SW: + case TK_ANCHOR_S: + case TK_ANCHOR_SE: + topY -= height; + break; + } + switch (textPtr->anchor) { + case TK_ANCHOR_NW: + case TK_ANCHOR_W: + case TK_ANCHOR_SW: + break; + + case TK_ANCHOR_N: + case TK_ANCHOR_CENTER: + case TK_ANCHOR_S: + leftX -= width / 2; + break; + + case TK_ANCHOR_NE: + case TK_ANCHOR_E: + case TK_ANCHOR_SE: + leftX -= width; + break; + } + + textPtr->leftEdge = leftX; + textPtr->rightEdge = leftX + width; + + /* + * Last of all, update the bounding box for the item. The item's + * bounding box includes the bounding box of all its lines, plus + * an extra fudge factor for the cursor border (which could + * potentially be quite large). + */ + + textInfoPtr = textPtr->textInfoPtr; + fudge = (textInfoPtr->insertWidth + 1) / 2; + if (textInfoPtr->selBorderWidth > fudge) { + fudge = textInfoPtr->selBorderWidth; + } + textPtr->header.x1 = leftX - fudge; + textPtr->header.y1 = topY; + textPtr->header.x2 = leftX + width + fudge; + textPtr->header.y2 = topY + height; +} + +/* + *-------------------------------------------------------------- + * + * DisplayCanvText -- + * + * This procedure is invoked to draw a text item in a given + * drawable. + * + * Results: + * None. + * + * Side effects: + * ItemPtr is drawn in drawable using the transformation + * information in canvas. + * + *-------------------------------------------------------------- + */ + +static void +DisplayCanvText(canvas, itemPtr, display, drawable, x, y, width, height) + Tk_Canvas canvas; /* Canvas that contains item. */ + Tk_Item *itemPtr; /* Item to be displayed. */ + Display *display; /* Display on which to draw item. */ + Drawable drawable; /* Pixmap or window in which to draw + * item. */ + int x, y, width, height; /* Describes region of canvas that + * must be redisplayed (not used). */ +{ + TextItem *textPtr; + Tk_CanvasTextInfo *textInfoPtr; + int selFirst, selLast; + short drawableX, drawableY; + + textPtr = (TextItem *) itemPtr; + textInfoPtr = textPtr->textInfoPtr; + + if (textPtr->gc == None) { + return; + } + + /* + * If we're stippling, then modify the stipple offset in the GC. Be + * sure to reset the offset when done, since the GC is supposed to be + * read-only. + */ + + if (textPtr->stipple != None) { + Tk_CanvasSetStippleOrigin(canvas, textPtr->gc); + } + + selFirst = -1; + selLast = 0; /* lint. */ + if (textInfoPtr->selItemPtr == itemPtr) { + selFirst = textInfoPtr->selectFirst; + selLast = textInfoPtr->selectLast; + if (selLast >= textPtr->numChars) { + selLast = textPtr->numChars - 1; + } + if ((selFirst >= 0) && (selFirst <= selLast)) { + /* + * Draw a special background under the selection. + */ + + int xFirst, yFirst, hFirst; + int xLast, yLast, wLast; + + Tk_CharBbox(textPtr->textLayout, selFirst, + &xFirst, &yFirst, NULL, &hFirst); + Tk_CharBbox(textPtr->textLayout, selLast, + &xLast, &yLast, &wLast, NULL); + + /* + * If the selection spans the end of this line, then display + * selection background all the way to the end of the line. + * However, for the last line we only want to display up to the + * last character, not the end of the line. + */ + + x = xFirst; + height = hFirst; + for (y = yFirst ; y <= yLast; y += height) { + if (y == yLast) { + width = (xLast + wLast) - x; + } else { + width = textPtr->rightEdge - textPtr->leftEdge - x; + } + Tk_CanvasDrawableCoords(canvas, + (double) (textPtr->leftEdge + x + - textInfoPtr->selBorderWidth), + (double) (textPtr->header.y1 + y), + &drawableX, &drawableY); + Tk_Fill3DRectangle(Tk_CanvasTkwin(canvas), drawable, + textInfoPtr->selBorder, drawableX, drawableY, + width + 2 * textInfoPtr->selBorderWidth, + height, textInfoPtr->selBorderWidth, TK_RELIEF_RAISED); + x = 0; + } + } + } + + /* + * If the insertion point should be displayed, then draw a special + * background for the cursor before drawing the text. Note: if + * we're the cursor item but the cursor is turned off, then redraw + * background over the area of the cursor. This guarantees that + * the selection won't make the cursor invisible on mono displays, + * where both are drawn in the same color. + */ + + if ((textInfoPtr->focusItemPtr == itemPtr) && (textInfoPtr->gotFocus)) { + if (Tk_CharBbox(textPtr->textLayout, textPtr->insertPos, + &x, &y, NULL, &height)) { + Tk_CanvasDrawableCoords(canvas, + (double) (textPtr->leftEdge + x + - (textInfoPtr->insertWidth / 2)), + (double) (textPtr->header.y1 + y), + &drawableX, &drawableY); + if (textInfoPtr->cursorOn) { + Tk_Fill3DRectangle(Tk_CanvasTkwin(canvas), drawable, + textInfoPtr->insertBorder, + drawableX, drawableY, + textInfoPtr->insertWidth, height, + textInfoPtr->insertBorderWidth, TK_RELIEF_RAISED); + } else if (textPtr->cursorOffGC != None) { + /* + * Redraw the background over the area of the cursor, + * even though the cursor is turned off. This + * guarantees that the selection won't make the cursor + * invisible on mono displays, where both may be drawn + * in the same color. + */ + + XFillRectangle(display, drawable, textPtr->cursorOffGC, + drawableX, drawableY, + (unsigned) textInfoPtr->insertWidth, + (unsigned) height); + } + } + } + + + /* + * Display the text in two pieces: draw the entire text item, then + * draw the selected text on top of it. The selected text then + * will only need to be drawn if it has different attributes (such + * as foreground color) than regular text. + */ + + Tk_CanvasDrawableCoords(canvas, (double) textPtr->leftEdge, + (double) textPtr->header.y1, &drawableX, &drawableY); + Tk_DrawTextLayout(display, drawable, textPtr->gc, textPtr->textLayout, + drawableX, drawableY, 0, -1); + + if ((selFirst >= 0) && (textPtr->selTextGC != textPtr->gc)) { + Tk_DrawTextLayout(display, drawable, textPtr->selTextGC, + textPtr->textLayout, drawableX, drawableY, selFirst, + selLast + 1); + } + + if (textPtr->stipple != None) { + XSetTSOrigin(display, textPtr->gc, 0, 0); + } +} + +/* + *-------------------------------------------------------------- + * + * TextInsert -- + * + * Insert characters into a text item at a given position. + * + * Results: + * None. + * + * Side effects: + * The text in the given item is modified. The cursor and + * selection positions are also modified to reflect the + * insertion. + * + *-------------------------------------------------------------- + */ + +static void +TextInsert(canvas, itemPtr, beforeThis, string) + Tk_Canvas canvas; /* Canvas containing text item. */ + Tk_Item *itemPtr; /* Text item to be modified. */ + int beforeThis; /* Index of character before which text is + * to be inserted. */ + char *string; /* New characters to be inserted. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + int length; + char *new; + Tk_CanvasTextInfo *textInfoPtr = textPtr->textInfoPtr; + + length = strlen(string); + if (length == 0) { + return; + } + if (beforeThis < 0) { + beforeThis = 0; + } + if (beforeThis > textPtr->numChars) { + beforeThis = textPtr->numChars; + } + + new = (char *) ckalloc((unsigned) (textPtr->numChars + length + 1)); + strncpy(new, textPtr->text, (size_t) beforeThis); + strcpy(new+beforeThis, string); + strcpy(new+beforeThis+length, textPtr->text+beforeThis); + ckfree(textPtr->text); + textPtr->text = new; + textPtr->numChars += length; + + /* + * Inserting characters invalidates indices such as those for the + * selection and cursor. Update the indices appropriately. + */ + + if (textInfoPtr->selItemPtr == itemPtr) { + if (textInfoPtr->selectFirst >= beforeThis) { + textInfoPtr->selectFirst += length; + } + if (textInfoPtr->selectLast >= beforeThis) { + textInfoPtr->selectLast += length; + } + if ((textInfoPtr->anchorItemPtr == itemPtr) + && (textInfoPtr->selectAnchor >= beforeThis)) { + textInfoPtr->selectAnchor += length; + } + } + if (textPtr->insertPos >= beforeThis) { + textPtr->insertPos += length; + } + ComputeTextBbox(canvas, textPtr); +} + +/* + *-------------------------------------------------------------- + * + * TextDeleteChars -- + * + * Delete one or more characters from a text item. + * + * Results: + * None. + * + * Side effects: + * Characters between "first" and "last", inclusive, get + * deleted from itemPtr, and things like the selection + * position get updated. + * + *-------------------------------------------------------------- + */ + +static void +TextDeleteChars(canvas, itemPtr, first, last) + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Item in which to delete characters. */ + int first; /* Index of first character to delete. */ + int last; /* Index of last character to delete. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + int count; + char *new; + Tk_CanvasTextInfo *textInfoPtr = textPtr->textInfoPtr; + + if (first < 0) { + first = 0; + } + if (last >= textPtr->numChars) { + last = textPtr->numChars-1; + } + if (first > last) { + return; + } + count = last + 1 - first; + + new = (char *) ckalloc((unsigned) (textPtr->numChars + 1 - count)); + strncpy(new, textPtr->text, (size_t) first); + strcpy(new+first, textPtr->text+last+1); + ckfree(textPtr->text); + textPtr->text = new; + textPtr->numChars -= count; + + /* + * Update indexes for the selection and cursor to reflect the + * renumbering of the remaining characters. + */ + + if (textInfoPtr->selItemPtr == itemPtr) { + if (textInfoPtr->selectFirst > first) { + textInfoPtr->selectFirst -= count; + if (textInfoPtr->selectFirst < first) { + textInfoPtr->selectFirst = first; + } + } + if (textInfoPtr->selectLast >= first) { + textInfoPtr->selectLast -= count; + if (textInfoPtr->selectLast < (first-1)) { + textInfoPtr->selectLast = (first-1); + } + } + if (textInfoPtr->selectFirst > textInfoPtr->selectLast) { + textInfoPtr->selItemPtr = NULL; + } + if ((textInfoPtr->anchorItemPtr == itemPtr) + && (textInfoPtr->selectAnchor > first)) { + textInfoPtr->selectAnchor -= count; + if (textInfoPtr->selectAnchor < first) { + textInfoPtr->selectAnchor = first; + } + } + } + if (textPtr->insertPos > first) { + textPtr->insertPos -= count; + if (textPtr->insertPos < first) { + textPtr->insertPos = first; + } + } + ComputeTextBbox(canvas, textPtr); + return; +} + +/* + *-------------------------------------------------------------- + * + * TextToPoint -- + * + * Computes the distance from a given point to a given + * text item, in canvas units. + * + * Results: + * The return value is 0 if the point whose x and y coordinates + * are pointPtr[0] and pointPtr[1] is inside the text item. If + * the point isn't inside the text item then the return value + * is the distance from the point to the text item. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static double +TextToPoint(canvas, itemPtr, pointPtr) + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Item to check against point. */ + double *pointPtr; /* Pointer to x and y coordinates. */ +{ + TextItem *textPtr; + + textPtr = (TextItem *) itemPtr; + return (double) Tk_DistanceToTextLayout(textPtr->textLayout, + (int) pointPtr[0] - textPtr->leftEdge, + (int) pointPtr[1] - textPtr->header.y1); +} + +/* + *-------------------------------------------------------------- + * + * TextToArea -- + * + * This procedure is called to determine whether an item + * lies entirely inside, entirely outside, or overlapping + * a given rectangle. + * + * Results: + * -1 is returned if the item is entirely outside the area + * given by rectPtr, 0 if it overlaps, and 1 if it is entirely + * inside the given area. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +TextToArea(canvas, itemPtr, rectPtr) + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Item to check against rectangle. */ + double *rectPtr; /* Pointer to array of four coordinates + * (x1, y1, x2, y2) describing rectangular + * area. */ +{ + TextItem *textPtr; + + textPtr = (TextItem *) itemPtr; + return Tk_IntersectTextLayout(textPtr->textLayout, + (int) (rectPtr[0] + 0.5) - textPtr->leftEdge, + (int) (rectPtr[1] + 0.5) - textPtr->header.y1, + (int) (rectPtr[2] - rectPtr[0] + 0.5), + (int) (rectPtr[3] - rectPtr[1] + 0.5)); +} + +/* + *-------------------------------------------------------------- + * + * ScaleText -- + * + * This procedure is invoked to rescale a text item. + * + * Results: + * None. + * + * Side effects: + * Scales the position of the text, but not the size + * of the font for the text. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +ScaleText(canvas, itemPtr, originX, originY, scaleX, scaleY) + Tk_Canvas canvas; /* Canvas containing rectangle. */ + Tk_Item *itemPtr; /* Rectangle to be scaled. */ + double originX, originY; /* Origin about which to scale rect. */ + double scaleX; /* Amount to scale in X direction. */ + double scaleY; /* Amount to scale in Y direction. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + + textPtr->x = originX + scaleX*(textPtr->x - originX); + textPtr->y = originY + scaleY*(textPtr->y - originY); + ComputeTextBbox(canvas, textPtr); + return; +} + +/* + *-------------------------------------------------------------- + * + * TranslateText -- + * + * This procedure is called to move a text item by a + * given amount. + * + * Results: + * None. + * + * Side effects: + * The position of the text item is offset by (xDelta, yDelta), + * and the bounding box is updated in the generic part of the + * item structure. + * + *-------------------------------------------------------------- + */ + +static void +TranslateText(canvas, itemPtr, deltaX, deltaY) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item that is being moved. */ + double deltaX, deltaY; /* Amount by which item is to be + * moved. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + + textPtr->x += deltaX; + textPtr->y += deltaY; + ComputeTextBbox(canvas, textPtr); +} + +/* + *-------------------------------------------------------------- + * + * GetTextIndex -- + * + * Parse an index into a text item and return either its value + * or an error. + * + * Results: + * A standard Tcl result. If all went well, then *indexPtr is + * filled in with the index (into itemPtr) corresponding to + * string. Otherwise an error message is left in + * interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +GetTextIndex(interp, canvas, itemPtr, string, indexPtr) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item for which the index is being + * specified. */ + char *string; /* Specification of a particular character + * in itemPtr's text. */ + int *indexPtr; /* Where to store converted index. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + size_t length; + int c; + TkCanvas *canvasPtr = (TkCanvas *) canvas; + Tk_CanvasTextInfo *textInfoPtr = textPtr->textInfoPtr; + + c = string[0]; + length = strlen(string); + + if ((c == 'e') && (strncmp(string, "end", length) == 0)) { + *indexPtr = textPtr->numChars; + } else if ((c == 'i') && (strncmp(string, "insert", length) == 0)) { + *indexPtr = textPtr->insertPos; + } else if ((c == 's') && (strncmp(string, "sel.first", length) == 0) + && (length >= 5)) { + if (textInfoPtr->selItemPtr != itemPtr) { + interp->result = "selection isn't in item"; + return TCL_ERROR; + } + *indexPtr = textInfoPtr->selectFirst; + } else if ((c == 's') && (strncmp(string, "sel.last", length) == 0) + && (length >= 5)) { + if (textInfoPtr->selItemPtr != itemPtr) { + interp->result = "selection isn't in item"; + return TCL_ERROR; + } + *indexPtr = textInfoPtr->selectLast; + } else if (c == '@') { + int x, y; + double tmp; + char *end, *p; + + p = string+1; + tmp = strtod(p, &end); + if ((end == p) || (*end != ',')) { + goto badIndex; + } + x = (int) ((tmp < 0) ? tmp - 0.5 : tmp + 0.5); + p = end+1; + tmp = strtod(p, &end); + if ((end == p) || (*end != 0)) { + goto badIndex; + } + y = (int) ((tmp < 0) ? tmp - 0.5 : tmp + 0.5); + *indexPtr = Tk_PointToChar(textPtr->textLayout, + x + canvasPtr->scrollX1 - textPtr->leftEdge, + y + canvasPtr->scrollY1 - textPtr->header.y1); + } else if (Tcl_GetInt(interp, string, indexPtr) == TCL_OK) { + if (*indexPtr < 0){ + *indexPtr = 0; + } else if (*indexPtr > textPtr->numChars) { + *indexPtr = textPtr->numChars; + } + } else { + /* + * Some of the paths here leave messages in interp->result, + * so we have to clear it out before storing our own message. + */ + + badIndex: + Tcl_SetResult(interp, (char *) NULL, TCL_STATIC); + Tcl_AppendResult(interp, "bad index \"", string, "\"", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * SetTextCursor -- + * + * Set the position of the insertion cursor in this item. + * + * Results: + * None. + * + * Side effects: + * The cursor position will change. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +SetTextCursor(canvas, itemPtr, index) + Tk_Canvas canvas; /* Record describing canvas widget. */ + Tk_Item *itemPtr; /* Text item in which cursor position + * is to be set. */ + int index; /* Index of character just before which + * cursor is to be positioned. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + + if (index < 0) { + textPtr->insertPos = 0; + } else if (index > textPtr->numChars) { + textPtr->insertPos = textPtr->numChars; + } else { + textPtr->insertPos = index; + } +} + +/* + *-------------------------------------------------------------- + * + * GetSelText -- + * + * This procedure is invoked to return the selected portion + * of a text item. It is only called when this item has + * the selection. + * + * Results: + * The return value is the number of non-NULL bytes stored + * at buffer. Buffer is filled (or partially filled) with a + * NULL-terminated string containing part or all of the selection, + * as given by offset and maxBytes. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +GetSelText(canvas, itemPtr, offset, buffer, maxBytes) + Tk_Canvas canvas; /* Canvas containing selection. */ + Tk_Item *itemPtr; /* Text item containing selection. */ + int offset; /* Offset within selection of first + * character to be returned. */ + char *buffer; /* Location in which to place + * selection. */ + int maxBytes; /* Maximum number of bytes to place + * at buffer, not including terminating + * NULL character. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + int count; + Tk_CanvasTextInfo *textInfoPtr = textPtr->textInfoPtr; + + count = textInfoPtr->selectLast + 1 - textInfoPtr->selectFirst - offset; + if (textInfoPtr->selectLast == textPtr->numChars) { + count -= 1; + } + if (count > maxBytes) { + count = maxBytes; + } + if (count <= 0) { + return 0; + } + strncpy(buffer, textPtr->text + textInfoPtr->selectFirst + offset, + (size_t) count); + buffer[count] = '\0'; + return count; +} + +/* + *-------------------------------------------------------------- + * + * TextToPostscript -- + * + * This procedure is called to generate Postscript for + * text items. + * + * Results: + * The return value is a standard Tcl result. If an error + * occurs in generating Postscript then an error message is + * left in interp->result, replacing whatever used + * to be there. If no error occurs, then Postscript for the + * item is appended to the result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +TextToPostscript(interp, canvas, itemPtr, prepass) + Tcl_Interp *interp; /* Leave Postscript or error message + * here. */ + Tk_Canvas canvas; /* Information about overall canvas. */ + Tk_Item *itemPtr; /* Item for which Postscript is + * wanted. */ + int prepass; /* 1 means this is a prepass to + * collect font information; 0 means + * final Postscript is being created. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + int x, y; + Tk_FontMetrics fm; + char *justify; + char buffer[500]; + + if (textPtr->color == NULL) { + return TCL_OK; + } + + if (Tk_CanvasPsFont(interp, canvas, textPtr->tkfont) != TCL_OK) { + return TCL_ERROR; + } + if (prepass != 0) { + return TCL_OK; + } + if (Tk_CanvasPsColor(interp, canvas, textPtr->color) != TCL_OK) { + return TCL_ERROR; + } + if (textPtr->stipple != None) { + Tcl_AppendResult(interp, "/StippleText {\n ", + (char *) NULL); + Tk_CanvasPsStipple(interp, canvas, textPtr->stipple); + Tcl_AppendResult(interp, "} bind def\n", (char *) NULL); + } + + sprintf(buffer, "%.15g %.15g [\n", textPtr->x, + Tk_CanvasPsY(canvas, textPtr->y)); + Tcl_AppendResult(interp, buffer, (char *) NULL); + + Tk_TextLayoutToPostscript(interp, textPtr->textLayout); + + x = 0; y = 0; justify = NULL; /* lint. */ + switch (textPtr->anchor) { + case TK_ANCHOR_NW: x = 0; y = 0; break; + case TK_ANCHOR_N: x = 1; y = 0; break; + case TK_ANCHOR_NE: x = 2; y = 0; break; + case TK_ANCHOR_E: x = 2; y = 1; break; + case TK_ANCHOR_SE: x = 2; y = 2; break; + case TK_ANCHOR_S: x = 1; y = 2; break; + case TK_ANCHOR_SW: x = 0; y = 2; break; + case TK_ANCHOR_W: x = 0; y = 1; break; + case TK_ANCHOR_CENTER: x = 1; y = 1; break; + } + switch (textPtr->justify) { + case TK_JUSTIFY_LEFT: justify = "0"; break; + case TK_JUSTIFY_CENTER: justify = "0.5";break; + case TK_JUSTIFY_RIGHT: justify = "1"; break; + } + + Tk_GetFontMetrics(textPtr->tkfont, &fm); + sprintf(buffer, "] %d %g %g %s %s DrawText\n", + fm.linespace, x / -2.0, y / 2.0, justify, + ((textPtr->stipple == None) ? "false" : "true")); + Tcl_AppendResult(interp, buffer, (char *) NULL); + + return TCL_OK; +} diff --git a/generic/tkCanvUtil.c b/generic/tkCanvUtil.c new file mode 100644 index 0000000..9b52a80 --- /dev/null +++ b/generic/tkCanvUtil.c @@ -0,0 +1,376 @@ +/* + * tkCanvUtil.c -- + * + * This procedure contains a collection of utility procedures + * used by the implementations of various canvas item types. + * + * Copyright (c) 1994 Sun Microsystems, Inc. + * Copyright (c) 1994 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvUtil.c 1.7 96/05/03 10:54:22 + */ + +#include "tk.h" +#include "tkCanvas.h" +#include "tkPort.h" + + +/* + *---------------------------------------------------------------------- + * + * Tk_CanvasTkwin -- + * + * Given a token for a canvas, this procedure returns the + * widget that represents the canvas. + * + * Results: + * The return value is a handle for the widget. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +Tk_CanvasTkwin(canvas) + Tk_Canvas canvas; /* Token for the canvas. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) canvas; + return canvasPtr->tkwin; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_CanvasDrawableCoords -- + * + * Given an (x,y) coordinate pair within a canvas, this procedure + * returns the corresponding coordinates at which the point should + * be drawn in the drawable used for display. + * + * Results: + * There is no return value. The values at *drawableXPtr and + * *drawableYPtr are filled in with the coordinates at which + * x and y should be drawn. These coordinates are clipped + * to fit within a "short", since this is what X uses in + * most cases for drawing. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +Tk_CanvasDrawableCoords(canvas, x, y, drawableXPtr, drawableYPtr) + Tk_Canvas canvas; /* Token for the canvas. */ + double x, y; /* Coordinates in canvas space. */ + short *drawableXPtr, *drawableYPtr; /* Screen coordinates are stored + * here. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) canvas; + double tmp; + + tmp = x - canvasPtr->drawableXOrigin; + if (tmp > 0) { + tmp += 0.5; + } else { + tmp -= 0.5; + } + if (tmp > 32767) { + *drawableXPtr = 32767; + } else if (tmp < -32768) { + *drawableXPtr = -32768; + } else { + *drawableXPtr = (short) tmp; + } + + tmp = y - canvasPtr->drawableYOrigin; + if (tmp > 0) { + tmp += 0.5; + } else { + tmp -= 0.5; + } + if (tmp > 32767) { + *drawableYPtr = 32767; + } else if (tmp < -32768) { + *drawableYPtr = -32768; + } else { + *drawableYPtr = (short) tmp; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_CanvasWindowCoords -- + * + * Given an (x,y) coordinate pair within a canvas, this procedure + * returns the corresponding coordinates in the canvas's window. + * + * Results: + * There is no return value. The values at *screenXPtr and + * *screenYPtr are filled in with the coordinates at which + * (x,y) appears in the canvas's window. These coordinates + * are clipped to fit within a "short", since this is what X + * uses in most cases for drawing. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +Tk_CanvasWindowCoords(canvas, x, y, screenXPtr, screenYPtr) + Tk_Canvas canvas; /* Token for the canvas. */ + double x, y; /* Coordinates in canvas space. */ + short *screenXPtr, *screenYPtr; /* Screen coordinates are stored + * here. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) canvas; + double tmp; + + tmp = x - canvasPtr->xOrigin; + if (tmp > 0) { + tmp += 0.5; + } else { + tmp -= 0.5; + } + if (tmp > 32767) { + *screenXPtr = 32767; + } else if (tmp < -32768) { + *screenXPtr = -32768; + } else { + *screenXPtr = (short) tmp; + } + + tmp = y - canvasPtr->yOrigin; + if (tmp > 0) { + tmp += 0.5; + } else { + tmp -= 0.5; + } + if (tmp > 32767) { + *screenYPtr = 32767; + } else if (tmp < -32768) { + *screenYPtr = -32768; + } else { + *screenYPtr = (short) tmp; + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasGetCoord -- + * + * Given a string, returns a floating-point canvas coordinate + * corresponding to that string. + * + * Results: + * The return value is a standard Tcl return result. If + * TCL_OK is returned, then everything went well and the + * canvas coordinate is stored at *doublePtr; otherwise + * TCL_ERROR is returned and an error message is left in + * interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_CanvasGetCoord(interp, canvas, string, doublePtr) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Canvas to which coordinate applies. */ + char *string; /* Describes coordinate (any screen + * coordinate form may be used here). */ + double *doublePtr; /* Place to store converted coordinate. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) canvas; + if (Tk_GetScreenMM(canvasPtr->interp, canvasPtr->tkwin, string, + doublePtr) != TCL_OK) { + return TCL_ERROR; + } + *doublePtr *= canvasPtr->pixelsPerMM; + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_CanvasSetStippleOrigin -- + * + * This procedure sets the stipple origin in a graphics context + * so that stipples drawn with the GC will line up with other + * stipples previously drawn in the canvas. + * + * Results: + * None. + * + * Side effects: + * The graphics context is modified. + * + *---------------------------------------------------------------------- + */ + +void +Tk_CanvasSetStippleOrigin(canvas, gc) + Tk_Canvas canvas; /* Token for a canvas. */ + GC gc; /* Graphics context that is about to be + * used to draw a stippled pattern as + * part of redisplaying the canvas. */ + +{ + TkCanvas *canvasPtr = (TkCanvas *) canvas; + + XSetTSOrigin(canvasPtr->display, gc, -canvasPtr->drawableXOrigin, + -canvasPtr->drawableYOrigin); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_CanvasGetTextInfo -- + * + * This procedure returns a pointer to a structure containing + * information about the selection and insertion cursor for + * a canvas widget. Items such as text items save the pointer + * and use it to share access to the information with the generic + * canvas code. + * + * Results: + * The return value is a pointer to the structure holding text + * information for the canvas. Most of the fields should not + * be modified outside the generic canvas code; see the user + * documentation for details. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_CanvasTextInfo * +Tk_CanvasGetTextInfo(canvas) + Tk_Canvas canvas; /* Token for the canvas widget. */ +{ + return &((TkCanvas *) canvas)->textInfo; +} + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasTagsParseProc -- + * + * This procedure is invoked during option processing to handle + * "-tags" options for canvas items. + * + * Results: + * A standard Tcl return value. + * + * Side effects: + * The tags for a given item get replaced by those indicated + * in the value argument. + * + *-------------------------------------------------------------- + */ + +int +Tk_CanvasTagsParseProc(clientData, interp, tkwin, value, widgRec, offset) + ClientData clientData; /* Not used.*/ + Tcl_Interp *interp; /* Used for reporting errors. */ + Tk_Window tkwin; /* Window containing canvas widget. */ + char *value; /* Value of option (list of tag + * names). */ + char *widgRec; /* Pointer to record for item. */ + int offset; /* Offset into item (ignored). */ +{ + register Tk_Item *itemPtr = (Tk_Item *) widgRec; + int argc, i; + char **argv; + Tk_Uid *newPtr; + + /* + * Break the value up into the individual tag names. + */ + + if (Tcl_SplitList(interp, value, &argc, &argv) != TCL_OK) { + return TCL_ERROR; + } + + /* + * Make sure that there's enough space in the item to hold the + * tag names. + */ + + if (itemPtr->tagSpace < argc) { + newPtr = (Tk_Uid *) ckalloc((unsigned) (argc * sizeof(Tk_Uid))); + for (i = itemPtr->numTags-1; i >= 0; i--) { + newPtr[i] = itemPtr->tagPtr[i]; + } + if (itemPtr->tagPtr != itemPtr->staticTagSpace) { + ckfree((char *) itemPtr->tagPtr); + } + itemPtr->tagPtr = newPtr; + itemPtr->tagSpace = argc; + } + itemPtr->numTags = argc; + for (i = 0; i < argc; i++) { + itemPtr->tagPtr[i] = Tk_GetUid(argv[i]); + } + ckfree((char *) argv); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasTagsPrintProc -- + * + * This procedure is invoked by the Tk configuration code + * to produce a printable string for the "-tags" configuration + * option for canvas items. + * + * Results: + * The return value is a string describing all the tags for + * the item referred to by "widgRec". In addition, *freeProcPtr + * is filled in with the address of a procedure to call to free + * the result string when it's no longer needed (or NULL to + * indicate that the string doesn't need to be freed). + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_CanvasTagsPrintProc(clientData, tkwin, widgRec, offset, freeProcPtr) + ClientData clientData; /* Ignored. */ + Tk_Window tkwin; /* Window containing canvas widget. */ + char *widgRec; /* Pointer to record for item. */ + int offset; /* Ignored. */ + Tcl_FreeProc **freeProcPtr; /* Pointer to variable to fill in with + * information about how to reclaim + * storage for return string. */ +{ + register Tk_Item *itemPtr = (Tk_Item *) widgRec; + + if (itemPtr->numTags == 0) { + *freeProcPtr = (Tcl_FreeProc *) NULL; + return ""; + } + if (itemPtr->numTags == 1) { + *freeProcPtr = (Tcl_FreeProc *) NULL; + return (char *) itemPtr->tagPtr[0]; + } + *freeProcPtr = TCL_DYNAMIC; + return Tcl_Merge(itemPtr->numTags, (char **) itemPtr->tagPtr); +} diff --git a/generic/tkCanvWind.c b/generic/tkCanvWind.c new file mode 100644 index 0000000..61b21da --- /dev/null +++ b/generic/tkCanvWind.c @@ -0,0 +1,862 @@ +/* + * tkCanvWind.c -- + * + * This file implements window items for canvas widgets. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvWind.c 1.29 97/10/14 10:40:54 + */ + +#include <stdio.h> +#include "tkInt.h" +#include "tkPort.h" +#include "tkCanvas.h" + +/* + * The structure below defines the record for each window item. + */ + +typedef struct WindowItem { + Tk_Item header; /* Generic stuff that's the same for all + * types. MUST BE FIRST IN STRUCTURE. */ + double x, y; /* Coordinates of positioning point for + * window. */ + Tk_Window tkwin; /* Window associated with item. NULL means + * window has been destroyed. */ + int width; /* Width to use for window (<= 0 means use + * window's requested width). */ + int height; /* Width to use for window (<= 0 means use + * window's requested width). */ + Tk_Anchor anchor; /* Where to anchor window relative to + * (x,y). */ + Tk_Canvas canvas; /* Canvas containing this item. */ +} WindowItem; + +/* + * Information used for parsing configuration specs: + */ + +static Tk_CustomOption tagsOption = {Tk_CanvasTagsParseProc, + Tk_CanvasTagsPrintProc, (ClientData) NULL +}; + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_ANCHOR, "-anchor", (char *) NULL, (char *) NULL, + "center", Tk_Offset(WindowItem, anchor), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_PIXELS, "-height", (char *) NULL, (char *) NULL, + "0", Tk_Offset(WindowItem, height), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_CUSTOM, "-tags", (char *) NULL, (char *) NULL, + (char *) NULL, 0, TK_CONFIG_NULL_OK, &tagsOption}, + {TK_CONFIG_PIXELS, "-width", (char *) NULL, (char *) NULL, + "0", Tk_Offset(WindowItem, width), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_WINDOW, "-window", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(WindowItem, tkwin), TK_CONFIG_NULL_OK}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Prototypes for procedures defined in this file: + */ + +static void ComputeWindowBbox _ANSI_ARGS_((Tk_Canvas canvas, + WindowItem *winItemPtr)); +static int ConfigureWinItem _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv, int flags)); +static int CreateWinItem _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, struct Tk_Item *itemPtr, + int argc, char **argv)); +static void DeleteWinItem _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display)); +static void DisplayWinItem _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display, Drawable dst, + int x, int y, int width, int height)); +static void ScaleWinItem _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double originX, double originY, + double scaleX, double scaleY)); +static void TranslateWinItem _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double deltaX, double deltaY)); +static int WinItemCoords _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv)); +static void WinItemLostSlaveProc _ANSI_ARGS_(( + ClientData clientData, Tk_Window tkwin)); +static void WinItemRequestProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); +static void WinItemStructureProc _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +static int WinItemToArea _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *rectPtr)); +static double WinItemToPoint _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *pointPtr)); + +/* + * The structure below defines the window item type by means of procedures + * that can be invoked by generic item code. + */ + +Tk_ItemType tkWindowType = { + "window", /* name */ + sizeof(WindowItem), /* itemSize */ + CreateWinItem, /* createProc */ + configSpecs, /* configSpecs */ + ConfigureWinItem, /* configureProc */ + WinItemCoords, /* coordProc */ + DeleteWinItem, /* deleteProc */ + DisplayWinItem, /* displayProc */ + 1, /* alwaysRedraw */ + WinItemToPoint, /* pointProc */ + WinItemToArea, /* areaProc */ + (Tk_ItemPostscriptProc *) NULL, /* postscriptProc */ + ScaleWinItem, /* scaleProc */ + TranslateWinItem, /* translateProc */ + (Tk_ItemIndexProc *) NULL, /* indexProc */ + (Tk_ItemCursorProc *) NULL, /* cursorProc */ + (Tk_ItemSelectionProc *) NULL, /* selectionProc */ + (Tk_ItemInsertProc *) NULL, /* insertProc */ + (Tk_ItemDCharsProc *) NULL, /* dTextProc */ + (Tk_ItemType *) NULL /* nextPtr */ +}; + + +/* + * The structure below defines the official type record for the + * placer: + */ + +static Tk_GeomMgr canvasGeomType = { + "canvas", /* name */ + WinItemRequestProc, /* requestProc */ + WinItemLostSlaveProc, /* lostSlaveProc */ +}; + +/* + *-------------------------------------------------------------- + * + * CreateWinItem -- + * + * This procedure is invoked to create a new window + * item in a canvas. + * + * Results: + * A standard Tcl return value. If an error occurred in + * creating the item, then an error message is left in + * interp->result; in this case itemPtr is + * left uninitialized, so it can be safely freed by the + * caller. + * + * Side effects: + * A new window item is created. + * + *-------------------------------------------------------------- + */ + +static int +CreateWinItem(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Canvas to hold new item. */ + Tk_Item *itemPtr; /* Record to hold new item; header + * has been initialized by caller. */ + int argc; /* Number of arguments in argv. */ + char **argv; /* Arguments describing rectangle. */ +{ + WindowItem *winItemPtr = (WindowItem *) itemPtr; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tk_PathName(Tk_CanvasTkwin(canvas)), " create ", + itemPtr->typePtr->name, " x y ?options?\"", + (char *) NULL); + return TCL_ERROR; + } + + /* + * Initialize item's record. + */ + + winItemPtr->tkwin = NULL; + winItemPtr->width = 0; + winItemPtr->height = 0; + winItemPtr->anchor = TK_ANCHOR_CENTER; + winItemPtr->canvas = canvas; + + /* + * Process the arguments to fill in the item record. + */ + + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], &winItemPtr->x) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], + &winItemPtr->y) != TCL_OK)) { + return TCL_ERROR; + } + + if (ConfigureWinItem(interp, canvas, itemPtr, argc-2, argv+2, 0) + != TCL_OK) { + DeleteWinItem(canvas, itemPtr, Tk_Display(Tk_CanvasTkwin(canvas))); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * WinItemCoords -- + * + * This procedure is invoked to process the "coords" widget + * command on window items. See the user documentation for + * details on what it does. + * + * Results: + * Returns TCL_OK or TCL_ERROR, and sets interp->result. + * + * Side effects: + * The coordinates for the given item may be changed. + * + *-------------------------------------------------------------- + */ + +static int +WinItemCoords(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item whose coordinates are to be + * read or modified. */ + int argc; /* Number of coordinates supplied in + * argv. */ + char **argv; /* Array of coordinates: x1, y1, + * x2, y2, ... */ +{ + WindowItem *winItemPtr = (WindowItem *) itemPtr; + char x[TCL_DOUBLE_SPACE], y[TCL_DOUBLE_SPACE]; + + if (argc == 0) { + Tcl_PrintDouble(interp, winItemPtr->x, x); + Tcl_PrintDouble(interp, winItemPtr->y, y); + Tcl_AppendResult(interp, x, " ", y, (char *) NULL); + } else if (argc == 2) { + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], &winItemPtr->x) + != TCL_OK) || (Tk_CanvasGetCoord(interp, canvas, argv[1], + &winItemPtr->y) != TCL_OK)) { + return TCL_ERROR; + } + ComputeWindowBbox(canvas, winItemPtr); + } else { + sprintf(interp->result, + "wrong # coordinates: expected 0 or 2, got %d", argc); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ConfigureWinItem -- + * + * This procedure is invoked to configure various aspects + * of a window item, such as its anchor position. + * + * Results: + * A standard Tcl result code. If an error occurs, then + * an error message is left in interp->result. + * + * Side effects: + * Configuration information may be set for itemPtr. + * + *-------------------------------------------------------------- + */ + +static int +ConfigureWinItem(interp, canvas, itemPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Window item to reconfigure. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Arguments describing things to configure. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + WindowItem *winItemPtr = (WindowItem *) itemPtr; + Tk_Window oldWindow; + Tk_Window canvasTkwin; + + oldWindow = winItemPtr->tkwin; + canvasTkwin = Tk_CanvasTkwin(canvas); + if (Tk_ConfigureWidget(interp, canvasTkwin, configSpecs, argc, argv, + (char *) winItemPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few of the options require additional processing. + */ + + if (oldWindow != winItemPtr->tkwin) { + if (oldWindow != NULL) { + Tk_DeleteEventHandler(oldWindow, StructureNotifyMask, + WinItemStructureProc, (ClientData) winItemPtr); + Tk_ManageGeometry(oldWindow, (Tk_GeomMgr *) NULL, + (ClientData) NULL); + Tk_UnmaintainGeometry(oldWindow, canvasTkwin); + Tk_UnmapWindow(oldWindow); + } + if (winItemPtr->tkwin != NULL) { + Tk_Window ancestor, parent; + + /* + * Make sure that the canvas is either the parent of the + * window associated with the item or a descendant of that + * parent. Also, don't allow a top-level window to be + * managed inside a canvas. + */ + + parent = Tk_Parent(winItemPtr->tkwin); + for (ancestor = canvasTkwin; ; + ancestor = Tk_Parent(ancestor)) { + if (ancestor == parent) { + break; + } + if (((Tk_FakeWin *) (ancestor))->flags & TK_TOP_LEVEL) { + badWindow: + Tcl_AppendResult(interp, "can't use ", + Tk_PathName(winItemPtr->tkwin), + " in a window item of this canvas", (char *) NULL); + winItemPtr->tkwin = NULL; + return TCL_ERROR; + } + } + if (((Tk_FakeWin *) (winItemPtr->tkwin))->flags & TK_TOP_LEVEL) { + goto badWindow; + } + if (winItemPtr->tkwin == canvasTkwin) { + goto badWindow; + } + Tk_CreateEventHandler(winItemPtr->tkwin, StructureNotifyMask, + WinItemStructureProc, (ClientData) winItemPtr); + Tk_ManageGeometry(winItemPtr->tkwin, &canvasGeomType, + (ClientData) winItemPtr); + } + } + + ComputeWindowBbox(canvas, winItemPtr); + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * DeleteWinItem -- + * + * This procedure is called to clean up the data structure + * associated with a window item. + * + * Results: + * None. + * + * Side effects: + * Resources associated with itemPtr are released. + * + *-------------------------------------------------------------- + */ + +static void +DeleteWinItem(canvas, itemPtr, display) + Tk_Canvas canvas; /* Overall info about widget. */ + Tk_Item *itemPtr; /* Item that is being deleted. */ + Display *display; /* Display containing window for + * canvas. */ +{ + WindowItem *winItemPtr = (WindowItem *) itemPtr; + Tk_Window canvasTkwin = Tk_CanvasTkwin(canvas); + + if (winItemPtr->tkwin != NULL) { + Tk_DeleteEventHandler(winItemPtr->tkwin, StructureNotifyMask, + WinItemStructureProc, (ClientData) winItemPtr); + Tk_ManageGeometry(winItemPtr->tkwin, (Tk_GeomMgr *) NULL, + (ClientData) NULL); + if (canvasTkwin != Tk_Parent(winItemPtr->tkwin)) { + Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin); + } + Tk_UnmapWindow(winItemPtr->tkwin); + } +} + +/* + *-------------------------------------------------------------- + * + * ComputeWindowBbox -- + * + * This procedure is invoked to compute the bounding box of + * all the pixels that may be drawn as part of a window item. + * This procedure is where the child window's placement is + * computed. + * + * Results: + * None. + * + * Side effects: + * The fields x1, y1, x2, and y2 are updated in the header + * for itemPtr. + * + *-------------------------------------------------------------- + */ + +static void +ComputeWindowBbox(canvas, winItemPtr) + Tk_Canvas canvas; /* Canvas that contains item. */ + WindowItem *winItemPtr; /* Item whose bbox is to be + * recomputed. */ +{ + int width, height, x, y; + + x = (int) (winItemPtr->x + ((winItemPtr->x >= 0) ? 0.5 : - 0.5)); + y = (int) (winItemPtr->y + ((winItemPtr->y >= 0) ? 0.5 : - 0.5)); + + if (winItemPtr->tkwin == NULL) { + /* + * There is no window for this item yet. Just give it a 1x1 + * bounding box. Don't give it a 0x0 bounding box; there are + * strange cases where this bounding box might be used as the + * dimensions of the window, and 0x0 causes problems under X. + */ + + winItemPtr->header.x1 = x; + winItemPtr->header.x2 = winItemPtr->header.x1 + 1; + winItemPtr->header.y1 = y; + winItemPtr->header.y2 = winItemPtr->header.y1 + 1; + return; + } + + /* + * Compute dimensions of window. + */ + + width = winItemPtr->width; + if (width <= 0) { + width = Tk_ReqWidth(winItemPtr->tkwin); + if (width <= 0) { + width = 1; + } + } + height = winItemPtr->height; + if (height <= 0) { + height = Tk_ReqHeight(winItemPtr->tkwin); + if (height <= 0) { + height = 1; + } + } + + /* + * Compute location of window, using anchor information. + */ + + switch (winItemPtr->anchor) { + case TK_ANCHOR_N: + x -= width/2; + break; + case TK_ANCHOR_NE: + x -= width; + break; + case TK_ANCHOR_E: + x -= width; + y -= height/2; + break; + case TK_ANCHOR_SE: + x -= width; + y -= height; + break; + case TK_ANCHOR_S: + x -= width/2; + y -= height; + break; + case TK_ANCHOR_SW: + y -= height; + break; + case TK_ANCHOR_W: + y -= height/2; + break; + case TK_ANCHOR_NW: + break; + case TK_ANCHOR_CENTER: + x -= width/2; + y -= height/2; + break; + } + + /* + * Store the information in the item header. + */ + + winItemPtr->header.x1 = x; + winItemPtr->header.y1 = y; + winItemPtr->header.x2 = x + width; + winItemPtr->header.y2 = y + height; +} + +/* + *-------------------------------------------------------------- + * + * DisplayWinItem -- + * + * This procedure is invoked to "draw" a window item in a given + * drawable. Since the window draws itself, we needn't do any + * actual redisplay here. However, this procedure takes care + * of actually repositioning the child window so that it occupies + * the correct screen position. + * + * Results: + * None. + * + * Side effects: + * The child window's position may get changed. Note: this + * procedure gets called both when a window needs to be displayed + * and when it ceases to be visible on the screen (e.g. it was + * scrolled or moved off-screen or the enclosing canvas is + * unmapped). + * + *-------------------------------------------------------------- + */ + +static void +DisplayWinItem(canvas, itemPtr, display, drawable, regionX, regionY, + regionWidth, regionHeight) + Tk_Canvas canvas; /* Canvas that contains item. */ + Tk_Item *itemPtr; /* Item to be displayed. */ + Display *display; /* Display on which to draw item. */ + Drawable drawable; /* Pixmap or window in which to draw + * item. */ + int regionX, regionY, regionWidth, regionHeight; + /* Describes region of canvas that + * must be redisplayed (not used). */ +{ + WindowItem *winItemPtr = (WindowItem *) itemPtr; + int width, height; + short x, y; + Tk_Window canvasTkwin = Tk_CanvasTkwin(canvas); + + if (winItemPtr->tkwin == NULL) { + return; + } + + Tk_CanvasWindowCoords(canvas, (double) winItemPtr->header.x1, + (double) winItemPtr->header.y1, &x, &y); + width = winItemPtr->header.x2 - winItemPtr->header.x1; + height = winItemPtr->header.y2 - winItemPtr->header.y1; + + /* + * If the window is completely out of the visible area of the canvas + * then unmap it. This code used not to be present (why unmap the + * window if it isn't visible anyway?) but this could cause the + * window to suddenly reappear if the canvas window got resized. + */ + + if (((x + width) <= 0) || ((y + height) <= 0) + || (x >= Tk_Width(canvasTkwin)) || (y >= Tk_Height(canvasTkwin))) { + if (canvasTkwin == Tk_Parent(winItemPtr->tkwin)) { + Tk_UnmapWindow(winItemPtr->tkwin); + } else { + Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin); + } + return; + } + + /* + * Reposition and map the window (but in different ways depending + * on whether the canvas is the window's parent). + */ + + if (canvasTkwin == Tk_Parent(winItemPtr->tkwin)) { + if ((x != Tk_X(winItemPtr->tkwin)) || (y != Tk_Y(winItemPtr->tkwin)) + || (width != Tk_Width(winItemPtr->tkwin)) + || (height != Tk_Height(winItemPtr->tkwin))) { + Tk_MoveResizeWindow(winItemPtr->tkwin, x, y, width, height); + } + Tk_MapWindow(winItemPtr->tkwin); + } else { + Tk_MaintainGeometry(winItemPtr->tkwin, canvasTkwin, x, y, + width, height); + } +} + +/* + *-------------------------------------------------------------- + * + * WinItemToPoint -- + * + * Computes the distance from a given point to a given + * rectangle, in canvas units. + * + * Results: + * The return value is 0 if the point whose x and y coordinates + * are coordPtr[0] and coordPtr[1] is inside the window. If the + * point isn't inside the window then the return value is the + * distance from the point to the window. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static double +WinItemToPoint(canvas, itemPtr, pointPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against point. */ + double *pointPtr; /* Pointer to x and y coordinates. */ +{ + WindowItem *winItemPtr = (WindowItem *) itemPtr; + double x1, x2, y1, y2, xDiff, yDiff; + + x1 = winItemPtr->header.x1; + y1 = winItemPtr->header.y1; + x2 = winItemPtr->header.x2; + y2 = winItemPtr->header.y2; + + /* + * Point is outside rectangle. + */ + + if (pointPtr[0] < x1) { + xDiff = x1 - pointPtr[0]; + } else if (pointPtr[0] >= x2) { + xDiff = pointPtr[0] + 1 - x2; + } else { + xDiff = 0; + } + + if (pointPtr[1] < y1) { + yDiff = y1 - pointPtr[1]; + } else if (pointPtr[1] >= y2) { + yDiff = pointPtr[1] + 1 - y2; + } else { + yDiff = 0; + } + + return hypot(xDiff, yDiff); +} + +/* + *-------------------------------------------------------------- + * + * WinItemToArea -- + * + * This procedure is called to determine whether an item + * lies entirely inside, entirely outside, or overlapping + * a given rectangle. + * + * Results: + * -1 is returned if the item is entirely outside the area + * given by rectPtr, 0 if it overlaps, and 1 if it is entirely + * inside the given area. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +WinItemToArea(canvas, itemPtr, rectPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against rectangle. */ + double *rectPtr; /* Pointer to array of four coordinates + * (x1, y1, x2, y2) describing rectangular + * area. */ +{ + WindowItem *winItemPtr = (WindowItem *) itemPtr; + + if ((rectPtr[2] <= winItemPtr->header.x1) + || (rectPtr[0] >= winItemPtr->header.x2) + || (rectPtr[3] <= winItemPtr->header.y1) + || (rectPtr[1] >= winItemPtr->header.y2)) { + return -1; + } + if ((rectPtr[0] <= winItemPtr->header.x1) + && (rectPtr[1] <= winItemPtr->header.y1) + && (rectPtr[2] >= winItemPtr->header.x2) + && (rectPtr[3] >= winItemPtr->header.y2)) { + return 1; + } + return 0; +} + +/* + *-------------------------------------------------------------- + * + * ScaleWinItem -- + * + * This procedure is invoked to rescale a rectangle or oval + * item. + * + * Results: + * None. + * + * Side effects: + * The rectangle or oval referred to by itemPtr is rescaled + * so that the following transformation is applied to all + * point coordinates: + * x' = originX + scaleX*(x-originX) + * y' = originY + scaleY*(y-originY) + * + *-------------------------------------------------------------- + */ + +static void +ScaleWinItem(canvas, itemPtr, originX, originY, scaleX, scaleY) + Tk_Canvas canvas; /* Canvas containing rectangle. */ + Tk_Item *itemPtr; /* Rectangle to be scaled. */ + double originX, originY; /* Origin about which to scale rect. */ + double scaleX; /* Amount to scale in X direction. */ + double scaleY; /* Amount to scale in Y direction. */ +{ + WindowItem *winItemPtr = (WindowItem *) itemPtr; + + winItemPtr->x = originX + scaleX*(winItemPtr->x - originX); + winItemPtr->y = originY + scaleY*(winItemPtr->y - originY); + if (winItemPtr->width > 0) { + winItemPtr->width = (int) (scaleX*winItemPtr->width); + } + if (winItemPtr->height > 0) { + winItemPtr->height = (int) (scaleY*winItemPtr->height); + } + ComputeWindowBbox(canvas, winItemPtr); +} + +/* + *-------------------------------------------------------------- + * + * TranslateWinItem -- + * + * This procedure is called to move a rectangle or oval by a + * given amount. + * + * Results: + * None. + * + * Side effects: + * The position of the rectangle or oval is offset by + * (xDelta, yDelta), and the bounding box is updated in the + * generic part of the item structure. + * + *-------------------------------------------------------------- + */ + +static void +TranslateWinItem(canvas, itemPtr, deltaX, deltaY) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item that is being moved. */ + double deltaX, deltaY; /* Amount by which item is to be + * moved. */ +{ + WindowItem *winItemPtr = (WindowItem *) itemPtr; + + winItemPtr->x += deltaX; + winItemPtr->y += deltaY; + ComputeWindowBbox(canvas, winItemPtr); +} + +/* + *-------------------------------------------------------------- + * + * WinItemStructureProc -- + * + * This procedure is invoked whenever StructureNotify events + * occur for a window that's managed as part of a canvas window + * item. This procudure's only purpose is to clean up when + * windows are deleted. + * + * Results: + * None. + * + * Side effects: + * The window is disassociated from the window item when it is + * deleted. + * + *-------------------------------------------------------------- + */ + +static void +WinItemStructureProc(clientData, eventPtr) + ClientData clientData; /* Pointer to record describing window item. */ + XEvent *eventPtr; /* Describes what just happened. */ +{ + WindowItem *winItemPtr = (WindowItem *) clientData; + + if (eventPtr->type == DestroyNotify) { + winItemPtr->tkwin = NULL; + } +} + +/* + *-------------------------------------------------------------- + * + * WinItemRequestProc -- + * + * This procedure is invoked whenever a window that's associated + * with a window canvas item changes its requested dimensions. + * + * Results: + * None. + * + * Side effects: + * The size and location on the screen of the window may change, + * depending on the options specified for the window item. + * + *-------------------------------------------------------------- + */ + +static void +WinItemRequestProc(clientData, tkwin) + ClientData clientData; /* Pointer to record for window item. */ + Tk_Window tkwin; /* Window that changed its desired + * size. */ +{ + WindowItem *winItemPtr = (WindowItem *) clientData; + + ComputeWindowBbox(winItemPtr->canvas, winItemPtr); + DisplayWinItem(winItemPtr->canvas, (Tk_Item *) winItemPtr, + (Display *) NULL, (Drawable) None, 0, 0, 0, 0); +} + +/* + *-------------------------------------------------------------- + * + * WinItemLostSlaveProc -- + * + * This procedure is invoked by Tk whenever some other geometry + * claims control over a slave that used to be managed by us. + * + * Results: + * None. + * + * Side effects: + * Forgets all canvas-related information about the slave. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +WinItemLostSlaveProc(clientData, tkwin) + ClientData clientData; /* WindowItem structure for slave window that + * was stolen away. */ + Tk_Window tkwin; /* Tk's handle for the slave window. */ +{ + WindowItem *winItemPtr = (WindowItem *) clientData; + Tk_Window canvasTkwin = Tk_CanvasTkwin(winItemPtr->canvas); + + Tk_DeleteEventHandler(winItemPtr->tkwin, StructureNotifyMask, + WinItemStructureProc, (ClientData) winItemPtr); + if (canvasTkwin != Tk_Parent(winItemPtr->tkwin)) { + Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin); + } + Tk_UnmapWindow(winItemPtr->tkwin); + winItemPtr->tkwin = NULL; +} diff --git a/generic/tkCanvas.c b/generic/tkCanvas.c new file mode 100644 index 0000000..b093226 --- /dev/null +++ b/generic/tkCanvas.c @@ -0,0 +1,3791 @@ +/* + * tkCanvas.c -- + * + * This module implements canvas widgets for the Tk toolkit. + * A canvas displays a background and a collection of graphical + * objects such as rectangles, lines, and texts. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvas.c 1.126 97/07/31 09:05:52 + */ + +#include "default.h" +#include "tkInt.h" +#include "tkPort.h" +#include "tkCanvas.h" + +/* + * See tkCanvas.h for key data structures used to implement canvases. + */ + +/* + * The structure defined below is used to keep track of a tag search + * in progress. Only the "prevPtr" field should be accessed by anyone + * other than StartTagSearch and NextItem. + */ + +typedef struct TagSearch { + TkCanvas *canvasPtr; /* Canvas widget being searched. */ + Tk_Uid tag; /* Tag to search for. 0 means return + * all items. */ + Tk_Item *prevPtr; /* Item just before last one found (or NULL + * if last one found was first in the item + * list of canvasPtr). */ + Tk_Item *currentPtr; /* Pointer to last item returned. */ + int searchOver; /* Non-zero means NextItem should always + * return NULL. */ +} TagSearch; + +/* + * Information used for argv parsing. + */ + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_CANVAS_BG_COLOR, Tk_Offset(TkCanvas, bgBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_CANVAS_BG_MONO, Tk_Offset(TkCanvas, bgBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_CANVAS_BORDER_WIDTH, Tk_Offset(TkCanvas, borderWidth), 0}, + {TK_CONFIG_DOUBLE, "-closeenough", "closeEnough", "CloseEnough", + DEF_CANVAS_CLOSE_ENOUGH, Tk_Offset(TkCanvas, closeEnough), 0}, + {TK_CONFIG_BOOLEAN, "-confine", "confine", "Confine", + DEF_CANVAS_CONFINE, Tk_Offset(TkCanvas, confine), 0}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_CANVAS_CURSOR, Tk_Offset(TkCanvas, cursor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-height", "height", "Height", + DEF_CANVAS_HEIGHT, Tk_Offset(TkCanvas, height), 0}, + {TK_CONFIG_COLOR, "-highlightbackground", "highlightBackground", + "HighlightBackground", DEF_CANVAS_HIGHLIGHT_BG, + Tk_Offset(TkCanvas, highlightBgColorPtr), 0}, + {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor", + DEF_CANVAS_HIGHLIGHT, Tk_Offset(TkCanvas, highlightColorPtr), 0}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", + DEF_CANVAS_HIGHLIGHT_WIDTH, Tk_Offset(TkCanvas, highlightWidth), 0}, + {TK_CONFIG_BORDER, "-insertbackground", "insertBackground", "Foreground", + DEF_CANVAS_INSERT_BG, Tk_Offset(TkCanvas, textInfo.insertBorder), 0}, + {TK_CONFIG_PIXELS, "-insertborderwidth", "insertBorderWidth", "BorderWidth", + DEF_CANVAS_INSERT_BD_COLOR, + Tk_Offset(TkCanvas, textInfo.insertBorderWidth), TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_PIXELS, "-insertborderwidth", "insertBorderWidth", "BorderWidth", + DEF_CANVAS_INSERT_BD_MONO, + Tk_Offset(TkCanvas, textInfo.insertBorderWidth), TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_INT, "-insertofftime", "insertOffTime", "OffTime", + DEF_CANVAS_INSERT_OFF_TIME, Tk_Offset(TkCanvas, insertOffTime), 0}, + {TK_CONFIG_INT, "-insertontime", "insertOnTime", "OnTime", + DEF_CANVAS_INSERT_ON_TIME, Tk_Offset(TkCanvas, insertOnTime), 0}, + {TK_CONFIG_PIXELS, "-insertwidth", "insertWidth", "InsertWidth", + DEF_CANVAS_INSERT_WIDTH, Tk_Offset(TkCanvas, textInfo.insertWidth), 0}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_CANVAS_RELIEF, Tk_Offset(TkCanvas, relief), 0}, + {TK_CONFIG_STRING, "-scrollregion", "scrollRegion", "ScrollRegion", + DEF_CANVAS_SCROLL_REGION, Tk_Offset(TkCanvas, regionString), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Foreground", + DEF_CANVAS_SELECT_COLOR, Tk_Offset(TkCanvas, textInfo.selBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Foreground", + DEF_CANVAS_SELECT_MONO, Tk_Offset(TkCanvas, textInfo.selBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_PIXELS, "-selectborderwidth", "selectBorderWidth", "BorderWidth", + DEF_CANVAS_SELECT_BD_COLOR, + Tk_Offset(TkCanvas, textInfo.selBorderWidth), TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_PIXELS, "-selectborderwidth", "selectBorderWidth", "BorderWidth", + DEF_CANVAS_SELECT_BD_MONO, Tk_Offset(TkCanvas, textInfo.selBorderWidth), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Background", + DEF_CANVAS_SELECT_FG_COLOR, Tk_Offset(TkCanvas, textInfo.selFgColorPtr), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Background", + DEF_CANVAS_SELECT_FG_MONO, Tk_Offset(TkCanvas, textInfo.selFgColorPtr), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_CANVAS_TAKE_FOCUS, Tk_Offset(TkCanvas, takeFocus), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-width", "width", "Width", + DEF_CANVAS_WIDTH, Tk_Offset(TkCanvas, width), 0}, + {TK_CONFIG_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand", + DEF_CANVAS_X_SCROLL_CMD, Tk_Offset(TkCanvas, xScrollCmd), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-xscrollincrement", "xScrollIncrement", + "ScrollIncrement", + DEF_CANVAS_X_SCROLL_INCREMENT, Tk_Offset(TkCanvas, xScrollIncrement), + 0}, + {TK_CONFIG_STRING, "-yscrollcommand", "yScrollCommand", "ScrollCommand", + DEF_CANVAS_Y_SCROLL_CMD, Tk_Offset(TkCanvas, yScrollCmd), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-yscrollincrement", "yScrollIncrement", + "ScrollIncrement", + DEF_CANVAS_Y_SCROLL_INCREMENT, Tk_Offset(TkCanvas, yScrollIncrement), + 0}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * List of all the item types known at present: + */ + +static Tk_ItemType *typeList = NULL; /* NULL means initialization hasn't + * been done yet. */ + +/* + * Standard item types provided by Tk: + */ + +extern Tk_ItemType tkArcType, tkBitmapType, tkImageType, tkLineType; +extern Tk_ItemType tkOvalType, tkPolygonType; +extern Tk_ItemType tkRectangleType, tkTextType, tkWindowType; + +/* + * Various Tk_Uid's used by this module (set up during initialization): + */ + +static Tk_Uid allUid = NULL; +static Tk_Uid currentUid = NULL; + +/* + * Statistics counters: + */ + +static int numIdSearches; +static int numSlowSearches; + +/* + * Prototypes for procedures defined later in this file: + */ + +static void CanvasBindProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void CanvasBlinkProc _ANSI_ARGS_((ClientData clientData)); +static void CanvasCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static void CanvasDoEvent _ANSI_ARGS_((TkCanvas *canvasPtr, + XEvent *eventPtr)); +static void CanvasEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int CanvasFetchSelection _ANSI_ARGS_(( + ClientData clientData, int offset, + char *buffer, int maxBytes)); +static Tk_Item * CanvasFindClosest _ANSI_ARGS_((TkCanvas *canvasPtr, + double coords[2])); +static void CanvasFocusProc _ANSI_ARGS_((TkCanvas *canvasPtr, + int gotFocus)); +static void CanvasLostSelection _ANSI_ARGS_(( + ClientData clientData)); +static void CanvasSelectTo _ANSI_ARGS_((TkCanvas *canvasPtr, + Tk_Item *itemPtr, int index)); +static void CanvasSetOrigin _ANSI_ARGS_((TkCanvas *canvasPtr, + int xOrigin, int yOrigin)); +static void CanvasUpdateScrollbars _ANSI_ARGS_(( + TkCanvas *canvasPtr)); +static int CanvasWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void CanvasWorldChanged _ANSI_ARGS_(( + ClientData instanceData)); +static int ConfigureCanvas _ANSI_ARGS_((Tcl_Interp *interp, + TkCanvas *canvasPtr, int argc, char **argv, + int flags)); +static void DestroyCanvas _ANSI_ARGS_((char *memPtr)); +static void DisplayCanvas _ANSI_ARGS_((ClientData clientData)); +static void DoItem _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Item *itemPtr, Tk_Uid tag)); +static int FindItems _ANSI_ARGS_((Tcl_Interp *interp, + TkCanvas *canvasPtr, int argc, char **argv, + char *newTag, char *cmdName, char *option)); +static int FindArea _ANSI_ARGS_((Tcl_Interp *interp, + TkCanvas *canvasPtr, char **argv, Tk_Uid uid, + int enclosed)); +static double GridAlign _ANSI_ARGS_((double coord, double spacing)); +static void InitCanvas _ANSI_ARGS_((void)); +static Tk_Item * NextItem _ANSI_ARGS_((TagSearch *searchPtr)); +static void PickCurrentItem _ANSI_ARGS_((TkCanvas *canvasPtr, + XEvent *eventPtr)); +static void PrintScrollFractions _ANSI_ARGS_((int screen1, + int screen2, int object1, int object2, + char *string)); +static void RelinkItems _ANSI_ARGS_((TkCanvas *canvasPtr, + char *tag, Tk_Item *prevPtr)); +static Tk_Item * StartTagSearch _ANSI_ARGS_((TkCanvas *canvasPtr, + char *tag, TagSearch *searchPtr)); + +/* + * The structure below defines canvas class behavior by means of procedures + * that can be invoked from generic window code. + */ + +static TkClassProcs canvasClass = { + NULL, /* createProc. */ + CanvasWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasCmd -- + * + * This procedure is invoked to process the "canvas" Tcl + * command. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_CanvasCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + TkCanvas *canvasPtr; + Tk_Window new; + + if (typeList == NULL) { + InitCanvas(); + } + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *) NULL); + if (new == NULL) { + return TCL_ERROR; + } + + /* + * Initialize fields that won't be initialized by ConfigureCanvas, + * or which ConfigureCanvas expects to have reasonable values + * (e.g. resource pointers). + */ + + canvasPtr = (TkCanvas *) ckalloc(sizeof(TkCanvas)); + canvasPtr->tkwin = new; + canvasPtr->display = Tk_Display(new); + canvasPtr->interp = interp; + canvasPtr->widgetCmd = Tcl_CreateCommand(interp, + Tk_PathName(canvasPtr->tkwin), CanvasWidgetCmd, + (ClientData) canvasPtr, CanvasCmdDeletedProc); + canvasPtr->firstItemPtr = NULL; + canvasPtr->lastItemPtr = NULL; + canvasPtr->borderWidth = 0; + canvasPtr->bgBorder = NULL; + canvasPtr->relief = TK_RELIEF_FLAT; + canvasPtr->highlightWidth = 0; + canvasPtr->highlightBgColorPtr = NULL; + canvasPtr->highlightColorPtr = NULL; + canvasPtr->inset = 0; + canvasPtr->pixmapGC = None; + canvasPtr->width = None; + canvasPtr->height = None; + canvasPtr->confine = 0; + canvasPtr->textInfo.selBorder = NULL; + canvasPtr->textInfo.selBorderWidth = 0; + canvasPtr->textInfo.selFgColorPtr = NULL; + canvasPtr->textInfo.selItemPtr = NULL; + canvasPtr->textInfo.selectFirst = -1; + canvasPtr->textInfo.selectLast = -1; + canvasPtr->textInfo.anchorItemPtr = NULL; + canvasPtr->textInfo.selectAnchor = 0; + canvasPtr->textInfo.insertBorder = NULL; + canvasPtr->textInfo.insertWidth = 0; + canvasPtr->textInfo.insertBorderWidth = 0; + canvasPtr->textInfo.focusItemPtr = NULL; + canvasPtr->textInfo.gotFocus = 0; + canvasPtr->textInfo.cursorOn = 0; + canvasPtr->insertOnTime = 0; + canvasPtr->insertOffTime = 0; + canvasPtr->insertBlinkHandler = (Tcl_TimerToken) NULL; + canvasPtr->xOrigin = canvasPtr->yOrigin = 0; + canvasPtr->drawableXOrigin = canvasPtr->drawableYOrigin = 0; + canvasPtr->bindingTable = NULL; + canvasPtr->currentItemPtr = NULL; + canvasPtr->newCurrentPtr = NULL; + canvasPtr->closeEnough = 0.0; + canvasPtr->pickEvent.type = LeaveNotify; + canvasPtr->pickEvent.xcrossing.x = 0; + canvasPtr->pickEvent.xcrossing.y = 0; + canvasPtr->state = 0; + canvasPtr->xScrollCmd = NULL; + canvasPtr->yScrollCmd = NULL; + canvasPtr->scrollX1 = 0; + canvasPtr->scrollY1 = 0; + canvasPtr->scrollX2 = 0; + canvasPtr->scrollY2 = 0; + canvasPtr->regionString = NULL; + canvasPtr->xScrollIncrement = 0; + canvasPtr->yScrollIncrement = 0; + canvasPtr->scanX = 0; + canvasPtr->scanXOrigin = 0; + canvasPtr->scanY = 0; + canvasPtr->scanYOrigin = 0; + canvasPtr->hotPtr = NULL; + canvasPtr->hotPrevPtr = NULL; + canvasPtr->cursor = None; + canvasPtr->takeFocus = NULL; + canvasPtr->pixelsPerMM = WidthOfScreen(Tk_Screen(new)); + canvasPtr->pixelsPerMM /= WidthMMOfScreen(Tk_Screen(new)); + canvasPtr->flags = 0; + canvasPtr->nextId = 1; + canvasPtr->psInfoPtr = NULL; + + Tk_SetClass(canvasPtr->tkwin, "Canvas"); + TkSetClassProcs(canvasPtr->tkwin, &canvasClass, (ClientData) canvasPtr); + Tk_CreateEventHandler(canvasPtr->tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + CanvasEventProc, (ClientData) canvasPtr); + Tk_CreateEventHandler(canvasPtr->tkwin, KeyPressMask|KeyReleaseMask + |ButtonPressMask|ButtonReleaseMask|EnterWindowMask + |LeaveWindowMask|PointerMotionMask|VirtualEventMask, + CanvasBindProc, (ClientData) canvasPtr); + Tk_CreateSelHandler(canvasPtr->tkwin, XA_PRIMARY, XA_STRING, + CanvasFetchSelection, (ClientData) canvasPtr, XA_STRING); + if (ConfigureCanvas(interp, canvasPtr, argc-2, argv+2, 0) != TCL_OK) { + goto error; + } + + interp->result = Tk_PathName(canvasPtr->tkwin); + return TCL_OK; + + error: + Tk_DestroyWindow(canvasPtr->tkwin); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * CanvasWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a widget managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +CanvasWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about canvas + * widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) clientData; + size_t length; + int c, result; + Tk_Item *itemPtr = NULL; /* Initialization needed only to + * prevent compiler warning. */ + TagSearch search; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) canvasPtr); + result = TCL_OK; + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'a') && (strncmp(argv[1], "addtag", length) == 0)) { + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " addtags tag searchCommand ?arg arg ...?\"", + (char *) NULL); + goto error; + } + result = FindItems(interp, canvasPtr, argc-3, argv+3, argv[2], argv[0], + " addtag tag"); + } else if ((c == 'b') && (strncmp(argv[1], "bbox", length) == 0) + && (length >= 2)) { + int i, gotAny; + int x1 = 0, y1 = 0, x2 = 0, y2 = 0; /* Initializations needed + * only to prevent compiler + * warnings. */ + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " bbox tagOrId ?tagOrId ...?\"", + (char *) NULL); + goto error; + } + gotAny = 0; + for (i = 2; i < argc; i++) { + for (itemPtr = StartTagSearch(canvasPtr, argv[i], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + if ((itemPtr->x1 >= itemPtr->x2) + || (itemPtr->y1 >= itemPtr->y2)) { + continue; + } + if (!gotAny) { + x1 = itemPtr->x1; + y1 = itemPtr->y1; + x2 = itemPtr->x2; + y2 = itemPtr->y2; + gotAny = 1; + } else { + if (itemPtr->x1 < x1) { + x1 = itemPtr->x1; + } + if (itemPtr->y1 < y1) { + y1 = itemPtr->y1; + } + if (itemPtr->x2 > x2) { + x2 = itemPtr->x2; + } + if (itemPtr->y2 > y2) { + y2 = itemPtr->y2; + } + } + } + } + if (gotAny) { + sprintf(interp->result, "%d %d %d %d", x1, y1, x2, y2); + } + } else if ((c == 'b') && (strncmp(argv[1], "bind", length) == 0) + && (length >= 2)) { + ClientData object; + + if ((argc < 3) || (argc > 5)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " bind tagOrId ?sequence? ?command?\"", + (char *) NULL); + goto error; + } + + /* + * Figure out what object to use for the binding (individual + * item vs. tag). + */ + + object = 0; + if (isdigit(UCHAR(argv[2][0]))) { + int id; + char *end; + + id = strtoul(argv[2], &end, 0); + if (*end != 0) { + goto bindByTag; + } + for (itemPtr = canvasPtr->firstItemPtr; itemPtr != NULL; + itemPtr = itemPtr->nextPtr) { + if (itemPtr->id == id) { + object = (ClientData) itemPtr; + break; + } + } + if (object == 0) { + Tcl_AppendResult(interp, "item \"", argv[2], + "\" doesn't exist", (char *) NULL); + goto error; + } + } else { + bindByTag: + object = (ClientData) Tk_GetUid(argv[2]); + } + + /* + * Make a binding table if the canvas doesn't already have + * one. + */ + + if (canvasPtr->bindingTable == NULL) { + canvasPtr->bindingTable = Tk_CreateBindingTable(interp); + } + + if (argc == 5) { + int append = 0; + unsigned long mask; + + if (argv[4][0] == 0) { + result = Tk_DeleteBinding(interp, canvasPtr->bindingTable, + object, argv[3]); + goto done; + } + if (argv[4][0] == '+') { + argv[4]++; + append = 1; + } + mask = Tk_CreateBinding(interp, canvasPtr->bindingTable, + object, argv[3], argv[4], append); + if (mask == 0) { + goto error; + } + if (mask & (unsigned) ~(ButtonMotionMask|Button1MotionMask + |Button2MotionMask|Button3MotionMask|Button4MotionMask + |Button5MotionMask|ButtonPressMask|ButtonReleaseMask + |EnterWindowMask|LeaveWindowMask|KeyPressMask + |KeyReleaseMask|PointerMotionMask|VirtualEventMask)) { + Tk_DeleteBinding(interp, canvasPtr->bindingTable, + object, argv[3]); + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "requested illegal events; ", + "only key, button, motion, enter, leave, and virtual ", + "events may be used", (char *) NULL); + goto error; + } + } else if (argc == 4) { + char *command; + + command = Tk_GetBinding(interp, canvasPtr->bindingTable, + object, argv[3]); + if (command == NULL) { + goto error; + } + interp->result = command; + } else { + Tk_GetAllBindings(interp, canvasPtr->bindingTable, object); + } + } else if ((c == 'c') && (strcmp(argv[1], "canvasx") == 0)) { + int x; + double grid; + + if ((argc < 3) || (argc > 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " canvasx screenx ?gridspacing?\"", + (char *) NULL); + goto error; + } + if (Tk_GetPixels(interp, canvasPtr->tkwin, argv[2], &x) != TCL_OK) { + goto error; + } + if (argc == 4) { + if (Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, argv[3], + &grid) != TCL_OK) { + goto error; + } + } else { + grid = 0.0; + } + x += canvasPtr->xOrigin; + Tcl_PrintDouble(interp, GridAlign((double) x, grid), interp->result); + } else if ((c == 'c') && (strcmp(argv[1], "canvasy") == 0)) { + int y; + double grid; + + if ((argc < 3) || (argc > 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " canvasy screeny ?gridspacing?\"", + (char *) NULL); + goto error; + } + if (Tk_GetPixels(interp, canvasPtr->tkwin, argv[2], &y) != TCL_OK) { + goto error; + } + if (argc == 4) { + if (Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, + argv[3], &grid) != TCL_OK) { + goto error; + } + } else { + grid = 0.0; + } + y += canvasPtr->yOrigin; + Tcl_PrintDouble(interp, GridAlign((double) y, grid), interp->result); + } else if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + goto error; + } + result = Tk_ConfigureValue(interp, canvasPtr->tkwin, configSpecs, + (char *) canvasPtr, argv[2], 0); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 3)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, canvasPtr->tkwin, configSpecs, + (char *) canvasPtr, (char *) NULL, 0); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, canvasPtr->tkwin, configSpecs, + (char *) canvasPtr, argv[2], 0); + } else { + result = ConfigureCanvas(interp, canvasPtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else if ((c == 'c') && (strncmp(argv[1], "coords", length) == 0) + && (length >= 3)) { + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " coords tagOrId ?x y x y ...?\"", + (char *) NULL); + goto error; + } + itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + if (itemPtr != NULL) { + if (argc != 3) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + } + if (itemPtr->typePtr->coordProc != NULL) { + result = (*itemPtr->typePtr->coordProc)(interp, + (Tk_Canvas) canvasPtr, itemPtr, argc-3, argv+3); + } + if (argc != 3) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + } + } + } else if ((c == 'c') && (strncmp(argv[1], "create", length) == 0) + && (length >= 2)) { + Tk_ItemType *typePtr; + Tk_ItemType *matchPtr = NULL; + Tk_Item *itemPtr; + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " create type ?arg arg ...?\"", (char *) NULL); + goto error; + } + c = argv[2][0]; + length = strlen(argv[2]); + for (typePtr = typeList; typePtr != NULL; typePtr = typePtr->nextPtr) { + if ((c == typePtr->name[0]) + && (strncmp(argv[2], typePtr->name, length) == 0)) { + if (matchPtr != NULL) { + badType: + Tcl_AppendResult(interp, + "unknown or ambiguous item type \"", + argv[2], "\"", (char *) NULL); + goto error; + } + matchPtr = typePtr; + } + } + if (matchPtr == NULL) { + goto badType; + } + typePtr = matchPtr; + itemPtr = (Tk_Item *) ckalloc((unsigned) typePtr->itemSize); + itemPtr->id = canvasPtr->nextId; + canvasPtr->nextId++; + itemPtr->tagPtr = itemPtr->staticTagSpace; + itemPtr->tagSpace = TK_TAG_SPACE; + itemPtr->numTags = 0; + itemPtr->typePtr = typePtr; + if ((*typePtr->createProc)(interp, (Tk_Canvas) canvasPtr, + itemPtr, argc-3, argv+3) != TCL_OK) { + ckfree((char *) itemPtr); + goto error; + } + itemPtr->nextPtr = NULL; + canvasPtr->hotPtr = itemPtr; + canvasPtr->hotPrevPtr = canvasPtr->lastItemPtr; + if (canvasPtr->lastItemPtr == NULL) { + canvasPtr->firstItemPtr = itemPtr; + } else { + canvasPtr->lastItemPtr->nextPtr = itemPtr; + } + canvasPtr->lastItemPtr = itemPtr; + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + canvasPtr->flags |= REPICK_NEEDED; + sprintf(interp->result, "%d", itemPtr->id); + } else if ((c == 'd') && (strncmp(argv[1], "dchars", length) == 0) + && (length >= 2)) { + int first, last; + + if ((argc != 4) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " dchars tagOrId first ?last?\"", + (char *) NULL); + goto error; + } + for (itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + if ((itemPtr->typePtr->indexProc == NULL) + || (itemPtr->typePtr->dCharsProc == NULL)) { + continue; + } + if ((*itemPtr->typePtr->indexProc)(interp, (Tk_Canvas) canvasPtr, + itemPtr, argv[3], &first) != TCL_OK) { + goto error; + } + if (argc == 5) { + if ((*itemPtr->typePtr->indexProc)(interp, + (Tk_Canvas) canvasPtr, itemPtr, argv[4], &last) + != TCL_OK) { + goto error; + } + } else { + last = first; + } + + /* + * Redraw both item's old and new areas: it's possible + * that a delete could result in a new area larger than + * the old area. + */ + + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + (*itemPtr->typePtr->dCharsProc)((Tk_Canvas) canvasPtr, + itemPtr, first, last); + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + } + } else if ((c == 'd') && (strncmp(argv[1], "delete", length) == 0) + && (length >= 2)) { + int i; + + for (i = 2; i < argc; i++) { + for (itemPtr = StartTagSearch(canvasPtr, argv[i], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + if (canvasPtr->bindingTable != NULL) { + Tk_DeleteAllBindings(canvasPtr->bindingTable, + (ClientData) itemPtr); + } + (*itemPtr->typePtr->deleteProc)((Tk_Canvas) canvasPtr, itemPtr, + canvasPtr->display); + if (itemPtr->tagPtr != itemPtr->staticTagSpace) { + ckfree((char *) itemPtr->tagPtr); + } + if (search.prevPtr == NULL) { + canvasPtr->firstItemPtr = itemPtr->nextPtr; + if (canvasPtr->firstItemPtr == NULL) { + canvasPtr->lastItemPtr = NULL; + } + } else { + search.prevPtr->nextPtr = itemPtr->nextPtr; + } + if (canvasPtr->lastItemPtr == itemPtr) { + canvasPtr->lastItemPtr = search.prevPtr; + } + ckfree((char *) itemPtr); + if (itemPtr == canvasPtr->currentItemPtr) { + canvasPtr->currentItemPtr = NULL; + canvasPtr->flags |= REPICK_NEEDED; + } + if (itemPtr == canvasPtr->newCurrentPtr) { + canvasPtr->newCurrentPtr = NULL; + canvasPtr->flags |= REPICK_NEEDED; + } + if (itemPtr == canvasPtr->textInfo.focusItemPtr) { + canvasPtr->textInfo.focusItemPtr = NULL; + } + if (itemPtr == canvasPtr->textInfo.selItemPtr) { + canvasPtr->textInfo.selItemPtr = NULL; + } + if ((itemPtr == canvasPtr->hotPtr) + || (itemPtr == canvasPtr->hotPrevPtr)) { + canvasPtr->hotPtr = NULL; + } + } + } + } else if ((c == 'd') && (strncmp(argv[1], "dtag", length) == 0) + && (length >= 2)) { + Tk_Uid tag; + int i; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " dtag tagOrId ?tagToDelete?\"", + (char *) NULL); + goto error; + } + if (argc == 4) { + tag = Tk_GetUid(argv[3]); + } else { + tag = Tk_GetUid(argv[2]); + } + for (itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + for (i = itemPtr->numTags-1; i >= 0; i--) { + if (itemPtr->tagPtr[i] == tag) { + itemPtr->tagPtr[i] = itemPtr->tagPtr[itemPtr->numTags-1]; + itemPtr->numTags--; + } + } + } + } else if ((c == 'f') && (strncmp(argv[1], "find", length) == 0) + && (length >= 2)) { + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " find searchCommand ?arg arg ...?\"", + (char *) NULL); + goto error; + } + result = FindItems(interp, canvasPtr, argc-2, argv+2, (char *) NULL, + argv[0]," find"); + } else if ((c == 'f') && (strncmp(argv[1], "focus", length) == 0) + && (length >= 2)) { + if (argc > 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " focus ?tagOrId?\"", + (char *) NULL); + goto error; + } + itemPtr = canvasPtr->textInfo.focusItemPtr; + if (argc == 2) { + if (itemPtr != NULL) { + sprintf(interp->result, "%d", itemPtr->id); + } + goto done; + } + if ((itemPtr != NULL) && (canvasPtr->textInfo.gotFocus)) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + } + if (argv[2][0] == 0) { + canvasPtr->textInfo.focusItemPtr = NULL; + goto done; + } + for (itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + if (itemPtr->typePtr->icursorProc != NULL) { + break; + } + } + if (itemPtr == NULL) { + goto done; + } + canvasPtr->textInfo.focusItemPtr = itemPtr; + if (canvasPtr->textInfo.gotFocus) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + } + } else if ((c == 'g') && (strncmp(argv[1], "gettags", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " gettags tagOrId\"", (char *) NULL); + goto error; + } + itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + if (itemPtr != NULL) { + int i; + for (i = 0; i < itemPtr->numTags; i++) { + Tcl_AppendElement(interp, (char *) itemPtr->tagPtr[i]); + } + } + } else if ((c == 'i') && (strncmp(argv[1], "icursor", length) == 0) + && (length >= 2)) { + int index; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " icursor tagOrId index\"", + (char *) NULL); + goto error; + } + for (itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + if ((itemPtr->typePtr->indexProc == NULL) + || (itemPtr->typePtr->icursorProc == NULL)) { + goto done; + } + if ((*itemPtr->typePtr->indexProc)(interp, (Tk_Canvas) canvasPtr, + itemPtr, argv[3], &index) != TCL_OK) { + goto error; + } + (*itemPtr->typePtr->icursorProc)((Tk_Canvas) canvasPtr, itemPtr, + index); + if ((itemPtr == canvasPtr->textInfo.focusItemPtr) + && (canvasPtr->textInfo.cursorOn)) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + } + } + } else if ((c == 'i') && (strncmp(argv[1], "index", length) == 0) + && (length >= 3)) { + int index; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " index tagOrId string\"", + (char *) NULL); + goto error; + } + for (itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + if (itemPtr->typePtr->indexProc != NULL) { + break; + } + } + if (itemPtr == NULL) { + Tcl_AppendResult(interp, "can't find an indexable item \"", + argv[2], "\"", (char *) NULL); + goto error; + } + if ((*itemPtr->typePtr->indexProc)(interp, (Tk_Canvas) canvasPtr, + itemPtr, argv[3], &index) != TCL_OK) { + goto error; + } + sprintf(interp->result, "%d", index); + } else if ((c == 'i') && (strncmp(argv[1], "insert", length) == 0) + && (length >= 3)) { + int beforeThis; + + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " insert tagOrId beforeThis string\"", + (char *) NULL); + goto error; + } + for (itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + if ((itemPtr->typePtr->indexProc == NULL) + || (itemPtr->typePtr->insertProc == NULL)) { + continue; + } + if ((*itemPtr->typePtr->indexProc)(interp, (Tk_Canvas) canvasPtr, + itemPtr, argv[3], &beforeThis) != TCL_OK) { + goto error; + } + + /* + * Redraw both item's old and new areas: it's possible + * that an insertion could result in a new area either + * larger or smaller than the old area. + */ + + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + (*itemPtr->typePtr->insertProc)((Tk_Canvas) canvasPtr, + itemPtr, beforeThis, argv[4]); + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, itemPtr->x1, + itemPtr->y1, itemPtr->x2, itemPtr->y2); + } + } else if ((c == 'i') && (strncmp(argv[1], "itemcget", length) == 0) + && (length >= 6)) { + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " itemcget tagOrId option\"", + (char *) NULL); + return TCL_ERROR; + } + itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + if (itemPtr != NULL) { + result = Tk_ConfigureValue(canvasPtr->interp, canvasPtr->tkwin, + itemPtr->typePtr->configSpecs, (char *) itemPtr, + argv[3], 0); + } + } else if ((c == 'i') && (strncmp(argv[1], "itemconfigure", length) == 0) + && (length >= 6)) { + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " itemconfigure tagOrId ?option value ...?\"", + (char *) NULL); + goto error; + } + for (itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + if (argc == 3) { + result = Tk_ConfigureInfo(canvasPtr->interp, canvasPtr->tkwin, + itemPtr->typePtr->configSpecs, (char *) itemPtr, + (char *) NULL, 0); + } else if (argc == 4) { + result = Tk_ConfigureInfo(canvasPtr->interp, canvasPtr->tkwin, + itemPtr->typePtr->configSpecs, (char *) itemPtr, + argv[3], 0); + } else { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + result = (*itemPtr->typePtr->configProc)(interp, + (Tk_Canvas) canvasPtr, itemPtr, argc-3, argv+3, + TK_CONFIG_ARGV_ONLY); + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + canvasPtr->flags |= REPICK_NEEDED; + } + if ((result != TCL_OK) || (argc < 5)) { + break; + } + } + } else if ((c == 'l') && (strncmp(argv[1], "lower", length) == 0)) { + Tk_Item *prevPtr; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " lower tagOrId ?belowThis?\"", + (char *) NULL); + goto error; + } + + /* + * First find the item just after which we'll insert the + * named items. + */ + + if (argc == 3) { + prevPtr = NULL; + } else { + prevPtr = StartTagSearch(canvasPtr, argv[3], &search); + if (prevPtr != NULL) { + prevPtr = search.prevPtr; + } else { + Tcl_AppendResult(interp, "tag \"", argv[3], + "\" doesn't match any items", (char *) NULL); + goto error; + } + } + RelinkItems(canvasPtr, argv[2], prevPtr); + } else if ((c == 'm') && (strncmp(argv[1], "move", length) == 0)) { + double xAmount, yAmount; + + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " move tagOrId xAmount yAmount\"", + (char *) NULL); + goto error; + } + if ((Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, argv[3], + &xAmount) != TCL_OK) || (Tk_CanvasGetCoord(interp, + (Tk_Canvas) canvasPtr, argv[4], &yAmount) != TCL_OK)) { + goto error; + } + for (itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + (void) (*itemPtr->typePtr->translateProc)((Tk_Canvas) canvasPtr, + itemPtr, xAmount, yAmount); + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + canvasPtr->flags |= REPICK_NEEDED; + } + } else if ((c == 'p') && (strncmp(argv[1], "postscript", length) == 0)) { + result = TkCanvPostscriptCmd(canvasPtr, interp, argc, argv); + } else if ((c == 'r') && (strncmp(argv[1], "raise", length) == 0)) { + Tk_Item *prevPtr; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " raise tagOrId ?aboveThis?\"", + (char *) NULL); + goto error; + } + + /* + * First find the item just after which we'll insert the + * named items. + */ + + if (argc == 3) { + prevPtr = canvasPtr->lastItemPtr; + } else { + prevPtr = NULL; + for (itemPtr = StartTagSearch(canvasPtr, argv[3], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + prevPtr = itemPtr; + } + if (prevPtr == NULL) { + Tcl_AppendResult(interp, "tagOrId \"", argv[3], + "\" doesn't match any items", (char *) NULL); + goto error; + } + } + RelinkItems(canvasPtr, argv[2], prevPtr); + } else if ((c == 's') && (strncmp(argv[1], "scale", length) == 0) + && (length >= 3)) { + double xOrigin, yOrigin, xScale, yScale; + + if (argc != 7) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " scale tagOrId xOrigin yOrigin xScale yScale\"", + (char *) NULL); + goto error; + } + if ((Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, + argv[3], &xOrigin) != TCL_OK) + || (Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, + argv[4], &yOrigin) != TCL_OK) + || (Tcl_GetDouble(interp, argv[5], &xScale) != TCL_OK) + || (Tcl_GetDouble(interp, argv[6], &yScale) != TCL_OK)) { + goto error; + } + if ((xScale == 0.0) || (yScale == 0.0)) { + interp->result = "scale factor cannot be zero"; + goto error; + } + for (itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + (void) (*itemPtr->typePtr->scaleProc)((Tk_Canvas) canvasPtr, + itemPtr, xOrigin, yOrigin, xScale, yScale); + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + canvasPtr->flags |= REPICK_NEEDED; + } + } else if ((c == 's') && (strncmp(argv[1], "scan", length) == 0) + && (length >= 3)) { + int x, y; + + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " scan mark|dragto x y\"", (char *) NULL); + goto error; + } + if ((Tcl_GetInt(interp, argv[3], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &y) != TCL_OK)){ + goto error; + } + if ((argv[2][0] == 'm') + && (strncmp(argv[2], "mark", strlen(argv[2])) == 0)) { + canvasPtr->scanX = x; + canvasPtr->scanXOrigin = canvasPtr->xOrigin; + canvasPtr->scanY = y; + canvasPtr->scanYOrigin = canvasPtr->yOrigin; + } else if ((argv[2][0] == 'd') + && (strncmp(argv[2], "dragto", strlen(argv[2])) == 0)) { + int newXOrigin, newYOrigin, tmp; + + /* + * Compute a new view origin for the canvas, amplifying the + * mouse motion. + */ + + tmp = canvasPtr->scanXOrigin - 10*(x - canvasPtr->scanX) + - canvasPtr->scrollX1; + newXOrigin = canvasPtr->scrollX1 + tmp; + tmp = canvasPtr->scanYOrigin - 10*(y - canvasPtr->scanY) + - canvasPtr->scrollY1; + newYOrigin = canvasPtr->scrollY1 + tmp; + CanvasSetOrigin(canvasPtr, newXOrigin, newYOrigin); + } else { + Tcl_AppendResult(interp, "bad scan option \"", argv[2], + "\": must be mark or dragto", (char *) NULL); + goto error; + } + } else if ((c == 's') && (strncmp(argv[1], "select", length) == 0) + && (length >= 2)) { + int index; + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " select option ?tagOrId? ?arg?\"", (char *) NULL); + goto error; + } + if (argc >= 4) { + for (itemPtr = StartTagSearch(canvasPtr, argv[3], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + if ((itemPtr->typePtr->indexProc != NULL) + && (itemPtr->typePtr->selectionProc != NULL)){ + break; + } + } + if (itemPtr == NULL) { + Tcl_AppendResult(interp, + "can't find an indexable and selectable item \"", + argv[3], "\"", (char *) NULL); + goto error; + } + } + if (argc == 5) { + if ((*itemPtr->typePtr->indexProc)(interp, (Tk_Canvas) canvasPtr, + itemPtr, argv[4], &index) != TCL_OK) { + goto error; + } + } + length = strlen(argv[2]); + c = argv[2][0]; + if ((c == 'a') && (strncmp(argv[2], "adjust", length) == 0)) { + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " select adjust tagOrId index\"", + (char *) NULL); + goto error; + } + if (canvasPtr->textInfo.selItemPtr == itemPtr) { + if (index < (canvasPtr->textInfo.selectFirst + + canvasPtr->textInfo.selectLast)/2) { + canvasPtr->textInfo.selectAnchor = + canvasPtr->textInfo.selectLast + 1; + } else { + canvasPtr->textInfo.selectAnchor = + canvasPtr->textInfo.selectFirst; + } + } + CanvasSelectTo(canvasPtr, itemPtr, index); + } else if ((c == 'c') && (argv[2] != NULL) + && (strncmp(argv[2], "clear", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " select clear\"", (char *) NULL); + goto error; + } + if (canvasPtr->textInfo.selItemPtr != NULL) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + canvasPtr->textInfo.selItemPtr->x1, + canvasPtr->textInfo.selItemPtr->y1, + canvasPtr->textInfo.selItemPtr->x2, + canvasPtr->textInfo.selItemPtr->y2); + canvasPtr->textInfo.selItemPtr = NULL; + } + goto done; + } else if ((c == 'f') && (strncmp(argv[2], "from", length) == 0)) { + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " select from tagOrId index\"", + (char *) NULL); + goto error; + } + canvasPtr->textInfo.anchorItemPtr = itemPtr; + canvasPtr->textInfo.selectAnchor = index; + } else if ((c == 'i') && (strncmp(argv[2], "item", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " select item\"", (char *) NULL); + goto error; + } + if (canvasPtr->textInfo.selItemPtr != NULL) { + sprintf(interp->result, "%d", + canvasPtr->textInfo.selItemPtr->id); + } + } else if ((c == 't') && (strncmp(argv[2], "to", length) == 0)) { + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " select to tagOrId index\"", + (char *) NULL); + goto error; + } + CanvasSelectTo(canvasPtr, itemPtr, index); + } else { + Tcl_AppendResult(interp, "bad select option \"", argv[2], + "\": must be adjust, clear, from, item, or to", + (char *) NULL); + goto error; + } + } else if ((c == 't') && (strncmp(argv[1], "type", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " type tag\"", (char *) NULL); + goto error; + } + itemPtr = StartTagSearch(canvasPtr, argv[2], &search); + if (itemPtr != NULL) { + interp->result = itemPtr->typePtr->name; + } + } else if ((c == 'x') && (strncmp(argv[1], "xview", length) == 0)) { + int count, type; + int newX = 0; /* Initialization needed only to prevent + * gcc warnings. */ + double fraction; + + if (argc == 2) { + PrintScrollFractions(canvasPtr->xOrigin + canvasPtr->inset, + canvasPtr->xOrigin + Tk_Width(canvasPtr->tkwin) + - canvasPtr->inset, canvasPtr->scrollX1, + canvasPtr->scrollX2, interp->result); + } else { + type = Tk_GetScrollInfo(interp, argc, argv, &fraction, &count); + switch (type) { + case TK_SCROLL_ERROR: + goto error; + case TK_SCROLL_MOVETO: + newX = canvasPtr->scrollX1 - canvasPtr->inset + + (int) (fraction * (canvasPtr->scrollX2 + - canvasPtr->scrollX1) + 0.5); + break; + case TK_SCROLL_PAGES: + newX = (int) (canvasPtr->xOrigin + count * .9 + * (Tk_Width(canvasPtr->tkwin) - 2*canvasPtr->inset)); + break; + case TK_SCROLL_UNITS: + if (canvasPtr->xScrollIncrement > 0) { + newX = canvasPtr->xOrigin + + count*canvasPtr->xScrollIncrement; + } else { + newX = (int) (canvasPtr->xOrigin + count * .1 + * (Tk_Width(canvasPtr->tkwin) + - 2*canvasPtr->inset)); + } + break; + } + CanvasSetOrigin(canvasPtr, newX, canvasPtr->yOrigin); + } + } else if ((c == 'y') && (strncmp(argv[1], "yview", length) == 0)) { + int count, type; + int newY = 0; /* Initialization needed only to prevent + * gcc warnings. */ + double fraction; + + if (argc == 2) { + PrintScrollFractions(canvasPtr->yOrigin + canvasPtr->inset, + canvasPtr->yOrigin + Tk_Height(canvasPtr->tkwin) + - canvasPtr->inset, canvasPtr->scrollY1, + canvasPtr->scrollY2, interp->result); + } else { + type = Tk_GetScrollInfo(interp, argc, argv, &fraction, &count); + switch (type) { + case TK_SCROLL_ERROR: + goto error; + case TK_SCROLL_MOVETO: + newY = canvasPtr->scrollY1 - canvasPtr->inset + + (int) (fraction*(canvasPtr->scrollY2 + - canvasPtr->scrollY1) + 0.5); + break; + case TK_SCROLL_PAGES: + newY = (int) (canvasPtr->yOrigin + count * .9 + * (Tk_Height(canvasPtr->tkwin) + - 2*canvasPtr->inset)); + break; + case TK_SCROLL_UNITS: + if (canvasPtr->yScrollIncrement > 0) { + newY = canvasPtr->yOrigin + + count*canvasPtr->yScrollIncrement; + } else { + newY = (int) (canvasPtr->yOrigin + count * .1 + * (Tk_Height(canvasPtr->tkwin) + - 2*canvasPtr->inset)); + } + break; + } + CanvasSetOrigin(canvasPtr, canvasPtr->xOrigin, newY); + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be addtag, bbox, bind, ", + "canvasx, canvasy, cget, configure, coords, create, ", + "dchars, delete, dtag, find, focus, ", + "gettags, icursor, index, insert, itemcget, itemconfigure, ", + "lower, move, postscript, raise, scale, scan, ", + "select, type, xview, or yview", + (char *) NULL); + goto error; + } + done: + Tcl_Release((ClientData) canvasPtr); + return result; + + error: + Tcl_Release((ClientData) canvasPtr); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyCanvas -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a canvas at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the canvas is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyCanvas(memPtr) + char *memPtr; /* Info about canvas widget. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) memPtr; + Tk_Item *itemPtr; + + /* + * Free up all of the items in the canvas. + */ + + for (itemPtr = canvasPtr->firstItemPtr; itemPtr != NULL; + itemPtr = canvasPtr->firstItemPtr) { + canvasPtr->firstItemPtr = itemPtr->nextPtr; + (*itemPtr->typePtr->deleteProc)((Tk_Canvas) canvasPtr, itemPtr, + canvasPtr->display); + if (itemPtr->tagPtr != itemPtr->staticTagSpace) { + ckfree((char *) itemPtr->tagPtr); + } + ckfree((char *) itemPtr); + } + + /* + * Free up all the stuff that requires special handling, + * then let Tk_FreeOptions handle all the standard option-related + * stuff. + */ + + if (canvasPtr->pixmapGC != None) { + Tk_FreeGC(canvasPtr->display, canvasPtr->pixmapGC); + } + Tcl_DeleteTimerHandler(canvasPtr->insertBlinkHandler); + if (canvasPtr->bindingTable != NULL) { + Tk_DeleteBindingTable(canvasPtr->bindingTable); + } + Tk_FreeOptions(configSpecs, (char *) canvasPtr, canvasPtr->display, 0); + ckfree((char *) canvasPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureCanvas -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or + * reconfigure) a canvas widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as colors, border width, + * etc. get set for canvasPtr; old resources get freed, + * if there were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureCanvas(interp, canvasPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + TkCanvas *canvasPtr; /* Information about widget; may or may + * not already have values for some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + XGCValues gcValues; + GC new; + + if (Tk_ConfigureWidget(interp, canvasPtr->tkwin, configSpecs, + argc, argv, (char *) canvasPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few options need special processing, such as setting the + * background from a 3-D border and creating a GC for copying + * bits to the screen. + */ + + Tk_SetBackgroundFromBorder(canvasPtr->tkwin, canvasPtr->bgBorder); + + if (canvasPtr->highlightWidth < 0) { + canvasPtr->highlightWidth = 0; + } + canvasPtr->inset = canvasPtr->borderWidth + canvasPtr->highlightWidth; + + gcValues.function = GXcopy; + gcValues.foreground = Tk_3DBorderColor(canvasPtr->bgBorder)->pixel; + gcValues.graphics_exposures = False; + new = Tk_GetGC(canvasPtr->tkwin, + GCFunction|GCForeground|GCGraphicsExposures, &gcValues); + if (canvasPtr->pixmapGC != None) { + Tk_FreeGC(canvasPtr->display, canvasPtr->pixmapGC); + } + canvasPtr->pixmapGC = new; + + /* + * Reset the desired dimensions for the window. + */ + + Tk_GeometryRequest(canvasPtr->tkwin, canvasPtr->width + 2*canvasPtr->inset, + canvasPtr->height + 2*canvasPtr->inset); + + /* + * Restart the cursor timing sequence in case the on-time or off-time + * just changed. + */ + + if (canvasPtr->textInfo.gotFocus) { + CanvasFocusProc(canvasPtr, 1); + } + + /* + * Recompute the scroll region. + */ + + canvasPtr->scrollX1 = 0; + canvasPtr->scrollY1 = 0; + canvasPtr->scrollX2 = 0; + canvasPtr->scrollY2 = 0; + if (canvasPtr->regionString != NULL) { + int argc2; + char **argv2; + + if (Tcl_SplitList(canvasPtr->interp, canvasPtr->regionString, + &argc2, &argv2) != TCL_OK) { + return TCL_ERROR; + } + if (argc2 != 4) { + Tcl_AppendResult(interp, "bad scrollRegion \"", + canvasPtr->regionString, "\"", (char *) NULL); + badRegion: + ckfree(canvasPtr->regionString); + ckfree((char *) argv2); + canvasPtr->regionString = NULL; + return TCL_ERROR; + } + if ((Tk_GetPixels(canvasPtr->interp, canvasPtr->tkwin, + argv2[0], &canvasPtr->scrollX1) != TCL_OK) + || (Tk_GetPixels(canvasPtr->interp, canvasPtr->tkwin, + argv2[1], &canvasPtr->scrollY1) != TCL_OK) + || (Tk_GetPixels(canvasPtr->interp, canvasPtr->tkwin, + argv2[2], &canvasPtr->scrollX2) != TCL_OK) + || (Tk_GetPixels(canvasPtr->interp, canvasPtr->tkwin, + argv2[3], &canvasPtr->scrollY2) != TCL_OK)) { + goto badRegion; + } + ckfree((char *) argv2); + } + + /* + * Reset the canvas's origin (this is a no-op unless confine + * mode has just been turned on or the scroll region has changed). + */ + + CanvasSetOrigin(canvasPtr, canvasPtr->xOrigin, canvasPtr->yOrigin); + canvasPtr->flags |= UPDATE_SCROLLBARS|REDRAW_BORDERS; + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + canvasPtr->xOrigin, canvasPtr->yOrigin, + canvasPtr->xOrigin + Tk_Width(canvasPtr->tkwin), + canvasPtr->yOrigin + Tk_Height(canvasPtr->tkwin)); + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * CanvasWorldChanged -- + * + * This procedure is called when the world has changed in some + * way and the widget needs to recompute all its graphics contexts + * and determine its new geometry. + * + * Results: + * None. + * + * Side effects: + * Configures all items in the canvas with a empty argc/argv, for + * the side effect of causing all the items to recompute their + * geometry and to be redisplayed. + * + *--------------------------------------------------------------------------- + */ + +static void +CanvasWorldChanged(instanceData) + ClientData instanceData; /* Information about widget. */ +{ + TkCanvas *canvasPtr; + Tk_Item *itemPtr; + int result; + + canvasPtr = (TkCanvas *) instanceData; + itemPtr = canvasPtr->firstItemPtr; + for ( ; itemPtr != NULL; itemPtr = itemPtr->nextPtr) { + result = (*itemPtr->typePtr->configProc)(canvasPtr->interp, + (Tk_Canvas) canvasPtr, itemPtr, 0, NULL, + TK_CONFIG_ARGV_ONLY); + if (result != TCL_OK) { + Tcl_ResetResult(canvasPtr->interp); + } + } + canvasPtr->flags |= REPICK_NEEDED; + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + canvasPtr->xOrigin, canvasPtr->yOrigin, + canvasPtr->xOrigin + Tk_Width(canvasPtr->tkwin), + canvasPtr->yOrigin + Tk_Height(canvasPtr->tkwin)); +} + +/* + *-------------------------------------------------------------- + * + * DisplayCanvas -- + * + * This procedure redraws the contents of a canvas window. + * It is invoked as a do-when-idle handler, so it only runs + * when there's nothing else for the application to do. + * + * Results: + * None. + * + * Side effects: + * Information appears on the screen. + * + *-------------------------------------------------------------- + */ + +static void +DisplayCanvas(clientData) + ClientData clientData; /* Information about widget. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) clientData; + Tk_Window tkwin = canvasPtr->tkwin; + Tk_Item *itemPtr; + Pixmap pixmap; + int screenX1, screenX2, screenY1, screenY2, width, height; + + if (canvasPtr->tkwin == NULL) { + return; + } + if (!Tk_IsMapped(tkwin)) { + goto done; + } + + /* + * Choose a new current item if that is needed (this could cause + * event handlers to be invoked). + */ + + while (canvasPtr->flags & REPICK_NEEDED) { + Tcl_Preserve((ClientData) canvasPtr); + canvasPtr->flags &= ~REPICK_NEEDED; + PickCurrentItem(canvasPtr, &canvasPtr->pickEvent); + tkwin = canvasPtr->tkwin; + Tcl_Release((ClientData) canvasPtr); + if (tkwin == NULL) { + return; + } + } + + /* + * Compute the intersection between the area that needs redrawing + * and the area that's visible on the screen. + */ + + if ((canvasPtr->redrawX1 < canvasPtr->redrawX2) + && (canvasPtr->redrawY1 < canvasPtr->redrawY2)) { + screenX1 = canvasPtr->xOrigin + canvasPtr->inset; + screenY1 = canvasPtr->yOrigin + canvasPtr->inset; + screenX2 = canvasPtr->xOrigin + Tk_Width(tkwin) - canvasPtr->inset; + screenY2 = canvasPtr->yOrigin + Tk_Height(tkwin) - canvasPtr->inset; + if (canvasPtr->redrawX1 > screenX1) { + screenX1 = canvasPtr->redrawX1; + } + if (canvasPtr->redrawY1 > screenY1) { + screenY1 = canvasPtr->redrawY1; + } + if (canvasPtr->redrawX2 < screenX2) { + screenX2 = canvasPtr->redrawX2; + } + if (canvasPtr->redrawY2 < screenY2) { + screenY2 = canvasPtr->redrawY2; + } + if ((screenX1 >= screenX2) || (screenY1 >= screenY2)) { + goto borders; + } + + /* + * Redrawing is done in a temporary pixmap that is allocated + * here and freed at the end of the procedure. All drawing + * is done to the pixmap, and the pixmap is copied to the + * screen at the end of the procedure. The temporary pixmap + * serves two purposes: + * + * 1. It provides a smoother visual effect (no clearing and + * gradual redraw will be visible to users). + * 2. It allows us to redraw only the objects that overlap + * the redraw area. Otherwise incorrect results could + * occur from redrawing things that stick outside of + * the redraw area (we'd have to redraw everything in + * order to make the overlaps look right). + * + * Some tricky points about the pixmap: + * + * 1. We only allocate a large enough pixmap to hold the + * area that has to be redisplayed. This saves time in + * in the X server for large objects that cover much + * more than the area being redisplayed: only the area + * of the pixmap will actually have to be redrawn. + * 2. Some X servers (e.g. the one for DECstations) have troubles + * with characters that overlap an edge of the pixmap (on the + * DEC servers, as of 8/18/92, such characters are drawn one + * pixel too far to the right). To handle this problem, + * make the pixmap a bit larger than is absolutely needed + * so that for normal-sized fonts the characters that overlap + * the edge of the pixmap will be outside the area we care + * about. + */ + + canvasPtr->drawableXOrigin = screenX1 - 30; + canvasPtr->drawableYOrigin = screenY1 - 30; + pixmap = Tk_GetPixmap(Tk_Display(tkwin), Tk_WindowId(tkwin), + (screenX2 + 30 - canvasPtr->drawableXOrigin), + (screenY2 + 30 - canvasPtr->drawableYOrigin), + Tk_Depth(tkwin)); + + /* + * Clear the area to be redrawn. + */ + + width = screenX2 - screenX1; + height = screenY2 - screenY1; + + XFillRectangle(Tk_Display(tkwin), pixmap, canvasPtr->pixmapGC, + screenX1 - canvasPtr->drawableXOrigin, + screenY1 - canvasPtr->drawableYOrigin, (unsigned int) width, + (unsigned int) height); + + /* + * Scan through the item list, redrawing those items that need it. + * An item must be redraw if either (a) it intersects the smaller + * on-screen area or (b) it intersects the full canvas area and its + * type requests that it be redrawn always (e.g. so subwindows can + * be unmapped when they move off-screen). + */ + + for (itemPtr = canvasPtr->firstItemPtr; itemPtr != NULL; + itemPtr = itemPtr->nextPtr) { + if ((itemPtr->x1 >= screenX2) + || (itemPtr->y1 >= screenY2) + || (itemPtr->x2 < screenX1) + || (itemPtr->y2 < screenY1)) { + if (!itemPtr->typePtr->alwaysRedraw + || (itemPtr->x1 >= canvasPtr->redrawX2) + || (itemPtr->y1 >= canvasPtr->redrawY2) + || (itemPtr->x2 < canvasPtr->redrawX1) + || (itemPtr->y2 < canvasPtr->redrawY1)) { + continue; + } + } + (*itemPtr->typePtr->displayProc)((Tk_Canvas) canvasPtr, itemPtr, + canvasPtr->display, pixmap, screenX1, screenY1, width, + height); + } + + /* + * Copy from the temporary pixmap to the screen, then free up + * the temporary pixmap. + */ + + XCopyArea(Tk_Display(tkwin), pixmap, Tk_WindowId(tkwin), + canvasPtr->pixmapGC, + screenX1 - canvasPtr->drawableXOrigin, + screenY1 - canvasPtr->drawableYOrigin, + (unsigned) (screenX2 - screenX1), + (unsigned) (screenY2 - screenY1), + screenX1 - canvasPtr->xOrigin, screenY1 - canvasPtr->yOrigin); + Tk_FreePixmap(Tk_Display(tkwin), pixmap); + } + + /* + * Draw the window borders, if needed. + */ + + borders: + if (canvasPtr->flags & REDRAW_BORDERS) { + canvasPtr->flags &= ~REDRAW_BORDERS; + if (canvasPtr->borderWidth > 0) { + Tk_Draw3DRectangle(tkwin, Tk_WindowId(tkwin), + canvasPtr->bgBorder, canvasPtr->highlightWidth, + canvasPtr->highlightWidth, + Tk_Width(tkwin) - 2*canvasPtr->highlightWidth, + Tk_Height(tkwin) - 2*canvasPtr->highlightWidth, + canvasPtr->borderWidth, canvasPtr->relief); + } + if (canvasPtr->highlightWidth != 0) { + GC gc; + + if (canvasPtr->textInfo.gotFocus) { + gc = Tk_GCForColor(canvasPtr->highlightColorPtr, + Tk_WindowId(tkwin)); + } else { + gc = Tk_GCForColor(canvasPtr->highlightBgColorPtr, + Tk_WindowId(tkwin)); + } + Tk_DrawFocusHighlight(tkwin, gc, canvasPtr->highlightWidth, + Tk_WindowId(tkwin)); + } + } + + done: + canvasPtr->flags &= ~REDRAW_PENDING; + canvasPtr->redrawX1 = canvasPtr->redrawX2 = 0; + canvasPtr->redrawY1 = canvasPtr->redrawY2 = 0; + if (canvasPtr->flags & UPDATE_SCROLLBARS) { + CanvasUpdateScrollbars(canvasPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * CanvasEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on canvases. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +CanvasEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) clientData; + + if (eventPtr->type == Expose) { + int x, y; + + x = eventPtr->xexpose.x + canvasPtr->xOrigin; + y = eventPtr->xexpose.y + canvasPtr->yOrigin; + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, x, y, + x + eventPtr->xexpose.width, + y + eventPtr->xexpose.height); + if ((eventPtr->xexpose.x < canvasPtr->inset) + || (eventPtr->xexpose.y < canvasPtr->inset) + || ((eventPtr->xexpose.x + eventPtr->xexpose.width) + > (Tk_Width(canvasPtr->tkwin) - canvasPtr->inset)) + || ((eventPtr->xexpose.y + eventPtr->xexpose.height) + > (Tk_Height(canvasPtr->tkwin) - canvasPtr->inset))) { + canvasPtr->flags |= REDRAW_BORDERS; + } + } else if (eventPtr->type == DestroyNotify) { + if (canvasPtr->tkwin != NULL) { + canvasPtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(canvasPtr->interp, + canvasPtr->widgetCmd); + } + if (canvasPtr->flags & REDRAW_PENDING) { + Tcl_CancelIdleCall(DisplayCanvas, (ClientData) canvasPtr); + } + Tcl_EventuallyFree((ClientData) canvasPtr, DestroyCanvas); + } else if (eventPtr->type == ConfigureNotify) { + canvasPtr->flags |= UPDATE_SCROLLBARS; + + /* + * The call below is needed in order to recenter the canvas if + * it's confined and its scroll region is smaller than the window. + */ + + CanvasSetOrigin(canvasPtr, canvasPtr->xOrigin, canvasPtr->yOrigin); + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, canvasPtr->xOrigin, + canvasPtr->yOrigin, + canvasPtr->xOrigin + Tk_Width(canvasPtr->tkwin), + canvasPtr->yOrigin + Tk_Height(canvasPtr->tkwin)); + canvasPtr->flags |= REDRAW_BORDERS; + } else if (eventPtr->type == FocusIn) { + if (eventPtr->xfocus.detail != NotifyInferior) { + CanvasFocusProc(canvasPtr, 1); + } + } else if (eventPtr->type == FocusOut) { + if (eventPtr->xfocus.detail != NotifyInferior) { + CanvasFocusProc(canvasPtr, 0); + } + } else if (eventPtr->type == UnmapNotify) { + Tk_Item *itemPtr; + + /* + * Special hack: if the canvas is unmapped, then must notify + * all items with "alwaysRedraw" set, so that they know that + * they are no longer displayed. + */ + + for (itemPtr = canvasPtr->firstItemPtr; itemPtr != NULL; + itemPtr = itemPtr->nextPtr) { + if (itemPtr->typePtr->alwaysRedraw) { + (*itemPtr->typePtr->displayProc)((Tk_Canvas) canvasPtr, + itemPtr, canvasPtr->display, None, 0, 0, 0, 0); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * CanvasCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +CanvasCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) clientData; + Tk_Window tkwin = canvasPtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + canvasPtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_CanvasEventuallyRedraw -- + * + * Arrange for part or all of a canvas widget to redrawn at + * some convenient time in the future. + * + * Results: + * None. + * + * Side effects: + * The screen will eventually be refreshed. + * + *-------------------------------------------------------------- + */ + +void +Tk_CanvasEventuallyRedraw(canvas, x1, y1, x2, y2) + Tk_Canvas canvas; /* Information about widget. */ + int x1, y1; /* Upper left corner of area to redraw. + * Pixels on edge are redrawn. */ + int x2, y2; /* Lower right corner of area to redraw. + * Pixels on edge are not redrawn. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) canvas; + if ((x1 == x2) || (y1 == y2)) { + return; + } + if (canvasPtr->flags & REDRAW_PENDING) { + if (x1 <= canvasPtr->redrawX1) { + canvasPtr->redrawX1 = x1; + } + if (y1 <= canvasPtr->redrawY1) { + canvasPtr->redrawY1 = y1; + } + if (x2 >= canvasPtr->redrawX2) { + canvasPtr->redrawX2 = x2; + } + if (y2 >= canvasPtr->redrawY2) { + canvasPtr->redrawY2 = y2; + } + } else { + canvasPtr->redrawX1 = x1; + canvasPtr->redrawY1 = y1; + canvasPtr->redrawX2 = x2; + canvasPtr->redrawY2 = y2; + Tcl_DoWhenIdle(DisplayCanvas, (ClientData) canvasPtr); + canvasPtr->flags |= REDRAW_PENDING; + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_CreateItemType -- + * + * This procedure may be invoked to add a new kind of canvas + * element to the core item types supported by Tk. + * + * Results: + * None. + * + * Side effects: + * From now on, the new item type will be useable in canvas + * widgets (e.g. typePtr->name can be used as the item type + * in "create" widget commands). If there was already a + * type with the same name as in typePtr, it is replaced with + * the new type. + * + *-------------------------------------------------------------- + */ + +void +Tk_CreateItemType(typePtr) + Tk_ItemType *typePtr; /* Information about item type; + * storage must be statically + * allocated (must live forever). */ +{ + Tk_ItemType *typePtr2, *prevPtr; + + if (typeList == NULL) { + InitCanvas(); + } + + /* + * If there's already an item type with the given name, remove it. + */ + + for (typePtr2 = typeList, prevPtr = NULL; typePtr2 != NULL; + prevPtr = typePtr2, typePtr2 = typePtr2->nextPtr) { + if (strcmp(typePtr2->name, typePtr->name) == 0) { + if (prevPtr == NULL) { + typeList = typePtr2->nextPtr; + } else { + prevPtr->nextPtr = typePtr2->nextPtr; + } + break; + } + } + typePtr->nextPtr = typeList; + typeList = typePtr; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetItemTypes -- + * + * This procedure returns a pointer to the list of all item + * types. + * + * Results: + * The return value is a pointer to the first in the list + * of item types currently supported by canvases. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_ItemType * +Tk_GetItemTypes() +{ + if (typeList == NULL) { + InitCanvas(); + } + return typeList; +} + +/* + *-------------------------------------------------------------- + * + * InitCanvas -- + * + * This procedure is invoked to perform once-only-ever + * initialization for the module, such as setting up + * the type table. + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static void +InitCanvas() +{ + if (typeList != NULL) { + return; + } + typeList = &tkRectangleType; + tkRectangleType.nextPtr = &tkTextType; + tkTextType.nextPtr = &tkLineType; + tkLineType.nextPtr = &tkPolygonType; + tkPolygonType.nextPtr = &tkImageType; + tkImageType.nextPtr = &tkOvalType; + tkOvalType.nextPtr = &tkBitmapType; + tkBitmapType.nextPtr = &tkArcType; + tkArcType.nextPtr = &tkWindowType; + tkWindowType.nextPtr = NULL; + allUid = Tk_GetUid("all"); + currentUid = Tk_GetUid("current"); +} + +/* + *-------------------------------------------------------------- + * + * StartTagSearch -- + * + * This procedure is called to initiate an enumeration of + * all items in a given canvas that contain a given tag. + * + * Results: + * The return value is a pointer to the first item in + * canvasPtr that matches tag, or NULL if there is no + * such item. The information at *searchPtr is initialized + * such that successive calls to NextItem will return + * successive items that match tag. + * + * Side effects: + * SearchPtr is linked into a list of searches in progress + * on canvasPtr, so that elements can safely be deleted + * while the search is in progress. EndTagSearch must be + * called at the end of the search to unlink searchPtr from + * this list. + * + *-------------------------------------------------------------- + */ + +static Tk_Item * +StartTagSearch(canvasPtr, tag, searchPtr) + TkCanvas *canvasPtr; /* Canvas whose items are to be + * searched. */ + char *tag; /* String giving tag value. */ + TagSearch *searchPtr; /* Record describing tag search; + * will be initialized here. */ +{ + int id; + Tk_Item *itemPtr, *prevPtr; + Tk_Uid *tagPtr; + Tk_Uid uid; + int count; + + /* + * Initialize the search. + */ + + searchPtr->canvasPtr = canvasPtr; + searchPtr->searchOver = 0; + + /* + * Find the first matching item in one of several ways. If the tag + * is a number then it selects the single item with the matching + * identifier. In this case see if the item being requested is the + * hot item, in which case the search can be skipped. + */ + + if (isdigit(UCHAR(*tag))) { + char *end; + + numIdSearches++; + id = strtoul(tag, &end, 0); + if (*end == 0) { + itemPtr = canvasPtr->hotPtr; + prevPtr = canvasPtr->hotPrevPtr; + if ((itemPtr == NULL) || (itemPtr->id != id) || (prevPtr == NULL) + || (prevPtr->nextPtr != itemPtr)) { + numSlowSearches++; + for (prevPtr = NULL, itemPtr = canvasPtr->firstItemPtr; + itemPtr != NULL; + prevPtr = itemPtr, itemPtr = itemPtr->nextPtr) { + if (itemPtr->id == id) { + break; + } + } + } + searchPtr->prevPtr = prevPtr; + searchPtr->searchOver = 1; + canvasPtr->hotPtr = itemPtr; + canvasPtr->hotPrevPtr = prevPtr; + return itemPtr; + } + } + + searchPtr->tag = uid = Tk_GetUid(tag); + if (uid == allUid) { + + /* + * All items match. + */ + + searchPtr->tag = NULL; + searchPtr->prevPtr = NULL; + searchPtr->currentPtr = canvasPtr->firstItemPtr; + return canvasPtr->firstItemPtr; + } + + /* + * None of the above. Search for an item with a matching tag. + */ + + for (prevPtr = NULL, itemPtr = canvasPtr->firstItemPtr; itemPtr != NULL; + prevPtr = itemPtr, itemPtr = itemPtr->nextPtr) { + for (tagPtr = itemPtr->tagPtr, count = itemPtr->numTags; + count > 0; tagPtr++, count--) { + if (*tagPtr == uid) { + searchPtr->prevPtr = prevPtr; + searchPtr->currentPtr = itemPtr; + return itemPtr; + } + } + } + searchPtr->prevPtr = prevPtr; + searchPtr->searchOver = 1; + return NULL; +} + +/* + *-------------------------------------------------------------- + * + * NextItem -- + * + * This procedure returns successive items that match a given + * tag; it should be called only after StartTagSearch has been + * used to begin a search. + * + * Results: + * The return value is a pointer to the next item that matches + * the tag specified to StartTagSearch, or NULL if no such + * item exists. *SearchPtr is updated so that the next call + * to this procedure will return the next item. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static Tk_Item * +NextItem(searchPtr) + TagSearch *searchPtr; /* Record describing search in + * progress. */ +{ + Tk_Item *itemPtr, *prevPtr; + int count; + Tk_Uid uid; + Tk_Uid *tagPtr; + + /* + * Find next item in list (this may not actually be a suitable + * one to return), and return if there are no items left. + */ + + prevPtr = searchPtr->prevPtr; + if (prevPtr == NULL) { + itemPtr = searchPtr->canvasPtr->firstItemPtr; + } else { + itemPtr = prevPtr->nextPtr; + } + if ((itemPtr == NULL) || (searchPtr->searchOver)) { + searchPtr->searchOver = 1; + return NULL; + } + if (itemPtr != searchPtr->currentPtr) { + /* + * The structure of the list has changed. Probably the + * previously-returned item was removed from the list. + * In this case, don't advance prevPtr; just return + * its new successor (i.e. do nothing here). + */ + } else { + prevPtr = itemPtr; + itemPtr = prevPtr->nextPtr; + } + + /* + * Handle special case of "all" search by returning next item. + */ + + uid = searchPtr->tag; + if (uid == NULL) { + searchPtr->prevPtr = prevPtr; + searchPtr->currentPtr = itemPtr; + return itemPtr; + } + + /* + * Look for an item with a particular tag. + */ + + for ( ; itemPtr != NULL; prevPtr = itemPtr, itemPtr = itemPtr->nextPtr) { + for (tagPtr = itemPtr->tagPtr, count = itemPtr->numTags; + count > 0; tagPtr++, count--) { + if (*tagPtr == uid) { + searchPtr->prevPtr = prevPtr; + searchPtr->currentPtr = itemPtr; + return itemPtr; + } + } + } + searchPtr->prevPtr = prevPtr; + searchPtr->searchOver = 1; + return NULL; +} + +/* + *-------------------------------------------------------------- + * + * DoItem -- + * + * This is a utility procedure called by FindItems. It + * either adds itemPtr's id to the result forming in interp, + * or it adds a new tag to itemPtr, depending on the value + * of tag. + * + * Results: + * None. + * + * Side effects: + * If tag is NULL then itemPtr's id is added as a list element + * to interp->result; otherwise tag is added to itemPtr's + * list of tags. + * + *-------------------------------------------------------------- + */ + +static void +DoItem(interp, itemPtr, tag) + Tcl_Interp *interp; /* Interpreter in which to (possibly) + * record item id. */ + Tk_Item *itemPtr; /* Item to (possibly) modify. */ + Tk_Uid tag; /* Tag to add to those already + * present for item, or NULL. */ +{ + Tk_Uid *tagPtr; + int count; + + /* + * Handle the "add-to-result" case and return, if appropriate. + */ + + if (tag == NULL) { + char msg[30]; + sprintf(msg, "%d", itemPtr->id); + Tcl_AppendElement(interp, msg); + return; + } + + for (tagPtr = itemPtr->tagPtr, count = itemPtr->numTags; + count > 0; tagPtr++, count--) { + if (tag == *tagPtr) { + return; + } + } + + /* + * Grow the tag space if there's no more room left in the current + * block. + */ + + if (itemPtr->tagSpace == itemPtr->numTags) { + Tk_Uid *newTagPtr; + + itemPtr->tagSpace += 5; + newTagPtr = (Tk_Uid *) ckalloc((unsigned) + (itemPtr->tagSpace * sizeof(Tk_Uid))); + memcpy((VOID *) newTagPtr, (VOID *) itemPtr->tagPtr, + (itemPtr->numTags * sizeof(Tk_Uid))); + if (itemPtr->tagPtr != itemPtr->staticTagSpace) { + ckfree((char *) itemPtr->tagPtr); + } + itemPtr->tagPtr = newTagPtr; + tagPtr = &itemPtr->tagPtr[itemPtr->numTags]; + } + + /* + * Add in the new tag. + */ + + *tagPtr = tag; + itemPtr->numTags++; +} + +/* + *-------------------------------------------------------------- + * + * FindItems -- + * + * This procedure does all the work of implementing the + * "find" and "addtag" options of the canvas widget command, + * which locate items that have certain features (location, + * tags, position in display list, etc.). + * + * Results: + * A standard Tcl return value. If newTag is NULL, then a + * list of ids from all the items that match argc/argv is + * returned in interp->result. If newTag is NULL, then + * the normal interp->result is an empty string. If an error + * occurs, then interp->result will hold an error message. + * + * Side effects: + * If newTag is non-NULL, then all the items that match the + * information in argc/argv have that tag added to their + * lists of tags. + * + *-------------------------------------------------------------- + */ + +static int +FindItems(interp, canvasPtr, argc, argv, newTag, cmdName, option) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + TkCanvas *canvasPtr; /* Canvas whose items are to be + * searched. */ + int argc; /* Number of entries in argv. Must be + * greater than zero. */ + char **argv; /* Arguments that describe what items + * to search for (see user doc on + * "find" and "addtag" options). */ + char *newTag; /* If non-NULL, gives new tag to set + * on all found items; if NULL, then + * ids of found items are returned + * in interp->result. */ + char *cmdName; /* Name of original Tcl command, for + * use in error messages. */ + char *option; /* For error messages: gives option + * from Tcl command and other stuff + * up to what's in argc/argv. */ +{ + int c; + size_t length; + TagSearch search; + Tk_Item *itemPtr; + Tk_Uid uid; + + if (newTag != NULL) { + uid = Tk_GetUid(newTag); + } else { + uid = NULL; + } + c = argv[0][0]; + length = strlen(argv[0]); + if ((c == 'a') && (strncmp(argv[0], "above", length) == 0) + && (length >= 2)) { + Tk_Item *lastPtr = NULL; + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + cmdName, option, " above tagOrId", (char *) NULL); + return TCL_ERROR; + } + for (itemPtr = StartTagSearch(canvasPtr, argv[1], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + lastPtr = itemPtr; + } + if ((lastPtr != NULL) && (lastPtr->nextPtr != NULL)) { + DoItem(interp, lastPtr->nextPtr, uid); + } + } else if ((c == 'a') && (strncmp(argv[0], "all", length) == 0) + && (length >= 2)) { + if (argc != 1) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + cmdName, option, " all", (char *) NULL); + return TCL_ERROR; + } + + for (itemPtr = canvasPtr->firstItemPtr; itemPtr != NULL; + itemPtr = itemPtr->nextPtr) { + DoItem(interp, itemPtr, uid); + } + } else if ((c == 'b') && (strncmp(argv[0], "below", length) == 0)) { + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + cmdName, option, " below tagOrId", (char *) NULL); + return TCL_ERROR; + } + (void) StartTagSearch(canvasPtr, argv[1], &search); + if (search.prevPtr != NULL) { + DoItem(interp, search.prevPtr, uid); + } + } else if ((c == 'c') && (strncmp(argv[0], "closest", length) == 0)) { + double closestDist; + Tk_Item *startPtr, *closestPtr; + double coords[2], halo; + int x1, y1, x2, y2; + + if ((argc < 3) || (argc > 5)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + cmdName, option, " closest x y ?halo? ?start?", + (char *) NULL); + return TCL_ERROR; + } + if ((Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, argv[1], + &coords[0]) != TCL_OK) || (Tk_CanvasGetCoord(interp, + (Tk_Canvas) canvasPtr, argv[2], &coords[1]) != TCL_OK)) { + return TCL_ERROR; + } + if (argc > 3) { + if (Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, argv[3], + &halo) != TCL_OK) { + return TCL_ERROR; + } + if (halo < 0.0) { + Tcl_AppendResult(interp, "can't have negative halo value \"", + argv[3], "\"", (char *) NULL); + return TCL_ERROR; + } + } else { + halo = 0.0; + } + + /* + * Find the item at which to start the search. + */ + + startPtr = canvasPtr->firstItemPtr; + if (argc == 5) { + itemPtr = StartTagSearch(canvasPtr, argv[4], &search); + if (itemPtr != NULL) { + startPtr = itemPtr; + } + } + + /* + * The code below is optimized so that it can eliminate most + * items without having to call their item-specific procedures. + * This is done by keeping a bounding box (x1, y1, x2, y2) that + * an item's bbox must overlap if the item is to have any + * chance of being closer than the closest so far. + */ + + itemPtr = startPtr; + if (itemPtr == NULL) { + return TCL_OK; + } + closestDist = (*itemPtr->typePtr->pointProc)((Tk_Canvas) canvasPtr, + itemPtr, coords) - halo; + if (closestDist < 0.0) { + closestDist = 0.0; + } + while (1) { + double newDist; + + /* + * Update the bounding box using itemPtr, which is the + * new closest item. + */ + + x1 = (int) (coords[0] - closestDist - halo - 1); + y1 = (int) (coords[1] - closestDist - halo - 1); + x2 = (int) (coords[0] + closestDist + halo + 1); + y2 = (int) (coords[1] + closestDist + halo + 1); + closestPtr = itemPtr; + + /* + * Search for an item that beats the current closest one. + * Work circularly through the canvas's item list until + * getting back to the starting item. + */ + + while (1) { + itemPtr = itemPtr->nextPtr; + if (itemPtr == NULL) { + itemPtr = canvasPtr->firstItemPtr; + } + if (itemPtr == startPtr) { + DoItem(interp, closestPtr, uid); + return TCL_OK; + } + if ((itemPtr->x1 >= x2) || (itemPtr->x2 <= x1) + || (itemPtr->y1 >= y2) || (itemPtr->y2 <= y1)) { + continue; + } + newDist = (*itemPtr->typePtr->pointProc)((Tk_Canvas) canvasPtr, + itemPtr, coords) - halo; + if (newDist < 0.0) { + newDist = 0.0; + } + if (newDist <= closestDist) { + closestDist = newDist; + break; + } + } + } + } else if ((c == 'e') && (strncmp(argv[0], "enclosed", length) == 0)) { + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + cmdName, option, " enclosed x1 y1 x2 y2", (char *) NULL); + return TCL_ERROR; + } + return FindArea(interp, canvasPtr, argv+1, uid, 1); + } else if ((c == 'o') && (strncmp(argv[0], "overlapping", length) == 0)) { + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + cmdName, option, " overlapping x1 y1 x2 y2", + (char *) NULL); + return TCL_ERROR; + } + return FindArea(interp, canvasPtr, argv+1, uid, 0); + } else if ((c == 'w') && (strncmp(argv[0], "withtag", length) == 0)) { + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + cmdName, option, " withtag tagOrId", (char *) NULL); + return TCL_ERROR; + } + for (itemPtr = StartTagSearch(canvasPtr, argv[1], &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + DoItem(interp, itemPtr, uid); + } + } else { + Tcl_AppendResult(interp, "bad search command \"", argv[0], + "\": must be above, all, below, closest, enclosed, ", + "overlapping, or withtag", (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * FindArea -- + * + * This procedure implements area searches for the "find" + * and "addtag" options. + * + * Results: + * A standard Tcl return value. If newTag is NULL, then a + * list of ids from all the items overlapping or enclosed + * by the rectangle given by argc is returned in interp->result. + * If newTag is NULL, then the normal interp->result is an + * empty string. If an error occurs, then interp->result will + * hold an error message. + * + * Side effects: + * If uid is non-NULL, then all the items overlapping + * or enclosed by the area in argv have that tag added to + * their lists of tags. + * + *-------------------------------------------------------------- + */ + +static int +FindArea(interp, canvasPtr, argv, uid, enclosed) + Tcl_Interp *interp; /* Interpreter for error reporting + * and result storing. */ + TkCanvas *canvasPtr; /* Canvas whose items are to be + * searched. */ + char **argv; /* Array of four arguments that + * give the coordinates of the + * rectangular area to search. */ + Tk_Uid uid; /* If non-NULL, gives new tag to set + * on all found items; if NULL, then + * ids of found items are returned + * in interp->result. */ + int enclosed; /* 0 means overlapping or enclosed + * items are OK, 1 means only enclosed + * items are OK. */ +{ + double rect[4], tmp; + int x1, y1, x2, y2; + Tk_Item *itemPtr; + + if ((Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, argv[0], + &rect[0]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, argv[1], + &rect[1]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, argv[2], + &rect[2]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, (Tk_Canvas) canvasPtr, argv[3], + &rect[3]) != TCL_OK)) { + return TCL_ERROR; + } + if (rect[0] > rect[2]) { + tmp = rect[0]; rect[0] = rect[2]; rect[2] = tmp; + } + if (rect[1] > rect[3]) { + tmp = rect[1]; rect[1] = rect[3]; rect[3] = tmp; + } + + /* + * Use an integer bounding box for a quick test, to avoid + * calling item-specific code except for items that are close. + */ + + x1 = (int) (rect[0]-1.0); + y1 = (int) (rect[1]-1.0); + x2 = (int) (rect[2]+1.0); + y2 = (int) (rect[3]+1.0); + for (itemPtr = canvasPtr->firstItemPtr; itemPtr != NULL; + itemPtr = itemPtr->nextPtr) { + if ((itemPtr->x1 >= x2) || (itemPtr->x2 <= x1) + || (itemPtr->y1 >= y2) || (itemPtr->y2 <= y1)) { + continue; + } + if ((*itemPtr->typePtr->areaProc)((Tk_Canvas) canvasPtr, itemPtr, rect) + >= enclosed) { + DoItem(interp, itemPtr, uid); + } + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * RelinkItems -- + * + * Move one or more items to a different place in the + * display order for a canvas. + * + * Results: + * None. + * + * Side effects: + * The items identified by "tag" are moved so that they + * are all together in the display list and immediately + * after prevPtr. The order of the moved items relative + * to each other is not changed. + * + *-------------------------------------------------------------- + */ + +static void +RelinkItems(canvasPtr, tag, prevPtr) + TkCanvas *canvasPtr; /* Canvas to be modified. */ + char *tag; /* Tag identifying items to be moved + * in the redisplay list. */ + Tk_Item *prevPtr; /* Reposition the items so that they + * go just after this item (NULL means + * put at beginning of list). */ +{ + Tk_Item *itemPtr; + TagSearch search; + Tk_Item *firstMovePtr, *lastMovePtr; + + /* + * Find all of the items to be moved and remove them from + * the list, making an auxiliary list running from firstMovePtr + * to lastMovePtr. Record their areas for redisplay. + */ + + firstMovePtr = lastMovePtr = NULL; + for (itemPtr = StartTagSearch(canvasPtr, tag, &search); + itemPtr != NULL; itemPtr = NextItem(&search)) { + if (itemPtr == prevPtr) { + /* + * Item after which insertion is to occur is being + * moved! Switch to insert after its predecessor. + */ + + prevPtr = search.prevPtr; + } + if (search.prevPtr == NULL) { + canvasPtr->firstItemPtr = itemPtr->nextPtr; + } else { + search.prevPtr->nextPtr = itemPtr->nextPtr; + } + if (canvasPtr->lastItemPtr == itemPtr) { + canvasPtr->lastItemPtr = search.prevPtr; + } + if (firstMovePtr == NULL) { + firstMovePtr = itemPtr; + } else { + lastMovePtr->nextPtr = itemPtr; + } + lastMovePtr = itemPtr; + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, itemPtr->x1, itemPtr->y1, + itemPtr->x2, itemPtr->y2); + canvasPtr->flags |= REPICK_NEEDED; + } + + /* + * Insert the list of to-be-moved items back into the canvas's + * at the desired position. + */ + + if (firstMovePtr == NULL) { + return; + } + if (prevPtr == NULL) { + lastMovePtr->nextPtr = canvasPtr->firstItemPtr; + canvasPtr->firstItemPtr = firstMovePtr; + } else { + lastMovePtr->nextPtr = prevPtr->nextPtr; + prevPtr->nextPtr = firstMovePtr; + } + if (canvasPtr->lastItemPtr == prevPtr) { + canvasPtr->lastItemPtr = lastMovePtr; + } +} + +/* + *-------------------------------------------------------------- + * + * CanvasBindProc -- + * + * This procedure is invoked by the Tk dispatcher to handle + * events associated with bindings on items. + * + * Results: + * None. + * + * Side effects: + * Depends on the command invoked as part of the binding + * (if there was any). + * + *-------------------------------------------------------------- + */ + +static void +CanvasBindProc(clientData, eventPtr) + ClientData clientData; /* Pointer to canvas structure. */ + XEvent *eventPtr; /* Pointer to X event that just + * happened. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) clientData; + + Tcl_Preserve((ClientData) canvasPtr); + + /* + * This code below keeps track of the current modifier state in + * canvasPtr>state. This information is used to defer repicks of + * the current item while buttons are down. + */ + + if ((eventPtr->type == ButtonPress) || (eventPtr->type == ButtonRelease)) { + int mask; + + switch (eventPtr->xbutton.button) { + case Button1: + mask = Button1Mask; + break; + case Button2: + mask = Button2Mask; + break; + case Button3: + mask = Button3Mask; + break; + case Button4: + mask = Button4Mask; + break; + case Button5: + mask = Button5Mask; + break; + default: + mask = 0; + break; + } + + /* + * For button press events, repick the current item using the + * button state before the event, then process the event. For + * button release events, first process the event, then repick + * the current item using the button state *after* the event + * (the button has logically gone up before we change the + * current item). + */ + + if (eventPtr->type == ButtonPress) { + /* + * On a button press, first repick the current item using + * the button state before the event, the process the event. + */ + + canvasPtr->state = eventPtr->xbutton.state; + PickCurrentItem(canvasPtr, eventPtr); + canvasPtr->state ^= mask; + CanvasDoEvent(canvasPtr, eventPtr); + } else { + /* + * Button release: first process the event, with the button + * still considered to be down. Then repick the current + * item under the assumption that the button is no longer down. + */ + + canvasPtr->state = eventPtr->xbutton.state; + CanvasDoEvent(canvasPtr, eventPtr); + eventPtr->xbutton.state ^= mask; + canvasPtr->state = eventPtr->xbutton.state; + PickCurrentItem(canvasPtr, eventPtr); + eventPtr->xbutton.state ^= mask; + } + goto done; + } else if ((eventPtr->type == EnterNotify) + || (eventPtr->type == LeaveNotify)) { + canvasPtr->state = eventPtr->xcrossing.state; + PickCurrentItem(canvasPtr, eventPtr); + goto done; + } else if (eventPtr->type == MotionNotify) { + canvasPtr->state = eventPtr->xmotion.state; + PickCurrentItem(canvasPtr, eventPtr); + } + CanvasDoEvent(canvasPtr, eventPtr); + + done: + Tcl_Release((ClientData) canvasPtr); +} + +/* + *-------------------------------------------------------------- + * + * PickCurrentItem -- + * + * Find the topmost item in a canvas that contains a given + * location and mark the the current item. If the current + * item has changed, generate a fake exit event on the old + * current item and a fake enter event on the new current + * item. + * + * Results: + * None. + * + * Side effects: + * The current item for canvasPtr may change. If it does, + * then the commands associated with item entry and exit + * could do just about anything. A binding script could + * delete the canvas, so callers should protect themselves + * with Tcl_Preserve and Tcl_Release. + * + *-------------------------------------------------------------- + */ + +static void +PickCurrentItem(canvasPtr, eventPtr) + TkCanvas *canvasPtr; /* Canvas widget in which to select + * current item. */ + XEvent *eventPtr; /* Event describing location of + * mouse cursor. Must be EnterWindow, + * LeaveWindow, ButtonRelease, or + * MotionNotify. */ +{ + double coords[2]; + int buttonDown; + + /* + * Check whether or not a button is down. If so, we'll log entry + * and exit into and out of the current item, but not entry into + * any other item. This implements a form of grabbing equivalent + * to what the X server does for windows. + */ + + buttonDown = canvasPtr->state + & (Button1Mask|Button2Mask|Button3Mask|Button4Mask|Button5Mask); + if (!buttonDown) { + canvasPtr->flags &= ~LEFT_GRABBED_ITEM; + } + + /* + * Save information about this event in the canvas. The event in + * the canvas is used for two purposes: + * + * 1. Event bindings: if the current item changes, fake events are + * generated to allow item-enter and item-leave bindings to trigger. + * 2. Reselection: if the current item gets deleted, can use the + * saved event to find a new current item. + * Translate MotionNotify events into EnterNotify events, since that's + * what gets reported to item handlers. + */ + + if (eventPtr != &canvasPtr->pickEvent) { + if ((eventPtr->type == MotionNotify) + || (eventPtr->type == ButtonRelease)) { + canvasPtr->pickEvent.xcrossing.type = EnterNotify; + canvasPtr->pickEvent.xcrossing.serial = eventPtr->xmotion.serial; + canvasPtr->pickEvent.xcrossing.send_event + = eventPtr->xmotion.send_event; + canvasPtr->pickEvent.xcrossing.display = eventPtr->xmotion.display; + canvasPtr->pickEvent.xcrossing.window = eventPtr->xmotion.window; + canvasPtr->pickEvent.xcrossing.root = eventPtr->xmotion.root; + canvasPtr->pickEvent.xcrossing.subwindow = None; + canvasPtr->pickEvent.xcrossing.time = eventPtr->xmotion.time; + canvasPtr->pickEvent.xcrossing.x = eventPtr->xmotion.x; + canvasPtr->pickEvent.xcrossing.y = eventPtr->xmotion.y; + canvasPtr->pickEvent.xcrossing.x_root = eventPtr->xmotion.x_root; + canvasPtr->pickEvent.xcrossing.y_root = eventPtr->xmotion.y_root; + canvasPtr->pickEvent.xcrossing.mode = NotifyNormal; + canvasPtr->pickEvent.xcrossing.detail = NotifyNonlinear; + canvasPtr->pickEvent.xcrossing.same_screen + = eventPtr->xmotion.same_screen; + canvasPtr->pickEvent.xcrossing.focus = False; + canvasPtr->pickEvent.xcrossing.state = eventPtr->xmotion.state; + } else { + canvasPtr->pickEvent = *eventPtr; + } + } + + /* + * If this is a recursive call (there's already a partially completed + * call pending on the stack; it's in the middle of processing a + * Leave event handler for the old current item) then just return; + * the pending call will do everything that's needed. + */ + + if (canvasPtr->flags & REPICK_IN_PROGRESS) { + return; + } + + /* + * A LeaveNotify event automatically means that there's no current + * object, so the check for closest item can be skipped. + */ + + coords[0] = canvasPtr->pickEvent.xcrossing.x + canvasPtr->xOrigin; + coords[1] = canvasPtr->pickEvent.xcrossing.y + canvasPtr->yOrigin; + if (canvasPtr->pickEvent.type != LeaveNotify) { + canvasPtr->newCurrentPtr = CanvasFindClosest(canvasPtr, coords); + } else { + canvasPtr->newCurrentPtr = NULL; + } + + if ((canvasPtr->newCurrentPtr == canvasPtr->currentItemPtr) + && !(canvasPtr->flags & LEFT_GRABBED_ITEM)) { + /* + * Nothing to do: the current item hasn't changed. + */ + + return; + } + + /* + * Simulate a LeaveNotify event on the previous current item and + * an EnterNotify event on the new current item. Remove the "current" + * tag from the previous current item and place it on the new current + * item. + */ + + if ((canvasPtr->newCurrentPtr != canvasPtr->currentItemPtr) + && (canvasPtr->currentItemPtr != NULL) + && !(canvasPtr->flags & LEFT_GRABBED_ITEM)) { + XEvent event; + Tk_Item *itemPtr = canvasPtr->currentItemPtr; + int i; + + event = canvasPtr->pickEvent; + event.type = LeaveNotify; + + /* + * If the event's detail happens to be NotifyInferior the + * binding mechanism will discard the event. To be consistent, + * always use NotifyAncestor. + */ + + event.xcrossing.detail = NotifyAncestor; + canvasPtr->flags |= REPICK_IN_PROGRESS; + CanvasDoEvent(canvasPtr, &event); + canvasPtr->flags &= ~REPICK_IN_PROGRESS; + + /* + * The check below is needed because there could be an event + * handler for <LeaveNotify> that deletes the current item. + */ + + if ((itemPtr == canvasPtr->currentItemPtr) && !buttonDown) { + for (i = itemPtr->numTags-1; i >= 0; i--) { + if (itemPtr->tagPtr[i] == currentUid) { + itemPtr->tagPtr[i] = itemPtr->tagPtr[itemPtr->numTags-1]; + itemPtr->numTags--; + break; + } + } + } + + /* + * Note: during CanvasDoEvent above, it's possible that + * canvasPtr->newCurrentPtr got reset to NULL because the + * item was deleted. + */ + } + if ((canvasPtr->newCurrentPtr != canvasPtr->currentItemPtr) && buttonDown) { + canvasPtr->flags |= LEFT_GRABBED_ITEM; + return; + } + + /* + * Special note: it's possible that canvasPtr->newCurrentPtr == + * canvasPtr->currentItemPtr here. This can happen, for example, + * if LEFT_GRABBED_ITEM was set. + */ + + canvasPtr->flags &= ~LEFT_GRABBED_ITEM; + canvasPtr->currentItemPtr = canvasPtr->newCurrentPtr; + if (canvasPtr->currentItemPtr != NULL) { + XEvent event; + + DoItem((Tcl_Interp *) NULL, canvasPtr->currentItemPtr, currentUid); + event = canvasPtr->pickEvent; + event.type = EnterNotify; + event.xcrossing.detail = NotifyAncestor; + CanvasDoEvent(canvasPtr, &event); + } +} + +/* + *---------------------------------------------------------------------- + * + * CanvasFindClosest -- + * + * Given x and y coordinates, find the topmost canvas item that + * is "close" to the coordinates. + * + * Results: + * The return value is a pointer to the topmost item that is + * close to (x,y), or NULL if no item is close. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static Tk_Item * +CanvasFindClosest(canvasPtr, coords) + TkCanvas *canvasPtr; /* Canvas widget to search. */ + double coords[2]; /* Desired x,y position in canvas, + * not screen, coordinates.) */ +{ + Tk_Item *itemPtr; + Tk_Item *bestPtr; + int x1, y1, x2, y2; + + x1 = (int) (coords[0] - canvasPtr->closeEnough); + y1 = (int) (coords[1] - canvasPtr->closeEnough); + x2 = (int) (coords[0] + canvasPtr->closeEnough); + y2 = (int) (coords[1] + canvasPtr->closeEnough); + + bestPtr = NULL; + for (itemPtr = canvasPtr->firstItemPtr; itemPtr != NULL; + itemPtr = itemPtr->nextPtr) { + if ((itemPtr->x1 > x2) || (itemPtr->x2 < x1) + || (itemPtr->y1 > y2) || (itemPtr->y2 < y1)) { + continue; + } + if ((*itemPtr->typePtr->pointProc)((Tk_Canvas) canvasPtr, + itemPtr, coords) <= canvasPtr->closeEnough) { + bestPtr = itemPtr; + } + } + return bestPtr; +} + +/* + *-------------------------------------------------------------- + * + * CanvasDoEvent -- + * + * This procedure is called to invoke binding processing + * for a new event that is associated with the current item + * for a canvas. + * + * Results: + * None. + * + * Side effects: + * Depends on the bindings for the canvas. A binding script + * could delete the canvas, so callers should protect themselves + * with Tcl_Preserve and Tcl_Release. + * + *-------------------------------------------------------------- + */ + +static void +CanvasDoEvent(canvasPtr, eventPtr) + TkCanvas *canvasPtr; /* Canvas widget in which event + * occurred. */ + XEvent *eventPtr; /* Real or simulated X event that + * is to be processed. */ +{ +#define NUM_STATIC 3 + ClientData staticObjects[NUM_STATIC]; + ClientData *objectPtr; + int numObjects, i; + Tk_Item *itemPtr; + + if (canvasPtr->bindingTable == NULL) { + return; + } + + itemPtr = canvasPtr->currentItemPtr; + if ((eventPtr->type == KeyPress) || (eventPtr->type == KeyRelease)) { + itemPtr = canvasPtr->textInfo.focusItemPtr; + } + if (itemPtr == NULL) { + return; + } + + /* + * Set up an array with all the relevant objects for processing + * this event. The relevant objects are (a) the event's item, + * (b) the tags associated with the event's item, and (c) the + * tag "all". If there are a lot of tags then malloc an array + * to hold all of the objects. + */ + + numObjects = itemPtr->numTags + 2; + if (numObjects <= NUM_STATIC) { + objectPtr = staticObjects; + } else { + objectPtr = (ClientData *) ckalloc((unsigned) + (numObjects * sizeof(ClientData))); + } + objectPtr[0] = (ClientData) allUid; + for (i = itemPtr->numTags-1; i >= 0; i--) { + objectPtr[i+1] = (ClientData) itemPtr->tagPtr[i]; + } + objectPtr[itemPtr->numTags+1] = (ClientData) itemPtr; + + /* + * Invoke the binding system, then free up the object array if + * it was malloc-ed. + */ + + if (canvasPtr->tkwin != NULL) { + Tk_BindEvent(canvasPtr->bindingTable, eventPtr, canvasPtr->tkwin, + numObjects, objectPtr); + } + if (objectPtr != staticObjects) { + ckfree((char *) objectPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * CanvasBlinkProc -- + * + * This procedure is called as a timer handler to blink the + * insertion cursor off and on. + * + * Results: + * None. + * + * Side effects: + * The cursor gets turned on or off, redisplay gets invoked, + * and this procedure reschedules itself. + * + *---------------------------------------------------------------------- + */ + +static void +CanvasBlinkProc(clientData) + ClientData clientData; /* Pointer to record describing entry. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) clientData; + + if (!canvasPtr->textInfo.gotFocus || (canvasPtr->insertOffTime == 0)) { + return; + } + if (canvasPtr->textInfo.cursorOn) { + canvasPtr->textInfo.cursorOn = 0; + canvasPtr->insertBlinkHandler = Tcl_CreateTimerHandler( + canvasPtr->insertOffTime, CanvasBlinkProc, + (ClientData) canvasPtr); + } else { + canvasPtr->textInfo.cursorOn = 1; + canvasPtr->insertBlinkHandler = Tcl_CreateTimerHandler( + canvasPtr->insertOnTime, CanvasBlinkProc, + (ClientData) canvasPtr); + } + if (canvasPtr->textInfo.focusItemPtr != NULL) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + canvasPtr->textInfo.focusItemPtr->x1, + canvasPtr->textInfo.focusItemPtr->y1, + canvasPtr->textInfo.focusItemPtr->x2, + canvasPtr->textInfo.focusItemPtr->y2); + } +} + +/* + *---------------------------------------------------------------------- + * + * CanvasFocusProc -- + * + * This procedure is called whenever a canvas gets or loses the + * input focus. It's also called whenever the window is + * reconfigured while it has the focus. + * + * Results: + * None. + * + * Side effects: + * The cursor gets turned on or off. + * + *---------------------------------------------------------------------- + */ + +static void +CanvasFocusProc(canvasPtr, gotFocus) + TkCanvas *canvasPtr; /* Canvas that just got or lost focus. */ + int gotFocus; /* 1 means window is getting focus, 0 means + * it's losing it. */ +{ + Tcl_DeleteTimerHandler(canvasPtr->insertBlinkHandler); + if (gotFocus) { + canvasPtr->textInfo.gotFocus = 1; + canvasPtr->textInfo.cursorOn = 1; + if (canvasPtr->insertOffTime != 0) { + canvasPtr->insertBlinkHandler = Tcl_CreateTimerHandler( + canvasPtr->insertOffTime, CanvasBlinkProc, + (ClientData) canvasPtr); + } + } else { + canvasPtr->textInfo.gotFocus = 0; + canvasPtr->textInfo.cursorOn = 0; + canvasPtr->insertBlinkHandler = (Tcl_TimerToken) NULL; + } + if (canvasPtr->textInfo.focusItemPtr != NULL) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + canvasPtr->textInfo.focusItemPtr->x1, + canvasPtr->textInfo.focusItemPtr->y1, + canvasPtr->textInfo.focusItemPtr->x2, + canvasPtr->textInfo.focusItemPtr->y2); + } + if (canvasPtr->highlightWidth > 0) { + canvasPtr->flags |= REDRAW_BORDERS; + if (!(canvasPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayCanvas, (ClientData) canvasPtr); + canvasPtr->flags |= REDRAW_PENDING; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * CanvasSelectTo -- + * + * Modify the selection by moving its un-anchored end. This could + * make the selection either larger or smaller. + * + * Results: + * None. + * + * Side effects: + * The selection changes. + * + *---------------------------------------------------------------------- + */ + +static void +CanvasSelectTo(canvasPtr, itemPtr, index) + TkCanvas *canvasPtr; /* Information about widget. */ + Tk_Item *itemPtr; /* Item that is to hold selection. */ + int index; /* Index of element that is to become the + * "other" end of the selection. */ +{ + int oldFirst, oldLast; + Tk_Item *oldSelPtr; + + oldFirst = canvasPtr->textInfo.selectFirst; + oldLast = canvasPtr->textInfo.selectLast; + oldSelPtr = canvasPtr->textInfo.selItemPtr; + + /* + * Grab the selection if we don't own it already. + */ + + if (canvasPtr->textInfo.selItemPtr == NULL) { + Tk_OwnSelection(canvasPtr->tkwin, XA_PRIMARY, CanvasLostSelection, + (ClientData) canvasPtr); + } else if (canvasPtr->textInfo.selItemPtr != itemPtr) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + canvasPtr->textInfo.selItemPtr->x1, + canvasPtr->textInfo.selItemPtr->y1, + canvasPtr->textInfo.selItemPtr->x2, + canvasPtr->textInfo.selItemPtr->y2); + } + canvasPtr->textInfo.selItemPtr = itemPtr; + + if (canvasPtr->textInfo.anchorItemPtr != itemPtr) { + canvasPtr->textInfo.anchorItemPtr = itemPtr; + canvasPtr->textInfo.selectAnchor = index; + } + if (canvasPtr->textInfo.selectAnchor <= index) { + canvasPtr->textInfo.selectFirst = canvasPtr->textInfo.selectAnchor; + canvasPtr->textInfo.selectLast = index; + } else { + canvasPtr->textInfo.selectFirst = index; + canvasPtr->textInfo.selectLast = canvasPtr->textInfo.selectAnchor - 1; + } + if ((canvasPtr->textInfo.selectFirst != oldFirst) + || (canvasPtr->textInfo.selectLast != oldLast) + || (itemPtr != oldSelPtr)) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2); + } +} + +/* + *-------------------------------------------------------------- + * + * CanvasFetchSelection -- + * + * This procedure is invoked by Tk to return part or all of + * the selection, when the selection is in a canvas widget. + * This procedure always returns the selection as a STRING. + * + * Results: + * The return value is the number of non-NULL bytes stored + * at buffer. Buffer is filled (or partially filled) with a + * NULL-terminated string containing part or all of the selection, + * as given by offset and maxBytes. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +CanvasFetchSelection(clientData, offset, buffer, maxBytes) + ClientData clientData; /* Information about canvas widget. */ + int offset; /* Offset within selection of first + * character to be returned. */ + char *buffer; /* Location in which to place + * selection. */ + int maxBytes; /* Maximum number of bytes to place + * at buffer, not including terminating + * NULL character. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) clientData; + + if (canvasPtr->textInfo.selItemPtr == NULL) { + return -1; + } + if (canvasPtr->textInfo.selItemPtr->typePtr->selectionProc == NULL) { + return -1; + } + return (*canvasPtr->textInfo.selItemPtr->typePtr->selectionProc)( + (Tk_Canvas) canvasPtr, canvasPtr->textInfo.selItemPtr, offset, + buffer, maxBytes); +} + +/* + *---------------------------------------------------------------------- + * + * CanvasLostSelection -- + * + * This procedure is called back by Tk when the selection is + * grabbed away from a canvas widget. + * + * Results: + * None. + * + * Side effects: + * The existing selection is unhighlighted, and the window is + * marked as not containing a selection. + * + *---------------------------------------------------------------------- + */ + +static void +CanvasLostSelection(clientData) + ClientData clientData; /* Information about entry widget. */ +{ + TkCanvas *canvasPtr = (TkCanvas *) clientData; + + if (canvasPtr->textInfo.selItemPtr != NULL) { + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + canvasPtr->textInfo.selItemPtr->x1, + canvasPtr->textInfo.selItemPtr->y1, + canvasPtr->textInfo.selItemPtr->x2, + canvasPtr->textInfo.selItemPtr->y2); + } + canvasPtr->textInfo.selItemPtr = NULL; +} + +/* + *-------------------------------------------------------------- + * + * GridAlign -- + * + * Given a coordinate and a grid spacing, this procedure + * computes the location of the nearest grid line to the + * coordinate. + * + * Results: + * The return value is the location of the grid line nearest + * to coord. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static double +GridAlign(coord, spacing) + double coord; /* Coordinate to grid-align. */ + double spacing; /* Spacing between grid lines. If <= 0 + * then no alignment is done. */ +{ + if (spacing <= 0.0) { + return coord; + } + if (coord < 0) { + return -((int) ((-coord)/spacing + 0.5)) * spacing; + } + return ((int) (coord/spacing + 0.5)) * spacing; +} + +/* + *---------------------------------------------------------------------- + * + * PrintScrollFractions -- + * + * Given the range that's visible in the window and the "100% + * range" for what's in the canvas, print a string containing + * the scroll fractions. This procedure is used for both x + * and y scrolling. + * + * Results: + * The memory pointed to by string is modified to hold + * two real numbers containing the scroll fractions (between + * 0 and 1) corresponding to the other arguments. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +PrintScrollFractions(screen1, screen2, object1, object2, string) + int screen1; /* Lowest coordinate visible in the window. */ + int screen2; /* Highest coordinate visible in the window. */ + int object1; /* Lowest coordinate in the object. */ + int object2; /* Highest coordinate in the object. */ + char *string; /* Two real numbers get printed here. Must + * have enough storage for two %g + * conversions. */ +{ + double range, f1, f2; + + range = object2 - object1; + if (range <= 0) { + f1 = 0; + f2 = 1.0; + } else { + f1 = (screen1 - object1)/range; + if (f1 < 0) { + f1 = 0.0; + } + f2 = (screen2 - object1)/range; + if (f2 > 1.0) { + f2 = 1.0; + } + if (f2 < f1) { + f2 = f1; + } + } + sprintf(string, "%g %g", f1, f2); +} + +/* + *-------------------------------------------------------------- + * + * CanvasUpdateScrollbars -- + * + * This procedure is invoked whenever a canvas has changed in + * a way that requires scrollbars to be redisplayed (e.g. the + * view in the canvas has changed). + * + * Results: + * None. + * + * Side effects: + * If there are scrollbars associated with the canvas, then + * their scrolling commands are invoked to cause them to + * redisplay. If errors occur, additional Tcl commands may + * be invoked to process the errors. + * + *-------------------------------------------------------------- + */ + +static void +CanvasUpdateScrollbars(canvasPtr) + TkCanvas *canvasPtr; /* Information about canvas. */ +{ + int result; + char buffer[200]; + Tcl_Interp *interp; + int xOrigin, yOrigin, inset, width, height, scrollX1, scrollX2, + scrollY1, scrollY2; + char *xScrollCmd, *yScrollCmd; + + /* + * Save all the relevant values from the canvasPtr, because it might be + * deleted as part of either of the two calls to Tcl_VarEval below. + */ + + interp = canvasPtr->interp; + Tcl_Preserve((ClientData) interp); + xScrollCmd = canvasPtr->xScrollCmd; + if (xScrollCmd != (char *) NULL) { + Tcl_Preserve((ClientData) xScrollCmd); + } + yScrollCmd = canvasPtr->yScrollCmd; + if (yScrollCmd != (char *) NULL) { + Tcl_Preserve((ClientData) yScrollCmd); + } + xOrigin = canvasPtr->xOrigin; + yOrigin = canvasPtr->yOrigin; + inset = canvasPtr->inset; + width = Tk_Width(canvasPtr->tkwin); + height = Tk_Height(canvasPtr->tkwin); + scrollX1 = canvasPtr->scrollX1; + scrollX2 = canvasPtr->scrollX2; + scrollY1 = canvasPtr->scrollY1; + scrollY2 = canvasPtr->scrollY2; + canvasPtr->flags &= ~UPDATE_SCROLLBARS; + if (canvasPtr->xScrollCmd != NULL) { + PrintScrollFractions(xOrigin + inset, xOrigin + width - inset, + scrollX1, scrollX2, buffer); + result = Tcl_VarEval(interp, xScrollCmd, " ", buffer, (char *) NULL); + if (result != TCL_OK) { + Tcl_BackgroundError(interp); + } + Tcl_ResetResult(interp); + Tcl_Release((ClientData) xScrollCmd); + } + + if (yScrollCmd != NULL) { + PrintScrollFractions(yOrigin + inset, yOrigin + height - inset, + scrollY1, scrollY2, buffer); + result = Tcl_VarEval(interp, yScrollCmd, " ", buffer, (char *) NULL); + if (result != TCL_OK) { + Tcl_BackgroundError(interp); + } + Tcl_ResetResult(interp); + Tcl_Release((ClientData) yScrollCmd); + } + Tcl_Release((ClientData) interp); +} + +/* + *-------------------------------------------------------------- + * + * CanvasSetOrigin -- + * + * This procedure is invoked to change the mapping between + * canvas coordinates and screen coordinates in the canvas + * window. + * + * Results: + * None. + * + * Side effects: + * The canvas will be redisplayed to reflect the change in + * view. In addition, scrollbars will be updated if there + * are any. + * + *-------------------------------------------------------------- + */ + +static void +CanvasSetOrigin(canvasPtr, xOrigin, yOrigin) + TkCanvas *canvasPtr; /* Information about canvas. */ + int xOrigin; /* New X origin for canvas (canvas x-coord + * corresponding to left edge of canvas + * window). */ + int yOrigin; /* New Y origin for canvas (canvas y-coord + * corresponding to top edge of canvas + * window). */ +{ + int left, right, top, bottom, delta; + + /* + * If scroll increments have been set, round the window origin + * to the nearest multiple of the increments. Remember, the + * origin is the place just inside the borders, not the upper + * left corner. + */ + + if (canvasPtr->xScrollIncrement > 0) { + if (xOrigin >= 0) { + xOrigin += canvasPtr->xScrollIncrement/2; + xOrigin -= (xOrigin + canvasPtr->inset) + % canvasPtr->xScrollIncrement; + } else { + xOrigin = (-xOrigin) + canvasPtr->xScrollIncrement/2; + xOrigin = -(xOrigin - (xOrigin - canvasPtr->inset) + % canvasPtr->xScrollIncrement); + } + } + if (canvasPtr->yScrollIncrement > 0) { + if (yOrigin >= 0) { + yOrigin += canvasPtr->yScrollIncrement/2; + yOrigin -= (yOrigin + canvasPtr->inset) + % canvasPtr->yScrollIncrement; + } else { + yOrigin = (-yOrigin) + canvasPtr->yScrollIncrement/2; + yOrigin = -(yOrigin - (yOrigin - canvasPtr->inset) + % canvasPtr->yScrollIncrement); + } + } + + /* + * Adjust the origin if necessary to keep as much as possible of the + * canvas in the view. The variables left, right, etc. keep track of + * how much extra space there is on each side of the view before it + * will stick out past the scroll region. If one side sticks out past + * the edge of the scroll region, adjust the view to bring that side + * back to the edge of the scrollregion (but don't move it so much that + * the other side sticks out now). If scroll increments are in effect, + * be sure to adjust only by full increments. + */ + + if ((canvasPtr->confine) && (canvasPtr->regionString != NULL)) { + left = xOrigin + canvasPtr->inset - canvasPtr->scrollX1; + right = canvasPtr->scrollX2 + - (xOrigin + Tk_Width(canvasPtr->tkwin) - canvasPtr->inset); + top = yOrigin + canvasPtr->inset - canvasPtr->scrollY1; + bottom = canvasPtr->scrollY2 + - (yOrigin + Tk_Height(canvasPtr->tkwin) - canvasPtr->inset); + if ((left < 0) && (right > 0)) { + delta = (right > -left) ? -left : right; + if (canvasPtr->xScrollIncrement > 0) { + delta -= delta % canvasPtr->xScrollIncrement; + } + xOrigin += delta; + } else if ((right < 0) && (left > 0)) { + delta = (left > -right) ? -right : left; + if (canvasPtr->xScrollIncrement > 0) { + delta -= delta % canvasPtr->xScrollIncrement; + } + xOrigin -= delta; + } + if ((top < 0) && (bottom > 0)) { + delta = (bottom > -top) ? -top : bottom; + if (canvasPtr->yScrollIncrement > 0) { + delta -= delta % canvasPtr->yScrollIncrement; + } + yOrigin += delta; + } else if ((bottom < 0) && (top > 0)) { + delta = (top > -bottom) ? -bottom : top; + if (canvasPtr->yScrollIncrement > 0) { + delta -= delta % canvasPtr->yScrollIncrement; + } + yOrigin -= delta; + } + } + + if ((xOrigin == canvasPtr->xOrigin) && (yOrigin == canvasPtr->yOrigin)) { + return; + } + + /* + * Tricky point: must redisplay not only everything that's visible + * in the window's final configuration, but also everything that was + * visible in the initial configuration. This is needed because some + * item types, like windows, need to know when they move off-screen + * so they can explicitly undisplay themselves. + */ + + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + canvasPtr->xOrigin, canvasPtr->yOrigin, + canvasPtr->xOrigin + Tk_Width(canvasPtr->tkwin), + canvasPtr->yOrigin + Tk_Height(canvasPtr->tkwin)); + canvasPtr->xOrigin = xOrigin; + canvasPtr->yOrigin = yOrigin; + canvasPtr->flags |= UPDATE_SCROLLBARS; + Tk_CanvasEventuallyRedraw((Tk_Canvas) canvasPtr, + canvasPtr->xOrigin, canvasPtr->yOrigin, + canvasPtr->xOrigin + Tk_Width(canvasPtr->tkwin), + canvasPtr->yOrigin + Tk_Height(canvasPtr->tkwin)); +} diff --git a/generic/tkCanvas.h b/generic/tkCanvas.h new file mode 100644 index 0000000..52b3a51 --- /dev/null +++ b/generic/tkCanvas.h @@ -0,0 +1,257 @@ +/* + * tkCanvas.h -- + * + * Declarations shared among all the files that implement + * canvas widgets. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCanvas.h 1.41 96/02/15 18:51:28 + */ + +#ifndef _TKCANVAS +#define _TKCANVAS + +#ifndef _TK +#include "tk.h" +#endif + +/* + * The record below describes a canvas widget. It is made available + * to the item procedures so they can access certain shared fields such + * as the overall displacement and scale factor for the canvas. + */ + +typedef struct TkCanvas { + Tk_Window tkwin; /* Window that embodies the canvas. NULL + * means that the window has been destroyed + * but the data structures haven't yet been + * cleaned up.*/ + Display *display; /* Display containing widget; needed, among + * other things, to release resources after + * tkwin has already gone away. */ + Tcl_Interp *interp; /* Interpreter associated with canvas. */ + Tcl_Command widgetCmd; /* Token for canvas's widget command. */ + Tk_Item *firstItemPtr; /* First in list of all items in canvas, + * or NULL if canvas empty. */ + Tk_Item *lastItemPtr; /* Last in list of all items in canvas, + * or NULL if canvas empty. */ + + /* + * Information used when displaying widget: + */ + + int borderWidth; /* Width of 3-D border around window. */ + Tk_3DBorder bgBorder; /* Used for canvas background. */ + int relief; /* Indicates whether window as a whole is + * raised, sunken, or flat. */ + int highlightWidth; /* Width in pixels of highlight to draw + * around widget when it has the focus. + * <= 0 means don't draw a highlight. */ + XColor *highlightBgColorPtr; + /* Color for drawing traversal highlight + * area when highlight is off. */ + XColor *highlightColorPtr; /* Color for drawing traversal highlight. */ + int inset; /* Total width of all borders, including + * traversal highlight and 3-D border. + * Indicates how much interior stuff must + * be offset from outside edges to leave + * room for borders. */ + GC pixmapGC; /* Used to copy bits from a pixmap to the + * screen and also to clear the pixmap. */ + int width, height; /* Dimensions to request for canvas window, + * specified in pixels. */ + int redrawX1, redrawY1; /* Upper left corner of area to redraw, + * in pixel coordinates. Border pixels + * are included. Only valid if + * REDRAW_PENDING flag is set. */ + int redrawX2, redrawY2; /* Lower right corner of area to redraw, + * in integer canvas coordinates. Border + * pixels will *not* be redrawn. */ + int confine; /* Non-zero means constrain view to keep + * as much of canvas visible as possible. */ + + /* + * Information used to manage the selection and insertion cursor: + */ + + Tk_CanvasTextInfo textInfo; /* Contains lots of fields; see tk.h for + * details. This structure is shared with + * the code that implements individual items. */ + int insertOnTime; /* Number of milliseconds cursor should spend + * in "on" state for each blink. */ + int insertOffTime; /* Number of milliseconds cursor should spend + * in "off" state for each blink. */ + Tcl_TimerToken insertBlinkHandler; + /* Timer handler used to blink cursor on and + * off. */ + + /* + * Transformation applied to canvas as a whole: to compute screen + * coordinates (X,Y) from canvas coordinates (x,y), do the following: + * + * X = x - xOrigin; + * Y = y - yOrigin; + */ + + int xOrigin, yOrigin; /* Canvas coordinates corresponding to + * upper-left corner of window, given in + * canvas pixel units. */ + int drawableXOrigin, drawableYOrigin; + /* During redisplay, these fields give the + * canvas coordinates corresponding to + * the upper-left corner of the drawable + * where items are actually being drawn + * (typically a pixmap smaller than the + * whole window). */ + + /* + * Information used for event bindings associated with items. + */ + + Tk_BindingTable bindingTable; + /* Table of all bindings currently defined + * for this canvas. NULL means that no + * bindings exist, so the table hasn't been + * created. Each "object" used for this + * table is either a Tk_Uid for a tag or + * the address of an item named by id. */ + Tk_Item *currentItemPtr; /* The item currently containing the mouse + * pointer, or NULL if none. */ + Tk_Item *newCurrentPtr; /* The item that is about to become the + * current one, or NULL. This field is + * used to detect deletions of the new + * current item pointer that occur during + * Leave processing of the previous current + * item. */ + double closeEnough; /* The mouse is assumed to be inside an + * item if it is this close to it. */ + XEvent pickEvent; /* The event upon which the current choice + * of currentItem is based. Must be saved + * so that if the currentItem is deleted, + * can pick another. */ + int state; /* Last known modifier state. Used to + * defer picking a new current object + * while buttons are down. */ + + /* + * Information used for managing scrollbars: + */ + + char *xScrollCmd; /* Command prefix for communicating with + * horizontal scrollbar. NULL means no + * horizontal scrollbar. Malloc'ed*/ + char *yScrollCmd; /* Command prefix for communicating with + * vertical scrollbar. NULL means no + * vertical scrollbar. Malloc'ed*/ + int scrollX1, scrollY1, scrollX2, scrollY2; + /* These four coordinates define the region + * that is the 100% area for scrolling (i.e. + * these numbers determine the size and + * location of the sliders on scrollbars). + * Units are pixels in canvas coords. */ + char *regionString; /* The option string from which scrollX1 + * etc. are derived. Malloc'ed. */ + int xScrollIncrement; /* If >0, defines a grid for horizontal + * scrolling. This is the size of the "unit", + * and the left edge of the screen will always + * lie on an even unit boundary. */ + int yScrollIncrement; /* If >0, defines a grid for horizontal + * scrolling. This is the size of the "unit", + * and the left edge of the screen will always + * lie on an even unit boundary. */ + + /* + * Information used for scanning: + */ + + int scanX; /* X-position at which scan started (e.g. + * button was pressed here). */ + int scanXOrigin; /* Value of xOrigin field when scan started. */ + int scanY; /* Y-position at which scan started (e.g. + * button was pressed here). */ + int scanYOrigin; /* Value of yOrigin field when scan started. */ + + /* + * Information used to speed up searches by remembering the last item + * created or found with an item id search. + */ + + Tk_Item *hotPtr; /* Pointer to "hot" item (one that's been + * recently used. NULL means there's no + * hot item. */ + Tk_Item *hotPrevPtr; /* Pointer to predecessor to hotPtr (NULL + * means item is first in list). This is + * only a hint and may not really be hotPtr's + * predecessor. */ + + /* + * Miscellaneous information: + */ + + Tk_Cursor cursor; /* Current cursor for window, or None. */ + char *takeFocus; /* Value of -takefocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + double pixelsPerMM; /* Scale factor between MM and pixels; + * used when converting coordinates. */ + int flags; /* Various flags; see below for + * definitions. */ + int nextId; /* Number to use as id for next item + * created in widget. */ + struct TkPostscriptInfo *psInfoPtr; + /* Pointer to information used for generating + * Postscript for the canvas. NULL means + * no Postscript is currently being + * generated. */ +} TkCanvas; + +/* + * Flag bits for canvases: + * + * REDRAW_PENDING - 1 means a DoWhenIdle handler has already + * been created to redraw some or all of the + * canvas. + * REDRAW_BORDERS - 1 means that the borders need to be redrawn + * during the next redisplay operation. + * REPICK_NEEDED - 1 means DisplayCanvas should pick a new + * current item before redrawing the canvas. + * GOT_FOCUS - 1 means the focus is currently in this + * widget, so should draw the insertion cursor + * and traversal highlight. + * CURSOR_ON - 1 means the insertion cursor is in the "on" + * phase of its blink cycle. 0 means either + * we don't have the focus or the cursor is in + * the "off" phase of its cycle. + * UPDATE_SCROLLBARS - 1 means the scrollbars should get updated + * as part of the next display operation. + * LEFT_GRABBED_ITEM - 1 means that the mouse left the current + * item while a grab was in effect, so we + * didn't change canvasPtr->currentItemPtr. + * REPICK_IN_PROGRESS - 1 means PickCurrentItem is currently + * executing. If it should be called recursively, + * it should simply return immediately. + */ + +#define REDRAW_PENDING 1 +#define REDRAW_BORDERS 2 +#define REPICK_NEEDED 4 +#define GOT_FOCUS 8 +#define CURSOR_ON 0x10 +#define UPDATE_SCROLLBARS 0x20 +#define LEFT_GRABBED_ITEM 0x40 +#define REPICK_IN_PROGRESS 0x100 + +/* + * Canvas-related procedures that are shared among Tk modules but not + * exported to the outside world: + */ + +extern int TkCanvPostscriptCmd _ANSI_ARGS_((TkCanvas *canvasPtr, + Tcl_Interp *interp, int argc, char **argv)); + +#endif /* _TKCANVAS */ diff --git a/generic/tkClipboard.c b/generic/tkClipboard.c new file mode 100644 index 0000000..e1c9510 --- /dev/null +++ b/generic/tkClipboard.c @@ -0,0 +1,606 @@ +/* + * tkClipboard.c -- + * + * This file manages the clipboard for the Tk toolkit, + * maintaining a collection of data buffers that will be + * supplied on demand to requesting applications. + * + * Copyright (c) 1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkClipboard.c 1.15 96/05/03 10:51:08 + */ + +#include "tkInt.h" +#include "tkPort.h" +#include "tkSelect.h" + +/* + * Prototypes for procedures used only in this file: + */ + +static int ClipboardAppHandler _ANSI_ARGS_((ClientData clientData, + int offset, char *buffer, int maxBytes)); +static int ClipboardHandler _ANSI_ARGS_((ClientData clientData, + int offset, char *buffer, int maxBytes)); +static int ClipboardWindowHandler _ANSI_ARGS_(( + ClientData clientData, int offset, char *buffer, + int maxBytes)); +static void ClipboardLostSel _ANSI_ARGS_((ClientData clientData)); + +/* + *---------------------------------------------------------------------- + * + * ClipboardHandler -- + * + * This procedure acts as selection handler for the + * clipboard manager. It extracts the required chunk of + * data from the buffer chain for a given selection target. + * + * Results: + * The return value is a count of the number of bytes + * actually stored at buffer. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +ClipboardHandler(clientData, offset, buffer, maxBytes) + ClientData clientData; /* Information about data to fetch. */ + int offset; /* Return selection bytes starting at this + * offset. */ + char *buffer; /* Place to store converted selection. */ + int maxBytes; /* Maximum # of bytes to store at buffer. */ +{ + TkClipboardTarget *targetPtr = (TkClipboardTarget*) clientData; + TkClipboardBuffer *cbPtr; + char *srcPtr, *destPtr; + int count = 0; + int scanned = 0; + size_t length, freeCount; + + /* + * Skip to buffer containing offset byte + */ + + for (cbPtr = targetPtr->firstBufferPtr; ; cbPtr = cbPtr->nextPtr) { + if (cbPtr == NULL) { + return 0; + } + if (scanned + cbPtr->length > offset) { + break; + } + scanned += cbPtr->length; + } + + /* + * Copy up to maxBytes or end of list, switching buffers as needed. + */ + + freeCount = maxBytes; + srcPtr = cbPtr->buffer + (offset - scanned); + destPtr = buffer; + length = cbPtr->length - (offset - scanned); + while (1) { + if (length > freeCount) { + strncpy(destPtr, srcPtr, freeCount); + return maxBytes; + } else { + strncpy(destPtr, srcPtr, length); + destPtr += length; + count += length; + freeCount -= length; + } + cbPtr = cbPtr->nextPtr; + if (cbPtr == NULL) { + break; + } + srcPtr = cbPtr->buffer; + length = cbPtr->length; + } + return count; +} + +/* + *---------------------------------------------------------------------- + * + * ClipboardAppHandler -- + * + * This procedure acts as selection handler for retrievals of type + * TK_APPLICATION. It returns the name of the application that + * owns the clipboard. Note: we can't use the default Tk + * selection handler for this selection type, because the clipboard + * window isn't a "real" window and doesn't have the necessary + * information. + * + * Results: + * The return value is a count of the number of bytes + * actually stored at buffer. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +ClipboardAppHandler(clientData, offset, buffer, maxBytes) + ClientData clientData; /* Pointer to TkDisplay structure. */ + int offset; /* Return selection bytes starting at this + * offset. */ + char *buffer; /* Place to store converted selection. */ + int maxBytes; /* Maximum # of bytes to store at buffer. */ +{ + TkDisplay *dispPtr = (TkDisplay *) clientData; + size_t length; + char *p; + + p = dispPtr->clipboardAppPtr->winPtr->nameUid; + length = strlen(p); + length -= offset; + if (length <= 0) { + return 0; + } + if (length > (size_t) maxBytes) { + length = maxBytes; + } + strncpy(buffer, p, length); + return length; +} + +/* + *---------------------------------------------------------------------- + * + * ClipboardWindowHandler -- + * + * This procedure acts as selection handler for retrievals of + * type TK_WINDOW. Since the clipboard doesn't correspond to + * any particular window, we just return ".". We can't use Tk's + * default handler for this selection type, because the clipboard + * window isn't a valid window. + * + * Results: + * The return value is 1, the number of non-null bytes stored + * at buffer. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +ClipboardWindowHandler(clientData, offset, buffer, maxBytes) + ClientData clientData; /* Not used. */ + int offset; /* Return selection bytes starting at this + * offset. */ + char *buffer; /* Place to store converted selection. */ + int maxBytes; /* Maximum # of bytes to store at buffer. */ +{ + buffer[0] = '.'; + buffer[1] = 0; + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * ClipboardLostSel -- + * + * This procedure is invoked whenever clipboard ownership is + * claimed by another window. It just sets a flag so that we + * know the clipboard was taken away. + * + * Results: + * None. + * + * Side effects: + * The clipboard is marked as inactive. + * + *---------------------------------------------------------------------- + */ + +static void +ClipboardLostSel(clientData) + ClientData clientData; /* Pointer to TkDisplay structure. */ +{ + TkDisplay *dispPtr = (TkDisplay*) clientData; + + dispPtr->clipboardActive = 0; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_ClipboardClear -- + * + * Take control of the clipboard and clear out the previous + * contents. This procedure must be invoked before any + * calls to Tk_AppendToClipboard. + * + * Results: + * A standard Tcl result. If an error occurs, an error message is + * left in interp->result. + * + * Side effects: + * From now on, requests for the CLIPBOARD selection will be + * directed to the clipboard manager routines associated with + * clipWindow for the display of tkwin. In order to guarantee + * atomicity, no event handling should occur between + * Tk_ClipboardClear and the following Tk_AppendToClipboard + * calls. This procedure may cause a user-defined LostSel command + * to be invoked when the CLIPBOARD is claimed, so any calling + * function should be reentrant at the point Tk_ClipboardClear is + * invoked. + * + *---------------------------------------------------------------------- + */ + +int +Tk_ClipboardClear(interp, tkwin) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + Tk_Window tkwin; /* Window in application that is clearing + * clipboard; identifies application and + * display. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr = winPtr->dispPtr; + TkClipboardTarget *targetPtr, *nextTargetPtr; + TkClipboardBuffer *cbPtr, *nextCbPtr; + + if (dispPtr->clipWindow == NULL) { + int result; + + result = TkClipInit(interp, dispPtr); + if (result != TCL_OK) { + return result; + } + } + + /* + * Discard any existing clipboard data and delete the selection + * handler(s) associated with that data. + */ + + for (targetPtr = dispPtr->clipTargetPtr; targetPtr != NULL; + targetPtr = nextTargetPtr) { + for (cbPtr = targetPtr->firstBufferPtr; cbPtr != NULL; + cbPtr = nextCbPtr) { + ckfree(cbPtr->buffer); + nextCbPtr = cbPtr->nextPtr; + ckfree((char *) cbPtr); + } + nextTargetPtr = targetPtr->nextPtr; + Tk_DeleteSelHandler(dispPtr->clipWindow, dispPtr->clipboardAtom, + targetPtr->type); + ckfree((char *) targetPtr); + } + dispPtr->clipTargetPtr = NULL; + + /* + * Reclaim the clipboard selection if we lost it. + */ + + if (!dispPtr->clipboardActive) { + Tk_OwnSelection(dispPtr->clipWindow, dispPtr->clipboardAtom, + ClipboardLostSel, (ClientData) dispPtr); + dispPtr->clipboardActive = 1; + } + dispPtr->clipboardAppPtr = winPtr->mainPtr; + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_ClipboardAppend -- + * + * Append a buffer of data to the clipboard. The first buffer of + * a given type determines the format for that type. Any successive + * appends to that type must have the same format or an error will + * be returned. Tk_ClipboardClear must be called before a sequence + * of Tk_ClipboardAppend calls can be issued. In order to guarantee + * atomicity, no event handling should occur between Tk_ClipboardClear + * and the following Tk_AppendToClipboard calls. + * + * Results: + * A standard Tcl result. If an error is returned, an error message + * is left in interp->result. + * + * Side effects: + * The specified buffer will be copied onto the end of the clipboard. + * The clipboard maintains a list of buffers which will be used to + * supply the data for a selection get request. The first time a given + * type is appended, Tk_ClipboardAppend will register a selection + * handler of the appropriate type. + * + *---------------------------------------------------------------------- + */ + +int +Tk_ClipboardAppend(interp, tkwin, type, format, buffer) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Window tkwin; /* Window that selects a display. */ + Atom type; /* The desired conversion type for this + * clipboard item, e.g. STRING or LENGTH. */ + Atom format; /* Format in which the selection + * information should be returned to + * the requestor. */ + char* buffer; /* NULL terminated string containing the data + * to be added to the clipboard. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr = winPtr->dispPtr; + TkClipboardTarget *targetPtr; + TkClipboardBuffer *cbPtr; + + /* + * If this application doesn't already own the clipboard, clear + * the clipboard. If we don't own the clipboard selection, claim it. + */ + + if (dispPtr->clipboardAppPtr != winPtr->mainPtr) { + Tk_ClipboardClear(interp, tkwin); + } else if (!dispPtr->clipboardActive) { + Tk_OwnSelection(dispPtr->clipWindow, dispPtr->clipboardAtom, + ClipboardLostSel, (ClientData) dispPtr); + dispPtr->clipboardActive = 1; + } + + /* + * Check to see if the specified target is already present on the + * clipboard. If it isn't, we need to create a new target; otherwise, + * we just append the new buffer to the clipboard list. + */ + + for (targetPtr = dispPtr->clipTargetPtr; targetPtr != NULL; + targetPtr = targetPtr->nextPtr) { + if (targetPtr->type == type) + break; + } + if (targetPtr == NULL) { + targetPtr = (TkClipboardTarget*) ckalloc(sizeof(TkClipboardTarget)); + targetPtr->type = type; + targetPtr->format = format; + targetPtr->firstBufferPtr = targetPtr->lastBufferPtr = NULL; + targetPtr->nextPtr = dispPtr->clipTargetPtr; + dispPtr->clipTargetPtr = targetPtr; + Tk_CreateSelHandler(dispPtr->clipWindow, dispPtr->clipboardAtom, + type, ClipboardHandler, (ClientData) targetPtr, format); + } else if (targetPtr->format != format) { + Tcl_AppendResult(interp, "format \"", Tk_GetAtomName(tkwin, format), + "\" does not match current format \"", + Tk_GetAtomName(tkwin, targetPtr->format),"\" for ", + Tk_GetAtomName(tkwin, type), (char *) NULL); + return TCL_ERROR; + } + + /* + * Append a new buffer to the buffer chain. + */ + + cbPtr = (TkClipboardBuffer*) ckalloc(sizeof(TkClipboardBuffer)); + cbPtr->nextPtr = NULL; + if (targetPtr->lastBufferPtr != NULL) { + targetPtr->lastBufferPtr->nextPtr = cbPtr; + } else { + targetPtr->firstBufferPtr = cbPtr; + } + targetPtr->lastBufferPtr = cbPtr; + + cbPtr->length = strlen(buffer); + cbPtr->buffer = (char *) ckalloc((unsigned) (cbPtr->length + 1)); + strcpy(cbPtr->buffer, buffer); + + TkSelUpdateClipboard((TkWindow*)(dispPtr->clipWindow), targetPtr); + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_ClipboardCmd -- + * + * This procedure is invoked to process the "clipboard" Tcl + * command. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_ClipboardCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + char *path = NULL; + size_t length; + int count; + char c; + char **args; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'a') && (strncmp(argv[1], "append", length) == 0)) { + Atom target, format; + char *targetName = NULL; + char *formatName = NULL; + + for (count = argc-2, args = argv+2; count > 1; count -= 2, args += 2) { + if (args[0][0] != '-') { + break; + } + c = args[0][1]; + length = strlen(args[0]); + if ((c == '-') && (length == 2)) { + args++; + count--; + break; + } + if ((c == 'd') && (strncmp(args[0], "-displayof", length) == 0)) { + path = args[1]; + } else if ((c == 'f') + && (strncmp(args[0], "-format", length) == 0)) { + formatName = args[1]; + } else if ((c == 't') + && (strncmp(args[0], "-type", length) == 0)) { + targetName = args[1]; + } else { + Tcl_AppendResult(interp, "unknown option \"", args[0], + "\"", (char *) NULL); + return TCL_ERROR; + } + } + if (count != 1) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " append ?options? data\"", (char *) NULL); + return TCL_ERROR; + } + if (path != NULL) { + tkwin = Tk_NameToWindow(interp, path, tkwin); + } + if (tkwin == NULL) { + return TCL_ERROR; + } + if (targetName != NULL) { + target = Tk_InternAtom(tkwin, targetName); + } else { + target = XA_STRING; + } + if (formatName != NULL) { + format = Tk_InternAtom(tkwin, formatName); + } else { + format = XA_STRING; + } + return Tk_ClipboardAppend(interp, tkwin, target, format, args[0]); + } else if ((c == 'c') && (strncmp(argv[1], "clear", length) == 0)) { + for (count = argc-2, args = argv+2; count > 0; count -= 2, args += 2) { + if (args[0][0] != '-') { + break; + } + if (count < 2) { + Tcl_AppendResult(interp, "value for \"", *args, + "\" missing", (char *) NULL); + return TCL_ERROR; + } + c = args[0][1]; + length = strlen(args[0]); + if ((c == 'd') && (strncmp(args[0], "-displayof", length) == 0)) { + path = args[1]; + } else { + Tcl_AppendResult(interp, "unknown option \"", args[0], + "\"", (char *) NULL); + return TCL_ERROR; + } + } + if (count > 0) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " clear ?options?\"", (char *) NULL); + return TCL_ERROR; + } + if (path != NULL) { + tkwin = Tk_NameToWindow(interp, path, tkwin); + } + if (tkwin == NULL) { + return TCL_ERROR; + } + return Tk_ClipboardClear(interp, tkwin); + } else { + sprintf(interp->result, + "bad option \"%.50s\": must be clear or append", + argv[1]); + return TCL_ERROR; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkClipInit -- + * + * This procedure is called to initialize the window for claiming + * clipboard ownership and for receiving selection get results. This + * function is called from tkSelect.c as well as tkClipboard.c. + * + * Results: + * The result is a standard Tcl return value, which is normally TCL_OK. + * If an error occurs then an error message is left in interp->result + * and TCL_ERROR is returned. + * + * Side effects: + * Sets up the clipWindow and related data structures. + * + *---------------------------------------------------------------------- + */ + +int +TkClipInit(interp, dispPtr) + Tcl_Interp *interp; /* Interpreter to use for error + * reporting. */ + register TkDisplay *dispPtr;/* Display to initialize. */ +{ + XSetWindowAttributes atts; + + dispPtr->clipTargetPtr = NULL; + dispPtr->clipboardActive = 0; + dispPtr->clipboardAppPtr = NULL; + + /* + * Create the window used for clipboard ownership and selection retrieval, + * and set up an event handler for it. + */ + + dispPtr->clipWindow = Tk_CreateWindow(interp, (Tk_Window) NULL, + "_clip", DisplayString(dispPtr->display)); + if (dispPtr->clipWindow == NULL) { + return TCL_ERROR; + } + atts.override_redirect = True; + Tk_ChangeWindowAttributes(dispPtr->clipWindow, CWOverrideRedirect, &atts); + Tk_MakeWindowExist(dispPtr->clipWindow); + + if (dispPtr->multipleAtom == None) { + /* + * Need to invoke selection initialization to make sure that + * atoms we depend on below are defined. + */ + + TkSelInit(dispPtr->clipWindow); + } + + /* + * Create selection handlers for types TK_APPLICATION and TK_WINDOW + * on this window. Can't use the default handlers for these types + * because this isn't a full-fledged window. + */ + + Tk_CreateSelHandler(dispPtr->clipWindow, dispPtr->clipboardAtom, + dispPtr->applicationAtom, ClipboardAppHandler, + (ClientData) dispPtr, XA_STRING); + Tk_CreateSelHandler(dispPtr->clipWindow, dispPtr->clipboardAtom, + dispPtr->windowAtom, ClipboardWindowHandler, + (ClientData) dispPtr, XA_STRING); + return TCL_OK; +} diff --git a/generic/tkCmds.c b/generic/tkCmds.c new file mode 100644 index 0000000..34e2867 --- /dev/null +++ b/generic/tkCmds.c @@ -0,0 +1,1646 @@ +/* + * tkCmds.c -- + * + * This file contains a collection of Tk-related Tcl commands + * that didn't fit in any particular file of the toolkit. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCmds.c 1.125 97/05/20 16:16:33 + */ + +#include "tkPort.h" +#include "tkInt.h" +#include <errno.h> + +/* + * Forward declarations for procedures defined later in this file: + */ + +static TkWindow * GetToplevel _ANSI_ARGS_((Tk_Window tkwin)); +static char * WaitVariableProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, char *name1, char *name2, + int flags)); +static void WaitVisibilityProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void WaitWindowProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); + +/* + *---------------------------------------------------------------------- + * + * Tk_BellCmd -- + * + * This procedure is invoked to process the "bell" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_BellCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + size_t length; + + if ((argc != 1) && (argc != 3)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ?-displayof window?\"", (char *) NULL); + return TCL_ERROR; + } + + if (argc == 3) { + length = strlen(argv[1]); + if ((length < 2) || (strncmp(argv[1], "-displayof", length) != 0)) { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be -displayof", (char *) NULL); + return TCL_ERROR; + } + tkwin = Tk_NameToWindow(interp, argv[2], tkwin); + if (tkwin == NULL) { + return TCL_ERROR; + } + } + XBell(Tk_Display(tkwin), 0); + XForceScreenSaver(Tk_Display(tkwin), ScreenSaverReset); + XFlush(Tk_Display(tkwin)); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_BindCmd -- + * + * This procedure is invoked to process the "bind" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_BindCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + TkWindow *winPtr; + ClientData object; + + if ((argc < 2) || (argc > 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " window ?pattern? ?command?\"", (char *) NULL); + return TCL_ERROR; + } + if (argv[1][0] == '.') { + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[1], tkwin); + if (winPtr == NULL) { + return TCL_ERROR; + } + object = (ClientData) winPtr->pathName; + } else { + winPtr = (TkWindow *) clientData; + object = (ClientData) Tk_GetUid(argv[1]); + } + + if (argc == 4) { + int append = 0; + unsigned long mask; + + if (argv[3][0] == 0) { + return Tk_DeleteBinding(interp, winPtr->mainPtr->bindingTable, + object, argv[2]); + } + if (argv[3][0] == '+') { + argv[3]++; + append = 1; + } + mask = Tk_CreateBinding(interp, winPtr->mainPtr->bindingTable, + object, argv[2], argv[3], append); + if (mask == 0) { + return TCL_ERROR; + } + } else if (argc == 3) { + char *command; + + command = Tk_GetBinding(interp, winPtr->mainPtr->bindingTable, + object, argv[2]); + if (command == NULL) { + Tcl_ResetResult(interp); + return TCL_OK; + } + interp->result = command; + } else { + Tk_GetAllBindings(interp, winPtr->mainPtr->bindingTable, object); + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkBindEventProc -- + * + * This procedure is invoked by Tk_HandleEvent for each event; it + * causes any appropriate bindings for that event to be invoked. + * + * Results: + * None. + * + * Side effects: + * Depends on what bindings have been established with the "bind" + * command. + * + *---------------------------------------------------------------------- + */ + +void +TkBindEventProc(winPtr, eventPtr) + TkWindow *winPtr; /* Pointer to info about window. */ + XEvent *eventPtr; /* Information about event. */ +{ +#define MAX_OBJS 20 + ClientData objects[MAX_OBJS], *objPtr; + static Tk_Uid allUid = NULL; + TkWindow *topLevPtr; + int i, count; + char *p; + Tcl_HashEntry *hPtr; + + if ((winPtr->mainPtr == NULL) || (winPtr->mainPtr->bindingTable == NULL)) { + return; + } + + objPtr = objects; + if (winPtr->numTags != 0) { + /* + * Make a copy of the tags for the window, replacing window names + * with pointers to the pathName from the appropriate window. + */ + + if (winPtr->numTags > MAX_OBJS) { + objPtr = (ClientData *) ckalloc((unsigned) + (winPtr->numTags * sizeof(ClientData))); + } + for (i = 0; i < winPtr->numTags; i++) { + p = (char *) winPtr->tagPtr[i]; + if (*p == '.') { + hPtr = Tcl_FindHashEntry(&winPtr->mainPtr->nameTable, p); + if (hPtr != NULL) { + p = ((TkWindow *) Tcl_GetHashValue(hPtr))->pathName; + } else { + p = NULL; + } + } + objPtr[i] = (ClientData) p; + } + count = winPtr->numTags; + } else { + objPtr[0] = (ClientData) winPtr->pathName; + objPtr[1] = (ClientData) winPtr->classUid; + for (topLevPtr = winPtr; + (topLevPtr != NULL) && !(topLevPtr->flags & TK_TOP_LEVEL); + topLevPtr = topLevPtr->parentPtr) { + /* Empty loop body. */ + } + if ((winPtr != topLevPtr) && (topLevPtr != NULL)) { + count = 4; + objPtr[2] = (ClientData) topLevPtr->pathName; + } else { + count = 3; + } + if (allUid == NULL) { + allUid = Tk_GetUid("all"); + } + objPtr[count-1] = (ClientData) allUid; + } + Tk_BindEvent(winPtr->mainPtr->bindingTable, eventPtr, (Tk_Window) winPtr, + count, objPtr); + if (objPtr != objects) { + ckfree((char *) objPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_BindtagsCmd -- + * + * This procedure is invoked to process the "bindtags" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_BindtagsCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + TkWindow *winPtr, *winPtr2; + int i, tagArgc; + char *p, **tagArgv; + + if ((argc < 2) || (argc > 3)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " window ?tags?\"", (char *) NULL); + return TCL_ERROR; + } + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[1], tkwin); + if (winPtr == NULL) { + return TCL_ERROR; + } + if (argc == 2) { + if (winPtr->numTags == 0) { + Tcl_AppendElement(interp, winPtr->pathName); + Tcl_AppendElement(interp, winPtr->classUid); + for (winPtr2 = winPtr; + (winPtr2 != NULL) && !(winPtr2->flags & TK_TOP_LEVEL); + winPtr2 = winPtr2->parentPtr) { + /* Empty loop body. */ + } + if ((winPtr != winPtr2) && (winPtr2 != NULL)) { + Tcl_AppendElement(interp, winPtr2->pathName); + } + Tcl_AppendElement(interp, "all"); + } else { + for (i = 0; i < winPtr->numTags; i++) { + Tcl_AppendElement(interp, (char *) winPtr->tagPtr[i]); + } + } + return TCL_OK; + } + if (winPtr->tagPtr != NULL) { + TkFreeBindingTags(winPtr); + } + if (argv[2][0] == 0) { + return TCL_OK; + } + if (Tcl_SplitList(interp, argv[2], &tagArgc, &tagArgv) != TCL_OK) { + return TCL_ERROR; + } + winPtr->numTags = tagArgc; + winPtr->tagPtr = (ClientData *) ckalloc((unsigned) + (tagArgc * sizeof(ClientData))); + for (i = 0; i < tagArgc; i++) { + p = tagArgv[i]; + if (p[0] == '.') { + char *copy; + + /* + * Handle names starting with "." specially: store a malloc'ed + * string, rather than a Uid; at event time we'll look up the + * name in the window table and use the corresponding window, + * if there is one. + */ + + copy = (char *) ckalloc((unsigned) (strlen(p) + 1)); + strcpy(copy, p); + winPtr->tagPtr[i] = (ClientData) copy; + } else { + winPtr->tagPtr[i] = (ClientData) Tk_GetUid(p); + } + } + ckfree((char *) tagArgv); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkFreeBindingTags -- + * + * This procedure is called to free all of the binding tags + * associated with a window; typically it is only invoked where + * there are window-specific tags. + * + * Results: + * None. + * + * Side effects: + * Any binding tags for winPtr are freed. + * + *---------------------------------------------------------------------- + */ + +void +TkFreeBindingTags(winPtr) + TkWindow *winPtr; /* Window whose tags are to be released. */ +{ + int i; + char *p; + + for (i = 0; i < winPtr->numTags; i++) { + p = (char *) (winPtr->tagPtr[i]); + if (*p == '.') { + /* + * Names starting with "." are malloced rather than Uids, so + * they have to be freed. + */ + + ckfree(p); + } + } + ckfree((char *) winPtr->tagPtr); + winPtr->numTags = 0; + winPtr->tagPtr = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_DestroyCmd -- + * + * This procedure is invoked to process the "destroy" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_DestroyCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window window; + Tk_Window tkwin = (Tk_Window) clientData; + int i; + + for (i = 1; i < argc; i++) { + window = Tk_NameToWindow(interp, argv[i], tkwin); + if (window == NULL) { + Tcl_ResetResult(interp); + continue; + } + Tk_DestroyWindow(window); + if (window == tkwin) { + /* + * We just deleted the main window for the application! This + * makes it impossible to do anything more (tkwin isn't + * valid anymore). + */ + + break; + } + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_LowerCmd -- + * + * This procedure is invoked to process the "lower" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +Tk_LowerCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window main = (Tk_Window) clientData; + Tk_Window tkwin, other; + + if ((argc != 2) && (argc != 3)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " window ?belowThis?\"", (char *) NULL); + return TCL_ERROR; + } + + tkwin = Tk_NameToWindow(interp, argv[1], main); + if (tkwin == NULL) { + return TCL_ERROR; + } + if (argc == 2) { + other = NULL; + } else { + other = Tk_NameToWindow(interp, argv[2], main); + if (other == NULL) { + return TCL_ERROR; + } + } + if (Tk_RestackWindow(tkwin, Below, other) != TCL_OK) { + Tcl_AppendResult(interp, "can't lower \"", argv[1], "\" below \"", + argv[2], "\"", (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_RaiseCmd -- + * + * This procedure is invoked to process the "raise" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +Tk_RaiseCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window main = (Tk_Window) clientData; + Tk_Window tkwin, other; + + if ((argc != 2) && (argc != 3)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " window ?aboveThis?\"", (char *) NULL); + return TCL_ERROR; + } + + tkwin = Tk_NameToWindow(interp, argv[1], main); + if (tkwin == NULL) { + return TCL_ERROR; + } + if (argc == 2) { + other = NULL; + } else { + other = Tk_NameToWindow(interp, argv[2], main); + if (other == NULL) { + return TCL_ERROR; + } + } + if (Tk_RestackWindow(tkwin, Above, other) != TCL_OK) { + Tcl_AppendResult(interp, "can't raise \"", argv[1], "\" above \"", + argv[2], "\"", (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_TkObjCmd -- + * + * This procedure is invoked to process the "tk" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_TkObjCmd(clientData, interp, objc, objv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. */ +{ + int index; + Tk_Window tkwin; + static char *optionStrings[] = { + "appname", "scaling", NULL + }; + enum options { + TK_APPNAME, TK_SCALING + }; + + tkwin = (Tk_Window) clientData; + + if (objc < 2) { + Tcl_WrongNumArgs(interp, 1, objv, "option ?arg?"); + return TCL_ERROR; + } + if (Tcl_GetIndexFromObj(interp, objv[1], optionStrings, "option", 0, + &index) != TCL_OK) { + return TCL_ERROR; + } + + switch ((enum options) index) { + case TK_APPNAME: { + TkWindow *winPtr; + char *string; + + winPtr = (TkWindow *) tkwin; + + if (objc > 3) { + Tcl_WrongNumArgs(interp, 2, objv, "?newName?"); + return TCL_ERROR; + } + if (objc == 3) { + string = Tcl_GetStringFromObj(objv[2], NULL); + winPtr->nameUid = Tk_GetUid(Tk_SetAppName(tkwin, string)); + } + Tcl_SetStringObj(Tcl_GetObjResult(interp), winPtr->nameUid, -1); + break; + } + case TK_SCALING: { + Screen *screenPtr; + int skip, width, height; + double d; + + screenPtr = Tk_Screen(tkwin); + + skip = TkGetDisplayOf(interp, objc - 2, objv + 2, &tkwin); + if (skip < 0) { + return TCL_ERROR; + } + if (objc - skip == 2) { + d = 25.4 / 72; + d *= WidthOfScreen(screenPtr); + d /= WidthMMOfScreen(screenPtr); + Tcl_SetDoubleObj(Tcl_GetObjResult(interp), d); + } else if (objc - skip == 3) { + if (Tcl_GetDoubleFromObj(interp, objv[2 + skip], &d) != TCL_OK) { + return TCL_ERROR; + } + d = (25.4 / 72) / d; + width = (int) (d * WidthOfScreen(screenPtr) + 0.5); + if (width <= 0) { + width = 1; + } + height = (int) (d * HeightOfScreen(screenPtr) + 0.5); + if (height <= 0) { + height = 1; + } + WidthMMOfScreen(screenPtr) = width; + HeightMMOfScreen(screenPtr) = height; + } else { + Tcl_WrongNumArgs(interp, 2, objv, + "?-displayof window? ?factor?"); + return TCL_ERROR; + } + break; + } + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_TkwaitCmd -- + * + * This procedure is invoked to process the "tkwait" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +Tk_TkwaitCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + int c, done; + size_t length; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " variable|visibility|window name\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'v') && (strncmp(argv[1], "variable", length) == 0) + && (length >= 2)) { + if (Tcl_TraceVar(interp, argv[2], + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + WaitVariableProc, (ClientData) &done) != TCL_OK) { + return TCL_ERROR; + } + done = 0; + while (!done) { + Tcl_DoOneEvent(0); + } + Tcl_UntraceVar(interp, argv[2], + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + WaitVariableProc, (ClientData) &done); + } else if ((c == 'v') && (strncmp(argv[1], "visibility", length) == 0) + && (length >= 2)) { + Tk_Window window; + + window = Tk_NameToWindow(interp, argv[2], tkwin); + if (window == NULL) { + return TCL_ERROR; + } + Tk_CreateEventHandler(window, VisibilityChangeMask|StructureNotifyMask, + WaitVisibilityProc, (ClientData) &done); + done = 0; + while (!done) { + Tcl_DoOneEvent(0); + } + if (done != 1) { + /* + * Note that we do not delete the event handler because it + * was deleted automatically when the window was destroyed. + */ + + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "window \"", argv[2], + "\" was deleted before its visibility changed", + (char *) NULL); + return TCL_ERROR; + } + Tk_DeleteEventHandler(window, VisibilityChangeMask|StructureNotifyMask, + WaitVisibilityProc, (ClientData) &done); + } else if ((c == 'w') && (strncmp(argv[1], "window", length) == 0)) { + Tk_Window window; + + window = Tk_NameToWindow(interp, argv[2], tkwin); + if (window == NULL) { + return TCL_ERROR; + } + Tk_CreateEventHandler(window, StructureNotifyMask, + WaitWindowProc, (ClientData) &done); + done = 0; + while (!done) { + Tcl_DoOneEvent(0); + } + /* + * Note: there's no need to delete the event handler. It was + * deleted automatically when the window was destroyed. + */ + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be variable, visibility, or window", (char *) NULL); + return TCL_ERROR; + } + + /* + * Clear out the interpreter's result, since it may have been set + * by event handlers. + */ + + Tcl_ResetResult(interp); + return TCL_OK; +} + + /* ARGSUSED */ +static char * +WaitVariableProc(clientData, interp, name1, name2, flags) + ClientData clientData; /* Pointer to integer to set to 1. */ + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *name1; /* Name of variable. */ + char *name2; /* Second part of variable name. */ + int flags; /* Information about what happened. */ +{ + int *donePtr = (int *) clientData; + + *donePtr = 1; + return (char *) NULL; +} + + /*ARGSUSED*/ +static void +WaitVisibilityProc(clientData, eventPtr) + ClientData clientData; /* Pointer to integer to set to 1. */ + XEvent *eventPtr; /* Information about event (not used). */ +{ + int *donePtr = (int *) clientData; + + if (eventPtr->type == VisibilityNotify) { + *donePtr = 1; + } + if (eventPtr->type == DestroyNotify) { + *donePtr = 2; + } +} + +static void +WaitWindowProc(clientData, eventPtr) + ClientData clientData; /* Pointer to integer to set to 1. */ + XEvent *eventPtr; /* Information about event. */ +{ + int *donePtr = (int *) clientData; + + if (eventPtr->type == DestroyNotify) { + *donePtr = 1; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_UpdateCmd -- + * + * This procedure is invoked to process the "update" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +Tk_UpdateCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + int flags; + TkDisplay *dispPtr; + + if (argc == 1) { + flags = TCL_DONT_WAIT; + } else if (argc == 2) { + if (strncmp(argv[1], "idletasks", strlen(argv[1])) != 0) { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be idletasks", (char *) NULL); + return TCL_ERROR; + } + flags = TCL_IDLE_EVENTS; + } else { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " ?idletasks?\"", (char *) NULL); + return TCL_ERROR; + } + + /* + * Handle all pending events, sync all displays, and repeat over + * and over again until all pending events have been handled. + * Special note: it's possible that the entire application could + * be destroyed by an event handler that occurs during the update. + * Thus, don't use any information from tkwin after calling + * Tcl_DoOneEvent. + */ + + while (1) { + while (Tcl_DoOneEvent(flags) != 0) { + /* Empty loop body */ + } + for (dispPtr = tkDisplayList; dispPtr != NULL; + dispPtr = dispPtr->nextPtr) { + XSync(dispPtr->display, False); + } + if (Tcl_DoOneEvent(flags) == 0) { + break; + } + } + + /* + * Must clear the interpreter's result because event handlers could + * have executed commands. + */ + + Tcl_ResetResult(interp); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_WinfoObjCmd -- + * + * This procedure is invoked to process the "winfo" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_WinfoObjCmd(clientData, interp, objc, objv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. */ +{ + int index, x, y, width, height, useX, useY, class, skip; + char buf[128]; + char *string; + TkWindow *winPtr; + Tk_Window tkwin; + + static TkStateMap visualMap[] = { + {PseudoColor, "pseudocolor"}, + {GrayScale, "grayscale"}, + {DirectColor, "directcolor"}, + {TrueColor, "truecolor"}, + {StaticColor, "staticcolor"}, + {StaticGray, "staticgray"}, + {-1, NULL} + }; + static char *optionStrings[] = { + "cells", "children", "class", "colormapfull", + "depth", "geometry", "height", "id", + "ismapped", "manager", "name", "parent", + "pointerx", "pointery", "pointerxy", "reqheight", + "reqwidth", "rootx", "rooty", "screen", + "screencells", "screendepth", "screenheight", "screenwidth", + "screenmmheight","screenmmwidth","screenvisual","server", + "toplevel", "viewable", "visual", "visualid", + "vrootheight", "vrootwidth", "vrootx", "vrooty", + "width", "x", "y", + + "atom", "atomname", "containing", "interps", + "pathname", + + "exists", "fpixels", "pixels", "rgb", + "visualsavailable", + + NULL + }; + enum options { + WIN_CELLS, WIN_CHILDREN, WIN_CLASS, WIN_COLORMAPFULL, + WIN_DEPTH, WIN_GEOMETRY, WIN_HEIGHT, WIN_ID, + WIN_ISMAPPED, WIN_MANAGER, WIN_NAME, WIN_PARENT, + WIN_POINTERX, WIN_POINTERY, WIN_POINTERXY, WIN_REQHEIGHT, + WIN_REQWIDTH, WIN_ROOTX, WIN_ROOTY, WIN_SCREEN, + WIN_SCREENCELLS,WIN_SCREENDEPTH,WIN_SCREENHEIGHT,WIN_SCREENWIDTH, + WIN_SCREENMMHEIGHT,WIN_SCREENMMWIDTH,WIN_SCREENVISUAL,WIN_SERVER, + WIN_TOPLEVEL, WIN_VIEWABLE, WIN_VISUAL, WIN_VISUALID, + WIN_VROOTHEIGHT,WIN_VROOTWIDTH, WIN_VROOTX, WIN_VROOTY, + WIN_WIDTH, WIN_X, WIN_Y, + + WIN_ATOM, WIN_ATOMNAME, WIN_CONTAINING, WIN_INTERPS, + WIN_PATHNAME, + + WIN_EXISTS, WIN_FPIXELS, WIN_PIXELS, WIN_RGB, + WIN_VISUALSAVAILABLE + }; + + tkwin = (Tk_Window) clientData; + + if (objc < 2) { + Tcl_WrongNumArgs(interp, 1, objv, "option ?arg?"); + return TCL_ERROR; + } + if (Tcl_GetIndexFromObj(interp, objv[1], optionStrings, "option", 0, + &index) != TCL_OK) { + return TCL_ERROR; + } + + if (index < WIN_ATOM) { + if (objc != 3) { + Tcl_WrongNumArgs(interp, 2, objv, "window"); + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[2], NULL); + tkwin = Tk_NameToWindow(interp, string, tkwin); + if (tkwin == NULL) { + return TCL_ERROR; + } + } + winPtr = (TkWindow *) tkwin; + + switch ((enum options) index) { + case WIN_CELLS: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), + Tk_Visual(tkwin)->map_entries); + break; + } + case WIN_CHILDREN: { + Tcl_Obj *strPtr; + + Tcl_ResetResult(interp); + winPtr = winPtr->childList; + for ( ; winPtr != NULL; winPtr = winPtr->nextPtr) { + strPtr = Tcl_NewStringObj(winPtr->pathName, -1); + Tcl_ListObjAppendElement(NULL, + Tcl_GetObjResult(interp), strPtr); + } + break; + } + case WIN_CLASS: { + Tcl_ResetResult(interp); + Tcl_SetStringObj(Tcl_GetObjResult(interp), Tk_Class(tkwin), -1); + break; + } + case WIN_COLORMAPFULL: { + Tcl_ResetResult(interp); + Tcl_SetBooleanObj(Tcl_GetObjResult(interp), + TkpCmapStressed(tkwin, Tk_Colormap(tkwin))); + break; + } + case WIN_DEPTH: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), Tk_Depth(tkwin)); + break; + } + case WIN_GEOMETRY: { + Tcl_ResetResult(interp); + sprintf(buf, "%dx%d+%d+%d", Tk_Width(tkwin), Tk_Height(tkwin), + Tk_X(tkwin), Tk_Y(tkwin)); + Tcl_SetStringObj(Tcl_GetObjResult(interp), buf, -1); + break; + } + case WIN_HEIGHT: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), Tk_Height(tkwin)); + break; + } + case WIN_ID: { + Tk_MakeWindowExist(tkwin); + TkpPrintWindowId(buf, Tk_WindowId(tkwin)); + Tcl_ResetResult(interp); + Tcl_SetStringObj(Tcl_GetObjResult(interp), buf, -1); + break; + } + case WIN_ISMAPPED: { + Tcl_ResetResult(interp); + Tcl_SetBooleanObj(Tcl_GetObjResult(interp), + (int) Tk_IsMapped(tkwin)); + break; + } + case WIN_MANAGER: { + Tcl_ResetResult(interp); + if (winPtr->geomMgrPtr != NULL) { + Tcl_SetStringObj(Tcl_GetObjResult(interp), + winPtr->geomMgrPtr->name, -1); + } + break; + } + case WIN_NAME: { + Tcl_ResetResult(interp); + Tcl_SetStringObj(Tcl_GetObjResult(interp), Tk_Name(tkwin), -1); + break; + } + case WIN_PARENT: { + Tcl_ResetResult(interp); + if (winPtr->parentPtr != NULL) { + Tcl_SetStringObj(Tcl_GetObjResult(interp), + winPtr->parentPtr->pathName, -1); + } + break; + } + case WIN_POINTERX: { + useX = 1; + useY = 0; + goto pointerxy; + } + case WIN_POINTERY: { + useX = 0; + useY = 1; + goto pointerxy; + } + case WIN_POINTERXY: { + useX = 1; + useY = 1; + + pointerxy: + winPtr = GetToplevel(tkwin); + if (winPtr == NULL) { + x = -1; + y = -1; + } else { + TkGetPointerCoords((Tk_Window) winPtr, &x, &y); + } + Tcl_ResetResult(interp); + if (useX & useY) { + sprintf(buf, "%d %d", x, y); + Tcl_SetStringObj(Tcl_GetObjResult(interp), buf, -1); + } else if (useX) { + Tcl_SetIntObj(Tcl_GetObjResult(interp), x); + } else { + Tcl_SetIntObj(Tcl_GetObjResult(interp), y); + } + break; + } + case WIN_REQHEIGHT: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), Tk_ReqHeight(tkwin)); + break; + } + case WIN_REQWIDTH: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), Tk_ReqWidth(tkwin)); + break; + } + case WIN_ROOTX: { + Tk_GetRootCoords(tkwin, &x, &y); + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), x); + break; + } + case WIN_ROOTY: { + Tk_GetRootCoords(tkwin, &x, &y); + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), y); + break; + } + case WIN_SCREEN: { + sprintf(buf, "%d", Tk_ScreenNumber(tkwin)); + Tcl_ResetResult(interp); + Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), + Tk_DisplayName(tkwin), ".", buf, NULL); + break; + } + case WIN_SCREENCELLS: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), + CellsOfScreen(Tk_Screen(tkwin))); + break; + } + case WIN_SCREENDEPTH: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), + DefaultDepthOfScreen(Tk_Screen(tkwin))); + break; + } + case WIN_SCREENHEIGHT: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), + HeightOfScreen(Tk_Screen(tkwin))); + break; + } + case WIN_SCREENWIDTH: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), + WidthOfScreen(Tk_Screen(tkwin))); + break; + } + case WIN_SCREENMMHEIGHT: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), + HeightMMOfScreen(Tk_Screen(tkwin))); + break; + } + case WIN_SCREENMMWIDTH: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), + WidthMMOfScreen(Tk_Screen(tkwin))); + break; + } + case WIN_SCREENVISUAL: { + class = DefaultVisualOfScreen(Tk_Screen(tkwin))->class; + goto visual; + } + case WIN_SERVER: { + TkGetServerInfo(interp, tkwin); + break; + } + case WIN_TOPLEVEL: { + winPtr = GetToplevel(tkwin); + if (winPtr != NULL) { + Tcl_ResetResult(interp); + Tcl_SetStringObj(Tcl_GetObjResult(interp), + winPtr->pathName, -1); + } + break; + } + case WIN_VIEWABLE: { + int viewable; + + viewable = 0; + for ( ; ; winPtr = winPtr->parentPtr) { + if ((winPtr == NULL) || !(winPtr->flags & TK_MAPPED)) { + break; + } + if (winPtr->flags & TK_TOP_LEVEL) { + viewable = 1; + break; + } + } + Tcl_ResetResult(interp); + Tcl_SetBooleanObj(Tcl_GetObjResult(interp), viewable); + break; + } + case WIN_VISUAL: { + class = Tk_Visual(tkwin)->class; + + visual: + string = TkFindStateString(visualMap, class); + if (string == NULL) { + string = "unknown"; + } + Tcl_ResetResult(interp); + Tcl_SetStringObj(Tcl_GetObjResult(interp), string, -1); + break; + } + case WIN_VISUALID: { + Tcl_ResetResult(interp); + sprintf(buf, "0x%x", + (unsigned int) XVisualIDFromVisual(Tk_Visual(tkwin))); + Tcl_SetStringObj(Tcl_GetObjResult(interp), buf, -1); + break; + } + case WIN_VROOTHEIGHT: { + Tk_GetVRootGeometry(tkwin, &x, &y, &width, &height); + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), height); + break; + } + case WIN_VROOTWIDTH: { + Tk_GetVRootGeometry(tkwin, &x, &y, &width, &height); + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), width); + break; + } + case WIN_VROOTX: { + Tk_GetVRootGeometry(tkwin, &x, &y, &width, &height); + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), x); + break; + } + case WIN_VROOTY: { + Tk_GetVRootGeometry(tkwin, &x, &y, &width, &height); + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), y); + break; + } + case WIN_WIDTH: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), Tk_Width(tkwin)); + break; + } + case WIN_X: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), Tk_X(tkwin)); + break; + } + case WIN_Y: { + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), Tk_Y(tkwin)); + break; + } + + /* + * Uses -displayof. + */ + + case WIN_ATOM: { + skip = TkGetDisplayOf(interp, objc - 2, objv + 2, &tkwin); + if (skip < 0) { + return TCL_ERROR; + } + if (objc - skip != 3) { + Tcl_WrongNumArgs(interp, 2, objv, "?-displayof window? name"); + return TCL_ERROR; + } + objv += skip; + string = Tcl_GetStringFromObj(objv[2], NULL); + Tcl_ResetResult(interp); + Tcl_SetLongObj(Tcl_GetObjResult(interp), + (long) Tk_InternAtom(tkwin, string)); + break; + } + case WIN_ATOMNAME: { + char *name; + long id; + + skip = TkGetDisplayOf(interp, objc - 2, objv + 2, &tkwin); + if (skip < 0) { + return TCL_ERROR; + } + if (objc - skip != 3) { + Tcl_WrongNumArgs(interp, 2, objv, "?-displayof window? id"); + return TCL_ERROR; + } + objv += skip; + if (Tcl_GetLongFromObj(interp, objv[2], &id) != TCL_OK) { + return TCL_ERROR; + } + Tcl_ResetResult(interp); + name = Tk_GetAtomName(tkwin, (Atom) id); + if (strcmp(name, "?bad atom?") == 0) { + string = Tcl_GetStringFromObj(objv[2], NULL); + Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), + "no atom exists with id \"", string, "\"", NULL); + return TCL_ERROR; + } + Tcl_SetStringObj(Tcl_GetObjResult(interp), name, -1); + break; + } + case WIN_CONTAINING: { + skip = TkGetDisplayOf(interp, objc - 2, objv + 2, &tkwin); + if (skip < 0) { + return TCL_ERROR; + } + if (objc - skip != 4) { + Tcl_WrongNumArgs(interp, 2, objv, + "?-displayof window? rootX rootY"); + return TCL_ERROR; + } + objv += skip; + string = Tcl_GetStringFromObj(objv[2], NULL); + if (Tk_GetPixels(interp, tkwin, string, &x) != TCL_OK) { + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[3], NULL); + if (Tk_GetPixels(interp, tkwin, string, &y) != TCL_OK) { + return TCL_ERROR; + } + tkwin = Tk_CoordsToWindow(x, y, tkwin); + if (tkwin != NULL) { + Tcl_ResetResult(interp); + Tcl_SetStringObj(Tcl_GetObjResult(interp), + Tk_PathName(tkwin), -1); + } + break; + } + case WIN_INTERPS: { + int result; + + skip = TkGetDisplayOf(interp, objc - 2, objv + 2, &tkwin); + if (skip < 0) { + return TCL_ERROR; + } + if (objc - skip != 2) { + Tcl_WrongNumArgs(interp, 2, objv, "?-displayof window?"); + return TCL_ERROR; + } + result = TkGetInterpNames(interp, tkwin); + return result; + } + case WIN_PATHNAME: { + int id; + + skip = TkGetDisplayOf(interp, objc - 2, objv + 2, &tkwin); + if (skip < 0) { + return TCL_ERROR; + } + if (objc - skip != 3) { + Tcl_WrongNumArgs(interp, 2, objv, "?-displayof window? id"); + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[2 + skip], NULL); + if (TkpScanWindowId(interp, string, &id) != TCL_OK) { + return TCL_ERROR; + } + winPtr = (TkWindow *) + Tk_IdToWindow(Tk_Display(tkwin), (Window) id); + if ((winPtr == NULL) || + (winPtr->mainPtr != ((TkWindow *) tkwin)->mainPtr)) { + Tcl_ResetResult(interp); + Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), + "window id \"", string, + "\" doesn't exist in this application", (char *) NULL); + return TCL_ERROR; + } + + /* + * If the window is a utility window with no associated path + * (such as a wrapper window or send communication window), just + * return an empty string. + */ + + tkwin = (Tk_Window) winPtr; + if (Tk_PathName(tkwin) != NULL) { + Tcl_ResetResult(interp); + Tcl_SetStringObj(Tcl_GetObjResult(interp), + Tk_PathName(tkwin), -1); + } + break; + } + + /* + * objv[3] is window. + */ + + case WIN_EXISTS: { + int alive; + + if (objc != 3) { + Tcl_WrongNumArgs(interp, 2, objv, "window"); + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[2], NULL); + winPtr = (TkWindow *) Tk_NameToWindow(interp, string, tkwin); + alive = 1; + if ((winPtr == NULL) || (winPtr->flags & TK_ALREADY_DEAD)) { + alive = 0; + } + Tcl_ResetResult(interp); /* clear any error msg */ + Tcl_SetBooleanObj(Tcl_GetObjResult(interp), alive); + break; + } + case WIN_FPIXELS: { + double mm, pixels; + + if (objc != 4) { + Tcl_WrongNumArgs(interp, 2, objv, "window number"); + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[2], NULL); + tkwin = Tk_NameToWindow(interp, string, tkwin); + if (tkwin == NULL) { + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[3], NULL); + if (Tk_GetScreenMM(interp, tkwin, string, &mm) != TCL_OK) { + return TCL_ERROR; + } + pixels = mm * WidthOfScreen(Tk_Screen(tkwin)) + / WidthMMOfScreen(Tk_Screen(tkwin)); + Tcl_ResetResult(interp); + Tcl_SetDoubleObj(Tcl_GetObjResult(interp), pixels); + break; + } + case WIN_PIXELS: { + int pixels; + + if (objc != 4) { + Tcl_WrongNumArgs(interp, 2, objv, "window number"); + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[2], NULL); + tkwin = Tk_NameToWindow(interp, string, tkwin); + if (tkwin == NULL) { + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[3], NULL); + if (Tk_GetPixels(interp, tkwin, string, &pixels) != TCL_OK) { + return TCL_ERROR; + } + Tcl_ResetResult(interp); + Tcl_SetIntObj(Tcl_GetObjResult(interp), pixels); + break; + } + case WIN_RGB: { + XColor *colorPtr; + + if (objc != 4) { + Tcl_WrongNumArgs(interp, 2, objv, "window colorName"); + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[2], NULL); + tkwin = Tk_NameToWindow(interp, string, tkwin); + if (tkwin == NULL) { + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[3], NULL); + colorPtr = Tk_GetColor(interp, tkwin, string); + if (colorPtr == NULL) { + return TCL_ERROR; + } + sprintf(buf, "%d %d %d", colorPtr->red, colorPtr->green, + colorPtr->blue); + Tk_FreeColor(colorPtr); + Tcl_ResetResult(interp); + Tcl_SetStringObj(Tcl_GetObjResult(interp), buf, -1); + break; + } + case WIN_VISUALSAVAILABLE: { + XVisualInfo template, *visInfoPtr; + int count, i; + char visualIdString[16]; + int includeVisualId; + Tcl_Obj *strPtr; + + if (objc == 3) { + includeVisualId = 0; + } else if ((objc == 4) + && (strcmp(Tcl_GetStringFromObj(objv[3], NULL), + "includeids") == 0)) { + includeVisualId = 1; + } else { + Tcl_WrongNumArgs(interp, 2, objv, "window ?includeids?"); + return TCL_ERROR; + } + + string = Tcl_GetStringFromObj(objv[2], NULL); + tkwin = Tk_NameToWindow(interp, string, tkwin); + if (tkwin == NULL) { + return TCL_ERROR; + } + + template.screen = Tk_ScreenNumber(tkwin); + visInfoPtr = XGetVisualInfo(Tk_Display(tkwin), VisualScreenMask, + &template, &count); + Tcl_ResetResult(interp); + if (visInfoPtr == NULL) { + Tcl_SetStringObj(Tcl_GetObjResult(interp), + "can't find any visuals for screen", -1); + return TCL_ERROR; + } + for (i = 0; i < count; i++) { + string = TkFindStateString(visualMap, visInfoPtr[i].class); + if (string == NULL) { + strcpy(buf, "unknown"); + } else { + sprintf(buf, "%s %d", string, visInfoPtr[i].depth); + } + if (includeVisualId) { + sprintf(visualIdString, " 0x%x", + (unsigned int) visInfoPtr[i].visualid); + strcat(buf, visualIdString); + } + strPtr = Tcl_NewStringObj(buf, -1); + Tcl_ListObjAppendElement(NULL, Tcl_GetObjResult(interp), + strPtr); + } + XFree((char *) visInfoPtr); + break; + } + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkGetDisplayOf -- + * + * Parses a "-displayof window" option for various commands. If + * present, the literal "-displayof" should be in objv[0] and the + * window name in objv[1]. + * + * Results: + * The return value is 0 if the argument strings did not contain + * the "-displayof" option. The return value is 2 if the + * argument strings contained both the "-displayof" option and + * a valid window name. Otherwise, the return value is -1 if + * the window name was missing or did not specify a valid window. + * + * If the return value was 2, *tkwinPtr is filled with the + * token for the window specified on the command line. If the + * return value was -1, an error message is left in interp's + * result object. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkGetDisplayOf(interp, objc, objv, tkwinPtr) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. If it is present, + * "-displayof" should be in objv[0] and + * objv[1] the name of a window. */ + Tk_Window *tkwinPtr; /* On input, contains main window of + * application associated with interp. On + * output, filled with window specified as + * option to "-displayof" argument, or + * unmodified if "-displayof" argument was not + * present. */ +{ + char *string; + int length; + + if (objc < 1) { + return 0; + } + string = Tcl_GetStringFromObj(objv[0], &length); + if ((length >= 2) && (strncmp(string, "-displayof", (unsigned) length) == 0)) { + if (objc < 2) { + Tcl_SetStringObj(Tcl_GetObjResult(interp), + "value for \"-displayof\" missing", -1); + return -1; + } + string = Tcl_GetStringFromObj(objv[1], NULL); + *tkwinPtr = Tk_NameToWindow(interp, string, *tkwinPtr); + if (*tkwinPtr == NULL) { + return -1; + } + return 2; + } + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * TkDeadAppCmd -- + * + * If an application has been deleted then all Tk commands will be + * re-bound to this procedure. + * + * Results: + * A standard Tcl error is reported to let the user know that + * the application is dead. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +TkDeadAppCmd(clientData, interp, argc, argv) + ClientData clientData; /* Dummy. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tcl_AppendResult(interp, "can't invoke \"", argv[0], + "\" command: application has been destroyed", (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * GetToplevel -- + * + * Retrieves the toplevel window which is the nearest ancestor of + * of the specified window. + * + * Results: + * Returns the toplevel window or NULL if the window has no + * ancestor which is a toplevel. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static TkWindow * +GetToplevel(tkwin) + Tk_Window tkwin; /* Window for which the toplevel should be + * deterined. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + + while (!(winPtr->flags & TK_TOP_LEVEL)) { + winPtr = winPtr->parentPtr; + if (winPtr == NULL) { + return NULL; + } + } + return winPtr; +} diff --git a/generic/tkColor.c b/generic/tkColor.c new file mode 100644 index 0000000..781971c --- /dev/null +++ b/generic/tkColor.c @@ -0,0 +1,397 @@ +/* + * tkColor.c -- + * + * This file maintains a database of color values for the Tk + * toolkit, in order to avoid round-trips to the server to + * map color names to pixel values. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkColor.c 1.44 96/11/04 13:55:25 + */ + +#include <tkColor.h> + +/* + * A two-level data structure is used to manage the color database. + * The top level consists of one entry for each color name that is + * currently active, and the bottom level contains one entry for each + * pixel value that is still in use. The distinction between + * levels is necessary because the same pixel may have several + * different names. There are two hash tables, one used to index into + * each of the data structures. The name hash table is used when + * allocating colors, and the pixel hash table is used when freeing + * colors. + */ + + +/* + * Hash table for name -> TkColor mapping, and key structure used to + * index into that table: + */ + +static Tcl_HashTable nameTable; +typedef struct { + Tk_Uid name; /* Name of desired color. */ + Colormap colormap; /* Colormap from which color will be + * allocated. */ + Display *display; /* Display for colormap. */ +} NameKey; + +/* + * Hash table for value -> TkColor mapping, and key structure used to + * index into that table: + */ + +static Tcl_HashTable valueTable; +typedef struct { + int red, green, blue; /* Values for desired color. */ + Colormap colormap; /* Colormap from which color will be + * allocated. */ + Display *display; /* Display for colormap. */ +} ValueKey; + +static int initialized = 0; /* 0 means static structures haven't been + * initialized yet. */ + +/* + * Forward declarations for procedures defined in this file: + */ + +static void ColorInit _ANSI_ARGS_((void)); + +/* + *---------------------------------------------------------------------- + * + * Tk_GetColor -- + * + * Given a string name for a color, map the name to a corresponding + * XColor structure. + * + * Results: + * The return value is a pointer to an XColor structure that + * indicates the red, blue, and green intensities for the color + * given by "name", and also specifies a pixel value to use to + * draw in that color. If an error occurs, NULL is returned and + * an error message will be left in interp->result. + * + * Side effects: + * The color is added to an internal database with a reference count. + * For each call to this procedure, there should eventually be a call + * to Tk_FreeColor so that the database is cleaned up when colors + * aren't in use anymore. + * + *---------------------------------------------------------------------- + */ + +XColor * +Tk_GetColor(interp, tkwin, name) + Tcl_Interp *interp; /* Place to leave error message if + * color can't be found. */ + Tk_Window tkwin; /* Window in which color will be used. */ + Tk_Uid name; /* Name of color to allocated (in form + * suitable for passing to XParseColor). */ +{ + NameKey nameKey; + Tcl_HashEntry *nameHashPtr; + int new; + TkColor *tkColPtr; + Display *display = Tk_Display(tkwin); + + if (!initialized) { + ColorInit(); + } + + /* + * First, check to see if there's already a mapping for this color + * name. + */ + + nameKey.name = name; + nameKey.colormap = Tk_Colormap(tkwin); + nameKey.display = display; + nameHashPtr = Tcl_CreateHashEntry(&nameTable, (char *) &nameKey, &new); + if (!new) { + tkColPtr = (TkColor *) Tcl_GetHashValue(nameHashPtr); + tkColPtr->refCount++; + return &tkColPtr->color; + } + + /* + * The name isn't currently known. Map from the name to a pixel + * value. + */ + + tkColPtr = TkpGetColor(tkwin, name); + if (tkColPtr == NULL) { + if (interp != NULL) { + if (*name == '#') { + Tcl_AppendResult(interp, "invalid color name \"", name, + "\"", (char *) NULL); + } else { + Tcl_AppendResult(interp, "unknown color name \"", name, + "\"", (char *) NULL); + } + } + Tcl_DeleteHashEntry(nameHashPtr); + return (XColor *) NULL; + } + + /* + * Now create a new TkColor structure and add it to nameTable. + */ + + tkColPtr->magic = COLOR_MAGIC; + tkColPtr->gc = None; + tkColPtr->screen = Tk_Screen(tkwin); + tkColPtr->colormap = nameKey.colormap; + tkColPtr->visual = Tk_Visual(tkwin); + tkColPtr->refCount = 1; + tkColPtr->tablePtr = &nameTable; + tkColPtr->hashPtr = nameHashPtr; + Tcl_SetHashValue(nameHashPtr, tkColPtr); + + return &tkColPtr->color; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetColorByValue -- + * + * Given a desired set of red-green-blue intensities for a color, + * locate a pixel value to use to draw that color in a given + * window. + * + * Results: + * The return value is a pointer to an XColor structure that + * indicates the closest red, blue, and green intensities available + * to those specified in colorPtr, and also specifies a pixel + * value to use to draw in that color. + * + * Side effects: + * The color is added to an internal database with a reference count. + * For each call to this procedure, there should eventually be a call + * to Tk_FreeColor, so that the database is cleaned up when colors + * aren't in use anymore. + * + *---------------------------------------------------------------------- + */ + +XColor * +Tk_GetColorByValue(tkwin, colorPtr) + Tk_Window tkwin; /* Window where color will be used. */ + XColor *colorPtr; /* Red, green, and blue fields indicate + * desired color. */ +{ + ValueKey valueKey; + Tcl_HashEntry *valueHashPtr; + int new; + TkColor *tkColPtr; + Display *display = Tk_Display(tkwin); + + if (!initialized) { + ColorInit(); + } + + /* + * First, check to see if there's already a mapping for this color + * name. + */ + + valueKey.red = colorPtr->red; + valueKey.green = colorPtr->green; + valueKey.blue = colorPtr->blue; + valueKey.colormap = Tk_Colormap(tkwin); + valueKey.display = display; + valueHashPtr = Tcl_CreateHashEntry(&valueTable, (char *) &valueKey, &new); + if (!new) { + tkColPtr = (TkColor *) Tcl_GetHashValue(valueHashPtr); + tkColPtr->refCount++; + return &tkColPtr->color; + } + + /* + * The name isn't currently known. Find a pixel value for this + * color and add a new structure to valueTable. + */ + + tkColPtr = TkpGetColorByValue(tkwin, colorPtr); + tkColPtr->magic = COLOR_MAGIC; + tkColPtr->gc = None; + tkColPtr->screen = Tk_Screen(tkwin); + tkColPtr->colormap = valueKey.colormap; + tkColPtr->visual = Tk_Visual(tkwin); + tkColPtr->refCount = 1; + tkColPtr->tablePtr = &valueTable; + tkColPtr->hashPtr = valueHashPtr; + Tcl_SetHashValue(valueHashPtr, tkColPtr); + return &tkColPtr->color; +} + +/* + *-------------------------------------------------------------- + * + * Tk_NameOfColor -- + * + * Given a color, return a textual string identifying + * the color. + * + * Results: + * If colorPtr was created by Tk_GetColor, then the return + * value is the "string" that was used to create it. + * Otherwise the return value is a string that could have + * been passed to Tk_GetColor to allocate that color. The + * storage for the returned string is only guaranteed to + * persist up until the next call to this procedure. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_NameOfColor(colorPtr) + XColor *colorPtr; /* Color whose name is desired. */ +{ + register TkColor *tkColPtr = (TkColor *) colorPtr; + static char string[20]; + + if ((tkColPtr->magic == COLOR_MAGIC) + && (tkColPtr->tablePtr == &nameTable)) { + return ((NameKey *) tkColPtr->hashPtr->key.words)->name; + } + sprintf(string, "#%04x%04x%04x", colorPtr->red, colorPtr->green, + colorPtr->blue); + return string; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GCForColor -- + * + * Given a color allocated from this module, this procedure + * returns a GC that can be used for simple drawing with that + * color. + * + * Results: + * The return value is a GC with color set as its foreground + * color and all other fields defaulted. This GC is only valid + * as long as the color exists; it is freed automatically when + * the last reference to the color is freed. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +GC +Tk_GCForColor(colorPtr, drawable) + XColor *colorPtr; /* Color for which a GC is desired. Must + * have been allocated by Tk_GetColor or + * Tk_GetColorByName. */ + Drawable drawable; /* Drawable in which the color will be + * used (must have same screen and depth + * as the one for which the color was + * allocated). */ +{ + TkColor *tkColPtr = (TkColor *) colorPtr; + XGCValues gcValues; + + /* + * Do a quick sanity check to make sure this color was really + * allocated by Tk_GetColor. + */ + + if (tkColPtr->magic != COLOR_MAGIC) { + panic("Tk_GCForColor called with bogus color"); + } + + if (tkColPtr->gc == None) { + gcValues.foreground = tkColPtr->color.pixel; + tkColPtr->gc = XCreateGC(DisplayOfScreen(tkColPtr->screen), + drawable, GCForeground, &gcValues); + } + return tkColPtr->gc; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreeColor -- + * + * This procedure is called to release a color allocated by + * Tk_GetColor. + * + * Results: + * None. + * + * Side effects: + * The reference count associated with colorPtr is deleted, and + * the color is released to X if there are no remaining uses + * for it. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreeColor(colorPtr) + XColor *colorPtr; /* Color to be released. Must have been + * allocated by Tk_GetColor or + * Tk_GetColorByValue. */ +{ + register TkColor *tkColPtr = (TkColor *) colorPtr; + Screen *screen = tkColPtr->screen; + + /* + * Do a quick sanity check to make sure this color was really + * allocated by Tk_GetColor. + */ + + if (tkColPtr->magic != COLOR_MAGIC) { + panic("Tk_FreeColor called with bogus color"); + } + + tkColPtr->refCount--; + if (tkColPtr->refCount == 0) { + if (tkColPtr->gc != None) { + XFreeGC(DisplayOfScreen(screen), tkColPtr->gc); + tkColPtr->gc = None; + } + TkpFreeColor(tkColPtr); + Tcl_DeleteHashEntry(tkColPtr->hashPtr); + tkColPtr->magic = 0; + ckfree((char *) tkColPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * ColorInit -- + * + * Initialize the structure used for color management. + * + * Results: + * None. + * + * Side effects: + * Read the code. + * + *---------------------------------------------------------------------- + */ + +static void +ColorInit() +{ + initialized = 1; + Tcl_InitHashTable(&nameTable, sizeof(NameKey)/sizeof(int)); + Tcl_InitHashTable(&valueTable, sizeof(ValueKey)/sizeof(int)); +} diff --git a/generic/tkColor.h b/generic/tkColor.h new file mode 100644 index 0000000..9653243 --- /dev/null +++ b/generic/tkColor.h @@ -0,0 +1,60 @@ +/* + * tkColor.h -- + * + * Declarations of data types and functions used by the + * Tk color module. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkColor.h 1.1 96/10/22 16:53:09 + */ + +#ifndef _TKCOLOR +#define _TKCOLOR + +#include <tkInt.h> + +/* + * One of the following data structures is used to keep track of + * each color that the color module has allocated from the X display + * server. + */ + +#define COLOR_MAGIC ((unsigned int) 0x46140277) + +typedef struct TkColor { + XColor color; /* Information about this color. */ + unsigned int magic; /* Used for quick integrity check on this + * structure. Must always have the + * value COLOR_MAGIC. */ + GC gc; /* Simple gc with this color as foreground + * color and all other fields defaulted. + * May be None. */ + Screen *screen; /* Screen where this color is valid. Used + * to delete it, and to find its display. */ + Colormap colormap; /* Colormap from which this entry was + * allocated. */ + Visual *visual; /* Visual associated with colormap. */ + int refCount; /* Number of uses of this structure. */ + Tcl_HashTable *tablePtr; /* Hash table that indexes this structure + * (needed when deleting structure). */ + Tcl_HashEntry *hashPtr; /* Pointer to hash table entry for this + * structure. (for use in deleting entry). */ +} TkColor; + +/* + * Common APIs exported from all platform-specific implementations. + */ + +#ifndef TkpFreeColor +EXTERN void TkpFreeColor _ANSI_ARGS_((TkColor *tkColPtr)); +#endif +EXTERN TkColor * TkpGetColor _ANSI_ARGS_((Tk_Window tkwin, + Tk_Uid name)); +EXTERN TkColor * TkpGetColorByValue _ANSI_ARGS_((Tk_Window tkwin, + XColor *colorPtr)); + +#endif /* _TKCOLOR */ diff --git a/generic/tkConfig.c b/generic/tkConfig.c new file mode 100644 index 0000000..2204714 --- /dev/null +++ b/generic/tkConfig.c @@ -0,0 +1,990 @@ +/* + * tkConfig.c -- + * + * This file contains the Tk_ConfigureWidget procedure. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkConfig.c 1.53 96/04/26 10:29:31 + */ + +#include "tkPort.h" +#include "tk.h" + +/* + * Values for "flags" field of Tk_ConfigSpec structures. Be sure + * to coordinate these values with those defined in tk.h + * (TK_CONFIG_COLOR_ONLY, etc.). There must not be overlap! + * + * INIT - Non-zero means (char *) things have been + * converted to Tk_Uid's. + */ + +#define INIT 0x20 + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int DoConfig _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_ConfigSpec *specPtr, + Tk_Uid value, int valueIsUid, char *widgRec)); +static Tk_ConfigSpec * FindConfigSpec _ANSI_ARGS_((Tcl_Interp *interp, + Tk_ConfigSpec *specs, char *argvName, + int needFlags, int hateFlags)); +static char * FormatConfigInfo _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_ConfigSpec *specPtr, + char *widgRec)); +static char * FormatConfigValue _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_ConfigSpec *specPtr, + char *widgRec, char *buffer, + Tcl_FreeProc **freeProcPtr)); + +/* + *-------------------------------------------------------------- + * + * Tk_ConfigureWidget -- + * + * Process command-line options and database options to + * fill in fields of a widget record with resources and + * other parameters. + * + * Results: + * A standard Tcl return value. In case of an error, + * interp->result will hold an error message. + * + * Side effects: + * The fields of widgRec get filled in with information + * from argc/argv and the option database. Old information + * in widgRec's fields gets recycled. + * + *-------------------------------------------------------------- + */ + +int +Tk_ConfigureWidget(interp, tkwin, specs, argc, argv, widgRec, flags) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Window tkwin; /* Window containing widget (needed to + * set up X resources). */ + Tk_ConfigSpec *specs; /* Describes legal options. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Command-line options. */ + char *widgRec; /* Record whose fields are to be + * modified. Values must be properly + * initialized. */ + int flags; /* Used to specify additional flags + * that must be present in config specs + * for them to be considered. Also, + * may have TK_CONFIG_ARGV_ONLY set. */ +{ + register Tk_ConfigSpec *specPtr; + Tk_Uid value; /* Value of option from database. */ + int needFlags; /* Specs must contain this set of flags + * or else they are not considered. */ + int hateFlags; /* If a spec contains any bits here, it's + * not considered. */ + + needFlags = flags & ~(TK_CONFIG_USER_BIT - 1); + if (Tk_Depth(tkwin) <= 1) { + hateFlags = TK_CONFIG_COLOR_ONLY; + } else { + hateFlags = TK_CONFIG_MONO_ONLY; + } + + /* + * Pass one: scan through all the option specs, replacing strings + * with Tk_Uids (if this hasn't been done already) and clearing + * the TK_CONFIG_OPTION_SPECIFIED flags. + */ + + for (specPtr = specs; specPtr->type != TK_CONFIG_END; specPtr++) { + if (!(specPtr->specFlags & INIT) && (specPtr->argvName != NULL)) { + if (specPtr->dbName != NULL) { + specPtr->dbName = Tk_GetUid(specPtr->dbName); + } + if (specPtr->dbClass != NULL) { + specPtr->dbClass = Tk_GetUid(specPtr->dbClass); + } + if (specPtr->defValue != NULL) { + specPtr->defValue = Tk_GetUid(specPtr->defValue); + } + } + specPtr->specFlags = (specPtr->specFlags & ~TK_CONFIG_OPTION_SPECIFIED) + | INIT; + } + + /* + * Pass two: scan through all of the arguments, processing those + * that match entries in the specs. + */ + + for ( ; argc > 0; argc -= 2, argv += 2) { + specPtr = FindConfigSpec(interp, specs, *argv, needFlags, hateFlags); + if (specPtr == NULL) { + return TCL_ERROR; + } + + /* + * Process the entry. + */ + + if (argc < 2) { + Tcl_AppendResult(interp, "value for \"", *argv, + "\" missing", (char *) NULL); + return TCL_ERROR; + } + if (DoConfig(interp, tkwin, specPtr, argv[1], 0, widgRec) != TCL_OK) { + char msg[100]; + + sprintf(msg, "\n (processing \"%.40s\" option)", + specPtr->argvName); + Tcl_AddErrorInfo(interp, msg); + return TCL_ERROR; + } + specPtr->specFlags |= TK_CONFIG_OPTION_SPECIFIED; + } + + /* + * Pass three: scan through all of the specs again; if no + * command-line argument matched a spec, then check for info + * in the option database. If there was nothing in the + * database, then use the default. + */ + + if (!(flags & TK_CONFIG_ARGV_ONLY)) { + for (specPtr = specs; specPtr->type != TK_CONFIG_END; specPtr++) { + if ((specPtr->specFlags & TK_CONFIG_OPTION_SPECIFIED) + || (specPtr->argvName == NULL) + || (specPtr->type == TK_CONFIG_SYNONYM)) { + continue; + } + if (((specPtr->specFlags & needFlags) != needFlags) + || (specPtr->specFlags & hateFlags)) { + continue; + } + value = NULL; + if (specPtr->dbName != NULL) { + value = Tk_GetOption(tkwin, specPtr->dbName, specPtr->dbClass); + } + if (value != NULL) { + if (DoConfig(interp, tkwin, specPtr, value, 1, widgRec) != + TCL_OK) { + char msg[200]; + + sprintf(msg, "\n (%s \"%.50s\" in widget \"%.50s\")", + "database entry for", + specPtr->dbName, Tk_PathName(tkwin)); + Tcl_AddErrorInfo(interp, msg); + return TCL_ERROR; + } + } else { + value = specPtr->defValue; + if ((value != NULL) && !(specPtr->specFlags + & TK_CONFIG_DONT_SET_DEFAULT)) { + if (DoConfig(interp, tkwin, specPtr, value, 1, widgRec) != + TCL_OK) { + char msg[200]; + + sprintf(msg, + "\n (%s \"%.50s\" in widget \"%.50s\")", + "default value for", + specPtr->dbName, Tk_PathName(tkwin)); + Tcl_AddErrorInfo(interp, msg); + return TCL_ERROR; + } + } + } + } + } + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * FindConfigSpec -- + * + * Search through a table of configuration specs, looking for + * one that matches a given argvName. + * + * Results: + * The return value is a pointer to the matching entry, or NULL + * if nothing matched. In that case an error message is left + * in interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static Tk_ConfigSpec * +FindConfigSpec(interp, specs, argvName, needFlags, hateFlags) + Tcl_Interp *interp; /* Used for reporting errors. */ + Tk_ConfigSpec *specs; /* Pointer to table of configuration + * specifications for a widget. */ + char *argvName; /* Name (suitable for use in a "config" + * command) identifying particular option. */ + int needFlags; /* Flags that must be present in matching + * entry. */ + int hateFlags; /* Flags that must NOT be present in + * matching entry. */ +{ + register Tk_ConfigSpec *specPtr; + register char c; /* First character of current argument. */ + Tk_ConfigSpec *matchPtr; /* Matching spec, or NULL. */ + size_t length; + + c = argvName[1]; + length = strlen(argvName); + matchPtr = NULL; + for (specPtr = specs; specPtr->type != TK_CONFIG_END; specPtr++) { + if (specPtr->argvName == NULL) { + continue; + } + if ((specPtr->argvName[1] != c) + || (strncmp(specPtr->argvName, argvName, length) != 0)) { + continue; + } + if (((specPtr->specFlags & needFlags) != needFlags) + || (specPtr->specFlags & hateFlags)) { + continue; + } + if (specPtr->argvName[length] == 0) { + matchPtr = specPtr; + goto gotMatch; + } + if (matchPtr != NULL) { + Tcl_AppendResult(interp, "ambiguous option \"", argvName, + "\"", (char *) NULL); + return (Tk_ConfigSpec *) NULL; + } + matchPtr = specPtr; + } + + if (matchPtr == NULL) { + Tcl_AppendResult(interp, "unknown option \"", argvName, + "\"", (char *) NULL); + return (Tk_ConfigSpec *) NULL; + } + + /* + * Found a matching entry. If it's a synonym, then find the + * entry that it's a synonym for. + */ + + gotMatch: + specPtr = matchPtr; + if (specPtr->type == TK_CONFIG_SYNONYM) { + for (specPtr = specs; ; specPtr++) { + if (specPtr->type == TK_CONFIG_END) { + Tcl_AppendResult(interp, + "couldn't find synonym for option \"", + argvName, "\"", (char *) NULL); + return (Tk_ConfigSpec *) NULL; + } + if ((specPtr->dbName == matchPtr->dbName) + && (specPtr->type != TK_CONFIG_SYNONYM) + && ((specPtr->specFlags & needFlags) == needFlags) + && !(specPtr->specFlags & hateFlags)) { + break; + } + } + } + return specPtr; +} + +/* + *-------------------------------------------------------------- + * + * DoConfig -- + * + * This procedure applies a single configuration option + * to a widget record. + * + * Results: + * A standard Tcl return value. + * + * Side effects: + * WidgRec is modified as indicated by specPtr and value. + * The old value is recycled, if that is appropriate for + * the value type. + * + *-------------------------------------------------------------- + */ + +static int +DoConfig(interp, tkwin, specPtr, value, valueIsUid, widgRec) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Window tkwin; /* Window containing widget (needed to + * set up X resources). */ + Tk_ConfigSpec *specPtr; /* Specifier to apply. */ + char *value; /* Value to use to fill in widgRec. */ + int valueIsUid; /* Non-zero means value is a Tk_Uid; + * zero means it's an ordinary string. */ + char *widgRec; /* Record whose fields are to be + * modified. Values must be properly + * initialized. */ +{ + char *ptr; + Tk_Uid uid; + int nullValue; + + nullValue = 0; + if ((*value == 0) && (specPtr->specFlags & TK_CONFIG_NULL_OK)) { + nullValue = 1; + } + + do { + ptr = widgRec + specPtr->offset; + switch (specPtr->type) { + case TK_CONFIG_BOOLEAN: + if (Tcl_GetBoolean(interp, value, (int *) ptr) != TCL_OK) { + return TCL_ERROR; + } + break; + case TK_CONFIG_INT: + if (Tcl_GetInt(interp, value, (int *) ptr) != TCL_OK) { + return TCL_ERROR; + } + break; + case TK_CONFIG_DOUBLE: + if (Tcl_GetDouble(interp, value, (double *) ptr) != TCL_OK) { + return TCL_ERROR; + } + break; + case TK_CONFIG_STRING: { + char *old, *new; + + if (nullValue) { + new = NULL; + } else { + new = (char *) ckalloc((unsigned) (strlen(value) + 1)); + strcpy(new, value); + } + old = *((char **) ptr); + if (old != NULL) { + ckfree(old); + } + *((char **) ptr) = new; + break; + } + case TK_CONFIG_UID: + if (nullValue) { + *((Tk_Uid *) ptr) = NULL; + } else { + uid = valueIsUid ? (Tk_Uid) value : Tk_GetUid(value); + *((Tk_Uid *) ptr) = uid; + } + break; + case TK_CONFIG_COLOR: { + XColor *newPtr, *oldPtr; + + if (nullValue) { + newPtr = NULL; + } else { + uid = valueIsUid ? (Tk_Uid) value : Tk_GetUid(value); + newPtr = Tk_GetColor(interp, tkwin, uid); + if (newPtr == NULL) { + return TCL_ERROR; + } + } + oldPtr = *((XColor **) ptr); + if (oldPtr != NULL) { + Tk_FreeColor(oldPtr); + } + *((XColor **) ptr) = newPtr; + break; + } + case TK_CONFIG_FONT: { + Tk_Font new; + + if (nullValue) { + new = NULL; + } else { + new = Tk_GetFont(interp, tkwin, value); + if (new == NULL) { + return TCL_ERROR; + } + } + Tk_FreeFont(*((Tk_Font *) ptr)); + *((Tk_Font *) ptr) = new; + break; + } + case TK_CONFIG_BITMAP: { + Pixmap new, old; + + if (nullValue) { + new = None; + } else { + uid = valueIsUid ? (Tk_Uid) value : Tk_GetUid(value); + new = Tk_GetBitmap(interp, tkwin, uid); + if (new == None) { + return TCL_ERROR; + } + } + old = *((Pixmap *) ptr); + if (old != None) { + Tk_FreeBitmap(Tk_Display(tkwin), old); + } + *((Pixmap *) ptr) = new; + break; + } + case TK_CONFIG_BORDER: { + Tk_3DBorder new, old; + + if (nullValue) { + new = NULL; + } else { + uid = valueIsUid ? (Tk_Uid) value : Tk_GetUid(value); + new = Tk_Get3DBorder(interp, tkwin, uid); + if (new == NULL) { + return TCL_ERROR; + } + } + old = *((Tk_3DBorder *) ptr); + if (old != NULL) { + Tk_Free3DBorder(old); + } + *((Tk_3DBorder *) ptr) = new; + break; + } + case TK_CONFIG_RELIEF: + uid = valueIsUid ? (Tk_Uid) value : Tk_GetUid(value); + if (Tk_GetRelief(interp, uid, (int *) ptr) != TCL_OK) { + return TCL_ERROR; + } + break; + case TK_CONFIG_CURSOR: + case TK_CONFIG_ACTIVE_CURSOR: { + Tk_Cursor new, old; + + if (nullValue) { + new = None; + } else { + uid = valueIsUid ? (Tk_Uid) value : Tk_GetUid(value); + new = Tk_GetCursor(interp, tkwin, uid); + if (new == None) { + return TCL_ERROR; + } + } + old = *((Tk_Cursor *) ptr); + if (old != None) { + Tk_FreeCursor(Tk_Display(tkwin), old); + } + *((Tk_Cursor *) ptr) = new; + if (specPtr->type == TK_CONFIG_ACTIVE_CURSOR) { + Tk_DefineCursor(tkwin, new); + } + break; + } + case TK_CONFIG_JUSTIFY: + uid = valueIsUid ? (Tk_Uid) value : Tk_GetUid(value); + if (Tk_GetJustify(interp, uid, (Tk_Justify *) ptr) != TCL_OK) { + return TCL_ERROR; + } + break; + case TK_CONFIG_ANCHOR: + uid = valueIsUid ? (Tk_Uid) value : Tk_GetUid(value); + if (Tk_GetAnchor(interp, uid, (Tk_Anchor *) ptr) != TCL_OK) { + return TCL_ERROR; + } + break; + case TK_CONFIG_CAP_STYLE: + uid = valueIsUid ? (Tk_Uid) value : Tk_GetUid(value); + if (Tk_GetCapStyle(interp, uid, (int *) ptr) != TCL_OK) { + return TCL_ERROR; + } + break; + case TK_CONFIG_JOIN_STYLE: + uid = valueIsUid ? (Tk_Uid) value : Tk_GetUid(value); + if (Tk_GetJoinStyle(interp, uid, (int *) ptr) != TCL_OK) { + return TCL_ERROR; + } + break; + case TK_CONFIG_PIXELS: + if (Tk_GetPixels(interp, tkwin, value, (int *) ptr) + != TCL_OK) { + return TCL_ERROR; + } + break; + case TK_CONFIG_MM: + if (Tk_GetScreenMM(interp, tkwin, value, (double *) ptr) + != TCL_OK) { + return TCL_ERROR; + } + break; + case TK_CONFIG_WINDOW: { + Tk_Window tkwin2; + + if (nullValue) { + tkwin2 = NULL; + } else { + tkwin2 = Tk_NameToWindow(interp, value, tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + } + *((Tk_Window *) ptr) = tkwin2; + break; + } + case TK_CONFIG_CUSTOM: + if ((*specPtr->customPtr->parseProc)( + specPtr->customPtr->clientData, interp, tkwin, + value, widgRec, specPtr->offset) != TCL_OK) { + return TCL_ERROR; + } + break; + default: { + sprintf(interp->result, "bad config table: unknown type %d", + specPtr->type); + return TCL_ERROR; + } + } + specPtr++; + } while ((specPtr->argvName == NULL) && (specPtr->type != TK_CONFIG_END)); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * Tk_ConfigureInfo -- + * + * Return information about the configuration options + * for a window, and their current values. + * + * Results: + * Always returns TCL_OK. Interp->result will be modified + * hold a description of either a single configuration option + * available for "widgRec" via "specs", or all the configuration + * options available. In the "all" case, the result will + * available for "widgRec" via "specs". The result will + * be a list, each of whose entries describes one option. + * Each entry will itself be a list containing the option's + * name for use on command lines, database name, database + * class, default value, and current value (empty string + * if none). For options that are synonyms, the list will + * contain only two values: name and synonym name. If the + * "name" argument is non-NULL, then the only information + * returned is that for the named argument (i.e. the corresponding + * entry in the overall list is returned). + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_ConfigureInfo(interp, tkwin, specs, widgRec, argvName, flags) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Window tkwin; /* Window corresponding to widgRec. */ + Tk_ConfigSpec *specs; /* Describes legal options. */ + char *widgRec; /* Record whose fields contain current + * values for options. */ + char *argvName; /* If non-NULL, indicates a single option + * whose info is to be returned. Otherwise + * info is returned for all options. */ + int flags; /* Used to specify additional flags + * that must be present in config specs + * for them to be considered. */ +{ + register Tk_ConfigSpec *specPtr; + int needFlags, hateFlags; + char *list; + char *leader = "{"; + + needFlags = flags & ~(TK_CONFIG_USER_BIT - 1); + if (Tk_Depth(tkwin) <= 1) { + hateFlags = TK_CONFIG_COLOR_ONLY; + } else { + hateFlags = TK_CONFIG_MONO_ONLY; + } + + /* + * If information is only wanted for a single configuration + * spec, then handle that one spec specially. + */ + + Tcl_SetResult(interp, (char *) NULL, TCL_STATIC); + if (argvName != NULL) { + specPtr = FindConfigSpec(interp, specs, argvName, needFlags, + hateFlags); + if (specPtr == NULL) { + return TCL_ERROR; + } + interp->result = FormatConfigInfo(interp, tkwin, specPtr, widgRec); + interp->freeProc = TCL_DYNAMIC; + return TCL_OK; + } + + /* + * Loop through all the specs, creating a big list with all + * their information. + */ + + for (specPtr = specs; specPtr->type != TK_CONFIG_END; specPtr++) { + if ((argvName != NULL) && (specPtr->argvName != argvName)) { + continue; + } + if (((specPtr->specFlags & needFlags) != needFlags) + || (specPtr->specFlags & hateFlags)) { + continue; + } + if (specPtr->argvName == NULL) { + continue; + } + list = FormatConfigInfo(interp, tkwin, specPtr, widgRec); + Tcl_AppendResult(interp, leader, list, "}", (char *) NULL); + ckfree(list); + leader = " {"; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * FormatConfigInfo -- + * + * Create a valid Tcl list holding the configuration information + * for a single configuration option. + * + * Results: + * A Tcl list, dynamically allocated. The caller is expected to + * arrange for this list to be freed eventually. + * + * Side effects: + * Memory is allocated. + * + *-------------------------------------------------------------- + */ + +static char * +FormatConfigInfo(interp, tkwin, specPtr, widgRec) + Tcl_Interp *interp; /* Interpreter to use for things + * like floating-point precision. */ + Tk_Window tkwin; /* Window corresponding to widget. */ + register Tk_ConfigSpec *specPtr; /* Pointer to information describing + * option. */ + char *widgRec; /* Pointer to record holding current + * values of info for widget. */ +{ + char *argv[6], *result; + char buffer[200]; + Tcl_FreeProc *freeProc = (Tcl_FreeProc *) NULL; + + argv[0] = specPtr->argvName; + argv[1] = specPtr->dbName; + argv[2] = specPtr->dbClass; + argv[3] = specPtr->defValue; + if (specPtr->type == TK_CONFIG_SYNONYM) { + return Tcl_Merge(2, argv); + } + argv[4] = FormatConfigValue(interp, tkwin, specPtr, widgRec, buffer, + &freeProc); + if (argv[1] == NULL) { + argv[1] = ""; + } + if (argv[2] == NULL) { + argv[2] = ""; + } + if (argv[3] == NULL) { + argv[3] = ""; + } + if (argv[4] == NULL) { + argv[4] = ""; + } + result = Tcl_Merge(5, argv); + if (freeProc != NULL) { + if ((freeProc == TCL_DYNAMIC) || (freeProc == (Tcl_FreeProc *) free)) { + ckfree(argv[4]); + } else { + (*freeProc)(argv[4]); + } + } + return result; +} + +/* + *---------------------------------------------------------------------- + * + * FormatConfigValue -- + * + * This procedure formats the current value of a configuration + * option. + * + * Results: + * The return value is the formatted value of the option given + * by specPtr and widgRec. If the value is static, so that it + * need not be freed, *freeProcPtr will be set to NULL; otherwise + * *freeProcPtr will be set to the address of a procedure to + * free the result, and the caller must invoke this procedure + * when it is finished with the result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static char * +FormatConfigValue(interp, tkwin, specPtr, widgRec, buffer, freeProcPtr) + Tcl_Interp *interp; /* Interpreter for use in real conversions. */ + Tk_Window tkwin; /* Window corresponding to widget. */ + Tk_ConfigSpec *specPtr; /* Pointer to information describing option. + * Must not point to a synonym option. */ + char *widgRec; /* Pointer to record holding current + * values of info for widget. */ + char *buffer; /* Static buffer to use for small values. + * Must have at least 200 bytes of storage. */ + Tcl_FreeProc **freeProcPtr; /* Pointer to word to fill in with address + * of procedure to free the result, or NULL + * if result is static. */ +{ + char *ptr, *result; + + *freeProcPtr = NULL; + ptr = widgRec + specPtr->offset; + result = ""; + switch (specPtr->type) { + case TK_CONFIG_BOOLEAN: + if (*((int *) ptr) == 0) { + result = "0"; + } else { + result = "1"; + } + break; + case TK_CONFIG_INT: + sprintf(buffer, "%d", *((int *) ptr)); + result = buffer; + break; + case TK_CONFIG_DOUBLE: + Tcl_PrintDouble(interp, *((double *) ptr), buffer); + result = buffer; + break; + case TK_CONFIG_STRING: + result = (*(char **) ptr); + if (result == NULL) { + result = ""; + } + break; + case TK_CONFIG_UID: { + Tk_Uid uid = *((Tk_Uid *) ptr); + if (uid != NULL) { + result = uid; + } + break; + } + case TK_CONFIG_COLOR: { + XColor *colorPtr = *((XColor **) ptr); + if (colorPtr != NULL) { + result = Tk_NameOfColor(colorPtr); + } + break; + } + case TK_CONFIG_FONT: { + Tk_Font tkfont = *((Tk_Font *) ptr); + if (tkfont != NULL) { + result = Tk_NameOfFont(tkfont); + } + break; + } + case TK_CONFIG_BITMAP: { + Pixmap pixmap = *((Pixmap *) ptr); + if (pixmap != None) { + result = Tk_NameOfBitmap(Tk_Display(tkwin), pixmap); + } + break; + } + case TK_CONFIG_BORDER: { + Tk_3DBorder border = *((Tk_3DBorder *) ptr); + if (border != NULL) { + result = Tk_NameOf3DBorder(border); + } + break; + } + case TK_CONFIG_RELIEF: + result = Tk_NameOfRelief(*((int *) ptr)); + break; + case TK_CONFIG_CURSOR: + case TK_CONFIG_ACTIVE_CURSOR: { + Tk_Cursor cursor = *((Tk_Cursor *) ptr); + if (cursor != None) { + result = Tk_NameOfCursor(Tk_Display(tkwin), cursor); + } + break; + } + case TK_CONFIG_JUSTIFY: + result = Tk_NameOfJustify(*((Tk_Justify *) ptr)); + break; + case TK_CONFIG_ANCHOR: + result = Tk_NameOfAnchor(*((Tk_Anchor *) ptr)); + break; + case TK_CONFIG_CAP_STYLE: + result = Tk_NameOfCapStyle(*((int *) ptr)); + break; + case TK_CONFIG_JOIN_STYLE: + result = Tk_NameOfJoinStyle(*((int *) ptr)); + break; + case TK_CONFIG_PIXELS: + sprintf(buffer, "%d", *((int *) ptr)); + result = buffer; + break; + case TK_CONFIG_MM: + Tcl_PrintDouble(interp, *((double *) ptr), buffer); + result = buffer; + break; + case TK_CONFIG_WINDOW: { + Tk_Window tkwin; + + tkwin = *((Tk_Window *) ptr); + if (tkwin != NULL) { + result = Tk_PathName(tkwin); + } + break; + } + case TK_CONFIG_CUSTOM: + result = (*specPtr->customPtr->printProc)( + specPtr->customPtr->clientData, tkwin, widgRec, + specPtr->offset, freeProcPtr); + break; + default: + result = "?? unknown type ??"; + } + return result; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_ConfigureValue -- + * + * This procedure returns the current value of a configuration + * option for a widget. + * + * Results: + * The return value is a standard Tcl completion code (TCL_OK or + * TCL_ERROR). Interp->result will be set to hold either the value + * of the option given by argvName (if TCL_OK is returned) or + * an error message (if TCL_ERROR is returned). + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +Tk_ConfigureValue(interp, tkwin, specs, widgRec, argvName, flags) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Window tkwin; /* Window corresponding to widgRec. */ + Tk_ConfigSpec *specs; /* Describes legal options. */ + char *widgRec; /* Record whose fields contain current + * values for options. */ + char *argvName; /* Gives the command-line name for the + * option whose value is to be returned. */ + int flags; /* Used to specify additional flags + * that must be present in config specs + * for them to be considered. */ +{ + Tk_ConfigSpec *specPtr; + int needFlags, hateFlags; + + needFlags = flags & ~(TK_CONFIG_USER_BIT - 1); + if (Tk_Depth(tkwin) <= 1) { + hateFlags = TK_CONFIG_COLOR_ONLY; + } else { + hateFlags = TK_CONFIG_MONO_ONLY; + } + specPtr = FindConfigSpec(interp, specs, argvName, needFlags, hateFlags); + if (specPtr == NULL) { + return TCL_ERROR; + } + interp->result = FormatConfigValue(interp, tkwin, specPtr, widgRec, + interp->result, &interp->freeProc); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreeOptions -- + * + * Free up all resources associated with configuration options. + * + * Results: + * None. + * + * Side effects: + * Any resource in widgRec that is controlled by a configuration + * option (e.g. a Tk_3DBorder or XColor) is freed in the appropriate + * fashion. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +void +Tk_FreeOptions(specs, widgRec, display, needFlags) + Tk_ConfigSpec *specs; /* Describes legal options. */ + char *widgRec; /* Record whose fields contain current + * values for options. */ + Display *display; /* X display; needed for freeing some + * resources. */ + int needFlags; /* Used to specify additional flags + * that must be present in config specs + * for them to be considered. */ +{ + register Tk_ConfigSpec *specPtr; + char *ptr; + + for (specPtr = specs; specPtr->type != TK_CONFIG_END; specPtr++) { + if ((specPtr->specFlags & needFlags) != needFlags) { + continue; + } + ptr = widgRec + specPtr->offset; + switch (specPtr->type) { + case TK_CONFIG_STRING: + if (*((char **) ptr) != NULL) { + ckfree(*((char **) ptr)); + *((char **) ptr) = NULL; + } + break; + case TK_CONFIG_COLOR: + if (*((XColor **) ptr) != NULL) { + Tk_FreeColor(*((XColor **) ptr)); + *((XColor **) ptr) = NULL; + } + break; + case TK_CONFIG_FONT: + Tk_FreeFont(*((Tk_Font *) ptr)); + *((Tk_Font *) ptr) = NULL; + break; + case TK_CONFIG_BITMAP: + if (*((Pixmap *) ptr) != None) { + Tk_FreeBitmap(display, *((Pixmap *) ptr)); + *((Pixmap *) ptr) = None; + } + break; + case TK_CONFIG_BORDER: + if (*((Tk_3DBorder *) ptr) != NULL) { + Tk_Free3DBorder(*((Tk_3DBorder *) ptr)); + *((Tk_3DBorder *) ptr) = NULL; + } + break; + case TK_CONFIG_CURSOR: + case TK_CONFIG_ACTIVE_CURSOR: + if (*((Tk_Cursor *) ptr) != None) { + Tk_FreeCursor(display, *((Tk_Cursor *) ptr)); + *((Tk_Cursor *) ptr) = None; + } + } + } +} diff --git a/generic/tkConsole.c b/generic/tkConsole.c new file mode 100644 index 0000000..c213371 --- /dev/null +++ b/generic/tkConsole.c @@ -0,0 +1,616 @@ +/* + * tkConsole.c -- + * + * This file implements a Tcl console for systems that may not + * otherwise have access to a console. It uses the Text widget + * and provides special access via a console command. + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkConsole.c 1.54 97/10/17 10:46:08 + */ + +#include "tk.h" +#include <string.h> + +/* + * A data structure of the following type holds information for each console + * which a handler (i.e. a Tcl command) has been defined for a particular + * top-level window. + */ + +typedef struct ConsoleInfo { + Tcl_Interp *consoleInterp; /* Interpreter for the console. */ + Tcl_Interp *interp; /* Interpreter to send console commands. */ +} ConsoleInfo; + +static Tcl_Interp *gStdoutInterp = NULL; + +/* + * Forward declarations for procedures defined later in this file: + * + * The first three will be used in the tk app shells... + */ + +void TkConsoleCreate _ANSI_ARGS_((void)); +int TkConsoleInit _ANSI_ARGS_((Tcl_Interp *interp)); +void TkConsolePrint _ANSI_ARGS_((Tcl_Interp *interp, + int devId, char *buffer, long size)); + +static int ConsoleCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void ConsoleDeleteProc _ANSI_ARGS_((ClientData clientData)); +static void ConsoleEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int InterpreterCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); + +static int ConsoleInput _ANSI_ARGS_((ClientData instanceData, + char *buf, int toRead, int *errorCode)); +static int ConsoleOutput _ANSI_ARGS_((ClientData instanceData, + char *buf, int toWrite, int *errorCode)); +static int ConsoleClose _ANSI_ARGS_((ClientData instanceData, + Tcl_Interp *interp)); +static void ConsoleWatch _ANSI_ARGS_((ClientData instanceData, + int mask)); +static int ConsoleHandle _ANSI_ARGS_((ClientData instanceData, + int direction, ClientData *handlePtr)); + +/* + * This structure describes the channel type structure for file based IO: + */ + +static Tcl_ChannelType consoleChannelType = { + "console", /* Type name. */ + NULL, /* Always non-blocking.*/ + ConsoleClose, /* Close proc. */ + ConsoleInput, /* Input proc. */ + ConsoleOutput, /* Output proc. */ + NULL, /* Seek proc. */ + NULL, /* Set option proc. */ + NULL, /* Get option proc. */ + ConsoleWatch, /* Watch for events on console. */ + ConsoleHandle, /* Get a handle from the device. */ +}; + +/* + *---------------------------------------------------------------------- + * + * TkConsoleCreate -- + * + * Create the console channels and install them as the standard + * channels. All I/O will be discarded until TkConsoleInit is + * called to attach the console to a text widget. + * + * Results: + * None. + * + * Side effects: + * Creates the console channel and installs it as the standard + * channels. + * + *---------------------------------------------------------------------- + */ + +void +TkConsoleCreate() +{ + Tcl_Channel consoleChannel; + + consoleChannel = Tcl_CreateChannel(&consoleChannelType, "console0", + (ClientData) TCL_STDIN, TCL_READABLE); + if (consoleChannel != NULL) { + Tcl_SetChannelOption(NULL, consoleChannel, "-translation", "lf"); + Tcl_SetChannelOption(NULL, consoleChannel, "-buffering", "none"); + } + Tcl_SetStdChannel(consoleChannel, TCL_STDIN); + consoleChannel = Tcl_CreateChannel(&consoleChannelType, "console1", + (ClientData) TCL_STDOUT, TCL_WRITABLE); + if (consoleChannel != NULL) { + Tcl_SetChannelOption(NULL, consoleChannel, "-translation", "lf"); + Tcl_SetChannelOption(NULL, consoleChannel, "-buffering", "none"); + } + Tcl_SetStdChannel(consoleChannel, TCL_STDOUT); + consoleChannel = Tcl_CreateChannel(&consoleChannelType, "console2", + (ClientData) TCL_STDERR, TCL_WRITABLE); + if (consoleChannel != NULL) { + Tcl_SetChannelOption(NULL, consoleChannel, "-translation", "lf"); + Tcl_SetChannelOption(NULL, consoleChannel, "-buffering", "none"); + } + Tcl_SetStdChannel(consoleChannel, TCL_STDERR); +} + +/* + *---------------------------------------------------------------------- + * + * TkConsoleInit -- + * + * Initialize the console. This code actually creates a new + * application and associated interpreter. This effectivly hides + * the implementation from the main application. + * + * Results: + * None. + * + * Side effects: + * A new console it created. + * + *---------------------------------------------------------------------- + */ + +int +TkConsoleInit(interp) + Tcl_Interp *interp; /* Interpreter to use for prompting. */ +{ + Tcl_Interp *consoleInterp; + ConsoleInfo *info; + Tk_Window mainWindow = Tk_MainWindow(interp); +#ifdef MAC_TCL + static char initCmd[] = "source -rsrc {Console}"; +#else + static char initCmd[] = "source $tk_library/console.tcl"; +#endif + + consoleInterp = Tcl_CreateInterp(); + if (consoleInterp == NULL) { + goto error; + } + + /* + * Initialized Tcl and Tk. + */ + + if (Tcl_Init(consoleInterp) != TCL_OK) { + goto error; + } + if (Tk_Init(consoleInterp) != TCL_OK) { + goto error; + } + gStdoutInterp = interp; + + /* + * Add console commands to the interp + */ + info = (ConsoleInfo *) ckalloc(sizeof(ConsoleInfo)); + info->interp = interp; + info->consoleInterp = consoleInterp; + Tcl_CreateCommand(interp, "console", ConsoleCmd, (ClientData) info, + (Tcl_CmdDeleteProc *) ConsoleDeleteProc); + Tcl_CreateCommand(consoleInterp, "consoleinterp", InterpreterCmd, + (ClientData) info, (Tcl_CmdDeleteProc *) NULL); + + Tk_CreateEventHandler(mainWindow, StructureNotifyMask, ConsoleEventProc, + (ClientData) info); + + Tcl_Preserve((ClientData) consoleInterp); + if (Tcl_Eval(consoleInterp, initCmd) == TCL_ERROR) { + /* goto error; -- no problem for now... */ + printf("Eval error: %s", consoleInterp->result); + } + Tcl_Release((ClientData) consoleInterp); + return TCL_OK; + + error: + if (consoleInterp != NULL) { + Tcl_DeleteInterp(consoleInterp); + } + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * ConsoleOutput-- + * + * Writes the given output on the IO channel. Returns count of how + * many characters were actually written, and an error indication. + * + * Results: + * A count of how many characters were written is returned and an + * error indication is returned in an output argument. + * + * Side effects: + * Writes output on the actual channel. + * + *---------------------------------------------------------------------- + */ + +static int +ConsoleOutput(instanceData, buf, toWrite, errorCode) + ClientData instanceData; /* Indicates which device to use. */ + char *buf; /* The data buffer. */ + int toWrite; /* How many bytes to write? */ + int *errorCode; /* Where to store error code. */ +{ + *errorCode = 0; + Tcl_SetErrno(0); + + if (gStdoutInterp != NULL) { + TkConsolePrint(gStdoutInterp, (int) instanceData, buf, toWrite); + } + + return toWrite; +} + +/* + *---------------------------------------------------------------------- + * + * ConsoleInput -- + * + * Read input from the console. Not currently implemented. + * + * Results: + * Always returns EOF. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +ConsoleInput(instanceData, buf, bufSize, errorCode) + ClientData instanceData; /* Unused. */ + char *buf; /* Where to store data read. */ + int bufSize; /* How much space is available + * in the buffer? */ + int *errorCode; /* Where to store error code. */ +{ + return 0; /* Always return EOF. */ +} + +/* + *---------------------------------------------------------------------- + * + * ConsoleClose -- + * + * Closes the IO channel. + * + * Results: + * Always returns 0 (success). + * + * Side effects: + * Frees the dummy file associated with the channel. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +ConsoleClose(instanceData, interp) + ClientData instanceData; /* Unused. */ + Tcl_Interp *interp; /* Unused. */ +{ + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * ConsoleWatch -- + * + * Called by the notifier to set up the console device so that + * events will be noticed. Since there are no events on the + * console, this routine just returns without doing anything. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +ConsoleWatch(instanceData, mask) + ClientData instanceData; /* Device ID for the channel. */ + int mask; /* OR-ed combination of + * TCL_READABLE, TCL_WRITABLE and + * TCL_EXCEPTION, for the events + * we are interested in. */ +{ +} + +/* + *---------------------------------------------------------------------- + * + * ConsoleHandle -- + * + * Invoked by the generic IO layer to get a handle from a channel. + * Because console channels are not devices, this function always + * fails. + * + * Results: + * Always returns TCL_ERROR. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +ConsoleHandle(instanceData, direction, handlePtr) + ClientData instanceData; /* Device ID for the channel. */ + int direction; /* TCL_READABLE or TCL_WRITABLE to indicate + * which direction of the channel is being + * requested. */ + ClientData *handlePtr; /* Where to store handle */ +{ + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * ConsoleCmd -- + * + * The console command implements a Tcl interface to the various console + * options. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +ConsoleCmd(clientData, interp, argc, argv) + ClientData clientData; /* Not used. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + ConsoleInfo *info = (ConsoleInfo *) clientData; + char c; + int length; + int result; + Tcl_Interp *consoleInterp; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + + c = argv[1][0]; + length = strlen(argv[1]); + result = TCL_OK; + consoleInterp = info->consoleInterp; + Tcl_Preserve((ClientData) consoleInterp); + if ((c == 't') && (strncmp(argv[1], "title", length)) == 0) { + Tcl_DString dString; + + Tcl_DStringInit(&dString); + Tcl_DStringAppend(&dString, "wm title . ", -1); + if (argc == 3) { + Tcl_DStringAppendElement(&dString, argv[2]); + } + Tcl_Eval(consoleInterp, Tcl_DStringValue(&dString)); + Tcl_DStringFree(&dString); + } else if ((c == 'h') && (strncmp(argv[1], "hide", length)) == 0) { + Tcl_Eval(info->consoleInterp, "wm withdraw ."); + } else if ((c == 's') && (strncmp(argv[1], "show", length)) == 0) { + Tcl_Eval(info->consoleInterp, "wm deiconify ."); + } else if ((c == 'e') && (strncmp(argv[1], "eval", length)) == 0) { + if (argc == 3) { + Tcl_Eval(info->consoleInterp, argv[2]); + } else { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " eval command\"", (char *) NULL); + return TCL_ERROR; + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": should be hide, show, or title", + (char *) NULL); + result = TCL_ERROR; + } + Tcl_Release((ClientData) consoleInterp); + return result; +} + +/* + *---------------------------------------------------------------------- + * + * InterpreterCmd -- + * + * This command allows the console interp to communicate with the + * main interpreter. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +InterpreterCmd(clientData, interp, argc, argv) + ClientData clientData; /* Not used. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + ConsoleInfo *info = (ConsoleInfo *) clientData; + char c; + int length; + int result; + Tcl_Interp *otherInterp; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + + c = argv[1][0]; + length = strlen(argv[1]); + otherInterp = info->interp; + Tcl_Preserve((ClientData) otherInterp); + if ((c == 'e') && (strncmp(argv[1], "eval", length)) == 0) { + result = Tcl_GlobalEval(otherInterp, argv[2]); + Tcl_AppendResult(interp, otherInterp->result, (char *) NULL); + } else if ((c == 'r') && (strncmp(argv[1], "record", length)) == 0) { + Tcl_RecordAndEval(otherInterp, argv[2], TCL_EVAL_GLOBAL); + result = TCL_OK; + Tcl_AppendResult(interp, otherInterp->result, (char *) NULL); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": should be eval or record", + (char *) NULL); + result = TCL_ERROR; + } + Tcl_Release((ClientData) otherInterp); + return result; +} + +/* + *---------------------------------------------------------------------- + * + * ConsoleDeleteProc -- + * + * If the console command is deleted we destroy the console window + * and all associated data structures. + * + * Results: + * None. + * + * Side effects: + * A new console it created. + * + *---------------------------------------------------------------------- + */ + +void +ConsoleDeleteProc(clientData) + ClientData clientData; +{ + ConsoleInfo *info = (ConsoleInfo *) clientData; + + Tcl_DeleteInterp(info->consoleInterp); + info->consoleInterp = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * ConsoleEventProc -- + * + * This event procedure is registered on the main window of the + * slave interpreter. If the user or a running script causes the + * main window to be destroyed, then we need to inform the console + * interpreter by invoking "tkConsoleExit". + * + * Results: + * None. + * + * Side effects: + * Invokes the "tkConsoleExit" procedure in the console interp. + * + *---------------------------------------------------------------------- + */ + +static void +ConsoleEventProc(clientData, eventPtr) + ClientData clientData; + XEvent *eventPtr; +{ + ConsoleInfo *info = (ConsoleInfo *) clientData; + Tcl_Interp *consoleInterp; + + if (eventPtr->type == DestroyNotify) { + consoleInterp = info->consoleInterp; + + /* + * It is possible that the console interpreter itself has + * already been deleted. In that case the consoleInterp + * field will be set to NULL. If the interpreter is already + * gone, we do not have to do any work here. + */ + + if (consoleInterp == (Tcl_Interp *) NULL) { + return; + } + Tcl_Preserve((ClientData) consoleInterp); + Tcl_Eval(consoleInterp, "tkConsoleExit"); + Tcl_Release((ClientData) consoleInterp); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkConsolePrint -- + * + * Prints to the give text to the console. Given the main interp + * this functions find the appropiate console interp and forwards + * the text to be added to that console. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkConsolePrint(interp, devId, buffer, size) + Tcl_Interp *interp; /* Main interpreter. */ + int devId; /* TCL_STDOUT for stdout, TCL_STDERR for + * stderr. */ + char *buffer; /* Text buffer. */ + long size; /* Size of text buffer. */ +{ + Tcl_DString command, output; + Tcl_CmdInfo cmdInfo; + char *cmd; + ConsoleInfo *info; + Tcl_Interp *consoleInterp; + int result; + + if (interp == NULL) { + return; + } + + if (devId == TCL_STDERR) { + cmd = "tkConsoleOutput stderr "; + } else { + cmd = "tkConsoleOutput stdout "; + } + + result = Tcl_GetCommandInfo(interp, "console", &cmdInfo); + if (result == 0) { + return; + } + info = (ConsoleInfo *) cmdInfo.clientData; + + Tcl_DStringInit(&output); + Tcl_DStringAppend(&output, buffer, size); + + Tcl_DStringInit(&command); + Tcl_DStringAppend(&command, cmd, strlen(cmd)); + Tcl_DStringAppendElement(&command, output.string); + + consoleInterp = info->consoleInterp; + Tcl_Preserve((ClientData) consoleInterp); + Tcl_Eval(consoleInterp, command.string); + Tcl_Release((ClientData) consoleInterp); + + Tcl_DStringFree(&command); + Tcl_DStringFree(&output); +} diff --git a/generic/tkCursor.c b/generic/tkCursor.c new file mode 100644 index 0000000..e185109 --- /dev/null +++ b/generic/tkCursor.c @@ -0,0 +1,384 @@ +/* + * tkCursor.c -- + * + * This file maintains a database of read-only cursors for the Tk + * toolkit. This allows cursors to be shared between widgets and + * also avoids round-trips to the X server. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkCursor.c 1.27 96/02/15 18:52:40 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * A TkCursor structure exists for each cursor that is currently + * active. Each structure is indexed with two hash tables defined + * below. One of the tables is idTable, and the other is either + * nameTable or dataTable, also defined below. + */ + +/* + * Hash table to map from a textual description of a cursor to the + * TkCursor record for the cursor, and key structure used in that + * hash table: + */ + +static Tcl_HashTable nameTable; +typedef struct { + Tk_Uid name; /* Textual name for desired cursor. */ + Display *display; /* Display for which cursor will be used. */ +} NameKey; + +/* + * Hash table to map from a collection of in-core data about a + * cursor (bitmap contents, etc.) to a TkCursor structure: + */ + +static Tcl_HashTable dataTable; +typedef struct { + char *source; /* Cursor bits. */ + char *mask; /* Mask bits. */ + int width, height; /* Dimensions of cursor (and data + * and mask). */ + int xHot, yHot; /* Location of cursor hot-spot. */ + Tk_Uid fg, bg; /* Colors for cursor. */ + Display *display; /* Display on which cursor will be used. */ +} DataKey; + +/* + * Hash table that maps from <display + cursor id> to the TkCursor structure + * for the cursor. This table is used by Tk_FreeCursor. + */ + +static Tcl_HashTable idTable; +typedef struct { + Display *display; /* Display for which cursor was allocated. */ + Tk_Cursor cursor; /* Cursor identifier. */ +} IdKey; + +static int initialized = 0; /* 0 means static structures haven't been + * initialized yet. */ + +/* + * Forward declarations for procedures defined in this file: + */ + +static void CursorInit _ANSI_ARGS_((void)); + +/* + *---------------------------------------------------------------------- + * + * Tk_GetCursor -- + * + * Given a string describing a cursor, locate (or create if necessary) + * a cursor that fits the description. + * + * Results: + * The return value is the X identifer for the desired cursor, + * unless string couldn't be parsed correctly. In this case, + * None is returned and an error message is left in interp->result. + * The caller should never modify the cursor that is returned, and + * should eventually call Tk_FreeCursor when the cursor is no longer + * needed. + * + * Side effects: + * The cursor is added to an internal database with a reference count. + * For each call to this procedure, there should eventually be a call + * to Tk_FreeCursor, so that the database can be cleaned up when cursors + * aren't needed anymore. + * + *---------------------------------------------------------------------- + */ + +Tk_Cursor +Tk_GetCursor(interp, tkwin, string) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + Tk_Window tkwin; /* Window in which cursor will be used. */ + Tk_Uid string; /* Description of cursor. See manual entry + * for details on legal syntax. */ +{ + NameKey nameKey; + IdKey idKey; + Tcl_HashEntry *nameHashPtr, *idHashPtr; + register TkCursor *cursorPtr; + int new; + + if (!initialized) { + CursorInit(); + } + + nameKey.name = string; + nameKey.display = Tk_Display(tkwin); + nameHashPtr = Tcl_CreateHashEntry(&nameTable, (char *) &nameKey, &new); + if (!new) { + cursorPtr = (TkCursor *) Tcl_GetHashValue(nameHashPtr); + cursorPtr->refCount++; + return cursorPtr->cursor; + } + + cursorPtr = TkGetCursorByName(interp, tkwin, string); + + if (cursorPtr == NULL) { + Tcl_DeleteHashEntry(nameHashPtr); + return None; + } + + /* + * Add information about this cursor to our database. + */ + + cursorPtr->refCount = 1; + cursorPtr->otherTable = &nameTable; + cursorPtr->hashPtr = nameHashPtr; + idKey.display = nameKey.display; + idKey.cursor = cursorPtr->cursor; + idHashPtr = Tcl_CreateHashEntry(&idTable, (char *) &idKey, &new); + if (!new) { + panic("cursor already registered in Tk_GetCursor"); + } + Tcl_SetHashValue(nameHashPtr, cursorPtr); + Tcl_SetHashValue(idHashPtr, cursorPtr); + + return cursorPtr->cursor; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetCursorFromData -- + * + * Given a description of the bits and colors for a cursor, + * make a cursor that has the given properties. + * + * Results: + * The return value is the X identifer for the desired cursor, + * unless it couldn't be created properly. In this case, None is + * returned and an error message is left in interp->result. The + * caller should never modify the cursor that is returned, and + * should eventually call Tk_FreeCursor when the cursor is no + * longer needed. + * + * Side effects: + * The cursor is added to an internal database with a reference count. + * For each call to this procedure, there should eventually be a call + * to Tk_FreeCursor, so that the database can be cleaned up when cursors + * aren't needed anymore. + * + *---------------------------------------------------------------------- + */ + +Tk_Cursor +Tk_GetCursorFromData(interp, tkwin, source, mask, width, height, + xHot, yHot, fg, bg) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + Tk_Window tkwin; /* Window in which cursor will be used. */ + char *source; /* Bitmap data for cursor shape. */ + char *mask; /* Bitmap data for cursor mask. */ + int width, height; /* Dimensions of cursor. */ + int xHot, yHot; /* Location of hot-spot in cursor. */ + Tk_Uid fg; /* Foreground color for cursor. */ + Tk_Uid bg; /* Background color for cursor. */ +{ + DataKey dataKey; + IdKey idKey; + Tcl_HashEntry *dataHashPtr, *idHashPtr; + register TkCursor *cursorPtr; + int new; + XColor fgColor, bgColor; + + if (!initialized) { + CursorInit(); + } + + dataKey.source = source; + dataKey.mask = mask; + dataKey.width = width; + dataKey.height = height; + dataKey.xHot = xHot; + dataKey.yHot = yHot; + dataKey.fg = fg; + dataKey.bg = bg; + dataKey.display = Tk_Display(tkwin); + dataHashPtr = Tcl_CreateHashEntry(&dataTable, (char *) &dataKey, &new); + if (!new) { + cursorPtr = (TkCursor *) Tcl_GetHashValue(dataHashPtr); + cursorPtr->refCount++; + return cursorPtr->cursor; + } + + /* + * No suitable cursor exists yet. Make one using the data + * available and add it to the database. + */ + + if (XParseColor(dataKey.display, Tk_Colormap(tkwin), fg, &fgColor) == 0) { + Tcl_AppendResult(interp, "invalid color name \"", fg, "\"", + (char *) NULL); + goto error; + } + if (XParseColor(dataKey.display, Tk_Colormap(tkwin), bg, &bgColor) == 0) { + Tcl_AppendResult(interp, "invalid color name \"", bg, "\"", + (char *) NULL); + goto error; + } + + cursorPtr = TkCreateCursorFromData(tkwin, source, mask, width, height, + xHot, yHot, fgColor, bgColor); + + if (cursorPtr == NULL) { + goto error; + } + + cursorPtr->refCount = 1; + cursorPtr->otherTable = &dataTable; + cursorPtr->hashPtr = dataHashPtr; + idKey.display = dataKey.display; + idKey.cursor = cursorPtr->cursor; + idHashPtr = Tcl_CreateHashEntry(&idTable, (char *) &idKey, &new); + if (!new) { + panic("cursor already registered in Tk_GetCursorFromData"); + } + Tcl_SetHashValue(dataHashPtr, cursorPtr); + Tcl_SetHashValue(idHashPtr, cursorPtr); + return cursorPtr->cursor; + + error: + Tcl_DeleteHashEntry(dataHashPtr); + return None; +} + +/* + *-------------------------------------------------------------- + * + * Tk_NameOfCursor -- + * + * Given a cursor, return a textual string identifying it. + * + * Results: + * If cursor was created by Tk_GetCursor, then the return + * value is the "string" that was used to create it. + * Otherwise the return value is a string giving the X + * identifier for the cursor. The storage for the returned + * string is only guaranteed to persist up until the next + * call to this procedure. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_NameOfCursor(display, cursor) + Display *display; /* Display for which cursor was allocated. */ + Tk_Cursor cursor; /* Identifier for cursor whose name is + * wanted. */ +{ + IdKey idKey; + Tcl_HashEntry *idHashPtr; + TkCursor *cursorPtr; + static char string[20]; + + if (!initialized) { + printid: + sprintf(string, "cursor id 0x%x", (unsigned int) cursor); + return string; + } + idKey.display = display; + idKey.cursor = cursor; + idHashPtr = Tcl_FindHashEntry(&idTable, (char *) &idKey); + if (idHashPtr == NULL) { + goto printid; + } + cursorPtr = (TkCursor *) Tcl_GetHashValue(idHashPtr); + if (cursorPtr->otherTable != &nameTable) { + goto printid; + } + return ((NameKey *) cursorPtr->hashPtr->key.words)->name; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreeCursor -- + * + * This procedure is called to release a cursor allocated by + * Tk_GetCursor or TkGetCursorFromData. + * + * Results: + * None. + * + * Side effects: + * The reference count associated with cursor is decremented, and + * it is officially deallocated if no-one is using it anymore. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreeCursor(display, cursor) + Display *display; /* Display for which cursor was allocated. */ + Tk_Cursor cursor; /* Identifier for cursor to be released. */ +{ + IdKey idKey; + Tcl_HashEntry *idHashPtr; + register TkCursor *cursorPtr; + + if (!initialized) { + panic("Tk_FreeCursor called before Tk_GetCursor"); + } + + idKey.display = display; + idKey.cursor = cursor; + idHashPtr = Tcl_FindHashEntry(&idTable, (char *) &idKey); + if (idHashPtr == NULL) { + panic("Tk_FreeCursor received unknown cursor argument"); + } + cursorPtr = (TkCursor *) Tcl_GetHashValue(idHashPtr); + cursorPtr->refCount--; + if (cursorPtr->refCount == 0) { + Tcl_DeleteHashEntry(cursorPtr->hashPtr); + Tcl_DeleteHashEntry(idHashPtr); + TkFreeCursor(cursorPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * CursorInit -- + * + * Initialize the structures used for cursor management. + * + * Results: + * None. + * + * Side effects: + * Read the code. + * + *---------------------------------------------------------------------- + */ + +static void +CursorInit() +{ + initialized = 1; + Tcl_InitHashTable(&nameTable, sizeof(NameKey)/sizeof(int)); + Tcl_InitHashTable(&dataTable, sizeof(DataKey)/sizeof(int)); + + /* + * The call below is tricky: can't use sizeof(IdKey) because it + * gets padded with extra unpredictable bytes on some 64-bit + * machines. + */ + + Tcl_InitHashTable(&idTable, (sizeof(Display *) + sizeof(Tk_Cursor)) + /sizeof(int)); +} diff --git a/generic/tkEntry.c b/generic/tkEntry.c new file mode 100644 index 0000000..35cc66c --- /dev/null +++ b/generic/tkEntry.c @@ -0,0 +1,2313 @@ +/* + * tkEntry.c -- + * + * This module implements entry widgets for the Tk + * toolkit. An entry displays a string and allows + * the string to be edited. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkEntry.c 1.112 97/11/06 16:56:16 + */ + +#include "tkInt.h" +#include "default.h" + +/* + * A data structure of the following type is kept for each entry + * widget managed by this file: + */ + +typedef struct { + Tk_Window tkwin; /* Window that embodies the entry. NULL + * means that the window has been destroyed + * but the data structures haven't yet been + * cleaned up.*/ + Display *display; /* Display containing widget. Used, among + * other things, so that resources can be + * freed even after tkwin has gone away. */ + Tcl_Interp *interp; /* Interpreter associated with entry. */ + Tcl_Command widgetCmd; /* Token for entry's widget command. */ + + /* + * Fields that are set by widget commands other than "configure". + */ + + char *string; /* Pointer to storage for string; + * NULL-terminated; malloc-ed. */ + int insertPos; /* Index of character before which next + * typed character will be inserted. */ + + /* + * Information about what's selected, if any. + */ + + int selectFirst; /* Index of first selected character (-1 means + * nothing selected. */ + int selectLast; /* Index of last selected character (-1 means + * nothing selected. */ + int selectAnchor; /* Fixed end of selection (i.e. "select to" + * operation will use this as one end of the + * selection). */ + + /* + * Information for scanning: + */ + + int scanMarkX; /* X-position at which scan started (e.g. + * button was pressed here). */ + int scanMarkIndex; /* Index of character that was at left of + * window when scan started. */ + + /* + * Configuration settings that are updated by Tk_ConfigureWidget. + */ + + Tk_3DBorder normalBorder; /* Used for drawing border around whole + * window, plus used for background. */ + int borderWidth; /* Width of 3-D border around window. */ + Tk_Cursor cursor; /* Current cursor for window, or None. */ + int exportSelection; /* Non-zero means tie internal entry selection + * to X selection. */ + Tk_Font tkfont; /* Information about text font, or NULL. */ + XColor *fgColorPtr; /* Text color in normal mode. */ + XColor *highlightBgColorPtr;/* Color for drawing traversal highlight + * area when highlight is off. */ + XColor *highlightColorPtr; /* Color for drawing traversal highlight. */ + int highlightWidth; /* Width in pixels of highlight to draw + * around widget when it has the focus. + * <= 0 means don't draw a highlight. */ + Tk_3DBorder insertBorder; /* Used to draw vertical bar for insertion + * cursor. */ + int insertBorderWidth; /* Width of 3-D border around insert cursor. */ + int insertOffTime; /* Number of milliseconds cursor should spend + * in "off" state for each blink. */ + int insertOnTime; /* Number of milliseconds cursor should spend + * in "on" state for each blink. */ + int insertWidth; /* Total width of insert cursor. */ + Tk_Justify justify; /* Justification to use for text within + * window. */ + int relief; /* 3-D effect: TK_RELIEF_RAISED, etc. */ + Tk_3DBorder selBorder; /* Border and background for selected + * characters. */ + int selBorderWidth; /* Width of border around selection. */ + XColor *selFgColorPtr; /* Foreground color for selected text. */ + char *showChar; /* Value of -show option. If non-NULL, first + * character is used for displaying all + * characters in entry. Malloc'ed. */ + Tk_Uid state; /* Normal or disabled. Entry is read-only + * when disabled. */ + char *textVarName; /* Name of variable (malloc'ed) or NULL. + * If non-NULL, entry's string tracks the + * contents of this variable and vice versa. */ + char *takeFocus; /* Value of -takefocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + int prefWidth; /* Desired width of window, measured in + * average characters. */ + char *scrollCmd; /* Command prefix for communicating with + * scrollbar(s). Malloc'ed. NULL means + * no command to issue. */ + + /* + * Fields whose values are derived from the current values of the + * configuration settings above. + */ + + int numChars; /* Number of non-NULL characters in + * string (may be 0). */ + char *displayString; /* If non-NULL, points to string with same + * length as string but whose characters + * are all equal to showChar. Malloc'ed. */ + int inset; /* Number of pixels on the left and right + * sides that are taken up by XPAD, borderWidth + * (if any), and highlightWidth (if any). */ + Tk_TextLayout textLayout; /* Cached text layout information. */ + int layoutX, layoutY; /* Origin for layout. */ + int leftIndex; /* Index of left-most character visible in + * window. */ + int leftX; /* X position at which character at leftIndex + * is drawn (varies depending on justify). */ + Tcl_TimerToken insertBlinkHandler; + /* Timer handler used to blink cursor on and + * off. */ + GC textGC; /* For drawing normal text. */ + GC selTextGC; /* For drawing selected text. */ + GC highlightGC; /* For drawing traversal highlight. */ + int avgWidth; /* Width of average character. */ + int flags; /* Miscellaneous flags; see below for + * definitions. */ +} Entry; + +/* + * Assigned bits of "flags" fields of Entry structures, and what those + * bits mean: + * + * REDRAW_PENDING: Non-zero means a DoWhenIdle handler has + * already been queued to redisplay the entry. + * BORDER_NEEDED: Non-zero means 3-D border must be redrawn + * around window during redisplay. Normally + * only text portion needs to be redrawn. + * CURSOR_ON: Non-zero means insert cursor is displayed at + * present. 0 means it isn't displayed. + * GOT_FOCUS: Non-zero means this window has the input + * focus. + * UPDATE_SCROLLBAR: Non-zero means scrollbar should be updated + * during next redisplay operation. + * GOT_SELECTION: Non-zero means we've claimed the selection. + */ + +#define REDRAW_PENDING 1 +#define BORDER_NEEDED 2 +#define CURSOR_ON 4 +#define GOT_FOCUS 8 +#define UPDATE_SCROLLBAR 0x10 +#define GOT_SELECTION 0x20 + +/* + * The following macro defines how many extra pixels to leave on each + * side of the text in the entry. + */ + +#define XPAD 1 +#define YPAD 1 + +/* + * Information used for argv parsing. + */ + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_ENTRY_BG_COLOR, Tk_Offset(Entry, normalBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_ENTRY_BG_MONO, Tk_Offset(Entry, normalBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_ENTRY_BORDER_WIDTH, Tk_Offset(Entry, borderWidth), 0}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_ENTRY_CURSOR, Tk_Offset(Entry, cursor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-exportselection", "exportSelection", + "ExportSelection", DEF_ENTRY_EXPORT_SELECTION, + Tk_Offset(Entry, exportSelection), 0}, + {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_FONT, "-font", "font", "Font", + DEF_ENTRY_FONT, Tk_Offset(Entry, tkfont), 0}, + {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground", + DEF_ENTRY_FG, Tk_Offset(Entry, fgColorPtr), 0}, + {TK_CONFIG_COLOR, "-highlightbackground", "highlightBackground", + "HighlightBackground", DEF_ENTRY_HIGHLIGHT_BG, + Tk_Offset(Entry, highlightBgColorPtr), 0}, + {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor", + DEF_ENTRY_HIGHLIGHT, Tk_Offset(Entry, highlightColorPtr), 0}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", + DEF_ENTRY_HIGHLIGHT_WIDTH, Tk_Offset(Entry, highlightWidth), 0}, + {TK_CONFIG_BORDER, "-insertbackground", "insertBackground", "Foreground", + DEF_ENTRY_INSERT_BG, Tk_Offset(Entry, insertBorder), 0}, + {TK_CONFIG_PIXELS, "-insertborderwidth", "insertBorderWidth", "BorderWidth", + DEF_ENTRY_INSERT_BD_COLOR, Tk_Offset(Entry, insertBorderWidth), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_PIXELS, "-insertborderwidth", "insertBorderWidth", "BorderWidth", + DEF_ENTRY_INSERT_BD_MONO, Tk_Offset(Entry, insertBorderWidth), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_INT, "-insertofftime", "insertOffTime", "OffTime", + DEF_ENTRY_INSERT_OFF_TIME, Tk_Offset(Entry, insertOffTime), 0}, + {TK_CONFIG_INT, "-insertontime", "insertOnTime", "OnTime", + DEF_ENTRY_INSERT_ON_TIME, Tk_Offset(Entry, insertOnTime), 0}, + {TK_CONFIG_PIXELS, "-insertwidth", "insertWidth", "InsertWidth", + DEF_ENTRY_INSERT_WIDTH, Tk_Offset(Entry, insertWidth), 0}, + {TK_CONFIG_JUSTIFY, "-justify", "justify", "Justify", + DEF_ENTRY_JUSTIFY, Tk_Offset(Entry, justify), 0}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_ENTRY_RELIEF, Tk_Offset(Entry, relief), 0}, + {TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Foreground", + DEF_ENTRY_SELECT_COLOR, Tk_Offset(Entry, selBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Foreground", + DEF_ENTRY_SELECT_MONO, Tk_Offset(Entry, selBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_PIXELS, "-selectborderwidth", "selectBorderWidth", "BorderWidth", + DEF_ENTRY_SELECT_BD_COLOR, Tk_Offset(Entry, selBorderWidth), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_PIXELS, "-selectborderwidth", "selectBorderWidth", "BorderWidth", + DEF_ENTRY_SELECT_BD_MONO, Tk_Offset(Entry, selBorderWidth), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Background", + DEF_ENTRY_SELECT_FG_COLOR, Tk_Offset(Entry, selFgColorPtr), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Background", + DEF_ENTRY_SELECT_FG_MONO, Tk_Offset(Entry, selFgColorPtr), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_STRING, "-show", "show", "Show", + DEF_ENTRY_SHOW, Tk_Offset(Entry, showChar), TK_CONFIG_NULL_OK}, + {TK_CONFIG_UID, "-state", "state", "State", + DEF_ENTRY_STATE, Tk_Offset(Entry, state), 0}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_ENTRY_TAKE_FOCUS, Tk_Offset(Entry, takeFocus), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-textvariable", "textVariable", "Variable", + DEF_ENTRY_TEXT_VARIABLE, Tk_Offset(Entry, textVarName), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_INT, "-width", "width", "Width", + DEF_ENTRY_WIDTH, Tk_Offset(Entry, prefWidth), 0}, + {TK_CONFIG_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand", + DEF_ENTRY_SCROLL_COMMAND, Tk_Offset(Entry, scrollCmd), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Flags for GetEntryIndex procedure: + */ + +#define ZERO_OK 1 +#define LAST_PLUS_ONE_OK 2 + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int ConfigureEntry _ANSI_ARGS_((Tcl_Interp *interp, + Entry *entryPtr, int argc, char **argv, + int flags)); +static void DeleteChars _ANSI_ARGS_((Entry *entryPtr, int index, + int count)); +static void DestroyEntry _ANSI_ARGS_((char *memPtr)); +static void DisplayEntry _ANSI_ARGS_((ClientData clientData)); +static void EntryBlinkProc _ANSI_ARGS_((ClientData clientData)); +static void EntryCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static void EntryComputeGeometry _ANSI_ARGS_((Entry *entryPtr)); +static void EntryEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void EntryFocusProc _ANSI_ARGS_ ((Entry *entryPtr, + int gotFocus)); +static int EntryFetchSelection _ANSI_ARGS_((ClientData clientData, + int offset, char *buffer, int maxBytes)); +static void EntryLostSelection _ANSI_ARGS_(( + ClientData clientData)); +static void EventuallyRedraw _ANSI_ARGS_((Entry *entryPtr)); +static void EntryScanTo _ANSI_ARGS_((Entry *entryPtr, int y)); +static void EntrySetValue _ANSI_ARGS_((Entry *entryPtr, + char *value)); +static void EntrySelectTo _ANSI_ARGS_(( + Entry *entryPtr, int index)); +static char * EntryTextVarProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, char *name1, char *name2, + int flags)); +static void EntryUpdateScrollbar _ANSI_ARGS_((Entry *entryPtr)); +static void EntryValueChanged _ANSI_ARGS_((Entry *entryPtr)); +static void EntryVisibleRange _ANSI_ARGS_((Entry *entryPtr, + double *firstPtr, double *lastPtr)); +static int EntryWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void EntryWorldChanged _ANSI_ARGS_(( + ClientData instanceData)); +static int GetEntryIndex _ANSI_ARGS_((Tcl_Interp *interp, + Entry *entryPtr, char *string, int *indexPtr)); +static void InsertChars _ANSI_ARGS_((Entry *entryPtr, int index, + char *string)); + +/* + * The structure below defines entry class behavior by means of procedures + * that can be invoked from generic window code. + */ + +static TkClassProcs entryClass = { + NULL, /* createProc. */ + EntryWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + + +/* + *-------------------------------------------------------------- + * + * Tk_EntryCmd -- + * + * This procedure is invoked to process the "entry" Tcl + * command. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_EntryCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + register Entry *entryPtr; + Tk_Window new; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *) NULL); + if (new == NULL) { + return TCL_ERROR; + } + + /* + * Initialize the fields of the structure that won't be initialized + * by ConfigureEntry, or that ConfigureEntry requires to be + * initialized already (e.g. resource pointers). + */ + + entryPtr = (Entry *) ckalloc(sizeof(Entry)); + entryPtr->tkwin = new; + entryPtr->display = Tk_Display(new); + entryPtr->interp = interp; + entryPtr->widgetCmd = Tcl_CreateCommand(interp, + Tk_PathName(entryPtr->tkwin), EntryWidgetCmd, + (ClientData) entryPtr, EntryCmdDeletedProc); + entryPtr->string = (char *) ckalloc(1); + entryPtr->string[0] = '\0'; + entryPtr->insertPos = 0; + entryPtr->selectFirst = -1; + entryPtr->selectLast = -1; + entryPtr->selectAnchor = 0; + entryPtr->scanMarkX = 0; + entryPtr->scanMarkIndex = 0; + + entryPtr->normalBorder = NULL; + entryPtr->borderWidth = 0; + entryPtr->cursor = None; + entryPtr->exportSelection = 1; + entryPtr->tkfont = NULL; + entryPtr->fgColorPtr = NULL; + entryPtr->highlightBgColorPtr = NULL; + entryPtr->highlightColorPtr = NULL; + entryPtr->highlightWidth = 0; + entryPtr->insertBorder = NULL; + entryPtr->insertBorderWidth = 0; + entryPtr->insertOffTime = 0; + entryPtr->insertOnTime = 0; + entryPtr->insertWidth = 0; + entryPtr->justify = TK_JUSTIFY_LEFT; + entryPtr->relief = TK_RELIEF_FLAT; + entryPtr->selBorder = NULL; + entryPtr->selBorderWidth = 0; + entryPtr->selFgColorPtr = NULL; + entryPtr->showChar = NULL; + entryPtr->state = tkNormalUid; + entryPtr->textVarName = NULL; + entryPtr->takeFocus = NULL; + entryPtr->prefWidth = 0; + entryPtr->scrollCmd = NULL; + + entryPtr->numChars = 0; + entryPtr->displayString = NULL; + entryPtr->inset = XPAD; + entryPtr->textLayout = NULL; + entryPtr->layoutX = 0; + entryPtr->layoutY = 0; + entryPtr->leftIndex = 0; + entryPtr->leftX = 0; + entryPtr->insertBlinkHandler = (Tcl_TimerToken) NULL; + entryPtr->textGC = None; + entryPtr->selTextGC = None; + entryPtr->highlightGC = None; + entryPtr->avgWidth = 1; + entryPtr->flags = 0; + + Tk_SetClass(entryPtr->tkwin, "Entry"); + TkSetClassProcs(entryPtr->tkwin, &entryClass, (ClientData) entryPtr); + Tk_CreateEventHandler(entryPtr->tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + EntryEventProc, (ClientData) entryPtr); + Tk_CreateSelHandler(entryPtr->tkwin, XA_PRIMARY, XA_STRING, + EntryFetchSelection, (ClientData) entryPtr, XA_STRING); + if (ConfigureEntry(interp, entryPtr, argc-2, argv+2, 0) != TCL_OK) { + goto error; + } + + interp->result = Tk_PathName(entryPtr->tkwin); + return TCL_OK; + + error: + Tk_DestroyWindow(entryPtr->tkwin); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * EntryWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a widget managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +EntryWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about entry widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register Entry *entryPtr = (Entry *) clientData; + int result = TCL_OK; + size_t length; + int c; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) entryPtr); + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'b') && (strncmp(argv[1], "bbox", length) == 0)) { + int index; + int x, y, width, height; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " bbox index\"", + (char *) NULL); + goto error; + } + if (GetEntryIndex(interp, entryPtr, argv[2], &index) != TCL_OK) { + goto error; + } + if ((index == entryPtr->numChars) && (index > 0)) { + index--; + } + Tk_CharBbox(entryPtr->textLayout, index, &x, &y, &width, &height); + sprintf(interp->result, "%d %d %d %d", + x + entryPtr->layoutX, y + entryPtr->layoutY, width, height); + } else if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + goto error; + } + result = Tk_ConfigureValue(interp, entryPtr->tkwin, configSpecs, + (char *) entryPtr, argv[2], 0); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 2)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, entryPtr->tkwin, configSpecs, + (char *) entryPtr, (char *) NULL, 0); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, entryPtr->tkwin, configSpecs, + (char *) entryPtr, argv[2], 0); + } else { + result = ConfigureEntry(interp, entryPtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else if ((c == 'd') && (strncmp(argv[1], "delete", length) == 0)) { + int first, last; + + if ((argc < 3) || (argc > 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " delete firstIndex ?lastIndex?\"", + (char *) NULL); + goto error; + } + if (GetEntryIndex(interp, entryPtr, argv[2], &first) != TCL_OK) { + goto error; + } + if (argc == 3) { + last = first+1; + } else { + if (GetEntryIndex(interp, entryPtr, argv[3], &last) != TCL_OK) { + goto error; + } + } + if ((last >= first) && (entryPtr->state == tkNormalUid)) { + DeleteChars(entryPtr, first, last-first); + } + } else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) { + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " get\"", (char *) NULL); + goto error; + } + interp->result = entryPtr->string; + } else if ((c == 'i') && (strncmp(argv[1], "icursor", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " icursor pos\"", + (char *) NULL); + goto error; + } + if (GetEntryIndex(interp, entryPtr, argv[2], &entryPtr->insertPos) + != TCL_OK) { + goto error; + } + EventuallyRedraw(entryPtr); + } else if ((c == 'i') && (strncmp(argv[1], "index", length) == 0) + && (length >= 3)) { + int index; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " index string\"", (char *) NULL); + goto error; + } + if (GetEntryIndex(interp, entryPtr, argv[2], &index) != TCL_OK) { + goto error; + } + sprintf(interp->result, "%d", index); + } else if ((c == 'i') && (strncmp(argv[1], "insert", length) == 0) + && (length >= 3)) { + int index; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " insert index text\"", + (char *) NULL); + goto error; + } + if (GetEntryIndex(interp, entryPtr, argv[2], &index) != TCL_OK) { + goto error; + } + if (entryPtr->state == tkNormalUid) { + InsertChars(entryPtr, index, argv[3]); + } + } else if ((c == 's') && (length >= 2) + && (strncmp(argv[1], "scan", length) == 0)) { + int x; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " scan mark|dragto x\"", (char *) NULL); + goto error; + } + if (Tcl_GetInt(interp, argv[3], &x) != TCL_OK) { + goto error; + } + if ((argv[2][0] == 'm') + && (strncmp(argv[2], "mark", strlen(argv[2])) == 0)) { + entryPtr->scanMarkX = x; + entryPtr->scanMarkIndex = entryPtr->leftIndex; + } else if ((argv[2][0] == 'd') + && (strncmp(argv[2], "dragto", strlen(argv[2])) == 0)) { + EntryScanTo(entryPtr, x); + } else { + Tcl_AppendResult(interp, "bad scan option \"", argv[2], + "\": must be mark or dragto", (char *) NULL); + goto error; + } + } else if ((c == 's') && (length >= 2) + && (strncmp(argv[1], "selection", length) == 0)) { + int index, index2; + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " select option ?index?\"", (char *) NULL); + goto error; + } + length = strlen(argv[2]); + c = argv[2][0]; + if ((c == 'c') && (strncmp(argv[2], "clear", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " selection clear\"", (char *) NULL); + goto error; + } + if (entryPtr->selectFirst != -1) { + entryPtr->selectFirst = entryPtr->selectLast = -1; + EventuallyRedraw(entryPtr); + } + goto done; + } else if ((c == 'p') && (strncmp(argv[2], "present", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " selection present\"", (char *) NULL); + goto error; + } + if (entryPtr->selectFirst == -1) { + interp->result = "0"; + } else { + interp->result = "1"; + } + goto done; + } + if (argc >= 4) { + if (GetEntryIndex(interp, entryPtr, argv[3], &index) != TCL_OK) { + goto error; + } + } + if ((c == 'a') && (strncmp(argv[2], "adjust", length) == 0)) { + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " selection adjust index\"", + (char *) NULL); + goto error; + } + if (entryPtr->selectFirst >= 0) { + int half1, half2; + + half1 = (entryPtr->selectFirst + entryPtr->selectLast)/2; + half2 = (entryPtr->selectFirst + entryPtr->selectLast + 1)/2; + if (index < half1) { + entryPtr->selectAnchor = entryPtr->selectLast; + } else if (index > half2) { + entryPtr->selectAnchor = entryPtr->selectFirst; + } else { + /* + * We're at about the halfway point in the selection; + * just keep the existing anchor. + */ + } + } + EntrySelectTo(entryPtr, index); + } else if ((c == 'f') && (strncmp(argv[2], "from", length) == 0)) { + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " selection from index\"", + (char *) NULL); + goto error; + } + entryPtr->selectAnchor = index; + } else if ((c == 'r') && (strncmp(argv[2], "range", length) == 0)) { + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " selection range start end\"", + (char *) NULL); + goto error; + } + if (GetEntryIndex(interp, entryPtr, argv[4], &index2) != TCL_OK) { + goto error; + } + if (index >= index2) { + entryPtr->selectFirst = entryPtr->selectLast = -1; + } else { + entryPtr->selectFirst = index; + entryPtr->selectLast = index2; + } + if (!(entryPtr->flags & GOT_SELECTION) + && (entryPtr->exportSelection)) { + Tk_OwnSelection(entryPtr->tkwin, XA_PRIMARY, + EntryLostSelection, (ClientData) entryPtr); + entryPtr->flags |= GOT_SELECTION; + } + EventuallyRedraw(entryPtr); + } else if ((c == 't') && (strncmp(argv[2], "to", length) == 0)) { + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " selection to index\"", + (char *) NULL); + goto error; + } + EntrySelectTo(entryPtr, index); + } else { + Tcl_AppendResult(interp, "bad selection option \"", argv[2], + "\": must be adjust, clear, from, present, range, or to", + (char *) NULL); + goto error; + } + } else if ((c == 'x') && (strncmp(argv[1], "xview", length) == 0)) { + int index, type, count, charsPerPage; + double fraction, first, last; + + if (argc == 2) { + EntryVisibleRange(entryPtr, &first, &last); + sprintf(interp->result, "%g %g", first, last); + goto done; + } else if (argc == 3) { + if (GetEntryIndex(interp, entryPtr, argv[2], &index) != TCL_OK) { + goto error; + } + } else { + type = Tk_GetScrollInfo(interp, argc, argv, &fraction, &count); + index = entryPtr->leftIndex; + switch (type) { + case TK_SCROLL_ERROR: + goto error; + case TK_SCROLL_MOVETO: + index = (int) ((fraction * entryPtr->numChars) + 0.5); + break; + case TK_SCROLL_PAGES: + charsPerPage = ((Tk_Width(entryPtr->tkwin) + - 2*entryPtr->inset) / entryPtr->avgWidth) - 2; + if (charsPerPage < 1) { + charsPerPage = 1; + } + index += charsPerPage*count; + break; + case TK_SCROLL_UNITS: + index += count; + break; + } + } + if (index >= entryPtr->numChars) { + index = entryPtr->numChars-1; + } + if (index < 0) { + index = 0; + } + entryPtr->leftIndex = index; + entryPtr->flags |= UPDATE_SCROLLBAR; + EntryComputeGeometry(entryPtr); + EventuallyRedraw(entryPtr); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be bbox, cget, configure, delete, get, ", + "icursor, index, insert, scan, selection, or xview", + (char *) NULL); + goto error; + } + done: + Tcl_Release((ClientData) entryPtr); + return result; + + error: + Tcl_Release((ClientData) entryPtr); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyEntry -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of an entry at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the entry is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyEntry(memPtr) + char *memPtr; /* Info about entry widget. */ +{ + register Entry *entryPtr = (Entry *) memPtr; + + /* + * Free up all the stuff that requires special handling, then + * let Tk_FreeOptions handle all the standard option-related + * stuff. + */ + + ckfree(entryPtr->string); + if (entryPtr->textVarName != NULL) { + Tcl_UntraceVar(entryPtr->interp, entryPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + EntryTextVarProc, (ClientData) entryPtr); + } + if (entryPtr->textGC != None) { + Tk_FreeGC(entryPtr->display, entryPtr->textGC); + } + if (entryPtr->selTextGC != None) { + Tk_FreeGC(entryPtr->display, entryPtr->selTextGC); + } + Tcl_DeleteTimerHandler(entryPtr->insertBlinkHandler); + if (entryPtr->displayString != NULL) { + ckfree(entryPtr->displayString); + } + Tk_FreeTextLayout(entryPtr->textLayout); + Tk_FreeOptions(configSpecs, (char *) entryPtr, entryPtr->display, 0); + ckfree((char *) entryPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureEntry -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or reconfigure) + * an entry widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as colors, border width, + * etc. get set for entryPtr; old resources get freed, + * if there were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureEntry(interp, entryPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + register Entry *entryPtr; /* Information about widget; may or may + * not already have values for some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + int oldExport; + + /* + * Eliminate any existing trace on a variable monitored by the entry. + */ + + if (entryPtr->textVarName != NULL) { + Tcl_UntraceVar(interp, entryPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + EntryTextVarProc, (ClientData) entryPtr); + } + + oldExport = entryPtr->exportSelection; + if (Tk_ConfigureWidget(interp, entryPtr->tkwin, configSpecs, + argc, argv, (char *) entryPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * If the entry is tied to the value of a variable, then set up + * a trace on the variable's value, create the variable if it doesn't + * exist, and set the entry's value from the variable's value. + */ + + if (entryPtr->textVarName != NULL) { + char *value; + + value = Tcl_GetVar(interp, entryPtr->textVarName, TCL_GLOBAL_ONLY); + if (value == NULL) { + EntryValueChanged(entryPtr); + } else { + EntrySetValue(entryPtr, value); + } + Tcl_TraceVar(interp, entryPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + EntryTextVarProc, (ClientData) entryPtr); + } + + /* + * A few other options also need special processing, such as parsing + * the geometry and setting the background from a 3-D border. + */ + + if ((entryPtr->state != tkNormalUid) + && (entryPtr->state != tkDisabledUid)) { + Tcl_AppendResult(interp, "bad state value \"", entryPtr->state, + "\": must be normal or disabled", (char *) NULL); + entryPtr->state = tkNormalUid; + return TCL_ERROR; + } + + Tk_SetBackgroundFromBorder(entryPtr->tkwin, entryPtr->normalBorder); + + if (entryPtr->insertWidth <= 0) { + entryPtr->insertWidth = 2; + } + if (entryPtr->insertBorderWidth > entryPtr->insertWidth/2) { + entryPtr->insertBorderWidth = entryPtr->insertWidth/2; + } + + /* + * Restart the cursor timing sequence in case the on-time or off-time + * just changed. + */ + + if (entryPtr->flags & GOT_FOCUS) { + EntryFocusProc(entryPtr, 1); + } + + /* + * Claim the selection if we've suddenly started exporting it. + */ + + if (entryPtr->exportSelection && (!oldExport) + && (entryPtr->selectFirst != -1) + && !(entryPtr->flags & GOT_SELECTION)) { + Tk_OwnSelection(entryPtr->tkwin, XA_PRIMARY, EntryLostSelection, + (ClientData) entryPtr); + entryPtr->flags |= GOT_SELECTION; + } + + /* + * Recompute the window's geometry and arrange for it to be + * redisplayed. + */ + + Tk_SetInternalBorder(entryPtr->tkwin, + entryPtr->borderWidth + entryPtr->highlightWidth); + if (entryPtr->highlightWidth <= 0) { + entryPtr->highlightWidth = 0; + } + entryPtr->inset = entryPtr->highlightWidth + entryPtr->borderWidth + XPAD; + + EntryWorldChanged((ClientData) entryPtr); + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * EntryWorldChanged -- + * + * This procedure is called when the world has changed in some + * way and the widget needs to recompute all its graphics contexts + * and determine its new geometry. + * + * Results: + * None. + * + * Side effects: + * Entry will be relayed out and redisplayed. + * + *--------------------------------------------------------------------------- + */ + +static void +EntryWorldChanged(instanceData) + ClientData instanceData; /* Information about widget. */ +{ + XGCValues gcValues; + GC gc; + unsigned long mask; + Entry *entryPtr; + + entryPtr = (Entry *) instanceData; + + entryPtr->avgWidth = Tk_TextWidth(entryPtr->tkfont, "0", 1); + if (entryPtr->avgWidth == 0) { + entryPtr->avgWidth = 1; + } + + gcValues.foreground = entryPtr->fgColorPtr->pixel; + gcValues.font = Tk_FontId(entryPtr->tkfont); + gcValues.graphics_exposures = False; + mask = GCForeground | GCFont | GCGraphicsExposures; + gc = Tk_GetGC(entryPtr->tkwin, mask, &gcValues); + if (entryPtr->textGC != None) { + Tk_FreeGC(entryPtr->display, entryPtr->textGC); + } + entryPtr->textGC = gc; + + gcValues.foreground = entryPtr->selFgColorPtr->pixel; + gcValues.font = Tk_FontId(entryPtr->tkfont); + mask = GCForeground | GCFont; + gc = Tk_GetGC(entryPtr->tkwin, mask, &gcValues); + if (entryPtr->selTextGC != None) { + Tk_FreeGC(entryPtr->display, entryPtr->selTextGC); + } + entryPtr->selTextGC = gc; + + /* + * Recompute the window's geometry and arrange for it to be + * redisplayed. + */ + + EntryComputeGeometry(entryPtr); + entryPtr->flags |= UPDATE_SCROLLBAR; + EventuallyRedraw(entryPtr); +} + +/* + *-------------------------------------------------------------- + * + * DisplayEntry -- + * + * This procedure redraws the contents of an entry window. + * + * Results: + * None. + * + * Side effects: + * Information appears on the screen. + * + *-------------------------------------------------------------- + */ + +static void +DisplayEntry(clientData) + ClientData clientData; /* Information about window. */ +{ + register Entry *entryPtr = (Entry *) clientData; + register Tk_Window tkwin = entryPtr->tkwin; + int baseY, selStartX, selEndX, cursorX, x, w; + int xBound; + Tk_FontMetrics fm; + Pixmap pixmap; + int showSelection; + + entryPtr->flags &= ~REDRAW_PENDING; + if ((entryPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + return; + } + + Tk_GetFontMetrics(entryPtr->tkfont, &fm); + + /* + * Update the scrollbar if that's needed. + */ + + if (entryPtr->flags & UPDATE_SCROLLBAR) { + entryPtr->flags &= ~UPDATE_SCROLLBAR; + EntryUpdateScrollbar(entryPtr); + } + + /* + * In order to avoid screen flashes, this procedure redraws the + * textual area of the entry into off-screen memory, then copies + * it back on-screen in a single operation. This means there's + * no point in time where the on-screen image has been cleared. + */ + + pixmap = Tk_GetPixmap(entryPtr->display, Tk_WindowId(tkwin), + Tk_Width(tkwin), Tk_Height(tkwin), Tk_Depth(tkwin)); + + /* + * Compute x-coordinate of the pixel just after last visible + * one, plus vertical position of baseline of text. + */ + + xBound = Tk_Width(tkwin) - entryPtr->inset; + baseY = (Tk_Height(tkwin) + fm.ascent - fm.descent) / 2; + + /* + * On Windows and Mac, we need to hide the selection whenever we + * don't have the focus. + */ + +#ifdef ALWAYS_SHOW_SELECTION + showSelection = 1; +#else + showSelection = (entryPtr->flags & GOT_FOCUS); +#endif + + /* + * Draw the background in three layers. From bottom to top the + * layers are: normal background, selection background, and + * insertion cursor background. + */ + + Tk_Fill3DRectangle(tkwin, pixmap, entryPtr->normalBorder, + 0, 0, Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); + if (showSelection && (entryPtr->selectLast > entryPtr->leftIndex)) { + if (entryPtr->selectFirst <= entryPtr->leftIndex) { + selStartX = entryPtr->leftX; + } else { + Tk_CharBbox(entryPtr->textLayout, entryPtr->selectFirst, + &x, NULL, NULL, NULL); + selStartX = x + entryPtr->layoutX; + } + if ((selStartX - entryPtr->selBorderWidth) < xBound) { + Tk_CharBbox(entryPtr->textLayout, entryPtr->selectLast - 1, + &x, NULL, &w, NULL); + selEndX = x + w + entryPtr->layoutX; + Tk_Fill3DRectangle(tkwin, pixmap, entryPtr->selBorder, + selStartX - entryPtr->selBorderWidth, + baseY - fm.ascent - entryPtr->selBorderWidth, + (selEndX - selStartX) + 2*entryPtr->selBorderWidth, + (fm.ascent + fm.descent) + 2*entryPtr->selBorderWidth, + entryPtr->selBorderWidth, TK_RELIEF_RAISED); + } + } + + /* + * Draw a special background for the insertion cursor, overriding + * even the selection background. As a special hack to keep the + * cursor visible when the insertion cursor color is the same as + * the color for selected text (e.g., on mono displays), write + * background in the cursor area (instead of nothing) when the + * cursor isn't on. Otherwise the selection would hide the cursor. + */ + + if ((entryPtr->insertPos >= entryPtr->leftIndex) + && (entryPtr->state == tkNormalUid) + && (entryPtr->flags & GOT_FOCUS)) { + if (entryPtr->insertPos == 0) { + cursorX = 0; + } else if (entryPtr->insertPos >= entryPtr->numChars) { + Tk_CharBbox(entryPtr->textLayout, entryPtr->numChars - 1, + &x, NULL, &w, NULL); + cursorX = x + w; + } else { + Tk_CharBbox(entryPtr->textLayout, entryPtr->insertPos, + &x, NULL, NULL, NULL); + cursorX = x; + } + cursorX += entryPtr->layoutX; + cursorX -= (entryPtr->insertWidth)/2; + if (cursorX < xBound) { + if (entryPtr->flags & CURSOR_ON) { + Tk_Fill3DRectangle(tkwin, pixmap, entryPtr->insertBorder, + cursorX, baseY - fm.ascent, + entryPtr->insertWidth, fm.ascent + fm.descent, + entryPtr->insertBorderWidth, TK_RELIEF_RAISED); + } else if (entryPtr->insertBorder == entryPtr->selBorder) { + Tk_Fill3DRectangle(tkwin, pixmap, entryPtr->normalBorder, + cursorX, baseY - fm.ascent, + entryPtr->insertWidth, fm.ascent + fm.descent, + 0, TK_RELIEF_FLAT); + } + } + } + + /* + * Draw the text in two pieces: first the unselected portion, then the + * selected portion on top of it. + */ + + Tk_DrawTextLayout(entryPtr->display, pixmap, entryPtr->textGC, + entryPtr->textLayout, entryPtr->layoutX, entryPtr->layoutY, + entryPtr->leftIndex, entryPtr->numChars); + + if (showSelection && (entryPtr->selTextGC != entryPtr->textGC) && + (entryPtr->selectFirst < entryPtr->selectLast)) { + int first; + + if (entryPtr->selectFirst - entryPtr->leftIndex < 0) { + first = entryPtr->leftIndex; + } else { + first = entryPtr->selectFirst; + } + Tk_DrawTextLayout(entryPtr->display, pixmap, entryPtr->selTextGC, + entryPtr->textLayout, entryPtr->layoutX, entryPtr->layoutY, + first, entryPtr->selectLast); + } + + /* + * Draw the border and focus highlight last, so they will overwrite + * any text that extends past the viewable part of the window. + */ + + if (entryPtr->relief != TK_RELIEF_FLAT) { + Tk_Draw3DRectangle(tkwin, pixmap, entryPtr->normalBorder, + entryPtr->highlightWidth, entryPtr->highlightWidth, + Tk_Width(tkwin) - 2*entryPtr->highlightWidth, + Tk_Height(tkwin) - 2*entryPtr->highlightWidth, + entryPtr->borderWidth, entryPtr->relief); + } + if (entryPtr->highlightWidth != 0) { + GC gc; + + if (entryPtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(entryPtr->highlightColorPtr, pixmap); + } else { + gc = Tk_GCForColor(entryPtr->highlightBgColorPtr, pixmap); + } + Tk_DrawFocusHighlight(tkwin, gc, entryPtr->highlightWidth, pixmap); + } + + /* + * Everything's been redisplayed; now copy the pixmap onto the screen + * and free up the pixmap. + */ + + XCopyArea(entryPtr->display, pixmap, Tk_WindowId(tkwin), entryPtr->textGC, + 0, 0, (unsigned) Tk_Width(tkwin), (unsigned) Tk_Height(tkwin), + 0, 0); + Tk_FreePixmap(entryPtr->display, pixmap); + entryPtr->flags &= ~BORDER_NEEDED; +} + +/* + *---------------------------------------------------------------------- + * + * EntryComputeGeometry -- + * + * This procedure is invoked to recompute information about where + * in its window an entry's string will be displayed. It also + * computes the requested size for the window. + * + * Results: + * None. + * + * Side effects: + * The leftX and tabOrigin fields are recomputed for entryPtr, + * and leftIndex may be adjusted. Tk_GeometryRequest is called + * to register the desired dimensions for the window. + * + *---------------------------------------------------------------------- + */ + +static void +EntryComputeGeometry(entryPtr) + Entry *entryPtr; /* Widget record for entry. */ +{ + int totalLength, overflow, maxOffScreen, rightX; + int height, width, i; + Tk_FontMetrics fm; + char *p, *displayString; + + /* + * If we're displaying a special character instead of the value of + * the entry, recompute the displayString. + */ + + if (entryPtr->displayString != NULL) { + ckfree(entryPtr->displayString); + entryPtr->displayString = NULL; + } + if (entryPtr->showChar != NULL) { + entryPtr->displayString = (char *) ckalloc((unsigned) + (entryPtr->numChars + 1)); + for (p = entryPtr->displayString, i = entryPtr->numChars; i > 0; + i--, p++) { + *p = entryPtr->showChar[0]; + } + *p = 0; + displayString = entryPtr->displayString; + } else { + displayString = entryPtr->string; + } + Tk_FreeTextLayout(entryPtr->textLayout); + entryPtr->textLayout = Tk_ComputeTextLayout(entryPtr->tkfont, + displayString, entryPtr->numChars, 0, entryPtr->justify, + TK_IGNORE_NEWLINES, &totalLength, &height); + + entryPtr->layoutY = (Tk_Height(entryPtr->tkwin) - height) / 2; + + /* + * Recompute where the leftmost character on the display will + * be drawn (entryPtr->leftX) and adjust leftIndex if necessary + * so that we don't let characters hang off the edge of the + * window unless the entire window is full. + */ + + overflow = totalLength - (Tk_Width(entryPtr->tkwin) - 2*entryPtr->inset); + if (overflow <= 0) { + entryPtr->leftIndex = 0; + if (entryPtr->justify == TK_JUSTIFY_LEFT) { + entryPtr->leftX = entryPtr->inset; + } else if (entryPtr->justify == TK_JUSTIFY_RIGHT) { + entryPtr->leftX = Tk_Width(entryPtr->tkwin) - entryPtr->inset + - totalLength; + } else { + entryPtr->leftX = (Tk_Width(entryPtr->tkwin) - totalLength)/2; + } + entryPtr->layoutX = entryPtr->leftX; + } else { + /* + * The whole string can't fit in the window. Compute the + * maximum number of characters that may be off-screen to + * the left without leaving empty space on the right of the + * window, then don't let leftIndex be any greater than that. + */ + + maxOffScreen = Tk_PointToChar(entryPtr->textLayout, overflow, 0); + Tk_CharBbox(entryPtr->textLayout, maxOffScreen, + &rightX, NULL, NULL, NULL); + if (rightX < overflow) { + maxOffScreen += 1; + } + if (entryPtr->leftIndex > maxOffScreen) { + entryPtr->leftIndex = maxOffScreen; + } + Tk_CharBbox(entryPtr->textLayout, entryPtr->leftIndex, + &rightX, NULL, NULL, NULL); + entryPtr->leftX = entryPtr->inset; + entryPtr->layoutX = entryPtr->leftX - rightX; + } + + Tk_GetFontMetrics(entryPtr->tkfont, &fm); + height = fm.linespace + 2*entryPtr->inset + 2*(YPAD-XPAD); + if (entryPtr->prefWidth > 0) { + width = entryPtr->prefWidth*entryPtr->avgWidth + 2*entryPtr->inset; + } else { + if (totalLength == 0) { + width = entryPtr->avgWidth + 2*entryPtr->inset; + } else { + width = totalLength + 2*entryPtr->inset; + } + } + Tk_GeometryRequest(entryPtr->tkwin, width, height); +} + +/* + *---------------------------------------------------------------------- + * + * InsertChars -- + * + * Add new characters to an entry widget. + * + * Results: + * None. + * + * Side effects: + * New information gets added to entryPtr; it will be redisplayed + * soon, but not necessarily immediately. + * + *---------------------------------------------------------------------- + */ + +static void +InsertChars(entryPtr, index, string) + register Entry *entryPtr; /* Entry that is to get the new + * elements. */ + int index; /* Add the new elements before this + * element. */ + char *string; /* New characters to add (NULL-terminated + * string). */ +{ + int length; + char *new; + + length = strlen(string); + if (length == 0) { + return; + } + new = (char *) ckalloc((unsigned) (entryPtr->numChars + length + 1)); + strncpy(new, entryPtr->string, (size_t) index); + strcpy(new+index, string); + strcpy(new+index+length, entryPtr->string+index); + ckfree(entryPtr->string); + entryPtr->string = new; + entryPtr->numChars += length; + + /* + * Inserting characters invalidates all indexes into the string. + * Touch up the indexes so that they still refer to the same + * characters (at new positions). When updating the selection + * end-points, don't include the new text in the selection unless + * it was completely surrounded by the selection. + */ + + if (entryPtr->selectFirst >= index) { + entryPtr->selectFirst += length; + } + if (entryPtr->selectLast > index) { + entryPtr->selectLast += length; + } + if ((entryPtr->selectAnchor > index) || (entryPtr->selectFirst >= index)) { + entryPtr->selectAnchor += length; + } + if (entryPtr->leftIndex > index) { + entryPtr->leftIndex += length; + } + if (entryPtr->insertPos >= index) { + entryPtr->insertPos += length; + } + EntryValueChanged(entryPtr); +} + +/* + *---------------------------------------------------------------------- + * + * DeleteChars -- + * + * Remove one or more characters from an entry widget. + * + * Results: + * None. + * + * Side effects: + * Memory gets freed, the entry gets modified and (eventually) + * redisplayed. + * + *---------------------------------------------------------------------- + */ + +static void +DeleteChars(entryPtr, index, count) + register Entry *entryPtr; /* Entry widget to modify. */ + int index; /* Index of first character to delete. */ + int count; /* How many characters to delete. */ +{ + char *new; + + if ((index + count) > entryPtr->numChars) { + count = entryPtr->numChars - index; + } + if (count <= 0) { + return; + } + + new = (char *) ckalloc((unsigned) (entryPtr->numChars + 1 - count)); + strncpy(new, entryPtr->string, (size_t) index); + strcpy(new+index, entryPtr->string+index+count); + ckfree(entryPtr->string); + entryPtr->string = new; + entryPtr->numChars -= count; + + /* + * Deleting characters results in the remaining characters being + * renumbered. Update the various indexes into the string to reflect + * this change. + */ + + if (entryPtr->selectFirst >= index) { + if (entryPtr->selectFirst >= (index+count)) { + entryPtr->selectFirst -= count; + } else { + entryPtr->selectFirst = index; + } + } + if (entryPtr->selectLast >= index) { + if (entryPtr->selectLast >= (index+count)) { + entryPtr->selectLast -= count; + } else { + entryPtr->selectLast = index; + } + } + if (entryPtr->selectLast <= entryPtr->selectFirst) { + entryPtr->selectFirst = entryPtr->selectLast = -1; + } + if (entryPtr->selectAnchor >= index) { + if (entryPtr->selectAnchor >= (index+count)) { + entryPtr->selectAnchor -= count; + } else { + entryPtr->selectAnchor = index; + } + } + if (entryPtr->leftIndex > index) { + if (entryPtr->leftIndex >= (index+count)) { + entryPtr->leftIndex -= count; + } else { + entryPtr->leftIndex = index; + } + } + if (entryPtr->insertPos >= index) { + if (entryPtr->insertPos >= (index+count)) { + entryPtr->insertPos -= count; + } else { + entryPtr->insertPos = index; + } + } + EntryValueChanged(entryPtr); +} + +/* + *---------------------------------------------------------------------- + * + * EntryValueChanged -- + * + * This procedure is invoked when characters are inserted into + * an entry or deleted from it. It updates the entry's associated + * variable, if there is one, and does other bookkeeping such + * as arranging for redisplay. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +EntryValueChanged(entryPtr) + Entry *entryPtr; /* Entry whose value just changed. */ +{ + char *newValue; + + if (entryPtr->textVarName == NULL) { + newValue = NULL; + } else { + newValue = Tcl_SetVar(entryPtr->interp, entryPtr->textVarName, + entryPtr->string, TCL_GLOBAL_ONLY); + } + + if ((newValue != NULL) && (strcmp(newValue, entryPtr->string) != 0)) { + /* + * The value of the variable is different than what we asked for. + * This means that a trace on the variable modified it. In this + * case our trace procedure wasn't invoked since the modification + * came while a trace was already active on the variable. So, + * update our value to reflect the variable's latest value. + */ + + EntrySetValue(entryPtr, newValue); + } else { + /* + * Arrange for redisplay. + */ + + entryPtr->flags |= UPDATE_SCROLLBAR; + EntryComputeGeometry(entryPtr); + EventuallyRedraw(entryPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * EntrySetValue -- + * + * Replace the contents of a text entry with a given value. This + * procedure is invoked when updating the entry from the entry's + * associated variable. + * + * Results: + * None. + * + * Side effects: + * The string displayed in the entry will change. The selection, + * insertion point, and view may have to be adjusted to keep them + * within the bounds of the new string. Note: this procedure does + * *not* update the entry's associated variable, since that could + * result in an infinite loop. + * + *---------------------------------------------------------------------- + */ + +static void +EntrySetValue(entryPtr, value) + register Entry *entryPtr; /* Entry whose value is to be + * changed. */ + char *value; /* New text to display in entry. */ +{ + ckfree(entryPtr->string); + entryPtr->numChars = strlen(value); + entryPtr->string = (char *) ckalloc((unsigned) (entryPtr->numChars + 1)); + strcpy(entryPtr->string, value); + if (entryPtr->selectFirst != -1) { + if (entryPtr->selectFirst >= entryPtr->numChars) { + entryPtr->selectFirst = entryPtr->selectLast = -1; + } else if (entryPtr->selectLast > entryPtr->numChars) { + entryPtr->selectLast = entryPtr->numChars; + } + } + if (entryPtr->leftIndex >= entryPtr->numChars) { + entryPtr->leftIndex = entryPtr->numChars-1; + if (entryPtr->leftIndex < 0) { + entryPtr->leftIndex = 0; + } + } + if (entryPtr->insertPos > entryPtr->numChars) { + entryPtr->insertPos = entryPtr->numChars; + } + + entryPtr->flags |= UPDATE_SCROLLBAR; + EntryComputeGeometry(entryPtr); + EventuallyRedraw(entryPtr); +} + +/* + *-------------------------------------------------------------- + * + * EntryEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on entryes. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +EntryEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + Entry *entryPtr = (Entry *) clientData; + if (eventPtr->type == Expose) { + EventuallyRedraw(entryPtr); + entryPtr->flags |= BORDER_NEEDED; + } else if (eventPtr->type == DestroyNotify) { + if (entryPtr->tkwin != NULL) { + entryPtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(entryPtr->interp, entryPtr->widgetCmd); + } + if (entryPtr->flags & REDRAW_PENDING) { + Tcl_CancelIdleCall(DisplayEntry, (ClientData) entryPtr); + } + Tcl_EventuallyFree((ClientData) entryPtr, DestroyEntry); + } else if (eventPtr->type == ConfigureNotify) { + Tcl_Preserve((ClientData) entryPtr); + entryPtr->flags |= UPDATE_SCROLLBAR; + EntryComputeGeometry(entryPtr); + EventuallyRedraw(entryPtr); + Tcl_Release((ClientData) entryPtr); + } else if (eventPtr->type == FocusIn) { + if (eventPtr->xfocus.detail != NotifyInferior) { + EntryFocusProc(entryPtr, 1); + } + } else if (eventPtr->type == FocusOut) { + if (eventPtr->xfocus.detail != NotifyInferior) { + EntryFocusProc(entryPtr, 0); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * EntryCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +EntryCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + Entry *entryPtr = (Entry *) clientData; + Tk_Window tkwin = entryPtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + entryPtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *-------------------------------------------------------------- + * + * GetEntryIndex -- + * + * Parse an index into an entry and return either its value + * or an error. + * + * Results: + * A standard Tcl result. If all went well, then *indexPtr is + * filled in with the index (into entryPtr) corresponding to + * string. The index value is guaranteed to lie between 0 and + * the number of characters in the string, inclusive. If an + * error occurs then an error message is left in interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +GetEntryIndex(interp, entryPtr, string, indexPtr) + Tcl_Interp *interp; /* For error messages. */ + Entry *entryPtr; /* Entry for which the index is being + * specified. */ + char *string; /* Specifies character in entryPtr. */ + int *indexPtr; /* Where to store converted index. */ +{ + size_t length; + + length = strlen(string); + + if (string[0] == 'a') { + if (strncmp(string, "anchor", length) == 0) { + *indexPtr = entryPtr->selectAnchor; + } else { + badIndex: + + /* + * Some of the paths here leave messages in interp->result, + * so we have to clear it out before storing our own message. + */ + + Tcl_SetResult(interp, (char *) NULL, TCL_STATIC); + Tcl_AppendResult(interp, "bad entry index \"", string, + "\"", (char *) NULL); + return TCL_ERROR; + } + } else if (string[0] == 'e') { + if (strncmp(string, "end", length) == 0) { + *indexPtr = entryPtr->numChars; + } else { + goto badIndex; + } + } else if (string[0] == 'i') { + if (strncmp(string, "insert", length) == 0) { + *indexPtr = entryPtr->insertPos; + } else { + goto badIndex; + } + } else if (string[0] == 's') { + if (entryPtr->selectFirst == -1) { + interp->result = "selection isn't in entry"; + return TCL_ERROR; + } + if (length < 5) { + goto badIndex; + } + if (strncmp(string, "sel.first", length) == 0) { + *indexPtr = entryPtr->selectFirst; + } else if (strncmp(string, "sel.last", length) == 0) { + *indexPtr = entryPtr->selectLast; + } else { + goto badIndex; + } + } else if (string[0] == '@') { + int x, roundUp; + + if (Tcl_GetInt(interp, string+1, &x) != TCL_OK) { + goto badIndex; + } + if (x < entryPtr->inset) { + x = entryPtr->inset; + } + roundUp = 0; + if (x >= (Tk_Width(entryPtr->tkwin) - entryPtr->inset)) { + x = Tk_Width(entryPtr->tkwin) - entryPtr->inset - 1; + roundUp = 1; + } + *indexPtr = Tk_PointToChar(entryPtr->textLayout, + x - entryPtr->layoutX, 0); + + /* + * Special trick: if the x-position was off-screen to the right, + * round the index up to refer to the character just after the + * last visible one on the screen. This is needed to enable the + * last character to be selected, for example. + */ + + if (roundUp && (*indexPtr < entryPtr->numChars)) { + *indexPtr += 1; + } + } else { + if (Tcl_GetInt(interp, string, indexPtr) != TCL_OK) { + goto badIndex; + } + if (*indexPtr < 0){ + *indexPtr = 0; + } else if (*indexPtr > entryPtr->numChars) { + *indexPtr = entryPtr->numChars; + } + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * EntryScanTo -- + * + * Given a y-coordinate (presumably of the curent mouse location) + * drag the view in the window to implement the scan operation. + * + * Results: + * None. + * + * Side effects: + * The view in the window may change. + * + *---------------------------------------------------------------------- + */ + +static void +EntryScanTo(entryPtr, x) + register Entry *entryPtr; /* Information about widget. */ + int x; /* X-coordinate to use for scan + * operation. */ +{ + int newLeftIndex; + + /* + * Compute new leftIndex for entry by amplifying the difference + * between the current position and the place where the scan + * started (the "mark" position). If we run off the left or right + * side of the entry, then reset the mark point so that the current + * position continues to correspond to the edge of the window. + * This means that the picture will start dragging as soon as the + * mouse reverses direction (without this reset, might have to slide + * mouse a long ways back before the picture starts moving again). + */ + + newLeftIndex = entryPtr->scanMarkIndex + - (10*(x - entryPtr->scanMarkX))/entryPtr->avgWidth; + if (newLeftIndex >= entryPtr->numChars) { + newLeftIndex = entryPtr->scanMarkIndex = entryPtr->numChars-1; + entryPtr->scanMarkX = x; + } + if (newLeftIndex < 0) { + newLeftIndex = entryPtr->scanMarkIndex = 0; + entryPtr->scanMarkX = x; + } + if (newLeftIndex != entryPtr->leftIndex) { + entryPtr->leftIndex = newLeftIndex; + entryPtr->flags |= UPDATE_SCROLLBAR; + EntryComputeGeometry(entryPtr); + EventuallyRedraw(entryPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * EntrySelectTo -- + * + * Modify the selection by moving its un-anchored end. This could + * make the selection either larger or smaller. + * + * Results: + * None. + * + * Side effects: + * The selection changes. + * + *---------------------------------------------------------------------- + */ + +static void +EntrySelectTo(entryPtr, index) + register Entry *entryPtr; /* Information about widget. */ + int index; /* Index of element that is to + * become the "other" end of the + * selection. */ +{ + int newFirst, newLast; + + /* + * Grab the selection if we don't own it already. + */ + + if (!(entryPtr->flags & GOT_SELECTION) && (entryPtr->exportSelection)) { + Tk_OwnSelection(entryPtr->tkwin, XA_PRIMARY, EntryLostSelection, + (ClientData) entryPtr); + entryPtr->flags |= GOT_SELECTION; + } + + /* + * Pick new starting and ending points for the selection. + */ + + if (entryPtr->selectAnchor > entryPtr->numChars) { + entryPtr->selectAnchor = entryPtr->numChars; + } + if (entryPtr->selectAnchor <= index) { + newFirst = entryPtr->selectAnchor; + newLast = index; + } else { + newFirst = index; + newLast = entryPtr->selectAnchor; + if (newLast < 0) { + newFirst = newLast = -1; + } + } + if ((entryPtr->selectFirst == newFirst) + && (entryPtr->selectLast == newLast)) { + return; + } + entryPtr->selectFirst = newFirst; + entryPtr->selectLast = newLast; + EventuallyRedraw(entryPtr); +} + +/* + *---------------------------------------------------------------------- + * + * EntryFetchSelection -- + * + * This procedure is called back by Tk when the selection is + * requested by someone. It returns part or all of the selection + * in a buffer provided by the caller. + * + * Results: + * The return value is the number of non-NULL bytes stored + * at buffer. Buffer is filled (or partially filled) with a + * NULL-terminated string containing part or all of the selection, + * as given by offset and maxBytes. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +EntryFetchSelection(clientData, offset, buffer, maxBytes) + ClientData clientData; /* Information about entry widget. */ + int offset; /* Offset within selection of first + * character to be returned. */ + char *buffer; /* Location in which to place + * selection. */ + int maxBytes; /* Maximum number of bytes to place + * at buffer, not including terminating + * NULL character. */ +{ + Entry *entryPtr = (Entry *) clientData; + int count; + char *displayString; + + if ((entryPtr->selectFirst < 0) || !(entryPtr->exportSelection)) { + return -1; + } + count = entryPtr->selectLast - entryPtr->selectFirst - offset; + if (count > maxBytes) { + count = maxBytes; + } + if (count <= 0) { + return 0; + } + if (entryPtr->displayString == NULL) { + displayString = entryPtr->string; + } else { + displayString = entryPtr->displayString; + } + strncpy(buffer, displayString + entryPtr->selectFirst + offset, + (size_t) count); + buffer[count] = '\0'; + return count; +} + +/* + *---------------------------------------------------------------------- + * + * EntryLostSelection -- + * + * This procedure is called back by Tk when the selection is + * grabbed away from an entry widget. + * + * Results: + * None. + * + * Side effects: + * The existing selection is unhighlighted, and the window is + * marked as not containing a selection. + * + *---------------------------------------------------------------------- + */ + +static void +EntryLostSelection(clientData) + ClientData clientData; /* Information about entry widget. */ +{ + Entry *entryPtr = (Entry *) clientData; + + entryPtr->flags &= ~GOT_SELECTION; + + /* + * On Windows and Mac systems, we want to remember the selection + * for the next time the focus enters the window. On Unix, we need + * to clear the selection since it is always visible. + */ + +#ifdef ALWAYS_SHOW_SELECTION + if ((entryPtr->selectFirst != -1) && entryPtr->exportSelection) { + entryPtr->selectFirst = -1; + entryPtr->selectLast = -1; + EventuallyRedraw(entryPtr); + } +#endif +} + +/* + *---------------------------------------------------------------------- + * + * EventuallyRedraw -- + * + * Ensure that an entry is eventually redrawn on the display. + * + * Results: + * None. + * + * Side effects: + * Information gets redisplayed. Right now we don't do selective + * redisplays: the whole window will be redrawn. This doesn't + * seem to hurt performance noticeably, but if it does then this + * could be changed. + * + *---------------------------------------------------------------------- + */ + +static void +EventuallyRedraw(entryPtr) + register Entry *entryPtr; /* Information about widget. */ +{ + if ((entryPtr->tkwin == NULL) || !Tk_IsMapped(entryPtr->tkwin)) { + return; + } + + /* + * Right now we don't do selective redisplays: the whole window + * will be redrawn. This doesn't seem to hurt performance noticeably, + * but if it does then this could be changed. + */ + + if (!(entryPtr->flags & REDRAW_PENDING)) { + entryPtr->flags |= REDRAW_PENDING; + Tcl_DoWhenIdle(DisplayEntry, (ClientData) entryPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * EntryVisibleRange -- + * + * Return information about the range of the entry that is + * currently visible. + * + * Results: + * *firstPtr and *lastPtr are modified to hold fractions between + * 0 and 1 identifying the range of characters visible in the + * entry. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +EntryVisibleRange(entryPtr, firstPtr, lastPtr) + Entry *entryPtr; /* Information about widget. */ + double *firstPtr; /* Return position of first visible + * character in widget. */ + double *lastPtr; /* Return position of char just after + * last visible one. */ +{ + int charsInWindow; + + if (entryPtr->numChars == 0) { + *firstPtr = 0.0; + *lastPtr = 1.0; + } else { + charsInWindow = Tk_PointToChar(entryPtr->textLayout, + Tk_Width(entryPtr->tkwin) - entryPtr->inset + - entryPtr->layoutX - 1, 0) + 1; + if (charsInWindow > entryPtr->numChars) { + /* + * If all chars were visible, then charsInWindow will be + * the index just after the last char that was visible. + */ + + charsInWindow = entryPtr->numChars; + } + charsInWindow -= entryPtr->leftIndex; + if (charsInWindow == 0) { + charsInWindow = 1; + } + *firstPtr = ((double) entryPtr->leftIndex)/entryPtr->numChars; + *lastPtr = ((double) (entryPtr->leftIndex + charsInWindow)) + /entryPtr->numChars; + } +} + +/* + *---------------------------------------------------------------------- + * + * EntryUpdateScrollbar -- + * + * This procedure is invoked whenever information has changed in + * an entry in a way that would invalidate a scrollbar display. + * If there is an associated scrollbar, then this procedure updates + * it by invoking a Tcl command. + * + * Results: + * None. + * + * Side effects: + * A Tcl command is invoked, and an additional command may be + * invoked to process errors in the command. + * + *---------------------------------------------------------------------- + */ + +static void +EntryUpdateScrollbar(entryPtr) + Entry *entryPtr; /* Information about widget. */ +{ + char args[100]; + int code; + double first, last; + Tcl_Interp *interp; + + if (entryPtr->scrollCmd == NULL) { + return; + } + + interp = entryPtr->interp; + Tcl_Preserve((ClientData) interp); + EntryVisibleRange(entryPtr, &first, &last); + sprintf(args, " %g %g", first, last); + code = Tcl_VarEval(interp, entryPtr->scrollCmd, args, (char *) NULL); + if (code != TCL_OK) { + Tcl_AddErrorInfo(interp, + "\n (horizontal scrolling command executed by entry)"); + Tcl_BackgroundError(interp); + } + Tcl_SetResult(interp, (char *) NULL, TCL_STATIC); + Tcl_Release((ClientData) interp); +} + +/* + *---------------------------------------------------------------------- + * + * EntryBlinkProc -- + * + * This procedure is called as a timer handler to blink the + * insertion cursor off and on. + * + * Results: + * None. + * + * Side effects: + * The cursor gets turned on or off, redisplay gets invoked, + * and this procedure reschedules itself. + * + *---------------------------------------------------------------------- + */ + +static void +EntryBlinkProc(clientData) + ClientData clientData; /* Pointer to record describing entry. */ +{ + register Entry *entryPtr = (Entry *) clientData; + + if (!(entryPtr->flags & GOT_FOCUS) || (entryPtr->insertOffTime == 0)) { + return; + } + if (entryPtr->flags & CURSOR_ON) { + entryPtr->flags &= ~CURSOR_ON; + entryPtr->insertBlinkHandler = Tcl_CreateTimerHandler( + entryPtr->insertOffTime, EntryBlinkProc, (ClientData) entryPtr); + } else { + entryPtr->flags |= CURSOR_ON; + entryPtr->insertBlinkHandler = Tcl_CreateTimerHandler( + entryPtr->insertOnTime, EntryBlinkProc, (ClientData) entryPtr); + } + EventuallyRedraw(entryPtr); +} + +/* + *---------------------------------------------------------------------- + * + * EntryFocusProc -- + * + * This procedure is called whenever the entry gets or loses the + * input focus. It's also called whenever the window is reconfigured + * while it has the focus. + * + * Results: + * None. + * + * Side effects: + * The cursor gets turned on or off. + * + *---------------------------------------------------------------------- + */ + +static void +EntryFocusProc(entryPtr, gotFocus) + register Entry *entryPtr; /* Entry that got or lost focus. */ + int gotFocus; /* 1 means window is getting focus, 0 means + * it's losing it. */ +{ + Tcl_DeleteTimerHandler(entryPtr->insertBlinkHandler); + if (gotFocus) { + entryPtr->flags |= GOT_FOCUS | CURSOR_ON; + if (entryPtr->insertOffTime != 0) { + entryPtr->insertBlinkHandler = Tcl_CreateTimerHandler( + entryPtr->insertOnTime, EntryBlinkProc, + (ClientData) entryPtr); + } + } else { + entryPtr->flags &= ~(GOT_FOCUS | CURSOR_ON); + entryPtr->insertBlinkHandler = (Tcl_TimerToken) NULL; + } + EventuallyRedraw(entryPtr); +} + +/* + *-------------------------------------------------------------- + * + * EntryTextVarProc -- + * + * This procedure is invoked when someone changes the variable + * whose contents are to be displayed in an entry. + * + * Results: + * NULL is always returned. + * + * Side effects: + * The text displayed in the entry will change to match the + * variable. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static char * +EntryTextVarProc(clientData, interp, name1, name2, flags) + ClientData clientData; /* Information about button. */ + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *name1; /* Not used. */ + char *name2; /* Not used. */ + int flags; /* Information about what happened. */ +{ + register Entry *entryPtr = (Entry *) clientData; + char *value; + + /* + * If the variable is unset, then immediately recreate it unless + * the whole interpreter is going away. + */ + + if (flags & TCL_TRACE_UNSETS) { + if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + Tcl_SetVar(interp, entryPtr->textVarName, entryPtr->string, + TCL_GLOBAL_ONLY); + Tcl_TraceVar(interp, entryPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + EntryTextVarProc, clientData); + } + return (char *) NULL; + } + + /* + * Update the entry's text with the value of the variable, unless + * the entry already has that value (this happens when the variable + * changes value because we changed it because someone typed in + * the entry). + */ + + value = Tcl_GetVar(interp, entryPtr->textVarName, TCL_GLOBAL_ONLY); + if (value == NULL) { + value = ""; + } + if (strcmp(value, entryPtr->string) != 0) { + EntrySetValue(entryPtr, value); + } + return (char *) NULL; +} diff --git a/generic/tkError.c b/generic/tkError.c new file mode 100644 index 0000000..3d52793 --- /dev/null +++ b/generic/tkError.c @@ -0,0 +1,307 @@ +/* + * tkError.c -- + * + * This file provides a high-performance mechanism for + * selectively dealing with errors that occur in talking + * to the X server. This is useful, for example, when + * communicating with a window that may not exist. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkError.c 1.23 97/04/25 16:51:27 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * The default X error handler gets saved here, so that it can + * be invoked if an error occurs that we can't handle. + */ + +static int (*defaultHandler) _ANSI_ARGS_((Display *display, + XErrorEvent *eventPtr)) = NULL; + + +/* + * Forward references to procedures declared later in this file: + */ + +static int ErrorProc _ANSI_ARGS_((Display *display, + XErrorEvent *errEventPtr)); + +/* + *-------------------------------------------------------------- + * + * Tk_CreateErrorHandler -- + * + * Arrange for all a given procedure to be invoked whenever + * certain errors occur. + * + * Results: + * The return value is a token identifying the handler; + * it must be passed to Tk_DeleteErrorHandler to delete the + * handler. + * + * Side effects: + * If an X error occurs that matches the error, request, + * and minor arguments, then errorProc will be invoked. + * ErrorProc should have the following structure: + * + * int + * errorProc(clientData, errorEventPtr) + * caddr_t clientData; + * XErrorEvent *errorEventPtr; + * { + * } + * + * The clientData argument will be the same as the clientData + * argument to this procedure, and errorEvent will describe + * the error. If errorProc returns 0, it means that it + * completely "handled" the error: no further processing + * should be done. If errorProc returns 1, it means that it + * didn't know how to deal with the error, so we should look + * for other error handlers, or invoke the default error + * handler if no other handler returns zero. Handlers are + * invoked in order of age: youngest handler first. + * + * Note: errorProc will only be called for errors associated + * with X requests made AFTER this call, but BEFORE the handler + * is deleted by calling Tk_DeleteErrorHandler. + * + *-------------------------------------------------------------- + */ + +Tk_ErrorHandler +Tk_CreateErrorHandler(display, error, request, minorCode, errorProc, clientData) + Display *display; /* Display for which to handle + * errors. */ + int error; /* Consider only errors with this + * error_code (-1 means consider + * all errors). */ + int request; /* Consider only errors with this + * major request code (-1 means + * consider all major codes). */ + int minorCode; /* Consider only errors with this + * minor request code (-1 means + * consider all minor codes). */ + Tk_ErrorProc *errorProc; /* Procedure to invoke when a + * matching error occurs. NULL means + * just ignore matching errors. */ + ClientData clientData; /* Arbitrary value to pass to + * errorProc. */ +{ + register TkErrorHandler *errorPtr; + register TkDisplay *dispPtr; + + /* + * Find the display. If Tk doesn't know about this display then + * it's an error: panic. + */ + + dispPtr = TkGetDisplay(display); + if (dispPtr == NULL) { + panic("Unknown display passed to Tk_CreateErrorHandler"); + } + + /* + * Make sure that X calls us whenever errors occur. + */ + + if (defaultHandler == NULL) { + defaultHandler = XSetErrorHandler(ErrorProc); + } + + /* + * Create the handler record. + */ + + errorPtr = (TkErrorHandler *) ckalloc(sizeof(TkErrorHandler)); + errorPtr->dispPtr = dispPtr; + errorPtr->firstRequest = NextRequest(display); + errorPtr->lastRequest = (unsigned) -1; + errorPtr->error = error; + errorPtr->request = request; + errorPtr->minorCode = minorCode; + errorPtr->errorProc = errorProc; + errorPtr->clientData = clientData; + errorPtr->nextPtr = dispPtr->errorPtr; + dispPtr->errorPtr = errorPtr; + + return (Tk_ErrorHandler) errorPtr; +} + +/* + *-------------------------------------------------------------- + * + * Tk_DeleteErrorHandler -- + * + * Do not use an error handler anymore. + * + * Results: + * None. + * + * Side effects: + * The handler denoted by the "handler" argument will not + * be invoked for any X errors associated with requests + * made after this call. However, if errors arrive later + * for requests made BEFORE this call, then the handler + * will still be invoked. Call XSync if you want to be + * sure that all outstanding errors have been received + * and processed. + * + *-------------------------------------------------------------- + */ + +void +Tk_DeleteErrorHandler(handler) + Tk_ErrorHandler handler; /* Token for handler to delete; + * was previous return value from + * Tk_CreateErrorHandler. */ +{ + register TkErrorHandler *errorPtr = (TkErrorHandler *) handler; + register TkDisplay *dispPtr = errorPtr->dispPtr; + + errorPtr->lastRequest = NextRequest(dispPtr->display) - 1; + + /* + * Every once-in-a-while, cleanup handlers that are no longer + * active. We probably won't be able to free the handler that + * was just deleted (need to wait for any outstanding requests to + * be processed by server), but there may be previously-deleted + * handlers that are now ready for garbage collection. To reduce + * the cost of the cleanup, let a few dead handlers pile up, then + * clean them all at once. This adds a bit of overhead to errors + * that might occur while the dead handlers are hanging around, + * but reduces the overhead of scanning the list to clean up + * (particularly if there are many handlers that stay around + * forever). + */ + + dispPtr->deleteCount += 1; + if (dispPtr->deleteCount >= 10) { + register TkErrorHandler *prevPtr; + TkErrorHandler *nextPtr; + int lastSerial; + + dispPtr->deleteCount = 0; + lastSerial = LastKnownRequestProcessed(dispPtr->display); + errorPtr = dispPtr->errorPtr; + for (prevPtr = NULL; errorPtr != NULL; errorPtr = nextPtr) { + nextPtr = errorPtr->nextPtr; + if ((errorPtr->lastRequest != (unsigned long) -1) + && (errorPtr->lastRequest <= (unsigned long) lastSerial)) { + if (prevPtr == NULL) { + dispPtr->errorPtr = nextPtr; + } else { + prevPtr->nextPtr = nextPtr; + } + ckfree((char *) errorPtr); + continue; + } + prevPtr = errorPtr; + } + } +} + +/* + *-------------------------------------------------------------- + * + * ErrorProc -- + * + * This procedure is invoked by the X system when error + * events arrive. + * + * Results: + * If it returns, the return value is zero. However, + * it is possible that one of the error handlers may + * just exit. + * + * Side effects: + * This procedure does two things. First, it uses the + * serial # in the error event to eliminate handlers whose + * expiration serials are now in the past. Second, it + * invokes any handlers that want to deal with the error. + * + *-------------------------------------------------------------- + */ + +static int +ErrorProc(display, errEventPtr) + Display *display; /* Display for which error + * occurred. */ + register XErrorEvent *errEventPtr; /* Information about error. */ +{ + register TkDisplay *dispPtr; + register TkErrorHandler *errorPtr; + + /* + * See if we know anything about the display. If not, then + * invoke the default error handler. + */ + + dispPtr = TkGetDisplay(display); + if (dispPtr == NULL) { + goto couldntHandle; + } + + /* + * Otherwise invoke any relevant handlers for the error, in order. + */ + + for (errorPtr = dispPtr->errorPtr; errorPtr != NULL; + errorPtr = errorPtr->nextPtr) { + if ((errorPtr->firstRequest > errEventPtr->serial) + || ((errorPtr->error != -1) + && (errorPtr->error != errEventPtr->error_code)) + || ((errorPtr->request != -1) + && (errorPtr->request != errEventPtr->request_code)) + || ((errorPtr->minorCode != -1) + && (errorPtr->minorCode != errEventPtr->minor_code)) + || ((errorPtr->lastRequest != (unsigned long) -1) + && (errorPtr->lastRequest < errEventPtr->serial))) { + continue; + } + if (errorPtr->errorProc == NULL) { + return 0; + } else { + if ((*errorPtr->errorProc)(errorPtr->clientData, + errEventPtr) == 0) { + return 0; + } + } + } + + /* + * See if the error is a BadWindow error. If so, and it refers + * to a window that still exists in our window table, then ignore + * the error. Errors like this can occur if a window owned by us + * is deleted by someone externally, like a window manager. We'll + * ignore the errors at least long enough to clean up internally and + * remove the entry from the window table. + * + * NOTE: For embedding, we must also check whether the window was + * recently deleted. If so, it may be that Tk generated operations on + * windows that were deleted by the container. Now we are getting + * the errors (BadWindow) after Tk already deleted the window itself. + */ + + if ((errEventPtr->error_code == BadWindow) && + ((Tk_IdToWindow(display, (Window) errEventPtr->resourceid) != + NULL) || + (TkpWindowWasRecentlyDeleted((Window) errEventPtr->resourceid, + dispPtr)))) { + return 0; + } + + /* + * We couldn't handle the error. Use the default handler. + */ + + couldntHandle: + return (*defaultHandler)(display, errEventPtr); +} diff --git a/generic/tkEvent.c b/generic/tkEvent.c new file mode 100644 index 0000000..045a478 --- /dev/null +++ b/generic/tkEvent.c @@ -0,0 +1,1038 @@ +/* + * tkEvent.c -- + * + * This file provides basic low-level facilities for managing + * X events in Tk. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkEvent.c 1.20 96/09/20 09:33:38 + */ + +#include "tkPort.h" +#include "tkInt.h" +#include <signal.h> + +/* + * There's a potential problem if a handler is deleted while it's + * current (i.e. its procedure is executing), since Tk_HandleEvent + * will need to read the handler's "nextPtr" field when the procedure + * returns. To handle this problem, structures of the type below + * indicate the next handler to be processed for any (recursively + * nested) dispatches in progress. The nextHandler fields get + * updated if the handlers pointed to are deleted. Tk_HandleEvent + * also needs to know if the entire window gets deleted; the winPtr + * field is set to zero if that particular window gets deleted. + */ + +typedef struct InProgress { + XEvent *eventPtr; /* Event currently being handled. */ + TkWindow *winPtr; /* Window for event. Gets set to None if + * window is deleted while event is being + * handled. */ + TkEventHandler *nextHandler; /* Next handler in search. */ + struct InProgress *nextPtr; /* Next higher nested search. */ +} InProgress; + +static InProgress *pendingPtr = NULL; + /* Topmost search in progress, or + * NULL if none. */ + +/* + * For each call to Tk_CreateGenericHandler, an instance of the following + * structure will be created. All of the active handlers are linked into a + * list. + */ + +typedef struct GenericHandler { + Tk_GenericProc *proc; /* Procedure to dispatch on all X events. */ + ClientData clientData; /* Client data to pass to procedure. */ + int deleteFlag; /* Flag to set when this handler is deleted. */ + struct GenericHandler *nextPtr; + /* Next handler in list of all generic + * handlers, or NULL for end of list. */ +} GenericHandler; + +static GenericHandler *genericList = NULL; + /* First handler in the list, or NULL. */ +static GenericHandler *lastGenericPtr = NULL; + /* Last handler in list. */ + +/* + * There's a potential problem if Tk_HandleEvent is entered recursively. + * A handler cannot be deleted physically until we have returned from + * calling it. Otherwise, we're looking at unallocated memory in advancing to + * its `next' entry. We deal with the problem by using the `delete flag' and + * deleting handlers only when it's known that there's no handler active. + * + * The following variable has a non-zero value when a handler is active. + */ + +static int genericHandlersActive = 0; + +/* + * The following structure is used for queueing X-style events on the + * Tcl event queue. + */ + +typedef struct TkWindowEvent { + Tcl_Event header; /* Standard information for all events. */ + XEvent event; /* The X event. */ +} TkWindowEvent; + +/* + * Array of event masks corresponding to each X event: + */ + +static unsigned long eventMasks[TK_LASTEVENT] = { + 0, + 0, + KeyPressMask, /* KeyPress */ + KeyReleaseMask, /* KeyRelease */ + ButtonPressMask, /* ButtonPress */ + ButtonReleaseMask, /* ButtonRelease */ + PointerMotionMask|PointerMotionHintMask|ButtonMotionMask + |Button1MotionMask|Button2MotionMask|Button3MotionMask + |Button4MotionMask|Button5MotionMask, + /* MotionNotify */ + EnterWindowMask, /* EnterNotify */ + LeaveWindowMask, /* LeaveNotify */ + FocusChangeMask, /* FocusIn */ + FocusChangeMask, /* FocusOut */ + KeymapStateMask, /* KeymapNotify */ + ExposureMask, /* Expose */ + ExposureMask, /* GraphicsExpose */ + ExposureMask, /* NoExpose */ + VisibilityChangeMask, /* VisibilityNotify */ + SubstructureNotifyMask, /* CreateNotify */ + StructureNotifyMask, /* DestroyNotify */ + StructureNotifyMask, /* UnmapNotify */ + StructureNotifyMask, /* MapNotify */ + SubstructureRedirectMask, /* MapRequest */ + StructureNotifyMask, /* ReparentNotify */ + StructureNotifyMask, /* ConfigureNotify */ + SubstructureRedirectMask, /* ConfigureRequest */ + StructureNotifyMask, /* GravityNotify */ + ResizeRedirectMask, /* ResizeRequest */ + StructureNotifyMask, /* CirculateNotify */ + SubstructureRedirectMask, /* CirculateRequest */ + PropertyChangeMask, /* PropertyNotify */ + 0, /* SelectionClear */ + 0, /* SelectionRequest */ + 0, /* SelectionNotify */ + ColormapChangeMask, /* ColormapNotify */ + 0, /* ClientMessage */ + 0, /* Mapping Notify */ + VirtualEventMask, /* VirtualEvents */ + ActivateMask, /* ActivateNotify */ + ActivateMask /* DeactivateNotify */ +}; + +/* + * If someone has called Tk_RestrictEvents, the information below + * keeps track of it. + */ + +static Tk_RestrictProc *restrictProc; + /* Procedure to call. NULL means no + * restrictProc is currently in effect. */ +static ClientData restrictArg; /* Argument to pass to restrictProc. */ + +/* + * Prototypes for procedures that are only referenced locally within + * this file. + */ + +static void DelayedMotionProc _ANSI_ARGS_((ClientData clientData)); +static int WindowEventProc _ANSI_ARGS_((Tcl_Event *evPtr, + int flags)); + +/* + *-------------------------------------------------------------- + * + * Tk_CreateEventHandler -- + * + * Arrange for a given procedure to be invoked whenever + * events from a given class occur in a given window. + * + * Results: + * None. + * + * Side effects: + * From now on, whenever an event of the type given by + * mask occurs for token and is processed by Tk_HandleEvent, + * proc will be called. See the manual entry for details + * of the calling sequence and return value for proc. + * + *-------------------------------------------------------------- + */ + +void +Tk_CreateEventHandler(token, mask, proc, clientData) + Tk_Window token; /* Token for window in which to + * create handler. */ + unsigned long mask; /* Events for which proc should + * be called. */ + Tk_EventProc *proc; /* Procedure to call for each + * selected event */ + ClientData clientData; /* Arbitrary data to pass to proc. */ +{ + register TkEventHandler *handlerPtr; + register TkWindow *winPtr = (TkWindow *) token; + int found; + + /* + * Skim through the list of existing handlers to (a) compute the + * overall event mask for the window (so we can pass this new + * value to the X system) and (b) see if there's already a handler + * declared with the same callback and clientData (if so, just + * change the mask). If no existing handler matches, then create + * a new handler. + */ + + found = 0; + if (winPtr->handlerList == NULL) { + handlerPtr = (TkEventHandler *) ckalloc( + (unsigned) sizeof(TkEventHandler)); + winPtr->handlerList = handlerPtr; + goto initHandler; + } else { + for (handlerPtr = winPtr->handlerList; ; + handlerPtr = handlerPtr->nextPtr) { + if ((handlerPtr->proc == proc) + && (handlerPtr->clientData == clientData)) { + handlerPtr->mask = mask; + found = 1; + } + if (handlerPtr->nextPtr == NULL) { + break; + } + } + } + + /* + * Create a new handler if no matching old handler was found. + */ + + if (!found) { + handlerPtr->nextPtr = (TkEventHandler *) + ckalloc(sizeof(TkEventHandler)); + handlerPtr = handlerPtr->nextPtr; + initHandler: + handlerPtr->mask = mask; + handlerPtr->proc = proc; + handlerPtr->clientData = clientData; + handlerPtr->nextPtr = NULL; + } + + /* + * No need to call XSelectInput: Tk always selects on all events + * for all windows (needed to support bindings on classes and "all"). + */ +} + +/* + *-------------------------------------------------------------- + * + * Tk_DeleteEventHandler -- + * + * Delete a previously-created handler. + * + * Results: + * None. + * + * Side effects: + * If there existed a handler as described by the + * parameters, the handler is deleted so that proc + * will not be invoked again. + * + *-------------------------------------------------------------- + */ + +void +Tk_DeleteEventHandler(token, mask, proc, clientData) + Tk_Window token; /* Same as corresponding arguments passed */ + unsigned long mask; /* previously to Tk_CreateEventHandler. */ + Tk_EventProc *proc; + ClientData clientData; +{ + register TkEventHandler *handlerPtr; + register InProgress *ipPtr; + TkEventHandler *prevPtr; + register TkWindow *winPtr = (TkWindow *) token; + + /* + * Find the event handler to be deleted, or return + * immediately if it doesn't exist. + */ + + for (handlerPtr = winPtr->handlerList, prevPtr = NULL; ; + prevPtr = handlerPtr, handlerPtr = handlerPtr->nextPtr) { + if (handlerPtr == NULL) { + return; + } + if ((handlerPtr->mask == mask) && (handlerPtr->proc == proc) + && (handlerPtr->clientData == clientData)) { + break; + } + } + + /* + * If Tk_HandleEvent is about to process this handler, tell it to + * process the next one instead. + */ + + for (ipPtr = pendingPtr; ipPtr != NULL; ipPtr = ipPtr->nextPtr) { + if (ipPtr->nextHandler == handlerPtr) { + ipPtr->nextHandler = handlerPtr->nextPtr; + } + } + + /* + * Free resources associated with the handler. + */ + + if (prevPtr == NULL) { + winPtr->handlerList = handlerPtr->nextPtr; + } else { + prevPtr->nextPtr = handlerPtr->nextPtr; + } + ckfree((char *) handlerPtr); + + + /* + * No need to call XSelectInput: Tk always selects on all events + * for all windows (needed to support bindings on classes and "all"). + */ +} + +/*-------------------------------------------------------------- + * + * Tk_CreateGenericHandler -- + * + * Register a procedure to be called on each X event, regardless + * of display or window. Generic handlers are useful for capturing + * events that aren't associated with windows, or events for windows + * not managed by Tk. + * + * Results: + * None. + * + * Side Effects: + * From now on, whenever an X event is given to Tk_HandleEvent, + * invoke proc, giving it clientData and the event as arguments. + * + *-------------------------------------------------------------- + */ + +void +Tk_CreateGenericHandler(proc, clientData) + Tk_GenericProc *proc; /* Procedure to call on every event. */ + ClientData clientData; /* One-word value to pass to proc. */ +{ + GenericHandler *handlerPtr; + + handlerPtr = (GenericHandler *) ckalloc (sizeof (GenericHandler)); + + handlerPtr->proc = proc; + handlerPtr->clientData = clientData; + handlerPtr->deleteFlag = 0; + handlerPtr->nextPtr = NULL; + if (genericList == NULL) { + genericList = handlerPtr; + } else { + lastGenericPtr->nextPtr = handlerPtr; + } + lastGenericPtr = handlerPtr; +} + +/* + *-------------------------------------------------------------- + * + * Tk_DeleteGenericHandler -- + * + * Delete a previously-created generic handler. + * + * Results: + * None. + * + * Side Effects: + * If there existed a handler as described by the parameters, + * that handler is logically deleted so that proc will not be + * invoked again. The physical deletion happens in the event + * loop in Tk_HandleEvent. + * + *-------------------------------------------------------------- + */ + +void +Tk_DeleteGenericHandler(proc, clientData) + Tk_GenericProc *proc; + ClientData clientData; +{ + GenericHandler * handler; + + for (handler = genericList; handler; handler = handler->nextPtr) { + if ((handler->proc == proc) && (handler->clientData == clientData)) { + handler->deleteFlag = 1; + } + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_HandleEvent -- + * + * Given an event, invoke all the handlers that have + * been registered for the event. + * + * Results: + * None. + * + * Side effects: + * Depends on the handlers. + * + *-------------------------------------------------------------- + */ + +void +Tk_HandleEvent(eventPtr) + XEvent *eventPtr; /* Event to dispatch. */ +{ + register TkEventHandler *handlerPtr; + register GenericHandler *genericPtr; + register GenericHandler *genPrevPtr; + TkWindow *winPtr; + unsigned long mask; + InProgress ip; + Window handlerWindow; + TkDisplay *dispPtr; + Tcl_Interp *interp = (Tcl_Interp *) NULL; + + /* + * Next, invoke all the generic event handlers (those that are + * invoked for all events). If a generic event handler reports that + * an event is fully processed, go no further. + */ + + for (genPrevPtr = NULL, genericPtr = genericList; genericPtr != NULL; ) { + if (genericPtr->deleteFlag) { + if (!genericHandlersActive) { + GenericHandler *tmpPtr; + + /* + * This handler needs to be deleted and there are no + * calls pending through the handler, so now is a safe + * time to delete it. + */ + + tmpPtr = genericPtr->nextPtr; + if (genPrevPtr == NULL) { + genericList = tmpPtr; + } else { + genPrevPtr->nextPtr = tmpPtr; + } + if (tmpPtr == NULL) { + lastGenericPtr = genPrevPtr; + } + (void) ckfree((char *) genericPtr); + genericPtr = tmpPtr; + continue; + } + } else { + int done; + + genericHandlersActive++; + done = (*genericPtr->proc)(genericPtr->clientData, eventPtr); + genericHandlersActive--; + if (done) { + return; + } + } + genPrevPtr = genericPtr; + genericPtr = genPrevPtr->nextPtr; + } + + /* + * If the event is a MappingNotify event, find its display and + * refresh the keyboard mapping information for the display. + * After that there's nothing else to do with the event, so just + * quit. + */ + + if (eventPtr->type == MappingNotify) { + dispPtr = TkGetDisplay(eventPtr->xmapping.display); + if (dispPtr != NULL) { + XRefreshKeyboardMapping(&eventPtr->xmapping); + dispPtr->bindInfoStale = 1; + } + return; + } + + /* + * Events selected by StructureNotify require special handling. + * They look the same as those selected by SubstructureNotify. + * The only difference is whether the "event" and "window" fields + * are the same. Compare the two fields and convert StructureNotify + * to SubstructureNotify if necessary. + */ + + handlerWindow = eventPtr->xany.window; + mask = eventMasks[eventPtr->xany.type]; + if (mask == StructureNotifyMask) { + if (eventPtr->xmap.event != eventPtr->xmap.window) { + mask = SubstructureNotifyMask; + handlerWindow = eventPtr->xmap.event; + } + } + winPtr = (TkWindow *) Tk_IdToWindow(eventPtr->xany.display, handlerWindow); + if (winPtr == NULL) { + + /* + * There isn't a TkWindow structure for this window. + * However, if the event is a PropertyNotify event then call + * the selection manager (it deals beneath-the-table with + * certain properties). + */ + + if (eventPtr->type == PropertyNotify) { + TkSelPropProc(eventPtr); + } + return; + } + + /* + * Once a window has started getting deleted, don't process any more + * events for it except for the DestroyNotify event. This check is + * needed because a DestroyNotify handler could re-invoke the event + * loop, causing other pending events to be handled for the window + * (the window doesn't get totally expunged from our tables until + * after the DestroyNotify event has been completely handled). + */ + + if ((winPtr->flags & TK_ALREADY_DEAD) + && (eventPtr->type != DestroyNotify)) { + return; + } + + if (winPtr->mainPtr != NULL) { + + /* + * Protect interpreter for this window from possible deletion + * while we are dealing with the event for this window. Thus, + * widget writers do not have to worry about protecting the + * interpreter in their own code. + */ + + interp = winPtr->mainPtr->interp; + Tcl_Preserve((ClientData) interp); + + /* + * Call focus-related code to look at FocusIn, FocusOut, Enter, + * and Leave events; depending on its return value, ignore the + * event. + */ + + if ((mask & (FocusChangeMask|EnterWindowMask|LeaveWindowMask)) + && !TkFocusFilterEvent(winPtr, eventPtr)) { + Tcl_Release((ClientData) interp); + return; + } + + /* + * Redirect KeyPress and KeyRelease events to the focus window, + * or ignore them entirely if there is no focus window. + */ + + if (mask & (KeyPressMask|KeyReleaseMask)) { + winPtr->dispPtr->lastEventTime = eventPtr->xkey.time; + winPtr = TkFocusKeyEvent(winPtr, eventPtr); + if (winPtr == NULL) { + Tcl_Release((ClientData) interp); + return; + } + } + + /* + * Call a grab-related procedure to do special processing on + * pointer events. + */ + + if (mask & (ButtonPressMask|ButtonReleaseMask|PointerMotionMask + |EnterWindowMask|LeaveWindowMask)) { + if (mask & (ButtonPressMask|ButtonReleaseMask)) { + winPtr->dispPtr->lastEventTime = eventPtr->xbutton.time; + } else if (mask & PointerMotionMask) { + winPtr->dispPtr->lastEventTime = eventPtr->xmotion.time; + } else { + winPtr->dispPtr->lastEventTime = eventPtr->xcrossing.time; + } + if (TkPointerEvent(eventPtr, winPtr) == 0) { + goto done; + } + } + } + +#ifdef TK_USE_INPUT_METHODS + /* + * Pass the event to the input method(s), if there are any, and + * discard the event if the input method(s) insist. Create the + * input context for the window if it hasn't already been done + * (XFilterEvent needs this context). + */ + + if (!(winPtr->flags & TK_CHECKED_IC)) { + if (winPtr->dispPtr->inputMethod != NULL) { + winPtr->inputContext = XCreateIC( + winPtr->dispPtr->inputMethod, XNInputStyle, + XIMPreeditNothing|XIMStatusNothing, + XNClientWindow, winPtr->window, + XNFocusWindow, winPtr->window, NULL); + } + winPtr->flags |= TK_CHECKED_IC; + } + if (XFilterEvent(eventPtr, None)) { + goto done; + } +#endif /* TK_USE_INPUT_METHODS */ + + /* + * For events where it hasn't already been done, update the current + * time in the display. + */ + + if (eventPtr->type == PropertyNotify) { + winPtr->dispPtr->lastEventTime = eventPtr->xproperty.time; + } + + /* + * There's a potential interaction here with Tk_DeleteEventHandler. + * Read the documentation for pendingPtr. + */ + + ip.eventPtr = eventPtr; + ip.winPtr = winPtr; + ip.nextHandler = NULL; + ip.nextPtr = pendingPtr; + pendingPtr = &ip; + if (mask == 0) { + if ((eventPtr->type == SelectionClear) + || (eventPtr->type == SelectionRequest) + || (eventPtr->type == SelectionNotify)) { + TkSelEventProc((Tk_Window) winPtr, eventPtr); + } else if ((eventPtr->type == ClientMessage) + && (eventPtr->xclient.message_type == + Tk_InternAtom((Tk_Window) winPtr, "WM_PROTOCOLS"))) { + TkWmProtocolEventProc(winPtr, eventPtr); + } + } else { + for (handlerPtr = winPtr->handlerList; handlerPtr != NULL; ) { + if ((handlerPtr->mask & mask) != 0) { + ip.nextHandler = handlerPtr->nextPtr; + (*(handlerPtr->proc))(handlerPtr->clientData, eventPtr); + handlerPtr = ip.nextHandler; + } else { + handlerPtr = handlerPtr->nextPtr; + } + } + + /* + * Pass the event to the "bind" command mechanism. But, don't + * do this for SubstructureNotify events. The "bind" command + * doesn't support them anyway, and it's easier to filter out + * these events here than in the lower-level procedures. + */ + + if ((ip.winPtr != None) && (mask != SubstructureNotifyMask)) { + TkBindEventProc(winPtr, eventPtr); + } + } + pendingPtr = ip.nextPtr; +done: + + /* + * Release the interpreter for this window so that it can be potentially + * deleted if requested. + */ + + if (interp != (Tcl_Interp *) NULL) { + Tcl_Release((ClientData) interp); + } +} + +/* + *-------------------------------------------------------------- + * + * TkEventDeadWindow -- + * + * This procedure is invoked when it is determined that + * a window is dead. It cleans up event-related information + * about the window. + * + * Results: + * None. + * + * Side effects: + * Various things get cleaned up and recycled. + * + *-------------------------------------------------------------- + */ + +void +TkEventDeadWindow(winPtr) + TkWindow *winPtr; /* Information about the window + * that is being deleted. */ +{ + register TkEventHandler *handlerPtr; + register InProgress *ipPtr; + + /* + * While deleting all the handlers, be careful to check for + * Tk_HandleEvent being about to process one of the deleted + * handlers. If it is, tell it to quit (all of the handlers + * are being deleted). + */ + + while (winPtr->handlerList != NULL) { + handlerPtr = winPtr->handlerList; + winPtr->handlerList = handlerPtr->nextPtr; + for (ipPtr = pendingPtr; ipPtr != NULL; ipPtr = ipPtr->nextPtr) { + if (ipPtr->nextHandler == handlerPtr) { + ipPtr->nextHandler = NULL; + } + if (ipPtr->winPtr == winPtr) { + ipPtr->winPtr = None; + } + } + ckfree((char *) handlerPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkCurrentTime -- + * + * Try to deduce the current time. "Current time" means the time + * of the event that led to the current code being executed, which + * means the time in the most recently-nested invocation of + * Tk_HandleEvent. + * + * Results: + * The return value is the time from the current event, or + * CurrentTime if there is no current event or if the current + * event contains no time. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Time +TkCurrentTime(dispPtr) + TkDisplay *dispPtr; /* Display for which the time is desired. */ +{ + register XEvent *eventPtr; + + if (pendingPtr == NULL) { + return dispPtr->lastEventTime; + } + eventPtr = pendingPtr->eventPtr; + switch (eventPtr->type) { + case ButtonPress: + case ButtonRelease: + return eventPtr->xbutton.time; + case KeyPress: + case KeyRelease: + return eventPtr->xkey.time; + case MotionNotify: + return eventPtr->xmotion.time; + case EnterNotify: + case LeaveNotify: + return eventPtr->xcrossing.time; + case PropertyNotify: + return eventPtr->xproperty.time; + } + return dispPtr->lastEventTime; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_RestrictEvents -- + * + * This procedure is used to globally restrict the set of events + * that will be dispatched. The restriction is done by filtering + * all incoming X events through a procedure that determines + * whether they are to be processed immediately, deferred, or + * discarded. + * + * Results: + * The return value is the previous restriction procedure in effect, + * if there was one, or NULL if there wasn't. + * + * Side effects: + * From now on, proc will be called to determine whether to process, + * defer or discard each incoming X event. + * + *---------------------------------------------------------------------- + */ + +Tk_RestrictProc * +Tk_RestrictEvents(proc, arg, prevArgPtr) + Tk_RestrictProc *proc; /* Procedure to call for each incoming + * event. */ + ClientData arg; /* Arbitrary argument to pass to proc. */ + ClientData *prevArgPtr; /* Place to store information about previous + * argument. */ +{ + Tk_RestrictProc *prev; + + prev = restrictProc; + *prevArgPtr = restrictArg; + restrictProc = proc; + restrictArg = arg; + return prev; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_QueueWindowEvent -- + * + * Given an X-style window event, this procedure adds it to the + * Tcl event queue at the given position. This procedure also + * performs mouse motion event collapsing if possible. + * + * Results: + * None. + * + * Side effects: + * Adds stuff to the event queue, which will eventually be + * processed. + * + *---------------------------------------------------------------------- + */ + +void +Tk_QueueWindowEvent(eventPtr, position) + XEvent *eventPtr; /* Event to add to queue. This + * procedures copies it before adding + * it to the queue. */ + Tcl_QueuePosition position; /* Where to put it on the queue: + * TCL_QUEUE_TAIL, TCL_QUEUE_HEAD, + * or TCL_QUEUE_MARK. */ +{ + TkWindowEvent *wevPtr; + TkDisplay *dispPtr; + + /* + * Find our display structure for the event's display. + */ + + for (dispPtr = tkDisplayList; ; dispPtr = dispPtr->nextPtr) { + if (dispPtr == NULL) { + return; + } + if (dispPtr->display == eventPtr->xany.display) { + break; + } + } + + if ((dispPtr->delayedMotionPtr != NULL) && (position == TCL_QUEUE_TAIL)) { + if ((eventPtr->type == MotionNotify) && (eventPtr->xmotion.window + == dispPtr->delayedMotionPtr->event.xmotion.window)) { + /* + * The new event is a motion event in the same window as the + * saved motion event. Just replace the saved event with the + * new one. + */ + + dispPtr->delayedMotionPtr->event = *eventPtr; + return; + } else if ((eventPtr->type != GraphicsExpose) + && (eventPtr->type != NoExpose) + && (eventPtr->type != Expose)) { + /* + * The new event may conflict with the saved motion event. Queue + * the saved motion event now so that it will be processed before + * the new event. + */ + + Tcl_QueueEvent(&dispPtr->delayedMotionPtr->header, position); + dispPtr->delayedMotionPtr = NULL; + Tcl_CancelIdleCall(DelayedMotionProc, (ClientData) dispPtr); + } + } + + wevPtr = (TkWindowEvent *) ckalloc(sizeof(TkWindowEvent)); + wevPtr->header.proc = WindowEventProc; + wevPtr->event = *eventPtr; + if ((eventPtr->type == MotionNotify) && (position == TCL_QUEUE_TAIL)) { + /* + * The new event is a motion event so don't queue it immediately; + * save it around in case another motion event arrives that it can + * be collapsed with. + */ + + if (dispPtr->delayedMotionPtr != NULL) { + panic("Tk_QueueWindowEvent found unexpected delayed motion event"); + } + dispPtr->delayedMotionPtr = wevPtr; + Tcl_DoWhenIdle(DelayedMotionProc, (ClientData) dispPtr); + } else { + Tcl_QueueEvent(&wevPtr->header, position); + } +} + +/* + *--------------------------------------------------------------------------- + * + * TkQueueEventForAllChildren -- + * + * Given an XEvent, recursively queue the event for this window and + * all non-toplevel children of the given window. + * + * Results: + * None. + * + * Side effects: + * Events queued. + * + *--------------------------------------------------------------------------- + */ + +void +TkQueueEventForAllChildren(winPtr, eventPtr) + TkWindow *winPtr; /* Window to which event is sent. */ + XEvent *eventPtr; /* The event to be sent. */ +{ + TkWindow *childPtr; + + eventPtr->xany.window = winPtr->window; + Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_TAIL); + + childPtr = winPtr->childList; + while (childPtr != NULL) { + if (!Tk_IsTopLevel(childPtr)) { + TkQueueEventForAllChildren(childPtr, eventPtr); + } + childPtr = childPtr->nextPtr; + } +} + +/* + *---------------------------------------------------------------------- + * + * WindowEventProc -- + * + * This procedure is called by Tcl_DoOneEvent when a window event + * reaches the front of the event queue. This procedure is responsible + * for actually handling the event. + * + * Results: + * Returns 1 if the event was handled, meaning it should be removed + * from the queue. Returns 0 if the event was not handled, meaning + * it should stay on the queue. The event isn't handled if the + * TCL_WINDOW_EVENTS bit isn't set in flags, if a restrict proc + * prevents the event from being handled. + * + * Side effects: + * Whatever the event handlers for the event do. + * + *---------------------------------------------------------------------- + */ + +static int +WindowEventProc(evPtr, flags) + Tcl_Event *evPtr; /* Event to service. */ + int flags; /* Flags that indicate what events to + * handle, such as TCL_WINDOW_EVENTS. */ +{ + TkWindowEvent *wevPtr = (TkWindowEvent *) evPtr; + Tk_RestrictAction result; + + if (!(flags & TCL_WINDOW_EVENTS)) { + return 0; + } + if (restrictProc != NULL) { + result = (*restrictProc)(restrictArg, &wevPtr->event); + if (result != TK_PROCESS_EVENT) { + if (result == TK_DEFER_EVENT) { + return 0; + } else { + /* + * TK_DELETE_EVENT: return and say we processed the event, + * even though we didn't do anything at all. + */ + return 1; + } + } + } + Tk_HandleEvent(&wevPtr->event); + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * DelayedMotionProc -- + * + * This procedure is invoked as an idle handler when a mouse motion + * event has been delayed. It queues the delayed event so that it + * will finally be serviced. + * + * Results: + * None. + * + * Side effects: + * The delayed mouse motion event gets added to the Tcl event + * queue for servicing. + * + *---------------------------------------------------------------------- + */ + +static void +DelayedMotionProc(clientData) + ClientData clientData; /* Pointer to display containing a delayed + * motion event to be serviced. */ +{ + TkDisplay *dispPtr = (TkDisplay *) clientData; + + if (dispPtr->delayedMotionPtr == NULL) { + panic("DelayedMotionProc found no delayed mouse motion event"); + } + Tcl_QueueEvent(&dispPtr->delayedMotionPtr->header, TCL_QUEUE_TAIL); + dispPtr->delayedMotionPtr = NULL; +} + +/* + *-------------------------------------------------------------- + * + * Tk_MainLoop -- + * + * Call Tcl_DoOneEvent over and over again in an infinite + * loop as long as there exist any main windows. + * + * Results: + * None. + * + * Side effects: + * Arbitrary; depends on handlers for events. + * + *-------------------------------------------------------------- + */ + +void +Tk_MainLoop() +{ + while (Tk_GetNumMainWindows() > 0) { + Tcl_DoOneEvent(0); + } +} diff --git a/generic/tkFileFilter.c b/generic/tkFileFilter.c new file mode 100644 index 0000000..1b7e61a --- /dev/null +++ b/generic/tkFileFilter.c @@ -0,0 +1,486 @@ +/* + * tkFileFilter.c -- + * + * Process the -filetypes option for the file dialogs on Windows and the + * Mac. + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkFileFilter.c 1.6 97/04/30 15:55:35 + * + */ + +#include "tkInt.h" +#include "tkFileFilter.h" + +static int AddClause _ANSI_ARGS_(( + Tcl_Interp * interp, FileFilter * filterPtr, + char * patternsStr, char * ostypesStr, + int isWindows)); +static void FreeClauses _ANSI_ARGS_((FileFilter * filterPtr)); +static void FreeGlobPatterns _ANSI_ARGS_(( + FileFilterClause * clausePtr)); +static void FreeMacFileTypes _ANSI_ARGS_(( + FileFilterClause * clausePtr)); +static FileFilter * GetFilter _ANSI_ARGS_((FileFilterList * flistPtr, + char * name)); + +/* + *---------------------------------------------------------------------- + * + * TkInitFileFilters -- + * + * Initializes a FileFilterList data structure. A FileFilterList + * must be initialized EXACTLY ONCE before any calls to + * TkGetFileFilters() is made. The usual flow of control is: + * TkInitFileFilters(&flist); + * TkGetFileFilters(&flist, ...); + * TkGetFileFilters(&flist, ...); + * ... + * TkFreeFileFilters(&flist); + * + * Results: + * None. + * + * Side effects: + * The fields in flistPtr are initialized. + *---------------------------------------------------------------------- + */ + +void +TkInitFileFilters(flistPtr) + FileFilterList * flistPtr; /* The structure to be initialized. */ +{ + flistPtr->filters = NULL; + flistPtr->filtersTail = NULL; + flistPtr->numFilters = 0; +} + +/* + *---------------------------------------------------------------------- + * + * TkGetFileFilters -- + * + * This function is called by the Mac and Windows implementation + * of tk_getOpenFile and tk_getSaveFile to translate the string + * value of the -filetypes option of into an easy-to-parse C + * structure (flistPtr). The caller of this function will then use + * flistPtr to perform filetype matching in a platform specific way. + * + * flistPtr must be initialized (See comments in TkInitFileFilters). + * + * Results: + * A standard TCL return value. + * + * Side effects: + * The fields in flistPtr are changed according to string. + *---------------------------------------------------------------------- + */ +int +TkGetFileFilters(interp, flistPtr, string, isWindows) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + FileFilterList * flistPtr; /* Stores the list of file filters. */ + char * string; /* Value of the -filetypes option. */ + int isWindows; /* True if we are running on Windows. */ +{ + int listArgc; + char ** listArgv = NULL; + char ** typeInfo = NULL; + int code = TCL_OK; + int i; + + if (Tcl_SplitList(interp, string, &listArgc, &listArgv) != TCL_OK) { + return TCL_ERROR; + } + if (listArgc == 0) { + goto done; + } + + /* + * Free the filter information that have been allocated the previous + * time -- the -filefilters option may have been used more than once in + * the command line. + */ + TkFreeFileFilters(flistPtr); + + for (i = 0; i<listArgc; i++) { + /* + * Each file type should have two or three elements: the first one + * is the name of the type and the second is the filter of the type. + * The third is the Mac OSType ID, but we don't care about them here. + */ + int count; + FileFilter * filterPtr; + + if (Tcl_SplitList(interp, listArgv[i], &count, &typeInfo) != TCL_OK) { + code = TCL_ERROR; + goto done; + } + + if (count != 2 && count != 3) { + Tcl_AppendResult(interp, "bad file type \"", listArgv[i], "\", ", + "should be \"typeName {extension ?extensions ...?} ", + "?{macType ?macTypes ...?}?\"", NULL); + code = TCL_ERROR; + goto done; + } + + filterPtr = GetFilter(flistPtr, typeInfo[0]); + + if (count == 2) { + code = AddClause(interp, filterPtr, typeInfo[1], NULL, + isWindows); + } else { + code = AddClause(interp, filterPtr, typeInfo[1], typeInfo[2], + isWindows); + } + if (code != TCL_OK) { + goto done; + } + + if (typeInfo) { + ckfree((char*)typeInfo); + } + typeInfo = NULL; + } + + done: + if (typeInfo) { + ckfree((char*)typeInfo); + } + if (listArgv) { + ckfree((char*)listArgv); + } + return code; +} + +/* + *---------------------------------------------------------------------- + * + * TkFreeFileFilters -- + * + * Frees the malloc'ed file filter information. + * + * Results: + * None. + * + * Side effects: + * The fields allocated by TkGetFileFilters() are freed. + *---------------------------------------------------------------------- + */ + +void +TkFreeFileFilters(flistPtr) + FileFilterList * flistPtr; /* List of file filters to free */ +{ + FileFilter * filterPtr, *toFree; + + filterPtr=flistPtr->filters; + while (filterPtr) { + toFree = filterPtr; + filterPtr=filterPtr->next; + FreeClauses(toFree); + ckfree((char*)toFree->name); + ckfree((char*)toFree); + } + flistPtr->filters = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * AddClause -- + * + * Add one FileFilterClause to filterPtr. + * + * Results: + * A standard TCL result. + * + * Side effects: + * The list of filter clauses are updated in filterPtr. + *---------------------------------------------------------------------- + */ + +static int AddClause(interp, filterPtr, patternsStr, ostypesStr, isWindows) + Tcl_Interp * interp; /* Interpreter to use for error reporting. */ + FileFilter * filterPtr; /* Stores the new filter clause */ + char * patternsStr; /* A TCL list of glob patterns. */ + char * ostypesStr; /* A TCL list of Mac OSType strings. */ + int isWindows; /* True if we are running on Windows; False + * if we are running on the Mac; Glob + * patterns need to be processed differently + * on these two platforms */ +{ + char ** globList = NULL; + int globCount; + char ** ostypeList = NULL; + int ostypeCount; + FileFilterClause * clausePtr; + int i; + int code = TCL_OK; + + if (Tcl_SplitList(interp, patternsStr, &globCount, &globList)!= TCL_OK) { + code = TCL_ERROR; + goto done; + } + if (ostypesStr != NULL) { + if (Tcl_SplitList(interp, ostypesStr, &ostypeCount, &ostypeList) + != TCL_OK) { + code = TCL_ERROR; + goto done; + } + for (i=0; i<ostypeCount; i++) { + if (strlen(ostypeList[i]) != 4) { + Tcl_AppendResult(interp, "bad Macintosh file type \"", + ostypeList[i], "\"", NULL); + code = TCL_ERROR; + goto done; + } + } + } + + /* + * Add the clause into the list of clauses + */ + + clausePtr = (FileFilterClause*)ckalloc(sizeof(FileFilterClause)); + clausePtr->patterns = NULL; + clausePtr->patternsTail = NULL; + clausePtr->macTypes = NULL; + clausePtr->macTypesTail = NULL; + + if (filterPtr->clauses == NULL) { + filterPtr->clauses = filterPtr->clausesTail = clausePtr; + } else { + filterPtr->clausesTail->next = clausePtr; + filterPtr->clausesTail = clausePtr; + } + clausePtr->next = NULL; + + if (globCount > 0 && globList != NULL) { + for (i=0; i<globCount; i++) { + GlobPattern * globPtr = (GlobPattern*)ckalloc(sizeof(GlobPattern)); + int len; + + len = (strlen(globList[i]) + 1) * sizeof(char); + + if (globList[i][0] && globList[i][0] != '*') { + /* + * Prepend a "*" to patterns that do not have a leading "*" + */ + globPtr->pattern = (char*)ckalloc(len+1); + globPtr->pattern[0] = '*'; + strcpy(globPtr->pattern+1, globList[i]); + } + else if (isWindows) { + if (strcmp(globList[i], "*") == 0) { + globPtr->pattern = (char*)ckalloc(4*sizeof(char)); + strcpy(globPtr->pattern, "*.*"); + } + else if (strcmp(globList[i], "") == 0) { + /* + * An empty string means "match all files with no + * extensions" + * BUG: "*." actually matches with all files on Win95 + */ + globPtr->pattern = (char*)ckalloc(3*sizeof(char)); + strcpy(globPtr->pattern, "*."); + } + else { + globPtr->pattern = (char*)ckalloc(len); + strcpy(globPtr->pattern, globList[i]); + } + } else { + globPtr->pattern = (char*)ckalloc(len); + strcpy(globPtr->pattern, globList[i]); + } + + /* + * Add the glob pattern into the list of patterns. + */ + + if (clausePtr->patterns == NULL) { + clausePtr->patterns = clausePtr->patternsTail = globPtr; + } else { + clausePtr->patternsTail->next = globPtr; + clausePtr->patternsTail = globPtr; + } + globPtr->next = NULL; + } + } + if (ostypeCount > 0 && ostypeList != NULL) { + for (i=0; i<ostypeCount; i++) { + MacFileType * mfPtr = (MacFileType*)ckalloc(sizeof(MacFileType)); + + memcpy(&mfPtr->type, ostypeList[i], sizeof(OSType)); + + /* + * Add the Mac type pattern into the list of Mac types + */ + if (clausePtr->macTypes == NULL) { + clausePtr->macTypes = clausePtr->macTypesTail = mfPtr; + } else { + clausePtr->macTypesTail->next = mfPtr; + clausePtr->macTypesTail = mfPtr; + } + mfPtr->next = NULL; + } + } + + done: + if (globList) { + ckfree((char*)globList); + } + if (ostypeList) { + ckfree((char*)ostypeList); + } + + return code; +} + +/* + *---------------------------------------------------------------------- + * + * GetFilter -- + * + * Add one FileFilter to flistPtr. + * + * Results: + * A standard TCL result. + * + * Side effects: + * The list of filters are updated in flistPtr. + *---------------------------------------------------------------------- + */ + +static FileFilter * GetFilter(flistPtr, name) + FileFilterList * flistPtr; /* The FileFilterList that contains the + * newly created filter */ + char * name; /* Name of the filter. It is usually displayed + * in the "File Types" listbox in the file + * dialogs. */ +{ + FileFilter * filterPtr; + + for (filterPtr=flistPtr->filters; filterPtr; filterPtr=filterPtr->next) { + if (strcmp(filterPtr->name, name)==0) { + return filterPtr; + } + } + + filterPtr = (FileFilter*)ckalloc(sizeof(FileFilter)); + filterPtr->clauses = NULL; + filterPtr->clausesTail = NULL; + filterPtr->name = (char*)ckalloc((strlen(name)+1) * sizeof(char)); + strcpy(filterPtr->name, name); + + if (flistPtr->filters == NULL) { + flistPtr->filters = flistPtr->filtersTail = filterPtr; + } else { + flistPtr->filtersTail->next = filterPtr; + flistPtr->filtersTail = filterPtr; + } + filterPtr->next = NULL; + + ++flistPtr->numFilters; + return filterPtr; +} + +/* + *---------------------------------------------------------------------- + * + * FreeClauses -- + * + * Frees the malloc'ed file type clause + * + * Results: + * None. + * + * Side effects: + * The list of clauses in filterPtr->clauses are freed. + *---------------------------------------------------------------------- + */ + +static void +FreeClauses(filterPtr) + FileFilter * filterPtr; /* FileFilter whose clauses are to be freed */ +{ + FileFilterClause * clausePtr, * toFree; + + clausePtr = filterPtr->clauses; + while (clausePtr) { + toFree = clausePtr; + clausePtr=clausePtr->next; + FreeGlobPatterns(toFree); + FreeMacFileTypes(toFree); + ckfree((char*)toFree); + } + filterPtr->clauses = NULL; + filterPtr->clausesTail = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * FreeGlobPatterns -- + * + * Frees the malloc'ed glob patterns in a clause + * + * Results: + * None. + * + * Side effects: + * The list of glob patterns in clausePtr->patterns are freed. + *---------------------------------------------------------------------- + */ + +static void +FreeGlobPatterns(clausePtr) + FileFilterClause * clausePtr;/* The clause whose patterns are to be freed*/ +{ + GlobPattern * globPtr, * toFree; + + globPtr = clausePtr->patterns; + while (globPtr) { + toFree = globPtr; + globPtr=globPtr->next; + + ckfree((char*)toFree->pattern); + ckfree((char*)toFree); + } + clausePtr->patterns = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * FreeMacFileTypes -- + * + * Frees the malloc'ed Mac file types in a clause + * + * Results: + * None. + * + * Side effects: + * The list of Mac file types in clausePtr->macTypes are freed. + *---------------------------------------------------------------------- + */ + +static void +FreeMacFileTypes(clausePtr) + FileFilterClause * clausePtr; /* The clause whose mac types are to be + * freed */ +{ + MacFileType * mfPtr, * toFree; + + mfPtr = clausePtr->macTypes; + while (mfPtr) { + toFree = mfPtr; + mfPtr=mfPtr->next; + ckfree((char*)toFree); + } + clausePtr->macTypes = NULL; +} diff --git a/generic/tkFileFilter.h b/generic/tkFileFilter.h new file mode 100644 index 0000000..2b113fc --- /dev/null +++ b/generic/tkFileFilter.h @@ -0,0 +1,83 @@ +/* + * tkFileFilter.h -- + * + * Declarations for the file filter processing routines needed by + * the file selection dialogs. + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkFileFilter.h 1.1 96/08/27 15:05:38 + * + */ + +#ifndef _TK_FILE_FILTER +#define _TK_FILE_FILTER + +#ifdef MAC_TCL +#include <StandardFile.h> +#else +#define OSType long +#endif + +typedef struct GlobPattern { + struct GlobPattern * next; /* Chains to the next glob pattern + * in a glob pattern list */ + char * pattern; /* String value of the pattern, such + * as "*.txt" or "*.*" + */ +} GlobPattern; + +typedef struct MacFileType { + struct MacFileType * next; /* Chains to the next mac file type + * in a mac file type list */ + OSType type; /* Mac file type, such as 'TEXT' or + * 'GIFF' */ +} MacFileType; + +typedef struct FileFilterClause { + struct FileFilterClause * next; /* Chains to the next clause in + * a clause list */ + GlobPattern * patterns; /* Head of glob pattern type list */ + GlobPattern * patternsTail; /* Tail of glob pattern type list */ + MacFileType * macTypes; /* Head of mac file type list */ + MacFileType * macTypesTail; /* Tail of mac file type list */ +} FileFilterClause; + +typedef struct FileFilter { + struct FileFilter * next; /* Chains to the next filter + * in a filter list */ + char * name; /* Name of the file filter, + * such as "Text Documents" */ + FileFilterClause * clauses; /* Head of the clauses list */ + FileFilterClause * clausesTail; /* Tail of the clauses list */ +} FileFilter; + +/*---------------------------------------------------------------------- + * FileFilterList -- + * + * The routine TkGetFileFilters() translates the string value of the + * -filefilters option into a FileFilterList structure, which consists + * of a list of file filters. + * + * Each file filter consists of one or more clauses. Each clause has + * one or more glob patterns and/or one or more Mac file types + *---------------------------------------------------------------------- + */ + +typedef struct FileFilterList { + FileFilter * filters; /* Head of the filter list */ + FileFilter * filtersTail; /* Tail of the filter list */ + int numFilters; /* number of filters in the list */ +} FileFilterList; + +EXTERN void TkFreeFileFilters _ANSI_ARGS_(( + FileFilterList * flistPtr)); +EXTERN void TkInitFileFilters _ANSI_ARGS_(( + FileFilterList * flistPtr)); +EXTERN int TkGetFileFilters _ANSI_ARGS_ ((Tcl_Interp *interp, + FileFilterList * flistPtr, char * string, + int isWindows)); +#endif diff --git a/generic/tkFocus.c b/generic/tkFocus.c new file mode 100644 index 0000000..fe8f2c5 --- /dev/null +++ b/generic/tkFocus.c @@ -0,0 +1,998 @@ +/* + * tkFocus.c -- + * + * This file contains procedures that manage the input + * focus for Tk. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkFocus.c 1.48 97/10/31 09:55:22 + */ + +#include "tkInt.h" +#include "tkPort.h" + + +/* + * For each top-level window that has ever received the focus, there + * is a record of the following type: + */ + +typedef struct TkToplevelFocusInfo { + TkWindow *topLevelPtr; /* Information about top-level window. */ + TkWindow *focusWinPtr; /* The next time the focus comes to this + * top-level, it will be given to this + * window. */ + struct TkToplevelFocusInfo *nextPtr; + /* Next in list of all toplevel focus records + * for a given application. */ +} ToplevelFocusInfo; + +/* + * One of the following structures exists for each display used by + * each application. These are linked together from the TkMainInfo + * structure. These structures are needed because it isn't + * sufficient to store a single piece of focus information in each + * display or in each application: we need the cross-product. + * There needs to be separate information for each display, because + * it's possible to have multiple focus windows active simultaneously + * on different displays. There also needs to be separate information + * for each application, because of embedding: if an embedded + * application has the focus, its container application also has + * the focus. Thus we keep a list of structures for each application: + * the same display can appear in structures for several applications + * at once. + */ + +typedef struct TkDisplayFocusInfo { + TkDisplay *dispPtr; /* Display that this information pertains + * to. */ + struct TkWindow *focusWinPtr; + /* Window that currently has the focus for + * this application on this display, or NULL + * if none. */ + struct TkWindow *focusOnMapPtr; + /* This points to a toplevel window that is + * supposed to receive the X input focus as + * soon as it is mapped (needed to handle the + * fact that X won't allow the focus on an + * unmapped window). NULL means no delayed + * focus op in progress for this display. */ + int forceFocus; /* Associated with focusOnMapPtr: non-zero + * means claim the focus even if some other + * application currently has it. */ + unsigned long focusSerial; /* Serial number of last request this + * application made to change the focus on + * this display. Used to identify stale + * focus notifications coming from the + * X server. */ + struct TkDisplayFocusInfo *nextPtr; + /* Next in list of all display focus + * records for a given application. */ +} DisplayFocusInfo; + +/* + * Global used for debugging. + */ + +int tclFocusDebug = 0; + +/* + * The following magic value is stored in the "send_event" field of + * FocusIn and FocusOut events that are generated in this file. This + * allows us to separate "real" events coming from the server from + * those that we generated. + */ + +#define GENERATED_EVENT_MAGIC ((Bool) 0x547321ac) + +/* + * Forward declarations for procedures defined in this file: + */ + + +static DisplayFocusInfo *FindDisplayFocusInfo _ANSI_ARGS_((TkMainInfo *mainPtr, + TkDisplay *dispPtr)); +static void FocusMapProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void GenerateFocusEvents _ANSI_ARGS_((TkWindow *sourcePtr, + TkWindow *destPtr)); +static void SetFocus _ANSI_ARGS_((TkWindow *winPtr, int force)); + +/* + *-------------------------------------------------------------- + * + * Tk_FocusCmd -- + * + * This procedure is invoked to process the "focus" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_FocusCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + TkWindow *winPtr = (TkWindow *) clientData; + TkWindow *newPtr, *focusWinPtr, *topLevelPtr; + ToplevelFocusInfo *tlFocusPtr; + char c; + size_t length; + + /* + * If invoked with no arguments, just return the current focus window. + */ + + if (argc == 1) { + focusWinPtr = TkGetFocusWin(winPtr); + if (focusWinPtr != NULL) { + interp->result = focusWinPtr->pathName; + } + return TCL_OK; + } + + /* + * If invoked with a single argument beginning with "." then focus + * on that window. + */ + + if (argc == 2) { + if (argv[1][0] == 0) { + return TCL_OK; + } + if (argv[1][0] == '.') { + newPtr = (TkWindow *) Tk_NameToWindow(interp, argv[1], tkwin); + if (newPtr == NULL) { + return TCL_ERROR; + } + if (!(newPtr->flags & TK_ALREADY_DEAD)) { + SetFocus(newPtr, 0); + } + return TCL_OK; + } + } + + length = strlen(argv[1]); + c = argv[1][1]; + if ((c == 'd') && (strncmp(argv[1], "-displayof", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " -displayof window\"", (char *) NULL); + return TCL_ERROR; + } + newPtr = (TkWindow *) Tk_NameToWindow(interp, argv[2], tkwin); + if (newPtr == NULL) { + return TCL_ERROR; + } + newPtr = TkGetFocusWin(newPtr); + if (newPtr != NULL) { + interp->result = newPtr->pathName; + } + } else if ((c == 'f') && (strncmp(argv[1], "-force", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " -force window\"", (char *) NULL); + return TCL_ERROR; + } + if (argv[2][0] == 0) { + return TCL_OK; + } + newPtr = (TkWindow *) Tk_NameToWindow(interp, argv[2], tkwin); + if (newPtr == NULL) { + return TCL_ERROR; + } + SetFocus(newPtr, 1); + } else if ((c == 'l') && (strncmp(argv[1], "-lastfor", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " -lastfor window\"", (char *) NULL); + return TCL_ERROR; + } + newPtr = (TkWindow *) Tk_NameToWindow(interp, argv[2], tkwin); + if (newPtr == NULL) { + return TCL_ERROR; + } + for (topLevelPtr = newPtr; topLevelPtr != NULL; + topLevelPtr = topLevelPtr->parentPtr) { + if (topLevelPtr->flags & TK_TOP_LEVEL) { + for (tlFocusPtr = newPtr->mainPtr->tlFocusPtr; + tlFocusPtr != NULL; + tlFocusPtr = tlFocusPtr->nextPtr) { + if (tlFocusPtr->topLevelPtr == topLevelPtr) { + interp->result = tlFocusPtr->focusWinPtr->pathName; + return TCL_OK; + } + } + interp->result = topLevelPtr->pathName; + return TCL_OK; + } + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be -displayof, -force, or -lastfor", (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * TkFocusFilterEvent -- + * + * This procedure is invoked by Tk_HandleEvent when it encounters + * a FocusIn, FocusOut, Enter, or Leave event. + * + * Results: + * A return value of 1 means that Tk_HandleEvent should process + * the event normally (i.e. event handlers should be invoked). + * A return value of 0 means that this event should be ignored. + * + * Side effects: + * Additional events may be generated, and the focus may switch. + * + *-------------------------------------------------------------- + */ + +int +TkFocusFilterEvent(winPtr, eventPtr) + TkWindow *winPtr; /* Window that focus event is directed to. */ + XEvent *eventPtr; /* FocusIn, FocusOut, Enter, or Leave + * event. */ +{ + /* + * Design notes: the window manager and X server work together to + * transfer the focus among top-level windows. This procedure takes + * care of transferring the focus from a top-level or wrapper window + * to the actual window within that top-level that has the focus. + * We do this by synthesizing X events to move the focus around. + * None of the FocusIn and FocusOut events generated by X are ever + * used outside of this procedure; only the synthesized events get + * through to the rest of the application. At one point (e.g. + * Tk4.0b1) Tk used to call X to move the focus from a top-level to + * one of its descendants, then just pass through the events + * generated by X. This approach didn't work very well, for a + * variety of reasons. For example, if X generates the events they + * go at the back of the event queue, which could cause problems if + * other things have already happened, such as moving the focus to + * yet another window. + */ + + ToplevelFocusInfo *tlFocusPtr; + DisplayFocusInfo *displayFocusPtr; + TkDisplay *dispPtr = winPtr->dispPtr; + TkWindow *newFocusPtr; + int retValue, delta; + + /* + * If this was a generated event, just turn off the generated + * flag and pass the event through to Tk bindings. + */ + + if (eventPtr->xfocus.send_event == GENERATED_EVENT_MAGIC) { + eventPtr->xfocus.send_event = 0; + return 1; + } + + /* + * Check for special events generated by embedded applications to + * request the input focus. If this is one of those events, make + * the change in focus and return without any additional processing + * of the event (note: the "detail" field of the event indicates + * whether to claim the focus even if we don't already have it). + */ + + if ((eventPtr->xfocus.mode == EMBEDDED_APP_WANTS_FOCUS) + && (eventPtr->type == FocusIn)) { + SetFocus(winPtr, eventPtr->xfocus.detail); + return 0; + } + + /* + * This was not a generated event. We'll return 1 (so that the + * event will be processed) if it's an Enter or Leave event, and + * 0 (so that the event won't be processed) if it's a FocusIn or + * FocusOut event. + */ + + retValue = 0; + displayFocusPtr = FindDisplayFocusInfo(winPtr->mainPtr, winPtr->dispPtr); + if (eventPtr->type == FocusIn) { + /* + * Skip FocusIn events that cause confusion + * NotifyVirtual and NotifyNonlinearVirtual - Virtual events occur + * on windows in between the origin and destination of the + * focus change. For FocusIn we may see this when focus + * goes into an embedded child. We don't care about this, + * although we may end up getting a NotifyPointer later. + * NotifyInferior - focus is coming to us from an embedded child. + * When focus is on an embeded focus, we still think we have + * the focus, too, so this message doesn't change our state. + * NotifyPointerRoot - should never happen because this is sent + * to the root window. + * + * Interesting FocusIn events are + * NotifyAncestor - focus is coming from our parent, probably the root. + * NotifyNonlinear - focus is coming from a different branch, probably + * another toplevel. + * NotifyPointer - implicit focus because of the mouse position. + * This is only interesting on toplevels, when it means that the + * focus has been set to the root window but the mouse is over + * this toplevel. We take the focus implicitly (probably no + * window manager) + */ + + if ((eventPtr->xfocus.detail == NotifyVirtual) + || (eventPtr->xfocus.detail == NotifyNonlinearVirtual) + || (eventPtr->xfocus.detail == NotifyPointerRoot) + || (eventPtr->xfocus.detail == NotifyInferior)) { + return retValue; + } + } else if (eventPtr->type == FocusOut) { + /* + * Skip FocusOut events that cause confusion. + * NotifyPointer - the pointer is in us or a child, and we are losing + * focus because of an XSetInputFocus. Other focus events + * will set our state properly. + * NotifyPointerRoot - should never happen because this is sent + * to the root window. + * NotifyInferior - focus leaving us for an embedded child. We + * retain a notion of focus when an embedded child has focus. + * + * Interesting events are: + * NotifyAncestor - focus is going to root. + * NotifyNonlinear - focus is going to another branch, probably + * another toplevel. + * NotifyVirtual, NotifyNonlinearVirtual - focus is passing through, + * and we need to make sure we track this. + */ + + if ((eventPtr->xfocus.detail == NotifyPointer) + || (eventPtr->xfocus.detail == NotifyPointerRoot) + || (eventPtr->xfocus.detail == NotifyInferior)) { + return retValue; + } + } else { + retValue = 1; + if (eventPtr->xcrossing.detail == NotifyInferior) { + return retValue; + } + } + + /* + * If winPtr isn't a top-level window than just ignore the event. + */ + + winPtr = TkWmFocusToplevel(winPtr); + if (winPtr == NULL) { + return retValue; + } + + /* + * If there is a grab in effect and this window is outside the + * grabbed tree, then ignore the event. + */ + + if (TkGrabState(winPtr) == TK_GRAB_EXCLUDED) { + return retValue; + } + + /* + * It is possible that there were outstanding FocusIn and FocusOut + * events on their way to us at the time the focus was changed + * internally with the "focus" command. If so, these events could + * potentially cause us to lose the focus (switch it to the window + * of the last FocusIn event) even though the focus change occurred + * after those events. The following code detects this and ignores + * the stale events. + * + * Note: the focusSerial is only generated by TkpChangeFocus, + * whereas in Tk 4.2 there was always a nop marker generated. + */ + + delta = eventPtr->xfocus.serial - displayFocusPtr->focusSerial; + if (delta < 0) { + return retValue; + } + + /* + * Find the ToplevelFocusInfo structure for the window, and make a new one + * if there isn't one already. + */ + + for (tlFocusPtr = winPtr->mainPtr->tlFocusPtr; tlFocusPtr != NULL; + tlFocusPtr = tlFocusPtr->nextPtr) { + if (tlFocusPtr->topLevelPtr == winPtr) { + break; + } + } + if (tlFocusPtr == NULL) { + tlFocusPtr = (ToplevelFocusInfo *) ckalloc(sizeof(ToplevelFocusInfo)); + tlFocusPtr->topLevelPtr = tlFocusPtr->focusWinPtr = winPtr; + tlFocusPtr->nextPtr = winPtr->mainPtr->tlFocusPtr; + winPtr->mainPtr->tlFocusPtr = tlFocusPtr; + } + newFocusPtr = tlFocusPtr->focusWinPtr; + + if (eventPtr->type == FocusIn) { + GenerateFocusEvents(displayFocusPtr->focusWinPtr, newFocusPtr); + displayFocusPtr->focusWinPtr = newFocusPtr; + dispPtr->focusPtr = newFocusPtr; + + /* + * NotifyPointer gets set when the focus has been set to the root window + * but we have the pointer. We'll treat this like an implicit + * focus in event so that upon Leave events we release focus. + */ + + if (!(winPtr->flags & TK_EMBEDDED)) { + if (eventPtr->xfocus.detail == NotifyPointer) { + dispPtr->implicitWinPtr = winPtr; + } else { + dispPtr->implicitWinPtr = NULL; + } + } + } else if (eventPtr->type == FocusOut) { + GenerateFocusEvents(displayFocusPtr->focusWinPtr, (TkWindow *) NULL); + + /* + * Reset dispPtr->focusPtr, but only if it currently is the same + * as this application's focusWinPtr: this check is needed to + * handle embedded applications in the same process. + */ + + if (dispPtr->focusPtr == displayFocusPtr->focusWinPtr) { + dispPtr->focusPtr = NULL; + } + displayFocusPtr->focusWinPtr = NULL; + } else if (eventPtr->type == EnterNotify) { + /* + * If there is no window manager, or if the window manager isn't + * moving the focus around (e.g. the disgusting "NoTitleFocus" + * option has been selected in twm), then we won't get FocusIn + * or FocusOut events. Instead, the "focus" field will be set + * in an Enter event to indicate that we've already got the focus + * when the mouse enters the window (even though we didn't get + * a FocusIn event). Watch for this and grab the focus when it + * happens. Note: if this is an embedded application then don't + * accept the focus implicitly like this; the container + * application will give us the focus explicitly if it wants us + * to have it. + */ + + if (eventPtr->xcrossing.focus && + (displayFocusPtr->focusWinPtr == NULL) + && !(winPtr->flags & TK_EMBEDDED)) { + if (tclFocusDebug) { + printf("Focussed implicitly on %s\n", + newFocusPtr->pathName); + } + + GenerateFocusEvents(displayFocusPtr->focusWinPtr, newFocusPtr); + displayFocusPtr->focusWinPtr = newFocusPtr; + dispPtr->implicitWinPtr = winPtr; + dispPtr->focusPtr = newFocusPtr; + } + } else if (eventPtr->type == LeaveNotify) { + /* + * If the pointer just left a window for which we automatically + * claimed the focus on enter, move the focus back to the root + * window, where it was before we claimed it above. Note: + * dispPtr->implicitWinPtr may not be the same as + * displayFocusPtr->focusWinPtr (e.g. because the "focus" + * command was used to redirect the focus after it arrived at + * dispPtr->implicitWinPtr)!! In addition, we generate events + * because the window manager won't give us a FocusOut event when + * we focus on the root. + */ + + if ((dispPtr->implicitWinPtr != NULL) + && !(winPtr->flags & TK_EMBEDDED)) { + if (tclFocusDebug) { + printf("Defocussed implicit Async\n"); + } + GenerateFocusEvents(displayFocusPtr->focusWinPtr, + (TkWindow *) NULL); + XSetInputFocus(dispPtr->display, PointerRoot, RevertToPointerRoot, + CurrentTime); + displayFocusPtr->focusWinPtr = NULL; + dispPtr->implicitWinPtr = NULL; + } + } + return retValue; +} + +/* + *---------------------------------------------------------------------- + * + * SetFocus -- + * + * This procedure is invoked to change the focus window for a + * given display in a given application. + * + * Results: + * None. + * + * Side effects: + * Event handlers may be invoked to process the change of + * focus. + * + *---------------------------------------------------------------------- + */ + +static void +SetFocus(winPtr, force) + TkWindow *winPtr; /* Window that is to be the new focus for + * its display and application. */ + int force; /* If non-zero, set the X focus to this + * window even if the application doesn't + * currently have the X focus. */ +{ + ToplevelFocusInfo *tlFocusPtr; + DisplayFocusInfo *displayFocusPtr; + TkWindow *topLevelPtr; + int allMapped, serial; + + displayFocusPtr = FindDisplayFocusInfo(winPtr->mainPtr, winPtr->dispPtr); + if (winPtr == displayFocusPtr->focusWinPtr) { + return; + } + + /* + * Find the top-level window for winPtr, then find (or create) + * a record for the top-level. Also see whether winPtr and all its + * ancestors are mapped. + */ + + allMapped = 1; + for (topLevelPtr = winPtr; ; topLevelPtr = topLevelPtr->parentPtr) { + if (topLevelPtr == NULL) { + /* + * The window is being deleted. No point in worrying about + * giving it the focus. + */ + return; + } + if (!(topLevelPtr->flags & TK_MAPPED)) { + allMapped = 0; + } + if (topLevelPtr->flags & TK_TOP_LEVEL) { + break; + } + } + + /* + * If the new focus window isn't mapped, then we can't focus on it + * (X will generate an error, for example). Instead, create an + * event handler that will set the focus to this window once it gets + * mapped. At the same time, delete any old handler that might be + * around; it's no longer relevant. + */ + + if (displayFocusPtr->focusOnMapPtr != NULL) { + Tk_DeleteEventHandler( + (Tk_Window) displayFocusPtr->focusOnMapPtr, + StructureNotifyMask, FocusMapProc, + (ClientData) displayFocusPtr->focusOnMapPtr); + displayFocusPtr->focusOnMapPtr = NULL; + } + if (!allMapped) { + Tk_CreateEventHandler((Tk_Window) winPtr, + VisibilityChangeMask, FocusMapProc, + (ClientData) winPtr); + displayFocusPtr->focusOnMapPtr = winPtr; + displayFocusPtr->forceFocus = force; + return; + } + + for (tlFocusPtr = winPtr->mainPtr->tlFocusPtr; tlFocusPtr != NULL; + tlFocusPtr = tlFocusPtr->nextPtr) { + if (tlFocusPtr->topLevelPtr == topLevelPtr) { + break; + } + } + if (tlFocusPtr == NULL) { + tlFocusPtr = (ToplevelFocusInfo *) ckalloc(sizeof(ToplevelFocusInfo)); + tlFocusPtr->topLevelPtr = topLevelPtr; + tlFocusPtr->nextPtr = winPtr->mainPtr->tlFocusPtr; + winPtr->mainPtr->tlFocusPtr = tlFocusPtr; + } + tlFocusPtr->focusWinPtr = winPtr; + + /* + * Reset the window system's focus window and generate focus events, + * with two special cases: + * + * 1. If the application is embedded and doesn't currently have the + * focus, don't set the focus directly. Instead, see if the + * embedding code can claim the focus from the enclosing + * container. + * 2. Otherwise, if the application doesn't currently have the + * focus, don't change the window system's focus unless it was + * already in this application or "force" was specified. + */ + + if ((topLevelPtr->flags & TK_EMBEDDED) + && (displayFocusPtr->focusWinPtr == NULL)) { + TkpClaimFocus(topLevelPtr, force); + } else if ((displayFocusPtr->focusWinPtr != NULL) || force) { + /* + * Generate events to shift focus between Tk windows. + * We do this regardless of what TkpChangeFocus does with + * the real X focus so that Tk widgets track focus commands + * when there is no window manager. GenerateFocusEvents will + * set up a serial number marker so we discard focus events + * that are triggered by the ChangeFocus. + */ + + serial = TkpChangeFocus(TkpGetWrapperWindow(topLevelPtr), force); + if (serial != 0) { + displayFocusPtr->focusSerial = serial; + } + GenerateFocusEvents(displayFocusPtr->focusWinPtr, winPtr); + displayFocusPtr->focusWinPtr = winPtr; + winPtr->dispPtr->focusPtr = winPtr; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkGetFocusWin -- + * + * Given a window, this procedure returns the current focus + * window for its application and display. + * + * Results: + * The return value is a pointer to the window that currently + * has the input focus for the specified application and + * display, or NULL if none. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkGetFocusWin(winPtr) + TkWindow *winPtr; /* Window that selects an application + * and a display. */ +{ + DisplayFocusInfo *displayFocusPtr; + + if (winPtr == NULL) { + return (TkWindow *) NULL; + } + + displayFocusPtr = FindDisplayFocusInfo(winPtr->mainPtr, winPtr->dispPtr); + return displayFocusPtr->focusWinPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkFocusKeyEvent -- + * + * Given a window and a key press or release event that arrived for + * the window, use information about the keyboard focus to compute + * which window should really get the event. In addition, update + * the event to refer to its new window. + * + * Results: + * The return value is a pointer to the window that has the input + * focus in winPtr's application, or NULL if winPtr's application + * doesn't have the input focus. If a non-NULL value is returned, + * eventPtr will be updated to refer properly to the focus window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkFocusKeyEvent(winPtr, eventPtr) + TkWindow *winPtr; /* Window that selects an application + * and a display. */ + XEvent *eventPtr; /* X event to redirect (should be KeyPress + * or KeyRelease). */ +{ + DisplayFocusInfo *displayFocusPtr; + TkWindow *focusWinPtr; + int focusX, focusY, vRootX, vRootY, vRootWidth, vRootHeight; + + displayFocusPtr = FindDisplayFocusInfo(winPtr->mainPtr, winPtr->dispPtr); + focusWinPtr = displayFocusPtr->focusWinPtr; + + /* + * The code below is a debugging aid to make sure that dispPtr->focusPtr + * is kept properly in sync with the "truth", which is the value in + * displayFocusPtr->focusWinPtr. + */ + +#ifdef TCL_MEM_DEBUG + if (focusWinPtr != winPtr->dispPtr->focusPtr) { + printf("TkFocusKeyEvent found dispPtr->focusPtr out of sync:\n"); + printf("expected %s, got %s\n", + (focusWinPtr != NULL) ? focusWinPtr->pathName : "??", + (winPtr->dispPtr->focusPtr != NULL) ? + winPtr->dispPtr->focusPtr->pathName : "??"); + } +#endif + + if ((focusWinPtr != NULL) && (focusWinPtr->mainPtr == winPtr->mainPtr)) { + /* + * Map the x and y coordinates to make sense in the context of + * the focus window, if possible (make both -1 if the map-from + * and map-to windows don't share the same screen). + */ + + if ((focusWinPtr->display != winPtr->display) + || (focusWinPtr->screenNum != winPtr->screenNum)) { + eventPtr->xkey.x = -1; + eventPtr->xkey.y = -1; + } else { + Tk_GetVRootGeometry((Tk_Window) focusWinPtr, &vRootX, &vRootY, + &vRootWidth, &vRootHeight); + Tk_GetRootCoords((Tk_Window) focusWinPtr, &focusX, &focusY); + eventPtr->xkey.x = eventPtr->xkey.x_root - vRootX - focusX; + eventPtr->xkey.y = eventPtr->xkey.y_root - vRootY - focusY; + } + eventPtr->xkey.window = focusWinPtr->window; + return focusWinPtr; + } + + /* + * The event doesn't belong to us. Perhaps, due to embedding, it + * really belongs to someone else. Give the embedding code a chance + * to redirect the event. + */ + + TkpRedirectKeyEvent(winPtr, eventPtr); + return (TkWindow *) NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TkFocusDeadWindow -- + * + * This procedure is invoked when it is determined that + * a window is dead. It cleans up focus-related information + * about the window. + * + * Results: + * None. + * + * Side effects: + * Various things get cleaned up and recycled. + * + *---------------------------------------------------------------------- + */ + +void +TkFocusDeadWindow(winPtr) + register TkWindow *winPtr; /* Information about the window + * that is being deleted. */ +{ + ToplevelFocusInfo *tlFocusPtr, *prevPtr; + DisplayFocusInfo *displayFocusPtr; + TkDisplay *dispPtr = winPtr->dispPtr; + + /* + * Search for focus records that refer to this window either as + * the top-level window or the current focus window. + */ + + displayFocusPtr = FindDisplayFocusInfo(winPtr->mainPtr, winPtr->dispPtr); + for (prevPtr = NULL, tlFocusPtr = winPtr->mainPtr->tlFocusPtr; + tlFocusPtr != NULL; + prevPtr = tlFocusPtr, tlFocusPtr = tlFocusPtr->nextPtr) { + if (winPtr == tlFocusPtr->topLevelPtr) { + /* + * The top-level window is the one being deleted: free + * the focus record and release the focus back to PointerRoot + * if we acquired it implicitly. + */ + + if (dispPtr->implicitWinPtr == winPtr) { + if (tclFocusDebug) { + printf("releasing focus to root after %s died\n", + tlFocusPtr->topLevelPtr->pathName); + } + dispPtr->implicitWinPtr = NULL; + displayFocusPtr->focusWinPtr = NULL; + dispPtr->focusPtr = NULL; + } + if (displayFocusPtr->focusWinPtr == tlFocusPtr->focusWinPtr) { + displayFocusPtr->focusWinPtr = NULL; + dispPtr->focusPtr = NULL; + } + if (prevPtr == NULL) { + winPtr->mainPtr->tlFocusPtr = tlFocusPtr->nextPtr; + } else { + prevPtr->nextPtr = tlFocusPtr->nextPtr; + } + ckfree((char *) tlFocusPtr); + break; + } else if (winPtr == tlFocusPtr->focusWinPtr) { + /* + * The deleted window had the focus for its top-level: + * move the focus to the top-level itself. + */ + + tlFocusPtr->focusWinPtr = tlFocusPtr->topLevelPtr; + if ((displayFocusPtr->focusWinPtr == winPtr) + && !(tlFocusPtr->topLevelPtr->flags & TK_ALREADY_DEAD)) { + if (tclFocusDebug) { + printf("forwarding focus to %s after %s died\n", + tlFocusPtr->topLevelPtr->pathName, + winPtr->pathName); + } + GenerateFocusEvents(displayFocusPtr->focusWinPtr, + tlFocusPtr->topLevelPtr); + displayFocusPtr->focusWinPtr = tlFocusPtr->topLevelPtr; + dispPtr->focusPtr = tlFocusPtr->topLevelPtr; + } + break; + } + } + + if (displayFocusPtr->focusOnMapPtr == winPtr) { + displayFocusPtr->focusOnMapPtr = NULL; + } +} + +/* + *---------------------------------------------------------------------- + * + * GenerateFocusEvents -- + * + * This procedure is called to create FocusIn and FocusOut events to + * move the input focus from one window to another. + * + * Results: + * None. + * + * Side effects: + * FocusIn and FocusOut events are generated. + * + *---------------------------------------------------------------------- + */ + +static void +GenerateFocusEvents(sourcePtr, destPtr) + TkWindow *sourcePtr; /* Window that used to have the focus (may + * be NULL). */ + TkWindow *destPtr; /* New window to have the focus (may be + * NULL). */ + +{ + XEvent event; + TkWindow *winPtr; + + winPtr = sourcePtr; + if (winPtr == NULL) { + winPtr = destPtr; + if (winPtr == NULL) { + return; + } + } + + event.xfocus.serial = LastKnownRequestProcessed(winPtr->display); + event.xfocus.send_event = GENERATED_EVENT_MAGIC; + event.xfocus.display = winPtr->display; + event.xfocus.mode = NotifyNormal; + TkInOutEvents(&event, sourcePtr, destPtr, FocusOut, FocusIn, + TCL_QUEUE_MARK); +} + +/* + *---------------------------------------------------------------------- + * + * FocusMapProc -- + * + * This procedure is called as an event handler for VisibilityNotify + * events, if a window receives the focus at a time when its + * toplevel isn't mapped. The procedure is needed because X + * won't allow the focus to be set to an unmapped window; we + * detect when the toplevel is mapped and set the focus to it then. + * + * Results: + * None. + * + * Side effects: + * If this is a map event, the focus gets set to the toplevel + * given by clientData. + * + *---------------------------------------------------------------------- + */ + +static void +FocusMapProc(clientData, eventPtr) + ClientData clientData; /* Toplevel window. */ + XEvent *eventPtr; /* Information about event. */ +{ + TkWindow *winPtr = (TkWindow *) clientData; + DisplayFocusInfo *displayFocusPtr; + + if (eventPtr->type == VisibilityNotify) { + displayFocusPtr = FindDisplayFocusInfo(winPtr->mainPtr, + winPtr->dispPtr); + if (tclFocusDebug) { + printf("auto-focussing on %s, force %d\n", winPtr->pathName, + displayFocusPtr->forceFocus); + } + Tk_DeleteEventHandler((Tk_Window) winPtr, VisibilityChangeMask, + FocusMapProc, clientData); + displayFocusPtr->focusOnMapPtr = NULL; + SetFocus(winPtr, displayFocusPtr->forceFocus); + } +} + +/* + *---------------------------------------------------------------------- + * + * FindDisplayFocusInfo -- + * + * Given an application and a display, this procedure locate the + * focus record for that combination. If no such record exists, + * it creates a new record and initializes it. + * + * Results: + * The return value is a pointer to the record. + * + * Side effects: + * A new record will be allocated if there wasn't one already. + * + *---------------------------------------------------------------------- + */ + +static DisplayFocusInfo * +FindDisplayFocusInfo(mainPtr, dispPtr) + TkMainInfo *mainPtr; /* Record that identifies a particular + * application. */ + TkDisplay *dispPtr; /* Display whose focus information is + * needed. */ +{ + DisplayFocusInfo *displayFocusPtr; + + for (displayFocusPtr = mainPtr->displayFocusPtr; + displayFocusPtr != NULL; + displayFocusPtr = displayFocusPtr->nextPtr) { + if (displayFocusPtr->dispPtr == dispPtr) { + return displayFocusPtr; + } + } + + /* + * The record doesn't exist yet. Make a new one. + */ + + displayFocusPtr = (DisplayFocusInfo *) ckalloc(sizeof(DisplayFocusInfo)); + displayFocusPtr->dispPtr = dispPtr; + displayFocusPtr->focusWinPtr = NULL; + displayFocusPtr->focusOnMapPtr = NULL; + displayFocusPtr->forceFocus = 0; + displayFocusPtr->focusSerial = 0; + displayFocusPtr->nextPtr = mainPtr->displayFocusPtr; + mainPtr->displayFocusPtr = displayFocusPtr; + return displayFocusPtr; +} diff --git a/generic/tkFont.c b/generic/tkFont.c new file mode 100644 index 0000000..11929b6 --- /dev/null +++ b/generic/tkFont.c @@ -0,0 +1,3008 @@ +/* + * tkFont.c -- + * + * This file maintains a database of fonts for the Tk toolkit. + * It also provides several utility procedures for measuring and + * displaying text. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkFont.c 1.74 97/10/10 14:34:11 + */ + +#include "tkInt.h" +#include "tkFont.h" + +/* + * The following structure is used to keep track of all the fonts that + * exist in the current application. It must be stored in the + * TkMainInfo for the application. + */ + +typedef struct TkFontInfo { + Tcl_HashTable fontCache; /* Map a string to an existing Tk_Font. + * Keys are CachedFontKey structs, values are + * TkFont structs. */ + Tcl_HashTable namedTable; /* Map a name to a set of attributes for a + * font, used when constructing a Tk_Font from + * a named font description. Keys are + * Tk_Uids, values are NamedFont structs. */ + TkMainInfo *mainPtr; /* Application that owns this structure. */ + int updatePending; +} TkFontInfo; + +/* + * The following structure is used as a key in the fontCache. + */ + +typedef struct CachedFontKey { + Display *display; /* Display for which font was constructed. */ + Tk_Uid string; /* String that describes font. */ +} CachedFontKey; + +/* + * The following data structure is used to keep track of the font attributes + * for each named font that has been defined. The named font is only deleted + * when the last reference to it goes away. + */ + +typedef struct NamedFont { + int refCount; /* Number of users of named font. */ + int deletePending; /* Non-zero if font should be deleted when + * last reference goes away. */ + TkFontAttributes fa; /* Desired attributes for named font. */ +} NamedFont; + +/* + * The following two structures are used to keep track of string + * measurement information when using the text layout facilities. + * + * A LayoutChunk represents a contiguous range of text that can be measured + * and displayed by low-level text calls. In general, chunks will be + * delimited by newlines and tabs. Low-level, platform-specific things + * like kerning and non-integer character widths may occur between the + * characters in a single chunk, but not between characters in different + * chunks. + * + * A TextLayout is a collection of LayoutChunks. It can be displayed with + * respect to any origin. It is the implementation of the Tk_TextLayout + * opaque token. + */ + +typedef struct LayoutChunk { + CONST char *start; /* Pointer to simple string to be displayed. + * This is a pointer into the TkTextLayout's + * string. */ + int numChars; /* The number of characters in this chunk. */ + int numDisplayChars; /* The number of characters to display when + * this chunk is displayed. Can be less than + * numChars if extra space characters were + * absorbed by the end of the chunk. This + * will be < 0 if this is a chunk that is + * holding a tab or newline. */ + int x, y; /* The origin of the first character in this + * chunk with respect to the upper-left hand + * corner of the TextLayout. */ + int totalWidth; /* Width in pixels of this chunk. Used + * when hit testing the invisible spaces at + * the end of a chunk. */ + int displayWidth; /* Width in pixels of the displayable + * characters in this chunk. Can be less than + * width if extra space characters were + * absorbed by the end of the chunk. */ +} LayoutChunk; + +typedef struct TextLayout { + Tk_Font tkfont; /* The font used when laying out the text. */ + CONST char *string; /* The string that was layed out. */ + int width; /* The maximum width of all lines in the + * text layout. */ + int numChunks; /* Number of chunks actually used in + * following array. */ + LayoutChunk chunks[1]; /* Array of chunks. The actual size will + * be maxChunks. THIS FIELD MUST BE THE LAST + * IN THE STRUCTURE. */ +} TextLayout; + +/* + * The following structures are used as two-way maps between the values for + * the fields in the TkFontAttributes structure and the strings used in + * Tcl, when parsing both option-value format and style-list format font + * name strings. + */ + +static TkStateMap weightMap[] = { + {TK_FW_NORMAL, "normal"}, + {TK_FW_BOLD, "bold"}, + {TK_FW_UNKNOWN, NULL} +}; + +static TkStateMap slantMap[] = { + {TK_FS_ROMAN, "roman"}, + {TK_FS_ITALIC, "italic"}, + {TK_FS_UNKNOWN, NULL} +}; + +static TkStateMap underlineMap[] = { + {1, "underline"}, + {0, NULL} +}; + +static TkStateMap overstrikeMap[] = { + {1, "overstrike"}, + {0, NULL} +}; + +/* + * The following structures are used when parsing XLFD's into a set of + * TkFontAttributes. + */ + +static TkStateMap xlfdWeightMap[] = { + {TK_FW_NORMAL, "normal"}, + {TK_FW_NORMAL, "medium"}, + {TK_FW_NORMAL, "book"}, + {TK_FW_NORMAL, "light"}, + {TK_FW_BOLD, "bold"}, + {TK_FW_BOLD, "demi"}, + {TK_FW_BOLD, "demibold"}, + {TK_FW_NORMAL, NULL} /* Assume anything else is "normal". */ +}; + +static TkStateMap xlfdSlantMap[] = { + {TK_FS_ROMAN, "r"}, + {TK_FS_ITALIC, "i"}, + {TK_FS_OBLIQUE, "o"}, + {TK_FS_ROMAN, NULL} /* Assume anything else is "roman". */ +}; + +static TkStateMap xlfdSetwidthMap[] = { + {TK_SW_NORMAL, "normal"}, + {TK_SW_CONDENSE, "narrow"}, + {TK_SW_CONDENSE, "semicondensed"}, + {TK_SW_CONDENSE, "condensed"}, + {TK_SW_UNKNOWN, NULL} +}; + +static TkStateMap xlfdCharsetMap[] = { + {TK_CS_NORMAL, "iso8859"}, + {TK_CS_SYMBOL, "adobe"}, + {TK_CS_SYMBOL, "sun"}, + {TK_CS_OTHER, NULL} +}; + +/* + * The following structure and defines specify the valid builtin options + * when configuring a set of font attributes. + */ + +static char *fontOpt[] = { + "-family", + "-size", + "-weight", + "-slant", + "-underline", + "-overstrike", + NULL +}; + +#define FONT_FAMILY 0 +#define FONT_SIZE 1 +#define FONT_WEIGHT 2 +#define FONT_SLANT 3 +#define FONT_UNDERLINE 4 +#define FONT_OVERSTRIKE 5 +#define FONT_NUMFIELDS 6 /* Length of fontOpt array. */ + +#define GetFontAttributes(tkfont) \ + ((CONST TkFontAttributes *) &((TkFont *) (tkfont))->fa) + +#define GetFontMetrics(tkfont) \ + ((CONST TkFontMetrics *) &((TkFont *) (tkfont))->fm) + + +static int ConfigAttributesObj _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, int objc, Tcl_Obj *CONST objv[], + TkFontAttributes *faPtr)); +static int FieldSpecified _ANSI_ARGS_((CONST char *field)); +static int GetAttributeInfoObj _ANSI_ARGS_((Tcl_Interp *interp, + CONST TkFontAttributes *faPtr, Tcl_Obj *objPtr)); +static LayoutChunk * NewChunk _ANSI_ARGS_((TextLayout **layoutPtrPtr, + int *maxPtr, CONST char *start, int numChars, + int curX, int newX, int y)); +static int ParseFontNameObj _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tcl_Obj *objPtr, + TkFontAttributes *faPtr)); +static void RecomputeWidgets _ANSI_ARGS_((TkWindow *winPtr)); +static void TheWorldHasChanged _ANSI_ARGS_(( + ClientData clientData)); +static void UpdateDependantFonts _ANSI_ARGS_((TkFontInfo *fiPtr, + Tk_Window tkwin, Tcl_HashEntry *namedHashPtr)); + + + + +/* + *--------------------------------------------------------------------------- + * + * TkFontPkgInit -- + * + * This procedure is called when an application is created. It + * initializes all the structures that are used by the font + * package on a per application basis. + * + * Results: + * Returns a token that must be stored in the TkMainInfo for this + * application. + * + * Side effects: + * Memory allocated. + * + *--------------------------------------------------------------------------- + */ +void +TkFontPkgInit(mainPtr) + TkMainInfo *mainPtr; /* The application being created. */ +{ + TkFontInfo *fiPtr; + + fiPtr = (TkFontInfo *) ckalloc(sizeof(TkFontInfo)); + Tcl_InitHashTable(&fiPtr->fontCache, sizeof(CachedFontKey) / sizeof(int)); + Tcl_InitHashTable(&fiPtr->namedTable, TCL_ONE_WORD_KEYS); + fiPtr->mainPtr = mainPtr; + fiPtr->updatePending = 0; + mainPtr->fontInfoPtr = fiPtr; +} + +/* + *--------------------------------------------------------------------------- + * + * TkFontPkgFree -- + * + * This procedure is called when an application is deleted. It + * deletes all the structures that were used by the font package + * for this application. + * + * Results: + * None. + * + * Side effects: + * Memory freed. + * + *--------------------------------------------------------------------------- + */ + +void +TkFontPkgFree(mainPtr) + TkMainInfo *mainPtr; /* The application being deleted. */ +{ + TkFontInfo *fiPtr; + Tcl_HashEntry *hPtr; + Tcl_HashSearch search; + + fiPtr = mainPtr->fontInfoPtr; + + if (fiPtr->fontCache.numEntries != 0) { + panic("TkFontPkgFree: all fonts should have been freed already"); + } + Tcl_DeleteHashTable(&fiPtr->fontCache); + + hPtr = Tcl_FirstHashEntry(&fiPtr->namedTable, &search); + while (hPtr != NULL) { + ckfree((char *) Tcl_GetHashValue(hPtr)); + hPtr = Tcl_NextHashEntry(&search); + } + Tcl_DeleteHashTable(&fiPtr->namedTable); + if (fiPtr->updatePending != 0) { + Tcl_CancelIdleCall(TheWorldHasChanged, (ClientData) fiPtr); + } + ckfree((char *) fiPtr); +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_FontObjCmd -- + * + * This procedure is implemented to process the "font" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_FontObjCmd(clientData, interp, objc, objv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. */ +{ + int index; + Tk_Window tkwin; + TkFontInfo *fiPtr; + static char *optionStrings[] = { + "actual", "configure", "create", "delete", + "families", "measure", "metrics", "names", + NULL + }; + enum options { + FONT_ACTUAL, FONT_CONFIGURE, FONT_CREATE, FONT_DELETE, + FONT_FAMILIES, FONT_MEASURE, FONT_METRICS, FONT_NAMES + }; + + tkwin = (Tk_Window) clientData; + fiPtr = ((TkWindow *) tkwin)->mainPtr->fontInfoPtr; + + if (objc < 2) { + Tcl_WrongNumArgs(interp, 1, objv, "option ?arg?"); + return TCL_ERROR; + } + if (Tcl_GetIndexFromObj(interp, objv[1], optionStrings, "option", 0, + &index) != TCL_OK) { + return TCL_ERROR; + } + + switch ((enum options) index) { + case FONT_ACTUAL: { + int skip, result; + Tk_Font tkfont; + Tcl_Obj *objPtr; + CONST TkFontAttributes *faPtr; + + skip = TkGetDisplayOf(interp, objc - 3, objv + 3, &tkwin); + if (skip < 0) { + return TCL_ERROR; + } + if ((objc < 3) || (objc - skip > 4)) { + Tcl_WrongNumArgs(interp, 2, objv, + "font ?-displayof window? ?option?"); + return TCL_ERROR; + } + tkfont = Tk_GetFontFromObj(interp, tkwin, objv[2]); + if (tkfont == NULL) { + return TCL_ERROR; + } + objc -= skip; + objv += skip; + faPtr = GetFontAttributes(tkfont); + objPtr = NULL; + if (objc > 3) { + objPtr = objv[3]; + } + result = GetAttributeInfoObj(interp, faPtr, objPtr); + Tk_FreeFont(tkfont); + return result; + } + case FONT_CONFIGURE: { + int result; + char *string; + Tcl_Obj *objPtr; + NamedFont *nfPtr; + Tcl_HashEntry *namedHashPtr; + + if (objc < 3) { + Tcl_WrongNumArgs(interp, 2, objv, "fontname ?options?"); + return TCL_ERROR; + } + string = Tk_GetUid(Tcl_GetStringFromObj(objv[2], NULL)); + namedHashPtr = Tcl_FindHashEntry(&fiPtr->namedTable, string); + nfPtr = NULL; /* lint. */ + if (namedHashPtr != NULL) { + nfPtr = (NamedFont *) Tcl_GetHashValue(namedHashPtr); + } + if ((namedHashPtr == NULL) || (nfPtr->deletePending != 0)) { + Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "named font \"", string, + "\" doesn't exist", NULL); + return TCL_ERROR; + } + if (objc == 3) { + objPtr = NULL; + } else if (objc == 4) { + objPtr = objv[3]; + } else { + result = ConfigAttributesObj(interp, tkwin, objc - 3, + objv + 3, &nfPtr->fa); + UpdateDependantFonts(fiPtr, tkwin, namedHashPtr); + return result; + } + return GetAttributeInfoObj(interp, &nfPtr->fa, objPtr); + } + case FONT_CREATE: { + int skip, i; + char *name; + char buf[32]; + TkFontAttributes fa; + Tcl_HashEntry *namedHashPtr; + + skip = 3; + if (objc < 3) { + name = NULL; + } else { + name = Tcl_GetStringFromObj(objv[2], NULL); + if (name[0] == '-') { + name = NULL; + } + } + if (name == NULL) { + /* + * No font name specified. Generate one of the form "fontX". + */ + + for (i = 1; ; i++) { + sprintf(buf, "font%d", i); + namedHashPtr = Tcl_FindHashEntry(&fiPtr->namedTable, + Tk_GetUid(buf)); + if (namedHashPtr == NULL) { + break; + } + } + name = buf; + skip = 2; + } + TkInitFontAttributes(&fa); + if (ConfigAttributesObj(interp, tkwin, objc - skip, objv + skip, + &fa) != TCL_OK) { + return TCL_ERROR; + } + if (TkCreateNamedFont(interp, tkwin, name, &fa) != TCL_OK) { + return TCL_ERROR; + } + Tcl_SetStringObj(Tcl_GetObjResult(interp), name, -1); + break; + } + case FONT_DELETE: { + int i; + char *string; + NamedFont *nfPtr; + Tcl_HashEntry *namedHashPtr; + + /* + * Delete the named font. If there are still widgets using this + * font, then it isn't deleted right away. + */ + + if (objc < 3) { + Tcl_WrongNumArgs(interp, 2, objv, "fontname ?fontname ...?"); + return TCL_ERROR; + } + for (i = 2; i < objc; i++) { + string = Tk_GetUid(Tcl_GetStringFromObj(objv[i], NULL)); + namedHashPtr = Tcl_FindHashEntry(&fiPtr->namedTable, string); + if (namedHashPtr == NULL) { + Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "named font \"", string, + "\" doesn't exist", (char *) NULL); + return TCL_ERROR; + } + nfPtr = (NamedFont *) Tcl_GetHashValue(namedHashPtr); + if (nfPtr->refCount != 0) { + nfPtr->deletePending = 1; + } else { + Tcl_DeleteHashEntry(namedHashPtr); + ckfree((char *) nfPtr); + } + } + break; + } + case FONT_FAMILIES: { + int skip; + + skip = TkGetDisplayOf(interp, objc - 2, objv + 2, &tkwin); + if (skip < 0) { + return TCL_ERROR; + } + if (objc - skip != 2) { + Tcl_WrongNumArgs(interp, 2, objv, "?-displayof window?"); + return TCL_ERROR; + } + TkpGetFontFamilies(interp, tkwin); + break; + } + case FONT_MEASURE: { + char *string; + Tk_Font tkfont; + int length, skip; + + skip = TkGetDisplayOf(interp, objc - 3, objv + 3, &tkwin); + if (skip < 0) { + return TCL_ERROR; + } + if (objc - skip != 4) { + Tcl_WrongNumArgs(interp, 2, objv, + "font ?-displayof window? text"); + return TCL_ERROR; + } + tkfont = Tk_GetFontFromObj(interp, tkwin, objv[2]); + if (tkfont == NULL) { + return TCL_ERROR; + } + string = Tcl_GetStringFromObj(objv[3 + skip], &length); + Tcl_SetIntObj(Tcl_GetObjResult(interp), Tk_TextWidth(tkfont, string, length)); + Tk_FreeFont(tkfont); + break; + } + case FONT_METRICS: { + char buf[64]; + Tk_Font tkfont; + int skip, index, i; + CONST TkFontMetrics *fmPtr; + static char *switches[] = { + "-ascent", "-descent", "-linespace", "-fixed", NULL + }; + + skip = TkGetDisplayOf(interp, objc - 3, objv + 3, &tkwin); + if (skip < 0) { + return TCL_ERROR; + } + if ((objc < 3) || ((objc - skip) > 4)) { + Tcl_WrongNumArgs(interp, 2, objv, + "font ?-displayof window? ?option?"); + return TCL_ERROR; + } + tkfont = Tk_GetFontFromObj(interp, tkwin, objv[2]); + if (tkfont == NULL) { + return TCL_ERROR; + } + objc -= skip; + objv += skip; + fmPtr = GetFontMetrics(tkfont); + if (objc == 3) { + sprintf(buf, "-ascent %d -descent %d -linespace %d -fixed %d", + fmPtr->ascent, fmPtr->descent, + fmPtr->ascent + fmPtr->descent, + fmPtr->fixed); + Tcl_SetStringObj(Tcl_GetObjResult(interp), buf, -1); + } else { + if (Tcl_GetIndexFromObj(interp, objv[3], switches, + "metric", 0, &index) != TCL_OK) { + Tk_FreeFont(tkfont); + return TCL_ERROR; + } + i = 0; /* Needed only to prevent compiler + * warning. */ + switch (index) { + case 0: i = fmPtr->ascent; break; + case 1: i = fmPtr->descent; break; + case 2: i = fmPtr->ascent + fmPtr->descent; break; + case 3: i = fmPtr->fixed; break; + } + Tcl_SetIntObj(Tcl_GetObjResult(interp), i); + } + Tk_FreeFont(tkfont); + break; + } + case FONT_NAMES: { + char *string; + Tcl_Obj *strPtr; + NamedFont *nfPtr; + Tcl_HashSearch search; + Tcl_HashEntry *namedHashPtr; + + if (objc != 2) { + Tcl_WrongNumArgs(interp, 1, objv, "names"); + return TCL_ERROR; + } + namedHashPtr = Tcl_FirstHashEntry(&fiPtr->namedTable, &search); + while (namedHashPtr != NULL) { + nfPtr = (NamedFont *) Tcl_GetHashValue(namedHashPtr); + if (nfPtr->deletePending == 0) { + string = Tcl_GetHashKey(&fiPtr->namedTable, namedHashPtr); + strPtr = Tcl_NewStringObj(string, -1); + Tcl_ListObjAppendElement(NULL, Tcl_GetObjResult(interp), strPtr); + } + namedHashPtr = Tcl_NextHashEntry(&search); + } + break; + } + } + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * UpdateDependantFonts, TheWorldHasChanged, RecomputeWidgets -- + * + * Called when the attributes of a named font changes. Updates all + * the instantiated fonts that depend on that named font and then + * uses the brute force approach and prepares every widget to + * recompute its geometry. + * + * Results: + * None. + * + * Side effects: + * Things get queued for redisplay. + * + *--------------------------------------------------------------------------- + */ + +static void +UpdateDependantFonts(fiPtr, tkwin, namedHashPtr) + TkFontInfo *fiPtr; /* Info about application's fonts. */ + Tk_Window tkwin; /* A window in the application. */ + Tcl_HashEntry *namedHashPtr;/* The named font that is changing. */ +{ + Tcl_HashEntry *cacheHashPtr; + Tcl_HashSearch search; + TkFont *fontPtr; + NamedFont *nfPtr; + + nfPtr = (NamedFont *) Tcl_GetHashValue(namedHashPtr); + if (nfPtr->refCount == 0) { + /* + * Well nobody's using this named font, so don't have to tell + * any widgets to recompute themselves. + */ + + return; + } + + + cacheHashPtr = Tcl_FirstHashEntry(&fiPtr->fontCache, &search); + while (cacheHashPtr != NULL) { + fontPtr = (TkFont *) Tcl_GetHashValue(cacheHashPtr); + if (fontPtr->namedHashPtr == namedHashPtr) { + TkpGetFontFromAttributes(fontPtr, tkwin, &nfPtr->fa); + if (fiPtr->updatePending == 0) { + fiPtr->updatePending = 1; + Tcl_DoWhenIdle(TheWorldHasChanged, (ClientData) fiPtr); + } + } + cacheHashPtr = Tcl_NextHashEntry(&search); + } +} + +static void +TheWorldHasChanged(clientData) + ClientData clientData; /* Info about application's fonts. */ +{ + TkFontInfo *fiPtr; + + fiPtr = (TkFontInfo *) clientData; + fiPtr->updatePending = 0; + + RecomputeWidgets(fiPtr->mainPtr->winPtr); +} + +static void +RecomputeWidgets(winPtr) + TkWindow *winPtr; /* Window to which command is sent. */ +{ + if ((winPtr->classProcsPtr != NULL) + && (winPtr->classProcsPtr->geometryProc != NULL)) { + (*winPtr->classProcsPtr->geometryProc)(winPtr->instanceData); + } + for (winPtr = winPtr->childList; winPtr != NULL; winPtr = winPtr->nextPtr) { + RecomputeWidgets(winPtr); + } +} + +/* + *--------------------------------------------------------------------------- + * + * TkCreateNamedFont -- + * + * Create the specified named font with the given attributes in the + * named font table associated with the interp. + * + * Results: + * Returns TCL_OK if the font was successfully created, or TCL_ERROR + * if the named font already existed. If TCL_ERROR is returned, an + * error message is left in interp->result. + * + * Side effects: + * Assume there used to exist a named font by the specified name, and + * that the named font had been deleted, but there were still some + * widgets using the named font at the time it was deleted. If a + * new named font is created with the same name, all those widgets + * that were using the old named font will be redisplayed using + * the new named font's attributes. + * + *--------------------------------------------------------------------------- + */ + +int +TkCreateNamedFont(interp, tkwin, name, faPtr) + Tcl_Interp *interp; /* Interp for error return. */ + Tk_Window tkwin; /* A window associated with interp. */ + CONST char *name; /* Name for the new named font. */ + TkFontAttributes *faPtr; /* Attributes for the new named font. */ +{ + TkFontInfo *fiPtr; + Tcl_HashEntry *namedHashPtr; + int new; + NamedFont *nfPtr; + + fiPtr = ((TkWindow *) tkwin)->mainPtr->fontInfoPtr; + + name = Tk_GetUid(name); + namedHashPtr = Tcl_CreateHashEntry(&fiPtr->namedTable, name, &new); + + if (new == 0) { + nfPtr = (NamedFont *) Tcl_GetHashValue(namedHashPtr); + if (nfPtr->deletePending == 0) { + interp->result[0] = '\0'; + Tcl_AppendResult(interp, "font \"", name, + "\" already exists", (char *) NULL); + return TCL_ERROR; + } + + /* + * Recreating a named font with the same name as a previous + * named font. Some widgets were still using that named + * font, so they need to get redisplayed. + */ + + nfPtr->fa = *faPtr; + nfPtr->deletePending = 0; + UpdateDependantFonts(fiPtr, tkwin, namedHashPtr); + return TCL_OK; + } + + nfPtr = (NamedFont *) ckalloc(sizeof(NamedFont)); + nfPtr->deletePending = 0; + Tcl_SetHashValue(namedHashPtr, nfPtr); + nfPtr->fa = *faPtr; + nfPtr->refCount = 0; + nfPtr->deletePending = 0; + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_GetFont -- + * + * Given a string description of a font, map the description to a + * corresponding Tk_Font that represents the font. + * + * Results: + * The return value is token for the font, or NULL if an error + * prevented the font from being created. If NULL is returned, an + * error message will be left in interp->result. + * + * Side effects: + * Calls Tk_GetFontFromObj(), which modifies interp's result object, + * then copies the string from the result object into interp->result. + * This procedure will go away when Tk_ConfigureWidget() is + * made into an object command. + * + *--------------------------------------------------------------------------- + */ + +Tk_Font +Tk_GetFont(interp, tkwin, string) + Tcl_Interp *interp; /* Interp for database and error return. */ + Tk_Window tkwin; /* For display on which font will be used. */ + CONST char *string; /* String describing font, as: named font, + * native format, or parseable string. */ +{ + Tcl_Obj *strPtr; + Tk_Font tkfont; + + strPtr = Tcl_NewStringObj((char *) string, -1); + + tkfont = Tk_GetFontFromObj(interp, tkwin, strPtr); + if (tkfont == NULL) { + Tcl_SetResult(interp, + Tcl_GetStringFromObj(Tcl_GetObjResult(interp), NULL), + TCL_VOLATILE); + } + + Tcl_DecrRefCount(strPtr); /* done with object */ + return tkfont; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_GetFontFromObj -- + * + * Given a string description of a font, map the description to a + * corresponding Tk_Font that represents the font. + * + * Results: + * The return value is token for the font, or NULL if an error + * prevented the font from being created. If NULL is returned, an + * error message will be left in interp's result object. + * + * Side effects: + * The font is added to an internal database with a reference + * count. For each call to this procedure, there should eventually + * be a call to Tk_FreeFont() so that the database is cleaned up when + * fonts aren't in use anymore. + * + *--------------------------------------------------------------------------- + */ + +Tk_Font +Tk_GetFontFromObj(interp, tkwin, objPtr) + Tcl_Interp *interp; /* Interp for database and error return. */ + Tk_Window tkwin; /* For display on which font will be used. */ + Tcl_Obj *objPtr; /* Object describing font, as: named font, + * native format, or parseable string. */ +{ + TkFontInfo *fiPtr; + CachedFontKey key; + Tcl_HashEntry *cacheHashPtr, *namedHashPtr; + TkFont *fontPtr; + int new, descent; + NamedFont *nfPtr; + char *string; + + fiPtr = ((TkWindow *) tkwin)->mainPtr->fontInfoPtr; + string = Tcl_GetStringFromObj(objPtr, NULL); + + key.display = Tk_Display(tkwin); + key.string = Tk_GetUid(string); + cacheHashPtr = Tcl_CreateHashEntry(&fiPtr->fontCache, (char *) &key, &new); + + if (new == 0) { + /* + * We have already constructed a font with this description for + * this display. Bump the reference count of the cached font. + */ + + fontPtr = (TkFont *) Tcl_GetHashValue(cacheHashPtr); + fontPtr->refCount++; + return (Tk_Font) fontPtr; + } + + namedHashPtr = Tcl_FindHashEntry(&fiPtr->namedTable, key.string); + if (namedHashPtr != NULL) { + /* + * Construct a font based on a named font. + */ + + nfPtr = (NamedFont *) Tcl_GetHashValue(namedHashPtr); + nfPtr->refCount++; + + fontPtr = TkpGetFontFromAttributes(NULL, tkwin, &nfPtr->fa); + } else { + /* + * Native font? + */ + + fontPtr = TkpGetNativeFont(tkwin, string); + if (fontPtr == NULL) { + TkFontAttributes fa; + + TkInitFontAttributes(&fa); + if (ParseFontNameObj(interp, tkwin, objPtr, &fa) != TCL_OK) { + Tcl_DeleteHashEntry(cacheHashPtr); + return NULL; + } + + /* + * String contained the attributes inline. + */ + + fontPtr = TkpGetFontFromAttributes(NULL, tkwin, &fa); + } + } + Tcl_SetHashValue(cacheHashPtr, fontPtr); + + fontPtr->refCount = 1; + fontPtr->cacheHashPtr = cacheHashPtr; + fontPtr->namedHashPtr = namedHashPtr; + + Tk_MeasureChars((Tk_Font) fontPtr, "0", 1, 0, 0, &fontPtr->tabWidth); + if (fontPtr->tabWidth == 0) { + fontPtr->tabWidth = fontPtr->fm.maxWidth; + } + fontPtr->tabWidth *= 8; + + /* + * Make sure the tab width isn't zero (some fonts may not have enough + * information to set a reasonable tab width). + */ + + if (fontPtr->tabWidth == 0) { + fontPtr->tabWidth = 1; + } + + /* + * Get information used for drawing underlines in generic code on a + * non-underlined font. + */ + + descent = fontPtr->fm.descent; + fontPtr->underlinePos = descent / 2; + fontPtr->underlineHeight = fontPtr->fa.pointsize / 10; + if (fontPtr->underlineHeight == 0) { + fontPtr->underlineHeight = 1; + } + if (fontPtr->underlinePos + fontPtr->underlineHeight > descent) { + /* + * If this set of values would cause the bottom of the underline + * bar to stick below the descent of the font, jack the underline + * up a bit higher. + */ + + fontPtr->underlineHeight = descent - fontPtr->underlinePos; + if (fontPtr->underlineHeight == 0) { + fontPtr->underlinePos--; + fontPtr->underlineHeight = 1; + } + } + + return (Tk_Font) fontPtr; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_NameOfFont -- + * + * Given a font, return a textual string identifying it. + * + * Results: + * The return value is the description that was passed to + * Tk_GetFont() to create the font. The storage for the returned + * string is only guaranteed to persist until the font is deleted. + * The caller should not modify this string. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +char * +Tk_NameOfFont(tkfont) + Tk_Font tkfont; /* Font whose name is desired. */ +{ + TkFont *fontPtr; + Tcl_HashEntry *hPtr; + CachedFontKey *keyPtr; + + fontPtr = (TkFont *) tkfont; + hPtr = fontPtr->cacheHashPtr; + + keyPtr = (CachedFontKey *) Tcl_GetHashKey(hPtr->tablePtr, hPtr); + return (char *) keyPtr->string; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_FreeFont -- + * + * Called to release a font allocated by Tk_GetFont(). + * + * Results: + * None. + * + * Side effects: + * The reference count associated with font is decremented, and + * only deallocated when no one is using it. + * + *--------------------------------------------------------------------------- + */ + +void +Tk_FreeFont(tkfont) + Tk_Font tkfont; /* Font to be released. */ +{ + TkFont *fontPtr; + NamedFont *nfPtr; + + if (tkfont == NULL) { + return; + } + fontPtr = (TkFont *) tkfont; + fontPtr->refCount--; + if (fontPtr->refCount == 0) { + if (fontPtr->namedHashPtr != NULL) { + /* + * The font is being deleted. Determine if the associated named + * font definition should and/or can be deleted too. + */ + + nfPtr = (NamedFont *) Tcl_GetHashValue(fontPtr->namedHashPtr); + nfPtr->refCount--; + if ((nfPtr->refCount == 0) && (nfPtr->deletePending != 0)) { + Tcl_DeleteHashEntry(fontPtr->namedHashPtr); + ckfree((char *) nfPtr); + } + } + Tcl_DeleteHashEntry(fontPtr->cacheHashPtr); + TkpDeleteFont(fontPtr); + } +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_FontId -- + * + * Given a font, return an opaque handle that should be selected + * into the XGCValues structure in order to get the constructed + * gc to use this font. This procedure would go away if the + * XGCValues structure were replaced with a TkGCValues structure. + * + * Results: + * As above. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +Font +Tk_FontId(tkfont) + Tk_Font tkfont; /* Font that is going to be selected into GC. */ +{ + TkFont *fontPtr; + + fontPtr = (TkFont *) tkfont; + return fontPtr->fid; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_GetFontMetrics -- + * + * Returns overall ascent and descent metrics for the given font. + * These values can be used to space multiple lines of text and + * to align the baselines of text in different fonts. + * + * Results: + * If *heightPtr is non-NULL, it is filled with the overall height + * of the font, which is the sum of the ascent and descent. + * If *ascentPtr or *descentPtr is non-NULL, they are filled with + * the ascent and/or descent information for the font. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ +void +Tk_GetFontMetrics(tkfont, fmPtr) + Tk_Font tkfont; /* Font in which metrics are calculated. */ + Tk_FontMetrics *fmPtr; /* Pointer to structure in which font + * metrics for tkfont will be stored. */ +{ + TkFont *fontPtr; + + fontPtr = (TkFont *) tkfont; + fmPtr->ascent = fontPtr->fm.ascent; + fmPtr->descent = fontPtr->fm.descent; + fmPtr->linespace = fontPtr->fm.ascent + fontPtr->fm.descent; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_PostscriptFontName -- + * + * Given a Tk_Font, return the name of the corresponding Postscript + * font. + * + * Results: + * The return value is the pointsize of the given Tk_Font. + * The name of the Postscript font is appended to dsPtr. + * + * Side effects: + * If the font does not exist on the printer, the print job will + * fail at print time. Given a "reasonable" Postscript printer, + * the following Tk_Font font families should print correctly: + * + * Avant Garde, Arial, Bookman, Courier, Courier New, Geneva, + * Helvetica, Monaco, New Century Schoolbook, New York, + * Palatino, Symbol, Times, Times New Roman, Zapf Chancery, + * and Zapf Dingbats. + * + * Any other Tk_Font font families may not print correctly + * because the computed Postscript font name may be incorrect. + * + *--------------------------------------------------------------------------- + */ + + +int +Tk_PostscriptFontName(tkfont, dsPtr) + Tk_Font tkfont; /* Font in which text will be printed. */ + Tcl_DString *dsPtr; /* Pointer to an initialized Tcl_DString to + * which the name of the Postscript font that + * corresponds to tkfont will be appended. */ +{ + TkFont *fontPtr; + char *family, *weightString, *slantString; + char *src, *dest; + int upper, len; + + len = Tcl_DStringLength(dsPtr); + fontPtr = (TkFont *) tkfont; + + /* + * Convert the case-insensitive Tk_Font family name to the + * case-sensitive Postscript family name. Take out any spaces and + * capitalize the first letter of each word. + */ + + family = fontPtr->fa.family; + if (strncasecmp(family, "itc ", 4) == 0) { + family = family + 4; + } + if ((strcasecmp(family, "Arial") == 0) + || (strcasecmp(family, "Geneva") == 0)) { + family = "Helvetica"; + } else if ((strcasecmp(family, "Times New Roman") == 0) + || (strcasecmp(family, "New York") == 0)) { + family = "Times"; + } else if ((strcasecmp(family, "Courier New") == 0) + || (strcasecmp(family, "Monaco") == 0)) { + family = "Courier"; + } else if (strcasecmp(family, "AvantGarde") == 0) { + family = "AvantGarde"; + } else if (strcasecmp(family, "ZapfChancery") == 0) { + family = "ZapfChancery"; + } else if (strcasecmp(family, "ZapfDingbats") == 0) { + family = "ZapfDingbats"; + } else { + /* + * Inline, capitalize the first letter of each word, lowercase the + * rest of the letters in each word, and then take out the spaces + * between the words. This may make the DString shorter, which is + * safe to do. + */ + + Tcl_DStringAppend(dsPtr, family, -1); + + src = dest = Tcl_DStringValue(dsPtr) + len; + upper = 1; + for (; *src != '\0'; src++, dest++) { + while (isspace(UCHAR(*src))) { + src++; + upper = 1; + } + *dest = *src; + if ((upper != 0) && (islower(UCHAR(*src)))) { + *dest = toupper(UCHAR(*src)); + } + upper = 0; + } + *dest = '\0'; + Tcl_DStringSetLength(dsPtr, dest - Tcl_DStringValue(dsPtr)); + family = Tcl_DStringValue(dsPtr) + len; + } + if (family != Tcl_DStringValue(dsPtr) + len) { + Tcl_DStringAppend(dsPtr, family, -1); + family = Tcl_DStringValue(dsPtr) + len; + } + + if (strcasecmp(family, "NewCenturySchoolbook") == 0) { + Tcl_DStringSetLength(dsPtr, len); + Tcl_DStringAppend(dsPtr, "NewCenturySchlbk", -1); + family = Tcl_DStringValue(dsPtr) + len; + } + + /* + * Get the string to use for the weight. + */ + + weightString = NULL; + if (fontPtr->fa.weight == TK_FW_NORMAL) { + if (strcmp(family, "Bookman") == 0) { + weightString = "Light"; + } else if (strcmp(family, "AvantGarde") == 0) { + weightString = "Book"; + } else if (strcmp(family, "ZapfChancery") == 0) { + weightString = "Medium"; + } + } else { + if ((strcmp(family, "Bookman") == 0) + || (strcmp(family, "AvantGarde") == 0)) { + weightString = "Demi"; + } else { + weightString = "Bold"; + } + } + + /* + * Get the string to use for the slant. + */ + + slantString = NULL; + if (fontPtr->fa.slant == TK_FS_ROMAN) { + ; + } else { + if ((strcmp(family, "Helvetica") == 0) + || (strcmp(family, "Courier") == 0) + || (strcmp(family, "AvantGarde") == 0)) { + slantString = "Oblique"; + } else { + slantString = "Italic"; + } + } + + /* + * The string "Roman" needs to be added to some fonts that are not bold + * and not italic. + */ + + if ((slantString == NULL) && (weightString == NULL)) { + if ((strcmp(family, "Times") == 0) + || (strcmp(family, "NewCenturySchlbk") == 0) + || (strcmp(family, "Palatino") == 0)) { + Tcl_DStringAppend(dsPtr, "-Roman", -1); + } + } else { + Tcl_DStringAppend(dsPtr, "-", -1); + if (weightString != NULL) { + Tcl_DStringAppend(dsPtr, weightString, -1); + } + if (slantString != NULL) { + Tcl_DStringAppend(dsPtr, slantString, -1); + } + } + + return fontPtr->fa.pointsize; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_TextWidth -- + * + * A wrapper function for the more complicated interface of + * Tk_MeasureChars. Computes how much space the given + * simple string needs. + * + * Results: + * The return value is the width (in pixels) of the given string. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +int +Tk_TextWidth(tkfont, string, numChars) + Tk_Font tkfont; /* Font in which text will be measured. */ + CONST char *string; /* String whose width will be computed. */ + int numChars; /* Number of characters to consider from + * string, or < 0 for strlen(). */ +{ + int width; + + if (numChars < 0) { + numChars = strlen(string); + } + Tk_MeasureChars(tkfont, string, numChars, 0, 0, &width); + return width; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_UnderlineChars -- + * + * This procedure draws an underline for a given range of characters + * in a given string. It doesn't draw the characters (which are + * assumed to have been displayed previously); it just draws the + * underline. This procedure would mainly be used to quickly + * underline a few characters without having to construct an + * underlined font. To produce properly underlined text, the + * appropriate underlined font should be constructed and used. + * + * Results: + * None. + * + * Side effects: + * Information gets displayed in "drawable". + * + *---------------------------------------------------------------------- + */ + +void +Tk_UnderlineChars(display, drawable, gc, tkfont, string, x, y, firstChar, + lastChar) + Display *display; /* Display on which to draw. */ + Drawable drawable; /* Window or pixmap in which to draw. */ + GC gc; /* Graphics context for actually drawing + * line. */ + Tk_Font tkfont; /* Font used in GC; must have been allocated + * by Tk_GetFont(). Used for character + * dimensions, etc. */ + CONST char *string; /* String containing characters to be + * underlined or overstruck. */ + int x, y; /* Coordinates at which first character of + * string is drawn. */ + int firstChar; /* Index of first character. */ + int lastChar; /* Index of one after the last character. */ +{ + TkFont *fontPtr; + int startX, endX; + + fontPtr = (TkFont *) tkfont; + + Tk_MeasureChars(tkfont, string, firstChar, 0, 0, &startX); + Tk_MeasureChars(tkfont, string, lastChar, 0, 0, &endX); + + XFillRectangle(display, drawable, gc, x + startX, + y + fontPtr->underlinePos, (unsigned int) (endX - startX), + (unsigned int) fontPtr->underlineHeight); +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_ComputeTextLayout -- + * + * Computes the amount of screen space needed to display a + * multi-line, justified string of text. Records all the + * measurements that were done to determine to size and + * positioning of the individual lines of text; this information + * can be used by the Tk_DrawTextLayout() procedure to + * display the text quickly (without remeasuring it). + * + * This procedure is useful for simple widgets that want to + * display single-font, multi-line text and want Tk to handle the + * details. + * + * Results: + * The return value is a Tk_TextLayout token that holds the + * measurement information for the given string. The token is + * only valid for the given string. If the string is freed, + * the token is no longer valid and must also be freed. To free + * the token, call Tk_FreeTextLayout(). + * + * The dimensions of the screen area needed to display the text + * are stored in *widthPtr and *heightPtr. + * + * Side effects: + * Memory is allocated to hold the measurement information. + * + *--------------------------------------------------------------------------- + */ + +Tk_TextLayout +Tk_ComputeTextLayout(tkfont, string, numChars, wrapLength, justify, flags, + widthPtr, heightPtr) + Tk_Font tkfont; /* Font that will be used to display text. */ + CONST char *string; /* String whose dimensions are to be + * computed. */ + int numChars; /* Number of characters to consider from + * string, or < 0 for strlen(). */ + int wrapLength; /* Longest permissible line length, in + * pixels. <= 0 means no automatic wrapping: + * just let lines get as long as needed. */ + Tk_Justify justify; /* How to justify lines. */ + int flags; /* Flag bits OR-ed together. + * TK_IGNORE_TABS means that tab characters + * should not be expanded. TK_IGNORE_NEWLINES + * means that newline characters should not + * cause a line break. */ + int *widthPtr; /* Filled with width of string. */ + int *heightPtr; /* Filled with height of string. */ +{ + TkFont *fontPtr; + CONST char *start, *end, *special; + int n, y, charsThisChunk, maxChunks; + int baseline, height, curX, newX, maxWidth; + TextLayout *layoutPtr; + LayoutChunk *chunkPtr; + CONST TkFontMetrics *fmPtr; +#define MAX_LINES 50 + int staticLineLengths[MAX_LINES]; + int *lineLengths; + int maxLines, curLine, layoutHeight; + + lineLengths = staticLineLengths; + maxLines = MAX_LINES; + + fontPtr = (TkFont *) tkfont; + fmPtr = &fontPtr->fm; + + height = fmPtr->ascent + fmPtr->descent; + + if (numChars < 0) { + numChars = strlen(string); + } + + maxChunks = 1; + + layoutPtr = (TextLayout *) ckalloc(sizeof(TextLayout) + + (maxChunks - 1) * sizeof(LayoutChunk)); + layoutPtr->tkfont = tkfont; + layoutPtr->string = string; + layoutPtr->numChunks = 0; + + baseline = fmPtr->ascent; + maxWidth = 0; + + /* + * Divide the string up into simple strings and measure each string. + */ + + curX = 0; + + end = string + numChars; + special = string; + + flags &= TK_IGNORE_TABS | TK_IGNORE_NEWLINES; + flags |= TK_WHOLE_WORDS | TK_AT_LEAST_ONE; + curLine = 0; + for (start = string; start < end; ) { + if (start >= special) { + /* + * Find the next special character in the string. + */ + + for (special = start; special < end; special++) { + if (!(flags & TK_IGNORE_NEWLINES)) { + if ((*special == '\n') || (*special == '\r')) { + break; + } + } + if (!(flags & TK_IGNORE_TABS)) { + if (*special == '\t') { + break; + } + } + } + } + + /* + * Special points at the next special character (or the end of the + * string). Process characters between start and special. + */ + + chunkPtr = NULL; + if (start < special) { + charsThisChunk = Tk_MeasureChars(tkfont, start, special - start, + wrapLength - curX, flags, &newX); + newX += curX; + flags &= ~TK_AT_LEAST_ONE; + if (charsThisChunk > 0) { + chunkPtr = NewChunk(&layoutPtr, &maxChunks, start, + charsThisChunk, curX, newX, baseline); + + start += charsThisChunk; + curX = newX; + } + } + + if ((start == special) && (special < end)) { + /* + * Handle the special character. + */ + + chunkPtr = NULL; + if (*special == '\t') { + newX = curX + fontPtr->tabWidth; + newX -= newX % fontPtr->tabWidth; + NewChunk(&layoutPtr, &maxChunks, start, 1, curX, newX, + baseline)->numDisplayChars = -1; + start++; + if ((start < end) && + ((wrapLength <= 0) || (newX <= wrapLength))) { + /* + * More chars can still fit on this line. + */ + + curX = newX; + flags &= ~TK_AT_LEAST_ONE; + continue; + } + } else { + NewChunk(&layoutPtr, &maxChunks, start, 1, curX, 1000000000, + baseline)->numDisplayChars = -1; + start++; + goto wrapLine; + } + } + + /* + * No more characters are going to go on this line, either because + * no more characters can fit or there are no more characters left. + * Consume all extra spaces at end of line. + */ + + while ((start < end) && isspace(UCHAR(*start))) { + if (!(flags & TK_IGNORE_NEWLINES)) { + if ((*start == '\n') || (*start == '\r')) { + break; + } + } + if (!(flags & TK_IGNORE_TABS)) { + if (*start == '\t') { + break; + } + } + start++; + } + if (chunkPtr != NULL) { + /* + * Append all the extra spaces on this line to the end of the + * last text chunk. + */ + charsThisChunk = start - (chunkPtr->start + chunkPtr->numChars); + if (charsThisChunk > 0) { + chunkPtr->numChars += Tk_MeasureChars(tkfont, + chunkPtr->start + chunkPtr->numChars, charsThisChunk, + 0, 0, &chunkPtr->totalWidth); + chunkPtr->totalWidth += curX; + } + } + + wrapLine: + flags |= TK_AT_LEAST_ONE; + + /* + * Save current line length, then move current position to start of + * next line. + */ + + if (curX > maxWidth) { + maxWidth = curX; + } + + /* + * Remember width of this line, so that all chunks on this line + * can be centered or right justified, if necessary. + */ + + if (curLine >= maxLines) { + int *newLengths; + + newLengths = (int *) ckalloc(2 * maxLines * sizeof(int)); + memcpy((void *) newLengths, lineLengths, maxLines * sizeof(int)); + if (lineLengths != staticLineLengths) { + ckfree((char *) lineLengths); + } + lineLengths = newLengths; + maxLines *= 2; + } + lineLengths[curLine] = curX; + curLine++; + + curX = 0; + baseline += height; + } + + /* + * If last line ends with a newline, then we need to make a 0 width + * chunk on the next line. Otherwise "Hello" and "Hello\n" are the + * same height. + */ + + if ((layoutPtr->numChunks > 0) && ((flags & TK_IGNORE_NEWLINES) == 0)) { + if (layoutPtr->chunks[layoutPtr->numChunks - 1].start[0] == '\n') { + chunkPtr = NewChunk(&layoutPtr, &maxChunks, start, 0, curX, + 1000000000, baseline); + chunkPtr->numDisplayChars = -1; + baseline += height; + } + } + + /* + * Using maximum line length, shift all the chunks so that the lines are + * all justified correctly. + */ + + curLine = 0; + chunkPtr = layoutPtr->chunks; + y = chunkPtr->y; + for (n = 0; n < layoutPtr->numChunks; n++) { + int extra; + + if (chunkPtr->y != y) { + curLine++; + y = chunkPtr->y; + } + extra = maxWidth - lineLengths[curLine]; + if (justify == TK_JUSTIFY_CENTER) { + chunkPtr->x += extra / 2; + } else if (justify == TK_JUSTIFY_RIGHT) { + chunkPtr->x += extra; + } + chunkPtr++; + } + + layoutPtr->width = maxWidth; + layoutHeight = baseline - fmPtr->ascent; + if (layoutPtr->numChunks == 0) { + layoutHeight = height; + + /* + * This fake chunk is used by the other procedures so that they can + * pretend that there is a chunk with no chars in it, which makes + * the coding simpler. + */ + + layoutPtr->numChunks = 1; + layoutPtr->chunks[0].start = string; + layoutPtr->chunks[0].numChars = 0; + layoutPtr->chunks[0].numDisplayChars = -1; + layoutPtr->chunks[0].x = 0; + layoutPtr->chunks[0].y = fmPtr->ascent; + layoutPtr->chunks[0].totalWidth = 0; + layoutPtr->chunks[0].displayWidth = 0; + } + + if (widthPtr != NULL) { + *widthPtr = layoutPtr->width; + } + if (heightPtr != NULL) { + *heightPtr = layoutHeight; + } + if (lineLengths != staticLineLengths) { + ckfree((char *) lineLengths); + } + + return (Tk_TextLayout) layoutPtr; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_FreeTextLayout -- + * + * This procedure is called to release the storage associated with + * a Tk_TextLayout when it is no longer needed. + * + * Results: + * None. + * + * Side effects: + * Memory is freed. + * + *--------------------------------------------------------------------------- + */ + +void +Tk_FreeTextLayout(textLayout) + Tk_TextLayout textLayout; /* The text layout to be released. */ +{ + TextLayout *layoutPtr; + + layoutPtr = (TextLayout *) textLayout; + if (layoutPtr != NULL) { + ckfree((char *) layoutPtr); + } +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_DrawTextLayout -- + * + * Use the information in the Tk_TextLayout token to display a + * multi-line, justified string of text. + * + * This procedure is useful for simple widgets that need to + * display single-font, multi-line text and want Tk to handle + * the details. + * + * Results: + * None. + * + * Side effects: + * Text drawn on the screen. + * + *--------------------------------------------------------------------------- + */ + +void +Tk_DrawTextLayout(display, drawable, gc, layout, x, y, firstChar, lastChar) + Display *display; /* Display on which to draw. */ + Drawable drawable; /* Window or pixmap in which to draw. */ + GC gc; /* Graphics context to use for drawing text. */ + Tk_TextLayout layout; /* Layout information, from a previous call + * to Tk_ComputeTextLayout(). */ + int x, y; /* Upper-left hand corner of rectangle in + * which to draw (pixels). */ + int firstChar; /* The index of the first character to draw + * from the given text item. 0 specfies the + * beginning. */ + int lastChar; /* The index just after the last character + * to draw from the given text item. A number + * < 0 means to draw all characters. */ +{ + TextLayout *layoutPtr; + int i, numDisplayChars, drawX; + LayoutChunk *chunkPtr; + + layoutPtr = (TextLayout *) layout; + if (layoutPtr == NULL) { + return; + } + + if (lastChar < 0) { + lastChar = 100000000; + } + chunkPtr = layoutPtr->chunks; + for (i = 0; i < layoutPtr->numChunks; i++) { + numDisplayChars = chunkPtr->numDisplayChars; + if ((numDisplayChars > 0) && (firstChar < numDisplayChars)) { + if (firstChar <= 0) { + drawX = 0; + firstChar = 0; + } else { + Tk_MeasureChars(layoutPtr->tkfont, chunkPtr->start, firstChar, + 0, 0, &drawX); + } + if (lastChar < numDisplayChars) { + numDisplayChars = lastChar; + } + Tk_DrawChars(display, drawable, gc, layoutPtr->tkfont, + chunkPtr->start + firstChar, numDisplayChars - firstChar, + x + chunkPtr->x + drawX, y + chunkPtr->y); + } + firstChar -= chunkPtr->numChars; + lastChar -= chunkPtr->numChars; + if (lastChar <= 0) { + break; + } + chunkPtr++; + } +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_UnderlineTextLayout -- + * + * Use the information in the Tk_TextLayout token to display an + * underline below an individual character. This procedure does + * not draw the text, just the underline. + * + * This procedure is useful for simple widgets that need to + * display single-font, multi-line text with an individual + * character underlined and want Tk to handle the details. + * To display larger amounts of underlined text, construct + * and use an underlined font. + * + * Results: + * None. + * + * Side effects: + * Underline drawn on the screen. + * + *--------------------------------------------------------------------------- + */ + +void +Tk_UnderlineTextLayout(display, drawable, gc, layout, x, y, underline) + Display *display; /* Display on which to draw. */ + Drawable drawable; /* Window or pixmap in which to draw. */ + GC gc; /* Graphics context to use for drawing text. */ + Tk_TextLayout layout; /* Layout information, from a previous call + * to Tk_ComputeTextLayout(). */ + int x, y; /* Upper-left hand corner of rectangle in + * which to draw (pixels). */ + int underline; /* Index of the single character to + * underline, or -1 for no underline. */ +{ + TextLayout *layoutPtr; + TkFont *fontPtr; + int xx, yy, width, height; + + if ((Tk_CharBbox(layout, underline, &xx, &yy, &width, &height) != 0) + && (width != 0)) { + layoutPtr = (TextLayout *) layout; + fontPtr = (TkFont *) layoutPtr->tkfont; + + XFillRectangle(display, drawable, gc, x + xx, + y + yy + fontPtr->fm.ascent + fontPtr->underlinePos, + (unsigned int) width, (unsigned int) fontPtr->underlineHeight); + } +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_PointToChar -- + * + * Use the information in the Tk_TextLayout token to determine the + * character closest to the given point. The point must be + * specified with respect to the upper-left hand corner of the + * text layout, which is considered to be located at (0, 0). + * + * Any point whose y-value is less that 0 will be considered closest + * to the first character in the text layout; any point whose y-value + * is greater than the height of the text layout will be considered + * closest to the last character in the text layout. + * + * Any point whose x-value is less than 0 will be considered closest + * to the first character on that line; any point whose x-value is + * greater than the width of the text layout will be considered + * closest to the last character on that line. + * + * Results: + * The return value is the index of the character that was + * closest to the point. Given a text layout with no characters, + * the value 0 will always be returned, referring to a hypothetical + * zero-width placeholder character. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +int +Tk_PointToChar(layout, x, y) + Tk_TextLayout layout; /* Layout information, from a previous call + * to Tk_ComputeTextLayout(). */ + int x, y; /* Coordinates of point to check, with + * respect to the upper-left corner of the + * text layout. */ +{ + TextLayout *layoutPtr; + LayoutChunk *chunkPtr, *lastPtr; + TkFont *fontPtr; + int i, n, dummy, baseline, pos; + + if (y < 0) { + /* + * Point lies above any line in this layout. Return the index of + * the first char. + */ + + return 0; + } + + /* + * Find which line contains the point. + */ + + layoutPtr = (TextLayout *) layout; + fontPtr = (TkFont *) layoutPtr->tkfont; + lastPtr = chunkPtr = layoutPtr->chunks; + for (i = 0; i < layoutPtr->numChunks; i++) { + baseline = chunkPtr->y; + if (y < baseline + fontPtr->fm.descent) { + if (x < chunkPtr->x) { + /* + * Point is to the left of all chunks on this line. Return + * the index of the first character on this line. + */ + + return chunkPtr->start - layoutPtr->string; + } + if (x >= layoutPtr->width) { + /* + * If point lies off right side of the text layout, return + * the last char in the last chunk on this line. Without + * this, it might return the index of the first char that + * was located outside of the text layout. + */ + + x = INT_MAX; + } + + /* + * Examine all chunks on this line to see which one contains + * the specified point. + */ + + lastPtr = chunkPtr; + while ((i < layoutPtr->numChunks) && (chunkPtr->y == baseline)) { + if (x < chunkPtr->x + chunkPtr->totalWidth) { + /* + * Point falls on one of the characters in this chunk. + */ + + if (chunkPtr->numDisplayChars < 0) { + /* + * This is a special chunk that encapsulates a single + * tab or newline char. + */ + + return chunkPtr->start - layoutPtr->string; + } + n = Tk_MeasureChars((Tk_Font) fontPtr, chunkPtr->start, + chunkPtr->numChars, x + 1 - chunkPtr->x, + TK_PARTIAL_OK, &dummy); + return (chunkPtr->start + n - 1) - layoutPtr->string; + } + lastPtr = chunkPtr; + chunkPtr++; + i++; + } + + /* + * Point is to the right of all chars in all the chunks on this + * line. Return the index just past the last char in the last + * chunk on this line. + */ + + pos = (lastPtr->start + lastPtr->numChars) - layoutPtr->string; + if (i < layoutPtr->numChunks) { + pos--; + } + return pos; + } + lastPtr = chunkPtr; + chunkPtr++; + } + + /* + * Point lies below any line in this text layout. Return the index + * just past the last char. + */ + + return (lastPtr->start + lastPtr->numChars) - layoutPtr->string; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_CharBbox -- + * + * Use the information in the Tk_TextLayout token to return the + * bounding box for the character specified by index. + * + * The width of the bounding box is the advance width of the + * character, and does not include and left- or right-bearing. + * Any character that extends partially outside of the + * text layout is considered to be truncated at the edge. Any + * character which is located completely outside of the text + * layout is considered to be zero-width and pegged against + * the edge. + * + * The height of the bounding box is the line height for this font, + * extending from the top of the ascent to the bottom of the + * descent. Information about the actual height of the individual + * letter is not available. + * + * A text layout that contains no characters is considered to + * contain a single zero-width placeholder character. + * + * Results: + * The return value is 0 if the index did not specify a character + * in the text layout, or non-zero otherwise. In that case, + * *bbox is filled with the bounding box of the character. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +int +Tk_CharBbox(layout, index, xPtr, yPtr, widthPtr, heightPtr) + Tk_TextLayout layout; /* Layout information, from a previous call to + * Tk_ComputeTextLayout(). */ + int index; /* The index of the character whose bbox is + * desired. */ + int *xPtr, *yPtr; /* Filled with the upper-left hand corner, in + * pixels, of the bounding box for the character + * specified by index, if non-NULL. */ + int *widthPtr, *heightPtr; + /* Filled with the width and height of the + * bounding box for the character specified by + * index, if non-NULL. */ +{ + TextLayout *layoutPtr; + LayoutChunk *chunkPtr; + int i, x, w; + Tk_Font tkfont; + TkFont *fontPtr; + + if (index < 0) { + return 0; + } + + layoutPtr = (TextLayout *) layout; + chunkPtr = layoutPtr->chunks; + tkfont = layoutPtr->tkfont; + fontPtr = (TkFont *) tkfont; + + for (i = 0; i < layoutPtr->numChunks; i++) { + if (chunkPtr->numDisplayChars < 0) { + if (index == 0) { + x = chunkPtr->x; + w = chunkPtr->totalWidth; + goto check; + } + } else if (index < chunkPtr->numChars) { + if (xPtr != NULL) { + Tk_MeasureChars(tkfont, chunkPtr->start, index, 0, 0, &x); + x += chunkPtr->x; + } + if (widthPtr != NULL) { + Tk_MeasureChars(tkfont, chunkPtr->start + index, 1, 0, 0, &w); + } + goto check; + } + index -= chunkPtr->numChars; + chunkPtr++; + } + if (index == 0) { + /* + * Special case to get location just past last char in layout. + */ + + chunkPtr--; + x = chunkPtr->x + chunkPtr->totalWidth; + w = 0; + } else { + return 0; + } + + /* + * Ensure that the bbox lies within the text layout. This forces all + * chars that extend off the right edge of the text layout to have + * truncated widths, and all chars that are completely off the right + * edge of the text layout to peg to the edge and have 0 width. + */ + check: + if (yPtr != NULL) { + *yPtr = chunkPtr->y - fontPtr->fm.ascent; + } + if (heightPtr != NULL) { + *heightPtr = fontPtr->fm.ascent + fontPtr->fm.descent; + } + + if (x > layoutPtr->width) { + x = layoutPtr->width; + } + if (xPtr != NULL) { + *xPtr = x; + } + if (widthPtr != NULL) { + if (x + w > layoutPtr->width) { + w = layoutPtr->width - x; + } + *widthPtr = w; + } + + return 1; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_DistanceToTextLayout -- + * + * Computes the distance in pixels from the given point to the + * given text layout. Non-displaying space characters that occur + * at the end of individual lines in the text layout are ignored + * for hit detection purposes. + * + * Results: + * The return value is 0 if the point (x, y) is inside the text + * layout. If the point isn't inside the text layout then the + * return value is the distance in pixels from the point to the + * text item. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +int +Tk_DistanceToTextLayout(layout, x, y) + Tk_TextLayout layout; /* Layout information, from a previous call + * to Tk_ComputeTextLayout(). */ + int x, y; /* Coordinates of point to check, with + * respect to the upper-left corner of the + * text layout (in pixels). */ +{ + int i, x1, x2, y1, y2, xDiff, yDiff, dist, minDist, ascent, descent; + LayoutChunk *chunkPtr; + TextLayout *layoutPtr; + TkFont *fontPtr; + + layoutPtr = (TextLayout *) layout; + fontPtr = (TkFont *) layoutPtr->tkfont; + ascent = fontPtr->fm.ascent; + descent = fontPtr->fm.descent; + + minDist = 0; + chunkPtr = layoutPtr->chunks; + for (i = 0; i < layoutPtr->numChunks; i++) { + if (chunkPtr->start[0] == '\n') { + /* + * Newline characters are not counted when computing distance + * (but tab characters would still be considered). + */ + + chunkPtr++; + continue; + } + + x1 = chunkPtr->x; + y1 = chunkPtr->y - ascent; + x2 = chunkPtr->x + chunkPtr->displayWidth; + y2 = chunkPtr->y + descent; + + if (x < x1) { + xDiff = x1 - x; + } else if (x >= x2) { + xDiff = x - x2 + 1; + } else { + xDiff = 0; + } + + if (y < y1) { + yDiff = y1 - y; + } else if (y >= y2) { + yDiff = y - y2 + 1; + } else { + yDiff = 0; + } + if ((xDiff == 0) && (yDiff == 0)) { + return 0; + } + dist = (int) hypot((double) xDiff, (double) yDiff); + if ((dist < minDist) || (minDist == 0)) { + minDist = dist; + } + chunkPtr++; + } + return minDist; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_IntersectTextLayout -- + * + * Determines whether a text layout lies entirely inside, + * entirely outside, or overlaps a given rectangle. Non-displaying + * space characters that occur at the end of individual lines in + * the text layout are ignored for intersection calculations. + * + * Results: + * The return value is -1 if the text layout is entirely outside of + * the rectangle, 0 if it overlaps, and 1 if it is entirely inside + * of the rectangle. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +int +Tk_IntersectTextLayout(layout, x, y, width, height) + Tk_TextLayout layout; /* Layout information, from a previous call + * to Tk_ComputeTextLayout(). */ + int x, y; /* Upper-left hand corner, in pixels, of + * rectangular area to compare with text + * layout. Coordinates are with respect to + * the upper-left hand corner of the text + * layout itself. */ + int width, height; /* The width and height of the above + * rectangular area, in pixels. */ +{ + int result, i, x1, y1, x2, y2; + TextLayout *layoutPtr; + LayoutChunk *chunkPtr; + TkFont *fontPtr; + int left, top, right, bottom; + + /* + * Scan the chunks one at a time, seeing whether each is entirely in, + * entirely out, or overlapping the rectangle. If an overlap is + * detected, return immediately; otherwise wait until all chunks have + * been processed and see if they were all inside or all outside. + */ + + layoutPtr = (TextLayout *) layout; + chunkPtr = layoutPtr->chunks; + fontPtr = (TkFont *) layoutPtr->tkfont; + + left = x; + top = y; + right = x + width; + bottom = y + height; + + result = 0; + for (i = 0; i < layoutPtr->numChunks; i++) { + if (chunkPtr->start[0] == '\n') { + /* + * Newline characters are not counted when computing area + * intersection (but tab characters would still be considered). + */ + + chunkPtr++; + continue; + } + + x1 = chunkPtr->x; + y1 = chunkPtr->y - fontPtr->fm.ascent; + x2 = chunkPtr->x + chunkPtr->displayWidth; + y2 = chunkPtr->y + fontPtr->fm.descent; + + if ((right < x1) || (left >= x2) + || (bottom < y1) || (top >= y2)) { + if (result == 1) { + return 0; + } + result = -1; + } else if ((x1 < left) || (x2 >= right) + || (y1 < top) || (y2 >= bottom)) { + return 0; + } else if (result == -1) { + return 0; + } else { + result = 1; + } + chunkPtr++; + } + return result; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_TextLayoutToPostscript -- + * + * Outputs the contents of a text layout in Postscript format. + * The set of lines in the text layout will be rendered by the user + * supplied Postscript function. The function should be of the form: + * + * justify x y string function -- + * + * Justify is -1, 0, or 1, depending on whether the following string + * should be left, center, or right justified, x and y is the + * location for the origin of the string, string is the sequence + * of characters to be printed, and function is the name of the + * caller-provided function; the function should leave nothing + * on the stack. + * + * The meaning of the origin of the string (x and y) depends on + * the justification. For left justification, x is where the + * left edge of the string should appear. For center justification, + * x is where the center of the string should appear. And for right + * justification, x is where the right edge of the string should + * appear. This behavior is necessary because, for example, right + * justified text on the screen is justified with screen metrics. + * The same string needs to be justified with printer metrics on + * the printer to appear in the correct place with respect to other + * similarly justified strings. In all circumstances, y is the + * location of the baseline for the string. + * + * Results: + * Interp->result is modified to hold the Postscript code that + * will render the text layout. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +void +Tk_TextLayoutToPostscript(interp, layout) + Tcl_Interp *interp; /* Filled with Postscript code. */ + Tk_TextLayout layout; /* The layout to be rendered. */ +{ +#define MAXUSE 128 + char buf[MAXUSE+10]; + LayoutChunk *chunkPtr; + int i, j, used, c, baseline; + TextLayout *layoutPtr; + + layoutPtr = (TextLayout *) layout; + chunkPtr = layoutPtr->chunks; + baseline = chunkPtr->y; + used = 0; + buf[used++] = '('; + for (i = 0; i < layoutPtr->numChunks; i++) { + if (baseline != chunkPtr->y) { + buf[used++] = ')'; + buf[used++] = '\n'; + buf[used++] = '('; + baseline = chunkPtr->y; + } + if (chunkPtr->numDisplayChars <= 0) { + if (chunkPtr->start[0] == '\t') { + buf[used++] = '\\'; + buf[used++] = 't'; + } + } else { + for (j = 0; j < chunkPtr->numDisplayChars; j++) { + c = UCHAR(chunkPtr->start[j]); + if ((c == '(') || (c == ')') || (c == '\\') || (c < 0x20) + || (c >= UCHAR(0x7f))) { + /* + * Tricky point: the "03" is necessary in the sprintf + * below, so that a full three digits of octal are + * always generated. Without the "03", a number + * following this sequence could be interpreted by + * Postscript as part of this sequence. + */ + + sprintf(buf + used, "\\%03o", c); + used += 4; + } else { + buf[used++] = c; + } + if (used >= MAXUSE) { + buf[used] = '\0'; + Tcl_AppendResult(interp, buf, (char *) NULL); + used = 0; + } + } + } + if (used >= MAXUSE) { + /* + * If there are a whole bunch of returns or tabs in a row, + * then buf[] could get filled up. + */ + + buf[used] = '\0'; + Tcl_AppendResult(interp, buf, (char *) NULL); + used = 0; + } + chunkPtr++; + } + buf[used++] = ')'; + buf[used++] = '\n'; + buf[used] = '\0'; + Tcl_AppendResult(interp, buf, (char *) NULL); +} + +/* + *--------------------------------------------------------------------------- + * + * TkInitFontAttributes -- + * + * Initialize the font attributes structure to contain sensible + * values. This must be called before using any other font + * attributes functions. + * + * Results: + * None. + * + * Side effects. + * None. + * + *--------------------------------------------------------------------------- + */ + +void +TkInitFontAttributes(faPtr) + TkFontAttributes *faPtr; /* The attributes structure to initialize. */ +{ + faPtr->family = NULL; + faPtr->pointsize = 0; + faPtr->weight = TK_FW_NORMAL; + faPtr->slant = TK_FS_ROMAN; + faPtr->underline = 0; + faPtr->overstrike = 0; +} + +/* + *--------------------------------------------------------------------------- + * + * ConfigAttributesObj -- + * + * Process command line options to fill in fields of a properly + * initialized font attributes structure. + * + * Results: + * A standard Tcl return value. If TCL_ERROR is returned, an + * error message will be left in interp's result object. + * + * Side effects: + * The fields of the font attributes structure get filled in with + * information from argc/argv. If an error occurs while parsing, + * the font attributes structure will contain all modifications + * specified in the command line options up to the point of the + * error. + * + *--------------------------------------------------------------------------- + */ + +static int +ConfigAttributesObj(interp, tkwin, objc, objv, faPtr) + Tcl_Interp *interp; /* Interp for error return. */ + Tk_Window tkwin; /* For display on which font will be used. */ + int objc; /* Number of elements in argv. */ + Tcl_Obj *CONST objv[]; /* Command line options. */ + TkFontAttributes *faPtr; /* Font attributes structure whose fields + * are to be modified. Structure must already + * be properly initialized. */ +{ + int i, n, index; + Tcl_Obj *value; + char *option, *string; + + if (objc & 1) { + string = Tcl_GetStringFromObj(objv[objc - 1], NULL); + Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "missing value for \"", + string, "\" option", (char *) NULL); + return TCL_ERROR; + } + + for (i = 0; i < objc; i += 2) { + option = Tcl_GetStringFromObj(objv[i], NULL); + value = objv[i + 1]; + + if (Tcl_GetIndexFromObj(interp, objv[i], fontOpt, "option", 1, + &index) != TCL_OK) { + return TCL_ERROR; + } + switch (index) { + case FONT_FAMILY: + string = Tcl_GetStringFromObj(value, NULL); + faPtr->family = Tk_GetUid(string); + break; + + case FONT_SIZE: + if (Tcl_GetIntFromObj(interp, value, &n) != TCL_OK) { + return TCL_ERROR; + } + faPtr->pointsize = n; + break; + + case FONT_WEIGHT: + string = Tcl_GetStringFromObj(value, NULL); + n = TkFindStateNum(interp, option, weightMap, string); + if (n == TK_FW_UNKNOWN) { + return TCL_ERROR; + } + faPtr->weight = n; + break; + + case FONT_SLANT: + string = Tcl_GetStringFromObj(value, NULL); + n = TkFindStateNum(interp, option, slantMap, string); + if (n == TK_FS_UNKNOWN) { + return TCL_ERROR; + } + faPtr->slant = n; + break; + + case FONT_UNDERLINE: + if (Tcl_GetBooleanFromObj(interp, value, &n) != TCL_OK) { + return TCL_ERROR; + } + faPtr->underline = n; + break; + + case FONT_OVERSTRIKE: + if (Tcl_GetBooleanFromObj(interp, value, &n) != TCL_OK) { + return TCL_ERROR; + } + faPtr->overstrike = n; + break; + } + } + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * GetAttributeInfoObj -- + * + * Return information about the font attributes as a Tcl list. + * + * Results: + * The return value is TCL_OK if the objPtr was non-NULL and + * specified a valid font attribute, TCL_ERROR otherwise. If TCL_OK + * is returned, the interp's result object is modified to hold a + * description of either the current value of a single option, or a + * list of all options and their current values for the given font + * attributes. If TCL_ERROR is returned, the interp's result is + * set to an error message describing that the objPtr did not refer + * to a valid option. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +static int +GetAttributeInfoObj(interp, faPtr, objPtr) + Tcl_Interp *interp; /* Interp to hold result. */ + CONST TkFontAttributes *faPtr; /* The font attributes to inspect. */ + Tcl_Obj *objPtr; /* If non-NULL, indicates the single + * option whose value is to be + * returned. Otherwise + * information is returned for + * all options. */ +{ + int i, index, start, end, num; + char *str; + Tcl_Obj *newPtr; + + start = 0; + end = FONT_NUMFIELDS; + if (objPtr != NULL) { + if (Tcl_GetIndexFromObj(interp, objPtr, fontOpt, "option", 1, + &index) != TCL_OK) { + return TCL_ERROR; + } + start = index; + end = index + 1; + } + + for (i = start; i < end; i++) { + str = NULL; + num = 0; /* Needed only to prevent compiler + * warning. */ + switch (i) { + case FONT_FAMILY: + str = faPtr->family; + if (str == NULL) { + str = ""; + } + break; + + case FONT_SIZE: + num = faPtr->pointsize; + break; + + case FONT_WEIGHT: + str = TkFindStateString(weightMap, faPtr->weight); + break; + + case FONT_SLANT: + str = TkFindStateString(slantMap, faPtr->slant); + break; + + case FONT_UNDERLINE: + num = faPtr->underline; + break; + + case FONT_OVERSTRIKE: + num = faPtr->overstrike; + break; + } + if (objPtr == NULL) { + Tcl_ListObjAppendElement(NULL, Tcl_GetObjResult(interp), + Tcl_NewStringObj(fontOpt[i], -1)); + if (str != NULL) { + newPtr = Tcl_NewStringObj(str, -1); + } else { + newPtr = Tcl_NewIntObj(num); + } + Tcl_ListObjAppendElement(NULL, Tcl_GetObjResult(interp), + newPtr); + } else { + if (str != NULL) { + Tcl_SetStringObj(Tcl_GetObjResult(interp), str, -1); + } else { + Tcl_SetIntObj(Tcl_GetObjResult(interp), num); + } + } + } + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * ParseFontNameObj -- + * + * Converts a object into a set of font attributes that can be used + * to construct a font. + * + * The string rep of the object can be one of the following forms: + * XLFD (see X documentation) + * "Family [size [style] [style ...]]" + * "-option value [-option value ...]" + * + * Results: + * The return value is TCL_ERROR if the object was syntactically + * invalid. In that case an error message is left in interp's + * result object. Otherwise, fills the font attribute buffer with + * the values parsed from the string and returns TCL_OK; + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +static int +ParseFontNameObj(interp, tkwin, objPtr, faPtr) + Tcl_Interp *interp; /* Interp for error return. */ + Tk_Window tkwin; /* For display on which font is used. */ + Tcl_Obj *objPtr; /* Parseable font description object. */ + TkFontAttributes *faPtr; /* Font attributes structure whose fields + * are to be modified. Structure must already + * be properly initialized. */ +{ + char *dash; + int objc, result, i, n; + Tcl_Obj **objv; + TkXLFDAttributes xa; + char *string; + + string = Tcl_GetStringFromObj(objPtr, NULL); + if (*string == '-') { + /* + * This may be an XLFD or an "-option value" string. + * + * If the string begins with "-*" or a "-foundry-family-*" pattern, + * then consider it an XLFD. + */ + + if (string[1] == '*') { + goto xlfd; + } + dash = strchr(string + 1, '-'); + if ((dash != NULL) && (!isspace(UCHAR(dash[-1])))) { + goto xlfd; + } + + if (Tcl_ListObjGetElements(interp, objPtr, &objc, &objv) != TCL_OK) { + return TCL_ERROR; + } + + return ConfigAttributesObj(interp, tkwin, objc, objv, faPtr); + } + + if (*string == '*') { + /* + * This appears to be an XLFD. + */ + + xlfd: + xa.fa = *faPtr; + result = TkParseXLFD(string, &xa); + if (result == TCL_OK) { + *faPtr = xa.fa; + return result; + } + } + + /* + * Wasn't an XLFD or "-option value" string. Try it as a + * "font size style" list. + */ + + if (Tcl_ListObjGetElements(interp, objPtr, &objc, &objv) != TCL_OK) { + return TCL_ERROR; + } + if (objc < 1) { + Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "font \"", string, + "\" doesn't exist", (char *) NULL); + return TCL_ERROR; + } + + faPtr->family = Tk_GetUid(Tcl_GetStringFromObj(objv[0], NULL)); + if (objc > 1) { + if (Tcl_GetIntFromObj(interp, objv[1], &n) != TCL_OK) { + return TCL_ERROR; + } + faPtr->pointsize = n; + } + + i = 2; + if (objc == 3) { + if (Tcl_ListObjGetElements(interp, objv[2], &objc, &objv) != TCL_OK) { + return TCL_ERROR; + } + i = 0; + } + for ( ; i < objc; i++) { + string = Tcl_GetStringFromObj(objv[i], NULL); + n = TkFindStateNum(NULL, NULL, weightMap, string); + if (n != TK_FW_UNKNOWN) { + faPtr->weight = n; + continue; + } + n = TkFindStateNum(NULL, NULL, slantMap, string); + if (n != TK_FS_UNKNOWN) { + faPtr->slant = n; + continue; + } + n = TkFindStateNum(NULL, NULL, underlineMap, string); + if (n != 0) { + faPtr->underline = n; + continue; + } + n = TkFindStateNum(NULL, NULL, overstrikeMap, string); + if (n != 0) { + faPtr->overstrike = n; + continue; + } + + /* + * Unknown style. + */ + + Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), + "unknown font style \"", string, "\"", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * TkParseXLFD -- + * + * Break up a fully specified XLFD into a set of font attributes. + * + * Results: + * Return value is TCL_ERROR if string was not a fully specified XLFD. + * Otherwise, fills font attribute buffer with the values parsed + * from the XLFD and returns TCL_OK. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +int +TkParseXLFD(string, xaPtr) + CONST char *string; /* Parseable font description string. */ + TkXLFDAttributes *xaPtr; /* XLFD attributes structure whose fields + * are to be modified. Structure must already + * be properly initialized. */ +{ + char *src; + CONST char *str; + int i, j; + char *field[XLFD_NUMFIELDS + 2]; + Tcl_DString ds; + + memset(field, '\0', sizeof(field)); + + str = string; + if (*str == '-') { + str++; + } + + Tcl_DStringInit(&ds); + Tcl_DStringAppend(&ds, (char *) str, -1); + src = Tcl_DStringValue(&ds); + + field[0] = src; + for (i = 0; *src != '\0'; src++) { + if (isupper(UCHAR(*src))) { + *src = tolower(UCHAR(*src)); + } + if (*src == '-') { + i++; + if (i > XLFD_NUMFIELDS) { + break; + } + *src = '\0'; + field[i] = src + 1; + } + } + + /* + * An XLFD of the form -adobe-times-medium-r-*-12-*-* is pretty common, + * but it is (strictly) malformed, because the first * is eliding both + * the Setwidth and the Addstyle fields. If the Addstyle field is a + * number, then assume the above incorrect form was used and shift all + * the rest of the fields up by one, so the number gets interpreted + * as a pixelsize. This fix is so that we don't get a million reports + * that "it works under X, but gives a syntax error under Windows". + */ + + if ((i > XLFD_ADD_STYLE) && (FieldSpecified(field[XLFD_ADD_STYLE]))) { + if (atoi(field[XLFD_ADD_STYLE]) != 0) { + for (j = XLFD_NUMFIELDS - 1; j >= XLFD_ADD_STYLE; j--) { + field[j + 1] = field[j]; + } + field[XLFD_ADD_STYLE] = NULL; + i++; + } + } + + /* + * Bail if we don't have enough of the fields (up to pointsize). + */ + + if (i < XLFD_FAMILY) { + Tcl_DStringFree(&ds); + return TCL_ERROR; + } + + if (FieldSpecified(field[XLFD_FOUNDRY])) { + xaPtr->foundry = Tk_GetUid(field[XLFD_FOUNDRY]); + } + + if (FieldSpecified(field[XLFD_FAMILY])) { + xaPtr->fa.family = Tk_GetUid(field[XLFD_FAMILY]); + } + if (FieldSpecified(field[XLFD_WEIGHT])) { + xaPtr->fa.weight = TkFindStateNum(NULL, NULL, xlfdWeightMap, + field[XLFD_WEIGHT]); + } + if (FieldSpecified(field[XLFD_SLANT])) { + xaPtr->slant = TkFindStateNum(NULL, NULL, xlfdSlantMap, + field[XLFD_SLANT]); + if (xaPtr->slant == TK_FS_ROMAN) { + xaPtr->fa.slant = TK_FS_ROMAN; + } else { + xaPtr->fa.slant = TK_FS_ITALIC; + } + } + if (FieldSpecified(field[XLFD_SETWIDTH])) { + xaPtr->setwidth = TkFindStateNum(NULL, NULL, xlfdSetwidthMap, + field[XLFD_SETWIDTH]); + } + + /* XLFD_ADD_STYLE ignored. */ + + /* + * Pointsize in tenths of a point, but treat it as tenths of a pixel. + */ + + if (FieldSpecified(field[XLFD_POINT_SIZE])) { + if (field[XLFD_POINT_SIZE][0] == '[') { + /* + * Some X fonts have the point size specified as follows: + * + * [ N1 N2 N3 N4 ] + * + * where N1 is the point size (in points, not decipoints!), and + * N2, N3, and N4 are some additional numbers that I don't know + * the purpose of, so I ignore them. + */ + + xaPtr->fa.pointsize = atoi(field[XLFD_POINT_SIZE] + 1); + } else if (Tcl_GetInt(NULL, field[XLFD_POINT_SIZE], + &xaPtr->fa.pointsize) == TCL_OK) { + xaPtr->fa.pointsize /= 10; + } else { + return TCL_ERROR; + } + } + + /* + * Pixel height of font. If specified, overrides pointsize. + */ + + if (FieldSpecified(field[XLFD_PIXEL_SIZE])) { + if (field[XLFD_PIXEL_SIZE][0] == '[') { + /* + * Some X fonts have the pixel size specified as follows: + * + * [ N1 N2 N3 N4 ] + * + * where N1 is the pixel size, and where N2, N3, and N4 + * are some additional numbers that I don't know + * the purpose of, so I ignore them. + */ + + xaPtr->fa.pointsize = atoi(field[XLFD_PIXEL_SIZE] + 1); + } else if (Tcl_GetInt(NULL, field[XLFD_PIXEL_SIZE], + &xaPtr->fa.pointsize) != TCL_OK) { + return TCL_ERROR; + } + } + + xaPtr->fa.pointsize = -xaPtr->fa.pointsize; + + /* XLFD_RESOLUTION_X ignored. */ + + /* XLFD_RESOLUTION_Y ignored. */ + + /* XLFD_SPACING ignored. */ + + /* XLFD_AVERAGE_WIDTH ignored. */ + + if (FieldSpecified(field[XLFD_REGISTRY])) { + xaPtr->charset = TkFindStateNum(NULL, NULL, xlfdCharsetMap, + field[XLFD_REGISTRY]); + } + if (FieldSpecified(field[XLFD_ENCODING])) { + xaPtr->encoding = atoi(field[XLFD_ENCODING]); + } + + Tcl_DStringFree(&ds); + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * FieldSpecified -- + * + * Helper function for TkParseXLFD(). Determines if a field in the + * XLFD was set to a non-null, non-don't-care value. + * + * Results: + * The return value is 0 if the field in the XLFD was not set and + * should be ignored, non-zero otherwise. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +static int +FieldSpecified(field) + CONST char *field; /* The field of the XLFD to check. Strictly + * speaking, only when the string is "*" does it mean + * don't-care. However, an unspecified or question + * mark is also interpreted as don't-care. */ +{ + char ch; + + if (field == NULL) { + return 0; + } + ch = field[0]; + return (ch != '*' && ch != '?'); +} + +/* + *--------------------------------------------------------------------------- + * + * NewChunk -- + * + * Helper function for Tk_ComputeTextLayout(). Encapsulates a + * measured set of characters in a chunk that can be quickly + * drawn. + * + * Results: + * A pointer to the new chunk in the text layout. + * + * Side effects: + * The text layout is reallocated to hold more chunks as necessary. + * + * Currently, Tk_ComputeTextLayout() stores contiguous ranges of + * "normal" characters in a chunk, along with individual tab + * and newline chars in their own chunks. All characters in the + * text layout are accounted for. + * + *--------------------------------------------------------------------------- + */ +static LayoutChunk * +NewChunk(layoutPtrPtr, maxPtr, start, numChars, curX, newX, y) + TextLayout **layoutPtrPtr; + int *maxPtr; + CONST char *start; + int numChars; + int curX; + int newX; + int y; +{ + TextLayout *layoutPtr; + LayoutChunk *chunkPtr; + int maxChunks; + size_t s; + + layoutPtr = *layoutPtrPtr; + maxChunks = *maxPtr; + if (layoutPtr->numChunks == maxChunks) { + maxChunks *= 2; + s = sizeof(TextLayout) + ((maxChunks - 1) * sizeof(LayoutChunk)); + layoutPtr = (TextLayout *) ckrealloc((char *) layoutPtr, s); + + *layoutPtrPtr = layoutPtr; + *maxPtr = maxChunks; + } + chunkPtr = &layoutPtr->chunks[layoutPtr->numChunks]; + chunkPtr->start = start; + chunkPtr->numChars = numChars; + chunkPtr->numDisplayChars = numChars; + chunkPtr->x = curX; + chunkPtr->y = y; + chunkPtr->totalWidth = newX - curX; + chunkPtr->displayWidth = newX - curX; + layoutPtr->numChunks++; + + return chunkPtr; +} + diff --git a/generic/tkFont.h b/generic/tkFont.h new file mode 100644 index 0000000..758c329 --- /dev/null +++ b/generic/tkFont.h @@ -0,0 +1,208 @@ +/* + * tkFont.h -- + * + * Declarations for interfaces between the generic and platform- + * specific parts of the font package. This information is not + * visible outside of the font package. + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkFont.h 1.11 97/05/07 14:44:13 + */ + +#ifndef _TKFONT +#define _TKFONT + +/* + * The following structure keeps track of the attributes of a font. It can + * be used to keep track of either the desired attributes or the actual + * attributes gotten when the font was instantiated. + */ + +typedef struct TkFontAttributes { + Tk_Uid family; /* Font family. The most important field. */ + int pointsize; /* Pointsize of font, 0 for default size, or + * negative number meaning pixel size. */ + int weight; /* Weight flag; see below for def'n. */ + int slant; /* Slant flag; see below for def'n. */ + int underline; /* Non-zero for underline font. */ + int overstrike; /* Non-zero for overstrike font. */ +} TkFontAttributes; + +/* + * Possible values for the "weight" field in a TkFontAttributes structure. + * Weight is a subjective term and depends on what the company that created + * the font considers bold. + */ + +#define TK_FW_NORMAL 0 +#define TK_FW_BOLD 1 + +#define TK_FW_UNKNOWN -1 /* Unknown weight. This value is used for + * error checking and is never actually stored + * in the weight field. */ + +/* + * Possible values for the "slant" field in a TkFontAttributes structure. + */ + +#define TK_FS_ROMAN 0 +#define TK_FS_ITALIC 1 +#define TK_FS_OBLIQUE 2 /* This value is only used when parsing X + * font names to determine the closest + * match. It is only stored in the + * XLFDAttributes structure, never in the + * slant field of the TkFontAttributes. */ + +#define TK_FS_UNKNOWN -1 /* Unknown slant. This value is used for + * error checking and is never actually stored + * in the slant field. */ + +/* + * The following structure keeps track of the metrics for an instantiated + * font. The metrics are the physical properties of the font itself. + */ + +typedef struct TkFontMetrics { + int ascent; /* From baseline to top of font. */ + int descent; /* From baseline to bottom of font. */ + int maxWidth; /* Width of widest character in font. */ + int fixed; /* Non-zero if this is a fixed-width font, + * 0 otherwise. */ +} TkFontMetrics; + +/* + * The following structure is used to keep track of the generic information + * about a font. Each platform-specific font is represented by a structure + * with the following structure at its beginning, plus any platform- + * specific stuff after that. + */ + +typedef struct TkFont { + /* + * Fields used and maintained exclusively by generic code. + */ + + int refCount; /* Number of users of the TkFont. */ + Tcl_HashEntry *cacheHashPtr;/* Entry in font cache for this structure, + * used when deleting it. */ + Tcl_HashEntry *namedHashPtr;/* Pointer to hash table entry that + * corresponds to the named font that the + * tkfont was based on, or NULL if the tkfont + * was not based on a named font. */ + int tabWidth; /* Width of tabs in this font (pixels). */ + int underlinePos; /* Offset from baseline to origin of + * underline bar (used for drawing underlines + * on a non-underlined font). */ + int underlineHeight; /* Height of underline bar (used for drawing + * underlines on a non-underlined font). */ + + /* + * Fields in the generic font structure that are filled in by + * platform-specific code. + */ + + Font fid; /* For backwards compatibility with XGCValues + * structures. Remove when TkGCValues is + * implemented. */ + TkFontAttributes fa; /* Actual font attributes obtained when the + * the font was created, as opposed to the + * desired attributes passed in to + * TkpGetFontFromAttributes(). The desired + * metrics can be determined from the string + * that was used to create this font. */ + TkFontMetrics fm; /* Font metrics determined when font was + * created. */ +} TkFont; + +/* + * The following structure is used to return attributes when parsing an + * XLFD. The extra information is of interest to the Unix-specific code + * when attempting to find the closest matching font. + */ + +typedef struct TkXLFDAttributes { + TkFontAttributes fa; /* Standard set of font attributes. */ + Tk_Uid foundry; /* The foundry of the font. */ + int slant; /* The tristate value for the slant, which + * is significant under X. */ + int setwidth; /* The proportionate width, see below for + * definition. */ + int charset; /* The character set encoding (the glyph + * family), see below for definition. */ + int encoding; /* Variations within a charset for the + * glyphs above character 127. */ +} TkXLFDAttributes; + +/* + * Possible values for the "setwidth" field in a TkXLFDAttributes structure. + * The setwidth is whether characters are considered wider or narrower than + * normal. + */ + +#define TK_SW_NORMAL 0 +#define TK_SW_CONDENSE 1 +#define TK_SW_EXPAND 2 +#define TK_SW_UNKNOWN 3 /* Unknown setwidth. This value may be + * stored in the setwidth field. */ + +/* + * Possible values for the "charset" field in a TkXLFDAttributes structure. + * The charset is the set of glyphs that are used in the font. + */ + +#define TK_CS_NORMAL 0 +#define TK_CS_SYMBOL 1 +#define TK_CS_OTHER 2 + +/* + * The following defines specify the meaning of the fields in a fully + * qualified XLFD. + */ + +#define XLFD_FOUNDRY 0 +#define XLFD_FAMILY 1 +#define XLFD_WEIGHT 2 +#define XLFD_SLANT 3 +#define XLFD_SETWIDTH 4 +#define XLFD_ADD_STYLE 5 +#define XLFD_PIXEL_SIZE 6 +#define XLFD_POINT_SIZE 7 +#define XLFD_RESOLUTION_X 8 +#define XLFD_RESOLUTION_Y 9 +#define XLFD_SPACING 10 +#define XLFD_AVERAGE_WIDTH 11 +#define XLFD_REGISTRY 12 +#define XLFD_ENCODING 13 +#define XLFD_NUMFIELDS 14 /* Number of fields in XLFD. */ + +/* + * Exported from generic code to platform-specific code. + */ + +EXTERN int TkCreateNamedFont _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, CONST char *name, + TkFontAttributes *faPtr)); +EXTERN void TkInitFontAttributes _ANSI_ARGS_(( + TkFontAttributes *faPtr)); +EXTERN int TkParseXLFD _ANSI_ARGS_((CONST char *string, + TkXLFDAttributes *xaPtr)); + +/* + * Common APIs exported to tkFont.c from all platform-specific + * implementations. + */ + +EXTERN void TkpDeleteFont _ANSI_ARGS_((TkFont *tkFontPtr)); +EXTERN TkFont * TkpGetFontFromAttributes _ANSI_ARGS_(( + TkFont *tkFontPtr, Tk_Window tkwin, + CONST TkFontAttributes *faPtr)); +EXTERN void TkpGetFontFamilies _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin)); +EXTERN TkFont * TkpGetNativeFont _ANSI_ARGS_((Tk_Window tkwin, + CONST char *name)); + +#endif /* _TKFONT */ diff --git a/generic/tkFrame.c b/generic/tkFrame.c new file mode 100644 index 0000000..a11f566 --- /dev/null +++ b/generic/tkFrame.c @@ -0,0 +1,939 @@ +/* + * tkFrame.c -- + * + * This module implements "frame" and "toplevel" widgets for + * the Tk toolkit. Frames are windows with a background color + * and possibly a 3-D effect, but not much else in the way of + * attributes. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkFrame.c 1.82 97/08/08 17:26:26 + */ + +#include "default.h" +#include "tkPort.h" +#include "tkInt.h" + +/* + * A data structure of the following type is kept for each + * frame that currently exists for this process: + */ + +typedef struct { + Tk_Window tkwin; /* Window that embodies the frame. NULL + * means that the window has been destroyed + * but the data structures haven't yet been + * cleaned up. */ + Display *display; /* Display containing widget. Used, among + * other things, so that resources can be + * freed even after tkwin has gone away. */ + Tcl_Interp *interp; /* Interpreter associated with widget. Used + * to delete widget command. */ + Tcl_Command widgetCmd; /* Token for frame's widget command. */ + char *className; /* Class name for widget (from configuration + * option). Malloc-ed. */ + int mask; /* Either FRAME or TOPLEVEL; used to select + * which configuration options are valid for + * widget. */ + char *screenName; /* Screen on which widget is created. Non-null + * only for top-levels. Malloc-ed, may be + * NULL. */ + char *visualName; /* Textual description of visual for window, + * from -visual option. Malloc-ed, may be + * NULL. */ + char *colormapName; /* Textual description of colormap for window, + * from -colormap option. Malloc-ed, may be + * NULL. */ + char *menuName; /* Textual description of menu to use for + * menubar. Malloc-ed, may be NULL. */ + Colormap colormap; /* If not None, identifies a colormap + * allocated for this window, which must be + * freed when the window is deleted. */ + Tk_3DBorder border; /* Structure used to draw 3-D border and + * background. NULL means no background + * or border. */ + int borderWidth; /* Width of 3-D border (if any). */ + int relief; /* 3-d effect: TK_RELIEF_RAISED etc. */ + int highlightWidth; /* Width in pixels of highlight to draw + * around widget when it has the focus. + * 0 means don't draw a highlight. */ + XColor *highlightBgColorPtr; + /* Color for drawing traversal highlight + * area when highlight is off. */ + XColor *highlightColorPtr; /* Color for drawing traversal highlight. */ + int width; /* Width to request for window. <= 0 means + * don't request any size. */ + int height; /* Height to request for window. <= 0 means + * don't request any size. */ + Tk_Cursor cursor; /* Current cursor for window, or None. */ + char *takeFocus; /* Value of -takefocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + int isContainer; /* 1 means this window is a container, 0 means + * that it isn't. */ + char *useThis; /* If the window is embedded, this points to + * the name of the window in which it is + * embedded (malloc'ed). For non-embedded + * windows this is NULL. */ + int flags; /* Various flags; see below for + * definitions. */ +} Frame; + +/* + * Flag bits for frames: + * + * REDRAW_PENDING: Non-zero means a DoWhenIdle handler + * has already been queued to redraw + * this window. + * GOT_FOCUS: Non-zero means this widget currently + * has the input focus. + */ + +#define REDRAW_PENDING 1 +#define GOT_FOCUS 4 + +/* + * The following flag bits are used so that there can be separate + * defaults for some configuration options for frames and toplevels. + */ + +#define FRAME TK_CONFIG_USER_BIT +#define TOPLEVEL (TK_CONFIG_USER_BIT << 1) +#define BOTH (FRAME | TOPLEVEL) + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_FRAME_BG_COLOR, Tk_Offset(Frame, border), + BOTH|TK_CONFIG_COLOR_ONLY|TK_CONFIG_NULL_OK}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_FRAME_BG_MONO, Tk_Offset(Frame, border), + BOTH|TK_CONFIG_MONO_ONLY|TK_CONFIG_NULL_OK}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, BOTH}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, BOTH}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_FRAME_BORDER_WIDTH, Tk_Offset(Frame, borderWidth), BOTH}, + {TK_CONFIG_STRING, "-class", "class", "Class", + DEF_FRAME_CLASS, Tk_Offset(Frame, className), FRAME}, + {TK_CONFIG_STRING, "-class", "class", "Class", + DEF_TOPLEVEL_CLASS, Tk_Offset(Frame, className), TOPLEVEL}, + {TK_CONFIG_STRING, "-colormap", "colormap", "Colormap", + DEF_FRAME_COLORMAP, Tk_Offset(Frame, colormapName), + BOTH|TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-container", "container", "Container", + DEF_FRAME_CONTAINER, Tk_Offset(Frame, isContainer), BOTH}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_FRAME_CURSOR, Tk_Offset(Frame, cursor), BOTH|TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-height", "height", "Height", + DEF_FRAME_HEIGHT, Tk_Offset(Frame, height), BOTH}, + {TK_CONFIG_COLOR, "-highlightbackground", "highlightBackground", + "HighlightBackground", DEF_FRAME_HIGHLIGHT_BG, + Tk_Offset(Frame, highlightBgColorPtr), BOTH}, + {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor", + DEF_FRAME_HIGHLIGHT, Tk_Offset(Frame, highlightColorPtr), BOTH}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", + DEF_FRAME_HIGHLIGHT_WIDTH, Tk_Offset(Frame, highlightWidth), BOTH}, + {TK_CONFIG_STRING, "-menu", "menu", "Menu", + DEF_TOPLEVEL_MENU, Tk_Offset(Frame, menuName), + TOPLEVEL|TK_CONFIG_NULL_OK}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_FRAME_RELIEF, Tk_Offset(Frame, relief), BOTH}, + {TK_CONFIG_STRING, "-screen", "screen", "Screen", + DEF_TOPLEVEL_SCREEN, Tk_Offset(Frame, screenName), + TOPLEVEL|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_FRAME_TAKE_FOCUS, Tk_Offset(Frame, takeFocus), + BOTH|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-use", "use", "Use", + DEF_FRAME_USE, Tk_Offset(Frame, useThis), TOPLEVEL|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-visual", "visual", "Visual", + DEF_FRAME_VISUAL, Tk_Offset(Frame, visualName), + BOTH|TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-width", "width", "Width", + DEF_FRAME_WIDTH, Tk_Offset(Frame, width), BOTH}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int ConfigureFrame _ANSI_ARGS_((Tcl_Interp *interp, + Frame *framePtr, int argc, char **argv, + int flags)); +static void DestroyFrame _ANSI_ARGS_((char *memPtr)); +static void DisplayFrame _ANSI_ARGS_((ClientData clientData)); +static void FrameCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static void FrameEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int FrameWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void MapFrame _ANSI_ARGS_((ClientData clientData)); + +/* + *-------------------------------------------------------------- + * + * Tk_FrameCmd, Tk_ToplevelCmd -- + * + * These procedures are invoked to process the "frame" and + * "toplevel" Tcl commands. See the user documentation for + * details on what they do. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. These procedures are just wrappers; + * they call ButtonCreate to do all of the real work. + * + *-------------------------------------------------------------- + */ + +int +Tk_FrameCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + return TkCreateFrame(clientData, interp, argc, argv, 0, (char *) NULL); +} + +int +Tk_ToplevelCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + return TkCreateFrame(clientData, interp, argc, argv, 1, (char *) NULL); +} + +/* + *-------------------------------------------------------------- + * + * TkFrameCreate -- + * + * This procedure is invoked to process the "frame" and "toplevel" + * Tcl commands; it is also invoked directly by Tk_Init to create + * a new main window. See the user documentation for the "frame" + * and "toplevel" commands for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +TkCreateFrame(clientData, interp, argc, argv, toplevel, appName) + ClientData clientData; /* Main window associated with interpreter. + * If we're called by Tk_Init to create a + * new application, then this is NULL. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ + int toplevel; /* Non-zero means create a toplevel window, + * zero means create a frame. */ + char *appName; /* Should only be non-NULL if clientData is + * NULL: gives the base name to use for the + * new application. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + Frame *framePtr; + Tk_Window new; + char *className, *screenName, *visualName, *colormapName, *arg, *useOption; + int i, c, length, depth; + unsigned int mask; + Colormap colormap; + Visual *visual; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + /* + * Pre-process the argument list. Scan through it to find any + * "-class", "-screen", "-visual", and "-colormap" options. These + * arguments need to be processed specially, before the window + * is configured using the usual Tk mechanisms. + */ + + className = colormapName = screenName = visualName = useOption = NULL; + colormap = None; + for (i = 2; i < argc; i += 2) { + arg = argv[i]; + length = strlen(arg); + if (length < 2) { + continue; + } + c = arg[1]; + if ((c == 'c') && (strncmp(arg, "-class", strlen(arg)) == 0) + && (length >= 3)) { + className = argv[i+1]; + } else if ((c == 'c') + && (strncmp(arg, "-colormap", strlen(arg)) == 0)) { + colormapName = argv[i+1]; + } else if ((c == 's') && toplevel + && (strncmp(arg, "-screen", strlen(arg)) == 0)) { + screenName = argv[i+1]; + } else if ((c == 'u') && toplevel + && (strncmp(arg, "-use", strlen(arg)) == 0)) { + useOption = argv[i+1]; + } else if ((c == 'v') + && (strncmp(arg, "-visual", strlen(arg)) == 0)) { + visualName = argv[i+1]; + } + } + + /* + * Create the window, and deal with the special options -use, + * -classname, -colormap, -screenname, and -visual. These options + * must be handle before calling ConfigureFrame below, and they must + * also be processed in a particular order, for the following + * reasons: + * 1. Must set the window's class before calling ConfigureFrame, + * so that unspecified options are looked up in the option + * database using the correct class. + * 2. Must set visual information before calling ConfigureFrame + * so that colors are allocated in a proper colormap. + * 3. Must call TkpUseWindow before setting non-default visual + * information, since TkpUseWindow changes the defaults. + */ + + if (screenName == NULL) { + screenName = (toplevel) ? "" : NULL; + } + if (tkwin != NULL) { + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], screenName); + } else { + /* + * We were called from Tk_Init; create a new application. + */ + + if (appName == NULL) { + panic("TkCreateFrame didn't get application name"); + } + new = TkCreateMainWindow(interp, screenName, appName); + } + if (new == NULL) { + goto error; + } + if (className == NULL) { + className = Tk_GetOption(new, "class", "Class"); + if (className == NULL) { + className = (toplevel) ? "Toplevel" : "Frame"; + } + } + Tk_SetClass(new, className); + if (useOption == NULL) { + useOption = Tk_GetOption(new, "use", "Use"); + } + if (useOption != NULL) { + if (TkpUseWindow(interp, new, useOption) != TCL_OK) { + goto error; + } + } + if (visualName == NULL) { + visualName = Tk_GetOption(new, "visual", "Visual"); + } + if (colormapName == NULL) { + colormapName = Tk_GetOption(new, "colormap", "Colormap"); + } + if (visualName != NULL) { + visual = Tk_GetVisual(interp, new, visualName, &depth, + (colormapName == NULL) ? &colormap : (Colormap *) NULL); + if (visual == NULL) { + goto error; + } + Tk_SetWindowVisual(new, visual, depth, colormap); + } + if (colormapName != NULL) { + colormap = Tk_GetColormap(interp, new, colormapName); + if (colormap == None) { + goto error; + } + Tk_SetWindowColormap(new, colormap); + } + + /* + * For top-level windows, provide an initial geometry request of + * 200x200, just so the window looks nicer on the screen if it + * doesn't request a size for itself. + */ + + if (toplevel) { + Tk_GeometryRequest(new, 200, 200); + } + + /* + * Create the widget record, process configuration options, and + * create event handlers. Then fill in a few additional fields + * in the widget record from the special options. + */ + + framePtr = (Frame *) ckalloc(sizeof(Frame)); + framePtr->tkwin = new; + framePtr->display = Tk_Display(new); + framePtr->interp = interp; + framePtr->widgetCmd = Tcl_CreateCommand(interp, + Tk_PathName(new), FrameWidgetCmd, + (ClientData) framePtr, FrameCmdDeletedProc); + framePtr->className = NULL; + framePtr->mask = (toplevel) ? TOPLEVEL : FRAME; + framePtr->screenName = NULL; + framePtr->visualName = NULL; + framePtr->colormapName = NULL; + framePtr->colormap = colormap; + framePtr->border = NULL; + framePtr->borderWidth = 0; + framePtr->relief = TK_RELIEF_FLAT; + framePtr->highlightWidth = 0; + framePtr->highlightBgColorPtr = NULL; + framePtr->highlightColorPtr = NULL; + framePtr->width = 0; + framePtr->height = 0; + framePtr->cursor = None; + framePtr->takeFocus = NULL; + framePtr->isContainer = 0; + framePtr->useThis = NULL; + framePtr->flags = 0; + framePtr->menuName = NULL; + + /* + * Store backreference to frame widget in window structure. + */ + TkSetClassProcs(new, NULL, (ClientData) framePtr); + + mask = ExposureMask | StructureNotifyMask | FocusChangeMask; + if (toplevel) { + mask |= ActivateMask; + } + Tk_CreateEventHandler(new, mask, FrameEventProc, (ClientData) framePtr); + if (ConfigureFrame(interp, framePtr, argc-2, argv+2, 0) != TCL_OK) { + goto error; + } + if ((framePtr->isContainer)) { + if (framePtr->useThis == NULL) { + TkpMakeContainer(framePtr->tkwin); + } else { + Tcl_AppendResult(interp,"A window cannot have both the -use ", + "and the -container option set."); + return TCL_ERROR; + } + } + if (toplevel) { + Tcl_DoWhenIdle(MapFrame, (ClientData) framePtr); + } + interp->result = Tk_PathName(new); + return TCL_OK; + + error: + if (new != NULL) { + Tk_DestroyWindow(new); + } + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * FrameWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a frame widget. See the user + * documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +FrameWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about frame widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register Frame *framePtr = (Frame *) clientData; + int result; + size_t length; + int c, i; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) framePtr); + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + result = TCL_ERROR; + goto done; + } + result = Tk_ConfigureValue(interp, framePtr->tkwin, configSpecs, + (char *) framePtr, argv[2], framePtr->mask); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 2)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, framePtr->tkwin, configSpecs, + (char *) framePtr, (char *) NULL, framePtr->mask); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, framePtr->tkwin, configSpecs, + (char *) framePtr, argv[2], framePtr->mask); + } else { + /* + * Don't allow the options -class, -colormap, -container, + * -newcmap, -screen, -use, or -visual to be changed. + */ + + for (i = 2; i < argc; i++) { + length = strlen(argv[i]); + if (length < 2) { + continue; + } + c = argv[i][1]; + if (((c == 'c') && (strncmp(argv[i], "-class", length) == 0) + && (length >= 2)) + || ((c == 'c') && (framePtr->mask == TOPLEVEL) + && (strncmp(argv[i], "-colormap", length) == 0) + && (length >= 3)) + || ((c == 'c') + && (strncmp(argv[i], "-container", length) == 0) + && (length >= 3)) + || ((c == 's') && (framePtr->mask == TOPLEVEL) + && (strncmp(argv[i], "-screen", length) == 0)) + || ((c == 'u') && (framePtr->mask == TOPLEVEL) + && (strncmp(argv[i], "-use", length) == 0)) + || ((c == 'v') && (framePtr->mask == TOPLEVEL) + && (strncmp(argv[i], "-visual", length) == 0))) { + Tcl_AppendResult(interp, "can't modify ", argv[i], + " option after widget is created", (char *) NULL); + result = TCL_ERROR; + goto done; + } + } + result = ConfigureFrame(interp, framePtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be cget or configure", (char *) NULL); + result = TCL_ERROR; + } + + done: + Tcl_Release((ClientData) framePtr); + return result; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyFrame -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a frame at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the frame is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyFrame(memPtr) + char *memPtr; /* Info about frame widget. */ +{ + register Frame *framePtr = (Frame *) memPtr; + + Tk_FreeOptions(configSpecs, (char *) framePtr, framePtr->display, + framePtr->mask); + if (framePtr->colormap != None) { + Tk_FreeColormap(framePtr->display, framePtr->colormap); + } + ckfree((char *) framePtr); +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureFrame -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or + * reconfigure) a frame widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as text string, colors, font, + * etc. get set for framePtr; old resources get freed, if there + * were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureFrame(interp, framePtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + register Frame *framePtr; /* Information about widget; may or may + * not already have values for some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + char *oldMenuName; + + /* + * Need the old menubar name for the menu code to delete it. + */ + + if (framePtr->menuName == NULL) { + oldMenuName = NULL; + } else { + oldMenuName = ckalloc(strlen(framePtr->menuName) + 1); + strcpy(oldMenuName, framePtr->menuName); + } + + if (Tk_ConfigureWidget(interp, framePtr->tkwin, configSpecs, + argc, argv, (char *) framePtr, flags | framePtr->mask) != TCL_OK) { + return TCL_ERROR; + } + + if (((oldMenuName == NULL) && (framePtr->menuName != NULL)) + || ((oldMenuName != NULL) && (framePtr->menuName == NULL)) + || ((oldMenuName != NULL) && (framePtr->menuName != NULL) + && strcmp(oldMenuName, framePtr->menuName) != 0)) { + TkSetWindowMenuBar(interp, framePtr->tkwin, oldMenuName, + framePtr->menuName); + } + + if (framePtr->border != NULL) { + Tk_SetBackgroundFromBorder(framePtr->tkwin, framePtr->border); + } else { + Tk_SetWindowBackgroundPixmap(framePtr->tkwin, None); + } + + if (framePtr->highlightWidth < 0) { + framePtr->highlightWidth = 0; + } + Tk_SetInternalBorder(framePtr->tkwin, + framePtr->borderWidth + framePtr->highlightWidth); + if ((framePtr->width > 0) || (framePtr->height > 0)) { + Tk_GeometryRequest(framePtr->tkwin, framePtr->width, + framePtr->height); + } + + if (oldMenuName != NULL) { + ckfree(oldMenuName); + } + + if (Tk_IsMapped(framePtr->tkwin)) { + if (!(framePtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayFrame, (ClientData) framePtr); + } + framePtr->flags |= REDRAW_PENDING; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * DisplayFrame -- + * + * This procedure is invoked to display a frame widget. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the frame in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static void +DisplayFrame(clientData) + ClientData clientData; /* Information about widget. */ +{ + register Frame *framePtr = (Frame *) clientData; + register Tk_Window tkwin = framePtr->tkwin; + GC gc; + + framePtr->flags &= ~REDRAW_PENDING; + if ((framePtr->tkwin == NULL) || !Tk_IsMapped(tkwin) + || framePtr->isContainer) { + return; + } + + if (framePtr->border != NULL) { + Tk_Fill3DRectangle(tkwin, Tk_WindowId(tkwin), + framePtr->border, framePtr->highlightWidth, + framePtr->highlightWidth, + Tk_Width(tkwin) - 2*framePtr->highlightWidth, + Tk_Height(tkwin) - 2*framePtr->highlightWidth, + framePtr->borderWidth, framePtr->relief); + } + if (framePtr->highlightWidth != 0) { + if (framePtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(framePtr->highlightColorPtr, + Tk_WindowId(tkwin)); + } else { + gc = Tk_GCForColor(framePtr->highlightBgColorPtr, + Tk_WindowId(tkwin)); + } + Tk_DrawFocusHighlight(tkwin, gc, framePtr->highlightWidth, + Tk_WindowId(tkwin)); + } +} + +/* + *-------------------------------------------------------------- + * + * FrameEventProc -- + * + * This procedure is invoked by the Tk dispatcher on + * structure changes to a frame. For frames with 3D + * borders, this procedure is also invoked for exposures. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +FrameEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + register XEvent *eventPtr; /* Information about event. */ +{ + register Frame *framePtr = (Frame *) clientData; + + if (((eventPtr->type == Expose) && (eventPtr->xexpose.count == 0)) + || (eventPtr->type == ConfigureNotify)) { + goto redraw; + } else if (eventPtr->type == DestroyNotify) { + if (framePtr->menuName != NULL) { + TkSetWindowMenuBar(framePtr->interp, framePtr->tkwin, + framePtr->menuName, NULL); + ckfree(framePtr->menuName); + framePtr->menuName = NULL; + } + if (framePtr->tkwin != NULL) { + + /* + * If this window is a container, then this event could be + * coming from the embedded application, in which case + * Tk_DestroyWindow hasn't been called yet. When Tk_DestroyWindow + * is called later, then another destroy event will be generated. + * We need to be sure we ignore the second event, since the frame + * could be gone by then. To do so, delete the event handler + * explicitly (normally it's done implicitly by Tk_DestroyWindow). + */ + + Tk_DeleteEventHandler(framePtr->tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + FrameEventProc, (ClientData) framePtr); + framePtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(framePtr->interp, framePtr->widgetCmd); + } + if (framePtr->flags & REDRAW_PENDING) { + Tcl_CancelIdleCall(DisplayFrame, (ClientData) framePtr); + } + Tcl_CancelIdleCall(MapFrame, (ClientData) framePtr); + Tcl_EventuallyFree((ClientData) framePtr, DestroyFrame); + } else if (eventPtr->type == FocusIn) { + if (eventPtr->xfocus.detail != NotifyInferior) { + framePtr->flags |= GOT_FOCUS; + if (framePtr->highlightWidth > 0) { + goto redraw; + } + } + } else if (eventPtr->type == FocusOut) { + if (eventPtr->xfocus.detail != NotifyInferior) { + framePtr->flags &= ~GOT_FOCUS; + if (framePtr->highlightWidth > 0) { + goto redraw; + } + } + } else if (eventPtr->type == ActivateNotify) { + TkpSetMainMenubar(framePtr->interp, framePtr->tkwin, + framePtr->menuName); + } + return; + + redraw: + if ((framePtr->tkwin != NULL) && !(framePtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayFrame, (ClientData) framePtr); + framePtr->flags |= REDRAW_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * FrameCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +FrameCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + Frame *framePtr = (Frame *) clientData; + Tk_Window tkwin = framePtr->tkwin; + + if (framePtr->menuName != NULL) { + TkSetWindowMenuBar(framePtr->interp, framePtr->tkwin, + framePtr->menuName, NULL); + ckfree(framePtr->menuName); + framePtr->menuName = NULL; + } + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + framePtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *---------------------------------------------------------------------- + * + * MapFrame -- + * + * This procedure is invoked as a when-idle handler to map a + * newly-created top-level frame. + * + * Results: + * None. + * + * Side effects: + * The frame given by the clientData argument is mapped. + * + *---------------------------------------------------------------------- + */ + +static void +MapFrame(clientData) + ClientData clientData; /* Pointer to frame structure. */ +{ + Frame *framePtr = (Frame *) clientData; + + /* + * Wait for all other background events to be processed before + * mapping window. This ensures that the window's correct geometry + * will have been determined before it is first mapped, so that the + * window manager doesn't get a false idea of its desired geometry. + */ + + Tcl_Preserve((ClientData) framePtr); + while (1) { + if (Tcl_DoOneEvent(TCL_IDLE_EVENTS) == 0) { + break; + } + + /* + * After each event, make sure that the window still exists + * and quit if the window has been destroyed. + */ + + if (framePtr->tkwin == NULL) { + Tcl_Release((ClientData) framePtr); + return; + } + } + Tk_MapWindow(framePtr->tkwin); + Tcl_Release((ClientData) framePtr); +} + +/* + *-------------------------------------------------------------- + * + * TkInstallFrameMenu -- + * + * This function is needed when a Windows HWND is created + * and a menubar has been set to the window with a system + * menu. It notifies the menu package so that the system + * menu can be rebuilt. + * + * Results: + * None. + * + * Side effects: + * The system menu (if any) is created for the menubar + * associated with this frame. + * + *-------------------------------------------------------------- + */ + +void +TkInstallFrameMenu(tkwin) + Tk_Window tkwin; /* The window that was just created. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + + if (winPtr->mainPtr != NULL) { + Frame *framePtr; + framePtr = (Frame*) winPtr->instanceData; + TkpMenuNotifyToplevelCreate(winPtr->mainPtr->interp, + framePtr->menuName); + } +} diff --git a/generic/tkGC.c b/generic/tkGC.c new file mode 100644 index 0000000..f68db12 --- /dev/null +++ b/generic/tkGC.c @@ -0,0 +1,363 @@ +/* + * tkGC.c -- + * + * This file maintains a database of read-only graphics contexts + * for the Tk toolkit, in order to allow GC's to be shared. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkGC.c 1.18 96/02/15 18:53:32 + */ + +#include "tkPort.h" +#include "tk.h" + +/* + * One of the following data structures exists for each GC that is + * currently active. The structure is indexed with two hash tables, + * one based on the values in the graphics context and the other + * based on the display and GC identifier. + */ + +typedef struct { + GC gc; /* Graphics context. */ + Display *display; /* Display to which gc belongs. */ + int refCount; /* Number of active uses of gc. */ + Tcl_HashEntry *valueHashPtr;/* Entry in valueTable (needed when deleting + * this structure). */ +} TkGC; + +/* + * Hash table to map from a GC's values to a TkGC structure describing + * a GC with those values (used by Tk_GetGC). + */ + +static Tcl_HashTable valueTable; +typedef struct { + XGCValues values; /* Desired values for GC. */ + Display *display; /* Display for which GC is valid. */ + int screenNum; /* screen number of display */ + int depth; /* and depth for which GC is valid. */ +} ValueKey; + +/* + * Hash table for <display + GC> -> TkGC mapping. This table is used by + * Tk_FreeGC. + */ + +static Tcl_HashTable idTable; +typedef struct { + Display *display; /* Display for which GC was allocated. */ + GC gc; /* X's identifier for GC. */ +} IdKey; + +static int initialized = 0; /* 0 means static structures haven't been + * initialized yet. */ + +/* + * Forward declarations for procedures defined in this file: + */ + +static void GCInit _ANSI_ARGS_((void)); + +/* + *---------------------------------------------------------------------- + * + * Tk_GetGC -- + * + * Given a desired set of values for a graphics context, find + * a read-only graphics context with the desired values. + * + * Results: + * The return value is the X identifer for the desired graphics + * context. The caller should never modify this GC, and should + * call Tk_FreeGC when the GC is no longer needed. + * + * Side effects: + * The GC is added to an internal database with a reference count. + * For each call to this procedure, there should eventually be a call + * to Tk_FreeGC, so that the database can be cleaned up when GC's + * aren't needed anymore. + * + *---------------------------------------------------------------------- + */ + +GC +Tk_GetGC(tkwin, valueMask, valuePtr) + Tk_Window tkwin; /* Window in which GC will be used. */ + register unsigned long valueMask; + /* 1 bits correspond to values specified + * in *valuesPtr; other values are set + * from defaults. */ + register XGCValues *valuePtr; + /* Values are specified here for bits set + * in valueMask. */ +{ + ValueKey valueKey; + IdKey idKey; + Tcl_HashEntry *valueHashPtr, *idHashPtr; + register TkGC *gcPtr; + int new; + Drawable d, freeDrawable; + + if (!initialized) { + GCInit(); + } + + /* + * Must zero valueKey at start to clear out pad bytes that may be + * part of structure on some systems. + */ + + memset((VOID *) &valueKey, 0, sizeof(valueKey)); + + /* + * First, check to see if there's already a GC that will work + * for this request (exact matches only, sorry). + */ + + if (valueMask & GCFunction) { + valueKey.values.function = valuePtr->function; + } else { + valueKey.values.function = GXcopy; + } + if (valueMask & GCPlaneMask) { + valueKey.values.plane_mask = valuePtr->plane_mask; + } else { + valueKey.values.plane_mask = (unsigned) ~0; + } + if (valueMask & GCForeground) { + valueKey.values.foreground = valuePtr->foreground; + } else { + valueKey.values.foreground = 0; + } + if (valueMask & GCBackground) { + valueKey.values.background = valuePtr->background; + } else { + valueKey.values.background = 1; + } + if (valueMask & GCLineWidth) { + valueKey.values.line_width = valuePtr->line_width; + } else { + valueKey.values.line_width = 0; + } + if (valueMask & GCLineStyle) { + valueKey.values.line_style = valuePtr->line_style; + } else { + valueKey.values.line_style = LineSolid; + } + if (valueMask & GCCapStyle) { + valueKey.values.cap_style = valuePtr->cap_style; + } else { + valueKey.values.cap_style = CapButt; + } + if (valueMask & GCJoinStyle) { + valueKey.values.join_style = valuePtr->join_style; + } else { + valueKey.values.join_style = JoinMiter; + } + if (valueMask & GCFillStyle) { + valueKey.values.fill_style = valuePtr->fill_style; + } else { + valueKey.values.fill_style = FillSolid; + } + if (valueMask & GCFillRule) { + valueKey.values.fill_rule = valuePtr->fill_rule; + } else { + valueKey.values.fill_rule = EvenOddRule; + } + if (valueMask & GCArcMode) { + valueKey.values.arc_mode = valuePtr->arc_mode; + } else { + valueKey.values.arc_mode = ArcPieSlice; + } + if (valueMask & GCTile) { + valueKey.values.tile = valuePtr->tile; + } else { + valueKey.values.tile = None; + } + if (valueMask & GCStipple) { + valueKey.values.stipple = valuePtr->stipple; + } else { + valueKey.values.stipple = None; + } + if (valueMask & GCTileStipXOrigin) { + valueKey.values.ts_x_origin = valuePtr->ts_x_origin; + } else { + valueKey.values.ts_x_origin = 0; + } + if (valueMask & GCTileStipYOrigin) { + valueKey.values.ts_y_origin = valuePtr->ts_y_origin; + } else { + valueKey.values.ts_y_origin = 0; + } + if (valueMask & GCFont) { + valueKey.values.font = valuePtr->font; + } else { + valueKey.values.font = None; + } + if (valueMask & GCSubwindowMode) { + valueKey.values.subwindow_mode = valuePtr->subwindow_mode; + } else { + valueKey.values.subwindow_mode = ClipByChildren; + } + if (valueMask & GCGraphicsExposures) { + valueKey.values.graphics_exposures = valuePtr->graphics_exposures; + } else { + valueKey.values.graphics_exposures = True; + } + if (valueMask & GCClipXOrigin) { + valueKey.values.clip_x_origin = valuePtr->clip_x_origin; + } else { + valueKey.values.clip_x_origin = 0; + } + if (valueMask & GCClipYOrigin) { + valueKey.values.clip_y_origin = valuePtr->clip_y_origin; + } else { + valueKey.values.clip_y_origin = 0; + } + if (valueMask & GCClipMask) { + valueKey.values.clip_mask = valuePtr->clip_mask; + } else { + valueKey.values.clip_mask = None; + } + if (valueMask & GCDashOffset) { + valueKey.values.dash_offset = valuePtr->dash_offset; + } else { + valueKey.values.dash_offset = 0; + } + if (valueMask & GCDashList) { + valueKey.values.dashes = valuePtr->dashes; + } else { + valueKey.values.dashes = 4; + } + valueKey.display = Tk_Display(tkwin); + valueKey.screenNum = Tk_ScreenNumber(tkwin); + valueKey.depth = Tk_Depth(tkwin); + valueHashPtr = Tcl_CreateHashEntry(&valueTable, (char *) &valueKey, &new); + if (!new) { + gcPtr = (TkGC *) Tcl_GetHashValue(valueHashPtr); + gcPtr->refCount++; + return gcPtr->gc; + } + + /* + * No GC is currently available for this set of values. Allocate a + * new GC and add a new structure to the database. + */ + + gcPtr = (TkGC *) ckalloc(sizeof(TkGC)); + + /* + * Find or make a drawable to use to specify the screen and depth + * of the GC. We may have to make a small pixmap, to avoid doing + * Tk_MakeWindowExist on the window. + */ + + freeDrawable = None; + if (Tk_WindowId(tkwin) != None) { + d = Tk_WindowId(tkwin); + } else if (valueKey.depth == + DefaultDepth(valueKey.display, valueKey.screenNum)) { + d = RootWindow(valueKey.display, valueKey.screenNum); + } else { + d = Tk_GetPixmap(valueKey.display, + RootWindow(valueKey.display, valueKey.screenNum), + 1, 1, valueKey.depth); + freeDrawable = d; + } + + gcPtr->gc = XCreateGC(valueKey.display, d, valueMask, &valueKey.values); + gcPtr->display = valueKey.display; + gcPtr->refCount = 1; + gcPtr->valueHashPtr = valueHashPtr; + idKey.display = valueKey.display; + idKey.gc = gcPtr->gc; + idHashPtr = Tcl_CreateHashEntry(&idTable, (char *) &idKey, &new); + if (!new) { + panic("GC already registered in Tk_GetGC"); + } + Tcl_SetHashValue(valueHashPtr, gcPtr); + Tcl_SetHashValue(idHashPtr, gcPtr); + if (freeDrawable != None) { + Tk_FreePixmap(valueKey.display, freeDrawable); + } + + return gcPtr->gc; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreeGC -- + * + * This procedure is called to release a graphics context allocated by + * Tk_GetGC. + * + * Results: + * None. + * + * Side effects: + * The reference count associated with gc is decremented, and + * gc is officially deallocated if no-one is using it anymore. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreeGC(display, gc) + Display *display; /* Display for which gc was allocated. */ + GC gc; /* Graphics context to be released. */ +{ + IdKey idKey; + Tcl_HashEntry *idHashPtr; + register TkGC *gcPtr; + + if (!initialized) { + panic("Tk_FreeGC called before Tk_GetGC"); + } + + idKey.display = display; + idKey.gc = gc; + idHashPtr = Tcl_FindHashEntry(&idTable, (char *) &idKey); + if (idHashPtr == NULL) { + panic("Tk_FreeGC received unknown gc argument"); + } + gcPtr = (TkGC *) Tcl_GetHashValue(idHashPtr); + gcPtr->refCount--; + if (gcPtr->refCount == 0) { + Tk_FreeXId(gcPtr->display, (XID) XGContextFromGC(gcPtr->gc)); + XFreeGC(gcPtr->display, gcPtr->gc); + Tcl_DeleteHashEntry(gcPtr->valueHashPtr); + Tcl_DeleteHashEntry(idHashPtr); + ckfree((char *) gcPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * GCInit -- + * + * Initialize the structures used for GC management. + * + * Results: + * None. + * + * Side effects: + * Read the code. + * + *---------------------------------------------------------------------- + */ + +static void +GCInit() +{ + initialized = 1; + Tcl_InitHashTable(&valueTable, sizeof(ValueKey)/sizeof(int)); + Tcl_InitHashTable(&idTable, sizeof(IdKey)/sizeof(int)); +} diff --git a/generic/tkGeometry.c b/generic/tkGeometry.c new file mode 100644 index 0000000..ec2c959 --- /dev/null +++ b/generic/tkGeometry.c @@ -0,0 +1,582 @@ +/* + * tkGeometry.c -- + * + * This file contains generic Tk code for geometry management + * (stuff that's used by all geometry managers). + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkGeometry.c 1.31 96/02/15 18:53:32 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * Data structures of the following type are used by Tk_MaintainGeometry. + * For each slave managed by Tk_MaintainGeometry, there is one of these + * structures associated with its master. + */ + +typedef struct MaintainSlave { + Tk_Window slave; /* The slave window being positioned. */ + Tk_Window master; /* The master that determines slave's + * position; it must be a descendant of + * slave's parent. */ + int x, y; /* Desired position of slave relative to + * master. */ + int width, height; /* Desired dimensions of slave. */ + struct MaintainSlave *nextPtr; + /* Next in list of Maintains associated + * with master. */ +} MaintainSlave; + +/* + * For each window that has been specified as a master to + * Tk_MaintainGeometry, there is a structure of the following type: + */ + +typedef struct MaintainMaster { + Tk_Window ancestor; /* The lowest ancestor of this window + * for which we have *not* created a + * StructureNotify handler. May be the + * same as the window itself. */ + int checkScheduled; /* Non-zero means that there is already a + * call to MaintainCheckProc scheduled as + * an idle handler. */ + MaintainSlave *slavePtr; /* First in list of all slaves associated + * with this master. */ +} MaintainMaster; + +/* + * Hash table that maps from a master's Tk_Window token to a list of + * Maintains for that master: + */ + +static Tcl_HashTable maintainHashTable; + +/* + * Has maintainHashTable been initialized yet? + */ + +static int initialized = 0; + +/* + * Prototypes for static procedures in this file: + */ + +static void MaintainCheckProc _ANSI_ARGS_((ClientData clientData)); +static void MaintainMasterProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void MaintainSlaveProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); + +/* + *-------------------------------------------------------------- + * + * Tk_ManageGeometry -- + * + * Arrange for a particular procedure to manage the geometry + * of a given slave window. + * + * Results: + * None. + * + * Side effects: + * Proc becomes the new geometry manager for tkwin, replacing + * any previous geometry manager. The geometry manager will + * be notified (by calling procedures in *mgrPtr) when interesting + * things happen in the future. If there was an existing geometry + * manager for tkwin different from the new one, it is notified + * by calling its lostSlaveProc. + * + *-------------------------------------------------------------- + */ + +void +Tk_ManageGeometry(tkwin, mgrPtr, clientData) + Tk_Window tkwin; /* Window whose geometry is to + * be managed by proc. */ + Tk_GeomMgr *mgrPtr; /* Static structure describing the + * geometry manager. This structure + * must never go away. */ + ClientData clientData; /* Arbitrary one-word argument to + * pass to geometry manager procedures. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + if ((winPtr->geomMgrPtr != NULL) && (mgrPtr != NULL) + && ((winPtr->geomMgrPtr != mgrPtr) + || (winPtr->geomData != clientData)) + && (winPtr->geomMgrPtr->lostSlaveProc != NULL)) { + (*winPtr->geomMgrPtr->lostSlaveProc)(winPtr->geomData, tkwin); + } + + winPtr->geomMgrPtr = mgrPtr; + winPtr->geomData = clientData; +} + +/* + *-------------------------------------------------------------- + * + * Tk_GeometryRequest -- + * + * This procedure is invoked by widget code to indicate + * its preferences about the size of a window it manages. + * In general, widget code should call this procedure + * rather than Tk_ResizeWindow. + * + * Results: + * None. + * + * Side effects: + * The geometry manager for tkwin (if any) is invoked to + * handle the request. If possible, it will reconfigure + * tkwin and/or other windows to satisfy the request. The + * caller gets no indication of success or failure, but it + * will get X events if the window size was actually + * changed. + * + *-------------------------------------------------------------- + */ + +void +Tk_GeometryRequest(tkwin, reqWidth, reqHeight) + Tk_Window tkwin; /* Window that geometry information + * pertains to. */ + int reqWidth, reqHeight; /* Minimum desired dimensions for + * window, in pixels. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + /* + * X gets very upset if a window requests a width or height of + * zero, so rounds requested sizes up to at least 1. + */ + + if (reqWidth <= 0) { + reqWidth = 1; + } + if (reqHeight <= 0) { + reqHeight = 1; + } + if ((reqWidth == winPtr->reqWidth) && (reqHeight == winPtr->reqHeight)) { + return; + } + winPtr->reqWidth = reqWidth; + winPtr->reqHeight = reqHeight; + if ((winPtr->geomMgrPtr != NULL) + && (winPtr->geomMgrPtr->requestProc != NULL)) { + (*winPtr->geomMgrPtr->requestProc)(winPtr->geomData, tkwin); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_SetInternalBorder -- + * + * Notify relevant geometry managers that a window has an internal + * border of a given width and that child windows should not be + * placed on that border. + * + * Results: + * None. + * + * Side effects: + * The border width is recorded for the window, and all geometry + * managers of all children are notified so that can re-layout, if + * necessary. + * + *---------------------------------------------------------------------- + */ + +void +Tk_SetInternalBorder(tkwin, width) + Tk_Window tkwin; /* Window that will have internal border. */ + int width; /* Width of internal border, in pixels. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + if (width == winPtr->internalBorderWidth) { + return; + } + if (width < 0) { + width = 0; + } + winPtr->internalBorderWidth = width; + + /* + * All the slaves for which this is the master window must now be + * repositioned to take account of the new internal border width. + * To signal all the geometry managers to do this, just resize the + * window to its current size. The ConfigureNotify event will + * cause geometry managers to recompute everything. + */ + + Tk_ResizeWindow(tkwin, Tk_Width(tkwin), Tk_Height(tkwin)); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_MaintainGeometry -- + * + * This procedure is invoked by geometry managers to handle slaves + * whose master's are not their parents. It translates the desired + * geometry for the slave into the coordinate system of the parent + * and respositions the slave if it isn't already at the right place. + * Furthermore, it sets up event handlers so that if the master (or + * any of its ancestors up to the slave's parent) is mapped, unmapped, + * or moved, then the slave will be adjusted to match. + * + * Results: + * None. + * + * Side effects: + * Event handlers are created and state is allocated to keep track + * of slave. Note: if slave was already managed for master by + * Tk_MaintainGeometry, then the previous information is replaced + * with the new information. The caller must eventually call + * Tk_UnmaintainGeometry to eliminate the correspondence (or, the + * state is automatically freed when either window is destroyed). + * + *---------------------------------------------------------------------- + */ + +void +Tk_MaintainGeometry(slave, master, x, y, width, height) + Tk_Window slave; /* Slave for geometry management. */ + Tk_Window master; /* Master for slave; must be a descendant + * of slave's parent. */ + int x, y; /* Desired position of slave within master. */ + int width, height; /* Desired dimensions for slave. */ +{ + Tcl_HashEntry *hPtr; + MaintainMaster *masterPtr; + register MaintainSlave *slavePtr; + int new, map; + Tk_Window ancestor, parent; + + if (!initialized) { + initialized = 1; + Tcl_InitHashTable(&maintainHashTable, TCL_ONE_WORD_KEYS); + } + + /* + * See if there is already a MaintainMaster structure for the master; + * if not, then create one. + */ + + parent = Tk_Parent(slave); + hPtr = Tcl_CreateHashEntry(&maintainHashTable, (char *) master, &new); + if (!new) { + masterPtr = (MaintainMaster *) Tcl_GetHashValue(hPtr); + } else { + masterPtr = (MaintainMaster *) ckalloc(sizeof(MaintainMaster)); + masterPtr->ancestor = master; + masterPtr->checkScheduled = 0; + masterPtr->slavePtr = NULL; + Tcl_SetHashValue(hPtr, masterPtr); + } + + /* + * Create a MaintainSlave structure for the slave if there isn't + * already one. + */ + + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + if (slavePtr->slave == slave) { + goto gotSlave; + } + } + slavePtr = (MaintainSlave *) ckalloc(sizeof(MaintainSlave)); + slavePtr->slave = slave; + slavePtr->master = master; + slavePtr->nextPtr = masterPtr->slavePtr; + masterPtr->slavePtr = slavePtr; + Tk_CreateEventHandler(slave, StructureNotifyMask, MaintainSlaveProc, + (ClientData) slavePtr); + + /* + * Make sure that there are event handlers registered for all + * the windows between master and slave's parent (including master + * but not slave's parent). There may already be handlers for master + * and some of its ancestors (masterPtr->ancestor tells how many). + */ + + for (ancestor = master; ancestor != parent; + ancestor = Tk_Parent(ancestor)) { + if (ancestor == masterPtr->ancestor) { + Tk_CreateEventHandler(ancestor, StructureNotifyMask, + MaintainMasterProc, (ClientData) masterPtr); + masterPtr->ancestor = Tk_Parent(ancestor); + } + } + + /* + * Fill in up-to-date information in the structure, then update the + * window if it's not currently in the right place or state. + */ + + gotSlave: + slavePtr->x = x; + slavePtr->y = y; + slavePtr->width = width; + slavePtr->height = height; + map = 1; + for (ancestor = slavePtr->master; ; ancestor = Tk_Parent(ancestor)) { + if (!Tk_IsMapped(ancestor) && (ancestor != parent)) { + map = 0; + } + if (ancestor == parent) { + if ((x != Tk_X(slavePtr->slave)) + || (y != Tk_Y(slavePtr->slave)) + || (width != Tk_Width(slavePtr->slave)) + || (height != Tk_Height(slavePtr->slave))) { + Tk_MoveResizeWindow(slavePtr->slave, x, y, width, height); + } + if (map) { + Tk_MapWindow(slavePtr->slave); + } else { + Tk_UnmapWindow(slavePtr->slave); + } + break; + } + x += Tk_X(ancestor) + Tk_Changes(ancestor)->border_width; + y += Tk_Y(ancestor) + Tk_Changes(ancestor)->border_width; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_UnmaintainGeometry -- + * + * This procedure cancels a previous Tk_MaintainGeometry call, + * so that the relationship between slave and master is no longer + * maintained. + * + * Results: + * None. + * + * Side effects: + * The slave is unmapped and state is released, so that slave won't + * track master any more. If we weren't previously managing slave + * relative to master, then this procedure has no effect. + * + *---------------------------------------------------------------------- + */ + +void +Tk_UnmaintainGeometry(slave, master) + Tk_Window slave; /* Slave for geometry management. */ + Tk_Window master; /* Master for slave; must be a descendant + * of slave's parent. */ +{ + Tcl_HashEntry *hPtr; + MaintainMaster *masterPtr; + register MaintainSlave *slavePtr, *prevPtr; + Tk_Window ancestor; + + if (!initialized) { + initialized = 1; + Tcl_InitHashTable(&maintainHashTable, TCL_ONE_WORD_KEYS); + } + + if (!(((TkWindow *) slave)->flags & TK_ALREADY_DEAD)) { + Tk_UnmapWindow(slave); + } + hPtr = Tcl_FindHashEntry(&maintainHashTable, (char *) master); + if (hPtr == NULL) { + return; + } + masterPtr = (MaintainMaster *) Tcl_GetHashValue(hPtr); + slavePtr = masterPtr->slavePtr; + if (slavePtr->slave == slave) { + masterPtr->slavePtr = slavePtr->nextPtr; + } else { + for (prevPtr = slavePtr, slavePtr = slavePtr->nextPtr; ; + prevPtr = slavePtr, slavePtr = slavePtr->nextPtr) { + if (slavePtr == NULL) { + return; + } + if (slavePtr->slave == slave) { + prevPtr->nextPtr = slavePtr->nextPtr; + break; + } + } + } + Tk_DeleteEventHandler(slavePtr->slave, StructureNotifyMask, + MaintainSlaveProc, (ClientData) slavePtr); + ckfree((char *) slavePtr); + if (masterPtr->slavePtr == NULL) { + if (masterPtr->ancestor != NULL) { + for (ancestor = master; ; ancestor = Tk_Parent(ancestor)) { + Tk_DeleteEventHandler(ancestor, StructureNotifyMask, + MaintainMasterProc, (ClientData) masterPtr); + if (ancestor == masterPtr->ancestor) { + break; + } + } + } + if (masterPtr->checkScheduled) { + Tcl_CancelIdleCall(MaintainCheckProc, (ClientData) masterPtr); + } + Tcl_DeleteHashEntry(hPtr); + ckfree((char *) masterPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * MaintainMasterProc -- + * + * This procedure is invoked by the Tk event dispatcher in + * response to StructureNotify events on the master or one + * of its ancestors, on behalf of Tk_MaintainGeometry. + * + * Results: + * None. + * + * Side effects: + * It schedules a call to MaintainCheckProc, which will eventually + * caused the postions and mapped states to be recalculated for all + * the maintained slaves of the master. Or, if the master window is + * being deleted then state is cleaned up. + * + *---------------------------------------------------------------------- + */ + +static void +MaintainMasterProc(clientData, eventPtr) + ClientData clientData; /* Pointer to MaintainMaster structure + * for the master window. */ + XEvent *eventPtr; /* Describes what just happened. */ +{ + MaintainMaster *masterPtr = (MaintainMaster *) clientData; + MaintainSlave *slavePtr; + int done; + + if ((eventPtr->type == ConfigureNotify) + || (eventPtr->type == MapNotify) + || (eventPtr->type == UnmapNotify)) { + if (!masterPtr->checkScheduled) { + masterPtr->checkScheduled = 1; + Tcl_DoWhenIdle(MaintainCheckProc, (ClientData) masterPtr); + } + } else if (eventPtr->type == DestroyNotify) { + /* + * Delete all of the state associated with this master, but + * be careful not to use masterPtr after the last slave is + * deleted, since its memory will have been freed. + */ + + done = 0; + do { + slavePtr = masterPtr->slavePtr; + if (slavePtr->nextPtr == NULL) { + done = 1; + } + Tk_UnmaintainGeometry(slavePtr->slave, slavePtr->master); + } while (!done); + } +} + +/* + *---------------------------------------------------------------------- + * + * MaintainSlaveProc -- + * + * This procedure is invoked by the Tk event dispatcher in + * response to StructureNotify events on a slave being managed + * by Tk_MaintainGeometry. + * + * Results: + * None. + * + * Side effects: + * If the event is a DestroyNotify event then the Maintain state + * and event handlers for this slave are deleted. + * + *---------------------------------------------------------------------- + */ + +static void +MaintainSlaveProc(clientData, eventPtr) + ClientData clientData; /* Pointer to MaintainSlave structure + * for master-slave pair. */ + XEvent *eventPtr; /* Describes what just happened. */ +{ + MaintainSlave *slavePtr = (MaintainSlave *) clientData; + + if (eventPtr->type == DestroyNotify) { + Tk_UnmaintainGeometry(slavePtr->slave, slavePtr->master); + } +} + +/* + *---------------------------------------------------------------------- + * + * MaintainCheckProc -- + * + * This procedure is invoked by the Tk event dispatcher as an + * idle handler, when a master or one of its ancestors has been + * reconfigured, mapped, or unmapped. Its job is to scan all of + * the slaves for the master and reposition them, map them, or + * unmap them as needed to maintain their geometry relative to + * the master. + * + * Results: + * None. + * + * Side effects: + * Slaves can get repositioned, mapped, or unmapped. + * + *---------------------------------------------------------------------- + */ + +static void +MaintainCheckProc(clientData) + ClientData clientData; /* Pointer to MaintainMaster structure + * for the master window. */ +{ + MaintainMaster *masterPtr = (MaintainMaster *) clientData; + MaintainSlave *slavePtr; + Tk_Window ancestor, parent; + int x, y, map; + + masterPtr->checkScheduled = 0; + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + parent = Tk_Parent(slavePtr->slave); + x = slavePtr->x; + y = slavePtr->y; + map = 1; + for (ancestor = slavePtr->master; ; ancestor = Tk_Parent(ancestor)) { + if (!Tk_IsMapped(ancestor) && (ancestor != parent)) { + map = 0; + } + if (ancestor == parent) { + if ((x != Tk_X(slavePtr->slave)) + || (y != Tk_Y(slavePtr->slave))) { + Tk_MoveWindow(slavePtr->slave, x, y); + } + if (map) { + Tk_MapWindow(slavePtr->slave); + } else { + Tk_UnmapWindow(slavePtr->slave); + } + break; + } + x += Tk_X(ancestor) + Tk_Changes(ancestor)->border_width; + y += Tk_Y(ancestor) + Tk_Changes(ancestor)->border_width; + } + } +} diff --git a/generic/tkGet.c b/generic/tkGet.c new file mode 100644 index 0000000..56258a6 --- /dev/null +++ b/generic/tkGet.c @@ -0,0 +1,586 @@ +/* + * tkGet.c -- + * + * This file contains a number of "Tk_GetXXX" procedures, which + * parse text strings into useful forms for Tk. This file has + * the simpler procedures, like Tk_GetDirection and Tk_GetUid. + * The more complex procedures like Tk_GetColor are in separate + * files. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkGet.c 1.13 96/04/26 10:25:46 + */ + +#include "tkInt.h" +#include "tkPort.h" + +/* + * The hash table below is used to keep track of all the Tk_Uids created + * so far. + */ + +static Tcl_HashTable uidTable; +static int initialized = 0; + +/* + *-------------------------------------------------------------- + * + * Tk_GetAnchor -- + * + * Given a string, return the corresponding Tk_Anchor. + * + * Results: + * The return value is a standard Tcl return result. If + * TCL_OK is returned, then everything went well and the + * position is stored at *anchorPtr; otherwise TCL_ERROR + * is returned and an error message is left in + * interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_GetAnchor(interp, string, anchorPtr) + Tcl_Interp *interp; /* Use this for error reporting. */ + char *string; /* String describing a direction. */ + Tk_Anchor *anchorPtr; /* Where to store Tk_Anchor corresponding + * to string. */ +{ + switch (string[0]) { + case 'n': + if (string[1] == 0) { + *anchorPtr = TK_ANCHOR_N; + return TCL_OK; + } else if ((string[1] == 'e') && (string[2] == 0)) { + *anchorPtr = TK_ANCHOR_NE; + return TCL_OK; + } else if ((string[1] == 'w') && (string[2] == 0)) { + *anchorPtr = TK_ANCHOR_NW; + return TCL_OK; + } + goto error; + case 's': + if (string[1] == 0) { + *anchorPtr = TK_ANCHOR_S; + return TCL_OK; + } else if ((string[1] == 'e') && (string[2] == 0)) { + *anchorPtr = TK_ANCHOR_SE; + return TCL_OK; + } else if ((string[1] == 'w') && (string[2] == 0)) { + *anchorPtr = TK_ANCHOR_SW; + return TCL_OK; + } else { + goto error; + } + case 'e': + if (string[1] == 0) { + *anchorPtr = TK_ANCHOR_E; + return TCL_OK; + } + goto error; + case 'w': + if (string[1] == 0) { + *anchorPtr = TK_ANCHOR_W; + return TCL_OK; + } + goto error; + case 'c': + if (strncmp(string, "center", strlen(string)) == 0) { + *anchorPtr = TK_ANCHOR_CENTER; + return TCL_OK; + } + goto error; + } + + error: + Tcl_AppendResult(interp, "bad anchor position \"", string, + "\": must be n, ne, e, se, s, sw, w, nw, or center", + (char *) NULL); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * Tk_NameOfAnchor -- + * + * Given a Tk_Anchor, return the string that corresponds + * to it. + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_NameOfAnchor(anchor) + Tk_Anchor anchor; /* Anchor for which identifying string + * is desired. */ +{ + switch (anchor) { + case TK_ANCHOR_N: return "n"; + case TK_ANCHOR_NE: return "ne"; + case TK_ANCHOR_E: return "e"; + case TK_ANCHOR_SE: return "se"; + case TK_ANCHOR_S: return "s"; + case TK_ANCHOR_SW: return "sw"; + case TK_ANCHOR_W: return "w"; + case TK_ANCHOR_NW: return "nw"; + case TK_ANCHOR_CENTER: return "center"; + } + return "unknown anchor position"; +} + +/* + *-------------------------------------------------------------- + * + * Tk_GetJoinStyle -- + * + * Given a string, return the corresponding Tk_JoinStyle. + * + * Results: + * The return value is a standard Tcl return result. If + * TCL_OK is returned, then everything went well and the + * justification is stored at *joinPtr; otherwise + * TCL_ERROR is returned and an error message is left in + * interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_GetJoinStyle(interp, string, joinPtr) + Tcl_Interp *interp; /* Use this for error reporting. */ + char *string; /* String describing a justification style. */ + int *joinPtr; /* Where to store join style corresponding + * to string. */ +{ + int c; + size_t length; + + c = string[0]; + length = strlen(string); + + if ((c == 'b') && (strncmp(string, "bevel", length) == 0)) { + *joinPtr = JoinBevel; + return TCL_OK; + } + if ((c == 'm') && (strncmp(string, "miter", length) == 0)) { + *joinPtr = JoinMiter; + return TCL_OK; + } + if ((c == 'r') && (strncmp(string, "round", length) == 0)) { + *joinPtr = JoinRound; + return TCL_OK; + } + + Tcl_AppendResult(interp, "bad join style \"", string, + "\": must be bevel, miter, or round", + (char *) NULL); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * Tk_NameOfJoinStyle -- + * + * Given a Tk_JoinStyle, return the string that corresponds + * to it. + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_NameOfJoinStyle(join) + int join; /* Join style for which identifying string + * is desired. */ +{ + switch (join) { + case JoinBevel: return "bevel"; + case JoinMiter: return "miter"; + case JoinRound: return "round"; + } + return "unknown join style"; +} + +/* + *-------------------------------------------------------------- + * + * Tk_GetCapStyle -- + * + * Given a string, return the corresponding Tk_CapStyle. + * + * Results: + * The return value is a standard Tcl return result. If + * TCL_OK is returned, then everything went well and the + * justification is stored at *capPtr; otherwise + * TCL_ERROR is returned and an error message is left in + * interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_GetCapStyle(interp, string, capPtr) + Tcl_Interp *interp; /* Use this for error reporting. */ + char *string; /* String describing a justification style. */ + int *capPtr; /* Where to store cap style corresponding + * to string. */ +{ + int c; + size_t length; + + c = string[0]; + length = strlen(string); + + if ((c == 'b') && (strncmp(string, "butt", length) == 0)) { + *capPtr = CapButt; + return TCL_OK; + } + if ((c == 'p') && (strncmp(string, "projecting", length) == 0)) { + *capPtr = CapProjecting; + return TCL_OK; + } + if ((c == 'r') && (strncmp(string, "round", length) == 0)) { + *capPtr = CapRound; + return TCL_OK; + } + + Tcl_AppendResult(interp, "bad cap style \"", string, + "\": must be butt, projecting, or round", + (char *) NULL); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * Tk_NameOfCapStyle -- + * + * Given a Tk_CapStyle, return the string that corresponds + * to it. + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_NameOfCapStyle(cap) + int cap; /* Cap style for which identifying string + * is desired. */ +{ + switch (cap) { + case CapButt: return "butt"; + case CapProjecting: return "projecting"; + case CapRound: return "round"; + } + return "unknown cap style"; +} + +/* + *-------------------------------------------------------------- + * + * Tk_GetJustify -- + * + * Given a string, return the corresponding Tk_Justify. + * + * Results: + * The return value is a standard Tcl return result. If + * TCL_OK is returned, then everything went well and the + * justification is stored at *justifyPtr; otherwise + * TCL_ERROR is returned and an error message is left in + * interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_GetJustify(interp, string, justifyPtr) + Tcl_Interp *interp; /* Use this for error reporting. */ + char *string; /* String describing a justification style. */ + Tk_Justify *justifyPtr; /* Where to store Tk_Justify corresponding + * to string. */ +{ + int c; + size_t length; + + c = string[0]; + length = strlen(string); + + if ((c == 'l') && (strncmp(string, "left", length) == 0)) { + *justifyPtr = TK_JUSTIFY_LEFT; + return TCL_OK; + } + if ((c == 'r') && (strncmp(string, "right", length) == 0)) { + *justifyPtr = TK_JUSTIFY_RIGHT; + return TCL_OK; + } + if ((c == 'c') && (strncmp(string, "center", length) == 0)) { + *justifyPtr = TK_JUSTIFY_CENTER; + return TCL_OK; + } + + Tcl_AppendResult(interp, "bad justification \"", string, + "\": must be left, right, or center", + (char *) NULL); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * Tk_NameOfJustify -- + * + * Given a Tk_Justify, return the string that corresponds + * to it. + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +char * +Tk_NameOfJustify(justify) + Tk_Justify justify; /* Justification style for which + * identifying string is desired. */ +{ + switch (justify) { + case TK_JUSTIFY_LEFT: return "left"; + case TK_JUSTIFY_RIGHT: return "right"; + case TK_JUSTIFY_CENTER: return "center"; + } + return "unknown justification style"; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetUid -- + * + * Given a string, this procedure returns a unique identifier + * for the string. + * + * Results: + * This procedure returns a Tk_Uid corresponding to the "string" + * argument. The Tk_Uid has a string value identical to string + * (strcmp will return 0), but it's guaranteed that any other + * calls to this procedure with a string equal to "string" will + * return exactly the same result (i.e. can compare Tk_Uid + * *values* directly, without having to call strcmp on what they + * point to). + * + * Side effects: + * New information may be entered into the identifier table. + * + *---------------------------------------------------------------------- + */ + +Tk_Uid +Tk_GetUid(string) + CONST char *string; /* String to convert. */ +{ + int dummy; + + if (!initialized) { + Tcl_InitHashTable(&uidTable, TCL_STRING_KEYS); + initialized = 1; + } + return (Tk_Uid) Tcl_GetHashKey(&uidTable, + Tcl_CreateHashEntry(&uidTable, string, &dummy)); +} + +/* + *-------------------------------------------------------------- + * + * Tk_GetScreenMM -- + * + * Given a string, returns the number of screen millimeters + * corresponding to that string. + * + * Results: + * The return value is a standard Tcl return result. If + * TCL_OK is returned, then everything went well and the + * screen distance is stored at *doublePtr; otherwise + * TCL_ERROR is returned and an error message is left in + * interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_GetScreenMM(interp, tkwin, string, doublePtr) + Tcl_Interp *interp; /* Use this for error reporting. */ + Tk_Window tkwin; /* Window whose screen determines conversion + * from centimeters and other absolute + * units. */ + char *string; /* String describing a screen distance. */ + double *doublePtr; /* Place to store converted result. */ +{ + char *end; + double d; + + d = strtod(string, &end); + if (end == string) { + error: + Tcl_AppendResult(interp, "bad screen distance \"", string, + "\"", (char *) NULL); + return TCL_ERROR; + } + while ((*end != '\0') && isspace(UCHAR(*end))) { + end++; + } + switch (*end) { + case 0: + d /= WidthOfScreen(Tk_Screen(tkwin)); + d *= WidthMMOfScreen(Tk_Screen(tkwin)); + break; + case 'c': + d *= 10; + end++; + break; + case 'i': + d *= 25.4; + end++; + break; + case 'm': + end++; + break; + case 'p': + d *= 25.4/72.0; + end++; + break; + default: + goto error; + } + while ((*end != '\0') && isspace(UCHAR(*end))) { + end++; + } + if (*end != 0) { + goto error; + } + *doublePtr = d; + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * Tk_GetPixels -- + * + * Given a string, returns the number of pixels corresponding + * to that string. + * + * Results: + * The return value is a standard Tcl return result. If + * TCL_OK is returned, then everything went well and the + * rounded pixel distance is stored at *intPtr; otherwise + * TCL_ERROR is returned and an error message is left in + * interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +Tk_GetPixels(interp, tkwin, string, intPtr) + Tcl_Interp *interp; /* Use this for error reporting. */ + Tk_Window tkwin; /* Window whose screen determines conversion + * from centimeters and other absolute + * units. */ + char *string; /* String describing a justification style. */ + int *intPtr; /* Place to store converted result. */ +{ + char *end; + double d; + + d = strtod(string, &end); + if (end == string) { + error: + Tcl_AppendResult(interp, "bad screen distance \"", string, + "\"", (char *) NULL); + return TCL_ERROR; + } + while ((*end != '\0') && isspace(UCHAR(*end))) { + end++; + } + switch (*end) { + case 0: + break; + case 'c': + d *= 10*WidthOfScreen(Tk_Screen(tkwin)); + d /= WidthMMOfScreen(Tk_Screen(tkwin)); + end++; + break; + case 'i': + d *= 25.4*WidthOfScreen(Tk_Screen(tkwin)); + d /= WidthMMOfScreen(Tk_Screen(tkwin)); + end++; + break; + case 'm': + d *= WidthOfScreen(Tk_Screen(tkwin)); + d /= WidthMMOfScreen(Tk_Screen(tkwin)); + end++; + break; + case 'p': + d *= (25.4/72.0)*WidthOfScreen(Tk_Screen(tkwin)); + d /= WidthMMOfScreen(Tk_Screen(tkwin)); + end++; + break; + default: + goto error; + } + while ((*end != '\0') && isspace(UCHAR(*end))) { + end++; + } + if (*end != 0) { + goto error; + } + if (d < 0) { + *intPtr = (int) (d - 0.5); + } else { + *intPtr = (int) (d + 0.5); + } + return TCL_OK; +} diff --git a/generic/tkGrab.c b/generic/tkGrab.c new file mode 100644 index 0000000..869e0b3 --- /dev/null +++ b/generic/tkGrab.c @@ -0,0 +1,1535 @@ +/* + * tkGrab.c -- + * + * This file provides procedures that implement grabs for Tk. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkGrab.c 1.52 97/03/21 11:14:34 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * The grab state machine has four states: ungrabbed, button pressed, + * grabbed, and button pressed while grabbed. In addition, there are + * three pieces of grab state information: the current grab window, + * the current restrict window, and whether the mouse is captured. + * + * The current grab window specifies the point in the Tk window + * heirarchy above which pointer events will not be reported. Any + * window within the subtree below the grab window will continue to + * receive events as normal. Events outside of the grab tree will be + * reported to the grab window. + * + * If the current restrict window is set, then all pointer events will + * be reported only to the restrict window. The restrict window is + * normally set during an automatic button grab. + * + * The mouse capture state specifies whether the window system will + * report mouse events outside of any Tk toplevels. This is set + * during a global grab or an automatic button grab. + * + * The transitions between different states is given in the following + * table: + * + * Event\State U B G GB + * ----------- -- -- -- -- + * FirstPress B B GB GB + * Press B B G GB + * Release U B G GB + * LastRelease U U G G + * Grab G G G G + * Ungrab U B U U + * + * Note: U=Ungrabbed, B=Button, G=Grabbed, GB=Grab and Button + * + * In addition, the following conditions are always true: + * + * State\Variable Grab Restrict Capture + * -------------- ---- -------- ------- + * Ungrabbed 0 0 0 + * Button 0 1 1 + * Grabbed 1 0 b/g + * Grab and Button 1 1 1 + * + * Note: 0 means variable is set to NULL, 1 means variable is set to + * some window, b/g means the variable is set to a window if a button + * is currently down or a global grab is in effect. + * + * The final complication to all of this is enter and leave events. + * In order to correctly handle all of the various cases, Tk cannot + * rely on X enter/leave events in all situations. The following + * describes the correct sequence of enter and leave events that + * should be observed by Tk scripts: + * + * Event(state) Enter/Leave From -> To + * ------------ ---------------------- + * LastRelease(B | GB): restrict window -> anc(grab window, event window) + * Grab(U | B): event window -> anc(grab window, event window) + * Grab(G): anc(old grab window, event window) -> + * anc(new grab window, event window) + * Grab(GB): restrict window -> anc(new grab window, event window) + * Ungrab(G): anc(grab window, event window) -> event window + * Ungrab(GB): restrict window -> event window + * + * Note: anc(x,y) returns the least ancestor of y that is in the tree + * of x, terminating at toplevels. + */ + +/* + * The following structure is used to pass information to + * GrabRestrictProc from EatGrabEvents. + */ + +typedef struct { + Display *display; /* Display from which to discard events. */ + unsigned int serial; /* Serial number with which to compare. */ +} GrabInfo; + +/* + * Bit definitions for grabFlags field of TkDisplay structures: + * + * GRAB_GLOBAL 1 means this is a global grab (we grabbed via + * the server so all applications are locked out). + * 0 means this is a local grab that affects + * only this application. + * GRAB_TEMP_GLOBAL 1 means we've temporarily grabbed via the + * server because a button is down and we want + * to make sure that we get the button-up + * event. The grab will be released when the + * last mouse button goes up. + */ + +#define GRAB_GLOBAL 1 +#define GRAB_TEMP_GLOBAL 4 + +/* + * The following structure is a Tcl_Event that triggers a change in + * the grabWinPtr field of a display. This event guarantees that + * the change occurs in the proper order relative to enter and leave + * events. + */ + +typedef struct NewGrabWinEvent { + Tcl_Event header; /* Standard information for all Tcl events. */ + TkDisplay *dispPtr; /* Display whose grab window is to change. */ + Window grabWindow; /* New grab window for display. This is + * recorded instead of a (TkWindow *) because + * it will allow us to detect cases where + * the window is destroyed before this event + * is processed. */ +} NewGrabWinEvent; + +/* + * The following magic value is stored in the "send_event" field of + * EnterNotify and LeaveNotify events that are generated in this + * file. This allows us to separate "real" events coming from the + * server from those that we generated. + */ + +#define GENERATED_EVENT_MAGIC ((Bool) 0x147321ac) + +/* + * Mask that selects any of the state bits corresponding to buttons, + * plus masks that select individual buttons' bits: + */ + +#define ALL_BUTTONS \ + (Button1Mask|Button2Mask|Button3Mask|Button4Mask|Button5Mask) +static unsigned int buttonStates[] = { + Button1Mask, Button2Mask, Button3Mask, Button4Mask, Button5Mask +}; + +/* + * Forward declarations for procedures declared later in this file: + */ + +static void EatGrabEvents _ANSI_ARGS_((TkDisplay *dispPtr, + unsigned int serial)); +static TkWindow * FindCommonAncestor _ANSI_ARGS_((TkWindow *winPtr1, + TkWindow *winPtr2, int *countPtr1, + int *countPtr2)); +static Tk_RestrictAction GrabRestrictProc _ANSI_ARGS_((ClientData arg, + XEvent *eventPtr)); +static int GrabWinEventProc _ANSI_ARGS_((Tcl_Event *evPtr, + int flags)); +static void MovePointer2 _ANSI_ARGS_((TkWindow *sourcePtr, + TkWindow *destPtr, int mode, int leaveEvents, + int EnterEvents)); +static void QueueGrabWindowChange _ANSI_ARGS_((TkDisplay *dispPtr, + TkWindow *grabWinPtr)); +static void ReleaseButtonGrab _ANSI_ARGS_((TkDisplay *dispPtr)); + +/* + *---------------------------------------------------------------------- + * + * Tk_GrabCmd -- + * + * This procedure is invoked to process the "grab" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +Tk_GrabCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + int globalGrab, c; + Tk_Window tkwin; + TkDisplay *dispPtr; + size_t length; + + if (argc < 2) { + badArgs: + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " ?-global? window\" or \"", argv[0], + " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if (c == '.') { + if (argc != 2) { + goto badArgs; + } + tkwin = Tk_NameToWindow(interp, argv[1], (Tk_Window) clientData); + if (tkwin == NULL) { + return TCL_ERROR; + } + return Tk_Grab(interp, tkwin, 0); + } else if ((c == '-') && (strncmp(argv[1], "-global", length) == 0) + && (length >= 2)) { + if (argc != 3) { + goto badArgs; + } + tkwin = Tk_NameToWindow(interp, argv[2], (Tk_Window) clientData); + if (tkwin == NULL) { + return TCL_ERROR; + } + return Tk_Grab(interp, tkwin, 1); + } else if ((c == 'c') && (strncmp(argv[1], "current", length) == 0)) { + if (argc > 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " current ?window?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + tkwin = Tk_NameToWindow(interp, argv[2], (Tk_Window) clientData); + if (tkwin == NULL) { + return TCL_ERROR; + } + dispPtr = ((TkWindow *) tkwin)->dispPtr; + if (dispPtr->eventualGrabWinPtr != NULL) { + interp->result = dispPtr->eventualGrabWinPtr->pathName; + } + } else { + for (dispPtr = tkDisplayList; dispPtr != NULL; + dispPtr = dispPtr->nextPtr) { + if (dispPtr->eventualGrabWinPtr != NULL) { + Tcl_AppendElement(interp, + dispPtr->eventualGrabWinPtr->pathName); + } + } + } + return TCL_OK; + } else if ((c == 'r') && (strncmp(argv[1], "release", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " release window\"", (char *) NULL); + return TCL_ERROR; + } + tkwin = Tk_NameToWindow(interp, argv[2], (Tk_Window) clientData); + if (tkwin == NULL) { + Tcl_ResetResult(interp); + } else { + Tk_Ungrab(tkwin); + } + } else if ((c == 's') && (strncmp(argv[1], "set", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " set ?-global? window\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + globalGrab = 0; + tkwin = Tk_NameToWindow(interp, argv[2], (Tk_Window) clientData); + } else { + globalGrab = 1; + length = strlen(argv[2]); + if ((strncmp(argv[2], "-global", length) != 0) || (length < 2)) { + Tcl_AppendResult(interp, "bad argument \"", argv[2], + "\": must be \"", argv[0], " set ?-global? window\"", + (char *) NULL); + return TCL_ERROR; + } + tkwin = Tk_NameToWindow(interp, argv[3], (Tk_Window) clientData); + } + if (tkwin == NULL) { + return TCL_ERROR; + } + return Tk_Grab(interp, tkwin, globalGrab); + } else if ((c == 's') && (strncmp(argv[1], "status", length) == 0) + && (length >= 2)) { + TkWindow *winPtr; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " status window\"", (char *) NULL); + return TCL_ERROR; + } + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[2], + (Tk_Window) clientData); + if (winPtr == NULL) { + return TCL_ERROR; + } + dispPtr = winPtr->dispPtr; + if (dispPtr->eventualGrabWinPtr != winPtr) { + interp->result = "none"; + } else if (dispPtr->grabFlags & GRAB_GLOBAL) { + interp->result = "global"; + } else { + interp->result = "local"; + } + } else { + Tcl_AppendResult(interp, "unknown or ambiguous option \"", argv[1], + "\": must be current, release, set, or status", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_Grab -- + * + * Grabs the pointer and keyboard, so that mouse-related events are + * only reported relative to a given window and its descendants. + * + * Results: + * A standard Tcl result is returned. TCL_OK is the normal return + * value; if the grab could not be set then TCL_ERROR is returned + * and interp->result will hold an error message. + * + * Side effects: + * Once this call completes successfully, no window outside the + * tree rooted at tkwin will receive pointer- or keyboard-related + * events until the next call to Tk_Ungrab. If a previous grab was + * in effect within this application, then it is replaced with a new + * one. + * + *---------------------------------------------------------------------- + */ + +int +Tk_Grab(interp, tkwin, grabGlobal) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Window tkwin; /* Window on whose behalf the pointer + * is to be grabbed. */ + int grabGlobal; /* Non-zero means issue a grab to the + * server so that no other application + * gets mouse or keyboard events. + * Zero means the grab only applies + * within this application. */ +{ + int grabResult, numTries; + TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr = winPtr->dispPtr; + TkWindow *winPtr2; + unsigned int serial; + + ReleaseButtonGrab(dispPtr); + if (dispPtr->eventualGrabWinPtr != NULL) { + if ((dispPtr->eventualGrabWinPtr == winPtr) + && (grabGlobal == ((dispPtr->grabFlags & GRAB_GLOBAL) != 0))) { + return TCL_OK; + } + if (dispPtr->eventualGrabWinPtr->mainPtr != winPtr->mainPtr) { + alreadyGrabbed: + interp->result = "grab failed: another application has grab"; + return TCL_ERROR; + } + Tk_Ungrab((Tk_Window) dispPtr->eventualGrabWinPtr); + } + + Tk_MakeWindowExist(tkwin); + if (!grabGlobal) { + Window dummy1, dummy2; + int dummy3, dummy4, dummy5, dummy6; + unsigned int state; + + /* + * Local grab. However, if any mouse buttons are down, turn + * it into a global grab temporarily, until the last button + * goes up. This does two things: (a) it makes sure that we + * see the button-up event; and (b) it allows us to track mouse + * motion among all of the windows of this application. + */ + + dispPtr->grabFlags &= ~(GRAB_GLOBAL|GRAB_TEMP_GLOBAL); + XQueryPointer(dispPtr->display, winPtr->window, &dummy1, + &dummy2, &dummy3, &dummy4, &dummy5, &dummy6, &state); + if ((state & ALL_BUTTONS) != 0) { + dispPtr->grabFlags |= GRAB_TEMP_GLOBAL; + goto setGlobalGrab; + } + } else { + dispPtr->grabFlags |= GRAB_GLOBAL; + setGlobalGrab: + + /* + * Tricky point: must ungrab before grabbing. This is needed + * in case there is a button auto-grab already in effect. If + * there is, and the mouse has moved to a different window, X + * won't generate enter and leave events to move the mouse if + * we grab without ungrabbing. + */ + + XUngrabPointer(dispPtr->display, CurrentTime); + serial = NextRequest(dispPtr->display); + + /* + * Another tricky point: there are races with some window + * managers that can cause grabs to fail because the window + * manager hasn't released its grab quickly enough. To work + * around this problem, retry a few times after AlreadyGrabbed + * errors to give the grab release enough time to register with + * the server. + */ + + grabResult = 0; /* Needed only to prevent gcc + * compiler warnings. */ + for (numTries = 0; numTries < 10; numTries++) { + grabResult = XGrabPointer(dispPtr->display, winPtr->window, + True, ButtonPressMask|ButtonReleaseMask|ButtonMotionMask + |PointerMotionMask, GrabModeAsync, GrabModeAsync, None, + None, CurrentTime); + if (grabResult != AlreadyGrabbed) { + break; + } + Tcl_Sleep(100); + } + if (grabResult != 0) { + grabError: + if (grabResult == GrabNotViewable) { + interp->result = "grab failed: window not viewable"; + } else if (grabResult == AlreadyGrabbed) { + goto alreadyGrabbed; + } else if (grabResult == GrabFrozen) { + interp->result = "grab failed: keyboard or pointer frozen"; + } else if (grabResult == GrabInvalidTime) { + interp->result = "grab failed: invalid time"; + } else { + char msg[100]; + + sprintf(msg, "grab failed for unknown reason (code %d)", + grabResult); + Tcl_AppendResult(interp, msg, (char *) NULL); + } + return TCL_ERROR; + } + grabResult = XGrabKeyboard(dispPtr->display, Tk_WindowId(tkwin), + False, GrabModeAsync, GrabModeAsync, CurrentTime); + if (grabResult != 0) { + XUngrabPointer(dispPtr->display, CurrentTime); + goto grabError; + } + + /* + * Eat up any grab-related events generated by the server for the + * grab. There are several reasons for doing this: + * + * 1. We have to synthesize the events for local grabs anyway, since + * the server doesn't participate in them. + * 2. The server doesn't always generate the right events for global + * grabs (e.g. it generates events even if the current window is + * in the grab tree, which we don't want). + * 3. We want all the grab-related events to be processed immediately + * (before other events that are already queued); events coming + * from the server will be in the wrong place, but events we + * synthesize here will go to the front of the queue. + */ + + EatGrabEvents(dispPtr, serial); + } + + /* + * Synthesize leave events to move the pointer from its current window + * up to the lowest ancestor that it has in common with the grab window. + * However, only do this if the pointer is outside the grab window's + * subtree but inside the grab window's application. + */ + + if ((dispPtr->serverWinPtr != NULL) + && (dispPtr->serverWinPtr->mainPtr == winPtr->mainPtr)) { + for (winPtr2 = dispPtr->serverWinPtr; ; winPtr2 = winPtr2->parentPtr) { + if (winPtr2 == winPtr) { + break; + } + if (winPtr2 == NULL) { + MovePointer2(dispPtr->serverWinPtr, winPtr, NotifyGrab, 1, 0); + break; + } + } + } + QueueGrabWindowChange(dispPtr, winPtr); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_Ungrab -- + * + * Releases a grab on the mouse pointer and keyboard, if there + * is one set on the specified window. + * + * Results: + * None. + * + * Side effects: + * Pointer and keyboard events will start being delivered to other + * windows again. + * + *---------------------------------------------------------------------- + */ + +void +Tk_Ungrab(tkwin) + Tk_Window tkwin; /* Window whose grab should be + * released. */ +{ + TkDisplay *dispPtr; + TkWindow *grabWinPtr, *winPtr; + unsigned int serial; + + grabWinPtr = (TkWindow *) tkwin; + dispPtr = grabWinPtr->dispPtr; + if (grabWinPtr != dispPtr->eventualGrabWinPtr) { + return; + } + ReleaseButtonGrab(dispPtr); + QueueGrabWindowChange(dispPtr, (TkWindow *) NULL); + if (dispPtr->grabFlags & (GRAB_GLOBAL|GRAB_TEMP_GLOBAL)) { + dispPtr->grabFlags &= ~(GRAB_GLOBAL|GRAB_TEMP_GLOBAL); + serial = NextRequest(dispPtr->display); + XUngrabPointer(dispPtr->display, CurrentTime); + XUngrabKeyboard(dispPtr->display, CurrentTime); + EatGrabEvents(dispPtr, serial); + } + + /* + * Generate events to move the pointer back to the window where it + * really is. Some notes: + * 1. As with grabs, only do this if the "real" window is not a + * descendant of the grab window, since in this case the pointer + * is already where it's supposed to be. + * 2. If the "real" window is in some other application then don't + * generate any events at all, since everything's already been + * reported correctly. + * 3. Only generate enter events. Don't generate leave events, + * because we never told the lower-level windows that they + * had the pointer in the first place. + */ + + for (winPtr = dispPtr->serverWinPtr; ; winPtr = winPtr->parentPtr) { + if (winPtr == grabWinPtr) { + break; + } + if (winPtr == NULL) { + if ((dispPtr->serverWinPtr == NULL) || + (dispPtr->serverWinPtr->mainPtr == grabWinPtr->mainPtr)) { + MovePointer2(grabWinPtr, dispPtr->serverWinPtr, + NotifyUngrab, 0, 1); + } + break; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * ReleaseButtonGrab -- + * + * This procedure is called to release a simulated button grab, if + * there is one in effect. A button grab is present whenever + * dispPtr->buttonWinPtr is non-NULL or when the GRAB_TEMP_GLOBAL + * flag is set. + * + * Results: + * None. + * + * Side effects: + * DispPtr->buttonWinPtr is reset to NULL, and enter and leave + * events are generated if necessary to move the pointer from + * the button grab window to its current window. + * + *---------------------------------------------------------------------- + */ + +static void +ReleaseButtonGrab(dispPtr) + register TkDisplay *dispPtr; /* Display whose button grab is to be + * released. */ +{ + unsigned int serial; + + if (dispPtr->buttonWinPtr != NULL) { + if (dispPtr->buttonWinPtr != dispPtr->serverWinPtr) { + MovePointer2(dispPtr->buttonWinPtr, dispPtr->serverWinPtr, + NotifyUngrab, 1, 1); + } + dispPtr->buttonWinPtr = NULL; + } + if (dispPtr->grabFlags & GRAB_TEMP_GLOBAL) { + dispPtr->grabFlags &= ~GRAB_TEMP_GLOBAL; + serial = NextRequest(dispPtr->display); + XUngrabPointer(dispPtr->display, CurrentTime); + XUngrabKeyboard(dispPtr->display, CurrentTime); + EatGrabEvents(dispPtr, serial); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkPointerEvent -- + * + * This procedure is called for each pointer-related event, before + * the event has been processed. It does various things to make + * grabs work correctly. + * + * Results: + * If the return value is 1 it means the event should be processed + * (event handlers should be invoked). If the return value is 0 + * it means the event should be ignored in order to make grabs + * work correctly. In some cases this procedure modifies the event. + * + * Side effects: + * Grab state information may be updated. New events may also be + * pushed back onto the event queue to replace or augment the + * one passed in here. + * + *---------------------------------------------------------------------- + */ + +int +TkPointerEvent(eventPtr, winPtr) + register XEvent *eventPtr; /* Pointer to the event. */ + TkWindow *winPtr; /* Tk's information for window + * where event was reported. */ +{ + register TkWindow *winPtr2; + TkDisplay *dispPtr = winPtr->dispPtr; + unsigned int serial; + int outsideGrabTree = 0; + int ancestorOfGrab = 0; + int appGrabbed = 0; /* Non-zero means event is being + * reported to an application that is + * affected by the grab. */ + + /* + * Collect information about the grab (if any). + */ + + switch (TkGrabState(winPtr)) { + case TK_GRAB_IN_TREE: + appGrabbed = 1; + break; + case TK_GRAB_ANCESTOR: + appGrabbed = 1; + outsideGrabTree = 1; + ancestorOfGrab = 1; + break; + case TK_GRAB_EXCLUDED: + appGrabbed = 1; + outsideGrabTree = 1; + break; + } + + if ((eventPtr->type == EnterNotify) || (eventPtr->type == LeaveNotify)) { + /* + * Keep track of what window the mouse is *really* over. + * Any events that we generate have a special send_event value, + * which is detected below and used to ignore the event for + * purposes of setting serverWinPtr. + */ + + if (eventPtr->xcrossing.send_event != GENERATED_EVENT_MAGIC) { + if ((eventPtr->type == LeaveNotify) && + (winPtr->flags & TK_TOP_LEVEL)) { + dispPtr->serverWinPtr = NULL; + } else { + dispPtr->serverWinPtr = winPtr; + } + } + + /* + * When a grab is active, X continues to report enter and leave + * events for windows outside the tree of the grab window: + * 1. Detect these events and ignore them except for + * windows above the grab window. + * 2. Allow Enter and Leave events to pass through the + * windows above the grab window, but never let them + * end up with the pointer *in* one of those windows. + */ + + if (dispPtr->grabWinPtr != NULL) { + if (outsideGrabTree && appGrabbed) { + if (!ancestorOfGrab) { + return 0; + } + switch (eventPtr->xcrossing.detail) { + case NotifyInferior: + return 0; + case NotifyAncestor: + eventPtr->xcrossing.detail = NotifyVirtual; + break; + case NotifyNonlinear: + eventPtr->xcrossing.detail = NotifyNonlinearVirtual; + break; + } + } + + /* + * Make buttons have the same grab-like behavior inside a grab + * as they do outside a grab: do this by ignoring enter and + * leave events except for the window in which the button was + * pressed. + */ + + if ((dispPtr->buttonWinPtr != NULL) + && (winPtr != dispPtr->buttonWinPtr)) { + return 0; + } + } + return 1; + } + + if (!appGrabbed) { + return 1; + } + + if (eventPtr->type == MotionNotify) { + /* + * When grabs are active, X reports motion events relative to the + * window under the pointer. Instead, it should report the events + * relative to the window the button went down in, if there is a + * button down. Otherwise, if the pointer window is outside the + * subtree of the grab window, the events should be reported + * relative to the grab window. Otherwise, the event should be + * reported to the pointer window. + */ + + winPtr2 = winPtr; + if (dispPtr->buttonWinPtr != NULL) { + winPtr2 = dispPtr->buttonWinPtr; + } else if (outsideGrabTree || (dispPtr->serverWinPtr == NULL)) { + winPtr2 = dispPtr->grabWinPtr; + } + if (winPtr2 != winPtr) { + TkChangeEventWindow(eventPtr, winPtr2); + Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD); + return 0; + } + return 1; + } + + /* + * Process ButtonPress and ButtonRelease events: + * 1. Keep track of whether a button is down and what window it + * went down in. + * 2. If the first button goes down outside the grab tree, pretend + * it went down in the grab window. Note: it's important to + * redirect events to the grab window like this in order to make + * things like menus work, where button presses outside the + * grabbed menu need to be seen. An application can always + * ignore the events if they occur outside its window. + * 3. If a button press or release occurs outside the window where + * the first button was pressed, retarget the event so it's reported + * to the window where the first button was pressed. + * 4. If the last button is released in a window different than where + * the first button was pressed, generate Enter/Leave events to + * move the mouse from the button window to its current window. + * 5. If the grab is set at a time when a button is already down, or + * if the window where the button was pressed was deleted, then + * dispPtr->buttonWinPtr will stay NULL. Just forget about the + * auto-grab for the button press; events will go to whatever + * window contains the pointer. If this window isn't in the grab + * tree then redirect events to the grab window. + * 6. When a button is pressed during a local grab, the X server sets + * a grab of its own, since it doesn't even know about our local + * grab. This causes enter and leave events no longer to be + * generated in the same way as for global grabs. To eliminate this + * problem, set a temporary global grab when the first button goes + * down and release it when the last button comes up. + */ + + if ((eventPtr->type == ButtonPress) || (eventPtr->type == ButtonRelease)) { + winPtr2 = dispPtr->buttonWinPtr; + if (winPtr2 == NULL) { + if (outsideGrabTree) { + winPtr2 = dispPtr->grabWinPtr; /* Note 5. */ + } else { + winPtr2 = winPtr; /* Note 5. */ + } + } + if (eventPtr->type == ButtonPress) { + if ((eventPtr->xbutton.state & ALL_BUTTONS) == 0) { + if (outsideGrabTree) { + TkChangeEventWindow(eventPtr, dispPtr->grabWinPtr); + Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD); + return 0; /* Note 2. */ + } + if (!(dispPtr->grabFlags & GRAB_GLOBAL)) { /* Note 6. */ + serial = NextRequest(dispPtr->display); + if (XGrabPointer(dispPtr->display, + dispPtr->grabWinPtr->window, True, + ButtonPressMask|ButtonReleaseMask|ButtonMotionMask, + GrabModeAsync, GrabModeAsync, None, None, + CurrentTime) == 0) { + EatGrabEvents(dispPtr, serial); + if (XGrabKeyboard(dispPtr->display, winPtr->window, + False, GrabModeAsync, GrabModeAsync, + CurrentTime) == 0) { + dispPtr->grabFlags |= GRAB_TEMP_GLOBAL; + } else { + XUngrabPointer(dispPtr->display, CurrentTime); + } + } + } + dispPtr->buttonWinPtr = winPtr; + return 1; + } + } else { + if ((eventPtr->xbutton.state & ALL_BUTTONS) + == buttonStates[eventPtr->xbutton.button - Button1]) { + ReleaseButtonGrab(dispPtr); /* Note 4. */ + } + } + if (winPtr2 != winPtr) { + TkChangeEventWindow(eventPtr, winPtr2); + Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD); + return 0; /* Note 3. */ + } + } + + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * TkChangeEventWindow -- + * + * Given an event and a new window to which the event should be + * retargeted, modify fields of the event so that the event is + * properly retargeted to the new window. + * + * Results: + * The following fields of eventPtr are modified: window, + * subwindow, x, y, same_screen. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkChangeEventWindow(eventPtr, winPtr) + register XEvent *eventPtr; /* Event to retarget. Must have + * type ButtonPress, ButtonRelease, KeyPress, + * KeyRelease, MotionNotify, EnterNotify, + * or LeaveNotify. */ + TkWindow *winPtr; /* New target window for event. */ +{ + int x, y, sameScreen, bd; + register TkWindow *childPtr; + + eventPtr->xmotion.window = Tk_WindowId(winPtr); + if (eventPtr->xmotion.root == + RootWindow(winPtr->display, winPtr->screenNum)) { + Tk_GetRootCoords((Tk_Window) winPtr, &x, &y); + eventPtr->xmotion.x = eventPtr->xmotion.x_root - x; + eventPtr->xmotion.y = eventPtr->xmotion.y_root - y; + eventPtr->xmotion.subwindow = None; + for (childPtr = winPtr->childList; childPtr != NULL; + childPtr = childPtr->nextPtr) { + if (childPtr->flags & TK_TOP_LEVEL) { + continue; + } + x = eventPtr->xmotion.x - childPtr->changes.x; + y = eventPtr->xmotion.y - childPtr->changes.y; + bd = childPtr->changes.border_width; + if ((x >= -bd) && (y >= -bd) + && (x < (childPtr->changes.width + bd)) + && (y < (childPtr->changes.height + bd))) { + eventPtr->xmotion.subwindow = childPtr->window; + } + } + sameScreen = 1; + } else { + eventPtr->xmotion.x = 0; + eventPtr->xmotion.y = 0; + eventPtr->xmotion.subwindow = None; + sameScreen = 0; + } + if (eventPtr->type == MotionNotify) { + eventPtr->xmotion.same_screen = sameScreen; + } else { + eventPtr->xbutton.same_screen = sameScreen; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkInOutEvents -- + * + * This procedure synthesizes EnterNotify and LeaveNotify events + * to correctly transfer the pointer from one window to another. + * It can also be used to generate FocusIn and FocusOut events + * to move the input focus. + * + * Results: + * None. + * + * Side effects: + * Synthesized events may be pushed back onto the event queue. + * The event pointed to by eventPtr is modified. + * + *---------------------------------------------------------------------- + */ + +void +TkInOutEvents(eventPtr, sourcePtr, destPtr, leaveType, enterType, position) + XEvent *eventPtr; /* A template X event. Must have all fields + * properly set except for type, window, + * subwindow, x, y, detail, and same_screen + * (Not all of these fields are valid for + * FocusIn/FocusOut events; x_root and y_root + * must be valid for Enter/Leave events, even + * though x and y needn't be valid). */ + TkWindow *sourcePtr; /* Window that used to have the pointer or + * focus (NULL means it was not in a window + * managed by this process). */ + TkWindow *destPtr; /* Window that is to end up with the pointer + * or focus (NULL means it's not one managed + * by this process). */ + int leaveType; /* Type of events to generate for windows + * being left (LeaveNotify or FocusOut). 0 + * means don't generate leave events. */ + int enterType; /* Type of events to generate for windows + * being entered (EnterNotify or FocusIn). 0 + * means don't generate enter events. */ + Tcl_QueuePosition position; /* Position at which events are added to + * the system event queue. */ +{ + register TkWindow *winPtr; + int upLevels, downLevels, i, j, focus; + + /* + * There are four possible cases to deal with: + * + * 1. SourcePtr and destPtr are the same. There's nothing to do in + * this case. + * 2. SourcePtr is an ancestor of destPtr in the same top-level + * window. Must generate events down the window tree from source + * to dest. + * 3. DestPtr is an ancestor of sourcePtr in the same top-level + * window. Must generate events up the window tree from sourcePtr + * to destPtr. + * 4. All other cases. Must first generate events up the window tree + * from sourcePtr to its top-level, then down from destPtr's + * top-level to destPtr. This form is called "non-linear." + * + * The call to FindCommonAncestor separates these four cases and decides + * how many levels up and down events have to be generated for. + */ + + if (sourcePtr == destPtr) { + return; + } + if ((leaveType == FocusOut) || (enterType == FocusIn)) { + focus = 1; + } else { + focus = 0; + } + FindCommonAncestor(sourcePtr, destPtr, &upLevels, &downLevels); + + /* + * Generate enter/leave events and add them to the grab event queue. + */ + + +#define QUEUE(w, t, d) \ + if (w->window != None) { \ + eventPtr->type = t; \ + if (focus) { \ + eventPtr->xfocus.window = w->window; \ + eventPtr->xfocus.detail = d; \ + } else { \ + eventPtr->xcrossing.detail = d; \ + TkChangeEventWindow(eventPtr, w); \ + } \ + Tk_QueueWindowEvent(eventPtr, position); \ + } + + if (downLevels == 0) { + + /* + * SourcePtr is an inferior of destPtr. + */ + + if (leaveType != 0) { + QUEUE(sourcePtr, leaveType, NotifyAncestor); + for (winPtr = sourcePtr->parentPtr, i = upLevels-1; i > 0; + winPtr = winPtr->parentPtr, i--) { + QUEUE(winPtr, leaveType, NotifyVirtual); + } + } + if ((enterType != 0) && (destPtr != NULL)) { + QUEUE(destPtr, enterType, NotifyInferior); + } + } else if (upLevels == 0) { + + /* + * DestPtr is an inferior of sourcePtr. + */ + + if ((leaveType != 0) && (sourcePtr != NULL)) { + QUEUE(sourcePtr, leaveType, NotifyInferior); + } + if (enterType != 0) { + for (i = downLevels-1; i > 0; i--) { + for (winPtr = destPtr->parentPtr, j = 1; j < i; + winPtr = winPtr->parentPtr, j++) { + } + QUEUE(winPtr, enterType, NotifyVirtual); + } + if (destPtr != NULL) { + QUEUE(destPtr, enterType, NotifyAncestor); + } + } + } else { + + /* + * Non-linear: neither window is an inferior of the other. + */ + + if (leaveType != 0) { + QUEUE(sourcePtr, leaveType, NotifyNonlinear); + for (winPtr = sourcePtr->parentPtr, i = upLevels-1; i > 0; + winPtr = winPtr->parentPtr, i--) { + QUEUE(winPtr, leaveType, NotifyNonlinearVirtual); + } + } + if (enterType != 0) { + for (i = downLevels-1; i > 0; i--) { + for (winPtr = destPtr->parentPtr, j = 1; j < i; + winPtr = winPtr->parentPtr, j++) { + } + QUEUE(winPtr, enterType, NotifyNonlinearVirtual); + } + if (destPtr != NULL) { + QUEUE(destPtr, enterType, NotifyNonlinear); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * MovePointer2 -- + * + * This procedure synthesizes EnterNotify and LeaveNotify events + * to correctly transfer the pointer from one window to another. + * It is different from TkInOutEvents in that no template X event + * needs to be supplied; this procedure generates the template + * event and calls TkInOutEvents. + * + * Results: + * None. + * + * Side effects: + * Synthesized events may be pushed back onto the event queue. + * + *---------------------------------------------------------------------- + */ + +static void +MovePointer2(sourcePtr, destPtr, mode, leaveEvents, enterEvents) + TkWindow *sourcePtr; /* Window currently containing pointer (NULL + * means it's not one managed by this + * process). */ + TkWindow *destPtr; /* Window that is to end up containing the + * pointer (NULL means it's not one managed + * by this process). */ + int mode; /* Mode for enter/leave events, such as + * NotifyNormal or NotifyUngrab. */ + int leaveEvents; /* Non-zero means generate leave events for the + * windows being left. Zero means don't + * generate leave events. */ + int enterEvents; /* Non-zero means generate enter events for the + * windows being entered. Zero means don't + * generate enter events. */ +{ + XEvent event; + Window dummy1, dummy2; + int dummy3, dummy4; + TkWindow *winPtr; + + winPtr = sourcePtr; + if ((winPtr == NULL) || (winPtr->window == None)) { + winPtr = destPtr; + if ((winPtr == NULL) || (winPtr->window == None)) { + return; + } + } + + event.xcrossing.serial = LastKnownRequestProcessed( + winPtr->display); + event.xcrossing.send_event = GENERATED_EVENT_MAGIC; + event.xcrossing.display = winPtr->display; + event.xcrossing.root = RootWindow(winPtr->display, + winPtr->screenNum); + event.xcrossing.time = TkCurrentTime(winPtr->dispPtr); + XQueryPointer(winPtr->display, winPtr->window, &dummy1, &dummy2, + &event.xcrossing.x_root, &event.xcrossing.y_root, + &dummy3, &dummy4, &event.xcrossing.state); + event.xcrossing.mode = mode; + event.xcrossing.focus = False; + TkInOutEvents(&event, sourcePtr, destPtr, (leaveEvents) ? LeaveNotify : 0, + (enterEvents) ? EnterNotify : 0, TCL_QUEUE_MARK); +} + +/* + *---------------------------------------------------------------------- + * + * TkGrabDeadWindow -- + * + * This procedure is invoked whenever a window is deleted, so that + * grab-related cleanup can be performed. + * + * Results: + * None. + * + * Side effects: + * Various cleanups happen, such as generating events to move the + * pointer back to its "natural" window as if an ungrab had been + * done. See the code. + * + *---------------------------------------------------------------------- + */ + +void +TkGrabDeadWindow(winPtr) + register TkWindow *winPtr; /* Window that is in the process + * of being deleted. */ +{ + TkDisplay *dispPtr = winPtr->dispPtr; + + if (dispPtr->eventualGrabWinPtr == winPtr) { + /* + * Grab window was deleted. Release the grab. + */ + + Tk_Ungrab((Tk_Window) dispPtr->eventualGrabWinPtr); + } else if (dispPtr->buttonWinPtr == winPtr) { + ReleaseButtonGrab(dispPtr); + } + if (dispPtr->serverWinPtr == winPtr) { + if (winPtr->flags & TK_TOP_LEVEL) { + dispPtr->serverWinPtr = NULL; + } else { + dispPtr->serverWinPtr = winPtr->parentPtr; + } + } + if (dispPtr->grabWinPtr == winPtr) { + dispPtr->grabWinPtr = NULL; + } +} + +/* + *---------------------------------------------------------------------- + * + * EatGrabEvents -- + * + * This procedure is called to eliminate any Enter, Leave, + * FocusIn, or FocusOut events in the event queue for a + * display that have mode NotifyGrab or NotifyUngrab and + * have a serial number no less than a given value and are not + * generated by the grab module. + * + * Results: + * None. + * + * Side effects: + * DispPtr's display gets sync-ed, and some of the events get + * removed from the Tk event queue. + * + *---------------------------------------------------------------------- + */ + +static void +EatGrabEvents(dispPtr, serial) + TkDisplay *dispPtr; /* Display from which to consume events. */ + unsigned int serial; /* Only discard events that have a serial + * number at least this great. */ +{ + Tk_RestrictProc *oldProc; + GrabInfo info; + ClientData oldArg, dummy; + + info.display = dispPtr->display; + info.serial = serial; + TkpSync(info.display); + oldProc = Tk_RestrictEvents(GrabRestrictProc, (ClientData)&info, &oldArg); + while (Tcl_ServiceEvent(TCL_WINDOW_EVENTS)) { + } + Tk_RestrictEvents(oldProc, oldArg, &dummy); +} + +/* + *---------------------------------------------------------------------- + * + * GrabRestrictProc -- + * + * A Tk_RestrictProc used by EatGrabEvents to eliminate any + * Enter, Leave, FocusIn, or FocusOut events in the event queue + * for a display that has mode NotifyGrab or NotifyUngrab and + * have a serial number no less than a given value. + * + * Results: + * Returns either TK_DISCARD_EVENT or TK_DEFER_EVENT. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static Tk_RestrictAction +GrabRestrictProc(arg, eventPtr) + ClientData arg; + XEvent *eventPtr; +{ + GrabInfo *info = (GrabInfo *) arg; + int mode, diff; + + /* + * The diff caculation is trickier than it may seem. Don't forget + * that serial numbers can wrap around, so can't compare the two + * serial numbers directly. + */ + + diff = eventPtr->xany.serial - info->serial; + if ((eventPtr->type == EnterNotify) + || (eventPtr->type == LeaveNotify)) { + mode = eventPtr->xcrossing.mode; + } else if ((eventPtr->type == FocusIn) + || (eventPtr->type == FocusOut)) { + mode = eventPtr->xfocus.mode; + } else { + mode = NotifyNormal; + } + if ((info->display != eventPtr->xany.display) || (mode == NotifyNormal) + || (diff < 0)) { + return TK_DEFER_EVENT; + } else { + return TK_DISCARD_EVENT; + } +} + +/* + *---------------------------------------------------------------------- + * + * QueueGrabWindowChange -- + * + * This procedure queues a special event in the Tcl event queue, + * which will cause the "grabWinPtr" field for the display to get + * modified when the event is processed. This is needed to make + * sure that the grab window changes at the proper time relative + * to grab-related enter and leave events that are also in the + * queue. In particular, this approach works even when multiple + * grabs and ungrabs happen back-to-back. + * + * Results: + * None. + * + * Side effects: + * DispPtr->grabWinPtr will be modified later (by GrabWinEventProc) + * when the event is removed from the grab event queue. + * + *---------------------------------------------------------------------- + */ + +static void +QueueGrabWindowChange(dispPtr, grabWinPtr) + TkDisplay *dispPtr; /* Display on which to change the grab + * window. */ + TkWindow *grabWinPtr; /* Window that is to become the new grab + * window (may be NULL). */ +{ + NewGrabWinEvent *grabEvPtr; + + grabEvPtr = (NewGrabWinEvent *) ckalloc(sizeof(NewGrabWinEvent)); + grabEvPtr->header.proc = GrabWinEventProc; + grabEvPtr->dispPtr = dispPtr; + if (grabWinPtr == NULL) { + grabEvPtr->grabWindow = None; + } else { + grabEvPtr->grabWindow = grabWinPtr->window; + } + Tcl_QueueEvent(&grabEvPtr->header, TCL_QUEUE_MARK); + dispPtr->eventualGrabWinPtr = grabWinPtr; +} + +/* + *---------------------------------------------------------------------- + * + * GrabWinEventProc -- + * + * This procedure is invoked as a handler for Tcl_Events of type + * NewGrabWinEvent. It updates the current grab window field in + * a display. + * + * Results: + * Returns 1 if the event was processed, 0 if it should be deferred + * for processing later. + * + * Side effects: + * The grabWinPtr field is modified in the display associated with + * the event. + * + *---------------------------------------------------------------------- + */ + +static int +GrabWinEventProc(evPtr, flags) + Tcl_Event *evPtr; /* Event of type NewGrabWinEvent. */ + int flags; /* Flags argument to Tk_DoOneEvent: indicates + * what kinds of events are being processed + * right now. */ +{ + NewGrabWinEvent *grabEvPtr = (NewGrabWinEvent *) evPtr; + + grabEvPtr->dispPtr->grabWinPtr = (TkWindow *) Tk_IdToWindow( + grabEvPtr->dispPtr->display, grabEvPtr->grabWindow); + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * FindCommonAncestor -- + * + * Given two windows, this procedure finds their least common + * ancestor and also computes how many levels up this ancestor + * is from each of the original windows. + * + * Results: + * If the windows are in different applications or top-level + * windows, then NULL is returned and *countPtr1 and *countPtr2 + * are set to the depths of the two windows in their respective + * top-level windows (1 means the window is a top-level, 2 means + * its parent is a top-level, and so on). Otherwise, the return + * value is a pointer to the common ancestor and the counts are + * set to the distance of winPtr1 and winPtr2 from this ancestor + * (1 means they're children, 2 means grand-children, etc.). + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static TkWindow * +FindCommonAncestor(winPtr1, winPtr2, countPtr1, countPtr2) + TkWindow *winPtr1; /* First window. May be NULL. */ + TkWindow *winPtr2; /* Second window. May be NULL. */ + int *countPtr1; /* Store nesting level of winPtr1 within + * common ancestor here. */ + int *countPtr2; /* Store nesting level of winPtr2 within + * common ancestor here. */ +{ + register TkWindow *winPtr; + TkWindow *ancestorPtr; + int count1, count2, i; + + /* + * Mark winPtr1 and all of its ancestors with a special flag bit. + */ + + if (winPtr1 != NULL) { + for (winPtr = winPtr1; winPtr != NULL; winPtr = winPtr->parentPtr) { + winPtr->flags |= TK_GRAB_FLAG; + if (winPtr->flags & TK_TOP_LEVEL) { + break; + } + } + } + + /* + * Search upwards from winPtr2 until an ancestor of winPtr1 is + * found or a top-level window is reached. + */ + + winPtr = winPtr2; + count2 = 0; + ancestorPtr = NULL; + if (winPtr2 != NULL) { + for (; winPtr != NULL; count2++, winPtr = winPtr->parentPtr) { + if (winPtr->flags & TK_GRAB_FLAG) { + ancestorPtr = winPtr; + break; + } + if (winPtr->flags & TK_TOP_LEVEL) { + count2++; + break; + } + } + } + + /* + * Search upwards from winPtr1 again, clearing the flag bits and + * remembering how many levels up we had to go. + */ + + if (winPtr1 == NULL) { + count1 = 0; + } else { + count1 = -1; + for (i = 0, winPtr = winPtr1; winPtr != NULL; + i++, winPtr = winPtr->parentPtr) { + winPtr->flags &= ~TK_GRAB_FLAG; + if (winPtr == ancestorPtr) { + count1 = i; + } + if (winPtr->flags & TK_TOP_LEVEL) { + if (count1 == -1) { + count1 = i+1; + } + break; + } + } + } + + *countPtr1 = count1; + *countPtr2 = count2; + return ancestorPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkPositionInTree -- + * + * Compute where the given window is relative to a particular + * subtree of the window hierarchy. + * + * Results: + * + * Returns TK_GRAB_IN_TREE if the window is contained in the + * subtree. Returns TK_GRAB_ANCESTOR if the window is an + * ancestor of the subtree, in the same toplevel. Otherwise + * it returns TK_GRAB_EXCLUDED. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkPositionInTree(winPtr, treePtr) + TkWindow *winPtr; /* Window to be checked. */ + TkWindow *treePtr; /* Root of tree to compare against. */ +{ + TkWindow *winPtr2; + + for (winPtr2 = winPtr; winPtr2 != treePtr; + winPtr2 = winPtr2->parentPtr) { + if (winPtr2 == NULL) { + for (winPtr2 = treePtr; winPtr2 != NULL; + winPtr2 = winPtr2->parentPtr) { + if (winPtr2 == winPtr) { + return TK_GRAB_ANCESTOR; + } + if (winPtr2->flags & TK_TOP_LEVEL) { + break; + } + } + return TK_GRAB_EXCLUDED; + } + } + return TK_GRAB_IN_TREE; +} + +/* + *---------------------------------------------------------------------- + * + * TkGrabState -- + * + * Given a window, this procedure returns a value that indicates + * the grab state of the application relative to the window. + * + * Results: + * The return value is one of three things: + * TK_GRAB_NONE - no grab is in effect. + * TK_GRAB_IN_TREE - there is a grab in effect, and winPtr + * is in the grabbed subtree. + * TK_GRAB_ANCESTOR - there is a grab in effect; winPtr is + * an ancestor of the grabbed window, in + * the same toplevel. + * TK_GRAB_EXCLUDED - there is a grab in effect; winPtr is + * outside the tree of the grab and is not + * an ancestor of the grabbed window in the + * same toplevel. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkGrabState(winPtr) + TkWindow *winPtr; /* Window for which grab information is + * needed. */ +{ + TkWindow *grabWinPtr = winPtr->dispPtr->grabWinPtr; + + if (grabWinPtr == NULL) { + return TK_GRAB_NONE; + } + if ((winPtr->mainPtr != grabWinPtr->mainPtr) + && !(winPtr->dispPtr->grabFlags & GRAB_GLOBAL)) { + return TK_GRAB_NONE; + } + + return TkPositionInTree(winPtr, grabWinPtr); +} diff --git a/generic/tkGrid.c b/generic/tkGrid.c new file mode 100644 index 0000000..ea11a01 --- /dev/null +++ b/generic/tkGrid.c @@ -0,0 +1,2615 @@ +/* + * tkGrid.c -- + * + * Grid based geometry manager. + * + * Copyright (c) 1996-1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkGrid.c 1.39 97/10/10 10:12:03 + */ + +#include "tkInt.h" + +/* + * Convenience Macros + */ + +#ifdef MAX +# undef MAX +#endif +#define MAX(x,y) ((x) > (y) ? (x) : (y)) +#ifdef MIN +# undef MIN +#endif +#define MIN(x,y) ((x) > (y) ? (y) : (x)) + +#define COLUMN (1) /* working on column offsets */ +#define ROW (2) /* working on row offsets */ + +#define CHECK_ONLY (1) /* check max slot constraint */ +#define CHECK_SPACE (2) /* alloc more space, don't change max */ + +/* + * Pre-allocate enough row and column slots for "typical" sized tables + * this value should be chosen so by the time the extra malloc's are + * required, the layout calculations overwehlm them. [A "slot" contains + * information for either a row or column, depending upon the context.] + */ + +#define TYPICAL_SIZE 25 /* (arbitrary guess) */ +#define PREALLOC 10 /* extra slots to allocate */ + +/* + * Data structures are allocated dynamically to support arbitrary sized tables. + * However, the space is proportional to the highest numbered slot with + * some non-default property. This limit is used to head off mistakes and + * denial of service attacks by limiting the amount of storage required. + */ + +#define MAX_ELEMENT 10000 + +/* + * Special characters to support relative layouts. + */ + +#define REL_SKIP 'x' /* Skip this column. */ +#define REL_HORIZ '-' /* Extend previous widget horizontally. */ +#define REL_VERT '^' /* Extend widget from row above. */ + +/* + * Structure to hold information for grid masters. A slot is either + * a row or column. + */ + +typedef struct SlotInfo { + int minSize; /* The minimum size of this slot (in pixels). + * It is set via the rowconfigure or + * columnconfigure commands. */ + int weight; /* The resize weight of this slot. (0) means + * this slot doesn't resize. Extra space in + * the layout is given distributed among slots + * inproportion to their weights. */ + int pad; /* Extra padding, in pixels, required for + * this slot. This amount is "added" to the + * largest slave in the slot. */ + int offset; /* This is a cached value used for + * introspection. It is the pixel + * offset of the right or bottom edge + * of this slot from the beginning of the + * layout. */ + int temp; /* This is a temporary value used for + * calculating adjusted weights when + * shrinking the layout below its + * nominal size. */ +} SlotInfo; + +/* + * Structure to hold information during layout calculations. There + * is one of these for each slot, an array for each of the rows or columns. + */ + +typedef struct GridLayout { + struct Gridder *binNextPtr; /* The next slave window in this bin. + * Each bin contains a list of all + * slaves whose spans are >1 and whose + * right edges fall in this slot. */ + int minSize; /* Minimum size needed for this slot, + * in pixels. This is the space required + * to hold any slaves contained entirely + * in this slot, adjusted for any slot + * constrants, such as size or padding. */ + int pad; /* Padding needed for this slot */ + int weight; /* Slot weight, controls resizing. */ + int minOffset; /* The minimum offset, in pixels, from + * the beginning of the layout to the + * right/bottom edge of the slot calculated + * from top/left to bottom/right. */ + int maxOffset; /* The maximum offset, in pixels, from + * the beginning of the layout to the + * right-or-bottom edge of the slot calculated + * from bottom-or-right to top-or-left. */ +} GridLayout; + +/* + * Keep one of these for each geometry master. + */ + +typedef struct { + SlotInfo *columnPtr; /* Pointer to array of column constraints. */ + SlotInfo *rowPtr; /* Pointer to array of row constraints. */ + int columnEnd; /* The last column occupied by any slave. */ + int columnMax; /* The number of columns with constraints. */ + int columnSpace; /* The number of slots currently allocated for + * column constraints. */ + int rowEnd; /* The last row occupied by any slave. */ + int rowMax; /* The number of rows with constraints. */ + int rowSpace; /* The number of slots currently allocated + * for row constraints. */ + int startX; /* Pixel offset of this layout within its + * parent. */ + int startY; /* Pixel offset of this layout within its + * parent. */ +} GridMaster; + +/* + * For each window that the grid cares about (either because + * the window is managed by the grid or because the window + * has slaves that are managed by the grid), there is a + * structure of the following type: + */ + +typedef struct Gridder { + Tk_Window tkwin; /* Tk token for window. NULL means that + * the window has been deleted, but the + * gridder hasn't had a chance to clean up + * yet because the structure is still in + * use. */ + struct Gridder *masterPtr; /* Master window within which this window + * is managed (NULL means this window + * isn't managed by the gridder). */ + struct Gridder *nextPtr; /* Next window managed within same + * parent. List order doesn't matter. */ + struct Gridder *slavePtr; /* First in list of slaves managed + * inside this window (NULL means + * no grid slaves). */ + GridMaster *masterDataPtr; /* Additional data for geometry master. */ + int column, row; /* Location in the grid (starting + * from zero). */ + int numCols, numRows; /* Number of columns or rows this slave spans. + * Should be at least 1. */ + int padX, padY; /* Total additional pixels to leave around the + * window (half of this space is left on each + * side). This is space *outside* the window: + * we'll allocate extra space in frame but + * won't enlarge window). */ + int iPadX, iPadY; /* Total extra pixels to allocate inside the + * window (half this amount will appear on + * each side). */ + int sticky; /* which sides of its cavity this window + * sticks to. See below for definitions */ + int doubleBw; /* Twice the window's last known border + * width. If this changes, the window + * must be re-arranged within its parent. */ + int *abortPtr; /* If non-NULL, it means that there is a nested + * call to ArrangeGrid already working on + * this window. *abortPtr may be set to 1 to + * abort that nested call. This happens, for + * example, if tkwin or any of its slaves + * is deleted. */ + int flags; /* Miscellaneous flags; see below + * for definitions. */ + + /* + * These fields are used temporarily for layout calculations only. + */ + + struct Gridder *binNextPtr; /* Link to next span>1 slave in this bin. */ + int size; /* Nominal size (width or height) in pixels + * of the slave. This includes the padding. */ +} Gridder; + +/* Flag values for "sticky"ness The 16 combinations subsume the packer's + * notion of anchor and fill. + * + * STICK_NORTH This window sticks to the top of its cavity. + * STICK_EAST This window sticks to the right edge of its cavity. + * STICK_SOUTH This window sticks to the bottom of its cavity. + * STICK_WEST This window sticks to the left edge of its cavity. + */ + +#define STICK_NORTH 1 +#define STICK_EAST 2 +#define STICK_SOUTH 4 +#define STICK_WEST 8 + +/* + * Flag values for Grid structures: + * + * REQUESTED_RELAYOUT: 1 means a Tcl_DoWhenIdle request + * has already been made to re-arrange + * all the slaves of this window. + * + * DONT_PROPAGATE: 1 means don't set this window's requested + * size. 0 means if this window is a master + * then Tk will set its requested size to fit + * the needs of its slaves. + */ + +#define REQUESTED_RELAYOUT 1 +#define DONT_PROPAGATE 2 + +/* + * Hash table used to map from Tk_Window tokens to corresponding + * Grid structures: + */ + +static Tcl_HashTable gridHashTable; +static int initialized = 0; + +/* + * Prototypes for procedures used only in this file: + */ + +static void AdjustForSticky _ANSI_ARGS_((Gridder *slavePtr, int *xPtr, + int *yPtr, int *widthPtr, int *heightPtr)); +static int AdjustOffsets _ANSI_ARGS_((int width, + int elements, SlotInfo *slotPtr)); +static void ArrangeGrid _ANSI_ARGS_((ClientData clientData)); +static int CheckSlotData _ANSI_ARGS_((Gridder *masterPtr, int slot, + int slotType, int checkOnly)); +static int ConfigureSlaves _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, int argc, char *argv[])); +static void DestroyGrid _ANSI_ARGS_((char *memPtr)); +static Gridder *GetGrid _ANSI_ARGS_((Tk_Window tkwin)); +static void GridStructureProc _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +static void GridLostSlaveProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); +static void GridReqProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); +static void InitMasterData _ANSI_ARGS_((Gridder *masterPtr)); +static int ResolveConstraints _ANSI_ARGS_((Gridder *gridPtr, + int rowOrColumn, int maxOffset)); +static void SetGridSize _ANSI_ARGS_((Gridder *gridPtr)); +static void StickyToString _ANSI_ARGS_((int flags, char *result)); +static int StringToSticky _ANSI_ARGS_((char *string)); +static void Unlink _ANSI_ARGS_((Gridder *gridPtr)); + +static Tk_GeomMgr gridMgrType = { + "grid", /* name */ + GridReqProc, /* requestProc */ + GridLostSlaveProc, /* lostSlaveProc */ +}; + +/* + *-------------------------------------------------------------- + * + * Tk_GridCmd -- + * + * This procedure is invoked to process the "grid" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_GridCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + Gridder *masterPtr; /* master grid record */ + GridMaster *gridPtr; /* pointer to grid data */ + size_t length; /* streing length of argument */ + char c; /* 1st character of argument */ + + if ((argc >= 2) && ((argv[1][0] == '.') || (argv[1][0] == REL_SKIP) || + (argv[1][0] == REL_VERT))) { + return ConfigureSlaves(interp, tkwin, argc-1, argv+1); + } + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option arg ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + + if ((c == 'b') && (strncmp(argv[1], "bbox", length) == 0)) { + Tk_Window master; + int row, column; /* origin for bounding box */ + int row2, column2; /* end of bounding box */ + int endX, endY; /* last column/row in the layout */ + int x=0, y=0; /* starting pixels for this bounding box */ + int width, height; /* size of the bounding box */ + + if (argc!=3 && argc != 5 && argc != 7) { + Tcl_AppendResult(interp, "wrong number of arguments: ", + "must be \"",argv[0], + " bbox master ?column row ?column row??\"", + (char *) NULL); + return TCL_ERROR; + } + + master = Tk_NameToWindow(interp, argv[2], tkwin); + if (master == NULL) { + return TCL_ERROR; + } + masterPtr = GetGrid(master); + + if (argc >= 5) { + if (Tcl_GetInt(interp, argv[3], &column) != TCL_OK) { + return TCL_ERROR; + } + if (Tcl_GetInt(interp, argv[4], &row) != TCL_OK) { + return TCL_ERROR; + } + column2 = column; + row2 = row; + } + + if (argc == 7) { + if (Tcl_GetInt(interp, argv[5], &column2) != TCL_OK) { + return TCL_ERROR; + } + if (Tcl_GetInt(interp, argv[6], &row2) != TCL_OK) { + return TCL_ERROR; + } + } + + gridPtr = masterPtr->masterDataPtr; + if (gridPtr == NULL) { + sprintf(interp->result, "%d %d %d %d",0,0,0,0); + return(TCL_OK); + } + + SetGridSize(masterPtr); + endX = MAX(gridPtr->columnEnd, gridPtr->columnMax); + endY = MAX(gridPtr->rowEnd, gridPtr->rowMax); + + if ((endX == 0) || (endY == 0)) { + sprintf(interp->result, "%d %d %d %d",0,0,0,0); + return(TCL_OK); + } + if (argc == 3) { + row = column = 0; + row2 = endY; + column2 = endX; + } + + if (column > column2) { + int temp = column; + column = column2, column2 = temp; + } + if (row > row2) { + int temp = row; + row = row2, row2 = temp; + } + + if (column > 0 && column < endX) { + x = gridPtr->columnPtr[column-1].offset; + } else if (column > 0) { + x = gridPtr->columnPtr[endX-1].offset; + } + + if (row > 0 && row < endY) { + y = gridPtr->rowPtr[row-1].offset; + } else if (row > 0) { + y = gridPtr->rowPtr[endY-1].offset; + } + + if (column2 < 0) { + width = 0; + } else if (column2 >= endX) { + width = gridPtr->columnPtr[endX-1].offset - x; + } else { + width = gridPtr->columnPtr[column2].offset - x; + } + + if (row2 < 0) { + height = 0; + } else if (row2 >= endY) { + height = gridPtr->rowPtr[endY-1].offset - y; + } else { + height = gridPtr->rowPtr[row2].offset - y; + } + + sprintf(interp->result, "%d %d %d %d", + x + gridPtr->startX, y + gridPtr->startY, width, height); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0)) { + if (argv[2][0] != '.') { + Tcl_AppendResult(interp, "bad argument \"", argv[2], + "\": must be name of window", (char *) NULL); + return TCL_ERROR; + } + return ConfigureSlaves(interp, tkwin, argc-2, argv+2); + } else if (((c == 'f') && (strncmp(argv[1], "forget", length) == 0)) || + ((c == 'r') && (strncmp(argv[1], "remove", length) == 0))) { + Tk_Window slave; + Gridder *slavePtr; + int i; + + for (i = 2; i < argc; i++) { + slave = Tk_NameToWindow(interp, argv[i], tkwin); + if (slave == NULL) { + return TCL_ERROR; + } + slavePtr = GetGrid(slave); + if (slavePtr->masterPtr != NULL) { + + /* + * For "forget", reset all the settings to their defaults + */ + + if (c == 'f') { + slavePtr->column = slavePtr->row = -1; + slavePtr->numCols = 1; + slavePtr->numRows = 1; + slavePtr->padX = slavePtr->padY = 0; + slavePtr->iPadX = slavePtr->iPadY = 0; + slavePtr->doubleBw = 2*Tk_Changes(tkwin)->border_width; + slavePtr->flags = 0; + slavePtr->sticky = 0; + } + Tk_ManageGeometry(slave, (Tk_GeomMgr *) NULL, + (ClientData) NULL); + if (slavePtr->masterPtr->tkwin != Tk_Parent(slavePtr->tkwin)) { + Tk_UnmaintainGeometry(slavePtr->tkwin, + slavePtr->masterPtr->tkwin); + } + Unlink(slavePtr); + Tk_UnmapWindow(slavePtr->tkwin); + } + } + } else if ((c == 'i') && (strncmp(argv[1], "info", length) == 0)) { + register Gridder *slavePtr; + Tk_Window slave; + char buffer[70]; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " info window\"", (char *) NULL); + return TCL_ERROR; + } + slave = Tk_NameToWindow(interp, argv[2], tkwin); + if (slave == NULL) { + return TCL_ERROR; + } + slavePtr = GetGrid(slave); + if (slavePtr->masterPtr == NULL) { + interp->result[0] = '\0'; + return TCL_OK; + } + + Tcl_AppendElement(interp, "-in"); + Tcl_AppendElement(interp, Tk_PathName(slavePtr->masterPtr->tkwin)); + sprintf(buffer, " -column %d -row %d -columnspan %d -rowspan %d", + slavePtr->column, slavePtr->row, + slavePtr->numCols, slavePtr->numRows); + Tcl_AppendResult(interp, buffer, (char *) NULL); + sprintf(buffer, " -ipadx %d -ipady %d -padx %d -pady %d", + slavePtr->iPadX/2, slavePtr->iPadY/2, slavePtr->padX/2, + slavePtr->padY/2); + Tcl_AppendResult(interp, buffer, (char *) NULL); + StickyToString(slavePtr->sticky,buffer); + Tcl_AppendResult(interp, " -sticky ", buffer, (char *) NULL); + } else if((c == 'l') && (strncmp(argv[1], "location", length) == 0)) { + Tk_Window master; + register SlotInfo *slotPtr; + int x, y; /* Offset in pixels, from edge of parent. */ + int i, j; /* Corresponding column and row indeces. */ + int endX, endY; /* end of grid */ + + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " location master x y\"", (char *)NULL); + return TCL_ERROR; + } + + master = Tk_NameToWindow(interp, argv[2], tkwin); + if (master == NULL) { + return TCL_ERROR; + } + + if (Tk_GetPixels(interp, master, argv[3], &x) != TCL_OK) { + return TCL_ERROR; + } + if (Tk_GetPixels(interp, master, argv[4], &y) != TCL_OK) { + return TCL_ERROR; + } + + masterPtr = GetGrid(master); + if (masterPtr->masterDataPtr == NULL) { + sprintf(interp->result, "%d %d", -1, -1); + return TCL_OK; + } + gridPtr = masterPtr->masterDataPtr; + + /* + * Update any pending requests. This is not always the + * steady state value, as more configure events could be in + * the pipeline, but its as close as its easy to get. + */ + + while (masterPtr->flags & REQUESTED_RELAYOUT) { + Tk_CancelIdleCall(ArrangeGrid, (ClientData) masterPtr); + ArrangeGrid ((ClientData) masterPtr); + } + SetGridSize(masterPtr); + endX = MAX(gridPtr->columnEnd, gridPtr->columnMax); + endY = MAX(gridPtr->rowEnd, gridPtr->rowMax); + + slotPtr = masterPtr->masterDataPtr->columnPtr; + if (x < masterPtr->masterDataPtr->startX) { + i = -1; + } else { + x -= masterPtr->masterDataPtr->startX; + for (i=0;slotPtr[i].offset < x && i < endX; i++) { + /* null body */ + } + } + + slotPtr = masterPtr->masterDataPtr->rowPtr; + if (y < masterPtr->masterDataPtr->startY) { + j = -1; + } else { + y -= masterPtr->masterDataPtr->startY; + for (j=0;slotPtr[j].offset < y && j < endY; j++) { + /* null body */ + } + } + + sprintf(interp->result, "%d %d", i, j); + } else if ((c == 'p') && (strncmp(argv[1], "propagate", length) == 0)) { + Tk_Window master; + int propagate; + + if (argc > 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " propagate window ?boolean?\"", + (char *) NULL); + return TCL_ERROR; + } + master = Tk_NameToWindow(interp, argv[2], tkwin); + if (master == NULL) { + return TCL_ERROR; + } + masterPtr = GetGrid(master); + if (argc == 3) { + interp->result = (masterPtr->flags & DONT_PROPAGATE) ? "0" : "1"; + return TCL_OK; + } + if (Tcl_GetBoolean(interp, argv[3], &propagate) != TCL_OK) { + return TCL_ERROR; + } + if ((!propagate) ^ (masterPtr->flags&DONT_PROPAGATE)) { + masterPtr->flags ^= DONT_PROPAGATE; + + /* + * Re-arrange the master to allow new geometry information to + * propagate upwards to the master's master. + */ + + if (masterPtr->abortPtr != NULL) { + *masterPtr->abortPtr = 1; + } + if (!(masterPtr->flags & REQUESTED_RELAYOUT)) { + masterPtr->flags |= REQUESTED_RELAYOUT; + Tcl_DoWhenIdle(ArrangeGrid, (ClientData) masterPtr); + } + } + } else if ((c == 's') && (strncmp(argv[1], "size", length) == 0) + && (length > 1)) { + Tk_Window master; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " size window\"", (char *) NULL); + return TCL_ERROR; + } + master = Tk_NameToWindow(interp, argv[2], tkwin); + if (master == NULL) { + return TCL_ERROR; + } + masterPtr = GetGrid(master); + + if (masterPtr->masterDataPtr != NULL) { + SetGridSize(masterPtr); + gridPtr = masterPtr->masterDataPtr; + sprintf(interp->result, "%d %d", + MAX(gridPtr->columnEnd, gridPtr->columnMax), + MAX(gridPtr->rowEnd, gridPtr->rowMax)); + } else { + sprintf(interp->result, "%d %d",0, 0); + } + } else if ((c == 's') && (strncmp(argv[1], "slaves", length) == 0) + && (length > 1)) { + Tk_Window master; + Gridder *slavePtr; + int i, value; + int row = -1, column = -1; + + if ((argc < 3) || ((argc%2) == 0)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " slaves window ?-option value...?\"", + (char *) NULL); + return TCL_ERROR; + } + + for (i=3; i<argc; i+=2) { + length = strlen(argv[i]); + if ((*argv[i] != '-') || (length < 2)) { + Tcl_AppendResult(interp, "invalid args: should be \"", + argv[0], " slaves window ?-option value...?\"", + (char *) NULL); + return TCL_ERROR; + } + if (Tcl_GetInt(interp, argv[i+1], &value) != TCL_OK) { + return TCL_ERROR; + } + if (value < 0) { + Tcl_AppendResult(interp, argv[i], + " is an invalid value: should NOT be < 0", + (char *) NULL); + return TCL_ERROR; + } + if (strncmp(argv[i], "-column", length) == 0) { + column = value; + } else if (strncmp(argv[i], "-row", length) == 0) { + row = value; + } else { + Tcl_AppendResult(interp, argv[i], + " is an invalid option: should be \"", + "-row, -column\"", + (char *) NULL); + return TCL_ERROR; + } + } + master = Tk_NameToWindow(interp, argv[2], tkwin); + if (master == NULL) { + return TCL_ERROR; + } + masterPtr = GetGrid(master); + + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + if (column>=0 && (slavePtr->column > column + || slavePtr->column+slavePtr->numCols-1 < column)) { + continue; + } + if (row>=0 && (slavePtr->row > row || + slavePtr->row+slavePtr->numRows-1 < row)) { + continue; + } + Tcl_AppendElement(interp, Tk_PathName(slavePtr->tkwin)); + } + + /* + * Sample argument combinations: + * grid columnconfigure <master> <index> -option + * grid columnconfigure <master> <index> -option value -option value + * grid rowconfigure <master> <index> + * grid rowconfigure <master> <index> -option + * grid rowconfigure <master> <index> -option value -option value. + */ + + } else if(((c == 'c') && (strncmp(argv[1], "columnconfigure", length) == 0) + && (length >= 3)) || + ((c == 'r') && (strncmp(argv[1], "rowconfigure", length) == 0) + && (length >=2))) { + Tk_Window master; + SlotInfo *slotPtr = NULL; + int slot; /* the column or row number */ + size_t length; /* the # of chars in the "-option" string */ + int slotType; /* COLUMN or ROW */ + int size; /* the configuration value */ + int checkOnly; /* check the size only */ + int argcPtr; /* Number of items in index list */ + char **argvPtr; /* array of indeces */ + char **indexP; /* String value of current index list item. */ + int ok; /* temporary TCL result code */ + int i; + + if (((argc%2 != 0) && (argc>6)) || (argc < 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ", argv[1], " master index ?-option value...?\"", + (char *)NULL); + return TCL_ERROR; + } + + master = Tk_NameToWindow(interp, argv[2], tkwin); + if (master == NULL) { + return TCL_ERROR; + } + + if (Tcl_SplitList(interp, argv[3], &argcPtr, &argvPtr) != TCL_OK) { + return TCL_ERROR; + } + + checkOnly = ((argc == 4) || (argc == 5)); + masterPtr = GetGrid(master); + slotType = (c == 'c') ? COLUMN : ROW; + if (checkOnly && argcPtr > 1) { + Tcl_AppendResult(interp, argv[3], + " must be a single element.", (char *) NULL); + Tcl_Free((char *)argvPtr); + return TCL_ERROR; + } + for (indexP=argvPtr; *indexP != NULL; indexP++) { + if (Tcl_GetInt(interp, *indexP, &slot) != TCL_OK) { + Tcl_Free((char *)argvPtr); + return TCL_ERROR; + } + ok = CheckSlotData(masterPtr, slot, slotType, checkOnly); + if ((ok!=TCL_OK) && ((argc<4) || (argc>5))) { + Tcl_AppendResult(interp, argv[0], + " ", argv[1], ": \"", *argvPtr,"\" is out of range", + (char *) NULL); + Tcl_Free((char *)argvPtr); + return TCL_ERROR; + } else if (ok == TCL_OK) { + slotPtr = (slotType == COLUMN) ? + masterPtr->masterDataPtr->columnPtr : + masterPtr->masterDataPtr->rowPtr; + } + + /* + * Return all of the options for this row or column. If the + * request is out of range, return all 0's. + */ + + if (argc == 4) { + Tcl_Free((char *)argvPtr); + } + if ((argc == 4) && (ok == TCL_OK)) { + sprintf(interp->result,"-minsize %d -pad %d -weight %d", + slotPtr[slot].minSize,slotPtr[slot].pad, + slotPtr[slot].weight); + return (TCL_OK); + } else if (argc == 4) { + sprintf(interp->result,"-minsize %d -pad %d -weight %d", 0,0,0); + return (TCL_OK); + } + + /* + * Loop through each option value pair, setting the values as required. + * If only one option is given, with no value, the current value is + * returned. + */ + + for (i=4; i<argc; i+=2) { + length = strlen(argv[i]); + if ((*argv[i] != '-') || length < 2) { + Tcl_AppendResult(interp, "invalid arg \"", + argv[i], "\" :expecting -minsize, -pad, or -weight.", + (char *) NULL); + Tcl_Free((char *)argvPtr); + return TCL_ERROR; + } + if (strncmp(argv[i], "-minsize", length) == 0) { + if (argc == 5) { + int value = ok == TCL_OK ? slotPtr[slot].minSize : 0; + sprintf(interp->result,"%d",value); + } else if (Tk_GetPixels(interp, master, argv[i+1], &size) + != TCL_OK) { + Tcl_Free((char *)argvPtr); + return TCL_ERROR; + } else { + slotPtr[slot].minSize = size; + } + } + else if (strncmp(argv[i], "-weight", length) == 0) { + int wt; + if (argc == 5) { + int value = ok == TCL_OK ? slotPtr[slot].weight : 0; + sprintf(interp->result,"%d",value); + } else if (Tcl_GetInt(interp, argv[i+1], &wt) != TCL_OK) { + Tcl_Free((char *)argvPtr); + return TCL_ERROR; + } else if (wt < 0) { + Tcl_AppendResult(interp, "invalid arg \"", argv[i], + "\": should be non-negative", (char *) NULL); + Tcl_Free((char *)argvPtr); + return TCL_ERROR; + } else { + slotPtr[slot].weight = wt; + } + } + else if (strncmp(argv[i], "-pad", length) == 0) { + if (argc == 5) { + int value = ok == TCL_OK ? slotPtr[slot].pad : 0; + sprintf(interp->result,"%d",value); + } else if (Tk_GetPixels(interp, master, argv[i+1], &size) + != TCL_OK) { + Tcl_Free((char *)argvPtr); + return TCL_ERROR; + } else if (size < 0) { + Tcl_AppendResult(interp, "invalid arg \"", argv[i], + "\": should be non-negative", (char *) NULL); + Tcl_Free((char *)argvPtr); + return TCL_ERROR; + } else { + slotPtr[slot].pad = size; + } + } else { + Tcl_AppendResult(interp, "invalid arg \"", + argv[i], "\": expecting -minsize, -pad, or -weight.", + (char *) NULL); + Tcl_Free((char *)argvPtr); + return TCL_ERROR; + } + } + } + Tcl_Free((char *)argvPtr); + + /* + * If we changed a property, re-arrange the table, + * and check for constraint shrinkage. + */ + + if (argc != 5) { + if (slotType == ROW) { + int last = masterPtr->masterDataPtr->rowMax - 1; + while ((last >= 0) && (slotPtr[last].weight == 0) + && (slotPtr[last].pad == 0) + && (slotPtr[last].minSize == 0)) { + last--; + } + masterPtr->masterDataPtr->rowMax = last+1; + } else { + int last = masterPtr->masterDataPtr->columnMax - 1; + while ((last >= 0) && (slotPtr[last].weight == 0) + && (slotPtr[last].pad == 0) + && (slotPtr[last].minSize == 0)) { + last--; + } + masterPtr->masterDataPtr->columnMax = last + 1; + } + + if (masterPtr->abortPtr != NULL) { + *masterPtr->abortPtr = 1; + } + if (!(masterPtr->flags & REQUESTED_RELAYOUT)) { + masterPtr->flags |= REQUESTED_RELAYOUT; + Tcl_DoWhenIdle(ArrangeGrid, (ClientData) masterPtr); + } + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be bbox, columnconfigure, configure, forget, info, ", + "location, propagate, remove, rowconfigure, size, or slaves.", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * GridReqProc -- + * + * This procedure is invoked by Tk_GeometryRequest for + * windows managed by the grid. + * + * Results: + * None. + * + * Side effects: + * Arranges for tkwin, and all its managed siblings, to + * be re-arranged at the next idle point. + * + *-------------------------------------------------------------- + */ + +static void +GridReqProc(clientData, tkwin) + ClientData clientData; /* Grid's information about + * window that got new preferred + * geometry. */ + Tk_Window tkwin; /* Other Tk-related information + * about the window. */ +{ + register Gridder *gridPtr = (Gridder *) clientData; + + gridPtr = gridPtr->masterPtr; + if (!(gridPtr->flags & REQUESTED_RELAYOUT)) { + gridPtr->flags |= REQUESTED_RELAYOUT; + Tcl_DoWhenIdle(ArrangeGrid, (ClientData) gridPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * GridLostSlaveProc -- + * + * This procedure is invoked by Tk whenever some other geometry + * claims control over a slave that used to be managed by us. + * + * Results: + * None. + * + * Side effects: + * Forgets all grid-related information about the slave. + * + *-------------------------------------------------------------- + */ + +static void +GridLostSlaveProc(clientData, tkwin) + ClientData clientData; /* Grid structure for slave window that + * was stolen away. */ + Tk_Window tkwin; /* Tk's handle for the slave window. */ +{ + register Gridder *slavePtr = (Gridder *) clientData; + + if (slavePtr->masterPtr->tkwin != Tk_Parent(slavePtr->tkwin)) { + Tk_UnmaintainGeometry(slavePtr->tkwin, slavePtr->masterPtr->tkwin); + } + Unlink(slavePtr); + Tk_UnmapWindow(slavePtr->tkwin); +} + +/* + *-------------------------------------------------------------- + * + * AdjustOffsets -- + * + * This procedure adjusts the size of the layout to fit in the + * space provided. If it needs more space, the extra is added + * according to the weights. If it needs less, the space is removed + * according to the weights, but at no time does the size drop below + * the minsize specified for that slot. + * + * Results: + * The initial offset of the layout, + * if all the weights are zero, else 0. + * + * Side effects: + * The slot offsets are modified to shrink the layout. + * + *-------------------------------------------------------------- + */ + +static int +AdjustOffsets(size, slots, slotPtr) + int size; /* The total layout size (in pixels). */ + int slots; /* Number of slots. */ + register SlotInfo *slotPtr; /* Pointer to slot array. */ +{ + register int slot; /* Current slot. */ + int diff; /* Extra pixels needed to add to the layout. */ + int totalWeight = 0; /* Sum of the weights for all the slots. */ + int weight = 0; /* Sum of the weights so far. */ + int minSize = 0; /* Minimum possible layout size. */ + int newDiff; /* The most pixels that can be added on + * the current pass. */ + + diff = size - slotPtr[slots-1].offset; + + /* + * The layout is already the correct size; all done. + */ + + if (diff == 0) { + return(0); + } + + /* + * If all the weights are zero, center the layout in its parent if + * there is extra space, else clip on the bottom/right. + */ + + for (slot=0; slot < slots; slot++) { + totalWeight += slotPtr[slot].weight; + } + + if (totalWeight == 0 ) { + return(diff > 0 ? diff/2 : 0); + } + + /* + * Add extra space according to the slot weights. This is done + * cumulatively to prevent round-off error accumulation. + */ + + if (diff > 0) { + for (weight=slot=0; slot < slots; slot++) { + weight += slotPtr[slot].weight; + slotPtr[slot].offset += diff * weight / totalWeight; + } + return(0); + } + + /* + * The layout must shrink below its requested size. Compute the + * minimum possible size by looking at the slot minSizes. + */ + + for (slot=0; slot < slots; slot++) { + if (slotPtr[slot].weight > 0) { + minSize += slotPtr[slot].minSize; + } else if (slot > 0) { + minSize += slotPtr[slot].offset - slotPtr[slot-1].offset; + } else { + minSize += slotPtr[slot].offset; + } + } + + /* + * If the requested size is less than the minimum required size, + * set the slot sizes to their minimum values, then clip on the + * bottom/right. + */ + + if (size <= minSize) { + int offset = 0; + for (slot=0; slot < slots; slot++) { + if (slotPtr[slot].weight > 0) { + offset += slotPtr[slot].minSize; + } else if (slot > 0) { + offset += slotPtr[slot].offset - slotPtr[slot-1].offset; + } else { + offset += slotPtr[slot].offset; + } + slotPtr[slot].offset = offset; + } + return(0); + } + + /* + * Remove space from slots according to their weights. The weights + * get renormalized anytime a slot shrinks to its minimum size. + */ + + while (diff < 0) { + + /* + * Find the total weight for the shrinkable slots. + */ + + for (totalWeight=slot=0; slot < slots; slot++) { + int current = (slot == 0) ? slotPtr[slot].offset : + slotPtr[slot].offset - slotPtr[slot-1].offset; + if (current > slotPtr[slot].minSize) { + totalWeight += slotPtr[slot].weight; + slotPtr[slot].temp = slotPtr[slot].weight; + } else { + slotPtr[slot].temp = 0; + } + } + if (totalWeight == 0) { + break; + } + + /* + * Find the maximum amount of space we can distribute this pass. + */ + + newDiff = diff; + for (slot = 0; slot < slots; slot++) { + int current; /* current size of this slot */ + int maxDiff; /* max diff that would cause + * this slot to equal its minsize */ + if (slotPtr[slot].temp == 0) { + continue; + } + current = (slot == 0) ? slotPtr[slot].offset : + slotPtr[slot].offset - slotPtr[slot-1].offset; + maxDiff = totalWeight * (slotPtr[slot].minSize - current) + / slotPtr[slot].temp; + if (maxDiff > newDiff) { + newDiff = maxDiff; + } + } + + /* + * Now distribute the space. + */ + + for (weight=slot=0; slot < slots; slot++) { + weight += slotPtr[slot].temp; + slotPtr[slot].offset += newDiff * weight / totalWeight; + } + diff -= newDiff; + } + return(0); +} + +/* + *-------------------------------------------------------------- + * + * AdjustForSticky -- + * + * This procedure adjusts the size of a slave in its cavity based + * on its "sticky" flags. + * + * Results: + * The input x, y, width, and height are changed to represent the + * desired coordinates of the slave. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static void +AdjustForSticky(slavePtr, xPtr, yPtr, widthPtr, heightPtr) + Gridder *slavePtr; /* Slave window to arrange in its cavity. */ + int *xPtr; /* Pixel location of the left edge of the cavity. */ + int *yPtr; /* Pixel location of the top edge of the cavity. */ + int *widthPtr; /* Width of the cavity (in pixels). */ + int *heightPtr; /* Height of the cavity (in pixels). */ +{ + int diffx=0; /* Cavity width - slave width. */ + int diffy=0; /* Cavity hight - slave height. */ + int sticky = slavePtr->sticky; + + *xPtr += slavePtr->padX/2; + *widthPtr -= slavePtr->padX; + *yPtr += slavePtr->padY/2; + *heightPtr -= slavePtr->padY; + + if (*widthPtr > (Tk_ReqWidth(slavePtr->tkwin) + slavePtr->iPadX)) { + diffx = *widthPtr - (Tk_ReqWidth(slavePtr->tkwin) + slavePtr->iPadX); + *widthPtr = Tk_ReqWidth(slavePtr->tkwin) + slavePtr->iPadX; + } + + if (*heightPtr > (Tk_ReqHeight(slavePtr->tkwin) + slavePtr->iPadY)) { + diffy = *heightPtr - (Tk_ReqHeight(slavePtr->tkwin) + slavePtr->iPadY); + *heightPtr = Tk_ReqHeight(slavePtr->tkwin) + slavePtr->iPadY; + } + + if (sticky&STICK_EAST && sticky&STICK_WEST) { + *widthPtr += diffx; + } + if (sticky&STICK_NORTH && sticky&STICK_SOUTH) { + *heightPtr += diffy; + } + if (!(sticky&STICK_WEST)) { + *xPtr += (sticky&STICK_EAST) ? diffx : diffx/2; + } + if (!(sticky&STICK_NORTH)) { + *yPtr += (sticky&STICK_SOUTH) ? diffy : diffy/2; + } +} + +/* + *-------------------------------------------------------------- + * + * ArrangeGrid -- + * + * This procedure is invoked (using the Tcl_DoWhenIdle + * mechanism) to re-layout a set of windows managed by + * the grid. It is invoked at idle time so that a + * series of grid requests can be merged into a single + * layout operation. + * + * Results: + * None. + * + * Side effects: + * The slaves of masterPtr may get resized or moved. + * + *-------------------------------------------------------------- + */ + +static void +ArrangeGrid(clientData) + ClientData clientData; /* Structure describing parent whose slaves + * are to be re-layed out. */ +{ + register Gridder *masterPtr = (Gridder *) clientData; + register Gridder *slavePtr; + GridMaster *slotPtr = masterPtr->masterDataPtr; + int abort; + int width, height; /* requested size of layout, in pixels */ + int realWidth, realHeight; /* actual size layout should take-up */ + + masterPtr->flags &= ~REQUESTED_RELAYOUT; + + /* + * If the parent has no slaves anymore, then don't do anything + * at all: just leave the parent's size as-is. Otherwise there is + * no way to "relinquish" control over the parent so another geometry + * manager can take over. + */ + + if (masterPtr->slavePtr == NULL) { + return; + } + + if (masterPtr->masterDataPtr == NULL) { + return; + } + + /* + * Abort any nested call to ArrangeGrid for this window, since + * we'll do everything necessary here, and set up so this call + * can be aborted if necessary. + */ + + if (masterPtr->abortPtr != NULL) { + *masterPtr->abortPtr = 1; + } + masterPtr->abortPtr = &abort; + abort = 0; + Tcl_Preserve((ClientData) masterPtr); + + /* + * Call the constraint engine to fill in the row and column offsets. + */ + + SetGridSize(masterPtr); + width = ResolveConstraints(masterPtr, COLUMN, 0); + height = ResolveConstraints(masterPtr, ROW, 0); + width += 2*Tk_InternalBorderWidth(masterPtr->tkwin); + height += 2*Tk_InternalBorderWidth(masterPtr->tkwin); + + if (((width != Tk_ReqWidth(masterPtr->tkwin)) + || (height != Tk_ReqHeight(masterPtr->tkwin))) + && !(masterPtr->flags & DONT_PROPAGATE)) { + Tk_GeometryRequest(masterPtr->tkwin, width, height); + if (width>1 && height>1) { + masterPtr->flags |= REQUESTED_RELAYOUT; + Tcl_DoWhenIdle(ArrangeGrid, (ClientData) masterPtr); + } + masterPtr->abortPtr = NULL; + Tcl_Release((ClientData) masterPtr); + return; + } + + /* + * If the currently requested layout size doesn't match the parent's + * window size, then adjust the slot offsets according to the + * weights. If all of the weights are zero, center the layout in + * its parent. I haven't decided what to do if the parent is smaller + * than the requested size. + */ + + realWidth = Tk_Width(masterPtr->tkwin) - + 2*Tk_InternalBorderWidth(masterPtr->tkwin); + realHeight = Tk_Height(masterPtr->tkwin) - + 2*Tk_InternalBorderWidth(masterPtr->tkwin); + slotPtr->startX = AdjustOffsets(realWidth, + MAX(slotPtr->columnEnd,slotPtr->columnMax), slotPtr->columnPtr); + slotPtr->startY = AdjustOffsets(realHeight, + MAX(slotPtr->rowEnd,slotPtr->rowMax), slotPtr->rowPtr); + slotPtr->startX += Tk_InternalBorderWidth(masterPtr->tkwin); + slotPtr->startY += Tk_InternalBorderWidth(masterPtr->tkwin); + + /* + * Now adjust the actual size of the slave to its cavity by + * computing the cavity size, and adjusting the widget according + * to its stickyness. + */ + + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL && !abort; + slavePtr = slavePtr->nextPtr) { + int x, y; /* top left coordinate */ + int width, height; /* slot or slave size */ + int col = slavePtr->column; + int row = slavePtr->row; + + x = (col>0) ? slotPtr->columnPtr[col-1].offset : 0; + y = (row>0) ? slotPtr->rowPtr[row-1].offset : 0; + + width = slotPtr->columnPtr[slavePtr->numCols+col-1].offset - x; + height = slotPtr->rowPtr[slavePtr->numRows+row-1].offset - y; + + x += slotPtr->startX; + y += slotPtr->startY; + + AdjustForSticky(slavePtr, &x, &y, &width, &height); + + /* + * Now put the window in the proper spot. (This was taken directly + * from tkPack.c.) If the slave is a child of the master, then + * do this here. Otherwise let Tk_MaintainGeometry do the work. + */ + + if (masterPtr->tkwin == Tk_Parent(slavePtr->tkwin)) { + if ((width <= 0) || (height <= 0)) { + Tk_UnmapWindow(slavePtr->tkwin); + } else { + if ((x != Tk_X(slavePtr->tkwin)) + || (y != Tk_Y(slavePtr->tkwin)) + || (width != Tk_Width(slavePtr->tkwin)) + || (height != Tk_Height(slavePtr->tkwin))) { + Tk_MoveResizeWindow(slavePtr->tkwin, x, y, width, height); + } + if (abort) { + break; + } + + /* + * Don't map the slave if the master isn't mapped: wait + * until the master gets mapped later. + */ + + if (Tk_IsMapped(masterPtr->tkwin)) { + Tk_MapWindow(slavePtr->tkwin); + } + } + } else { + if ((width <= 0) || (height <= 0)) { + Tk_UnmaintainGeometry(slavePtr->tkwin, masterPtr->tkwin); + Tk_UnmapWindow(slavePtr->tkwin); + } else { + Tk_MaintainGeometry(slavePtr->tkwin, masterPtr->tkwin, + x, y, width, height); + } + } + } + + masterPtr->abortPtr = NULL; + Tcl_Release((ClientData) masterPtr); +} + +/* + *-------------------------------------------------------------- + * + * ResolveConstraints -- + * + * Resolve all of the column and row boundaries. Most of + * the calculations are identical for rows and columns, so this procedure + * is called twice, once for rows, and again for columns. + * + * Results: + * The offset (in pixels) from the left/top edge of this layout is + * returned. + * + * Side effects: + * The slot offsets are copied into the SlotInfo structure for the + * geometry master. + * + *-------------------------------------------------------------- + */ + +static int +ResolveConstraints(masterPtr, slotType, maxOffset) + Gridder *masterPtr; /* The geometry master for this grid. */ + int slotType; /* Either ROW or COLUMN. */ + int maxOffset; /* The actual maximum size of this layout + * in pixels, or 0 (not currently used). */ +{ + register SlotInfo *slotPtr; /* Pointer to row/col constraints. */ + register Gridder *slavePtr; /* List of slave windows in this grid. */ + int constraintCount; /* Count of rows or columns that have + * constraints. */ + int slotCount; /* Last occupied row or column. */ + int gridCount; /* The larger of slotCount and constraintCount. + */ + GridLayout *layoutPtr; /* Temporary layout structure. */ + int requiredSize; /* The natural size of the grid (pixels). + * This is the minimum size needed to + * accomodate all of the slaves at their + * requested sizes. */ + int offset; /* The pixel offset of the right edge of the + * current slot from the beginning of the + * layout. */ + int slot; /* The current slot. */ + int start; /* The first slot of a contiguous set whose + * constraints are not yet fully resolved. */ + int end; /* The Last slot of a contiguous set whose + * constraints are not yet fully resolved. */ + + /* + * For typical sized tables, we'll use stack space for the layout data + * to avoid the overhead of a malloc and free for every layout. + */ + + GridLayout layoutData[TYPICAL_SIZE + 1]; + + if (slotType == COLUMN) { + constraintCount = masterPtr->masterDataPtr->columnMax; + slotCount = masterPtr->masterDataPtr->columnEnd; + slotPtr = masterPtr->masterDataPtr->columnPtr; + } else { + constraintCount = masterPtr->masterDataPtr->rowMax; + slotCount = masterPtr->masterDataPtr->rowEnd; + slotPtr = masterPtr->masterDataPtr->rowPtr; + } + + /* + * Make sure there is enough memory for the layout. + */ + + gridCount = MAX(constraintCount,slotCount); + if (gridCount >= TYPICAL_SIZE) { + layoutPtr = (GridLayout *) Tcl_Alloc(sizeof(GridLayout) * (1+gridCount)); + } else { + layoutPtr = layoutData; + } + + /* + * Allocate an extra layout slot to represent the left/top edge of + * the 0th slot to make it easier to calculate slot widths from + * offsets without special case code. + * Initialize the "dummy" slot to the left/top of the table. + * This slot avoids special casing the first slot. + */ + + layoutPtr->minOffset = 0; + layoutPtr->maxOffset = 0; + layoutPtr++; + + /* + * Step 1. + * Copy the slot constraints into the layout structure, + * and initialize the rest of the fields. + */ + + for (slot=0; slot < constraintCount; slot++) { + layoutPtr[slot].minSize = slotPtr[slot].minSize; + layoutPtr[slot].weight = slotPtr[slot].weight; + layoutPtr[slot].pad = slotPtr[slot].pad; + layoutPtr[slot].binNextPtr = NULL; + } + for(;slot<gridCount;slot++) { + layoutPtr[slot].minSize = 0; + layoutPtr[slot].weight = 0; + layoutPtr[slot].pad = 0; + layoutPtr[slot].binNextPtr = NULL; + } + + /* + * Step 2. + * Slaves with a span of 1 are used to determine the minimum size of + * each slot. Slaves whose span is two or more slots don't + * contribute to the minimum size of each slot directly, but can cause + * slots to grow if their size exceeds the the sizes of the slots they + * span. + * + * Bin all slaves whose spans are > 1 by their right edges. This + * allows the computation on minimum and maximum possible layout + * sizes at each slot boundary, without the need to re-sort the slaves. + */ + + switch (slotType) { + case COLUMN: + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + int rightEdge = slavePtr->column + slavePtr->numCols - 1; + slavePtr->size = Tk_ReqWidth(slavePtr->tkwin) + + slavePtr->padX + slavePtr->iPadX + slavePtr->doubleBw; + if (slavePtr->numCols > 1) { + slavePtr->binNextPtr = layoutPtr[rightEdge].binNextPtr; + layoutPtr[rightEdge].binNextPtr = slavePtr; + } else { + int size = slavePtr->size + layoutPtr[rightEdge].pad; + if (size > layoutPtr[rightEdge].minSize) { + layoutPtr[rightEdge].minSize = size; + } + } + } + break; + case ROW: + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + int rightEdge = slavePtr->row + slavePtr->numRows - 1; + slavePtr->size = Tk_ReqHeight(slavePtr->tkwin) + + slavePtr->padY + slavePtr->iPadY + slavePtr->doubleBw; + if (slavePtr->numRows > 1) { + slavePtr->binNextPtr = layoutPtr[rightEdge].binNextPtr; + layoutPtr[rightEdge].binNextPtr = slavePtr; + } else { + int size = slavePtr->size + layoutPtr[rightEdge].pad; + if (size > layoutPtr[rightEdge].minSize) { + layoutPtr[rightEdge].minSize = size; + } + } + } + break; + } + + /* + * Step 3. + * Determine the minimum slot offsets going from left to right + * that would fit all of the slaves. This determines the minimum + */ + + for (offset=slot=0; slot < gridCount; slot++) { + layoutPtr[slot].minOffset = layoutPtr[slot].minSize + offset; + for (slavePtr = layoutPtr[slot].binNextPtr; slavePtr != NULL; + slavePtr = slavePtr->binNextPtr) { + int span = (slotType == COLUMN) ? slavePtr->numCols : slavePtr->numRows; + int required = slavePtr->size + layoutPtr[slot - span].minOffset; + if (required > layoutPtr[slot].minOffset) { + layoutPtr[slot].minOffset = required; + } + } + offset = layoutPtr[slot].minOffset; + } + + /* + * At this point, we know the minimum required size of the entire layout. + * It might be prudent to stop here if our "master" will resize itself + * to this size. + */ + + requiredSize = offset; + if (maxOffset > offset) { + offset=maxOffset; + } + + /* + * Step 4. + * Determine the minimum slot offsets going from right to left, + * bounding the pixel range of each slot boundary. + * Pre-fill all of the right offsets with the actual size of the table; + * they will be reduced as required. + */ + + for (slot=0; slot < gridCount; slot++) { + layoutPtr[slot].maxOffset = offset; + } + for (slot=gridCount-1; slot > 0;) { + for (slavePtr = layoutPtr[slot].binNextPtr; slavePtr != NULL; + slavePtr = slavePtr->binNextPtr) { + int span = (slotType == COLUMN) ? slavePtr->numCols : slavePtr->numRows; + int require = offset - slavePtr->size; + int startSlot = slot - span; + if (startSlot >=0 && require < layoutPtr[startSlot].maxOffset) { + layoutPtr[startSlot].maxOffset = require; + } + } + offset -= layoutPtr[slot].minSize; + slot--; + if (layoutPtr[slot].maxOffset < offset) { + offset = layoutPtr[slot].maxOffset; + } else { + layoutPtr[slot].maxOffset = offset; + } + } + + /* + * Step 5. + * At this point, each slot boundary has a range of values that + * will satisfy the overall layout size. + * Make repeated passes over the layout structure looking for + * spans of slot boundaries where the minOffsets are less than + * the maxOffsets, and adjust the offsets according to the slot + * weights. At each pass, at least one slot boundary will have + * its range of possible values fixed at a single value. + */ + + for (start=0; start < gridCount;) { + int totalWeight = 0; /* Sum of the weights for all of the + * slots in this span. */ + int need = 0; /* The minimum space needed to layout + * this span. */ + int have; /* The actual amount of space that will + * be taken up by this span. */ + int weight; /* Cumulative weights of the columns in + * this span. */ + int noWeights = 0; /* True if the span has no weights. */ + + /* + * Find a span by identifying ranges of slots whose edges are + * already constrained at fixed offsets, but whose internal + * slot boundaries have a range of possible positions. + */ + + if (layoutPtr[start].minOffset == layoutPtr[start].maxOffset) { + start++; + continue; + } + + for (end=start+1; end<gridCount; end++) { + if (layoutPtr[end].minOffset == layoutPtr[end].maxOffset) { + break; + } + } + + /* + * We found a span. Compute the total weight, minumum space required, + * for this span, and the actual amount of space the span should + * use. + */ + + for (slot=start; slot<=end; slot++) { + totalWeight += layoutPtr[slot].weight; + need += layoutPtr[slot].minSize; + } + have = layoutPtr[end].maxOffset - layoutPtr[start-1].minOffset; + + /* + * If all the weights in the span are zero, then distribute the + * extra space evenly. + */ + + if (totalWeight == 0) { + noWeights++; + totalWeight = end - start + 1; + } + + /* + * It might not be possible to give the span all of the space + * available on this pass without violating the size constraints + * of one or more of the internal slot boundaries. + * Determine the maximum amount of space that when added to the + * entire span, would cause a slot boundary to have its possible + * range reduced to one value, and reduce the amount of extra + * space allocated on this pass accordingly. + * + * The calculation is done cumulatively to avoid accumulating + * roundoff errors. + */ + + for (weight=0,slot=start; slot<end; slot++) { + int diff = layoutPtr[slot].maxOffset - layoutPtr[slot].minOffset; + weight += noWeights ? 1 : layoutPtr[slot].weight; + if ((noWeights || layoutPtr[slot].weight>0) && + (diff*totalWeight/weight) < (have-need)) { + have = diff * totalWeight / weight + need; + } + } + + /* + * Now distribute the extra space among the slots by + * adjusting the minSizes and minOffsets. + */ + + for (weight=0,slot=start; slot<end; slot++) { + weight += noWeights ? 1 : layoutPtr[slot].weight; + layoutPtr[slot].minOffset += + (int)((double) (have-need) * weight/totalWeight + 0.5); + layoutPtr[slot].minSize = layoutPtr[slot].minOffset + - layoutPtr[slot-1].minOffset; + } + layoutPtr[slot].minSize = layoutPtr[slot].minOffset + - layoutPtr[slot-1].minOffset; + + /* + * Having pushed the top/left boundaries of the slots to + * take up extra space, the bottom/right space is recalculated + * to propagate the new space allocation. + */ + + for (slot=end; slot > start; slot--) { + layoutPtr[slot-1].maxOffset = + layoutPtr[slot].maxOffset-layoutPtr[slot].minSize; + } + } + + + /* + * Step 6. + * All of the space has been apportioned; copy the + * layout information back into the master. + */ + + for (slot=0; slot < gridCount; slot++) { + slotPtr[slot].offset = layoutPtr[slot].minOffset; + } + + --layoutPtr; + if (layoutPtr != layoutData) { + Tcl_Free((char *)layoutPtr); + } + return requiredSize; +} + +/* + *-------------------------------------------------------------- + * + * GetGrid -- + * + * This internal procedure is used to locate a Grid + * structure for a given window, creating one if one + * doesn't exist already. + * + * Results: + * The return value is a pointer to the Grid structure + * corresponding to tkwin. + * + * Side effects: + * A new grid structure may be created. If so, then + * a callback is set up to clean things up when the + * window is deleted. + * + *-------------------------------------------------------------- + */ + +static Gridder * +GetGrid(tkwin) + Tk_Window tkwin; /* Token for window for which + * grid structure is desired. */ +{ + register Gridder *gridPtr; + Tcl_HashEntry *hPtr; + int new; + + if (!initialized) { + initialized = 1; + Tcl_InitHashTable(&gridHashTable, TCL_ONE_WORD_KEYS); + } + + /* + * See if there's already grid for this window. If not, + * then create a new one. + */ + + hPtr = Tcl_CreateHashEntry(&gridHashTable, (char *) tkwin, &new); + if (!new) { + return (Gridder *) Tcl_GetHashValue(hPtr); + } + gridPtr = (Gridder *) Tcl_Alloc(sizeof(Gridder)); + gridPtr->tkwin = tkwin; + gridPtr->masterPtr = NULL; + gridPtr->masterDataPtr = NULL; + gridPtr->nextPtr = NULL; + gridPtr->slavePtr = NULL; + gridPtr->binNextPtr = NULL; + + gridPtr->column = gridPtr->row = -1; + gridPtr->numCols = 1; + gridPtr->numRows = 1; + + gridPtr->padX = gridPtr->padY = 0; + gridPtr->iPadX = gridPtr->iPadY = 0; + gridPtr->doubleBw = 2*Tk_Changes(tkwin)->border_width; + gridPtr->abortPtr = NULL; + gridPtr->flags = 0; + gridPtr->sticky = 0; + gridPtr->size = 0; + gridPtr->masterDataPtr = NULL; + Tcl_SetHashValue(hPtr, gridPtr); + Tk_CreateEventHandler(tkwin, StructureNotifyMask, + GridStructureProc, (ClientData) gridPtr); + return gridPtr; +} + +/* + *-------------------------------------------------------------- + * + * SetGridSize -- + * + * This internal procedure sets the size of the grid occupied + * by slaves. + * + * Results: + * none + * + * Side effects: + * The width and height arguments are filled in the master data structure. + * Additional space is allocated for the constraints to accomodate + * the offsets. + * + *-------------------------------------------------------------- + */ + +static void +SetGridSize(masterPtr) + Gridder *masterPtr; /* The geometry master for this grid. */ +{ + register Gridder *slavePtr; /* Current slave window. */ + int maxX = 0, maxY = 0; + + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + maxX = MAX(maxX,slavePtr->numCols + slavePtr->column); + maxY = MAX(maxY,slavePtr->numRows + slavePtr->row); + } + masterPtr->masterDataPtr->columnEnd = maxX; + masterPtr->masterDataPtr->rowEnd = maxY; + CheckSlotData(masterPtr, maxX, COLUMN, CHECK_SPACE); + CheckSlotData(masterPtr, maxY, ROW, CHECK_SPACE); +} + +/* + *-------------------------------------------------------------- + * + * CheckSlotData -- + * + * This internal procedure is used to manage the storage for + * row and column (slot) constraints. + * + * Results: + * TRUE if the index is OK, False otherwise. + * + * Side effects: + * A new master grid structure may be created. If so, then + * it is initialized. In addition, additional storage for + * a row or column constraints may be allocated, and the constraint + * maximums are adjusted. + * + *-------------------------------------------------------------- + */ + +static int +CheckSlotData(masterPtr, slot, slotType, checkOnly) + Gridder *masterPtr; /* the geometry master for this grid */ + int slot; /* which slot to look at */ + int slotType; /* ROW or COLUMN */ + int checkOnly; /* don't allocate new space if true */ +{ + int numSlot; /* number of slots already allocated (Space) */ + int end; /* last used constraint */ + + /* + * If slot is out of bounds, return immediately. + */ + + if (slot < 0 || slot >= MAX_ELEMENT) { + return TCL_ERROR; + } + + if ((checkOnly == CHECK_ONLY) && (masterPtr->masterDataPtr == NULL)) { + return TCL_ERROR; + } + + /* + * If we need to allocate more space, allocate a little extra to avoid + * repeated re-alloc's for large tables. We need enough space to + * hold all of the offsets as well. + */ + + InitMasterData(masterPtr); + end = (slotType == ROW) ? masterPtr->masterDataPtr->rowMax : + masterPtr->masterDataPtr->columnMax; + if (checkOnly == CHECK_ONLY) { + return (end < slot) ? TCL_ERROR : TCL_OK; + } else { + numSlot = (slotType == ROW) ? masterPtr->masterDataPtr->rowSpace + : masterPtr->masterDataPtr->columnSpace; + if (slot >= numSlot) { + int newNumSlot = slot + PREALLOC ; + size_t oldSize = numSlot * sizeof(SlotInfo) ; + size_t newSize = newNumSlot * sizeof(SlotInfo) ; + SlotInfo *new = (SlotInfo *) Tcl_Alloc(newSize); + SlotInfo *old = (slotType == ROW) ? + masterPtr->masterDataPtr->rowPtr : + masterPtr->masterDataPtr->columnPtr; + memcpy((VOID *) new, (VOID *) old, oldSize ); + memset((VOID *) (new+numSlot), 0, newSize - oldSize ); + Tcl_Free((char *) old); + if (slotType == ROW) { + masterPtr->masterDataPtr->rowPtr = new ; + masterPtr->masterDataPtr->rowSpace = newNumSlot ; + } else { + masterPtr->masterDataPtr->columnPtr = new; + masterPtr->masterDataPtr->columnSpace = newNumSlot ; + } + } + if (slot >= end && checkOnly != CHECK_SPACE) { + if (slotType == ROW) { + masterPtr->masterDataPtr->rowMax = slot+1; + } else { + masterPtr->masterDataPtr->columnMax = slot+1; + } + } + return TCL_OK; + } +} + +/* + *-------------------------------------------------------------- + * + * InitMasterData -- + * + * This internal procedure is used to allocate and initialize + * the data for a geometry master, if the data + * doesn't exist already. + * + * Results: + * none + * + * Side effects: + * A new master grid structure may be created. If so, then + * it is initialized. + * + *-------------------------------------------------------------- + */ + +static void +InitMasterData(masterPtr) + Gridder *masterPtr; +{ + size_t size; + if (masterPtr->masterDataPtr == NULL) { + GridMaster *gridPtr = masterPtr->masterDataPtr = + (GridMaster *) Tcl_Alloc(sizeof(GridMaster)); + size = sizeof(SlotInfo) * TYPICAL_SIZE; + + gridPtr->columnEnd = 0; + gridPtr->columnMax = 0; + gridPtr->columnPtr = (SlotInfo *) Tcl_Alloc(size); + gridPtr->columnSpace = 0; + gridPtr->columnSpace = TYPICAL_SIZE; + gridPtr->rowEnd = 0; + gridPtr->rowMax = 0; + gridPtr->rowPtr = (SlotInfo *) Tcl_Alloc(size); + gridPtr->rowSpace = 0; + gridPtr->rowSpace = TYPICAL_SIZE; + + memset((VOID *) gridPtr->columnPtr, 0, size); + memset((VOID *) gridPtr->rowPtr, 0, size); + } +} + +/* + *---------------------------------------------------------------------- + * + * Unlink -- + * + * Remove a grid from its parent's list of slaves. + * + * Results: + * None. + * + * Side effects: + * The parent will be scheduled for re-arranging, and the size of the + * grid will be adjusted accordingly + * + *---------------------------------------------------------------------- + */ + +static void +Unlink(slavePtr) + register Gridder *slavePtr; /* Window to unlink. */ +{ + register Gridder *masterPtr, *slavePtr2; + GridMaster *gridPtr; /* pointer to grid data */ + + masterPtr = slavePtr->masterPtr; + if (masterPtr == NULL) { + return; + } + + gridPtr = masterPtr->masterDataPtr; + if (masterPtr->slavePtr == slavePtr) { + masterPtr->slavePtr = slavePtr->nextPtr; + } + else { + for (slavePtr2 = masterPtr->slavePtr; ; slavePtr2 = slavePtr2->nextPtr) { + if (slavePtr2 == NULL) { + panic("Unlink couldn't find previous window"); + } + if (slavePtr2->nextPtr == slavePtr) { + slavePtr2->nextPtr = slavePtr->nextPtr; + break; + } + } + } + if (!(masterPtr->flags & REQUESTED_RELAYOUT)) { + masterPtr->flags |= REQUESTED_RELAYOUT; + Tcl_DoWhenIdle(ArrangeGrid, (ClientData) masterPtr); + } + if (masterPtr->abortPtr != NULL) { + *masterPtr->abortPtr = 1; + } + + if ((slavePtr->numCols+slavePtr->column == gridPtr->columnMax) + || (slavePtr->numRows+slavePtr->row == gridPtr->rowMax)) { + } + slavePtr->masterPtr = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyGrid -- + * + * This procedure is invoked by Tk_EventuallyFree or Tcl_Release + * to clean up the internal structure of a grid at a safe time + * (when no-one is using it anymore). Cleaning up the grid involves + * freeing the main structure for all windows. and the master structure + * for geometry managers. + * + * Results: + * None. + * + * Side effects: + * Everything associated with the grid is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyGrid(memPtr) + char *memPtr; /* Info about window that is now dead. */ +{ + register Gridder *gridPtr = (Gridder *) memPtr; + + if (gridPtr->masterDataPtr != NULL) { + if (gridPtr->masterDataPtr->rowPtr != NULL) { + Tcl_Free((char *) gridPtr->masterDataPtr -> rowPtr); + } + if (gridPtr->masterDataPtr->columnPtr != NULL) { + Tcl_Free((char *) gridPtr->masterDataPtr -> columnPtr); + } + Tcl_Free((char *) gridPtr->masterDataPtr); + } + Tcl_Free((char *) gridPtr); +} + +/* + *---------------------------------------------------------------------- + * + * GridStructureProc -- + * + * This procedure is invoked by the Tk event dispatcher in response + * to StructureNotify events. + * + * Results: + * None. + * + * Side effects: + * If a window was just deleted, clean up all its grid-related + * information. If it was just resized, re-configure its slaves, if + * any. + * + *---------------------------------------------------------------------- + */ + +static void +GridStructureProc(clientData, eventPtr) + ClientData clientData; /* Our information about window + * referred to by eventPtr. */ + XEvent *eventPtr; /* Describes what just happened. */ +{ + register Gridder *gridPtr = (Gridder *) clientData; + + if (eventPtr->type == ConfigureNotify) { + if (!(gridPtr->flags & REQUESTED_RELAYOUT)) { + gridPtr->flags |= REQUESTED_RELAYOUT; + Tcl_DoWhenIdle(ArrangeGrid, (ClientData) gridPtr); + } + if (gridPtr->doubleBw != 2*Tk_Changes(gridPtr->tkwin)->border_width) { + if ((gridPtr->masterPtr != NULL) && + !(gridPtr->masterPtr->flags & REQUESTED_RELAYOUT)) { + gridPtr->doubleBw = 2*Tk_Changes(gridPtr->tkwin)->border_width; + gridPtr->masterPtr->flags |= REQUESTED_RELAYOUT; + Tcl_DoWhenIdle(ArrangeGrid, (ClientData) gridPtr->masterPtr); + } + } + } else if (eventPtr->type == DestroyNotify) { + register Gridder *gridPtr2, *nextPtr; + + if (gridPtr->masterPtr != NULL) { + Unlink(gridPtr); + } + for (gridPtr2 = gridPtr->slavePtr; gridPtr2 != NULL; + gridPtr2 = nextPtr) { + Tk_UnmapWindow(gridPtr2->tkwin); + gridPtr2->masterPtr = NULL; + nextPtr = gridPtr2->nextPtr; + gridPtr2->nextPtr = NULL; + } + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&gridHashTable, + (char *) gridPtr->tkwin)); + if (gridPtr->flags & REQUESTED_RELAYOUT) { + Tk_CancelIdleCall(ArrangeGrid, (ClientData) gridPtr); + } + gridPtr->tkwin = NULL; + Tk_EventuallyFree((ClientData) gridPtr, DestroyGrid); + } else if (eventPtr->type == MapNotify) { + if (!(gridPtr->flags & REQUESTED_RELAYOUT)) { + gridPtr->flags |= REQUESTED_RELAYOUT; + Tcl_DoWhenIdle(ArrangeGrid, (ClientData) gridPtr); + } + } else if (eventPtr->type == UnmapNotify) { + register Gridder *gridPtr2; + + for (gridPtr2 = gridPtr->slavePtr; gridPtr2 != NULL; + gridPtr2 = gridPtr2->nextPtr) { + Tk_UnmapWindow(gridPtr2->tkwin); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureSlaves -- + * + * This implements the guts of the "grid configure" command. Given + * a list of slaves and configuration options, it arranges for the + * grid to manage the slaves and sets the specified options. + * arguments consist of windows or window shortcuts followed by + * "-option value" pairs. + * + * Results: + * TCL_OK is returned if all went well. Otherwise, TCL_ERROR is + * returned and interp->result is set to contain an error message. + * + * Side effects: + * Slave windows get taken over by the grid. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureSlaves(interp, tkwin, argc, argv) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Window tkwin; /* Any window in application containing + * slaves. Used to look up slave names. */ + int argc; /* Number of elements in argv. */ + char *argv[]; /* Argument strings: contains one or more + * window names followed by any number + * of "option value" pairs. Caller must + * make sure that there is at least one + * window name. */ +{ + Gridder *masterPtr; + Gridder *slavePtr; + Tk_Window other, slave, parent, ancestor; + int i, j, c, tmp; + size_t length; + int numWindows; + int width; + int defaultColumn = 0; /* default column number */ + int defaultColumnSpan = 1; /* default number of columns */ + char *lastWindow; /* use this window to base current + * Row/col on */ + + /* + * Count the number of windows, or window short-cuts. + */ + + for(numWindows=i=0;i<argc;i++) { + char firstChar = *argv[i]; + if (firstChar == '.') { + numWindows++; + continue; + } + length = strlen(argv[i]); + if (length > 1 && firstChar == '-') { + break; + } + if (length > 1) { + Tcl_AppendResult(interp, "unexpected parameter, \"", + argv[i], "\", in configure list. ", + "Should be window name or option", (char *) NULL); + return TCL_ERROR; + } + + if ((firstChar == REL_HORIZ) && ((numWindows == 0) || + (*argv[i-1] == REL_SKIP) || (*argv[i-1] == REL_VERT))) { + Tcl_AppendResult(interp, + "Must specify window before shortcut '-'.", + (char *) NULL); + return TCL_ERROR; + } + + if ((firstChar == REL_VERT) || (firstChar == REL_SKIP) + || (firstChar == REL_HORIZ)) { + continue; + } + + Tcl_AppendResult(interp, "invalid window shortcut, \"", + argv[i], "\" should be '-', 'x', or '^'", (char *) NULL); + return TCL_ERROR; + } + numWindows = i; + + if ((argc-numWindows)&1) { + Tcl_AppendResult(interp, "extra option or", + " option with no value", (char *) NULL); + return TCL_ERROR; + } + + /* + * Iterate over all of the slave windows and short-cuts, parsing + * options for each slave. It's a bit wasteful to re-parse the + * options for each slave, but things get too messy if we try to + * parse the arguments just once at the beginning. For example, + * if a slave already is managed we want to just change a few + * existing values without resetting everything. If there are + * multiple windows, the -in option only gets processed for the + * first window. + */ + + masterPtr = NULL; + for (j = 0; j < numWindows; j++) { + char firstChar = *argv[j]; + + /* + * '^' and 'x' cause us to skip a column. '-' is processed + * as part of its preceeding slave. + */ + + if ((firstChar == REL_VERT) || (firstChar == REL_SKIP)) { + defaultColumn++; + continue; + } + if (firstChar == REL_HORIZ) { + continue; + } + + for (defaultColumnSpan=1; + j + defaultColumnSpan < numWindows && + (*argv[j+defaultColumnSpan] == REL_HORIZ); + defaultColumnSpan++) { + /* null body */ + } + + slave = Tk_NameToWindow(interp, argv[j], tkwin); + if (slave == NULL) { + return TCL_ERROR; + } + if (Tk_IsTopLevel(slave)) { + Tcl_AppendResult(interp, "can't manage \"", argv[j], + "\": it's a top-level window", (char *) NULL); + return TCL_ERROR; + } + slavePtr = GetGrid(slave); + + /* + * The following statement is taken from tkPack.c: + * + * "If the slave isn't currently managed, reset all of its + * configuration information to default values (there could + * be old values left from a previous packer)." + * + * I [D.S.] disagree with this statement. If a slave is disabled (using + * "forget") and then re-enabled, I submit that 90% of the time the + * programmer will want it to retain its old configuration information. + * If the programmer doesn't want this behavior, then the + * defaults can be reestablished by hand, without having to worry + * about keeping track of the old state. + */ + + for (i = numWindows; i < argc; i+=2) { + length = strlen(argv[i]); + c = argv[i][1]; + + if (length < 2) { + Tcl_AppendResult(interp, "unknown or ambiguous option \"", + argv[i], "\": must be ", + "-column, -columnspan, -in, -ipadx, -ipady, ", + "-padx, -pady, -row, -rowspan, or -sticky", + (char *) NULL); + return TCL_ERROR; + } + if ((c == 'c') && (strncmp(argv[i], "-column", length) == 0)) { + if (Tcl_GetInt(interp, argv[i+1], &tmp) != TCL_OK || tmp<0) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad column value \"", argv[i+1], + "\": must be a non-negative integer", (char *)NULL); + return TCL_ERROR; + } + slavePtr->column = tmp; + } else if ((c == 'c') + && (strncmp(argv[i], "-columnspan", length) == 0)) { + if (Tcl_GetInt(interp, argv[i+1], &tmp) != TCL_OK || tmp <= 0) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad columnspan value \"", argv[i+1], + "\": must be a positive integer", (char *)NULL); + return TCL_ERROR; + } + slavePtr->numCols = tmp; + } else if ((c == 'i') && (strncmp(argv[i], "-in", length) == 0)) { + other = Tk_NameToWindow(interp, argv[i+1], tkwin); + if (other == NULL) { + return TCL_ERROR; + } + if (other == slave) { + sprintf(interp->result,"Window can't be managed in itself"); + return TCL_ERROR; + } + masterPtr = GetGrid(other); + InitMasterData(masterPtr); + } else if ((c == 'i') + && (strncmp(argv[i], "-ipadx", length) == 0)) { + if ((Tk_GetPixels(interp, slave, argv[i+1], &tmp) != TCL_OK) + || (tmp < 0)) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad ipadx value \"", argv[i+1], + "\": must be positive screen distance", + (char *) NULL); + return TCL_ERROR; + } + slavePtr->iPadX = tmp*2; + } else if ((c == 'i') + && (strncmp(argv[i], "-ipady", length) == 0)) { + if ((Tk_GetPixels(interp, slave, argv[i+1], &tmp) != TCL_OK) + || (tmp< 0)) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad ipady value \"", argv[i+1], + "\": must be positive screen distance", + (char *) NULL); + return TCL_ERROR; + } + slavePtr->iPadY = tmp*2; + } else if ((c == 'p') + && (strncmp(argv[i], "-padx", length) == 0)) { + if ((Tk_GetPixels(interp, slave, argv[i+1], &tmp) != TCL_OK) + || (tmp< 0)) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad padx value \"", argv[i+1], + "\": must be positive screen distance", + (char *) NULL); + return TCL_ERROR; + } + slavePtr->padX = tmp*2; + } else if ((c == 'p') + && (strncmp(argv[i], "-pady", length) == 0)) { + if ((Tk_GetPixels(interp, slave, argv[i+1], &tmp) != TCL_OK) + || (tmp< 0)) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad pady value \"", argv[i+1], + "\": must be positive screen distance", + (char *) NULL); + return TCL_ERROR; + } + slavePtr->padY = tmp*2; + } else if ((c == 'r') && (strncmp(argv[i], "-row", length) == 0)) { + if (Tcl_GetInt(interp, argv[i+1], &tmp) != TCL_OK || tmp<0) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad grid value \"", argv[i+1], + "\": must be a non-negative integer", (char *)NULL); + return TCL_ERROR; + } + slavePtr->row = tmp; + } else if ((c == 'r') + && (strncmp(argv[i], "-rowspan", length) == 0)) { + if ((Tcl_GetInt(interp, argv[i+1], &tmp) != TCL_OK) || tmp<=0) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad rowspan value \"", argv[i+1], + "\": must be a positive integer", (char *)NULL); + return TCL_ERROR; + } + slavePtr->numRows = tmp; + } else if ((c == 's') + && strncmp(argv[i], "-sticky", length) == 0) { + int sticky = StringToSticky(argv[i+1]); + if (sticky == -1) { + Tcl_AppendResult(interp, "bad stickyness value \"", argv[i+1], + "\": must be a string containing n, e, s, and/or w", + (char *)NULL); + return TCL_ERROR; + } + slavePtr->sticky = sticky; + } else { + Tcl_AppendResult(interp, "unknown or ambiguous option \"", + argv[i], "\": must be ", + "-column, -columnspan, -in, -ipadx, -ipady, ", + "-padx, -pady, -row, -rowspan, or -sticky", + (char *) NULL); + return TCL_ERROR; + } + } + + /* + * Make sure we have a geometry master. We look at: + * 1) the -in flag + * 2) the geometry master of the first slave (if specified) + * 3) the parent of the first slave. + */ + + if (masterPtr == NULL) { + masterPtr = slavePtr->masterPtr; + } + parent = Tk_Parent(slave); + if (masterPtr == NULL) { + masterPtr = GetGrid(parent); + InitMasterData(masterPtr); + } + + if (slavePtr->masterPtr != NULL && slavePtr->masterPtr != masterPtr) { + Unlink(slavePtr); + slavePtr->masterPtr = NULL; + } + + if (slavePtr->masterPtr == NULL) { + Gridder *tempPtr = masterPtr->slavePtr; + slavePtr->masterPtr = masterPtr; + masterPtr->slavePtr = slavePtr; + slavePtr->nextPtr = tempPtr; + } + + /* + * Make sure that the slave's parent is either the master or + * an ancestor of the master, and that the master and slave + * aren't the same. + */ + + for (ancestor = masterPtr->tkwin; ; ancestor = Tk_Parent(ancestor)) { + if (ancestor == parent) { + break; + } + if (Tk_IsTopLevel(ancestor)) { + Tcl_AppendResult(interp, "can't put ", argv[j], + " inside ", Tk_PathName(masterPtr->tkwin), + (char *) NULL); + Unlink(slavePtr); + return TCL_ERROR; + } + } + + /* + * Try to make sure our master isn't managed by us. + */ + + if (masterPtr->masterPtr == slavePtr) { + Tcl_AppendResult(interp, "can't put ", argv[j], + " inside ", Tk_PathName(masterPtr->tkwin), + ", would cause management loop.", + (char *) NULL); + Unlink(slavePtr); + return TCL_ERROR; + } + + Tk_ManageGeometry(slave, &gridMgrType, (ClientData) slavePtr); + + /* + * Assign default position information. + */ + + if (slavePtr->column == -1) { + slavePtr->column = defaultColumn; + } + slavePtr->numCols += defaultColumnSpan - 1; + if (slavePtr->row == -1) { + if (masterPtr->masterDataPtr == NULL) { + slavePtr->row = 0; + } else { + slavePtr->row = masterPtr->masterDataPtr->rowEnd; + } + } + defaultColumn += slavePtr->numCols; + defaultColumnSpan = 1; + + /* + * Arrange for the parent to be re-arranged at the first + * idle moment. + */ + + if (masterPtr->abortPtr != NULL) { + *masterPtr->abortPtr = 1; + } + if (!(masterPtr->flags & REQUESTED_RELAYOUT)) { + masterPtr->flags |= REQUESTED_RELAYOUT; + Tcl_DoWhenIdle(ArrangeGrid, (ClientData) masterPtr); + } + } + + /* Now look for all the "^"'s. */ + + lastWindow = NULL; + for (j = 0; j < numWindows; j++) { + struct Gridder *otherPtr; + int match; /* found a match for the ^ */ + int lastRow, lastColumn; /* implied end of table */ + + if (*argv[j] == '.') { + lastWindow = argv[j]; + } + if (*argv[j] != REL_VERT) { + continue; + } + + if (masterPtr == NULL) { + Tcl_AppendResult(interp, "can't use '^', cant find master", + (char *) NULL); + return TCL_ERROR; + } + + for (width=1; width+j < numWindows && *argv[j+width] == REL_VERT; + width++) { + /* Null Body */ + } + + /* + * Find the implied grid location of the ^ + */ + + if (lastWindow == NULL) { + if (masterPtr->masterDataPtr != NULL) { + SetGridSize(masterPtr); + lastRow = masterPtr->masterDataPtr->rowEnd - 1; + } else { + lastRow = 0; + } + lastColumn = 0; + } else { + other = Tk_NameToWindow(interp, lastWindow, tkwin); + otherPtr = GetGrid(other); + lastRow = otherPtr->row; + lastColumn = otherPtr->column + otherPtr->numCols; + } + + for (match=0, slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + + if (slavePtr->numCols == width + && slavePtr->column == lastColumn + && slavePtr->row + slavePtr->numRows == lastRow) { + slavePtr->numRows++; + match++; + } + lastWindow = Tk_PathName(slavePtr->tkwin); + } + if (!match) { + Tcl_AppendResult(interp, "can't find slave to extend with \"^\".", + (char *) NULL); + return TCL_ERROR; + } + j += width - 1; + } + + if (masterPtr == NULL) { + Tcl_AppendResult(interp, "can't determine master window", + (char *) NULL); + return TCL_ERROR; + } + SetGridSize(masterPtr); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * StickyToString + * + * Converts the internal boolean combination of "sticky" bits onto + * a TCL list element containing zero or mor of n, s, e, or w. + * + * Results: + * A string is placed into the "result" pointer. + * + * Side effects: + * none. + * + *---------------------------------------------------------------------- + */ + +static void +StickyToString(flags, result) + int flags; /* the sticky flags */ + char *result; /* where to put the result */ +{ + int count = 0; + if (flags&STICK_NORTH) { + result[count++] = 'n'; + } + if (flags&STICK_EAST) { + result[count++] = 'e'; + } + if (flags&STICK_SOUTH) { + result[count++] = 's'; + } + if (flags&STICK_WEST) { + result[count++] = 'w'; + } + if (count) { + result[count] = '\0'; + } else { + sprintf(result,"{}"); + } +} + +/* + *---------------------------------------------------------------------- + * + * StringToSticky -- + * + * Converts an ascii string representing a widgets stickyness + * into the boolean result. + * + * Results: + * The boolean combination of the "sticky" bits is retuned. If an + * error occurs, such as an invalid character, -1 is returned instead. + * + * Side effects: + * none + * + *---------------------------------------------------------------------- + */ + +static int +StringToSticky(string) + char *string; +{ + int sticky = 0; + char c; + + while ((c = *string++) != '\0') { + switch (c) { + case 'n': case 'N': sticky |= STICK_NORTH; break; + case 'e': case 'E': sticky |= STICK_EAST; break; + case 's': case 'S': sticky |= STICK_SOUTH; break; + case 'w': case 'W': sticky |= STICK_WEST; break; + case ' ': case ',': case '\t': case '\r': case '\n': break; + default: return -1; + } + } + return sticky; +} diff --git a/generic/tkImage.c b/generic/tkImage.c new file mode 100644 index 0000000..251fe30 --- /dev/null +++ b/generic/tkImage.c @@ -0,0 +1,789 @@ +/* + * tkImage.c -- + * + * This module implements the image protocol, which allows lots + * of different kinds of images to be used in lots of different + * widgets. + * + * Copyright (c) 1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkImage.c 1.15 97/10/09 09:57:50 + */ + +#include "tkInt.h" +#include "tkPort.h" + +/* + * Each call to Tk_GetImage returns a pointer to one of the following + * structures, which is used as a token by clients (widgets) that + * display images. + */ + +typedef struct Image { + Tk_Window tkwin; /* Window passed to Tk_GetImage (needed to + * "re-get" the image later if the manager + * changes). */ + Display *display; /* Display for tkwin. Needed because when + * the image is eventually freed tkwin may + * not exist anymore. */ + struct ImageMaster *masterPtr; + /* Master for this image (identifiers image + * manager, for example). */ + ClientData instanceData; + /* One word argument to pass to image manager + * when dealing with this image instance. */ + Tk_ImageChangedProc *changeProc; + /* Code in widget to call when image changes + * in a way that affects redisplay. */ + ClientData widgetClientData; + /* Argument to pass to changeProc. */ + struct Image *nextPtr; /* Next in list of all image instances + * associated with the same name. */ + +} Image; + +/* + * For each image master there is one of the following structures, + * which represents a name in the image table and all of the images + * instantiated from it. Entries in mainPtr->imageTable point to + * these structures. + */ + +typedef struct ImageMaster { + Tk_ImageType *typePtr; /* Information about image type. NULL means + * that no image manager owns this image: the + * image was deleted. */ + ClientData masterData; /* One-word argument to pass to image mgr + * when dealing with the master, as opposed + * to instances. */ + int width, height; /* Last known dimensions for image. */ + Tcl_HashTable *tablePtr; /* Pointer to hash table containing image + * (the imageTable field in some TkMainInfo + * structure). */ + Tcl_HashEntry *hPtr; /* Hash entry in mainPtr->imageTable for + * this structure (used to delete the hash + * entry). */ + Image *instancePtr; /* Pointer to first in list of instances + * derived from this name. */ +} ImageMaster; + +/* + * The following variable points to the first in a list of all known + * image types. + */ + +static Tk_ImageType *imageTypeList = NULL; + +/* + * Prototypes for local procedures: + */ + +static void DeleteImage _ANSI_ARGS_((ImageMaster *masterPtr)); + +/* + *---------------------------------------------------------------------- + * + * Tk_CreateImageType -- + * + * This procedure is invoked by an image manager to tell Tk about + * a new kind of image and the procedures that manage the new type. + * The procedure is typically invoked during Tcl_AppInit. + * + * Results: + * None. + * + * Side effects: + * The new image type is entered into a table used in the "image + * create" command. + * + *---------------------------------------------------------------------- + */ + +void +Tk_CreateImageType(typePtr) + Tk_ImageType *typePtr; /* Structure describing the type. All of + * the fields except "nextPtr" must be filled + * in by caller. Must not have been passed + * to Tk_CreateImageType previously. */ +{ + typePtr->nextPtr = imageTypeList; + imageTypeList = typePtr; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_ImageCmd -- + * + * This procedure is invoked to process the "image" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_ImageCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + TkWindow *winPtr = (TkWindow *) clientData; + int c, i, new, firstOption; + size_t length; + Tk_ImageType *typePtr; + ImageMaster *masterPtr; + Image *imagePtr; + Tcl_HashEntry *hPtr; + Tcl_HashSearch search; + char idString[30], *name; + static int id = 0; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " option ?args?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'c') && (strncmp(argv[1], "create", length) == 0)) { + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " create type ?name? ?options?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[2][0]; + + /* + * Look up the image type. + */ + + for (typePtr = imageTypeList; typePtr != NULL; + typePtr = typePtr->nextPtr) { + if ((c == typePtr->name[0]) + && (strcmp(argv[2], typePtr->name) == 0)) { + break; + } + } + if (typePtr == NULL) { + Tcl_AppendResult(interp, "image type \"", argv[2], + "\" doesn't exist", (char *) NULL); + return TCL_ERROR; + } + + /* + * Figure out a name to use for the new image. + */ + + if ((argc == 3) || (argv[3][0] == '-')) { + id++; + sprintf(idString, "image%d", id); + name = idString; + firstOption = 3; + } else { + name = argv[3]; + firstOption = 4; + } + + /* + * Create the data structure for the new image. + */ + + hPtr = Tcl_CreateHashEntry(&winPtr->mainPtr->imageTable, name, &new); + if (new) { + masterPtr = (ImageMaster *) ckalloc(sizeof(ImageMaster)); + masterPtr->typePtr = NULL; + masterPtr->masterData = NULL; + masterPtr->width = masterPtr->height = 1; + masterPtr->tablePtr = &winPtr->mainPtr->imageTable; + masterPtr->hPtr = hPtr; + masterPtr->instancePtr = NULL; + Tcl_SetHashValue(hPtr, masterPtr); + } else { + /* + * An image already exists by this name. Disconnect the + * instances from the master. + */ + + masterPtr = (ImageMaster *) Tcl_GetHashValue(hPtr); + if (masterPtr->typePtr != NULL) { + for (imagePtr = masterPtr->instancePtr; imagePtr != NULL; + imagePtr = imagePtr->nextPtr) { + (*masterPtr->typePtr->freeProc)( + imagePtr->instanceData, imagePtr->display); + (*imagePtr->changeProc)(imagePtr->widgetClientData, 0, 0, + masterPtr->width, masterPtr->height, masterPtr->width, + masterPtr->height); + } + (*masterPtr->typePtr->deleteProc)(masterPtr->masterData); + masterPtr->typePtr = NULL; + } + } + + /* + * Call the image type manager so that it can perform its own + * initialization, then re-"get" for any existing instances of + * the image. + */ + + if ((*typePtr->createProc)(interp, name, argc-firstOption, + argv+firstOption, typePtr, (Tk_ImageMaster) masterPtr, + &masterPtr->masterData) != TCL_OK) { + DeleteImage(masterPtr); + return TCL_ERROR; + } + masterPtr->typePtr = typePtr; + for (imagePtr = masterPtr->instancePtr; imagePtr != NULL; + imagePtr = imagePtr->nextPtr) { + imagePtr->instanceData = (*typePtr->getProc)( + imagePtr->tkwin, masterPtr->masterData); + } + interp->result = Tcl_GetHashKey(&winPtr->mainPtr->imageTable, hPtr); + } else if ((c == 'd') && (strncmp(argv[1], "delete", length) == 0)) { + for (i = 2; i < argc; i++) { + hPtr = Tcl_FindHashEntry(&winPtr->mainPtr->imageTable, argv[i]); + if (hPtr == NULL) { + Tcl_AppendResult(interp, "image \"", argv[i], + "\" doesn't exist", (char *) NULL); + return TCL_ERROR; + } + masterPtr = (ImageMaster *) Tcl_GetHashValue(hPtr); + DeleteImage(masterPtr); + } + } else if ((c == 'h') && (strncmp(argv[1], "height", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " height name\"", (char *) NULL); + return TCL_ERROR; + } + hPtr = Tcl_FindHashEntry(&winPtr->mainPtr->imageTable, argv[2]); + if (hPtr == NULL) { + Tcl_AppendResult(interp, "image \"", argv[2], + "\" doesn't exist", (char *) NULL); + return TCL_ERROR; + } + masterPtr = (ImageMaster *) Tcl_GetHashValue(hPtr); + sprintf(interp->result, "%d", masterPtr->height); + } else if ((c == 'n') && (strncmp(argv[1], "names", length) == 0)) { + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " names\"", (char *) NULL); + return TCL_ERROR; + } + for (hPtr = Tcl_FirstHashEntry(&winPtr->mainPtr->imageTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + Tcl_AppendElement(interp, Tcl_GetHashKey( + &winPtr->mainPtr->imageTable, hPtr)); + } + } else if ((c == 't') && (strcmp(argv[1], "type") == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " type name\"", (char *) NULL); + return TCL_ERROR; + } + hPtr = Tcl_FindHashEntry(&winPtr->mainPtr->imageTable, argv[2]); + if (hPtr == NULL) { + Tcl_AppendResult(interp, "image \"", argv[2], + "\" doesn't exist", (char *) NULL); + return TCL_ERROR; + } + masterPtr = (ImageMaster *) Tcl_GetHashValue(hPtr); + if (masterPtr->typePtr != NULL) { + interp->result = masterPtr->typePtr->name; + } + } else if ((c == 't') && (strcmp(argv[1], "types") == 0)) { + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " types\"", (char *) NULL); + return TCL_ERROR; + } + for (typePtr = imageTypeList; typePtr != NULL; + typePtr = typePtr->nextPtr) { + Tcl_AppendElement(interp, typePtr->name); + } + } else if ((c == 'w') && (strncmp(argv[1], "width", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " width name\"", (char *) NULL); + return TCL_ERROR; + } + hPtr = Tcl_FindHashEntry(&winPtr->mainPtr->imageTable, argv[2]); + if (hPtr == NULL) { + Tcl_AppendResult(interp, "image \"", argv[2], + "\" doesn't exist", (char *) NULL); + return TCL_ERROR; + } + masterPtr = (ImageMaster *) Tcl_GetHashValue(hPtr); + sprintf(interp->result, "%d", masterPtr->width); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be create, delete, height, names, type, types,", + " or width", (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_ImageChanged -- + * + * This procedure is called by an image manager whenever something + * has happened that requires the image to be redrawn (some of its + * pixels have changed, or its size has changed). + * + * Results: + * None. + * + * Side effects: + * Any widgets that display the image are notified so that they + * can redisplay themselves as appropriate. + * + *---------------------------------------------------------------------- + */ + +void +Tk_ImageChanged(imageMaster, x, y, width, height, imageWidth, + imageHeight) + Tk_ImageMaster imageMaster; /* Image that needs redisplay. */ + int x, y; /* Coordinates of upper-left pixel of + * region of image that needs to be + * redrawn. */ + int width, height; /* Dimensions (in pixels) of region of + * image to redraw. If either dimension + * is zero then the image doesn't need to + * be redrawn (perhaps all that happened is + * that its size changed). */ + int imageWidth, imageHeight;/* New dimensions of image. */ +{ + ImageMaster *masterPtr = (ImageMaster *) imageMaster; + Image *imagePtr; + + masterPtr->width = imageWidth; + masterPtr->height = imageHeight; + for (imagePtr = masterPtr->instancePtr; imagePtr != NULL; + imagePtr = imagePtr->nextPtr) { + (*imagePtr->changeProc)(imagePtr->widgetClientData, x, y, + width, height, imageWidth, imageHeight); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_NameOfImage -- + * + * Given a token for an image master, this procedure returns + * the name of the image. + * + * Results: + * The return value is the string name for imageMaster. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +char * +Tk_NameOfImage(imageMaster) + Tk_ImageMaster imageMaster; /* Token for image. */ +{ + ImageMaster *masterPtr = (ImageMaster *) imageMaster; + + return Tcl_GetHashKey(masterPtr->tablePtr, masterPtr->hPtr); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetImage -- + * + * This procedure is invoked by a widget when it wants to use + * a particular image in a particular window. + * + * Results: + * The return value is a token for the image. If there is no image + * by the given name, then NULL is returned and an error message is + * left in interp->result. + * + * Side effects: + * Tk records the fact that the widget is using the image, and + * it will invoke changeProc later if the widget needs redisplay + * (i.e. its size changes or some of its pixels change). The + * caller must eventually invoke Tk_FreeImage when it no longer + * needs the image. + * + *---------------------------------------------------------------------- + */ + +Tk_Image +Tk_GetImage(interp, tkwin, name, changeProc, clientData) + Tcl_Interp *interp; /* Place to leave error message if image + * can't be found. */ + Tk_Window tkwin; /* Token for window in which image will + * be used. */ + char *name; /* Name of desired image. */ + Tk_ImageChangedProc *changeProc; + /* Procedure to invoke when redisplay is + * needed because image's pixels or size + * changed. */ + ClientData clientData; /* One-word argument to pass to damageProc. */ +{ + Tcl_HashEntry *hPtr; + ImageMaster *masterPtr; + Image *imagePtr; + + hPtr = Tcl_FindHashEntry(&((TkWindow *) tkwin)->mainPtr->imageTable, name); + if (hPtr == NULL) { + goto noSuchImage; + } + masterPtr = (ImageMaster *) Tcl_GetHashValue(hPtr); + if (masterPtr->typePtr == NULL) { + goto noSuchImage; + } + imagePtr = (Image *) ckalloc(sizeof(Image)); + imagePtr->tkwin = tkwin; + imagePtr->display = Tk_Display(tkwin); + imagePtr->masterPtr = masterPtr; + imagePtr->instanceData = + (*masterPtr->typePtr->getProc)(tkwin, masterPtr->masterData); + imagePtr->changeProc = changeProc; + imagePtr->widgetClientData = clientData; + imagePtr->nextPtr = masterPtr->instancePtr; + masterPtr->instancePtr = imagePtr; + return (Tk_Image) imagePtr; + + noSuchImage: + Tcl_AppendResult(interp, "image \"", name, "\" doesn't exist", + (char *) NULL); + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreeImage -- + * + * This procedure is invoked by a widget when it no longer needs + * an image acquired by a previous call to Tk_GetImage. For each + * call to Tk_GetImage there must be exactly one call to Tk_FreeImage. + * + * Results: + * None. + * + * Side effects: + * The association between the image and the widget is removed. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreeImage(image) + Tk_Image image; /* Token for image that is no longer + * needed by a widget. */ +{ + Image *imagePtr = (Image *) image; + ImageMaster *masterPtr = imagePtr->masterPtr; + Image *prevPtr; + + /* + * Clean up the particular instance. + */ + + if (masterPtr->typePtr != NULL) { + (*masterPtr->typePtr->freeProc)(imagePtr->instanceData, + imagePtr->display); + } + prevPtr = masterPtr->instancePtr; + if (prevPtr == imagePtr) { + masterPtr->instancePtr = imagePtr->nextPtr; + } else { + while (prevPtr->nextPtr != imagePtr) { + prevPtr = prevPtr->nextPtr; + } + prevPtr->nextPtr = imagePtr->nextPtr; + } + ckfree((char *) imagePtr); + + /* + * If there are no more instances left for the master, and if the + * master image has been deleted, then delete the master too. + */ + + if ((masterPtr->typePtr == NULL) && (masterPtr->instancePtr == NULL)) { + Tcl_DeleteHashEntry(masterPtr->hPtr); + ckfree((char *) masterPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_RedrawImage -- + * + * This procedure is called by widgets that contain images in order + * to redisplay an image on the screen or an off-screen pixmap. + * + * Results: + * None. + * + * Side effects: + * The image's manager is notified, and it redraws the desired + * portion of the image before returning. + * + *---------------------------------------------------------------------- + */ + +void +Tk_RedrawImage(image, imageX, imageY, width, height, drawable, + drawableX, drawableY) + Tk_Image image; /* Token for image to redisplay. */ + int imageX, imageY; /* Upper-left pixel of region in image that + * needs to be redisplayed. */ + int width, height; /* Dimensions of region to redraw. */ + Drawable drawable; /* Drawable in which to display image + * (window or pixmap). If this is a pixmap, + * it must have the same depth as the window + * used in the Tk_GetImage call for the + * image. */ + int drawableX, drawableY; /* Coordinates in drawable that correspond + * to imageX and imageY. */ +{ + Image *imagePtr = (Image *) image; + + if (imagePtr->masterPtr->typePtr == NULL) { + /* + * No master for image, so nothing to display. + */ + + return; + } + + /* + * Clip the redraw area to the area of the image. + */ + + if (imageX < 0) { + width += imageX; + drawableX -= imageX; + imageX = 0; + } + if (imageY < 0) { + height += imageY; + drawableY -= imageY; + imageY = 0; + } + if ((imageX + width) > imagePtr->masterPtr->width) { + width = imagePtr->masterPtr->width - imageX; + } + if ((imageY + height) > imagePtr->masterPtr->height) { + height = imagePtr->masterPtr->height - imageY; + } + (*imagePtr->masterPtr->typePtr->displayProc)( + imagePtr->instanceData, imagePtr->display, drawable, + imageX, imageY, width, height, drawableX, drawableY); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_SizeOfImage -- + * + * This procedure returns the current dimensions of an image. + * + * Results: + * The width and height of the image are returned in *widthPtr + * and *heightPtr. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +Tk_SizeOfImage(image, widthPtr, heightPtr) + Tk_Image image; /* Token for image whose size is wanted. */ + int *widthPtr; /* Return width of image here. */ + int *heightPtr; /* Return height of image here. */ +{ + Image *imagePtr = (Image *) image; + + *widthPtr = imagePtr->masterPtr->width; + *heightPtr = imagePtr->masterPtr->height; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_DeleteImage -- + * + * Given the name of an image, this procedure destroys the + * image. + * + * Results: + * None. + * + * Side effects: + * The image is destroyed; existing instances will display as + * blank areas. If no such image exists then the procedure does + * nothing. + * + *---------------------------------------------------------------------- + */ + +void +Tk_DeleteImage(interp, name) + Tcl_Interp *interp; /* Interpreter in which the image was + * created. */ + char *name; /* Name of image. */ +{ + Tcl_HashEntry *hPtr; + TkWindow *winPtr; + + winPtr = (TkWindow *) Tk_MainWindow(interp); + if (winPtr == NULL) { + return; + } + hPtr = Tcl_FindHashEntry(&winPtr->mainPtr->imageTable, name); + if (hPtr == NULL) { + return; + } + DeleteImage((ImageMaster *) Tcl_GetHashValue(hPtr)); +} + +/* + *---------------------------------------------------------------------- + * + * DeleteImage -- + * + * This procedure is responsible for deleting an image. + * + * Results: + * None. + * + * Side effects: + * The connection is dropped between instances of this image and + * an image master. Image instances will redisplay themselves + * as empty areas, but existing instances will not be deleted. + * + *---------------------------------------------------------------------- + */ + +static void +DeleteImage(masterPtr) + ImageMaster *masterPtr; /* Pointer to main data structure for image. */ +{ + Image *imagePtr; + Tk_ImageType *typePtr; + + typePtr = masterPtr->typePtr; + masterPtr->typePtr = NULL; + if (typePtr != NULL) { + for (imagePtr = masterPtr->instancePtr; imagePtr != NULL; + imagePtr = imagePtr->nextPtr) { + (*typePtr->freeProc)(imagePtr->instanceData, + imagePtr->display); + (*imagePtr->changeProc)(imagePtr->widgetClientData, 0, 0, + masterPtr->width, masterPtr->height, masterPtr->width, + masterPtr->height); + } + (*typePtr->deleteProc)(masterPtr->masterData); + } + if (masterPtr->instancePtr == NULL) { + Tcl_DeleteHashEntry(masterPtr->hPtr); + ckfree((char *) masterPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkDeleteAllImages -- + * + * This procedure is called when an application is deleted. It + * calls back all of the managers for all images so that they + * can cleanup, then it deletes all of Tk's internal information + * about images. + * + * Results: + * None. + * + * Side effects: + * All information for all images gets deleted. + * + *---------------------------------------------------------------------- + */ + +void +TkDeleteAllImages(mainPtr) + TkMainInfo *mainPtr; /* Structure describing application that is + * going away. */ +{ + Tcl_HashSearch search; + Tcl_HashEntry *hPtr; + ImageMaster *masterPtr; + + for (hPtr = Tcl_FirstHashEntry(&mainPtr->imageTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + masterPtr = (ImageMaster *) Tcl_GetHashValue(hPtr); + DeleteImage(masterPtr); + } + Tcl_DeleteHashTable(&mainPtr->imageTable); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetImageMasterData -- + * + * Given the name of an image, this procedure returns the type + * of the image and the clientData associated with its master. + * + * Results: + * If there is no image by the given name, then NULL is returned + * and a NULL value is stored at *typePtrPtr. Otherwise the return + * value is the clientData returned by the createProc when the + * image was created and a pointer to the type structure for the + * image is stored at *typePtrPtr. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +ClientData +Tk_GetImageMasterData(interp, name, typePtrPtr) + Tcl_Interp *interp; /* Interpreter in which the image was + * created. */ + char *name; /* Name of image. */ + Tk_ImageType **typePtrPtr; /* Points to location to fill in with + * pointer to type information for image. */ +{ + Tcl_HashEntry *hPtr; + TkWindow *winPtr; + ImageMaster *masterPtr; + + winPtr = (TkWindow *) Tk_MainWindow(interp); + hPtr = Tcl_FindHashEntry(&winPtr->mainPtr->imageTable, name); + if (hPtr == NULL) { + *typePtrPtr = NULL; + return NULL; + } + masterPtr = (ImageMaster *) Tcl_GetHashValue(hPtr); + *typePtrPtr = masterPtr->typePtr; + return masterPtr->masterData; +} diff --git a/generic/tkImgBmap.c b/generic/tkImgBmap.c new file mode 100644 index 0000000..f8a1d6e --- /dev/null +++ b/generic/tkImgBmap.c @@ -0,0 +1,1061 @@ +/* + * tkImgBmap.c -- + * + * This procedure implements images of type "bitmap" for Tk. + * + * Copyright (c) 1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkImgBmap.c 1.33 97/07/31 09:08:22 + */ + +#include "tkInt.h" +#include "tkPort.h" + +/* + * The following data structure represents the master for a bitmap + * image: + */ + +typedef struct BitmapMaster { + Tk_ImageMaster tkMaster; /* Tk's token for image master. NULL means + * the image is being deleted. */ + Tcl_Interp *interp; /* Interpreter for application that is + * using image. */ + Tcl_Command imageCmd; /* Token for image command (used to delete + * it when the image goes away). NULL means + * the image command has already been + * deleted. */ + int width, height; /* Dimensions of image. */ + char *data; /* Data comprising bitmap (suitable for + * input to XCreateBitmapFromData). May + * be NULL if no data. Malloc'ed. */ + char *maskData; /* Data for bitmap's mask (suitable for + * input to XCreateBitmapFromData). + * Malloc'ed. */ + Tk_Uid fgUid; /* Value of -foreground option (malloc'ed). */ + Tk_Uid bgUid; /* Value of -background option (malloc'ed). */ + char *fileString; /* Value of -file option (malloc'ed). */ + char *dataString; /* Value of -data option (malloc'ed). */ + char *maskFileString; /* Value of -maskfile option (malloc'ed). */ + char *maskDataString; /* Value of -maskdata option (malloc'ed). */ + struct BitmapInstance *instancePtr; + /* First in list of all instances associated + * with this master. */ +} BitmapMaster; + +/* + * The following data structure represents all of the instances of an + * image that lie within a particular window: + */ + +typedef struct BitmapInstance { + int refCount; /* Number of instances that share this + * data structure. */ + BitmapMaster *masterPtr; /* Pointer to master for image. */ + Tk_Window tkwin; /* Window in which the instances will be + * displayed. */ + XColor *fg; /* Foreground color for displaying image. */ + XColor *bg; /* Background color for displaying image. */ + Pixmap bitmap; /* The bitmap to display. */ + Pixmap mask; /* Mask: only display bitmap pixels where + * there are 1's here. */ + GC gc; /* Graphics context for displaying bitmap. + * None means there was an error while + * setting up the instance, so it cannot + * be displayed. */ + struct BitmapInstance *nextPtr; + /* Next in list of all instance structures + * associated with masterPtr (NULL means + * end of list). */ +} BitmapInstance; + +/* + * The type record for bitmap images: + */ + +static int GetByte _ANSI_ARGS_((Tcl_Channel chan)); +static int ImgBmapCreate _ANSI_ARGS_((Tcl_Interp *interp, + char *name, int argc, char **argv, + Tk_ImageType *typePtr, Tk_ImageMaster master, + ClientData *clientDataPtr)); +static ClientData ImgBmapGet _ANSI_ARGS_((Tk_Window tkwin, + ClientData clientData)); +static void ImgBmapDisplay _ANSI_ARGS_((ClientData clientData, + Display *display, Drawable drawable, + int imageX, int imageY, int width, int height, + int drawableX, int drawableY)); +static void ImgBmapFree _ANSI_ARGS_((ClientData clientData, + Display *display)); +static void ImgBmapDelete _ANSI_ARGS_((ClientData clientData)); + +Tk_ImageType tkBitmapImageType = { + "bitmap", /* name */ + ImgBmapCreate, /* createProc */ + ImgBmapGet, /* getProc */ + ImgBmapDisplay, /* displayProc */ + ImgBmapFree, /* freeProc */ + ImgBmapDelete, /* deleteProc */ + (Tk_ImageType *) NULL /* nextPtr */ +}; + +/* + * Information used for parsing configuration specs: + */ + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_UID, "-background", (char *) NULL, (char *) NULL, + "", Tk_Offset(BitmapMaster, bgUid), 0}, + {TK_CONFIG_STRING, "-data", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(BitmapMaster, dataString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-file", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(BitmapMaster, fileString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_UID, "-foreground", (char *) NULL, (char *) NULL, + "#000000", Tk_Offset(BitmapMaster, fgUid), 0}, + {TK_CONFIG_STRING, "-maskdata", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(BitmapMaster, maskDataString), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-maskfile", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(BitmapMaster, maskFileString), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * The following data structure is used to describe the state of + * parsing a bitmap file or string. It is used for communication + * between TkGetBitmapData and NextBitmapWord. + */ + +#define MAX_WORD_LENGTH 100 +typedef struct ParseInfo { + char *string; /* Next character of string data for bitmap, + * or NULL if bitmap is being read from + * file. */ + Tcl_Channel chan; /* File containing bitmap data, or NULL + * if no file. */ + char word[MAX_WORD_LENGTH+1]; + /* Current word of bitmap data, NULL + * terminated. */ + int wordLength; /* Number of non-NULL bytes in word. */ +} ParseInfo; + +/* + * Prototypes for procedures used only locally in this file: + */ + +static int ImgBmapCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void ImgBmapCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static void ImgBmapConfigureInstance _ANSI_ARGS_(( + BitmapInstance *instancePtr)); +static int ImgBmapConfigureMaster _ANSI_ARGS_(( + BitmapMaster *masterPtr, int argc, char **argv, + int flags)); +static int NextBitmapWord _ANSI_ARGS_((ParseInfo *parseInfoPtr)); + +/* + *---------------------------------------------------------------------- + * + * ImgBmapCreate -- + * + * This procedure is called by the Tk image code to create "test" + * images. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * The data structure for a new image is allocated. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +ImgBmapCreate(interp, name, argc, argv, typePtr, master, clientDataPtr) + Tcl_Interp *interp; /* Interpreter for application containing + * image. */ + char *name; /* Name to use for image. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings for options (doesn't + * include image name or type). */ + Tk_ImageType *typePtr; /* Pointer to our type record (not used). */ + Tk_ImageMaster master; /* Token for image, to be used by us in + * later callbacks. */ + ClientData *clientDataPtr; /* Store manager's token for image here; + * it will be returned in later callbacks. */ +{ + BitmapMaster *masterPtr; + + masterPtr = (BitmapMaster *) ckalloc(sizeof(BitmapMaster)); + masterPtr->tkMaster = master; + masterPtr->interp = interp; + masterPtr->imageCmd = Tcl_CreateCommand(interp, name, ImgBmapCmd, + (ClientData) masterPtr, ImgBmapCmdDeletedProc); + masterPtr->width = masterPtr->height = 0; + masterPtr->data = NULL; + masterPtr->maskData = NULL; + masterPtr->fgUid = NULL; + masterPtr->bgUid = NULL; + masterPtr->fileString = NULL; + masterPtr->dataString = NULL; + masterPtr->maskFileString = NULL; + masterPtr->maskDataString = NULL; + masterPtr->instancePtr = NULL; + if (ImgBmapConfigureMaster(masterPtr, argc, argv, 0) != TCL_OK) { + ImgBmapDelete((ClientData) masterPtr); + return TCL_ERROR; + } + *clientDataPtr = (ClientData) masterPtr; + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ImgBmapConfigureMaster -- + * + * This procedure is called when a bitmap image is created or + * reconfigured. It process configuration options and resets + * any instances of the image. + * + * Results: + * A standard Tcl return value. If TCL_ERROR is returned then + * an error message is left in masterPtr->interp->result. + * + * Side effects: + * Existing instances of the image will be redisplayed to match + * the new configuration options. + * + *---------------------------------------------------------------------- + */ + +static int +ImgBmapConfigureMaster(masterPtr, argc, argv, flags) + BitmapMaster *masterPtr; /* Pointer to data structure describing + * overall bitmap image to (reconfigure). */ + int argc; /* Number of entries in argv. */ + char **argv; /* Pairs of configuration options for image. */ + int flags; /* Flags to pass to Tk_ConfigureWidget, + * such as TK_CONFIG_ARGV_ONLY. */ +{ + BitmapInstance *instancePtr; + int maskWidth, maskHeight, dummy1, dummy2; + + if (Tk_ConfigureWidget(masterPtr->interp, Tk_MainWindow(masterPtr->interp), + configSpecs, argc, argv, (char *) masterPtr, flags) + != TCL_OK) { + return TCL_ERROR; + } + + /* + * Parse the bitmap and/or mask to create binary data. Make sure that + * the bitmap and mask have the same dimensions. + */ + + if (masterPtr->data != NULL) { + ckfree(masterPtr->data); + masterPtr->data = NULL; + } + if ((masterPtr->fileString != NULL) || (masterPtr->dataString != NULL)) { + masterPtr->data = TkGetBitmapData(masterPtr->interp, + masterPtr->dataString, masterPtr->fileString, + &masterPtr->width, &masterPtr->height, &dummy1, &dummy2); + if (masterPtr->data == NULL) { + return TCL_ERROR; + } + } + if (masterPtr->maskData != NULL) { + ckfree(masterPtr->maskData); + masterPtr->maskData = NULL; + } + if ((masterPtr->maskFileString != NULL) + || (masterPtr->maskDataString != NULL)) { + if (masterPtr->data == NULL) { + masterPtr->interp->result = "can't have mask without bitmap"; + return TCL_ERROR; + } + masterPtr->maskData = TkGetBitmapData(masterPtr->interp, + masterPtr->maskDataString, masterPtr->maskFileString, + &maskWidth, &maskHeight, &dummy1, &dummy2); + if (masterPtr->maskData == NULL) { + return TCL_ERROR; + } + if ((maskWidth != masterPtr->width) + || (maskHeight != masterPtr->height)) { + ckfree(masterPtr->maskData); + masterPtr->maskData = NULL; + masterPtr->interp->result = "bitmap and mask have different sizes"; + return TCL_ERROR; + } + } + + /* + * Cycle through all of the instances of this image, regenerating + * the information for each instance. Then force the image to be + * redisplayed everywhere that it is used. + */ + + for (instancePtr = masterPtr->instancePtr; instancePtr != NULL; + instancePtr = instancePtr->nextPtr) { + ImgBmapConfigureInstance(instancePtr); + } + Tk_ImageChanged(masterPtr->tkMaster, 0, 0, masterPtr->width, + masterPtr->height, masterPtr->width, masterPtr->height); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ImgBmapConfigureInstance -- + * + * This procedure is called to create displaying information for + * a bitmap image instance based on the configuration information + * in the master. It is invoked both when new instances are + * created and when the master is reconfigured. + * + * Results: + * None. + * + * Side effects: + * Generates errors via Tcl_BackgroundError if there are problems + * in setting up the instance. + * + *---------------------------------------------------------------------- + */ + +static void +ImgBmapConfigureInstance(instancePtr) + BitmapInstance *instancePtr; /* Instance to reconfigure. */ +{ + BitmapMaster *masterPtr = instancePtr->masterPtr; + XColor *colorPtr; + XGCValues gcValues; + GC gc; + unsigned int mask; + + /* + * For each of the options in masterPtr, translate the string + * form into an internal form appropriate for instancePtr. + */ + + if (*masterPtr->bgUid != 0) { + colorPtr = Tk_GetColor(masterPtr->interp, instancePtr->tkwin, + masterPtr->bgUid); + if (colorPtr == NULL) { + goto error; + } + } else { + colorPtr = NULL; + } + if (instancePtr->bg != NULL) { + Tk_FreeColor(instancePtr->bg); + } + instancePtr->bg = colorPtr; + + colorPtr = Tk_GetColor(masterPtr->interp, instancePtr->tkwin, + masterPtr->fgUid); + if (colorPtr == NULL) { + goto error; + } + if (instancePtr->fg != NULL) { + Tk_FreeColor(instancePtr->fg); + } + instancePtr->fg = colorPtr; + + if (instancePtr->bitmap != None) { + Tk_FreePixmap(Tk_Display(instancePtr->tkwin), instancePtr->bitmap); + instancePtr->bitmap = None; + } + if (masterPtr->data != NULL) { + instancePtr->bitmap = XCreateBitmapFromData( + Tk_Display(instancePtr->tkwin), + RootWindowOfScreen(Tk_Screen(instancePtr->tkwin)), + masterPtr->data, (unsigned) masterPtr->width, + (unsigned) masterPtr->height); + } + + if (instancePtr->mask != None) { + Tk_FreePixmap(Tk_Display(instancePtr->tkwin), instancePtr->mask); + instancePtr->mask = None; + } + if (masterPtr->maskData != NULL) { + instancePtr->mask = XCreateBitmapFromData( + Tk_Display(instancePtr->tkwin), + RootWindowOfScreen(Tk_Screen(instancePtr->tkwin)), + masterPtr->maskData, (unsigned) masterPtr->width, + (unsigned) masterPtr->height); + } + + if (masterPtr->data != NULL) { + gcValues.foreground = instancePtr->fg->pixel; + gcValues.graphics_exposures = False; + mask = GCForeground|GCGraphicsExposures; + if (instancePtr->bg != NULL) { + gcValues.background = instancePtr->bg->pixel; + mask |= GCBackground; + if (instancePtr->mask != None) { + gcValues.clip_mask = instancePtr->mask; + mask |= GCClipMask; + } + } else { + gcValues.clip_mask = instancePtr->bitmap; + mask |= GCClipMask; + } + gc = Tk_GetGC(instancePtr->tkwin, mask, &gcValues); + } else { + gc = None; + } + if (instancePtr->gc != None) { + Tk_FreeGC(Tk_Display(instancePtr->tkwin), instancePtr->gc); + } + instancePtr->gc = gc; + return; + + error: + /* + * An error occurred: clear the graphics context in the instance to + * make it clear that this instance cannot be displayed. Then report + * the error. + */ + + if (instancePtr->gc != None) { + Tk_FreeGC(Tk_Display(instancePtr->tkwin), instancePtr->gc); + } + instancePtr->gc = None; + Tcl_AddErrorInfo(masterPtr->interp, "\n (while configuring image \""); + Tcl_AddErrorInfo(masterPtr->interp, Tk_NameOfImage(masterPtr->tkMaster)); + Tcl_AddErrorInfo(masterPtr->interp, "\")"); + Tcl_BackgroundError(masterPtr->interp); +} + +/* + *---------------------------------------------------------------------- + * + * TkGetBitmapData -- + * + * Given a file name or ASCII string, this procedure parses the + * file or string contents to produce binary data for a bitmap. + * + * Results: + * If the bitmap description was parsed successfully then the + * return value is a malloc-ed array containing the bitmap data. + * The dimensions of the data are stored in *widthPtr and + * *heightPtr. *hotXPtr and *hotYPtr are set to the bitmap + * hotspot if one is defined, otherwise they are set to -1, -1. + * If an error occurred, NULL is returned and an error message is + * left in interp->result. + * + * Side effects: + * A bitmap is created. + * + *---------------------------------------------------------------------- + */ + +char * +TkGetBitmapData(interp, string, fileName, widthPtr, heightPtr, + hotXPtr, hotYPtr) + Tcl_Interp *interp; /* For reporting errors. */ + char *string; /* String describing bitmap. May + * be NULL. */ + char *fileName; /* Name of file containing bitmap + * description. Used only if string + * is NULL. Must not be NULL if + * string is NULL. */ + int *widthPtr, *heightPtr; /* Dimensions of bitmap get returned + * here. */ + int *hotXPtr, *hotYPtr; /* Position of hot spot or -1,-1. */ +{ + int width, height, numBytes, hotX, hotY; + char *p, *end, *expandedFileName; + ParseInfo pi; + char *data = NULL; + Tcl_DString buffer; + + pi.string = string; + if (string == NULL) { + if (Tcl_IsSafe(interp)) { + Tcl_AppendResult(interp, "can't get bitmap data from a file in a", + " safe interpreter", (char *) NULL); + return NULL; + } + expandedFileName = Tcl_TranslateFileName(interp, fileName, &buffer); + if (expandedFileName == NULL) { + return NULL; + } + pi.chan = Tcl_OpenFileChannel(interp, expandedFileName, "r", 0); + Tcl_DStringFree(&buffer); + if (pi.chan == NULL) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "couldn't read bitmap file \"", + fileName, "\": ", Tcl_PosixError(interp), (char *) NULL); + return NULL; + } + } else { + pi.chan = NULL; + } + + /* + * Parse the lines that define the dimensions of the bitmap, + * plus the first line that defines the bitmap data (it declares + * the name of a data variable but doesn't include any actual + * data). These lines look something like the following: + * + * #define foo_width 16 + * #define foo_height 16 + * #define foo_x_hot 3 + * #define foo_y_hot 3 + * static char foo_bits[] = { + * + * The x_hot and y_hot lines may or may not be present. It's + * important to check for "char" in the last line, in order to + * reject old X10-style bitmaps that used shorts. + */ + + width = 0; + height = 0; + hotX = -1; + hotY = -1; + while (1) { + if (NextBitmapWord(&pi) != TCL_OK) { + goto error; + } + if ((pi.wordLength >= 6) && (pi.word[pi.wordLength-6] == '_') + && (strcmp(pi.word+pi.wordLength-6, "_width") == 0)) { + if (NextBitmapWord(&pi) != TCL_OK) { + goto error; + } + width = strtol(pi.word, &end, 0); + if ((end == pi.word) || (*end != 0)) { + goto error; + } + } else if ((pi.wordLength >= 7) && (pi.word[pi.wordLength-7] == '_') + && (strcmp(pi.word+pi.wordLength-7, "_height") == 0)) { + if (NextBitmapWord(&pi) != TCL_OK) { + goto error; + } + height = strtol(pi.word, &end, 0); + if ((end == pi.word) || (*end != 0)) { + goto error; + } + } else if ((pi.wordLength >= 6) && (pi.word[pi.wordLength-6] == '_') + && (strcmp(pi.word+pi.wordLength-6, "_x_hot") == 0)) { + if (NextBitmapWord(&pi) != TCL_OK) { + goto error; + } + hotX = strtol(pi.word, &end, 0); + if ((end == pi.word) || (*end != 0)) { + goto error; + } + } else if ((pi.wordLength >= 6) && (pi.word[pi.wordLength-6] == '_') + && (strcmp(pi.word+pi.wordLength-6, "_y_hot") == 0)) { + if (NextBitmapWord(&pi) != TCL_OK) { + goto error; + } + hotY = strtol(pi.word, &end, 0); + if ((end == pi.word) || (*end != 0)) { + goto error; + } + } else if ((pi.word[0] == 'c') && (strcmp(pi.word, "char") == 0)) { + while (1) { + if (NextBitmapWord(&pi) != TCL_OK) { + goto error; + } + if ((pi.word[0] == '{') && (pi.word[1] == 0)) { + goto getData; + } + } + } else if ((pi.word[0] == '{') && (pi.word[1] == 0)) { + Tcl_AppendResult(interp, "format error in bitmap data; ", + "looks like it's an obsolete X10 bitmap file", + (char *) NULL); + goto errorCleanup; + } + } + + /* + * Now we've read everything but the data. Allocate an array + * and read in the data. + */ + + getData: + if ((width <= 0) || (height <= 0)) { + goto error; + } + numBytes = ((width+7)/8) * height; + data = (char *) ckalloc((unsigned) numBytes); + for (p = data; numBytes > 0; p++, numBytes--) { + if (NextBitmapWord(&pi) != TCL_OK) { + goto error; + } + *p = (char) strtol(pi.word, &end, 0); + if (end == pi.word) { + goto error; + } + } + + /* + * All done. Clean up and return. + */ + + if (pi.chan != NULL) { + Tcl_Close(NULL, pi.chan); + } + *widthPtr = width; + *heightPtr = height; + *hotXPtr = hotX; + *hotYPtr = hotY; + return data; + + error: + interp->result = "format error in bitmap data"; + errorCleanup: + if (data != NULL) { + ckfree(data); + } + if (pi.chan != NULL) { + Tcl_Close(NULL, pi.chan); + } + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * NextBitmapWord -- + * + * This procedure retrieves the next word of information (stuff + * between commas or white space) from a bitmap description. + * + * Results: + * Returns TCL_OK if all went well. In this case the next word, + * and its length, will be availble in *parseInfoPtr. If the end + * of the bitmap description was reached then TCL_ERROR is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +NextBitmapWord(parseInfoPtr) + ParseInfo *parseInfoPtr; /* Describes what we're reading + * and where we are in it. */ +{ + char *src, *dst; + int c; + + parseInfoPtr->wordLength = 0; + dst = parseInfoPtr->word; + if (parseInfoPtr->string != NULL) { + for (src = parseInfoPtr->string; isspace(UCHAR(*src)) || (*src == ','); + src++) { + if (*src == 0) { + return TCL_ERROR; + } + } + for ( ; !isspace(UCHAR(*src)) && (*src != ',') && (*src != 0); src++) { + *dst = *src; + dst++; + parseInfoPtr->wordLength++; + if (parseInfoPtr->wordLength > MAX_WORD_LENGTH) { + return TCL_ERROR; + } + } + parseInfoPtr->string = src; + } else { + for (c = GetByte(parseInfoPtr->chan); isspace(UCHAR(c)) || (c == ','); + c = GetByte(parseInfoPtr->chan)) { + if (c == EOF) { + return TCL_ERROR; + } + } + for ( ; !isspace(UCHAR(c)) && (c != ',') && (c != EOF); + c = GetByte(parseInfoPtr->chan)) { + *dst = c; + dst++; + parseInfoPtr->wordLength++; + if (parseInfoPtr->wordLength > MAX_WORD_LENGTH) { + return TCL_ERROR; + } + } + } + if (parseInfoPtr->wordLength == 0) { + return TCL_ERROR; + } + parseInfoPtr->word[parseInfoPtr->wordLength] = 0; + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ImgBmapCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to an image managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +ImgBmapCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about the image master. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + BitmapMaster *masterPtr = (BitmapMaster *) clientData; + int c, code; + size_t length; + + if (argc < 2) { + sprintf(interp->result, + "wrong # args: should be \"%.50s option ?arg arg ...?\"", + argv[0]); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + return TCL_ERROR; + } + return Tk_ConfigureValue(interp, Tk_MainWindow(interp), configSpecs, + (char *) masterPtr, argv[2], 0); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 2)) { + if (argc == 2) { + code = Tk_ConfigureInfo(interp, Tk_MainWindow(interp), + configSpecs, (char *) masterPtr, (char *) NULL, 0); + } else if (argc == 3) { + code = Tk_ConfigureInfo(interp, Tk_MainWindow(interp), + configSpecs, (char *) masterPtr, argv[2], 0); + } else { + code = ImgBmapConfigureMaster(masterPtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + return code; + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be cget or configure", (char *) NULL); + return TCL_ERROR; + } +} + +/* + *---------------------------------------------------------------------- + * + * ImgBmapGet -- + * + * This procedure is called for each use of a bitmap image in a + * widget. + * + * Results: + * The return value is a token for the instance, which is passed + * back to us in calls to ImgBmapDisplay and ImgBmapFree. + * + * Side effects: + * A data structure is set up for the instance (or, an existing + * instance is re-used for the new one). + * + *---------------------------------------------------------------------- + */ + +static ClientData +ImgBmapGet(tkwin, masterData) + Tk_Window tkwin; /* Window in which the instance will be + * used. */ + ClientData masterData; /* Pointer to our master structure for the + * image. */ +{ + BitmapMaster *masterPtr = (BitmapMaster *) masterData; + BitmapInstance *instancePtr; + + /* + * See if there is already an instance for this window. If so + * then just re-use it. + */ + + for (instancePtr = masterPtr->instancePtr; instancePtr != NULL; + instancePtr = instancePtr->nextPtr) { + if (instancePtr->tkwin == tkwin) { + instancePtr->refCount++; + return (ClientData) instancePtr; + } + } + + /* + * The image isn't already in use in this window. Make a new + * instance of the image. + */ + + instancePtr = (BitmapInstance *) ckalloc(sizeof(BitmapInstance)); + instancePtr->refCount = 1; + instancePtr->masterPtr = masterPtr; + instancePtr->tkwin = tkwin; + instancePtr->fg = NULL; + instancePtr->bg = NULL; + instancePtr->bitmap = None; + instancePtr->mask = None; + instancePtr->gc = None; + instancePtr->nextPtr = masterPtr->instancePtr; + masterPtr->instancePtr = instancePtr; + ImgBmapConfigureInstance(instancePtr); + + /* + * If this is the first instance, must set the size of the image. + */ + + if (instancePtr->nextPtr == NULL) { + Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0, masterPtr->width, + masterPtr->height); + } + + return (ClientData) instancePtr; +} + +/* + *---------------------------------------------------------------------- + * + * ImgBmapDisplay -- + * + * This procedure is invoked to draw a bitmap image. + * + * Results: + * None. + * + * Side effects: + * A portion of the image gets rendered in a pixmap or window. + * + *---------------------------------------------------------------------- + */ + +static void +ImgBmapDisplay(clientData, display, drawable, imageX, imageY, width, + height, drawableX, drawableY) + ClientData clientData; /* Pointer to BitmapInstance structure for + * for instance to be displayed. */ + Display *display; /* Display on which to draw image. */ + Drawable drawable; /* Pixmap or window in which to draw image. */ + int imageX, imageY; /* Upper-left corner of region within image + * to draw. */ + int width, height; /* Dimensions of region within image to draw. */ + int drawableX, drawableY; /* Coordinates within drawable that + * correspond to imageX and imageY. */ +{ + BitmapInstance *instancePtr = (BitmapInstance *) clientData; + int masking; + + /* + * If there's no graphics context, it means that an error occurred + * while creating the image instance so it can't be displayed. + */ + + if (instancePtr->gc == None) { + return; + } + + /* + * If masking is in effect, must modify the mask origin within + * the graphics context to line up with the image's origin. + * Then draw the image and reset the clip origin, if there's + * a mask. + */ + + masking = (instancePtr->mask != None) || (instancePtr->bg == NULL); + if (masking) { + XSetClipOrigin(display, instancePtr->gc, drawableX - imageX, + drawableY - imageY); + } + XCopyPlane(display, instancePtr->bitmap, drawable, instancePtr->gc, + imageX, imageY, (unsigned) width, (unsigned) height, + drawableX, drawableY, 1); + if (masking) { + XSetClipOrigin(display, instancePtr->gc, 0, 0); + } +} + +/* + *---------------------------------------------------------------------- + * + * ImgBmapFree -- + * + * This procedure is called when a widget ceases to use a + * particular instance of an image. + * + * Results: + * None. + * + * Side effects: + * Internal data structures get cleaned up. + * + *---------------------------------------------------------------------- + */ + +static void +ImgBmapFree(clientData, display) + ClientData clientData; /* Pointer to BitmapInstance structure for + * for instance to be displayed. */ + Display *display; /* Display containing window that used image. */ +{ + BitmapInstance *instancePtr = (BitmapInstance *) clientData; + BitmapInstance *prevPtr; + + instancePtr->refCount--; + if (instancePtr->refCount > 0) { + return; + } + + /* + * There are no more uses of the image within this widget. Free + * the instance structure. + */ + + if (instancePtr->fg != NULL) { + Tk_FreeColor(instancePtr->fg); + } + if (instancePtr->bg != NULL) { + Tk_FreeColor(instancePtr->bg); + } + if (instancePtr->bitmap != None) { + Tk_FreePixmap(display, instancePtr->bitmap); + } + if (instancePtr->mask != None) { + Tk_FreePixmap(display, instancePtr->mask); + } + if (instancePtr->gc != None) { + Tk_FreeGC(display, instancePtr->gc); + } + if (instancePtr->masterPtr->instancePtr == instancePtr) { + instancePtr->masterPtr->instancePtr = instancePtr->nextPtr; + } else { + for (prevPtr = instancePtr->masterPtr->instancePtr; + prevPtr->nextPtr != instancePtr; prevPtr = prevPtr->nextPtr) { + /* Empty loop body */ + } + prevPtr->nextPtr = instancePtr->nextPtr; + } + ckfree((char *) instancePtr); +} + +/* + *---------------------------------------------------------------------- + * + * ImgBmapDelete -- + * + * This procedure is called by the image code to delete the + * master structure for an image. + * + * Results: + * None. + * + * Side effects: + * Resources associated with the image get freed. + * + *---------------------------------------------------------------------- + */ + +static void +ImgBmapDelete(masterData) + ClientData masterData; /* Pointer to BitmapMaster structure for + * image. Must not have any more instances. */ +{ + BitmapMaster *masterPtr = (BitmapMaster *) masterData; + + if (masterPtr->instancePtr != NULL) { + panic("tried to delete bitmap image when instances still exist"); + } + masterPtr->tkMaster = NULL; + if (masterPtr->imageCmd != NULL) { + Tcl_DeleteCommandFromToken(masterPtr->interp, masterPtr->imageCmd); + } + if (masterPtr->data != NULL) { + ckfree(masterPtr->data); + } + if (masterPtr->maskData != NULL) { + ckfree(masterPtr->maskData); + } + Tk_FreeOptions(configSpecs, (char *) masterPtr, (Display *) NULL, 0); + ckfree((char *) masterPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ImgBmapCmdDeletedProc -- + * + * This procedure is invoked when the image command for an image + * is deleted. It deletes the image. + * + * Results: + * None. + * + * Side effects: + * The image is deleted. + * + *---------------------------------------------------------------------- + */ + +static void +ImgBmapCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to BitmapMaster structure for + * image. */ +{ + BitmapMaster *masterPtr = (BitmapMaster *) clientData; + + masterPtr->imageCmd = NULL; + if (masterPtr->tkMaster != NULL) { + Tk_DeleteImage(masterPtr->interp, Tk_NameOfImage(masterPtr->tkMaster)); + } +} + +/* + *---------------------------------------------------------------------- + * + * GetByte -- + * + * Get the next byte from the open channel. + * + * Results: + * The next byte or EOF. + * + * Side effects: + * We read from the channel. + * + *---------------------------------------------------------------------- + */ + +static int +GetByte(chan) + Tcl_Channel chan; /* The channel we read from. */ +{ + char buffer; + int size; + + size = Tcl_Read(chan, &buffer, 1); + if (size <= 0) { + return EOF; + } else { + return buffer; + } +} diff --git a/generic/tkImgGIF.c b/generic/tkImgGIF.c new file mode 100644 index 0000000..a2ad081 --- /dev/null +++ b/generic/tkImgGIF.c @@ -0,0 +1,1059 @@ +/* + * tkImgGIF.c -- + * + * A photo image file handler for GIF files. Reads 87a and 89a GIF + * files. At present there is no write function. GIF images may be + * read using the -data option of the photo image by representing + * the data as BASE64 encoded ascii. Derived from the giftoppm code + * found in the pbmplus package and tkImgFmtPPM.c in the tk4.0b2 + * distribution. + * + * Copyright (c) Reed Wade (wade@cs.utk.edu), University of Tennessee + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * This file also contains code from the giftoppm program, which is + * copyrighted as follows: + * + * +-------------------------------------------------------------------+ + * | Copyright 1990, David Koblas. | + * | Permission to use, copy, modify, and distribute this software | + * | and its documentation for any purpose and without fee is hereby | + * | granted, provided that the above copyright notice appear in all | + * | copies and that both that copyright notice and this permission | + * | notice appear in supporting documentation. This software is | + * | provided "as is" without express or implied warranty. | + * +-------------------------------------------------------------------+ + * + * SCCS: @(#) tkImgGIF.c 1.19 97/08/13 15:23:45 + */ + +/* + * GIF's are represented as data in base64 format. + * base64 strings consist of 4 6-bit characters -> 3 8 bit bytes. + * A-Z, a-z, 0-9, + and / represent the 64 values (in order). + * '=' is a trailing padding char when the un-encoded data is not a + * multiple of 3 bytes. We'll ignore white space when encountered. + * Any other invalid character is treated as an EOF + */ + +#define GIF_SPECIAL (256) +#define GIF_PAD (GIF_SPECIAL+1) +#define GIF_SPACE (GIF_SPECIAL+2) +#define GIF_BAD (GIF_SPECIAL+3) +#define GIF_DONE (GIF_SPECIAL+4) + +/* + * structure to "mimic" FILE for Mread, so we can look like fread. + * The decoder state keeps track of which byte we are about to read, + * or EOF. + */ + +typedef struct mFile { + unsigned char *data; /* mmencoded source string */ + int c; /* bits left over from previous character */ + int state; /* decoder state (0-4 or GIF_DONE) */ +} MFile; + +#include "tkInt.h" +#include "tkPort.h" + +/* + * The format record for the GIF file format: + */ + +static int FileMatchGIF _ANSI_ARGS_((Tcl_Channel chan, char *fileName, + char *formatString, int *widthPtr, int *heightPtr)); +static int FileReadGIF _ANSI_ARGS_((Tcl_Interp *interp, + Tcl_Channel chan, char *fileName, char *formatString, + Tk_PhotoHandle imageHandle, int destX, int destY, + int width, int height, int srcX, int srcY)); +static int StringMatchGIF _ANSI_ARGS_(( char *string, + char *formatString, int *widthPtr, int *heightPtr)); +static int StringReadGIF _ANSI_ARGS_((Tcl_Interp *interp, char *string, + char *formatString, Tk_PhotoHandle imageHandle, + int destX, int destY, int width, int height, + int srcX, int srcY)); + +Tk_PhotoImageFormat tkImgFmtGIF = { + "GIF", /* name */ + FileMatchGIF, /* fileMatchProc */ + StringMatchGIF, /* stringMatchProc */ + FileReadGIF, /* fileReadProc */ + StringReadGIF, /* stringReadProc */ + NULL, /* fileWriteProc */ + NULL, /* stringWriteProc */ +}; + +#define INTERLACE 0x40 +#define LOCALCOLORMAP 0x80 +#define BitSet(byte, bit) (((byte) & (bit)) == (bit)) +#define MAXCOLORMAPSIZE 256 +#define CM_RED 0 +#define CM_GREEN 1 +#define CM_BLUE 2 +#define CM_ALPHA 3 +#define MAX_LWZ_BITS 12 +#define LM_to_uint(a,b) (((b)<<8)|(a)) +#define ReadOK(file,buffer,len) (Fread(buffer, len, 1, file) != 0) + +/* + * HACK ALERT!! HACK ALERT!! HACK ALERT!! + * This code is hard-wired for reading from files. In order to read + * from a data stream, we'll trick fread so we can reuse the same code + */ + +static int fromData=0; + +/* + * Prototypes for local procedures defined in this file: + */ + +static int DoExtension _ANSI_ARGS_((Tcl_Channel chan, int label, + int *transparent)); +static int GetCode _ANSI_ARGS_((Tcl_Channel chan, int code_size, + int flag)); +static int GetDataBlock _ANSI_ARGS_((Tcl_Channel chan, + unsigned char *buf)); +static int LWZReadByte _ANSI_ARGS_((Tcl_Channel chan, int flag, + int input_code_size)); +static int ReadColorMap _ANSI_ARGS_((Tcl_Channel chan, int number, + unsigned char buffer[MAXCOLORMAPSIZE][4])); +static int ReadGIFHeader _ANSI_ARGS_((Tcl_Channel chan, + int *widthPtr, int *heightPtr)); +static int ReadImage _ANSI_ARGS_((Tcl_Interp *interp, + char *imagePtr, Tcl_Channel chan, + int len, int rows, + unsigned char cmap[MAXCOLORMAPSIZE][4], + int width, int height, int srcX, int srcY, + int interlace, int transparent)); + +/* + * these are for the BASE64 image reader code only + */ + +static int Fread _ANSI_ARGS_((unsigned char *dst, size_t size, + size_t count, Tcl_Channel chan)); +static int Mread _ANSI_ARGS_((unsigned char *dst, size_t size, + size_t count, MFile *handle)); +static int Mgetc _ANSI_ARGS_((MFile *handle)); +static int char64 _ANSI_ARGS_((int c)); +static void mInit _ANSI_ARGS_((unsigned char *string, + MFile *handle)); + +/* + *---------------------------------------------------------------------- + * + * FileMatchGIF -- + * + * This procedure is invoked by the photo image type to see if + * a file contains image data in GIF format. + * + * Results: + * The return value is 1 if the first characters in file f look + * like GIF data, and 0 otherwise. + * + * Side effects: + * The access position in f may change. + * + *---------------------------------------------------------------------- + */ + +static int +FileMatchGIF(chan, fileName, formatString, widthPtr, heightPtr) + Tcl_Channel chan; /* The image file, open for reading. */ + char *fileName; /* The name of the image file. */ + char *formatString; /* User-specified format string, or NULL. */ + int *widthPtr, *heightPtr; /* The dimensions of the image are + * returned here if the file is a valid + * raw GIF file. */ +{ + return ReadGIFHeader(chan, widthPtr, heightPtr); +} + +/* + *---------------------------------------------------------------------- + * + * FileReadGIF -- + * + * This procedure is called by the photo image type to read + * GIF format data from a file and write it into a given + * photo image. + * + * Results: + * A standard TCL completion code. If TCL_ERROR is returned + * then an error message is left in interp->result. + * + * Side effects: + * The access position in file f is changed, and new data is + * added to the image given by imageHandle. + * + *---------------------------------------------------------------------- + */ + +static int +FileReadGIF(interp, chan, fileName, formatString, imageHandle, destX, destY, + width, height, srcX, srcY) + Tcl_Interp *interp; /* Interpreter to use for reporting errors. */ + Tcl_Channel chan; /* The image file, open for reading. */ + char *fileName; /* The name of the image file. */ + char *formatString; /* User-specified format string, or NULL. */ + Tk_PhotoHandle imageHandle; /* The photo image to write into. */ + int destX, destY; /* Coordinates of top-left pixel in + * photo image to be written to. */ + int width, height; /* Dimensions of block of photo image to + * be written to. */ + int srcX, srcY; /* Coordinates of top-left pixel to be used + * in image being read. */ +{ + int fileWidth, fileHeight; + int nBytes; + Tk_PhotoImageBlock block; + unsigned char buf[100]; + int bitPixel; + unsigned char colorMap[MAXCOLORMAPSIZE][4]; + int transparent = -1; + + if (!ReadGIFHeader(chan, &fileWidth, &fileHeight)) { + Tcl_AppendResult(interp, "couldn't read GIF header from file \"", + fileName, "\"", NULL); + return TCL_ERROR; + } + if ((fileWidth <= 0) || (fileHeight <= 0)) { + Tcl_AppendResult(interp, "GIF image file \"", fileName, + "\" has dimension(s) <= 0", (char *) NULL); + return TCL_ERROR; + } + + if (Fread(buf, 1, 3, chan) != 3) { + return TCL_OK; + } + bitPixel = 2<<(buf[0]&0x07); + + if (BitSet(buf[0], LOCALCOLORMAP)) { /* Global Colormap */ + if (!ReadColorMap(chan, bitPixel, colorMap)) { + Tcl_AppendResult(interp, "error reading color map", + (char *) NULL); + return TCL_ERROR; + } + } + + if ((srcX + width) > fileWidth) { + width = fileWidth - srcX; + } + if ((srcY + height) > fileHeight) { + height = fileHeight - srcY; + } + if ((width <= 0) || (height <= 0) + || (srcX >= fileWidth) || (srcY >= fileHeight)) { + return TCL_OK; + } + + Tk_PhotoExpand(imageHandle, destX + width, destY + height); + + block.width = width; + block.height = height; + block.pixelSize = 4; + block.pitch = block.pixelSize * block.width; + block.offset[0] = 0; + block.offset[1] = 1; + block.offset[2] = 2; + nBytes = height * block.pitch; + block.pixelPtr = (unsigned char *) ckalloc((unsigned) nBytes); + + while (1) { + if (Fread(buf, 1, 1, chan) != 1) { + /* + * Premature end of image. We should really notify + * the user, but for now just show garbage. + */ + + break; + } + + if (buf[0] == ';') { + /* + * GIF terminator. + */ + + break; + } + + if (buf[0] == '!') { + /* + * This is a GIF extension. + */ + + if (Fread(buf, 1, 1, chan) != 1) { + interp->result = + "error reading extension function code in GIF image"; + goto error; + } + if (DoExtension(chan, buf[0], &transparent) < 0) { + interp->result = "error reading extension in GIF image"; + goto error; + } + continue; + } + + if (buf[0] != ',') { + /* + * Not a valid start character; ignore it. + */ + continue; + } + + if (Fread(buf, 1, 9, chan) != 9) { + interp->result = "couldn't read left/top/width/height in GIF image"; + goto error; + } + + bitPixel = 1<<((buf[8]&0x07)+1); + + if (BitSet(buf[8], LOCALCOLORMAP)) { + if (!ReadColorMap(chan, bitPixel, colorMap)) { + Tcl_AppendResult(interp, "error reading color map", + (char *) NULL); + goto error; + } + } + if (ReadImage(interp, (char *) block.pixelPtr, chan, width, + height, colorMap, fileWidth, fileHeight, srcX, srcY, + BitSet(buf[8], INTERLACE), transparent) != TCL_OK) { + goto error; + } + break; + } + + if (transparent == -1) { + Tk_PhotoPutBlock(imageHandle, &block, destX, destY, width, height); + } else { + int x, y, end; + unsigned char *imagePtr, *rowPtr, *pixelPtr; + + imagePtr = rowPtr = block.pixelPtr; + for (y = 0; y < height; y++) { + x = 0; + pixelPtr = rowPtr; + while(x < width) { + /* search for first non-transparent pixel */ + while ((x < width) && !(pixelPtr[CM_ALPHA])) { + x++; pixelPtr += 4; + } + end = x; + /* search for first transparent pixel */ + while ((end < width) && pixelPtr[CM_ALPHA]) { + end++; pixelPtr += 4; + } + if (end > x) { + block.pixelPtr = rowPtr + 4 * x; + Tk_PhotoPutBlock(imageHandle, &block, destX+x, + destY+y, end-x, 1); + } + x = end; + } + rowPtr += block.pitch; + } + block.pixelPtr = imagePtr; + } + ckfree((char *) block.pixelPtr); + return TCL_OK; + + error: + ckfree((char *) block.pixelPtr); + return TCL_ERROR; + +} + +/* + *---------------------------------------------------------------------- + * + * StringMatchGIF -- + * + * This procedure is invoked by the photo image type to see if + * a string contains image data in GIF format. + * + * Results: + * The return value is 1 if the first characters in the string + * like GIF data, and 0 otherwise. + * + * Side effects: + * the size of the image is placed in widthPre and heightPtr. + * + *---------------------------------------------------------------------- + */ + +static int +StringMatchGIF(string, formatString, widthPtr, heightPtr) + char *string; /* the string containing the image data */ + char *formatString; /* the image format string */ + int *widthPtr; /* where to put the string width */ + int *heightPtr; /* where to put the string height */ +{ + unsigned char header[10]; + int got; + MFile handle; + mInit((unsigned char *) string, &handle); + got = Mread(header, 10, 1, &handle); + if (got != 10 + || ((strncmp("GIF87a", (char *) header, 6) != 0) + && (strncmp("GIF89a", (char *) header, 6) != 0))) { + return 0; + } + *widthPtr = LM_to_uint(header[6],header[7]); + *heightPtr = LM_to_uint(header[8],header[9]); + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * StringReadGif -- -- + * + * This procedure is called by the photo image type to read + * GIF format data from a base64 encoded string, and give it to + * the photo image. + * + * Results: + * A standard TCL completion code. If TCL_ERROR is returned + * then an error message is left in interp->result. + * + * Side effects: + * new data is added to the image given by imageHandle. This + * procedure calls FileReadGif by redefining the operation of + * fprintf temporarily. + * + *---------------------------------------------------------------------- + */ + +static int +StringReadGIF(interp,string,formatString,imageHandle, + destX, destY, width, height, srcX, srcY) + Tcl_Interp *interp; /* interpreter for reporting errors in */ + char *string; /* string containing the image */ + char *formatString; /* format string if any */ + Tk_PhotoHandle imageHandle; /* the image to write this data into */ + int destX, destY; /* The rectangular region of the */ + int width, height; /* image to copy */ + int srcX, srcY; +{ + int result; + MFile handle; + mInit((unsigned char *)string,&handle); + fromData = 1; + result = FileReadGIF(interp, (Tcl_Channel) &handle, "inline data", + formatString, imageHandle, destX, destY, width, height, + srcX, srcY); + fromData = 0; + return(result); +} + +/* + *---------------------------------------------------------------------- + * + * ReadGIFHeader -- + * + * This procedure reads the GIF header from the beginning of a + * GIF file and returns the dimensions of the image. + * + * Results: + * The return value is 1 if file "f" appears to start with + * a valid GIF header, 0 otherwise. If the header is valid, + * then *widthPtr and *heightPtr are modified to hold the + * dimensions of the image. + * + * Side effects: + * The access position in f advances. + * + *---------------------------------------------------------------------- + */ + +static int +ReadGIFHeader(chan, widthPtr, heightPtr) + Tcl_Channel chan; /* Image file to read the header from */ + int *widthPtr, *heightPtr; /* The dimensions of the image are + * returned here. */ +{ + unsigned char buf[7]; + + if ((Fread(buf, 1, 6, chan) != 6) + || ((strncmp("GIF87a", (char *) buf, 6) != 0) + && (strncmp("GIF89a", (char *) buf, 6) != 0))) { + return 0; + } + + if (Fread(buf, 1, 4, chan) != 4) { + return 0; + } + + *widthPtr = LM_to_uint(buf[0],buf[1]); + *heightPtr = LM_to_uint(buf[2],buf[3]); + return 1; +} + +/* + *----------------------------------------------------------------- + * The code below is copied from the giftoppm program and modified + * just slightly. + *----------------------------------------------------------------- + */ + +static int +ReadColorMap(chan, number, buffer) + Tcl_Channel chan; + int number; + unsigned char buffer[MAXCOLORMAPSIZE][4]; +{ + int i; + unsigned char rgb[3]; + + for (i = 0; i < number; ++i) { + if (! ReadOK(chan, rgb, sizeof(rgb))) { + return 0; + } + + buffer[i][CM_RED] = rgb[0] ; + buffer[i][CM_GREEN] = rgb[1] ; + buffer[i][CM_BLUE] = rgb[2] ; + buffer[i][CM_ALPHA] = 255 ; + } + return 1; +} + + + +static int +DoExtension(chan, label, transparent) + Tcl_Channel chan; + int label; + int *transparent; +{ + static unsigned char buf[256]; + int count; + + switch (label) { + case 0x01: /* Plain Text Extension */ + break; + + case 0xff: /* Application Extension */ + break; + + case 0xfe: /* Comment Extension */ + do { + count = GetDataBlock(chan, (unsigned char*) buf); + } while (count > 0); + return count; + + case 0xf9: /* Graphic Control Extension */ + count = GetDataBlock(chan, (unsigned char*) buf); + if (count < 0) { + return 1; + } + if ((buf[0] & 0x1) != 0) { + *transparent = buf[3]; + } + + do { + count = GetDataBlock(chan, (unsigned char*) buf); + } while (count > 0); + return count; + } + + do { + count = GetDataBlock(chan, (unsigned char*) buf); + } while (count > 0); + return count; +} + +static int ZeroDataBlock = 0; + +static int +GetDataBlock(chan, buf) + Tcl_Channel chan; + unsigned char *buf; +{ + unsigned char count; + + if (! ReadOK(chan, &count,1)) { + return -1; + } + + ZeroDataBlock = count == 0; + + if ((count != 0) && (! ReadOK(chan, buf, count))) { + return -1; + } + + return count; +} + + +static int +ReadImage(interp, imagePtr, chan, len, rows, cmap, + width, height, srcX, srcY, interlace, transparent) + Tcl_Interp *interp; + char *imagePtr; + Tcl_Channel chan; + int len, rows; + unsigned char cmap[MAXCOLORMAPSIZE][4]; + int width, height; + int srcX, srcY; + int interlace; + int transparent; +{ + unsigned char c; + int v; + int xpos = 0, ypos = 0, pass = 0; + char *pixelPtr; + + + /* + * Initialize the Compression routines + */ + if (! ReadOK(chan, &c, 1)) { + Tcl_AppendResult(interp, "error reading GIF image: ", + Tcl_PosixError(interp), (char *) NULL); + return TCL_ERROR; + } + + if (LWZReadByte(chan, 1, c) < 0) { + interp->result = "format error in GIF image"; + return TCL_ERROR; + } + + if (transparent!=-1) { + cmap[transparent][CM_RED] = 0; + cmap[transparent][CM_GREEN] = 0; + cmap[transparent][CM_BLUE] = 0; + cmap[transparent][CM_ALPHA] = 0; + } + + pixelPtr = imagePtr; + while ((v = LWZReadByte(chan, 0, c)) >= 0 ) { + + if ((xpos>=srcX) && (xpos<srcX+len) && + (ypos>=srcY) && (ypos<srcY+rows)) { + *pixelPtr++ = cmap[v][CM_RED]; + *pixelPtr++ = cmap[v][CM_GREEN]; + *pixelPtr++ = cmap[v][CM_BLUE]; + *pixelPtr++ = cmap[v][CM_ALPHA]; + } + + ++xpos; + if (xpos == width) { + xpos = 0; + if (interlace) { + switch (pass) { + case 0: + case 1: + ypos += 8; break; + case 2: + ypos += 4; break; + case 3: + ypos += 2; break; + } + + while (ypos >= height) { + ++pass; + switch (pass) { + case 1: + ypos = 4; break; + case 2: + ypos = 2; break; + case 3: + ypos = 1; break; + default: + return TCL_OK; + } + } + } else { + ++ypos; + } + pixelPtr = imagePtr + (ypos-srcY) * len * 4; + } + if (ypos >= height) + break; + } + return TCL_OK; +} + +static int +LWZReadByte(chan, flag, input_code_size) + Tcl_Channel chan; + int flag; + int input_code_size; +{ + static int fresh = 0; + int code, incode; + static int code_size, set_code_size; + static int max_code, max_code_size; + static int firstcode, oldcode; + static int clear_code, end_code; + static int table[2][(1<< MAX_LWZ_BITS)]; + static int stack[(1<<(MAX_LWZ_BITS))*2], *sp; + register int i; + + if (flag) { + set_code_size = input_code_size; + code_size = set_code_size+1; + clear_code = 1 << set_code_size ; + end_code = clear_code + 1; + max_code_size = 2*clear_code; + max_code = clear_code+2; + + GetCode(chan, 0, 1); + + fresh = 1; + + for (i = 0; i < clear_code; ++i) { + table[0][i] = 0; + table[1][i] = i; + } + for (; i < (1<<MAX_LWZ_BITS); ++i) { + table[0][i] = table[1][0] = 0; + } + + sp = stack; + + return 0; + } else if (fresh) { + fresh = 0; + do { + firstcode = oldcode = GetCode(chan, code_size, 0); + } while (firstcode == clear_code); + return firstcode; + } + + if (sp > stack) { + return *--sp; + } + + while ((code = GetCode(chan, code_size, 0)) >= 0) { + if (code == clear_code) { + for (i = 0; i < clear_code; ++i) { + table[0][i] = 0; + table[1][i] = i; + } + + for (; i < (1<<MAX_LWZ_BITS); ++i) { + table[0][i] = table[1][i] = 0; + } + + code_size = set_code_size+1; + max_code_size = 2*clear_code; + max_code = clear_code+2; + sp = stack; + firstcode = oldcode = GetCode(chan, code_size, 0); + return firstcode; + + } else if (code == end_code) { + int count; + unsigned char buf[260]; + + if (ZeroDataBlock) { + return -2; + } + + while ((count = GetDataBlock(chan, buf)) > 0) + /* Empty body */; + + if (count != 0) { + return -2; + } + } + + incode = code; + + if (code >= max_code) { + *sp++ = firstcode; + code = oldcode; + } + + while (code >= clear_code) { + *sp++ = table[1][code]; + if (code == table[0][code]) { + return -2; + + /* + * Used to be this instead, Steve Ball suggested + * the change to just return. + printf("circular table entry BIG ERROR\n"); + */ + } + code = table[0][code]; + } + + *sp++ = firstcode = table[1][code]; + + if ((code = max_code) <(1<<MAX_LWZ_BITS)) { + table[0][code] = oldcode; + table[1][code] = firstcode; + ++max_code; + if ((max_code>=max_code_size) && (max_code_size < (1<<MAX_LWZ_BITS))) { + max_code_size *= 2; + ++code_size; + } + } + + oldcode = incode; + + if (sp > stack) + return *--sp; + } + return code; +} + + +static int +GetCode(chan, code_size, flag) + Tcl_Channel chan; + int code_size; + int flag; +{ + static unsigned char buf[280]; + static int curbit, lastbit, done, last_byte; + int i, j, ret; + unsigned char count; + + if (flag) { + curbit = 0; + lastbit = 0; + done = 0; + return 0; + } + + + if ( (curbit+code_size) >= lastbit) { + if (done) { + /* ran off the end of my bits */ + return -1; + } + if (last_byte >= 2) { + buf[0] = buf[last_byte-2]; + } + if (last_byte >= 1) { + buf[1] = buf[last_byte-1]; + } + + if ((count = GetDataBlock(chan, &buf[2])) == 0) { + done = 1; + } + + last_byte = 2 + count; + curbit = (curbit - lastbit) + 16; + lastbit = (2+count)*8 ; + } + + ret = 0; + for (i = curbit, j = 0; j < code_size; ++i, ++j) { + ret |= ((buf[ i / 8 ] & (1 << (i % 8))) != 0) << j; + } + + curbit += code_size; + + return ret; +} + +/* + *---------------------------------------------------------------------- + * + * Minit -- -- + * + * This procedure initializes a base64 decoder handle + * + * Results: + * none + * + * Side effects: + * the base64 handle is initialized + * + *---------------------------------------------------------------------- + */ + +static void +mInit(string, handle) + unsigned char *string; /* string containing initial mmencoded data */ + MFile *handle; /* mmdecode "file" handle */ +{ + handle->data = string; + handle->state = 0; +} + +/* + *---------------------------------------------------------------------- + * + * Mread -- + * + * This procedure is invoked by the GIF file reader as a + * temporary replacement for "fread", to get GIF data out + * of a string (using Mgetc). + * + * Results: + * The return value is the number of characters "read" + * + * Side effects: + * The base64 handle will change state. + * + *---------------------------------------------------------------------- + */ + +static int +Mread(dst, chunkSize, numChunks, handle) + unsigned char *dst; /* where to put the result */ + size_t chunkSize; /* size of each transfer */ + size_t numChunks; /* number of chunks */ + MFile *handle; /* mmdecode "file" handle */ +{ + register int i, c; + int count = chunkSize * numChunks; + + for(i=0; i<count && (c=Mgetc(handle)) != GIF_DONE; i++) { + *dst++ = c; + } + return i; +} + +/* + * get the next decoded character from an mmencode handle + * This causes at least 1 character to be "read" from the encoded string + */ + +/* + *---------------------------------------------------------------------- + * + * Mgetc -- + * + * This procedure decodes and returns the next byte from a base64 + * encoded string. + * + * Results: + * The next byte (or GIF_DONE) is returned. + * + * Side effects: + * The base64 handle will change state. + * + *---------------------------------------------------------------------- + */ + +static int +Mgetc(handle) + MFile *handle; /* Handle containing decoder data and state. */ +{ + int c; + int result = 0; /* Initialization needed only to prevent + * gcc compiler warning. */ + + if (handle->state == GIF_DONE) { + return(GIF_DONE); + } + + do { + c = char64(*handle->data); + handle->data++; + } while (c==GIF_SPACE); + + if (c>GIF_SPECIAL) { + handle->state = GIF_DONE; + return(handle->state ? handle->c : GIF_DONE); + } + + switch (handle->state++) { + case 0: + handle->c = c<<2; + result = Mgetc(handle); + break; + case 1: + result = handle->c | (c>>4); + handle->c = (c&0xF)<<4; + break; + case 2: + result = handle->c | (c>>2); + handle->c = (c&0x3) << 6; + break; + case 3: + result = handle->c | c; + handle->state = 0; + break; + } + return(result); +} + +/* + *---------------------------------------------------------------------- + * + * char64 -- + * + * This procedure converts a base64 ascii character into its binary + * equivalent. This code is a slightly modified version of the + * char64 proc in N. Borenstein's metamail decoder. + * + * Results: + * The binary value, or an error code. + * + * Side effects: + * None. + *---------------------------------------------------------------------- + */ + +static int +char64(c) +int c; +{ + switch(c) { + case 'A': return(0); case 'B': return(1); case 'C': return(2); + case 'D': return(3); case 'E': return(4); case 'F': return(5); + case 'G': return(6); case 'H': return(7); case 'I': return(8); + case 'J': return(9); case 'K': return(10); case 'L': return(11); + case 'M': return(12); case 'N': return(13); case 'O': return(14); + case 'P': return(15); case 'Q': return(16); case 'R': return(17); + case 'S': return(18); case 'T': return(19); case 'U': return(20); + case 'V': return(21); case 'W': return(22); case 'X': return(23); + case 'Y': return(24); case 'Z': return(25); case 'a': return(26); + case 'b': return(27); case 'c': return(28); case 'd': return(29); + case 'e': return(30); case 'f': return(31); case 'g': return(32); + case 'h': return(33); case 'i': return(34); case 'j': return(35); + case 'k': return(36); case 'l': return(37); case 'm': return(38); + case 'n': return(39); case 'o': return(40); case 'p': return(41); + case 'q': return(42); case 'r': return(43); case 's': return(44); + case 't': return(45); case 'u': return(46); case 'v': return(47); + case 'w': return(48); case 'x': return(49); case 'y': return(50); + case 'z': return(51); case '0': return(52); case '1': return(53); + case '2': return(54); case '3': return(55); case '4': return(56); + case '5': return(57); case '6': return(58); case '7': return(59); + case '8': return(60); case '9': return(61); case '+': return(62); + case '/': return(63); + + case ' ': case '\t': case '\n': case '\r': case '\f': return(GIF_SPACE); + case '=': return(GIF_PAD); + case '\0': return(GIF_DONE); + default: return(GIF_BAD); + } +} + +/* + *---------------------------------------------------------------------- + * + * Fread -- + * + * This procedure calls either fread or Mread to read data + * from a file or a base64 encoded string. + * + * Results: - same as fread + * + *---------------------------------------------------------------------- + */ + +static int +Fread(dst, hunk, count, chan) + unsigned char *dst; /* where to put the result */ + size_t hunk,count; /* how many */ + Tcl_Channel chan; +{ + if (fromData) { + return(Mread(dst, hunk, count, (MFile *) chan)); + } else { + return Tcl_Read(chan, (char *) dst, (int) (hunk * count)); + } +} diff --git a/generic/tkImgPPM.c b/generic/tkImgPPM.c new file mode 100644 index 0000000..3a54003 --- /dev/null +++ b/generic/tkImgPPM.c @@ -0,0 +1,421 @@ +/* + * tkImgPPM.c -- + * + * A photo image file handler for PPM (Portable PixMap) files. + * + * Copyright (c) 1994 The Australian National University. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * Author: Paul Mackerras (paulus@cs.anu.edu.au), + * Department of Computer Science, + * Australian National University. + * + * SCCS: @(#) tkImgPPM.c 1.16 97/10/28 14:51:46 + */ + +#include "tkInt.h" +#include "tkPort.h" + +/* + * The maximum amount of memory to allocate for data read from the + * file. If we need more than this, we do it in pieces. + */ + +#define MAX_MEMORY 10000 /* don't allocate > 10KB */ + +/* + * Define PGM and PPM, i.e. gray images and color images. + */ + +#define PGM 1 +#define PPM 2 + +/* + * The format record for the PPM file format: + */ + +static int FileMatchPPM _ANSI_ARGS_((Tcl_Channel chan, + char *fileName, char *formatString, + int *widthPtr, int *heightPtr)); +static int FileReadPPM _ANSI_ARGS_((Tcl_Interp *interp, + Tcl_Channel chan, char *fileName, + char *formatString, Tk_PhotoHandle imageHandle, + int destX, int destY, int width, int height, + int srcX, int srcY)); +static int FileWritePPM _ANSI_ARGS_((Tcl_Interp *interp, + char *fileName, char *formatString, + Tk_PhotoImageBlock *blockPtr)); + +Tk_PhotoImageFormat tkImgFmtPPM = { + "PPM", /* name */ + FileMatchPPM, /* fileMatchProc */ + NULL, /* stringMatchProc */ + FileReadPPM, /* fileReadProc */ + NULL, /* stringReadProc */ + FileWritePPM, /* fileWriteProc */ + NULL, /* stringWriteProc */ +}; + +/* + * Prototypes for local procedures defined in this file: + */ + +static int ReadPPMFileHeader _ANSI_ARGS_((Tcl_Channel chan, + int *widthPtr, int *heightPtr, + int *maxIntensityPtr)); + +/* + *---------------------------------------------------------------------- + * + * FileMatchPPM -- + * + * This procedure is invoked by the photo image type to see if + * a file contains image data in PPM format. + * + * Results: + * The return value is >0 if the first characters in file "f" look + * like PPM data, and 0 otherwise. + * + * Side effects: + * The access position in f may change. + * + *---------------------------------------------------------------------- + */ + +static int +FileMatchPPM(chan, fileName, formatString, widthPtr, heightPtr) + Tcl_Channel chan; /* The image file, open for reading. */ + char *fileName; /* The name of the image file. */ + char *formatString; /* User-specified format string, or NULL. */ + int *widthPtr, *heightPtr; /* The dimensions of the image are + * returned here if the file is a valid + * raw PPM file. */ +{ + int dummy; + + return ReadPPMFileHeader(chan, widthPtr, heightPtr, &dummy); +} + +/* + *---------------------------------------------------------------------- + * + * FileReadPPM -- + * + * This procedure is called by the photo image type to read + * PPM format data from a file and write it into a given + * photo image. + * + * Results: + * A standard TCL completion code. If TCL_ERROR is returned + * then an error message is left in interp->result. + * + * Side effects: + * The access position in file f is changed, and new data is + * added to the image given by imageHandle. + * + *---------------------------------------------------------------------- + */ + +static int +FileReadPPM(interp, chan, fileName, formatString, imageHandle, destX, destY, + width, height, srcX, srcY) + Tcl_Interp *interp; /* Interpreter to use for reporting errors. */ + Tcl_Channel chan; /* The image file, open for reading. */ + char *fileName; /* The name of the image file. */ + char *formatString; /* User-specified format string, or NULL. */ + Tk_PhotoHandle imageHandle; /* The photo image to write into. */ + int destX, destY; /* Coordinates of top-left pixel in + * photo image to be written to. */ + int width, height; /* Dimensions of block of photo image to + * be written to. */ + int srcX, srcY; /* Coordinates of top-left pixel to be used + * in image being read. */ +{ + int fileWidth, fileHeight, maxIntensity; + int nLines, nBytes, h, type, count; + unsigned char *pixelPtr; + Tk_PhotoImageBlock block; + + type = ReadPPMFileHeader(chan, &fileWidth, &fileHeight, &maxIntensity); + if (type == 0) { + Tcl_AppendResult(interp, "couldn't read raw PPM header from file \"", + fileName, "\"", NULL); + return TCL_ERROR; + } + if ((fileWidth <= 0) || (fileHeight <= 0)) { + Tcl_AppendResult(interp, "PPM image file \"", fileName, + "\" has dimension(s) <= 0", (char *) NULL); + return TCL_ERROR; + } + if ((maxIntensity <= 0) || (maxIntensity >= 256)) { + char buffer[30]; + + sprintf(buffer, "%d", maxIntensity); + Tcl_AppendResult(interp, "PPM image file \"", fileName, + "\" has bad maximum intensity value ", buffer, + (char *) NULL); + return TCL_ERROR; + } + + if ((srcX + width) > fileWidth) { + width = fileWidth - srcX; + } + if ((srcY + height) > fileHeight) { + height = fileHeight - srcY; + } + if ((width <= 0) || (height <= 0) + || (srcX >= fileWidth) || (srcY >= fileHeight)) { + return TCL_OK; + } + + if (type == PGM) { + block.pixelSize = 1; + block.offset[0] = 0; + block.offset[1] = 0; + block.offset[2] = 0; + } + else { + block.pixelSize = 3; + block.offset[0] = 0; + block.offset[1] = 1; + block.offset[2] = 2; + } + block.width = width; + block.pitch = block.pixelSize * fileWidth; + + Tk_PhotoExpand(imageHandle, destX + width, destY + height); + + if (srcY > 0) { + Tcl_Seek(chan, (srcY * block.pitch), SEEK_CUR); + } + + nLines = (MAX_MEMORY + block.pitch - 1) / block.pitch; + if (nLines > height) { + nLines = height; + } + if (nLines <= 0) { + nLines = 1; + } + nBytes = nLines * block.pitch; + pixelPtr = (unsigned char *) ckalloc((unsigned) nBytes); + block.pixelPtr = pixelPtr + srcX * block.pixelSize; + + for (h = height; h > 0; h -= nLines) { + if (nLines > h) { + nLines = h; + nBytes = nLines * block.pitch; + } + count = Tcl_Read(chan, (char *) pixelPtr, nBytes); + if (count != nBytes) { + Tcl_AppendResult(interp, "error reading PPM image file \"", + fileName, "\": ", + Tcl_Eof(chan) ? "not enough data" : Tcl_PosixError(interp), + (char *) NULL); + ckfree((char *) pixelPtr); + return TCL_ERROR; + } + if (maxIntensity != 255) { + unsigned char *p; + + for (p = pixelPtr; count > 0; count--, p++) { + *p = (((int) *p) * 255)/maxIntensity; + } + } + block.height = nLines; + Tk_PhotoPutBlock(imageHandle, &block, destX, destY, width, nLines); + destY += nLines; + } + + ckfree((char *) pixelPtr); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FileWritePPM -- + * + * This procedure is invoked to write image data to a file in PPM + * format. + * + * Results: + * A standard TCL completion code. If TCL_ERROR is returned + * then an error message is left in interp->result. + * + * Side effects: + * Data is written to the file given by "fileName". + * + *---------------------------------------------------------------------- + */ + +static int +FileWritePPM(interp, fileName, formatString, blockPtr) + Tcl_Interp *interp; + char *fileName; + char *formatString; + Tk_PhotoImageBlock *blockPtr; +{ + Tcl_Channel chan; + int w, h; + int greenOffset, blueOffset, nBytes; + unsigned char *pixelPtr, *pixLinePtr; + char header[30]; + + chan = Tcl_OpenFileChannel(interp, fileName, "w", 0666); + if (chan == NULL) { + return TCL_ERROR; + } + + sprintf(header, "P6\n%d %d\n255\n", blockPtr->width, blockPtr->height); + Tcl_Write(chan, header, -1); + + pixLinePtr = blockPtr->pixelPtr + blockPtr->offset[0]; + greenOffset = blockPtr->offset[1] - blockPtr->offset[0]; + blueOffset = blockPtr->offset[2] - blockPtr->offset[0]; + + if ((greenOffset == 1) && (blueOffset == 2) && (blockPtr->pixelSize == 3) + && (blockPtr->pitch == (blockPtr->width * 3))) { + nBytes = blockPtr->height * blockPtr->pitch; + if (Tcl_Write(chan, (char *) pixLinePtr, nBytes) != nBytes) { + goto writeerror; + } + } else { + for (h = blockPtr->height; h > 0; h--) { + pixelPtr = pixLinePtr; + for (w = blockPtr->width; w > 0; w--) { + if ((Tcl_Write(chan, (char *) &pixelPtr[0], 1) == -1) + || (Tcl_Write(chan, (char *) &pixelPtr[greenOffset], 1) == -1) + || (Tcl_Write(chan, (char *) &pixelPtr[blueOffset], 1) == -1)) { + goto writeerror; + } + pixelPtr += blockPtr->pixelSize; + } + pixLinePtr += blockPtr->pitch; + } + } + + if (Tcl_Close(NULL, chan) == 0) { + return TCL_OK; + } + chan = NULL; + + writeerror: + Tcl_AppendResult(interp, "error writing \"", fileName, "\": ", + Tcl_PosixError(interp), (char *) NULL); + if (chan != NULL) { + Tcl_Close(NULL, chan); + } + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * ReadPPMFileHeader -- + * + * This procedure reads the PPM header from the beginning of a + * PPM file and returns information from the header. + * + * Results: + * The return value is PGM if file "f" appears to start with + * a valid PGM header, PPM if "f" appears to start with a valid + * PPM header, and 0 otherwise. If the header is valid, + * then *widthPtr and *heightPtr are modified to hold the + * dimensions of the image and *maxIntensityPtr is modified to + * hold the value of a "fully on" intensity value. + * + * Side effects: + * The access position in f advances. + * + *---------------------------------------------------------------------- + */ + +static int +ReadPPMFileHeader(chan, widthPtr, heightPtr, maxIntensityPtr) + Tcl_Channel chan; /* Image file to read the header from */ + int *widthPtr, *heightPtr; /* The dimensions of the image are + * returned here. */ + int *maxIntensityPtr; /* The maximum intensity value for + * the image is stored here. */ +{ +#define BUFFER_SIZE 1000 + char buffer[BUFFER_SIZE]; + int i, numFields, firstInLine; + int type = 0; + char c; + + /* + * Read 4 space-separated fields from the file, ignoring + * comments (any line that starts with "#"). + */ + + if (Tcl_Read(chan, &c, 1) != 1) { + return 0; + } + firstInLine = 1; + i = 0; + for (numFields = 0; numFields < 4; numFields++) { + /* + * Skip comments and white space. + */ + + while (1) { + while (isspace(UCHAR(c))) { + firstInLine = (c == '\n'); + if (Tcl_Read(chan, &c, 1) != 1) { + return 0; + } + } + if (c != '#') { + break; + } + do { + if (Tcl_Read(chan, &c, 1) != 1) { + return 0; + } + } while (c != '\n'); + firstInLine = 1; + } + + /* + * Read a field (everything up to the next white space). + */ + + while (!isspace(UCHAR(c))) { + if (i < (BUFFER_SIZE-2)) { + buffer[i] = c; + i++; + } + if (Tcl_Read(chan, &c, 1) != 1) { + goto done; + } + } + if (i < (BUFFER_SIZE-1)) { + buffer[i] = ' '; + i++; + } + firstInLine = 0; + } + done: + buffer[i] = 0; + + /* + * Parse the fields, which are: id, width, height, maxIntensity. + */ + + if (strncmp(buffer, "P6 ", 3) == 0) { + type = PPM; + } else if (strncmp(buffer, "P5 ", 3) == 0) { + type = PGM; + } else { + return 0; + } + if (sscanf(buffer+3, "%d %d %d", widthPtr, heightPtr, maxIntensityPtr) + != 3) { + return 0; + } + return type; +} diff --git a/generic/tkImgPhoto.c b/generic/tkImgPhoto.c new file mode 100644 index 0000000..86fbf80 --- /dev/null +++ b/generic/tkImgPhoto.c @@ -0,0 +1,4144 @@ +/* + * tkImgPhoto.c -- + * + * Implements images of type "photo" for Tk. Photo images are + * stored in full color (24 bits per pixel) and displayed using + * dithering if necessary. + * + * Copyright (c) 1994 The Australian National University. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * Author: Paul Mackerras (paulus@cs.anu.edu.au), + * Department of Computer Science, + * Australian National University. + * + * SCCS: @(#) tkImgPhoto.c 1.60 97/08/08 11:32:46 + */ + +#include "tkInt.h" +#include "tkPort.h" +#include "tclMath.h" +#include <ctype.h> + +/* + * Declaration for internal Xlib function used here: + */ + +extern _XInitImageFuncPtrs _ANSI_ARGS_((XImage *image)); + +/* + * A signed 8-bit integral type. If chars are unsigned and the compiler + * isn't an ANSI one, then we have to use short instead (which wastes + * space) to get signed behavior. + */ + +#if defined(__STDC__) || defined(_AIX) + typedef signed char schar; +#else +# ifndef __CHAR_UNSIGNED__ + typedef char schar; +# else + typedef short schar; +# endif +#endif + +/* + * An unsigned 32-bit integral type, used for pixel values. + * We use int rather than long here to accommodate those systems + * where longs are 64 bits. + */ + +typedef unsigned int pixel; + +/* + * The maximum number of pixels to transmit to the server in a + * single XPutImage call. + */ + +#define MAX_PIXELS 65536 + +/* + * The set of colors required to display a photo image in a window depends on: + * - the visual used by the window + * - the palette, which specifies how many levels of each primary + * color to use, and + * - the gamma value for the image. + * + * Pixel values allocated for specific colors are valid only for the + * colormap in which they were allocated. Sets of pixel values + * allocated for displaying photos are re-used in other windows if + * possible, that is, if the display, colormap, palette and gamma + * values match. A hash table is used to locate these sets of pixel + * values, using the following data structure as key: + */ + +typedef struct { + Display *display; /* Qualifies the colormap resource ID */ + Colormap colormap; /* Colormap that the windows are using. */ + double gamma; /* Gamma exponent value for images. */ + Tk_Uid palette; /* Specifies how many shades of each primary + * we want to allocate. */ +} ColorTableId; + +/* + * For a particular (display, colormap, palette, gamma) combination, + * a data structure of the following type is used to store the allocated + * pixel values and other information: + */ + +typedef struct ColorTable { + ColorTableId id; /* Information used in selecting this + * color table. */ + int flags; /* See below. */ + int refCount; /* Number of instances using this map. */ + int liveRefCount; /* Number of instances which are actually + * in use, using this map. */ + int numColors; /* Number of colors allocated for this map. */ + + XVisualInfo visualInfo; /* Information about the visual for windows + * using this color table. */ + + pixel redValues[256]; /* Maps 8-bit values of red intensity + * to a pixel value or index in pixelMap. */ + pixel greenValues[256]; /* Ditto for green intensity */ + pixel blueValues[256]; /* Ditto for blue intensity */ + unsigned long *pixelMap; /* Actual pixel values allocated. */ + + unsigned char colorQuant[3][256]; + /* Maps 8-bit intensities to quantized + * intensities. The first index is 0 for + * red, 1 for green, 2 for blue. */ +} ColorTable; + +/* + * Bit definitions for the flags field of a ColorTable. + * BLACK_AND_WHITE: 1 means only black and white colors are + * available. + * COLOR_WINDOW: 1 means a full 3-D color cube has been + * allocated. + * DISPOSE_PENDING: 1 means a call to DisposeColorTable has + * been scheduled as an idle handler, but it + * hasn't been invoked yet. + * MAP_COLORS: 1 means pixel values should be mapped + * through pixelMap. + */ + +#define BLACK_AND_WHITE 1 +#define COLOR_WINDOW 2 +#define DISPOSE_PENDING 4 +#define MAP_COLORS 8 + +/* + * Definition of the data associated with each photo image master. + */ + +typedef struct PhotoMaster { + Tk_ImageMaster tkMaster; /* Tk's token for image master. NULL means + * the image is being deleted. */ + Tcl_Interp *interp; /* Interpreter associated with the + * application using this image. */ + Tcl_Command imageCmd; /* Token for image command (used to delete + * it when the image goes away). NULL means + * the image command has already been + * deleted. */ + int flags; /* Sundry flags, defined below. */ + int width, height; /* Dimensions of image. */ + int userWidth, userHeight; /* User-declared image dimensions. */ + Tk_Uid palette; /* User-specified default palette for + * instances of this image. */ + double gamma; /* Display gamma value to correct for. */ + char *fileString; /* Name of file to read into image. */ + char *dataString; /* String value to use as contents of image. */ + char *format; /* User-specified format of data in image + * file or string value. */ + unsigned char *pix24; /* Local storage for 24-bit image. */ + int ditherX, ditherY; /* Location of first incorrectly + * dithered pixel in image. */ + TkRegion validRegion; /* Tk region indicating which parts of + * the image have valid image data. */ + struct PhotoInstance *instancePtr; + /* First in the list of instances + * associated with this master. */ +} PhotoMaster; + +/* + * Bit definitions for the flags field of a PhotoMaster. + * COLOR_IMAGE: 1 means that the image has different color + * components. + * IMAGE_CHANGED: 1 means that the instances of this image + * need to be redithered. + */ + +#define COLOR_IMAGE 1 +#define IMAGE_CHANGED 2 + +/* + * The following data structure represents all of the instances of + * a photo image in windows on a given screen that are using the + * same colormap. + */ + +typedef struct PhotoInstance { + PhotoMaster *masterPtr; /* Pointer to master for image. */ + Display *display; /* Display for windows using this instance. */ + Colormap colormap; /* The image may only be used in windows with + * this particular colormap. */ + struct PhotoInstance *nextPtr; + /* Pointer to the next instance in the list + * of instances associated with this master. */ + int refCount; /* Number of instances using this structure. */ + Tk_Uid palette; /* Palette for these particular instances. */ + double gamma; /* Gamma value for these instances. */ + Tk_Uid defaultPalette; /* Default palette to use if a palette + * is not specified for the master. */ + ColorTable *colorTablePtr; /* Pointer to information about colors + * allocated for image display in windows + * like this one. */ + Pixmap pixels; /* X pixmap containing dithered image. */ + int width, height; /* Dimensions of the pixmap. */ + schar *error; /* Error image, used in dithering. */ + XImage *imagePtr; /* Image structure for converted pixels. */ + XVisualInfo visualInfo; /* Information about the visual that these + * windows are using. */ + GC gc; /* Graphics context for writing images + * to the pixmap. */ +} PhotoInstance; + +/* + * The following data structure is used to return information + * from ParseSubcommandOptions: + */ + +struct SubcommandOptions { + int options; /* Individual bits indicate which + * options were specified - see below. */ + char *name; /* Name specified without an option. */ + int fromX, fromY; /* Values specified for -from option. */ + int fromX2, fromY2; /* Second coordinate pair for -from option. */ + int toX, toY; /* Values specified for -to option. */ + int toX2, toY2; /* Second coordinate pair for -to option. */ + int zoomX, zoomY; /* Values specified for -zoom option. */ + int subsampleX, subsampleY; /* Values specified for -subsample option. */ + char *format; /* Value specified for -format option. */ +}; + +/* + * Bit definitions for use with ParseSubcommandOptions: + * Each bit is set in the allowedOptions parameter on a call to + * ParseSubcommandOptions if that option is allowed for the current + * photo image subcommand. On return, the bit is set in the options + * field of the SubcommandOptions structure if that option was specified. + * + * OPT_FORMAT: Set if -format option allowed/specified. + * OPT_FROM: Set if -from option allowed/specified. + * OPT_SHRINK: Set if -shrink option allowed/specified. + * OPT_SUBSAMPLE: Set if -subsample option allowed/spec'd. + * OPT_TO: Set if -to option allowed/specified. + * OPT_ZOOM: Set if -zoom option allowed/specified. + */ + +#define OPT_FORMAT 1 +#define OPT_FROM 2 +#define OPT_SHRINK 4 +#define OPT_SUBSAMPLE 8 +#define OPT_TO 0x10 +#define OPT_ZOOM 0x20 + +/* + * List of option names. The order here must match the order of + * declarations of the OPT_* constants above. + */ + +static char *optionNames[] = { + "-format", + "-from", + "-shrink", + "-subsample", + "-to", + "-zoom", + (char *) NULL +}; + +/* + * The type record for photo images: + */ + +static int ImgPhotoCreate _ANSI_ARGS_((Tcl_Interp *interp, + char *name, int argc, char **argv, + Tk_ImageType *typePtr, Tk_ImageMaster master, + ClientData *clientDataPtr)); +static ClientData ImgPhotoGet _ANSI_ARGS_((Tk_Window tkwin, + ClientData clientData)); +static void ImgPhotoDisplay _ANSI_ARGS_((ClientData clientData, + Display *display, Drawable drawable, + int imageX, int imageY, int width, int height, + int drawableX, int drawableY)); +static void ImgPhotoFree _ANSI_ARGS_((ClientData clientData, + Display *display)); +static void ImgPhotoDelete _ANSI_ARGS_((ClientData clientData)); + +Tk_ImageType tkPhotoImageType = { + "photo", /* name */ + ImgPhotoCreate, /* createProc */ + ImgPhotoGet, /* getProc */ + ImgPhotoDisplay, /* displayProc */ + ImgPhotoFree, /* freeProc */ + ImgPhotoDelete, /* deleteProc */ + (Tk_ImageType *) NULL /* nextPtr */ +}; + +/* + * Default configuration + */ + +#define DEF_PHOTO_GAMMA "1" +#define DEF_PHOTO_HEIGHT "0" +#define DEF_PHOTO_PALETTE "" +#define DEF_PHOTO_WIDTH "0" + +/* + * Information used for parsing configuration specifications: + */ +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_STRING, "-data", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(PhotoMaster, dataString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-format", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(PhotoMaster, format), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-file", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(PhotoMaster, fileString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_DOUBLE, "-gamma", (char *) NULL, (char *) NULL, + DEF_PHOTO_GAMMA, Tk_Offset(PhotoMaster, gamma), 0}, + {TK_CONFIG_INT, "-height", (char *) NULL, (char *) NULL, + DEF_PHOTO_HEIGHT, Tk_Offset(PhotoMaster, userHeight), 0}, + {TK_CONFIG_UID, "-palette", (char *) NULL, (char *) NULL, + DEF_PHOTO_PALETTE, Tk_Offset(PhotoMaster, palette), 0}, + {TK_CONFIG_INT, "-width", (char *) NULL, (char *) NULL, + DEF_PHOTO_WIDTH, Tk_Offset(PhotoMaster, userWidth), 0}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Hash table used to hash from (display, colormap, palette, gamma) + * to ColorTable address. + */ + +static Tcl_HashTable imgPhotoColorHash; +static int imgPhotoColorHashInitialized; +#define N_COLOR_HASH (sizeof(ColorTableId) / sizeof(int)) + +/* + * Pointer to the first in the list of known photo image formats. + */ + +static Tk_PhotoImageFormat *formatList = NULL; + +/* + * Forward declarations + */ + +static int ImgPhotoCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static int ParseSubcommandOptions _ANSI_ARGS_(( + struct SubcommandOptions *optPtr, + Tcl_Interp *interp, int allowedOptions, + int *indexPtr, int argc, char **argv)); +static void ImgPhotoCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static int ImgPhotoConfigureMaster _ANSI_ARGS_(( + Tcl_Interp *interp, PhotoMaster *masterPtr, + int argc, char **argv, int flags)); +static void ImgPhotoConfigureInstance _ANSI_ARGS_(( + PhotoInstance *instancePtr)); +static void ImgPhotoSetSize _ANSI_ARGS_((PhotoMaster *masterPtr, + int width, int height)); +static void ImgPhotoInstanceSetSize _ANSI_ARGS_(( + PhotoInstance *instancePtr)); +static int IsValidPalette _ANSI_ARGS_((PhotoInstance *instancePtr, + char *palette)); +static int CountBits _ANSI_ARGS_((pixel mask)); +static void GetColorTable _ANSI_ARGS_((PhotoInstance *instancePtr)); +static void FreeColorTable _ANSI_ARGS_((ColorTable *colorPtr)); +static void AllocateColors _ANSI_ARGS_((ColorTable *colorPtr)); +static void DisposeColorTable _ANSI_ARGS_((ClientData clientData)); +static void DisposeInstance _ANSI_ARGS_((ClientData clientData)); +static int ReclaimColors _ANSI_ARGS_((ColorTableId *id, + int numColors)); +static int MatchFileFormat _ANSI_ARGS_((Tcl_Interp *interp, + Tcl_Channel chan, char *fileName, + char *formatString, + Tk_PhotoImageFormat **imageFormatPtr, + int *widthPtr, int *heightPtr)); +static int MatchStringFormat _ANSI_ARGS_((Tcl_Interp *interp, + char *string, char *formatString, + Tk_PhotoImageFormat **imageFormatPtr, + int *widthPtr, int *heightPtr)); +static void Dither _ANSI_ARGS_((PhotoMaster *masterPtr, + int x, int y, int width, int height)); +static void DitherInstance _ANSI_ARGS_((PhotoInstance *instancePtr, + int x, int y, int width, int height)); + +#undef MIN +#define MIN(a, b) ((a) < (b)? (a): (b)) +#undef MAX +#define MAX(a, b) ((a) > (b)? (a): (b)) + +/* + *---------------------------------------------------------------------- + * + * Tk_CreatePhotoImageFormat -- + * + * This procedure is invoked by an image file handler to register + * a new photo image format and the procedures that handle the + * new format. The procedure is typically invoked during + * Tcl_AppInit. + * + * Results: + * None. + * + * Side effects: + * The new image file format is entered into a table used in the + * photo image "read" and "write" subcommands. + * + *---------------------------------------------------------------------- + */ + +void +Tk_CreatePhotoImageFormat(formatPtr) + Tk_PhotoImageFormat *formatPtr; + /* Structure describing the format. All of + * the fields except "nextPtr" must be filled + * in by caller. Must not have been passed + * to Tk_CreatePhotoImageFormat previously. */ +{ + Tk_PhotoImageFormat *copyPtr; + + copyPtr = (Tk_PhotoImageFormat *) ckalloc(sizeof(Tk_PhotoImageFormat)); + *copyPtr = *formatPtr; + copyPtr->name = (char *) ckalloc((unsigned) (strlen(formatPtr->name) + 1)); + strcpy(copyPtr->name, formatPtr->name); + copyPtr->nextPtr = formatList; + formatList = copyPtr; +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoCreate -- + * + * This procedure is called by the Tk image code to create + * a new photo image. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * The data structure for a new photo image is allocated and + * initialized. + * + *---------------------------------------------------------------------- + */ + +static int +ImgPhotoCreate(interp, name, argc, argv, typePtr, master, clientDataPtr) + Tcl_Interp *interp; /* Interpreter for application containing + * image. */ + char *name; /* Name to use for image. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings for options (doesn't + * include image name or type). */ + Tk_ImageType *typePtr; /* Pointer to our type record (not used). */ + Tk_ImageMaster master; /* Token for image, to be used by us in + * later callbacks. */ + ClientData *clientDataPtr; /* Store manager's token for image here; + * it will be returned in later callbacks. */ +{ + PhotoMaster *masterPtr; + + /* + * Allocate and initialize the photo image master record. + */ + + masterPtr = (PhotoMaster *) ckalloc(sizeof(PhotoMaster)); + memset((void *) masterPtr, 0, sizeof(PhotoMaster)); + masterPtr->tkMaster = master; + masterPtr->interp = interp; + masterPtr->imageCmd = Tcl_CreateCommand(interp, name, ImgPhotoCmd, + (ClientData) masterPtr, ImgPhotoCmdDeletedProc); + masterPtr->palette = NULL; + masterPtr->pix24 = NULL; + masterPtr->instancePtr = NULL; + masterPtr->validRegion = TkCreateRegion(); + + /* + * Process configuration options given in the image create command. + */ + + if (ImgPhotoConfigureMaster(interp, masterPtr, argc, argv, 0) != TCL_OK) { + ImgPhotoDelete((ClientData) masterPtr); + return TCL_ERROR; + } + + *clientDataPtr = (ClientData) masterPtr; + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoCmd -- + * + * This procedure is invoked to process the Tcl command that + * corresponds to a photo image. See the user documentation + * for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +static int +ImgPhotoCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about photo master. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + PhotoMaster *masterPtr = (PhotoMaster *) clientData; + int c, result, index; + int x, y, width, height; + int dataWidth, dataHeight; + struct SubcommandOptions options; + int listArgc; + char **listArgv; + char **srcArgv; + unsigned char *pixelPtr; + Tk_PhotoImageBlock block; + Tk_Window tkwin; + char string[16]; + XColor color; + Tk_PhotoImageFormat *imageFormat; + int imageWidth, imageHeight; + int matched; + Tcl_Channel chan; + Tk_PhotoHandle srcHandle; + size_t length; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + + if ((c == 'b') && (strncmp(argv[1], "blank", length) == 0)) { + /* + * photo blank command - just call Tk_PhotoBlank. + */ + + if (argc == 2) { + Tk_PhotoBlank(masterPtr); + } else { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " blank\"", (char *) NULL); + return TCL_ERROR; + } + } else if ((c == 'c') && (length >= 2) + && (strncmp(argv[1], "cget", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + return TCL_ERROR; + } + Tk_ConfigureValue(interp, Tk_MainWindow(interp), configSpecs, + (char *) masterPtr, argv[2], 0); + } else if ((c == 'c') && (length >= 3) + && (strncmp(argv[1], "configure", length) == 0)) { + /* + * photo configure command - handle this in the standard way. + */ + + if (argc == 2) { + return Tk_ConfigureInfo(interp, Tk_MainWindow(interp), + configSpecs, (char *) masterPtr, (char *) NULL, 0); + } + if (argc == 3) { + return Tk_ConfigureInfo(interp, Tk_MainWindow(interp), + configSpecs, (char *) masterPtr, argv[2], 0); + } + return ImgPhotoConfigureMaster(interp, masterPtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } else if ((c == 'c') && (length >= 3) + && (strncmp(argv[1], "copy", length) == 0)) { + /* + * photo copy command - first parse options. + */ + + index = 2; + memset((VOID *) &options, 0, sizeof(options)); + options.zoomX = options.zoomY = 1; + options.subsampleX = options.subsampleY = 1; + options.name = NULL; + if (ParseSubcommandOptions(&options, interp, + OPT_FROM | OPT_TO | OPT_ZOOM | OPT_SUBSAMPLE | OPT_SHRINK, + &index, argc, argv) != TCL_OK) { + return TCL_ERROR; + } + if (options.name == NULL || index < argc) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " copy source-image ?-from x1 y1 x2 y2?", + " ?-to x1 y1 x2 y2? ?-zoom x y? ?-subsample x y?", + "\"", (char *) NULL); + return TCL_ERROR; + } + + /* + * Look for the source image and get a pointer to its image data. + * Check the values given for the -from option. + */ + + if ((srcHandle = Tk_FindPhoto(interp, options.name)) == NULL) { + Tcl_AppendResult(interp, "image \"", argv[2], "\" doesn't", + " exist or is not a photo image", (char *) NULL); + return TCL_ERROR; + } + Tk_PhotoGetImage(srcHandle, &block); + if ((options.fromX2 > block.width) || (options.fromY2 > block.height) + || (options.fromX2 > block.width) + || (options.fromY2 > block.height)) { + Tcl_AppendResult(interp, "coordinates for -from option extend ", + "outside source image", (char *) NULL); + return TCL_ERROR; + } + + /* + * Fill in default values for unspecified parameters. + */ + + if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) { + options.fromX2 = block.width; + options.fromY2 = block.height; + } + if (((options.options & OPT_TO) == 0) || (options.toX2 < 0)) { + width = options.fromX2 - options.fromX; + if (options.subsampleX > 0) { + width = (width + options.subsampleX - 1) / options.subsampleX; + } else if (options.subsampleX == 0) { + width = 0; + } else { + width = (width - options.subsampleX - 1) / -options.subsampleX; + } + options.toX2 = options.toX + width * options.zoomX; + + height = options.fromY2 - options.fromY; + if (options.subsampleY > 0) { + height = (height + options.subsampleY - 1) + / options.subsampleY; + } else if (options.subsampleY == 0) { + height = 0; + } else { + height = (height - options.subsampleY - 1) + / -options.subsampleY; + } + options.toY2 = options.toY + height * options.zoomY; + } + + /* + * Set the destination image size if the -shrink option was specified. + */ + + if (options.options & OPT_SHRINK) { + ImgPhotoSetSize(masterPtr, options.toX2, options.toY2); + } + + /* + * Copy the image data over using Tk_PhotoPutZoomedBlock. + */ + + block.pixelPtr += options.fromX * block.pixelSize + + options.fromY * block.pitch; + block.width = options.fromX2 - options.fromX; + block.height = options.fromY2 - options.fromY; + Tk_PhotoPutZoomedBlock((Tk_PhotoHandle) masterPtr, &block, + options.toX, options.toY, options.toX2 - options.toX, + options.toY2 - options.toY, options.zoomX, options.zoomY, + options.subsampleX, options.subsampleY); + + } else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) { + /* + * photo get command - first parse and check parameters. + */ + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " get x y\"", (char *) NULL); + return TCL_ERROR; + } + if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[3], &y) != TCL_OK)) { + return TCL_ERROR; + } + if ((x < 0) || (x >= masterPtr->width) + || (y < 0) || (y >= masterPtr->height)) { + Tcl_AppendResult(interp, argv[0], " get: ", + "coordinates out of range", (char *) NULL); + return TCL_ERROR; + } + + /* + * Extract the value of the desired pixel and format it as a string. + */ + + pixelPtr = masterPtr->pix24 + (y * masterPtr->width + x) * 3; + sprintf(string, "%d %d %d", pixelPtr[0], pixelPtr[1], + pixelPtr[2]); + Tcl_AppendResult(interp, string, (char *) NULL); + } else if ((c == 'p') && (strncmp(argv[1], "put", length) == 0)) { + /* + * photo put command - first parse the options and colors specified. + */ + + index = 2; + memset((VOID *) &options, 0, sizeof(options)); + options.name = NULL; + if (ParseSubcommandOptions(&options, interp, OPT_TO, + &index, argc, argv) != TCL_OK) { + return TCL_ERROR; + } + if ((options.name == NULL) || (index < argc)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " put {{colors...}...} ?-to x1 y1 x2 y2?\"", + (char *) NULL); + return TCL_ERROR; + } + if (Tcl_SplitList(interp, options.name, &dataHeight, &srcArgv) + != TCL_OK) { + return TCL_ERROR; + } + tkwin = Tk_MainWindow(interp); + block.pixelPtr = NULL; + dataWidth = 0; + pixelPtr = NULL; + for (y = 0; y < dataHeight; ++y) { + if (Tcl_SplitList(interp, srcArgv[y], &listArgc, &listArgv) + != TCL_OK) { + break; + } + if (y == 0) { + dataWidth = listArgc; + pixelPtr = (unsigned char *) ckalloc((unsigned) + dataWidth * dataHeight * 3); + block.pixelPtr = pixelPtr; + } else { + if (listArgc != dataWidth) { + Tcl_AppendResult(interp, "all elements of color list must", + " have the same number of elements", + (char *) NULL); + ckfree((char *) listArgv); + break; + } + } + for (x = 0; x < dataWidth; ++x) { + if (!XParseColor(Tk_Display(tkwin), Tk_Colormap(tkwin), + listArgv[x], &color)) { + Tcl_AppendResult(interp, "can't parse color \"", + listArgv[x], "\"", (char *) NULL); + break; + } + *pixelPtr++ = color.red >> 8; + *pixelPtr++ = color.green >> 8; + *pixelPtr++ = color.blue >> 8; + } + ckfree((char *) listArgv); + if (x < dataWidth) + break; + } + ckfree((char *) srcArgv); + if (y < dataHeight || dataHeight == 0 || dataWidth == 0) { + if (block.pixelPtr != NULL) { + ckfree((char *) block.pixelPtr); + } + if (y < dataHeight) { + return TCL_ERROR; + } + return TCL_OK; + } + + /* + * Fill in default values for the -to option, then + * copy the block in using Tk_PhotoPutBlock. + */ + + if (((options.options & OPT_TO) == 0) || (options.toX2 < 0)) { + options.toX2 = options.toX + dataWidth; + options.toY2 = options.toY + dataHeight; + } + block.width = dataWidth; + block.height = dataHeight; + block.pitch = dataWidth * 3; + block.pixelSize = 3; + block.offset[0] = 0; + block.offset[1] = 1; + block.offset[2] = 2; + Tk_PhotoPutBlock((ClientData)masterPtr, &block, + options.toX, options.toY, options.toX2 - options.toX, + options.toY2 - options.toY); + ckfree((char *) block.pixelPtr); + } else if ((c == 'r') && (length >= 3) + && (strncmp(argv[1], "read", length) == 0)) { + /* + * photo read command - first parse the options specified. + */ + + index = 2; + memset((VOID *) &options, 0, sizeof(options)); + options.name = NULL; + options.format = NULL; + if (ParseSubcommandOptions(&options, interp, + OPT_FORMAT | OPT_FROM | OPT_TO | OPT_SHRINK, + &index, argc, argv) != TCL_OK) { + return TCL_ERROR; + } + if ((options.name == NULL) || (index < argc)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " read fileName ?-format format-name?", + " ?-from x1 y1 x2 y2? ?-to x y? ?-shrink?\"", + (char *) NULL); + return TCL_ERROR; + } + + /* + * Prevent file system access in safe interpreters. + */ + + if (Tcl_IsSafe(interp)) { + Tcl_AppendResult(interp, "can't get image from a file in a", + " safe interpreter", (char *) NULL); + return TCL_ERROR; + } + + /* + * Open the image file and look for a handler for it. + */ + + chan = Tcl_OpenFileChannel(interp, options.name, "r", 0); + if (chan == NULL) { + return TCL_ERROR; + } + if (Tcl_SetChannelOption(interp, chan, "-translation", "binary") + != TCL_OK) { + return TCL_ERROR; + } + if (MatchFileFormat(interp, chan, options.name, options.format, + &imageFormat, &imageWidth, &imageHeight) != TCL_OK) { + Tcl_Close(NULL, chan); + return TCL_ERROR; + } + + /* + * Check the values given for the -from option. + */ + + if ((options.fromX > imageWidth) || (options.fromY > imageHeight) + || (options.fromX2 > imageWidth) + || (options.fromY2 > imageHeight)) { + Tcl_AppendResult(interp, "coordinates for -from option extend ", + "outside source image", (char *) NULL); + Tcl_Close(NULL, chan); + return TCL_ERROR; + } + if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) { + width = imageWidth - options.fromX; + height = imageHeight - options.fromY; + } else { + width = options.fromX2 - options.fromX; + height = options.fromY2 - options.fromY; + } + + /* + * If the -shrink option was specified, set the size of the image. + */ + + if (options.options & OPT_SHRINK) { + ImgPhotoSetSize(masterPtr, options.toX + width, + options.toY + height); + } + + /* + * Call the handler's file read procedure to read the data + * into the image. + */ + + result = (*imageFormat->fileReadProc)(interp, chan, options.name, + options.format, (Tk_PhotoHandle) masterPtr, options.toX, + options.toY, width, height, options.fromX, options.fromY); + if (chan != NULL) { + Tcl_Close(NULL, chan); + } + return result; + } else if ((c == 'r') && (length >= 3) + && (strncmp(argv[1], "redither", length) == 0)) { + + if (argc == 2) { + /* + * Call Dither if any part of the image is not correctly + * dithered at present. + */ + + x = masterPtr->ditherX; + y = masterPtr->ditherY; + if (masterPtr->ditherX != 0) { + Dither(masterPtr, x, y, masterPtr->width - x, 1); + } + if (masterPtr->ditherY < masterPtr->height) { + x = 0; + Dither(masterPtr, 0, masterPtr->ditherY, masterPtr->width, + masterPtr->height - masterPtr->ditherY); + } + + if (y < masterPtr->height) { + /* + * Tell the core image code that part of the image has changed. + */ + + Tk_ImageChanged(masterPtr->tkMaster, x, y, + (masterPtr->width - x), (masterPtr->height - y), + masterPtr->width, masterPtr->height); + } + + } else { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " redither\"", (char *) NULL); + return TCL_ERROR; + } + } else if ((c == 'w') && (strncmp(argv[1], "write", length) == 0)) { + + /* + * Prevent file system access in safe interpreters. + */ + + if (Tcl_IsSafe(interp)) { + Tcl_AppendResult(interp, "can't write image to a file in a", + " safe interpreter", (char *) NULL); + return TCL_ERROR; + } + + /* + * photo write command - first parse and check any options given. + */ + + index = 2; + memset((VOID *) &options, 0, sizeof(options)); + options.name = NULL; + options.format = NULL; + if (ParseSubcommandOptions(&options, interp, OPT_FORMAT | OPT_FROM, + &index, argc, argv) != TCL_OK) { + return TCL_ERROR; + } + if ((options.name == NULL) || (index < argc)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " write fileName ?-format format-name?", + "?-from x1 y1 x2 y2?\"", (char *) NULL); + return TCL_ERROR; + } + if ((options.fromX > masterPtr->width) + || (options.fromY > masterPtr->height) + || (options.fromX2 > masterPtr->width) + || (options.fromY2 > masterPtr->height)) { + Tcl_AppendResult(interp, "coordinates for -from option extend ", + "outside image", (char *) NULL); + return TCL_ERROR; + } + + /* + * Fill in default values for unspecified parameters. + */ + + if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) { + options.fromX2 = masterPtr->width; + options.fromY2 = masterPtr->height; + } + + /* + * Search for an appropriate image file format handler, + * and give an error if none is found. + */ + + matched = 0; + for (imageFormat = formatList; imageFormat != NULL; + imageFormat = imageFormat->nextPtr) { + if ((options.format == NULL) + || (strncasecmp(options.format, imageFormat->name, + strlen(imageFormat->name)) == 0)) { + matched = 1; + if (imageFormat->fileWriteProc != NULL) { + break; + } + } + } + if (imageFormat == NULL) { + if (options.format == NULL) { + Tcl_AppendResult(interp, "no available image file format ", + "has file writing capability", (char *) NULL); + } else if (!matched) { + Tcl_AppendResult(interp, "image file format \"", + options.format, "\" is unknown", (char *) NULL); + } else { + Tcl_AppendResult(interp, "image file format \"", + options.format, "\" has no file writing capability", + (char *) NULL); + } + return TCL_ERROR; + } + + /* + * Call the handler's file write procedure to write out + * the image. + */ + + Tk_PhotoGetImage((Tk_PhotoHandle) masterPtr, &block); + block.pixelPtr += options.fromY * block.pitch + options.fromX * 3; + block.width = options.fromX2 - options.fromX; + block.height = options.fromY2 - options.fromY; + return (*imageFormat->fileWriteProc)(interp, options.name, + options.format, &block); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be blank, cget, configure, copy, get, put,", + " read, redither, or write", (char *) NULL); + return TCL_ERROR; + } + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ParseSubcommandOptions -- + * + * This procedure is invoked to process one of the options + * which may be specified for the photo image subcommands, + * namely, -from, -to, -zoom, -subsample, -format, and -shrink. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * Fields in *optPtr get filled in. + * + *---------------------------------------------------------------------- + */ + +static int +ParseSubcommandOptions(optPtr, interp, allowedOptions, optIndexPtr, argc, argv) + struct SubcommandOptions *optPtr; + /* Information about the options specified + * and the values given is returned here. */ + Tcl_Interp *interp; /* Interpreter to use for reporting errors. */ + int allowedOptions; /* Indicates which options are valid for + * the current command. */ + int *optIndexPtr; /* Points to a variable containing the + * current index in argv; this variable is + * updated by this procedure. */ + int argc; /* Number of arguments in argv[]. */ + char **argv; /* Arguments to be parsed. */ +{ + int index, c, bit, currentBit; + size_t length; + char *option, **listPtr; + int values[4]; + int numValues, maxValues, argIndex; + + for (index = *optIndexPtr; index < argc; *optIndexPtr = ++index) { + /* + * We can have one value specified without an option; + * it goes into optPtr->name. + */ + + option = argv[index]; + if (option[0] != '-') { + if (optPtr->name == NULL) { + optPtr->name = option; + continue; + } + break; + } + + /* + * Work out which option this is. + */ + + length = strlen(option); + c = option[0]; + bit = 0; + currentBit = 1; + for (listPtr = optionNames; *listPtr != NULL; ++listPtr) { + if ((c == *listPtr[0]) + && (strncmp(option, *listPtr, length) == 0)) { + if (bit != 0) { + bit = 0; /* An ambiguous option. */ + break; + } + bit = currentBit; + } + currentBit <<= 1; + } + + /* + * If this option is not recognized and allowed, put + * an error message in the interpreter and return. + */ + + if ((allowedOptions & bit) == 0) { + Tcl_AppendResult(interp, "unrecognized option \"", argv[index], + "\": must be ", (char *)NULL); + bit = 1; + for (listPtr = optionNames; *listPtr != NULL; ++listPtr) { + if ((allowedOptions & bit) != 0) { + if ((allowedOptions & (bit - 1)) != 0) { + Tcl_AppendResult(interp, ", ", (char *) NULL); + if ((allowedOptions & ~((bit << 1) - 1)) == 0) { + Tcl_AppendResult(interp, "or ", (char *) NULL); + } + } + Tcl_AppendResult(interp, *listPtr, (char *) NULL); + } + bit <<= 1; + } + return TCL_ERROR; + } + + /* + * For the -from, -to, -zoom and -subsample options, + * parse the values given. Report an error if too few + * or too many values are given. + */ + + if ((bit != OPT_SHRINK) && (bit != OPT_FORMAT)) { + maxValues = ((bit == OPT_FROM) || (bit == OPT_TO))? 4: 2; + argIndex = index + 1; + for (numValues = 0; numValues < maxValues; ++numValues) { + if ((argIndex < argc) && (isdigit(UCHAR(argv[argIndex][0])) + || ((argv[argIndex][0] == '-') + && (isdigit(UCHAR(argv[argIndex][1])))))) { + if (Tcl_GetInt(interp, argv[argIndex], &values[numValues]) + != TCL_OK) { + return TCL_ERROR; + } + } else { + break; + } + ++argIndex; + } + + if (numValues == 0) { + Tcl_AppendResult(interp, "the \"", argv[index], "\" option ", + "requires one ", maxValues == 2? "or two": "to four", + " integer values", (char *) NULL); + return TCL_ERROR; + } + *optIndexPtr = (index += numValues); + + /* + * Y values default to the corresponding X value if not specified. + */ + + if (numValues == 1) { + values[1] = values[0]; + } + if (numValues == 3) { + values[3] = values[2]; + } + + /* + * Check the values given and put them in the appropriate + * field of the SubcommandOptions structure. + */ + + switch (bit) { + case OPT_FROM: + if ((values[0] < 0) || (values[1] < 0) || ((numValues > 2) + && ((values[2] < 0) || (values[3] < 0)))) { + Tcl_AppendResult(interp, "value(s) for the -from", + " option must be non-negative", (char *) NULL); + return TCL_ERROR; + } + if (numValues <= 2) { + optPtr->fromX = values[0]; + optPtr->fromY = values[1]; + optPtr->fromX2 = -1; + optPtr->fromY2 = -1; + } else { + optPtr->fromX = MIN(values[0], values[2]); + optPtr->fromY = MIN(values[1], values[3]); + optPtr->fromX2 = MAX(values[0], values[2]); + optPtr->fromY2 = MAX(values[1], values[3]); + } + break; + case OPT_SUBSAMPLE: + optPtr->subsampleX = values[0]; + optPtr->subsampleY = values[1]; + break; + case OPT_TO: + if ((values[0] < 0) || (values[1] < 0) || ((numValues > 2) + && ((values[2] < 0) || (values[3] < 0)))) { + Tcl_AppendResult(interp, "value(s) for the -to", + " option must be non-negative", (char *) NULL); + return TCL_ERROR; + } + if (numValues <= 2) { + optPtr->toX = values[0]; + optPtr->toY = values[1]; + optPtr->toX2 = -1; + optPtr->toY2 = -1; + } else { + optPtr->toX = MIN(values[0], values[2]); + optPtr->toY = MIN(values[1], values[3]); + optPtr->toX2 = MAX(values[0], values[2]); + optPtr->toY2 = MAX(values[1], values[3]); + } + break; + case OPT_ZOOM: + if ((values[0] <= 0) || (values[1] <= 0)) { + Tcl_AppendResult(interp, "value(s) for the -zoom", + " option must be positive", (char *) NULL); + return TCL_ERROR; + } + optPtr->zoomX = values[0]; + optPtr->zoomY = values[1]; + break; + } + } else if (bit == OPT_FORMAT) { + /* + * The -format option takes a single string value. + */ + + if (index + 1 < argc) { + *optIndexPtr = ++index; + optPtr->format = argv[index]; + } else { + Tcl_AppendResult(interp, "the \"-format\" option ", + "requires a value", (char *) NULL); + return TCL_ERROR; + } + } + + /* + * Remember that we saw this option. + */ + + optPtr->options |= bit; + } + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoConfigureMaster -- + * + * This procedure is called when a photo image is created or + * reconfigured. It processes configuration options and resets + * any instances of the image. + * + * Results: + * A standard Tcl return value. If TCL_ERROR is returned then + * an error message is left in masterPtr->interp->result. + * + * Side effects: + * Existing instances of the image will be redisplayed to match + * the new configuration options. + * + *---------------------------------------------------------------------- + */ + +static int +ImgPhotoConfigureMaster(interp, masterPtr, argc, argv, flags) + Tcl_Interp *interp; /* Interpreter to use for reporting errors. */ + PhotoMaster *masterPtr; /* Pointer to data structure describing + * overall photo image to (re)configure. */ + int argc; /* Number of entries in argv. */ + char **argv; /* Pairs of configuration options for image. */ + int flags; /* Flags to pass to Tk_ConfigureWidget, + * such as TK_CONFIG_ARGV_ONLY. */ +{ + PhotoInstance *instancePtr; + char *oldFileString, *oldDataString, *oldPaletteString; + double oldGamma; + int result; + Tcl_Channel chan; + Tk_PhotoImageFormat *imageFormat; + int imageWidth, imageHeight; + + /* + * Save the current values for fileString and dataString, so we + * can tell if the user specifies them anew. + */ + + oldFileString = masterPtr->fileString; + oldDataString = (oldFileString == NULL)? masterPtr->dataString: NULL; + oldPaletteString = masterPtr->palette; + oldGamma = masterPtr->gamma; + + /* + * Process the configuration options specified. + */ + + if (Tk_ConfigureWidget(interp, Tk_MainWindow(interp), configSpecs, + argc, argv, (char *) masterPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * Regard the empty string for -file, -data or -format as the null + * value. + */ + + if ((masterPtr->fileString != NULL) && (masterPtr->fileString[0] == 0)) { + ckfree(masterPtr->fileString); + masterPtr->fileString = NULL; + } + if ((masterPtr->dataString != NULL) && (masterPtr->dataString[0] == 0)) { + ckfree(masterPtr->dataString); + masterPtr->dataString = NULL; + } + if ((masterPtr->format != NULL) && (masterPtr->format[0] == 0)) { + ckfree(masterPtr->format); + masterPtr->format = NULL; + } + + /* + * Set the image to the user-requested size, if any, + * and make sure storage is correctly allocated for this image. + */ + + ImgPhotoSetSize(masterPtr, masterPtr->width, masterPtr->height); + + /* + * Read in the image from the file or string if the user has + * specified the -file or -data option. + */ + + if ((masterPtr->fileString != NULL) + && (masterPtr->fileString != oldFileString)) { + + /* + * Prevent file system access in a safe interpreter. + */ + + if (Tcl_IsSafe(interp)) { + Tcl_AppendResult(interp, "can't get image from a file in a", + " safe interpreter", (char *) NULL); + return TCL_ERROR; + } + + chan = Tcl_OpenFileChannel(interp, masterPtr->fileString, "r", 0); + if (chan == NULL) { + return TCL_ERROR; + } + if (Tcl_SetChannelOption(interp, chan, "-translation", "binary") + != TCL_OK) { + return TCL_ERROR; + } + if (MatchFileFormat(interp, chan, masterPtr->fileString, + masterPtr->format, &imageFormat, &imageWidth, + &imageHeight) != TCL_OK) { + Tcl_Close(NULL, chan); + return TCL_ERROR; + } + ImgPhotoSetSize(masterPtr, imageWidth, imageHeight); + result = (*imageFormat->fileReadProc)(interp, chan, + masterPtr->fileString, masterPtr->format, + (Tk_PhotoHandle) masterPtr, 0, 0, + imageWidth, imageHeight, 0, 0); + Tcl_Close(NULL, chan); + if (result != TCL_OK) { + return TCL_ERROR; + } + + masterPtr->flags |= IMAGE_CHANGED; + } + + if ((masterPtr->fileString == NULL) && (masterPtr->dataString != NULL) + && (masterPtr->dataString != oldDataString)) { + + if (MatchStringFormat(interp, masterPtr->dataString, + masterPtr->format, &imageFormat, &imageWidth, + &imageHeight) != TCL_OK) { + return TCL_ERROR; + } + ImgPhotoSetSize(masterPtr, imageWidth, imageHeight); + if ((*imageFormat->stringReadProc)(interp, masterPtr->dataString, + masterPtr->format, (Tk_PhotoHandle) masterPtr, + 0, 0, imageWidth, imageHeight, 0, 0) != TCL_OK) { + return TCL_ERROR; + } + + masterPtr->flags |= IMAGE_CHANGED; + } + + /* + * Enforce a reasonable value for gamma. + */ + + if (masterPtr->gamma <= 0) { + masterPtr->gamma = 1.0; + } + + if ((masterPtr->gamma != oldGamma) + || (masterPtr->palette != oldPaletteString)) { + masterPtr->flags |= IMAGE_CHANGED; + } + + /* + * Cycle through all of the instances of this image, regenerating + * the information for each instance. Then force the image to be + * redisplayed everywhere that it is used. + */ + + for (instancePtr = masterPtr->instancePtr; instancePtr != NULL; + instancePtr = instancePtr->nextPtr) { + ImgPhotoConfigureInstance(instancePtr); + } + + /* + * Inform the generic image code that the image + * has (potentially) changed. + */ + + Tk_ImageChanged(masterPtr->tkMaster, 0, 0, masterPtr->width, + masterPtr->height, masterPtr->width, masterPtr->height); + masterPtr->flags &= ~IMAGE_CHANGED; + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoConfigureInstance -- + * + * This procedure is called to create displaying information for + * a photo image instance based on the configuration information + * in the master. It is invoked both when new instances are + * created and when the master is reconfigured. + * + * Results: + * None. + * + * Side effects: + * Generates errors via Tcl_BackgroundError if there are problems + * in setting up the instance. + * + *---------------------------------------------------------------------- + */ + +static void +ImgPhotoConfigureInstance(instancePtr) + PhotoInstance *instancePtr; /* Instance to reconfigure. */ +{ + PhotoMaster *masterPtr = instancePtr->masterPtr; + XImage *imagePtr; + int bitsPerPixel; + ColorTable *colorTablePtr; + XRectangle validBox; + + /* + * If the -palette configuration option has been set for the master, + * use the value specified for our palette, but only if it is + * a valid palette for our windows. Use the gamma value specified + * the master. + */ + + if ((masterPtr->palette && masterPtr->palette[0]) + && IsValidPalette(instancePtr, masterPtr->palette)) { + instancePtr->palette = masterPtr->palette; + } else { + instancePtr->palette = instancePtr->defaultPalette; + } + instancePtr->gamma = masterPtr->gamma; + + /* + * If we don't currently have a color table, or if the one we + * have no longer applies (e.g. because our palette or gamma + * has changed), get a new one. + */ + + colorTablePtr = instancePtr->colorTablePtr; + if ((colorTablePtr == NULL) + || (instancePtr->colormap != colorTablePtr->id.colormap) + || (instancePtr->palette != colorTablePtr->id.palette) + || (instancePtr->gamma != colorTablePtr->id.gamma)) { + /* + * Free up our old color table, and get a new one. + */ + + if (colorTablePtr != NULL) { + colorTablePtr->liveRefCount -= 1; + FreeColorTable(colorTablePtr); + } + GetColorTable(instancePtr); + + /* + * Create a new XImage structure for sending data to + * the X server, if necessary. + */ + + if (instancePtr->colorTablePtr->flags & BLACK_AND_WHITE) { + bitsPerPixel = 1; + } else { + bitsPerPixel = instancePtr->visualInfo.depth; + } + + if ((instancePtr->imagePtr == NULL) + || (instancePtr->imagePtr->bits_per_pixel != bitsPerPixel)) { + if (instancePtr->imagePtr != NULL) { + XFree((char *) instancePtr->imagePtr); + } + imagePtr = XCreateImage(instancePtr->display, + instancePtr->visualInfo.visual, (unsigned) bitsPerPixel, + (bitsPerPixel > 1? ZPixmap: XYBitmap), 0, (char *) NULL, + 1, 1, 32, 0); + instancePtr->imagePtr = imagePtr; + + /* + * Determine the endianness of this machine. + * We create images using the local host's endianness, rather + * than the endianness of the server; otherwise we would have + * to byte-swap any 16 or 32 bit values that we store in the + * image in those situations where the server's endianness + * is different from ours. + */ + + if (imagePtr != NULL) { + union { + int i; + char c[sizeof(int)]; + } kludge; + + imagePtr->bitmap_unit = sizeof(pixel) * NBBY; + kludge.i = 0; + kludge.c[0] = 1; + imagePtr->byte_order = (kludge.i == 1) ? LSBFirst : MSBFirst; + _XInitImageFuncPtrs(imagePtr); + } + } + } + + /* + * If the user has specified a width and/or height for the master + * which is different from our current width/height, set the size + * to the values specified by the user. If we have no pixmap, we + * do this also, since it has the side effect of allocating a + * pixmap for us. + */ + + if ((instancePtr->pixels == None) || (instancePtr->error == NULL) + || (instancePtr->width != masterPtr->width) + || (instancePtr->height != masterPtr->height)) { + ImgPhotoInstanceSetSize(instancePtr); + } + + /* + * Redither this instance if necessary. + */ + + if ((masterPtr->flags & IMAGE_CHANGED) + || (instancePtr->colorTablePtr != colorTablePtr)) { + TkClipBox(masterPtr->validRegion, &validBox); + if ((validBox.width > 0) && (validBox.height > 0)) { + DitherInstance(instancePtr, validBox.x, validBox.y, + validBox.width, validBox.height); + } + } + +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoGet -- + * + * This procedure is called for each use of a photo image in a + * widget. + * + * Results: + * The return value is a token for the instance, which is passed + * back to us in calls to ImgPhotoDisplay and ImgPhotoFree. + * + * Side effects: + * A data structure is set up for the instance (or, an existing + * instance is re-used for the new one). + * + *---------------------------------------------------------------------- + */ + +static ClientData +ImgPhotoGet(tkwin, masterData) + Tk_Window tkwin; /* Window in which the instance will be + * used. */ + ClientData masterData; /* Pointer to our master structure for the + * image. */ +{ + PhotoMaster *masterPtr = (PhotoMaster *) masterData; + PhotoInstance *instancePtr; + Colormap colormap; + int mono, nRed, nGreen, nBlue; + XVisualInfo visualInfo, *visInfoPtr; + XRectangle validBox; + char buf[16]; + int numVisuals; + XColor *white, *black; + XGCValues gcValues; + + /* + * Table of "best" choices for palette for PseudoColor displays + * with between 3 and 15 bits/pixel. + */ + + static int paletteChoice[13][3] = { + /* #red, #green, #blue */ + {2, 2, 2, /* 3 bits, 8 colors */}, + {2, 3, 2, /* 4 bits, 12 colors */}, + {3, 4, 2, /* 5 bits, 24 colors */}, + {4, 5, 3, /* 6 bits, 60 colors */}, + {5, 6, 4, /* 7 bits, 120 colors */}, + {7, 7, 4, /* 8 bits, 198 colors */}, + {8, 10, 6, /* 9 bits, 480 colors */}, + {10, 12, 8, /* 10 bits, 960 colors */}, + {14, 15, 9, /* 11 bits, 1890 colors */}, + {16, 20, 12, /* 12 bits, 3840 colors */}, + {20, 24, 16, /* 13 bits, 7680 colors */}, + {26, 30, 20, /* 14 bits, 15600 colors */}, + {32, 32, 30, /* 15 bits, 30720 colors */} + }; + + /* + * See if there is already an instance for windows using + * the same colormap. If so then just re-use it. + */ + + colormap = Tk_Colormap(tkwin); + for (instancePtr = masterPtr->instancePtr; instancePtr != NULL; + instancePtr = instancePtr->nextPtr) { + if ((colormap == instancePtr->colormap) + && (Tk_Display(tkwin) == instancePtr->display)) { + + /* + * Re-use this instance. + */ + + if (instancePtr->refCount == 0) { + /* + * We are resurrecting this instance. + */ + + Tcl_CancelIdleCall(DisposeInstance, (ClientData) instancePtr); + if (instancePtr->colorTablePtr != NULL) { + FreeColorTable(instancePtr->colorTablePtr); + } + GetColorTable(instancePtr); + } + instancePtr->refCount++; + return (ClientData) instancePtr; + } + } + + /* + * The image isn't already in use in a window with the same colormap. + * Make a new instance of the image. + */ + + instancePtr = (PhotoInstance *) ckalloc(sizeof(PhotoInstance)); + instancePtr->masterPtr = masterPtr; + instancePtr->display = Tk_Display(tkwin); + instancePtr->colormap = Tk_Colormap(tkwin); + Tk_PreserveColormap(instancePtr->display, instancePtr->colormap); + instancePtr->refCount = 1; + instancePtr->colorTablePtr = NULL; + instancePtr->pixels = None; + instancePtr->error = NULL; + instancePtr->width = 0; + instancePtr->height = 0; + instancePtr->imagePtr = 0; + instancePtr->nextPtr = masterPtr->instancePtr; + masterPtr->instancePtr = instancePtr; + + /* + * Obtain information about the visual and decide on the + * default palette. + */ + + visualInfo.screen = Tk_ScreenNumber(tkwin); + visualInfo.visualid = XVisualIDFromVisual(Tk_Visual(tkwin)); + visInfoPtr = XGetVisualInfo(Tk_Display(tkwin), + VisualScreenMask | VisualIDMask, &visualInfo, &numVisuals); + nRed = 2; + nGreen = nBlue = 0; + mono = 1; + if (visInfoPtr != NULL) { + instancePtr->visualInfo = *visInfoPtr; + switch (visInfoPtr->class) { + case DirectColor: + case TrueColor: + nRed = 1 << CountBits(visInfoPtr->red_mask); + nGreen = 1 << CountBits(visInfoPtr->green_mask); + nBlue = 1 << CountBits(visInfoPtr->blue_mask); + mono = 0; + break; + case PseudoColor: + case StaticColor: + if (visInfoPtr->depth > 15) { + nRed = 32; + nGreen = 32; + nBlue = 32; + mono = 0; + } else if (visInfoPtr->depth >= 3) { + int *ip = paletteChoice[visInfoPtr->depth - 3]; + + nRed = ip[0]; + nGreen = ip[1]; + nBlue = ip[2]; + mono = 0; + } + break; + case GrayScale: + case StaticGray: + nRed = 1 << visInfoPtr->depth; + break; + } + XFree((char *) visInfoPtr); + + } else { + panic("ImgPhotoGet couldn't find visual for window"); + } + + sprintf(buf, ((mono) ? "%d": "%d/%d/%d"), nRed, nGreen, nBlue); + instancePtr->defaultPalette = Tk_GetUid(buf); + + /* + * Make a GC with background = black and foreground = white. + */ + + white = Tk_GetColor(masterPtr->interp, tkwin, "white"); + black = Tk_GetColor(masterPtr->interp, tkwin, "black"); + gcValues.foreground = (white != NULL)? white->pixel: + WhitePixelOfScreen(Tk_Screen(tkwin)); + gcValues.background = (black != NULL)? black->pixel: + BlackPixelOfScreen(Tk_Screen(tkwin)); + gcValues.graphics_exposures = False; + instancePtr->gc = Tk_GetGC(tkwin, + GCForeground|GCBackground|GCGraphicsExposures, &gcValues); + + /* + * Set configuration options and finish the initialization of the instance. + */ + + ImgPhotoConfigureInstance(instancePtr); + + /* + * If this is the first instance, must set the size of the image. + */ + + if (instancePtr->nextPtr == NULL) { + Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0, + masterPtr->width, masterPtr->height); + } + + /* + * Dither the image to fill in this instance's pixmap. + */ + + TkClipBox(masterPtr->validRegion, &validBox); + if ((validBox.width > 0) && (validBox.height > 0)) { + DitherInstance(instancePtr, validBox.x, validBox.y, validBox.width, + validBox.height); + } + + return (ClientData) instancePtr; +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoDisplay -- + * + * This procedure is invoked to draw a photo image. + * + * Results: + * None. + * + * Side effects: + * A portion of the image gets rendered in a pixmap or window. + * + *---------------------------------------------------------------------- + */ + +static void +ImgPhotoDisplay(clientData, display, drawable, imageX, imageY, width, + height, drawableX, drawableY) + ClientData clientData; /* Pointer to PhotoInstance structure for + * for instance to be displayed. */ + Display *display; /* Display on which to draw image. */ + Drawable drawable; /* Pixmap or window in which to draw image. */ + int imageX, imageY; /* Upper-left corner of region within image + * to draw. */ + int width, height; /* Dimensions of region within image to draw. */ + int drawableX, drawableY; /* Coordinates within drawable that + * correspond to imageX and imageY. */ +{ + PhotoInstance *instancePtr = (PhotoInstance *) clientData; + + /* + * If there's no pixmap, it means that an error occurred + * while creating the image instance so it can't be displayed. + */ + + if (instancePtr->pixels == None) { + return; + } + + /* + * masterPtr->region describes which parts of the image contain + * valid data. We set this region as the clip mask for the gc, + * setting its origin appropriately, and use it when drawing the + * image. + */ + + TkSetRegion(display, instancePtr->gc, instancePtr->masterPtr->validRegion); + XSetClipOrigin(display, instancePtr->gc, drawableX - imageX, + drawableY - imageY); + XCopyArea(display, instancePtr->pixels, drawable, instancePtr->gc, + imageX, imageY, (unsigned) width, (unsigned) height, + drawableX, drawableY); + XSetClipMask(display, instancePtr->gc, None); + XSetClipOrigin(display, instancePtr->gc, 0, 0); +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoFree -- + * + * This procedure is called when a widget ceases to use a + * particular instance of an image. We don't actually get + * rid of the instance until later because we may be about + * to get this instance again. + * + * Results: + * None. + * + * Side effects: + * Internal data structures get cleaned up, later. + * + *---------------------------------------------------------------------- + */ + +static void +ImgPhotoFree(clientData, display) + ClientData clientData; /* Pointer to PhotoInstance structure for + * for instance to be displayed. */ + Display *display; /* Display containing window that used image. */ +{ + PhotoInstance *instancePtr = (PhotoInstance *) clientData; + ColorTable *colorPtr; + + instancePtr->refCount -= 1; + if (instancePtr->refCount > 0) { + return; + } + + /* + * There are no more uses of the image within this widget. + * Decrement the count of live uses of its color table, so + * that its colors can be reclaimed if necessary, and + * set up an idle call to free the instance structure. + */ + + colorPtr = instancePtr->colorTablePtr; + if (colorPtr != NULL) { + colorPtr->liveRefCount -= 1; + } + + Tcl_DoWhenIdle(DisposeInstance, (ClientData) instancePtr); +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoDelete -- + * + * This procedure is called by the image code to delete the + * master structure for an image. + * + * Results: + * None. + * + * Side effects: + * Resources associated with the image get freed. + * + *---------------------------------------------------------------------- + */ + +static void +ImgPhotoDelete(masterData) + ClientData masterData; /* Pointer to PhotoMaster structure for + * image. Must not have any more instances. */ +{ + PhotoMaster *masterPtr = (PhotoMaster *) masterData; + PhotoInstance *instancePtr; + + while ((instancePtr = masterPtr->instancePtr) != NULL) { + if (instancePtr->refCount > 0) { + panic("tried to delete photo image when instances still exist"); + } + Tcl_CancelIdleCall(DisposeInstance, (ClientData) instancePtr); + DisposeInstance((ClientData) instancePtr); + } + masterPtr->tkMaster = NULL; + if (masterPtr->imageCmd != NULL) { + Tcl_DeleteCommandFromToken(masterPtr->interp, masterPtr->imageCmd); + } + if (masterPtr->pix24 != NULL) { + ckfree((char *) masterPtr->pix24); + } + if (masterPtr->validRegion != NULL) { + TkDestroyRegion(masterPtr->validRegion); + } + Tk_FreeOptions(configSpecs, (char *) masterPtr, (Display *) NULL, 0); + ckfree((char *) masterPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoCmdDeletedProc -- + * + * This procedure is invoked when the image command for an image + * is deleted. It deletes the image. + * + * Results: + * None. + * + * Side effects: + * The image is deleted. + * + *---------------------------------------------------------------------- + */ + +static void +ImgPhotoCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to PhotoMaster structure for + * image. */ +{ + PhotoMaster *masterPtr = (PhotoMaster *) clientData; + + masterPtr->imageCmd = NULL; + if (masterPtr->tkMaster != NULL) { + Tk_DeleteImage(masterPtr->interp, Tk_NameOfImage(masterPtr->tkMaster)); + } +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoSetSize -- + * + * This procedure reallocates the image storage and instance + * pixmaps for a photo image, as necessary, to change the + * image's size to `width' x `height' pixels. + * + * Results: + * None. + * + * Side effects: + * Storage gets reallocated, for the master and all its instances. + * + *---------------------------------------------------------------------- + */ + +static void +ImgPhotoSetSize(masterPtr, width, height) + PhotoMaster *masterPtr; + int width, height; +{ + unsigned char *newPix24; + int h, offset, pitch; + unsigned char *srcPtr, *destPtr; + XRectangle validBox, clipBox; + TkRegion clipRegion; + PhotoInstance *instancePtr; + + if (masterPtr->userWidth > 0) { + width = masterPtr->userWidth; + } + if (masterPtr->userHeight > 0) { + height = masterPtr->userHeight; + } + + /* + * We have to trim the valid region if it is currently + * larger than the new image size. + */ + + TkClipBox(masterPtr->validRegion, &validBox); + if ((validBox.x + validBox.width > width) + || (validBox.y + validBox.height > height)) { + clipBox.x = 0; + clipBox.y = 0; + clipBox.width = width; + clipBox.height = height; + clipRegion = TkCreateRegion(); + TkUnionRectWithRegion(&clipBox, clipRegion, clipRegion); + TkIntersectRegion(masterPtr->validRegion, clipRegion, + masterPtr->validRegion); + TkDestroyRegion(clipRegion); + TkClipBox(masterPtr->validRegion, &validBox); + } + + if ((width != masterPtr->width) || (height != masterPtr->height) + || (masterPtr->pix24 == NULL)) { + + /* + * Reallocate storage for the 24-bit image and copy + * over valid regions. + */ + + pitch = width * 3; + newPix24 = (unsigned char *) ckalloc((unsigned) (height * pitch)); + + /* + * Zero the new array. The dithering code shouldn't read the + * areas outside validBox, but they might be copied to another + * photo image or written to a file. + */ + + if ((masterPtr->pix24 != NULL) + && ((width == masterPtr->width) || (width == validBox.width))) { + if (validBox.y > 0) { + memset((VOID *) newPix24, 0, (size_t) (validBox.y * pitch)); + } + h = validBox.y + validBox.height; + if (h < height) { + memset((VOID *) (newPix24 + h * pitch), 0, + (size_t) ((height - h) * pitch)); + } + } else { + memset((VOID *) newPix24, 0, (size_t) (height * pitch)); + } + + if (masterPtr->pix24 != NULL) { + + /* + * Copy the common area over to the new array array and + * free the old array. + */ + + if (width == masterPtr->width) { + + /* + * The region to be copied is contiguous. + */ + + offset = validBox.y * pitch; + memcpy((VOID *) (newPix24 + offset), + (VOID *) (masterPtr->pix24 + offset), + (size_t) (validBox.height * pitch)); + + } else if ((validBox.width > 0) && (validBox.height > 0)) { + + /* + * Area to be copied is not contiguous - copy line by line. + */ + + destPtr = newPix24 + (validBox.y * width + validBox.x) * 3; + srcPtr = masterPtr->pix24 + (validBox.y * masterPtr->width + + validBox.x) * 3; + for (h = validBox.height; h > 0; h--) { + memcpy((VOID *) destPtr, (VOID *) srcPtr, + (size_t) (validBox.width * 3)); + destPtr += width * 3; + srcPtr += masterPtr->width * 3; + } + } + + ckfree((char *) masterPtr->pix24); + } + + masterPtr->pix24 = newPix24; + masterPtr->width = width; + masterPtr->height = height; + + /* + * Dithering will be correct up to the end of the last + * pre-existing complete scanline. + */ + + if ((validBox.x > 0) || (validBox.y > 0)) { + masterPtr->ditherX = 0; + masterPtr->ditherY = 0; + } else if (validBox.width == width) { + if ((int) validBox.height < masterPtr->ditherY) { + masterPtr->ditherX = 0; + masterPtr->ditherY = validBox.height; + } + } else { + if ((masterPtr->ditherY > 0) + || ((int) validBox.width < masterPtr->ditherX)) { + masterPtr->ditherX = validBox.width; + masterPtr->ditherY = 0; + } + } + } + + /* + * Now adjust the sizes of the pixmaps for all of the instances. + */ + + for (instancePtr = masterPtr->instancePtr; instancePtr != NULL; + instancePtr = instancePtr->nextPtr) { + ImgPhotoInstanceSetSize(instancePtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * ImgPhotoInstanceSetSize -- + * + * This procedure reallocates the instance pixmap and dithering + * error array for a photo instance, as necessary, to change the + * image's size to `width' x `height' pixels. + * + * Results: + * None. + * + * Side effects: + * Storage gets reallocated, here and in the X server. + * + *---------------------------------------------------------------------- + */ + +static void +ImgPhotoInstanceSetSize(instancePtr) + PhotoInstance *instancePtr; /* Instance whose size is to be + * changed. */ +{ + PhotoMaster *masterPtr; + schar *newError; + schar *errSrcPtr, *errDestPtr; + int h, offset; + XRectangle validBox; + Pixmap newPixmap; + + masterPtr = instancePtr->masterPtr; + TkClipBox(masterPtr->validRegion, &validBox); + + if ((instancePtr->width != masterPtr->width) + || (instancePtr->height != masterPtr->height) + || (instancePtr->pixels == None)) { + newPixmap = Tk_GetPixmap(instancePtr->display, + RootWindow(instancePtr->display, + instancePtr->visualInfo.screen), + (masterPtr->width > 0) ? masterPtr->width: 1, + (masterPtr->height > 0) ? masterPtr->height: 1, + instancePtr->visualInfo.depth); + + /* + * The following is a gross hack needed to properly support colormaps + * under Windows. Before the pixels can be copied to the pixmap, + * the relevent colormap must be associated with the drawable. + * Normally we can infer this association from the window that + * was used to create the pixmap. However, in this case we're + * using the root window, so we have to be more explicit. + */ + + TkSetPixmapColormap(newPixmap, instancePtr->colormap); + + if (instancePtr->pixels != None) { + /* + * Copy any common pixels from the old pixmap and free it. + */ + XCopyArea(instancePtr->display, instancePtr->pixels, newPixmap, + instancePtr->gc, validBox.x, validBox.y, + validBox.width, validBox.height, validBox.x, validBox.y); + Tk_FreePixmap(instancePtr->display, instancePtr->pixels); + } + instancePtr->pixels = newPixmap; + } + + if ((instancePtr->width != masterPtr->width) + || (instancePtr->height != masterPtr->height) + || (instancePtr->error == NULL)) { + + newError = (schar *) ckalloc((unsigned) + (masterPtr->height * masterPtr->width * 3 * sizeof(schar))); + + /* + * Zero the new array so that we don't get bogus error values + * propagating into areas we dither later. + */ + + if ((instancePtr->error != NULL) + && ((instancePtr->width == masterPtr->width) + || (validBox.width == masterPtr->width))) { + if (validBox.y > 0) { + memset((VOID *) newError, 0, (size_t) + (validBox.y * masterPtr->width * 3 * sizeof(schar))); + } + h = validBox.y + validBox.height; + if (h < masterPtr->height) { + memset((VOID *) (newError + h * masterPtr->width * 3), 0, + (size_t) ((masterPtr->height - h) + * masterPtr->width * 3 * sizeof(schar))); + } + } else { + memset((VOID *) newError, 0, (size_t) + (masterPtr->height * masterPtr->width * 3 * sizeof(schar))); + } + + if (instancePtr->error != NULL) { + + /* + * Copy the common area over to the new array + * and free the old array. + */ + + if (masterPtr->width == instancePtr->width) { + + offset = validBox.y * masterPtr->width * 3; + memcpy((VOID *) (newError + offset), + (VOID *) (instancePtr->error + offset), + (size_t) (validBox.height + * masterPtr->width * 3 * sizeof(schar))); + + } else if (validBox.width > 0 && validBox.height > 0) { + + errDestPtr = newError + + (validBox.y * masterPtr->width + validBox.x) * 3; + errSrcPtr = instancePtr->error + + (validBox.y * instancePtr->width + validBox.x) * 3; + for (h = validBox.height; h > 0; --h) { + memcpy((VOID *) errDestPtr, (VOID *) errSrcPtr, + validBox.width * 3 * sizeof(schar)); + errDestPtr += masterPtr->width * 3; + errSrcPtr += instancePtr->width * 3; + } + } + ckfree((char *) instancePtr->error); + } + + instancePtr->error = newError; + } + + instancePtr->width = masterPtr->width; + instancePtr->height = masterPtr->height; +} + +/* + *---------------------------------------------------------------------- + * + * IsValidPalette -- + * + * This procedure is called to check whether a value given for + * the -palette option is valid for a particular instance + * of a photo image. + * + * Results: + * A boolean value: 1 if the palette is acceptable, 0 otherwise. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +IsValidPalette(instancePtr, palette) + PhotoInstance *instancePtr; /* Instance to which the palette + * specification is to be applied. */ + char *palette; /* Palette specification string. */ +{ + int nRed, nGreen, nBlue, mono, numColors; + char *endp; + + /* + * First parse the specification: it must be of the form + * %d or %d/%d/%d. + */ + + nRed = strtol(palette, &endp, 10); + if ((endp == palette) || ((*endp != 0) && (*endp != '/')) + || (nRed < 2) || (nRed > 256)) { + return 0; + } + + if (*endp == 0) { + mono = 1; + nGreen = nBlue = nRed; + } else { + palette = endp + 1; + nGreen = strtol(palette, &endp, 10); + if ((endp == palette) || (*endp != '/') || (nGreen < 2) + || (nGreen > 256)) { + return 0; + } + palette = endp + 1; + nBlue = strtol(palette, &endp, 10); + if ((endp == palette) || (*endp != 0) || (nBlue < 2) + || (nBlue > 256)) { + return 0; + } + mono = 0; + } + + switch (instancePtr->visualInfo.class) { + case DirectColor: + case TrueColor: + if ((nRed > (1 << CountBits(instancePtr->visualInfo.red_mask))) + || (nGreen > (1 + << CountBits(instancePtr->visualInfo.green_mask))) + || (nBlue > (1 + << CountBits(instancePtr->visualInfo.blue_mask)))) { + return 0; + } + break; + case PseudoColor: + case StaticColor: + numColors = nRed; + if (!mono) { + numColors *= nGreen*nBlue; + } + if (numColors > (1 << instancePtr->visualInfo.depth)) { + return 0; + } + break; + case GrayScale: + case StaticGray: + if (!mono || (nRed > (1 << instancePtr->visualInfo.depth))) { + return 0; + } + break; + } + + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * CountBits -- + * + * This procedure counts how many bits are set to 1 in `mask'. + * + * Results: + * The integer number of bits. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +CountBits(mask) + pixel mask; /* Value to count the 1 bits in. */ +{ + int n; + + for( n = 0; mask != 0; mask &= mask - 1 ) + n++; + return n; +} + +/* + *---------------------------------------------------------------------- + * + * GetColorTable -- + * + * This procedure is called to allocate a table of colormap + * information for an instance of a photo image. Only one such + * table is allocated for all photo instances using the same + * display, colormap, palette and gamma values, so that the + * application need only request a set of colors from the X + * server once for all such photo widgets. This procedure + * maintains a hash table to find previously-allocated + * ColorTables. + * + * Results: + * None. + * + * Side effects: + * A new ColorTable may be allocated and placed in the hash + * table, and have colors allocated for it. + * + *---------------------------------------------------------------------- + */ + +static void +GetColorTable(instancePtr) + PhotoInstance *instancePtr; /* Instance needing a color table. */ +{ + ColorTable *colorPtr; + Tcl_HashEntry *entry; + ColorTableId id; + int isNew; + + /* + * Look for an existing ColorTable in the hash table. + */ + + memset((VOID *) &id, 0, sizeof(id)); + id.display = instancePtr->display; + id.colormap = instancePtr->colormap; + id.palette = instancePtr->palette; + id.gamma = instancePtr->gamma; + if (!imgPhotoColorHashInitialized) { + Tcl_InitHashTable(&imgPhotoColorHash, N_COLOR_HASH); + imgPhotoColorHashInitialized = 1; + } + entry = Tcl_CreateHashEntry(&imgPhotoColorHash, (char *) &id, &isNew); + + if (!isNew) { + /* + * Re-use the existing entry. + */ + + colorPtr = (ColorTable *) Tcl_GetHashValue(entry); + + } else { + /* + * No color table currently available; need to make one. + */ + + colorPtr = (ColorTable *) ckalloc(sizeof(ColorTable)); + + /* + * The following line of code should not normally be needed due + * to the assignment in the following line. However, it compensates + * for bugs in some compilers (HP, for example) where + * sizeof(ColorTable) is 24 but the assignment only copies 20 bytes, + * leaving 4 bytes uninitialized; these cause problems when using + * the id for lookups in imgPhotoColorHash, and can result in + * core dumps. + */ + + memset((VOID *) &colorPtr->id, 0, sizeof(ColorTableId)); + colorPtr->id = id; + Tk_PreserveColormap(colorPtr->id.display, colorPtr->id.colormap); + colorPtr->flags = 0; + colorPtr->refCount = 0; + colorPtr->liveRefCount = 0; + colorPtr->numColors = 0; + colorPtr->visualInfo = instancePtr->visualInfo; + colorPtr->pixelMap = NULL; + Tcl_SetHashValue(entry, colorPtr); + } + + colorPtr->refCount++; + colorPtr->liveRefCount++; + instancePtr->colorTablePtr = colorPtr; + if (colorPtr->flags & DISPOSE_PENDING) { + Tcl_CancelIdleCall(DisposeColorTable, (ClientData) colorPtr); + colorPtr->flags &= ~DISPOSE_PENDING; + } + + /* + * Allocate colors for this color table if necessary. + */ + + if ((colorPtr->numColors == 0) + && ((colorPtr->flags & BLACK_AND_WHITE) == 0)) { + AllocateColors(colorPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * FreeColorTable -- + * + * This procedure is called when an instance ceases using a + * color table. + * + * Results: + * None. + * + * Side effects: + * If no other instances are using this color table, a when-idle + * handler is registered to free up the color table and the colors + * allocated for it. + * + *---------------------------------------------------------------------- + */ + +static void +FreeColorTable(colorPtr) + ColorTable *colorPtr; /* Pointer to the color table which is + * no longer required by an instance. */ +{ + colorPtr->refCount--; + if (colorPtr->refCount > 0) { + return; + } + if ((colorPtr->flags & DISPOSE_PENDING) == 0) { + Tcl_DoWhenIdle(DisposeColorTable, (ClientData) colorPtr); + colorPtr->flags |= DISPOSE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * AllocateColors -- + * + * This procedure allocates the colors required by a color table, + * and sets up the fields in the color table data structure which + * are used in dithering. + * + * Results: + * None. + * + * Side effects: + * Colors are allocated from the X server. Fields in the + * color table data structure are updated. + * + *---------------------------------------------------------------------- + */ + +static void +AllocateColors(colorPtr) + ColorTable *colorPtr; /* Pointer to the color table requiring + * colors to be allocated. */ +{ + int i, r, g, b, rMult, mono; + int numColors, nRed, nGreen, nBlue; + double fr, fg, fb, igam; + XColor *colors; + unsigned long *pixels; + + /* 16-bit intensity value for i/n of full intensity. */ +# define CFRAC(i, n) ((i) * 65535 / (n)) + + /* As for CFRAC, but apply exponent of g. */ +# define CGFRAC(i, n, g) ((int)(65535 * pow((double)(i) / (n), (g)))) + + /* + * First parse the palette specification to get the required number of + * shades of each primary. + */ + + mono = sscanf(colorPtr->id.palette, "%d/%d/%d", &nRed, &nGreen, &nBlue) + <= 1; + igam = 1.0 / colorPtr->id.gamma; + + /* + * Each time around this loop, we reduce the number of colors we're + * trying to allocate until we succeed in allocating all of the colors + * we need. + */ + + for (;;) { + /* + * If we are using 1 bit/pixel, we don't need to allocate + * any colors (we just use the foreground and background + * colors in the GC). + */ + + if (mono && (nRed <= 2)) { + colorPtr->flags |= BLACK_AND_WHITE; + return; + } + + /* + * Calculate the RGB coordinates of the colors we want to + * allocate and store them in *colors. + */ + + if ((colorPtr->visualInfo.class == DirectColor) + || (colorPtr->visualInfo.class == TrueColor)) { + + /* + * Direct/True Color: allocate shades of red, green, blue + * independently. + */ + + if (mono) { + numColors = nGreen = nBlue = nRed; + } else { + numColors = MAX(MAX(nRed, nGreen), nBlue); + } + colors = (XColor *) ckalloc(numColors * sizeof(XColor)); + + for (i = 0; i < numColors; ++i) { + if (igam == 1.0) { + colors[i].red = CFRAC(i, nRed - 1); + colors[i].green = CFRAC(i, nGreen - 1); + colors[i].blue = CFRAC(i, nBlue - 1); + } else { + colors[i].red = CGFRAC(i, nRed - 1, igam); + colors[i].green = CGFRAC(i, nGreen - 1, igam); + colors[i].blue = CGFRAC(i, nBlue - 1, igam); + } + } + } else { + /* + * PseudoColor, StaticColor, GrayScale or StaticGray visual: + * we have to allocate each color in the color cube separately. + */ + + numColors = (mono) ? nRed: (nRed * nGreen * nBlue); + colors = (XColor *) ckalloc(numColors * sizeof(XColor)); + + if (!mono) { + /* + * Color display using a PseudoColor or StaticColor visual. + */ + + i = 0; + for (r = 0; r < nRed; ++r) { + for (g = 0; g < nGreen; ++g) { + for (b = 0; b < nBlue; ++b) { + if (igam == 1.0) { + colors[i].red = CFRAC(r, nRed - 1); + colors[i].green = CFRAC(g, nGreen - 1); + colors[i].blue = CFRAC(b, nBlue - 1); + } else { + colors[i].red = CGFRAC(r, nRed - 1, igam); + colors[i].green = CGFRAC(g, nGreen - 1, igam); + colors[i].blue = CGFRAC(b, nBlue - 1, igam); + } + i++; + } + } + } + } else { + /* + * Monochrome display - allocate the shades of grey we want. + */ + + for (i = 0; i < numColors; ++i) { + if (igam == 1.0) { + r = CFRAC(i, numColors - 1); + } else { + r = CGFRAC(i, numColors - 1, igam); + } + colors[i].red = colors[i].green = colors[i].blue = r; + } + } + } + + /* + * Now try to allocate the colors we've calculated. + */ + + pixels = (unsigned long *) ckalloc(numColors * sizeof(unsigned long)); + for (i = 0; i < numColors; ++i) { + if (!XAllocColor(colorPtr->id.display, colorPtr->id.colormap, + &colors[i])) { + + /* + * Can't get all the colors we want in the default colormap; + * first try freeing colors from other unused color tables. + */ + + if (!ReclaimColors(&colorPtr->id, numColors - i) + || !XAllocColor(colorPtr->id.display, + colorPtr->id.colormap, &colors[i])) { + /* + * Still can't allocate the color. + */ + break; + } + } + pixels[i] = colors[i].pixel; + } + + /* + * If we didn't get all of the colors, reduce the + * resolution of the color cube, free the ones we got, + * and try again. + */ + + if (i >= numColors) { + break; + } + XFreeColors(colorPtr->id.display, colorPtr->id.colormap, pixels, i, 0); + ckfree((char *) colors); + ckfree((char *) pixels); + + if (!mono) { + if ((nRed == 2) && (nGreen == 2) && (nBlue == 2)) { + /* + * Fall back to 1-bit monochrome display. + */ + + mono = 1; + } else { + /* + * Reduce the number of shades of each primary to about + * 3/4 of the previous value. This should reduce the + * total number of colors required to about half the + * previous value for PseudoColor displays. + */ + + nRed = (nRed * 3 + 2) / 4; + nGreen = (nGreen * 3 + 2) / 4; + nBlue = (nBlue * 3 + 2) / 4; + } + } else { + /* + * Reduce the number of shades of gray to about 1/2. + */ + + nRed = nRed / 2; + } + } + + /* + * We have allocated all of the necessary colors: + * fill in various fields of the ColorTable record. + */ + + if (!mono) { + colorPtr->flags |= COLOR_WINDOW; + + /* + * The following is a hairy hack. We only want to index into + * the pixelMap on colormap displays. However, if the display + * is on Windows, then we actually want to store the index not + * the value since we will be passing the color table into the + * TkPutImage call. + */ + +#ifndef __WIN32__ + if ((colorPtr->visualInfo.class != DirectColor) + && (colorPtr->visualInfo.class != TrueColor)) { + colorPtr->flags |= MAP_COLORS; + } +#endif /* __WIN32__ */ + } + + colorPtr->numColors = numColors; + colorPtr->pixelMap = pixels; + + /* + * Set up quantization tables for dithering. + */ + rMult = nGreen * nBlue; + for (i = 0; i < 256; ++i) { + r = (i * (nRed - 1) + 127) / 255; + if (mono) { + fr = (double) colors[r].red / 65535.0; + if (colorPtr->id.gamma != 1.0 ) { + fr = pow(fr, colorPtr->id.gamma); + } + colorPtr->colorQuant[0][i] = (int)(fr * 255.99); + colorPtr->redValues[i] = colors[r].pixel; + } else { + g = (i * (nGreen - 1) + 127) / 255; + b = (i * (nBlue - 1) + 127) / 255; + if ((colorPtr->visualInfo.class == DirectColor) + || (colorPtr->visualInfo.class == TrueColor)) { + colorPtr->redValues[i] = colors[r].pixel + & colorPtr->visualInfo.red_mask; + colorPtr->greenValues[i] = colors[g].pixel + & colorPtr->visualInfo.green_mask; + colorPtr->blueValues[i] = colors[b].pixel + & colorPtr->visualInfo.blue_mask; + } else { + r *= rMult; + g *= nBlue; + colorPtr->redValues[i] = r; + colorPtr->greenValues[i] = g; + colorPtr->blueValues[i] = b; + } + fr = (double) colors[r].red / 65535.0; + fg = (double) colors[g].green / 65535.0; + fb = (double) colors[b].blue / 65535.0; + if (colorPtr->id.gamma != 1.0) { + fr = pow(fr, colorPtr->id.gamma); + fg = pow(fg, colorPtr->id.gamma); + fb = pow(fb, colorPtr->id.gamma); + } + colorPtr->colorQuant[0][i] = (int)(fr * 255.99); + colorPtr->colorQuant[1][i] = (int)(fg * 255.99); + colorPtr->colorQuant[2][i] = (int)(fb * 255.99); + } + } + + ckfree((char *) colors); +} + +/* + *---------------------------------------------------------------------- + * + * DisposeColorTable -- + * + * + * Results: + * None. + * + * Side effects: + * The colors in the argument color table are freed, as is the + * color table structure itself. The color table is removed + * from the hash table which is used to locate color tables. + * + *---------------------------------------------------------------------- + */ + +static void +DisposeColorTable(clientData) + ClientData clientData; /* Pointer to the ColorTable whose + * colors are to be released. */ +{ + ColorTable *colorPtr; + Tcl_HashEntry *entry; + + colorPtr = (ColorTable *) clientData; + if (colorPtr->pixelMap != NULL) { + if (colorPtr->numColors > 0) { + XFreeColors(colorPtr->id.display, colorPtr->id.colormap, + colorPtr->pixelMap, colorPtr->numColors, 0); + Tk_FreeColormap(colorPtr->id.display, colorPtr->id.colormap); + } + ckfree((char *) colorPtr->pixelMap); + } + + entry = Tcl_FindHashEntry(&imgPhotoColorHash, (char *) &colorPtr->id); + if (entry == NULL) { + panic("DisposeColorTable couldn't find hash entry"); + } + Tcl_DeleteHashEntry(entry); + + ckfree((char *) colorPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ReclaimColors -- + * + * This procedure is called to try to free up colors in the + * colormap used by a color table. It looks for other color + * tables with the same colormap and with a zero live reference + * count, and frees their colors. It only does so if there is + * the possibility of freeing up at least `numColors' colors. + * + * Results: + * The return value is TRUE if any colors were freed, FALSE + * otherwise. + * + * Side effects: + * ColorTables which are not currently in use may lose their + * color allocations. + * + *---------------------------------------------------------------------- */ + +static int +ReclaimColors(id, numColors) + ColorTableId *id; /* Pointer to information identifying + * the color table which needs more colors. */ + int numColors; /* Number of colors required. */ +{ + Tcl_HashSearch srch; + Tcl_HashEntry *entry; + ColorTable *colorPtr; + int nAvail; + + /* + * First scan through the color hash table to get an + * upper bound on how many colors we might be able to free. + */ + + nAvail = 0; + entry = Tcl_FirstHashEntry(&imgPhotoColorHash, &srch); + while (entry != NULL) { + colorPtr = (ColorTable *) Tcl_GetHashValue(entry); + if ((colorPtr->id.display == id->display) + && (colorPtr->id.colormap == id->colormap) + && (colorPtr->liveRefCount == 0 )&& (colorPtr->numColors != 0) + && ((colorPtr->id.palette != id->palette) + || (colorPtr->id.gamma != id->gamma))) { + + /* + * We could take this guy's colors off him. + */ + + nAvail += colorPtr->numColors; + } + entry = Tcl_NextHashEntry(&srch); + } + + /* + * nAvail is an (over)estimate of the number of colors we could free. + */ + + if (nAvail < numColors) { + return 0; + } + + /* + * Scan through a second time freeing colors. + */ + + entry = Tcl_FirstHashEntry(&imgPhotoColorHash, &srch); + while ((entry != NULL) && (numColors > 0)) { + colorPtr = (ColorTable *) Tcl_GetHashValue(entry); + if ((colorPtr->id.display == id->display) + && (colorPtr->id.colormap == id->colormap) + && (colorPtr->liveRefCount == 0) && (colorPtr->numColors != 0) + && ((colorPtr->id.palette != id->palette) + || (colorPtr->id.gamma != id->gamma))) { + + /* + * Free the colors that this ColorTable has. + */ + + XFreeColors(colorPtr->id.display, colorPtr->id.colormap, + colorPtr->pixelMap, colorPtr->numColors, 0); + numColors -= colorPtr->numColors; + colorPtr->numColors = 0; + ckfree((char *) colorPtr->pixelMap); + colorPtr->pixelMap = NULL; + } + + entry = Tcl_NextHashEntry(&srch); + } + return 1; /* we freed some colors */ +} + +/* + *---------------------------------------------------------------------- + * + * DisposeInstance -- + * + * This procedure is called to finally free up an instance + * of a photo image which is no longer required. + * + * Results: + * None. + * + * Side effects: + * The instance data structure and the resources it references + * are freed. + * + *---------------------------------------------------------------------- + */ + +static void +DisposeInstance(clientData) + ClientData clientData; /* Pointer to the instance whose resources + * are to be released. */ +{ + PhotoInstance *instancePtr = (PhotoInstance *) clientData; + PhotoInstance *prevPtr; + + if (instancePtr->pixels != None) { + Tk_FreePixmap(instancePtr->display, instancePtr->pixels); + } + if (instancePtr->gc != None) { + Tk_FreeGC(instancePtr->display, instancePtr->gc); + } + if (instancePtr->imagePtr != NULL) { + XFree((char *) instancePtr->imagePtr); + } + if (instancePtr->error != NULL) { + ckfree((char *) instancePtr->error); + } + if (instancePtr->colorTablePtr != NULL) { + FreeColorTable(instancePtr->colorTablePtr); + } + + if (instancePtr->masterPtr->instancePtr == instancePtr) { + instancePtr->masterPtr->instancePtr = instancePtr->nextPtr; + } else { + for (prevPtr = instancePtr->masterPtr->instancePtr; + prevPtr->nextPtr != instancePtr; prevPtr = prevPtr->nextPtr) { + /* Empty loop body */ + } + prevPtr->nextPtr = instancePtr->nextPtr; + } + Tk_FreeColormap(instancePtr->display, instancePtr->colormap); + ckfree((char *) instancePtr); +} + +/* + *---------------------------------------------------------------------- + * + * MatchFileFormat -- + * + * This procedure is called to find a photo image file format + * handler which can parse the image data in the given file. + * If a user-specified format string is provided, only handlers + * whose names match a prefix of the format string are tried. + * + * Results: + * A standard TCL return value. If the return value is TCL_OK, a + * pointer to the image format record is returned in + * *imageFormatPtr, and the width and height of the image are + * returned in *widthPtr and *heightPtr. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +MatchFileFormat(interp, chan, fileName, formatString, imageFormatPtr, + widthPtr, heightPtr) + Tcl_Interp *interp; /* Interpreter to use for reporting errors. */ + Tcl_Channel chan; /* The image file, open for reading. */ + char *fileName; /* The name of the image file. */ + char *formatString; /* User-specified format string, or NULL. */ + Tk_PhotoImageFormat **imageFormatPtr; + /* A pointer to the photo image format + * record is returned here. */ + int *widthPtr, *heightPtr; /* The dimensions of the image are + * returned here. */ +{ + int matched; + Tk_PhotoImageFormat *formatPtr; + + /* + * Scan through the table of file format handlers to find + * one which can handle the image. + */ + + matched = 0; + for (formatPtr = formatList; formatPtr != NULL; + formatPtr = formatPtr->nextPtr) { + if (formatString != NULL) { + if (strncasecmp(formatString, formatPtr->name, + strlen(formatPtr->name)) != 0) { + continue; + } + matched = 1; + if (formatPtr->fileMatchProc == NULL) { + Tcl_AppendResult(interp, "-file option isn't supported for ", + formatString, " images", (char *) NULL); + return TCL_ERROR; + } + } + if (formatPtr->fileMatchProc != NULL) { + (void) Tcl_Seek(chan, 0L, SEEK_SET); + + if ((*formatPtr->fileMatchProc)(chan, fileName, formatString, + widthPtr, heightPtr)) { + if (*widthPtr < 1) { + *widthPtr = 1; + } + if (*heightPtr < 1) { + *heightPtr = 1; + } + break; + } + } + } + + if (formatPtr == NULL) { + if ((formatString != NULL) && !matched) { + Tcl_AppendResult(interp, "image file format \"", formatString, + "\" is not supported", (char *) NULL); + } else { + Tcl_AppendResult(interp, + "couldn't recognize data in image file \"", + fileName, "\"", (char *) NULL); + } + return TCL_ERROR; + } + + *imageFormatPtr = formatPtr; + (void) Tcl_Seek(chan, 0L, SEEK_SET); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * MatchStringFormat -- + * + * This procedure is called to find a photo image file format + * handler which can parse the image data in the given string. + * If a user-specified format string is provided, only handlers + * whose names match a prefix of the format string are tried. + * + * Results: + * A standard TCL return value. If the return value is TCL_OK, a + * pointer to the image format record is returned in + * *imageFormatPtr, and the width and height of the image are + * returned in *widthPtr and *heightPtr. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +MatchStringFormat(interp, string, formatString, imageFormatPtr, + widthPtr, heightPtr) + Tcl_Interp *interp; /* Interpreter to use for reporting errors. */ + char *string; /* String containing the image data. */ + char *formatString; /* User-specified format string, or NULL. */ + Tk_PhotoImageFormat **imageFormatPtr; + /* A pointer to the photo image format + * record is returned here. */ + int *widthPtr, *heightPtr; /* The dimensions of the image are + * returned here. */ +{ + int matched; + Tk_PhotoImageFormat *formatPtr; + + /* + * Scan through the table of file format handlers to find + * one which can handle the image. + */ + + matched = 0; + for (formatPtr = formatList; formatPtr != NULL; + formatPtr = formatPtr->nextPtr) { + if (formatString != NULL) { + if (strncasecmp(formatString, formatPtr->name, + strlen(formatPtr->name)) != 0) { + continue; + } + matched = 1; + if (formatPtr->stringMatchProc == NULL) { + Tcl_AppendResult(interp, "-data option isn't supported for ", + formatString, " images", (char *) NULL); + return TCL_ERROR; + } + } + if ((formatPtr->stringMatchProc != NULL) + && (*formatPtr->stringMatchProc)(string, formatString, + widthPtr, heightPtr)) { + break; + } + } + + if (formatPtr == NULL) { + if ((formatString != NULL) && !matched) { + Tcl_AppendResult(interp, "image format \"", formatString, + "\" is not supported", (char *) NULL); + } else { + Tcl_AppendResult(interp, "couldn't recognize image data", + (char *) NULL); + } + return TCL_ERROR; + } + + *imageFormatPtr = formatPtr; + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FindPhoto -- + * + * This procedure is called to get an opaque handle (actually a + * PhotoMaster *) for a given image, which can be used in + * subsequent calls to Tk_PhotoPutBlock, etc. The `name' + * parameter is the name of the image. + * + * Results: + * The handle for the photo image, or NULL if there is no + * photo image with the name given. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_PhotoHandle +Tk_FindPhoto(interp, imageName) + Tcl_Interp *interp; /* Interpreter (application) in which image + * exists. */ + char *imageName; /* Name of the desired photo image. */ +{ + ClientData clientData; + Tk_ImageType *typePtr; + + clientData = Tk_GetImageMasterData(interp, imageName, &typePtr); + if (typePtr != &tkPhotoImageType) { + return NULL; + } + return (Tk_PhotoHandle) clientData; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_PhotoPutBlock -- + * + * This procedure is called to put image data into a photo image. + * + * Results: + * None. + * + * Side effects: + * The image data is stored. The image may be expanded. + * The Tk image code is informed that the image has changed. + * + *---------------------------------------------------------------------- */ + +void +Tk_PhotoPutBlock(handle, blockPtr, x, y, width, height) + Tk_PhotoHandle handle; /* Opaque handle for the photo image + * to be updated. */ + register Tk_PhotoImageBlock *blockPtr; + /* Pointer to a structure describing the + * pixel data to be copied into the image. */ + int x, y; /* Coordinates of the top-left pixel to + * be updated in the image. */ + int width, height; /* Dimensions of the area of the image + * to be updated. */ +{ + register PhotoMaster *masterPtr; + int xEnd, yEnd; + int greenOffset, blueOffset; + int wLeft, hLeft; + int wCopy, hCopy; + unsigned char *srcPtr, *srcLinePtr; + unsigned char *destPtr, *destLinePtr; + int pitch; + XRectangle rect; + + masterPtr = (PhotoMaster *) handle; + + if ((masterPtr->userWidth != 0) && ((x + width) > masterPtr->userWidth)) { + width = masterPtr->userWidth - x; + } + if ((masterPtr->userHeight != 0) + && ((y + height) > masterPtr->userHeight)) { + height = masterPtr->userHeight - y; + } + if ((width <= 0) || (height <= 0)) + return; + + xEnd = x + width; + yEnd = y + height; + if ((xEnd > masterPtr->width) || (yEnd > masterPtr->height)) { + ImgPhotoSetSize(masterPtr, MAX(xEnd, masterPtr->width), + MAX(yEnd, masterPtr->height)); + } + + if ((y < masterPtr->ditherY) || ((y == masterPtr->ditherY) + && (x < masterPtr->ditherX))) { + /* + * The dithering isn't correct past the start of this block. + */ + masterPtr->ditherX = x; + masterPtr->ditherY = y; + } + + /* + * If this image block could have different red, green and blue + * components, mark it as a color image. + */ + + greenOffset = blockPtr->offset[1] - blockPtr->offset[0]; + blueOffset = blockPtr->offset[2] - blockPtr->offset[0]; + if ((greenOffset != 0) || (blueOffset != 0)) { + masterPtr->flags |= COLOR_IMAGE; + } + + /* + * Copy the data into our local 24-bit/pixel array. + * If we can do it with a single memcpy, we do. + */ + + destLinePtr = masterPtr->pix24 + (y * masterPtr->width + x) * 3; + pitch = masterPtr->width * 3; + + if ((blockPtr->pixelSize == 3) && (greenOffset == 1) && (blueOffset == 2) + && (width <= blockPtr->width) && (height <= blockPtr->height) + && ((height == 1) || ((x == 0) && (width == masterPtr->width) + && (blockPtr->pitch == pitch)))) { + memcpy((VOID *) destLinePtr, + (VOID *) (blockPtr->pixelPtr + blockPtr->offset[0]), + (size_t) (height * width * 3)); + } else { + for (hLeft = height; hLeft > 0;) { + srcLinePtr = blockPtr->pixelPtr + blockPtr->offset[0]; + hCopy = MIN(hLeft, blockPtr->height); + hLeft -= hCopy; + for (; hCopy > 0; --hCopy) { + destPtr = destLinePtr; + for (wLeft = width; wLeft > 0;) { + wCopy = MIN(wLeft, blockPtr->width); + wLeft -= wCopy; + srcPtr = srcLinePtr; + for (; wCopy > 0; --wCopy) { + *destPtr++ = srcPtr[0]; + *destPtr++ = srcPtr[greenOffset]; + *destPtr++ = srcPtr[blueOffset]; + srcPtr += blockPtr->pixelSize; + } + } + srcLinePtr += blockPtr->pitch; + destLinePtr += pitch; + } + } + } + + /* + * Add this new block to the region which specifies which data is valid. + */ + + rect.x = x; + rect.y = y; + rect.width = width; + rect.height = height; + TkUnionRectWithRegion(&rect, masterPtr->validRegion, + masterPtr->validRegion); + + /* + * Update each instance. + */ + + Dither(masterPtr, x, y, width, height); + + /* + * Tell the core image code that this image has changed. + */ + + Tk_ImageChanged(masterPtr->tkMaster, x, y, width, height, masterPtr->width, + masterPtr->height); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_PhotoPutZoomedBlock -- + * + * This procedure is called to put image data into a photo image, + * with possible subsampling and/or zooming of the pixels. + * + * Results: + * None. + * + * Side effects: + * The image data is stored. The image may be expanded. + * The Tk image code is informed that the image has changed. + * + *---------------------------------------------------------------------- + */ + +void +Tk_PhotoPutZoomedBlock(handle, blockPtr, x, y, width, height, zoomX, zoomY, + subsampleX, subsampleY) + Tk_PhotoHandle handle; /* Opaque handle for the photo image + * to be updated. */ + register Tk_PhotoImageBlock *blockPtr; + /* Pointer to a structure describing the + * pixel data to be copied into the image. */ + int x, y; /* Coordinates of the top-left pixel to + * be updated in the image. */ + int width, height; /* Dimensions of the area of the image + * to be updated. */ + int zoomX, zoomY; /* Zoom factors for the X and Y axes. */ + int subsampleX, subsampleY; /* Subsampling factors for the X and Y axes. */ +{ + register PhotoMaster *masterPtr; + int xEnd, yEnd; + int greenOffset, blueOffset; + int wLeft, hLeft; + int wCopy, hCopy; + int blockWid, blockHt; + unsigned char *srcPtr, *srcLinePtr, *srcOrigPtr; + unsigned char *destPtr, *destLinePtr; + int pitch; + int xRepeat, yRepeat; + int blockXSkip, blockYSkip; + XRectangle rect; + + if ((zoomX == 1) && (zoomY == 1) && (subsampleX == 1) + && (subsampleY == 1)) { + Tk_PhotoPutBlock(handle, blockPtr, x, y, width, height); + return; + } + + masterPtr = (PhotoMaster *) handle; + + if ((zoomX <= 0) || (zoomY <= 0)) + return; + if ((masterPtr->userWidth != 0) && ((x + width) > masterPtr->userWidth)) { + width = masterPtr->userWidth - x; + } + if ((masterPtr->userHeight != 0) + && ((y + height) > masterPtr->userHeight)) { + height = masterPtr->userHeight - y; + } + if ((width <= 0) || (height <= 0)) + return; + + xEnd = x + width; + yEnd = y + height; + if ((xEnd > masterPtr->width) || (yEnd > masterPtr->height)) { + int sameSrc = (blockPtr->pixelPtr == masterPtr->pix24); + ImgPhotoSetSize(masterPtr, MAX(xEnd, masterPtr->width), + MAX(yEnd, masterPtr->height)); + if (sameSrc) { + blockPtr->pixelPtr = masterPtr->pix24; + } + } + + if ((y < masterPtr->ditherY) || ((y == masterPtr->ditherY) + && (x < masterPtr->ditherX))) { + /* + * The dithering isn't correct past the start of this block. + */ + + masterPtr->ditherX = x; + masterPtr->ditherY = y; + } + + /* + * If this image block could have different red, green and blue + * components, mark it as a color image. + */ + + greenOffset = blockPtr->offset[1] - blockPtr->offset[0]; + blueOffset = blockPtr->offset[2] - blockPtr->offset[0]; + if ((greenOffset != 0) || (blueOffset != 0)) { + masterPtr->flags |= COLOR_IMAGE; + } + + /* + * Work out what area the pixel data in the block expands to after + * subsampling and zooming. + */ + + blockXSkip = subsampleX * blockPtr->pixelSize; + blockYSkip = subsampleY * blockPtr->pitch; + if (subsampleX > 0) + blockWid = ((blockPtr->width + subsampleX - 1) / subsampleX) * zoomX; + else if (subsampleX == 0) + blockWid = width; + else + blockWid = ((blockPtr->width - subsampleX - 1) / -subsampleX) * zoomX; + if (subsampleY > 0) + blockHt = ((blockPtr->height + subsampleY - 1) / subsampleY) * zoomY; + else if (subsampleY == 0) + blockHt = height; + else + blockHt = ((blockPtr->height - subsampleY - 1) / -subsampleY) * zoomY; + + /* + * Copy the data into our local 24-bit/pixel array. + */ + + destLinePtr = masterPtr->pix24 + (y * masterPtr->width + x) * 3; + srcOrigPtr = blockPtr->pixelPtr + blockPtr->offset[0]; + if (subsampleX < 0) { + srcOrigPtr += (blockPtr->width - 1) * blockPtr->pixelSize; + } + if (subsampleY < 0) { + srcOrigPtr += (blockPtr->height - 1) * blockPtr->pitch; + } + + pitch = masterPtr->width * 3; + for (hLeft = height; hLeft > 0; ) { + hCopy = MIN(hLeft, blockHt); + hLeft -= hCopy; + yRepeat = zoomY; + srcLinePtr = srcOrigPtr; + for (; hCopy > 0; --hCopy) { + destPtr = destLinePtr; + for (wLeft = width; wLeft > 0;) { + wCopy = MIN(wLeft, blockWid); + wLeft -= wCopy; + srcPtr = srcLinePtr; + for (; wCopy > 0; wCopy -= zoomX) { + for (xRepeat = MIN(wCopy, zoomX); xRepeat > 0; xRepeat--) { + *destPtr++ = srcPtr[0]; + *destPtr++ = srcPtr[greenOffset]; + *destPtr++ = srcPtr[blueOffset]; + } + srcPtr += blockXSkip; + } + } + destLinePtr += pitch; + yRepeat--; + if (yRepeat <= 0) { + srcLinePtr += blockYSkip; + yRepeat = zoomY; + } + } + } + + /* + * Add this new block to the region that specifies which data is valid. + */ + + rect.x = x; + rect.y = y; + rect.width = width; + rect.height = height; + TkUnionRectWithRegion(&rect, masterPtr->validRegion, + masterPtr->validRegion); + + /* + * Update each instance. + */ + + Dither(masterPtr, x, y, width, height); + + /* + * Tell the core image code that this image has changed. + */ + + Tk_ImageChanged(masterPtr->tkMaster, x, y, width, height, masterPtr->width, + masterPtr->height); +} + +/* + *---------------------------------------------------------------------- + * + * Dither -- + * + * This procedure is called to update an area of each instance's + * pixmap by dithering the corresponding area of the image master. + * + * Results: + * None. + * + * Side effects: + * The pixmap of each instance of this image gets updated. + * The fields in *masterPtr indicating which area of the image + * is correctly dithered get updated. + * + *---------------------------------------------------------------------- + */ + +static void +Dither(masterPtr, x, y, width, height) + PhotoMaster *masterPtr; /* Image master whose instances are + * to be updated. */ + int x, y; /* Coordinates of the top-left pixel + * in the area to be dithered. */ + int width, height; /* Dimensions of the area to be dithered. */ +{ + PhotoInstance *instancePtr; + + if ((width <= 0) || (height <= 0)) { + return; + } + + for (instancePtr = masterPtr->instancePtr; instancePtr != NULL; + instancePtr = instancePtr->nextPtr) { + DitherInstance(instancePtr, x, y, width, height); + } + + /* + * Work out whether this block will be correctly dithered + * and whether it will extend the correctly dithered region. + */ + + if (((y < masterPtr->ditherY) + || ((y == masterPtr->ditherY) && (x <= masterPtr->ditherX))) + && ((y + height) > (masterPtr->ditherY))) { + + /* + * This block starts inside (or immediately after) the correctly + * dithered region, so the first scan line at least will be right. + * Furthermore this block extends into scanline masterPtr->ditherY. + */ + + if ((x == 0) && (width == masterPtr->width)) { + /* + * We are doing the full width, therefore the dithering + * will be correct to the end. + */ + + masterPtr->ditherX = 0; + masterPtr->ditherY = y + height; + } else { + /* + * We are doing partial scanlines, therefore the + * correctly-dithered region will be extended by + * at most one scan line. + */ + + if (x <= masterPtr->ditherX) { + masterPtr->ditherX = x + width; + if (masterPtr->ditherX >= masterPtr->width) { + masterPtr->ditherX = 0; + masterPtr->ditherY++; + } + } + } + } + +} + +/* + *---------------------------------------------------------------------- + * + * DitherInstance -- + * + * This procedure is called to update an area of an instance's + * pixmap by dithering the corresponding area of the master. + * + * Results: + * None. + * + * Side effects: + * The instance's pixmap gets updated. + * + *---------------------------------------------------------------------- + */ + +static void +DitherInstance(instancePtr, xStart, yStart, width, height) + PhotoInstance *instancePtr; /* The instance to be updated. */ + int xStart, yStart; /* Coordinates of the top-left pixel in the + * block to be dithered. */ + int width, height; /* Dimensions of the block to be dithered. */ +{ + PhotoMaster *masterPtr; + ColorTable *colorPtr; + XImage *imagePtr; + int nLines, bigEndian; + int i, c, x, y; + int xEnd, yEnd; + int bitsPerPixel, bytesPerLine, lineLength; + unsigned char *srcLinePtr, *srcPtr; + schar *errLinePtr, *errPtr; + unsigned char *destBytePtr, *dstLinePtr; + pixel *destLongPtr; + pixel firstBit, word, mask; + int col[3]; + int doDithering = 1; + + colorPtr = instancePtr->colorTablePtr; + masterPtr = instancePtr->masterPtr; + + /* + * Turn dithering off in certain cases where it is not + * needed (TrueColor, DirectColor with many colors). + */ + + if ((colorPtr->visualInfo.class == DirectColor) + || (colorPtr->visualInfo.class == TrueColor)) { + int nRed, nGreen, nBlue, result; + + result = sscanf(colorPtr->id.palette, "%d/%d/%d", &nRed, + &nGreen, &nBlue); + if ((nRed >= 256) + && ((result == 1) || ((nGreen >= 256) && (nBlue >= 256)))) { + doDithering = 0; + } + } + + /* + * First work out how many lines to do at a time, + * then how many bytes we'll need for pixel storage, + * and allocate it. + */ + + nLines = (MAX_PIXELS + width - 1) / width; + if (nLines < 1) { + nLines = 1; + } + if (nLines > height ) { + nLines = height; + } + + imagePtr = instancePtr->imagePtr; + if (imagePtr == NULL) { + return; /* we must be really tight on memory */ + } + bitsPerPixel = imagePtr->bits_per_pixel; + bytesPerLine = ((bitsPerPixel * width + 31) >> 3) & ~3; + imagePtr->width = width; + imagePtr->height = nLines; + imagePtr->bytes_per_line = bytesPerLine; + imagePtr->data = (char *) ckalloc((unsigned) (imagePtr->bytes_per_line * nLines)); + bigEndian = imagePtr->bitmap_bit_order == MSBFirst; + firstBit = bigEndian? (1 << (imagePtr->bitmap_unit - 1)): 1; + + lineLength = masterPtr->width * 3; + srcLinePtr = masterPtr->pix24 + yStart * lineLength + xStart * 3; + errLinePtr = instancePtr->error + yStart * lineLength + xStart * 3; + xEnd = xStart + width; + + /* + * Loop over the image, doing at most nLines lines before + * updating the screen image. + */ + + for (; height > 0; height -= nLines) { + if (nLines > height) { + nLines = height; + } + dstLinePtr = (unsigned char *) imagePtr->data; + yEnd = yStart + nLines; + for (y = yStart; y < yEnd; ++y) { + srcPtr = srcLinePtr; + errPtr = errLinePtr; + destBytePtr = dstLinePtr; + destLongPtr = (pixel *) dstLinePtr; + if (colorPtr->flags & COLOR_WINDOW) { + /* + * Color window. We dither the three components + * independently, using Floyd-Steinberg dithering, + * which propagates errors from the quantization of + * pixels to the pixels below and to the right. + */ + + for (x = xStart; x < xEnd; ++x) { + if (doDithering) { + for (i = 0; i < 3; ++i) { + /* + * Compute the error propagated into this pixel + * for this component. + * If e[x,y] is the array of quantization error + * values, we compute + * 7/16 * e[x-1,y] + 1/16 * e[x-1,y-1] + * + 5/16 * e[x,y-1] + 3/16 * e[x+1,y-1] + * and round it to an integer. + * + * The expression ((c + 2056) >> 4) - 128 + * computes round(c / 16), and works correctly on + * machines without a sign-extending right shift. + */ + + c = (x > 0) ? errPtr[-3] * 7: 0; + if (y > 0) { + if (x > 0) { + c += errPtr[-lineLength-3]; + } + c += errPtr[-lineLength] * 5; + if ((x + 1) < masterPtr->width) { + c += errPtr[-lineLength+3] * 3; + } + } + + /* + * Add the propagated error to the value of this + * component, quantize it, and store the + * quantization error. + */ + + c = ((c + 2056) >> 4) - 128 + *srcPtr++; + if (c < 0) { + c = 0; + } else if (c > 255) { + c = 255; + } + col[i] = colorPtr->colorQuant[i][c]; + *errPtr++ = c - col[i]; + } + } else { + /* + * Output is virtually continuous in this case, + * so don't bother dithering. + */ + + col[0] = *srcPtr++; + col[1] = *srcPtr++; + col[2] = *srcPtr++; + } + + /* + * Translate the quantized component values into + * an X pixel value, and store it in the image. + */ + + i = colorPtr->redValues[col[0]] + + colorPtr->greenValues[col[1]] + + colorPtr->blueValues[col[2]]; + if (colorPtr->flags & MAP_COLORS) { + i = colorPtr->pixelMap[i]; + } + switch (bitsPerPixel) { + case NBBY: + *destBytePtr++ = i; + break; +#ifndef __WIN32__ +/* + * This case is not valid for Windows because the image format is different + * from the pixel format in Win32. Eventually we need to fix the image + * code in Tk to use the Windows native image ordering. This would speed + * up the image code for all of the common sizes. + */ + + case NBBY * sizeof(pixel): + *destLongPtr++ = i; + break; +#endif + default: + XPutPixel(imagePtr, x - xStart, y - yStart, + (unsigned) i); + } + } + + } else if (bitsPerPixel > 1) { + /* + * Multibit monochrome window. The operation here is similar + * to the color window case above, except that there is only + * one component. If the master image is in color, use the + * luminance computed as + * 0.344 * red + 0.5 * green + 0.156 * blue. + */ + + for (x = xStart; x < xEnd; ++x) { + c = (x > 0) ? errPtr[-1] * 7: 0; + if (y > 0) { + if (x > 0) { + c += errPtr[-lineLength-1]; + } + c += errPtr[-lineLength] * 5; + if (x + 1 < masterPtr->width) { + c += errPtr[-lineLength+1] * 3; + } + } + c = ((c + 2056) >> 4) - 128; + + if ((masterPtr->flags & COLOR_IMAGE) == 0) { + c += srcPtr[0]; + } else { + c += (unsigned)(srcPtr[0] * 11 + srcPtr[1] * 16 + + srcPtr[2] * 5 + 16) >> 5; + } + srcPtr += 3; + + if (c < 0) { + c = 0; + } else if (c > 255) { + c = 255; + } + i = colorPtr->colorQuant[0][c]; + *errPtr++ = c - i; + i = colorPtr->redValues[i]; + switch (bitsPerPixel) { + case NBBY: + *destBytePtr++ = i; + break; +#ifndef __WIN32__ +/* + * This case is not valid for Windows because the image format is different + * from the pixel format in Win32. Eventually we need to fix the image + * code in Tk to use the Windows native image ordering. This would speed + * up the image code for all of the common sizes. + */ + + case NBBY * sizeof(pixel): + *destLongPtr++ = i; + break; +#endif + default: + XPutPixel(imagePtr, x - xStart, y - yStart, + (unsigned) i); + } + } + } else { + /* + * 1-bit monochrome window. This is similar to the + * multibit monochrome case above, except that the + * quantization is simpler (we only have black = 0 + * and white = 255), and we produce an XY-Bitmap. + */ + + word = 0; + mask = firstBit; + for (x = xStart; x < xEnd; ++x) { + /* + * If we have accumulated a whole word, store it + * in the image and start a new word. + */ + + if (mask == 0) { + *destLongPtr++ = word; + mask = firstBit; + word = 0; + } + + c = (x > 0) ? errPtr[-1] * 7: 0; + if (y > 0) { + if (x > 0) { + c += errPtr[-lineLength-1]; + } + c += errPtr[-lineLength] * 5; + if (x + 1 < masterPtr->width) { + c += errPtr[-lineLength+1] * 3; + } + } + c = ((c + 2056) >> 4) - 128; + + if ((masterPtr->flags & COLOR_IMAGE) == 0) { + c += srcPtr[0]; + } else { + c += (unsigned)(srcPtr[0] * 11 + srcPtr[1] * 16 + + srcPtr[2] * 5 + 16) >> 5; + } + srcPtr += 3; + + if (c < 0) { + c = 0; + } else if (c > 255) { + c = 255; + } + if (c >= 128) { + word |= mask; + *errPtr++ = c - 255; + } else { + *errPtr++ = c; + } + mask = bigEndian? (mask >> 1): (mask << 1); + } + *destLongPtr = word; + } + srcLinePtr += lineLength; + errLinePtr += lineLength; + dstLinePtr += bytesPerLine; + } + + /* + * Update the pixmap for this instance with the block of + * pixels that we have just computed. + */ + + TkPutImage(colorPtr->pixelMap, colorPtr->numColors, + instancePtr->display, instancePtr->pixels, + instancePtr->gc, imagePtr, 0, 0, xStart, yStart, + (unsigned) width, (unsigned) nLines); + yStart = yEnd; + + } + + ckfree(imagePtr->data); + imagePtr->data = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_PhotoBlank -- + * + * This procedure is called to clear an entire photo image. + * + * Results: + * None. + * + * Side effects: + * The valid region for the image is set to the null region. + * The generic image code is notified that the image has changed. + * + *---------------------------------------------------------------------- + */ + +void +Tk_PhotoBlank(handle) + Tk_PhotoHandle handle; /* Handle for the image to be blanked. */ +{ + PhotoMaster *masterPtr; + PhotoInstance *instancePtr; + + masterPtr = (PhotoMaster *) handle; + masterPtr->ditherX = masterPtr->ditherY = 0; + masterPtr->flags = 0; + + /* + * The image has valid data nowhere. + */ + + if (masterPtr->validRegion != NULL) { + TkDestroyRegion(masterPtr->validRegion); + } + masterPtr->validRegion = TkCreateRegion(); + + /* + * Clear out the 24-bit pixel storage array. + * Clear out the dithering error arrays for each instance. + */ + + memset((VOID *) masterPtr->pix24, 0, + (size_t) (masterPtr->width * masterPtr->height * 3)); + for (instancePtr = masterPtr->instancePtr; instancePtr != NULL; + instancePtr = instancePtr->nextPtr) { + if (instancePtr->error) { + memset((VOID *) instancePtr->error, 0, + (size_t) (masterPtr->width * masterPtr->height + * 3 * sizeof(schar))); + } + } + + /* + * Tell the core image code that this image has changed. + */ + + Tk_ImageChanged(masterPtr->tkMaster, 0, 0, masterPtr->width, + masterPtr->height, masterPtr->width, masterPtr->height); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_PhotoExpand -- + * + * This procedure is called to request that a photo image be + * expanded if necessary to be at least `width' pixels wide and + * `height' pixels high. If the user has declared a definite + * image size (using the -width and -height configuration + * options) then this call has no effect. + * + * Results: + * None. + * + * Side effects: + * The size of the photo image may change; if so the generic + * image code is informed. + * + *---------------------------------------------------------------------- + */ + +void +Tk_PhotoExpand(handle, width, height) + Tk_PhotoHandle handle; /* Handle for the image to be expanded. */ + int width, height; /* Desired minimum dimensions of the image. */ +{ + PhotoMaster *masterPtr; + + masterPtr = (PhotoMaster *) handle; + + if (width <= masterPtr->width) { + width = masterPtr->width; + } + if (height <= masterPtr->height) { + height = masterPtr->height; + } + if ((width != masterPtr->width) || (height != masterPtr->height)) { + ImgPhotoSetSize(masterPtr, MAX(width, masterPtr->width), + MAX(height, masterPtr->height)); + Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0, masterPtr->width, + masterPtr->height); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_PhotoGetSize -- + * + * This procedure is called to obtain the current size of a photo + * image. + * + * Results: + * The image's width and height are returned in *widthp + * and *heightp. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +Tk_PhotoGetSize(handle, widthPtr, heightPtr) + Tk_PhotoHandle handle; /* Handle for the image whose dimensions + * are requested. */ + int *widthPtr, *heightPtr; /* The dimensions of the image are returned + * here. */ +{ + PhotoMaster *masterPtr; + + masterPtr = (PhotoMaster *) handle; + *widthPtr = masterPtr->width; + *heightPtr = masterPtr->height; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_PhotoSetSize -- + * + * This procedure is called to set size of a photo image. + * This call is equivalent to using the -width and -height + * configuration options. + * + * Results: + * None. + * + * Side effects: + * The size of the image may change; if so the generic + * image code is informed. + * + *---------------------------------------------------------------------- + */ + +void +Tk_PhotoSetSize(handle, width, height) + Tk_PhotoHandle handle; /* Handle for the image whose size is to + * be set. */ + int width, height; /* New dimensions for the image. */ +{ + PhotoMaster *masterPtr; + + masterPtr = (PhotoMaster *) handle; + + masterPtr->userWidth = width; + masterPtr->userHeight = height; + ImgPhotoSetSize(masterPtr, ((width > 0) ? width: masterPtr->width), + ((height > 0) ? height: masterPtr->height)); + Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0, + masterPtr->width, masterPtr->height); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_PhotoGetImage -- + * + * This procedure is called to obtain image data from a photo + * image. This procedure fills in the Tk_PhotoImageBlock structure + * pointed to by `blockPtr' with details of the address and + * layout of the image data in memory. + * + * Results: + * TRUE (1) indicating that image data is available, + * for backwards compatibility with the old photo widget. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +Tk_PhotoGetImage(handle, blockPtr) + Tk_PhotoHandle handle; /* Handle for the photo image from which + * image data is desired. */ + Tk_PhotoImageBlock *blockPtr; + /* Information about the address and layout + * of the image data is returned here. */ +{ + PhotoMaster *masterPtr; + + masterPtr = (PhotoMaster *) handle; + blockPtr->pixelPtr = masterPtr->pix24; + blockPtr->width = masterPtr->width; + blockPtr->height = masterPtr->height; + blockPtr->pitch = masterPtr->width * 3; + blockPtr->pixelSize = 3; + blockPtr->offset[0] = 0; + blockPtr->offset[1] = 1; + blockPtr->offset[2] = 2; + return 1; +} diff --git a/generic/tkImgUtil.c b/generic/tkImgUtil.c new file mode 100644 index 0000000..31504b8 --- /dev/null +++ b/generic/tkImgUtil.c @@ -0,0 +1,78 @@ +/* + * tkImgUtil.c -- + * + * This file contains image related utility functions. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkImgUtil.c 1.3 96/02/15 18:53:12 + */ + +#include "tkInt.h" +#include "tkPort.h" +#include "xbytes.h" + + +/* + *---------------------------------------------------------------------- + * + * TkAlignImageData -- + * + * This function takes an image and copies the data into an + * aligned buffer, performing any necessary bit swapping. + * + * Results: + * Returns a newly allocated buffer that should be freed by the + * caller. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +char * +TkAlignImageData(image, alignment, bitOrder) + XImage *image; /* Image to be aligned. */ + int alignment; /* Number of bytes to which the data should + * be aligned (e.g. 2 or 4) */ + int bitOrder; /* Desired bit order: LSBFirst or MSBFirst. */ +{ + long dataWidth; + char *data, *srcPtr, *destPtr; + int i, j; + + if (image->bits_per_pixel != 1) { + panic("TkAlignImageData: Can't handle image depths greater than 1."); + } + + /* + * Compute line width for output data buffer. + */ + + dataWidth = image->bytes_per_line; + if (dataWidth % alignment) { + dataWidth += (alignment - (dataWidth % alignment)); + } + + data = ckalloc(dataWidth * image->height); + + destPtr = data; + for (i = 0; i < image->height; i++) { + srcPtr = &image->data[i * image->bytes_per_line]; + for (j = 0; j < dataWidth; j++) { + if (j >= image->bytes_per_line) { + *destPtr = 0; + } else if (image->bitmap_bit_order != bitOrder) { + *destPtr = xBitReverseTable[(unsigned char)(*(srcPtr++))]; + } else { + *destPtr = *(srcPtr++); + } + destPtr++; + } + } + return data; +} diff --git a/generic/tkInitScript.h b/generic/tkInitScript.h new file mode 100644 index 0000000..e86d16e --- /dev/null +++ b/generic/tkInitScript.h @@ -0,0 +1,73 @@ +/* + * tkInitScript.h -- + * + * This file contains Unix & Windows common init script + * It is not used on the Mac. (the mac init script is in tkMacInit.c) + * + * Copyright (c) 1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkInitScript.h 1.3 97/08/11 19:12:28 + */ + + + +/* + * The following string is the startup script executed in new + * interpreters. It looks in several different directories + * for a script "tk.tcl" that is compatible with this version + * of Tk. The tk.tcl script does all of the real work of + * initialization. + * When called from a safe interpreter, it does not use file exists. + * we don't use pwd either because of safe interpreters. + */ + +static char initScript[] = +"proc tkInit {} {\n\ + global tk_library tk_version tk_patchLevel env errorInfo\n\ + rename tkInit {}\n\ + set errors \"\"\n\ + if {![info exists tk_library]} {\n\ + set tk_library .\n\ + }\n\ + set dirs {}\n\ + if {[info exists env(TK_LIBRARY)]} {\n\ + lappend dirs $env(TK_LIBRARY)\n\ + }\n\ + lappend dirs $tk_library\n\ + lappend dirs [file join [file dirname [info library]] tk$tk_version]\n\ + set parentDir [file dirname [file dirname [info nameofexecutable]]]\n\ + lappend dirs [file join $parentDir tk$tk_version]\n\ + lappend dirs [file join $parentDir lib tk$tk_version]\n\ + lappend dirs [file join $parentDir library]\n\ + set parentParentDir [file dirname $parentDir]\n\ + if [string match {*[ab]*} $tk_patchLevel] {\n\ + set dirSuffix $tk_patchLevel\n\ + } else {\n\ + set dirSuffix $tk_version\n\ + }\n\ + lappend dirs [file join $parentParentDir tk$dirSuffix library]\n\ + lappend dirs [file join $parentParentDir library]\n\ + lappend dirs [file join [file dirname \ + [file dirname [info library]]] tk$dirSuffix library]\n\ + foreach i $dirs {\n\ + set tk_library $i\n\ + set tkfile [file join $i tk.tcl]\n\ + if {[interp issafe] || [file exists $tkfile]} {\n\ + if {![catch {uplevel #0 [list source $tkfile]} msg]} {\n\ + return\n\ + } else {\n\ + append errors \"$tkfile: $msg\n$errorInfo\n\"\n\ + }\n\ + }\n\ + }\n\ + set msg \"Can't find a usable tk.tcl in the following directories: \n\"\n\ + append msg \" $dirs\n\n\"\n\ + append msg \"$errors\n\n\"\n\ + append msg \"This probably means that Tk wasn't installed properly.\n\"\n\ + error $msg\n\ +}\n\ +tkInit"; + diff --git a/generic/tkInt.h b/generic/tkInt.h new file mode 100644 index 0000000..b5dd92d --- /dev/null +++ b/generic/tkInt.h @@ -0,0 +1,990 @@ +/* + * tkInt.h -- + * + * Declarations for things used internally by the Tk + * procedures but not exported outside the module. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkInt.h 1.204 97/10/31 09:55:20 + */ + +#ifndef _TKINT +#define _TKINT + +#ifndef _TK +#include "tk.h" +#endif +#ifndef _TCL +#include "tcl.h" +#endif +#ifndef _TKPORT +#include <tkPort.h> +#endif + +/* + * Opaque type declarations: + */ + +typedef struct TkColormap TkColormap; +typedef struct TkGrabEvent TkGrabEvent; +typedef struct Tk_PostscriptInfo Tk_PostscriptInfo; +typedef struct TkpCursor_ *TkpCursor; +typedef struct TkRegion_ *TkRegion; +typedef struct TkStressedCmap TkStressedCmap; +typedef struct TkBindInfo_ *TkBindInfo; + +/* + * Procedure types. + */ + +typedef int (TkBindEvalProc) _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, XEvent *eventPtr, Tk_Window tkwin, + KeySym keySym)); +typedef void (TkBindFreeProc) _ANSI_ARGS_((ClientData clientData)); +typedef Window (TkClassCreateProc) _ANSI_ARGS_((Tk_Window tkwin, + Window parent, ClientData instanceData)); +typedef void (TkClassGeometryProc) _ANSI_ARGS_((ClientData instanceData)); +typedef void (TkClassModalProc) _ANSI_ARGS_((Tk_Window tkwin, + XEvent *eventPtr)); + + +/* + * Widget class procedures used to implement platform specific widget + * behavior. + */ + +typedef struct TkClassProcs { + TkClassCreateProc *createProc; + /* Procedure to invoke when the + platform-dependent window needs to be + created. */ + TkClassGeometryProc *geometryProc; + /* Procedure to invoke when the geometry of a + window needs to be recalculated as a result + of some change in the system. */ + TkClassModalProc *modalProc; + /* Procedure to invoke after all bindings on a + widget have been triggered in order to + handle a modal loop. */ +} TkClassProcs; + +/* + * One of the following structures is maintained for each cursor in + * use in the system. This structure is used by tkCursor.c and the + * various system specific cursor files. + */ + +typedef struct TkCursor { + Tk_Cursor cursor; /* System specific identifier for cursor. */ + int refCount; /* Number of active uses of cursor. */ + Tcl_HashTable *otherTable; /* Second table (other than idTable) used + * to index this entry. */ + Tcl_HashEntry *hashPtr; /* Entry in otherTable for this structure + * (needed when deleting). */ +} TkCursor; + +/* + * One of the following structures is maintained for each display + * containing a window managed by Tk: + */ + +typedef struct TkDisplay { + Display *display; /* Xlib's info about display. */ + struct TkDisplay *nextPtr; /* Next in list of all displays. */ + char *name; /* Name of display (with any screen + * identifier removed). Malloc-ed. */ + Time lastEventTime; /* Time of last event received for this + * display. */ + + /* + * Information used primarily by tkBind.c: + */ + + int bindInfoStale; /* Non-zero means the variables in this + * part of the structure are potentially + * incorrect and should be recomputed. */ + unsigned int modeModMask; /* Has one bit set to indicate the modifier + * corresponding to "mode shift". If no + * such modifier, than this is zero. */ + unsigned int metaModMask; /* Has one bit set to indicate the modifier + * corresponding to the "Meta" key. If no + * such modifier, then this is zero. */ + unsigned int altModMask; /* Has one bit set to indicate the modifier + * corresponding to the "Meta" key. If no + * such modifier, then this is zero. */ + enum {LU_IGNORE, LU_CAPS, LU_SHIFT} lockUsage; + /* Indicates how to interpret lock modifier. */ + int numModKeyCodes; /* Number of entries in modKeyCodes array + * below. */ + KeyCode *modKeyCodes; /* Pointer to an array giving keycodes for + * all of the keys that have modifiers + * associated with them. Malloc'ed, but + * may be NULL. */ + + /* + * Information used by tkError.c only: + */ + + struct TkErrorHandler *errorPtr; + /* First in list of error handlers + * for this display. NULL means + * no handlers exist at present. */ + int deleteCount; /* Counts # of handlers deleted since + * last time inactive handlers were + * garbage-collected. When this number + * gets big, handlers get cleaned up. */ + + /* + * Information used by tkSend.c only: + */ + + Tk_Window commTkwin; /* Window used for communication + * between interpreters during "send" + * commands. NULL means send info hasn't + * been initialized yet. */ + Atom commProperty; /* X's name for comm property. */ + Atom registryProperty; /* X's name for property containing + * registry of interpreter names. */ + Atom appNameProperty; /* X's name for property used to hold the + * application name on each comm window. */ + + /* + * Information used by tkSelect.c and tkClipboard.c only: + */ + + struct TkSelectionInfo *selectionInfoPtr; + /* First in list of selection information + * records. Each entry contains information + * about the current owner of a particular + * selection on this display. */ + Atom multipleAtom; /* Atom for MULTIPLE. None means + * selection stuff isn't initialized. */ + Atom incrAtom; /* Atom for INCR. */ + Atom targetsAtom; /* Atom for TARGETS. */ + Atom timestampAtom; /* Atom for TIMESTAMP. */ + Atom textAtom; /* Atom for TEXT. */ + Atom compoundTextAtom; /* Atom for COMPOUND_TEXT. */ + Atom applicationAtom; /* Atom for TK_APPLICATION. */ + Atom windowAtom; /* Atom for TK_WINDOW. */ + Atom clipboardAtom; /* Atom for CLIPBOARD. */ + + Tk_Window clipWindow; /* Window used for clipboard ownership and to + * retrieve selections between processes. NULL + * means clipboard info hasn't been + * initialized. */ + int clipboardActive; /* 1 means we currently own the clipboard + * selection, 0 means we don't. */ + struct TkMainInfo *clipboardAppPtr; + /* Last application that owned clipboard. */ + struct TkClipboardTarget *clipTargetPtr; + /* First in list of clipboard type information + * records. Each entry contains information + * about the buffers for a given selection + * target. */ + + /* + * Information used by tkAtom.c only: + */ + + int atomInit; /* 0 means stuff below hasn't been + * initialized yet. */ + Tcl_HashTable nameTable; /* Maps from names to Atom's. */ + Tcl_HashTable atomTable; /* Maps from Atom's back to names. */ + + /* + * Information used by tkCursor.c only: + */ + + Font cursorFont; /* Font to use for standard cursors. + * None means font not loaded yet. */ + + /* + * Information used by tkGrab.c only: + */ + + struct TkWindow *grabWinPtr; + /* Window in which the pointer is currently + * grabbed, or NULL if none. */ + struct TkWindow *eventualGrabWinPtr; + /* Value that grabWinPtr will have once the + * grab event queue (below) has been + * completely emptied. */ + struct TkWindow *buttonWinPtr; + /* Window in which first mouse button was + * pressed while grab was in effect, or NULL + * if no such press in effect. */ + struct TkWindow *serverWinPtr; + /* If no application contains the pointer then + * this is NULL. Otherwise it contains the + * last window for which we've gotten an + * Enter or Leave event from the server (i.e. + * the last window known to have contained + * the pointer). Doesn't reflect events + * that were synthesized in tkGrab.c. */ + TkGrabEvent *firstGrabEventPtr; + /* First in list of enter/leave events + * synthesized by grab code. These events + * must be processed in order before any other + * events are processed. NULL means no such + * events. */ + TkGrabEvent *lastGrabEventPtr; + /* Last in list of synthesized events, or NULL + * if list is empty. */ + int grabFlags; /* Miscellaneous flag values. See definitions + * in tkGrab.c. */ + + /* + * Information used by tkXId.c only: + */ + + struct TkIdStack *idStackPtr; + /* First in list of chunks of free resource + * identifiers, or NULL if there are no free + * resources. */ + XID (*defaultAllocProc) _ANSI_ARGS_((Display *display)); + /* Default resource allocator for display. */ + struct TkIdStack *windowStackPtr; + /* First in list of chunks of window + * identifers that can't be reused right + * now. */ + int idCleanupScheduled; /* 1 means a call to WindowIdCleanup has + * already been scheduled, 0 means it + * hasn't. */ + + /* + * Information maintained by tkWindow.c for use later on by tkXId.c: + */ + + + int destroyCount; /* Number of Tk_DestroyWindow operations + * in progress. */ + unsigned long lastDestroyRequest; + /* Id of most recent XDestroyWindow request; + * can re-use ids in windowStackPtr when + * server has seen this request and event + * queue is empty. */ + + /* + * Information used by tkVisual.c only: + */ + + TkColormap *cmapPtr; /* First in list of all non-default colormaps + * allocated for this display. */ + + /* + * Information used by tkFocus.c only: + */ + + struct TkWindow *implicitWinPtr; + /* If the focus arrived at a toplevel window + * implicitly via an Enter event (rather + * than via a FocusIn event), this points + * to the toplevel window. Otherwise it is + * NULL. */ + struct TkWindow *focusPtr; /* Points to the window on this display that + * should be receiving keyboard events. When + * multiple applications on the display have + * the focus, this will refer to the + * innermost window in the innermost + * application. This information isn't used + * under Unix or Windows, but it's needed on + * the Macintosh. */ + + /* + * Used by tkColor.c only: + */ + + TkStressedCmap *stressPtr; /* First in list of colormaps that have + * filled up, so we have to pick an + * approximate color. */ + + /* + * Used by tkEvent.c only: + */ + + struct TkWindowEvent *delayedMotionPtr; + /* Points to a malloc-ed motion event + * whose processing has been delayed in + * the hopes that another motion event + * will come along right away and we can + * merge the two of them together. NULL + * means that there is no delayed motion + * event. */ + + /* + * Miscellaneous information: + */ + +#ifdef TK_USE_INPUT_METHODS + XIM inputMethod; /* Input method for this display */ +#endif /* TK_USE_INPUT_METHODS */ + Tcl_HashTable winTable; /* Maps from X window ids to TkWindow ptrs. */ + + int refCount; /* Reference count of how many Tk applications + * are using this display. Used to clean up + * the display when we no longer have any + * Tk applications using it. + */ +} TkDisplay; + +/* + * One of the following structures exists for each error handler + * created by a call to Tk_CreateErrorHandler. The structure + * is managed by tkError.c. + */ + +typedef struct TkErrorHandler { + TkDisplay *dispPtr; /* Display to which handler applies. */ + unsigned long firstRequest; /* Only errors with serial numbers + * >= to this are considered. */ + unsigned long lastRequest; /* Only errors with serial numbers + * <= to this are considered. This + * field is filled in when XUnhandle + * is called. -1 means XUnhandle + * hasn't been called yet. */ + int error; /* Consider only errors with this + * error_code (-1 means consider + * all errors). */ + int request; /* Consider only errors with this + * major request code (-1 means + * consider all major codes). */ + int minorCode; /* Consider only errors with this + * minor request code (-1 means + * consider all minor codes). */ + Tk_ErrorProc *errorProc; /* Procedure to invoke when a matching + * error occurs. NULL means just ignore + * errors. */ + ClientData clientData; /* Arbitrary value to pass to + * errorProc. */ + struct TkErrorHandler *nextPtr; + /* Pointer to next older handler for + * this display, or NULL for end of + * list. */ +} TkErrorHandler; + +/* + * One of the following structures exists for each event handler + * created by calling Tk_CreateEventHandler. This information + * is used by tkEvent.c only. + */ + +typedef struct TkEventHandler { + unsigned long mask; /* Events for which to invoke + * proc. */ + Tk_EventProc *proc; /* Procedure to invoke when an event + * in mask occurs. */ + ClientData clientData; /* Argument to pass to proc. */ + struct TkEventHandler *nextPtr; + /* Next in list of handlers + * associated with window (NULL means + * end of list). */ +} TkEventHandler; + +/* + * Tk keeps one of the following data structures for each main + * window (created by a call to Tk_CreateMainWindow). It stores + * information that is shared by all of the windows associated + * with a particular main window. + */ + +typedef struct TkMainInfo { + int refCount; /* Number of windows whose "mainPtr" fields + * point here. When this becomes zero, can + * free up the structure (the reference + * count is zero because windows can get + * deleted in almost any order; the main + * window isn't necessarily the last one + * deleted). */ + struct TkWindow *winPtr; /* Pointer to main window. */ + Tcl_Interp *interp; /* Interpreter associated with application. */ + Tcl_HashTable nameTable; /* Hash table mapping path names to TkWindow + * structs for all windows related to this + * main window. Managed by tkWindow.c. */ + Tk_BindingTable bindingTable; + /* Used in conjunction with "bind" command + * to bind events to Tcl commands. */ + TkBindInfo bindInfo; /* Information used by tkBind.c on a per + * interpreter basis. */ + struct TkFontInfo *fontInfoPtr; + /* Hold named font tables. Used only by + * tkFont.c. */ + + /* + * Information used only by tkFocus.c and tk*Embed.c: + */ + + struct TkToplevelFocusInfo *tlFocusPtr; + /* First in list of records containing focus + * information for each top-level in the + * application. Used only by tkFocus.c. */ + struct TkDisplayFocusInfo *displayFocusPtr; + /* First in list of records containing focus + * information for each display that this + * application has ever used. Used only + * by tkFocus.c. */ + + struct ElArray *optionRootPtr; + /* Top level of option hierarchy for this + * main window. NULL means uninitialized. + * Managed by tkOption.c. */ + Tcl_HashTable imageTable; /* Maps from image names to Tk_ImageMaster + * structures. Managed by tkImage.c. */ + int strictMotif; /* This is linked to the tk_strictMotif + * global variable. */ + struct TkMainInfo *nextPtr; /* Next in list of all main windows managed by + * this process. */ +} TkMainInfo; + +/* + * Tk keeps the following data structure for each of it's builtin + * bitmaps. This structure is only used by tkBitmap.c and other + * platform specific bitmap files. + */ + +typedef struct { + char *source; /* Bits for bitmap. */ + int width, height; /* Dimensions of bitmap. */ + int native; /* 0 means generic (X style) bitmap, + * 1 means native style bitmap. */ +} TkPredefBitmap; + +/* + * Tk keeps one of the following structures for each window. + * Some of the information (like size and location) is a shadow + * of information managed by the X server, and some is special + * information used here, such as event and geometry management + * information. This information is (mostly) managed by tkWindow.c. + * WARNING: the declaration below must be kept consistent with the + * Tk_FakeWin structure in tk.h. If you change one, be sure to + * change the other!! + */ + +typedef struct TkWindow { + + /* + * Structural information: + */ + + Display *display; /* Display containing window. */ + TkDisplay *dispPtr; /* Tk's information about display + * for window. */ + int screenNum; /* Index of screen for window, among all + * those for dispPtr. */ + Visual *visual; /* Visual to use for window. If not default, + * MUST be set before X window is created. */ + int depth; /* Number of bits/pixel. */ + Window window; /* X's id for window. NULL means window + * hasn't actually been created yet, or it's + * been deleted. */ + struct TkWindow *childList; /* First in list of child windows, + * or NULL if no children. List is in + * stacking order, lowest window first.*/ + struct TkWindow *lastChildPtr; + /* Last in list of child windows (highest + * in stacking order), or NULL if no + * children. */ + struct TkWindow *parentPtr; /* Pointer to parent window (logical + * parent, not necessarily X parent). NULL + * means either this is the main window, or + * the window's parent has already been + * deleted. */ + struct TkWindow *nextPtr; /* Next higher sibling (in stacking order) + * in list of children with same parent. NULL + * means end of list. */ + TkMainInfo *mainPtr; /* Information shared by all windows + * associated with a particular main + * window. NULL means this window is + * a rogue that isn't associated with + * any application (at present, this + * only happens for the dummy windows + * used for "send" communication). */ + + /* + * Name and type information for the window: + */ + + char *pathName; /* Path name of window (concatenation + * of all names between this window and + * its top-level ancestor). This is a + * pointer into an entry in + * mainPtr->nameTable. NULL means that + * the window hasn't been completely + * created yet. */ + Tk_Uid nameUid; /* Name of the window within its parent + * (unique within the parent). */ + Tk_Uid classUid; /* Class of the window. NULL means window + * hasn't been given a class yet. */ + + /* + * Geometry and other attributes of window. This information + * may not be updated on the server immediately; stuff that + * hasn't been reflected in the server yet is called "dirty". + * At present, information can be dirty only if the window + * hasn't yet been created. + */ + + XWindowChanges changes; /* Geometry and other info about + * window. */ + unsigned int dirtyChanges; /* Bits indicate fields of "changes" + * that are dirty. */ + XSetWindowAttributes atts; /* Current attributes of window. */ + unsigned long dirtyAtts; /* Bits indicate fields of "atts" + * that are dirty. */ + + unsigned int flags; /* Various flag values: these are all + * defined in tk.h (confusing, but they're + * needed there for some query macros). */ + + /* + * Information kept by the event manager (tkEvent.c): + */ + + TkEventHandler *handlerList;/* First in list of event handlers + * declared for this window, or + * NULL if none. */ +#ifdef TK_USE_INPUT_METHODS + XIC inputContext; /* Input context (for input methods). */ +#endif /* TK_USE_INPUT_METHODS */ + + /* + * Information used for event bindings (see "bind" and "bindtags" + * commands in tkCmds.c): + */ + + ClientData *tagPtr; /* Points to array of tags used for bindings + * on this window. Each tag is a Tk_Uid. + * Malloc'ed. NULL means no tags. */ + int numTags; /* Number of tags at *tagPtr. */ + + /* + * Information used by tkOption.c to manage options for the + * window. + */ + + int optionLevel; /* -1 means no option information is + * currently cached for this window. + * Otherwise this gives the level in + * the option stack at which info is + * cached. */ + /* + * Information used by tkSelect.c to manage the selection. + */ + + struct TkSelHandler *selHandlerList; + /* First in list of handlers for + * returning the selection in various + * forms. */ + + /* + * Information used by tkGeometry.c for geometry management. + */ + + Tk_GeomMgr *geomMgrPtr; /* Information about geometry manager for + * this window. */ + ClientData geomData; /* Argument for geometry manager procedures. */ + int reqWidth, reqHeight; /* Arguments from last call to + * Tk_GeometryRequest, or 0's if + * Tk_GeometryRequest hasn't been + * called. */ + int internalBorderWidth; /* Width of internal border of window + * (0 means no internal border). Geometry + * managers should not normally place children + * on top of the border. */ + + /* + * Information maintained by tkWm.c for window manager communication. + */ + + struct TkWmInfo *wmInfoPtr; /* For top-level windows (and also + * for special Unix menubar and wrapper + * windows), points to structure with + * wm-related info (see tkWm.c). For + * other windows, this is NULL. */ + + /* + * Information used by widget classes. + */ + + TkClassProcs *classProcsPtr; + ClientData instanceData; + + /* + * Platform specific information private to each port. + */ + + struct TkWindowPrivate *privatePtr; +} TkWindow; + +/* + * The following structure is used as a two way map between integers + * and strings, usually to map between an internal C representation + * and the strings used in Tcl. + */ + +typedef struct TkStateMap { + int numKey; /* Integer representation of a value. */ + char *strKey; /* String representation of a value. */ +} TkStateMap; + +/* + * This structure is used by the Mac and Window porting layers as + * the internal representation of a clip_mask in a GC. + */ + +typedef struct TkpClipMask { + int type; /* One of TKP_CLIP_PIXMAP or TKP_CLIP_REGION */ + union { + Pixmap pixmap; + TkRegion region; + } value; +} TkpClipMask; + +#define TKP_CLIP_PIXMAP 0 +#define TKP_CLIP_REGION 1 + +/* + * Pointer to first entry in list of all displays currently known. + */ + +extern TkDisplay *tkDisplayList; + +/* + * Return values from TkGrabState: + */ + +#define TK_GRAB_NONE 0 +#define TK_GRAB_IN_TREE 1 +#define TK_GRAB_ANCESTOR 2 +#define TK_GRAB_EXCLUDED 3 + +/* + * The macro below is used to modify a "char" value (e.g. by casting + * it to an unsigned character) so that it can be used safely with + * macros such as isspace. + */ + +#define UCHAR(c) ((unsigned char) (c)) + +/* + * The following symbol is used in the mode field of FocusIn events + * generated by an embedded application to request the input focus from + * its container. + */ + +#define EMBEDDED_APP_WANTS_FOCUS (NotifyNormal + 20) + +/* + * Miscellaneous variables shared among Tk modules but not exported + * to the outside world: + */ + +extern Tk_Uid tkActiveUid; +extern Tk_ImageType tkBitmapImageType; +extern Tk_Uid tkDisabledUid; +extern Tk_PhotoImageFormat tkImgFmtGIF; +extern void (*tkHandleEventProc) _ANSI_ARGS_(( + XEvent* eventPtr)); +extern Tk_PhotoImageFormat tkImgFmtPPM; +extern TkMainInfo *tkMainWindowList; +extern Tk_Uid tkNormalUid; +extern Tk_ImageType tkPhotoImageType; +extern Tcl_HashTable tkPredefBitmapTable; +extern int tkSendSerial; + +/* + * Internal procedures shared among Tk modules but not exported + * to the outside world: + */ + +EXTERN char * TkAlignImageData _ANSI_ARGS_((XImage *image, + int alignment, int bitOrder)); +EXTERN TkWindow * TkAllocWindow _ANSI_ARGS_((TkDisplay *dispPtr, + int screenNum, TkWindow *parentPtr)); +EXTERN int TkAreaToPolygon _ANSI_ARGS_((double *polyPtr, + int numPoints, double *rectPtr)); +EXTERN void TkBezierPoints _ANSI_ARGS_((double control[], + int numSteps, double *coordPtr)); +EXTERN void TkBezierScreenPoints _ANSI_ARGS_((Tk_Canvas canvas, + double control[], int numSteps, + XPoint *xPointPtr)); +EXTERN void TkBindDeadWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkBindEventProc _ANSI_ARGS_((TkWindow *winPtr, + XEvent *eventPtr)); +EXTERN void TkBindFree _ANSI_ARGS_((TkMainInfo *mainPtr)); +EXTERN void TkBindInit _ANSI_ARGS_((TkMainInfo *mainPtr)); +EXTERN void TkChangeEventWindow _ANSI_ARGS_((XEvent *eventPtr, + TkWindow *winPtr)); +#ifndef TkClipBox +EXTERN void TkClipBox _ANSI_ARGS_((TkRegion rgn, + XRectangle* rect_return)); +#endif +EXTERN int TkClipInit _ANSI_ARGS_((Tcl_Interp *interp, + TkDisplay *dispPtr)); +EXTERN void TkComputeAnchor _ANSI_ARGS_((Tk_Anchor anchor, + Tk_Window tkwin, int padX, int padY, + int innerWidth, int innerHeight, int *xPtr, + int *yPtr)); +EXTERN int TkCopyAndGlobalEval _ANSI_ARGS_((Tcl_Interp *interp, + char *script)); +EXTERN unsigned long TkCreateBindingProcedure _ANSI_ARGS_(( + Tcl_Interp *interp, Tk_BindingTable bindingTable, + ClientData object, char *eventString, + TkBindEvalProc *evalProc, TkBindFreeProc *freeProc, + ClientData clientData)); +EXTERN TkCursor * TkCreateCursorFromData _ANSI_ARGS_((Tk_Window tkwin, + char *source, char *mask, int width, int height, + int xHot, int yHot, XColor fg, XColor bg)); +EXTERN int TkCreateFrame _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv, + int toplevel, char *appName)); +EXTERN Tk_Window TkCreateMainWindow _ANSI_ARGS_((Tcl_Interp *interp, + char *screenName, char *baseName)); +#ifndef TkCreateRegion +EXTERN TkRegion TkCreateRegion _ANSI_ARGS_((void)); +#endif +EXTERN Time TkCurrentTime _ANSI_ARGS_((TkDisplay *dispPtr)); +EXTERN int TkDeadAppCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN void TkDeleteAllImages _ANSI_ARGS_((TkMainInfo *mainPtr)); +#ifndef TkDestroyRegion +EXTERN void TkDestroyRegion _ANSI_ARGS_((TkRegion rgn)); +#endif +EXTERN void TkDoConfigureNotify _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkDrawInsetFocusHighlight _ANSI_ARGS_(( + Tk_Window tkwin, GC gc, int width, + Drawable drawable, int padding)); +EXTERN void TkEventCleanupProc _ANSI_ARGS_(( + ClientData clientData, Tcl_Interp *interp)); +EXTERN void TkEventDeadWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkFillPolygon _ANSI_ARGS_((Tk_Canvas canvas, + double *coordPtr, int numPoints, Display *display, + Drawable drawable, GC gc, GC outlineGC)); +EXTERN int TkFindStateNum _ANSI_ARGS_((Tcl_Interp *interp, + CONST char *option, CONST TkStateMap *mapPtr, + CONST char *strKey)); +EXTERN char * TkFindStateString _ANSI_ARGS_(( + CONST TkStateMap *mapPtr, int numKey)); +EXTERN void TkFocusDeadWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN int TkFocusFilterEvent _ANSI_ARGS_((TkWindow *winPtr, + XEvent *eventPtr)); +EXTERN TkWindow * TkFocusKeyEvent _ANSI_ARGS_((TkWindow *winPtr, + XEvent *eventPtr)); +EXTERN void TkFontPkgInit _ANSI_ARGS_((TkMainInfo *mainPtr)); +EXTERN void TkFontPkgFree _ANSI_ARGS_((TkMainInfo *mainPtr)); +EXTERN void TkFreeBindingTags _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkFreeCursor _ANSI_ARGS_((TkCursor *cursorPtr)); +EXTERN void TkFreeWindowId _ANSI_ARGS_((TkDisplay *dispPtr, + Window w)); +EXTERN void TkGenerateActivateEvents _ANSI_ARGS_(( + TkWindow *winPtr, int active)); +EXTERN char * TkGetBitmapData _ANSI_ARGS_((Tcl_Interp *interp, + char *string, char *fileName, int *widthPtr, + int *heightPtr, int *hotXPtr, int *hotYPtr)); +EXTERN void TkGetButtPoints _ANSI_ARGS_((double p1[], double p2[], + double width, int project, double m1[], + double m2[])); +EXTERN TkCursor * TkGetCursorByName _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Tk_Uid string)); +EXTERN char * TkGetDefaultScreenName _ANSI_ARGS_((Tcl_Interp *interp, + char *screenName)); +EXTERN TkDisplay * TkGetDisplay _ANSI_ARGS_((Display *display)); +EXTERN int TkGetDisplayOf _ANSI_ARGS_((Tcl_Interp *interp, + int objc, Tcl_Obj *CONST objv[], + Tk_Window *tkwinPtr)); +EXTERN TkWindow * TkGetFocusWin _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN int TkGetInterpNames _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin)); +EXTERN int TkGetMiterPoints _ANSI_ARGS_((double p1[], double p2[], + double p3[], double width, double m1[], + double m2[])); +#ifndef TkGetNativeProlog +EXTERN int TkGetNativeProlog _ANSI_ARGS_((Tcl_Interp *interp)); +#endif +EXTERN void TkGetPointerCoords _ANSI_ARGS_((Tk_Window tkwin, + int *xPtr, int *yPtr)); +EXTERN int TkGetProlog _ANSI_ARGS_((Tcl_Interp *interp)); +EXTERN void TkGetServerInfo _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin)); +EXTERN void TkGrabDeadWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN int TkGrabState _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN TkWindow * TkIDToWindow _ANSI_ARGS_((Window window, + TkDisplay *display)); +EXTERN void TkIncludePoint _ANSI_ARGS_((Tk_Item *itemPtr, + double *pointPtr)); +EXTERN void TkInitXId _ANSI_ARGS_((TkDisplay *dispPtr)); +EXTERN void TkInOutEvents _ANSI_ARGS_((XEvent *eventPtr, + TkWindow *sourcePtr, TkWindow *destPtr, + int leaveType, int enterType, + Tcl_QueuePosition position)); +EXTERN void TkInstallFrameMenu _ANSI_ARGS_((Tk_Window tkwin)); +#ifndef TkIntersectRegion +EXTERN void TkIntersectRegion _ANSI_ARGS_((TkRegion sra, + TkRegion srcb, TkRegion dr_return)); +#endif +EXTERN char * TkKeysymToString _ANSI_ARGS_((KeySym keysym)); +EXTERN int TkLineToArea _ANSI_ARGS_((double end1Ptr[2], + double end2Ptr[2], double rectPtr[4])); +EXTERN double TkLineToPoint _ANSI_ARGS_((double end1Ptr[2], + double end2Ptr[2], double pointPtr[2])); +EXTERN int TkListAppend _ANSI_ARGS_((void **headPtrPtr, + void *itemPtr, size_t size)); +EXTERN int TkListDelete _ANSI_ARGS_((void **headPtrPtr, + void *itemPtr, size_t size)); +EXTERN void * TkListFind _ANSI_ARGS_((void *headPtr, void *itemPtr, + size_t size)); +EXTERN int TkMakeBezierCurve _ANSI_ARGS_((Tk_Canvas canvas, + double *pointPtr, int numPoints, int numSteps, + XPoint xPoints[], double dblPoints[])); +EXTERN void TkMakeBezierPostscript _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, double *pointPtr, + int numPoints)); +EXTERN void TkOptionClassChanged _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkOptionDeadWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN int TkOvalToArea _ANSI_ARGS_((double *ovalPtr, + double *rectPtr)); +EXTERN double TkOvalToPoint _ANSI_ARGS_((double ovalPtr[4], + double width, int filled, double pointPtr[2])); +EXTERN int TkpChangeFocus _ANSI_ARGS_((TkWindow *winPtr, + int force)); +EXTERN void TkpCloseDisplay _ANSI_ARGS_((TkDisplay *dispPtr)); +EXTERN void TkpClaimFocus _ANSI_ARGS_((TkWindow *topLevelPtr, + int force)); +#ifndef TkpCmapStressed +EXTERN int TkpCmapStressed _ANSI_ARGS_((Tk_Window tkwin, + Colormap colormap)); +#endif +#ifndef TkpCreateNativeBitmap +EXTERN Pixmap TkpCreateNativeBitmap _ANSI_ARGS_((Display *display, + char * source)); +#endif +#ifndef TkpDefineNativeBitmaps +EXTERN void TkpDefineNativeBitmaps _ANSI_ARGS_((void)); +#endif +EXTERN void TkpDisplayWarning _ANSI_ARGS_((char *msg, + char *title)); +EXTERN void TkpGetAppName _ANSI_ARGS_((Tcl_Interp *interp, + Tcl_DString *name)); +EXTERN unsigned long TkpGetMS _ANSI_ARGS_((void)); +#ifndef TkpGetNativeAppBitmap +EXTERN Pixmap TkpGetNativeAppBitmap _ANSI_ARGS_((Display *display, + char *name, int *width, int *height)); +#endif +EXTERN TkWindow * TkpGetOtherWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN TkWindow * TkpGetWrapperWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN int TkpInit _ANSI_ARGS_((Tcl_Interp *interp)); +EXTERN void TkpInitializeMenuBindings _ANSI_ARGS_(( + Tcl_Interp *interp, Tk_BindingTable bindingTable)); +EXTERN void TkpMakeContainer _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN void TkpMakeMenuWindow _ANSI_ARGS_((Tk_Window tkwin, + int transient)); +EXTERN Window TkpMakeWindow _ANSI_ARGS_((TkWindow *winPtr, + Window parent)); +EXTERN void TkpMenuNotifyToplevelCreate _ANSI_ARGS_(( + Tcl_Interp *, char *menuName)); +EXTERN TkDisplay * TkpOpenDisplay _ANSI_ARGS_((char *display_name)); +EXTERN void TkPointerDeadWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN int TkPointerEvent _ANSI_ARGS_((XEvent *eventPtr, + TkWindow *winPtr)); +EXTERN int TkPolygonToArea _ANSI_ARGS_((double *polyPtr, + int numPoints, double *rectPtr)); +EXTERN double TkPolygonToPoint _ANSI_ARGS_((double *polyPtr, + int numPoints, double *pointPtr)); +EXTERN int TkPositionInTree _ANSI_ARGS_((TkWindow *winPtr, + TkWindow *treePtr)); +#ifndef TkpPrintWindowId +EXTERN void TkpPrintWindowId _ANSI_ARGS_((char *buf, + Window window)); +#endif +EXTERN void TkpRedirectKeyEvent _ANSI_ARGS_((TkWindow *winPtr, + XEvent *eventPtr)); +#ifndef TkpScanWindowId +EXTERN int TkpScanWindowId _ANSI_ARGS_((Tcl_Interp *interp, + char *string, int *idPtr)); +#endif +EXTERN void TkpSetCapture _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkpSetCursor _ANSI_ARGS_((TkpCursor cursor)); +EXTERN void TkpSetMainMenubar _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *menuName)); +#ifndef TkpSync +EXTERN void TkpSync _ANSI_ARGS_((Display *display)); +#endif +EXTERN int TkpTestembedCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +EXTERN int TkpUseWindow _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *string)); +#ifndef TkPutImage +EXTERN void TkPutImage _ANSI_ARGS_((unsigned long *colors, + int ncolors, Display* display, Drawable d, + GC gc, XImage* image, int src_x, int src_y, + int dest_x, int dest_y, unsigned int width, + unsigned int height)); +#endif +EXTERN int TkpWindowWasRecentlyDeleted _ANSI_ARGS_((Window win, + TkDisplay *dispPtr)); +EXTERN void TkpWmSetState _ANSI_ARGS_((TkWindow *winPtr, + int state)); +EXTERN void TkQueueEventForAllChildren _ANSI_ARGS_(( + TkWindow *winPtr, XEvent *eventPtr)); +#ifndef TkRectInRegion +EXTERN int TkRectInRegion _ANSI_ARGS_((TkRegion rgn, + int x, int y, unsigned int width, + unsigned int height)); +#endif +EXTERN int TkScrollWindow _ANSI_ARGS_((Tk_Window tkwin, GC gc, + int x, int y, int width, int height, int dx, + int dy, TkRegion damageRgn)); +EXTERN void TkSelDeadWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkSelEventProc _ANSI_ARGS_((Tk_Window tkwin, + XEvent *eventPtr)); +EXTERN void TkSelInit _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN void TkSelPropProc _ANSI_ARGS_((XEvent *eventPtr)); +EXTERN void TkSetClassProcs _ANSI_ARGS_((Tk_Window tkwin, + TkClassProcs *procs, ClientData instanceData)); +#ifndef TkSetPixmapColormap +EXTERN void TkSetPixmapColormap _ANSI_ARGS_((Pixmap pixmap, + Colormap colormap)); +#endif +#ifndef TkSetRegion +EXTERN void TkSetRegion _ANSI_ARGS_((Display* display, GC gc, + TkRegion rgn)); +#endif +EXTERN void TkSetWindowMenuBar _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *oldMenuName, + char *menuName)); +EXTERN KeySym TkStringToKeysym _ANSI_ARGS_((char *name)); +EXTERN int TkThickPolyLineToArea _ANSI_ARGS_((double *coordPtr, + int numPoints, double width, int capStyle, + int joinStyle, double *rectPtr)); +#ifndef TkUnionRectWithRegion +EXTERN void TkUnionRectWithRegion _ANSI_ARGS_((XRectangle* rect, + TkRegion src, TkRegion dr_return)); +#endif +EXTERN void TkWmAddToColormapWindows _ANSI_ARGS_(( + TkWindow *winPtr)); +EXTERN void TkWmDeadWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN TkWindow * TkWmFocusToplevel _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkWmMapWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkWmNewWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkWmProtocolEventProc _ANSI_ARGS_((TkWindow *winPtr, + XEvent *evenvPtr)); +EXTERN void TkWmRemoveFromColormapWindows _ANSI_ARGS_(( + TkWindow *winPtr)); +EXTERN void TkWmRestackToplevel _ANSI_ARGS_((TkWindow *winPtr, + int aboveBelow, TkWindow *otherPtr)); +EXTERN void TkWmSetClass _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN void TkWmUnmapWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN int TkXFileProc _ANSI_ARGS_((ClientData clientData, + int mask, int flags)); + +/* + * Unsupported commands. + */ +EXTERN int TkUnsupported1Cmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); + +#endif /* _TKINT */ diff --git a/generic/tkListbox.c b/generic/tkListbox.c new file mode 100644 index 0000000..234130d --- /dev/null +++ b/generic/tkListbox.c @@ -0,0 +1,2335 @@ +/* + * tkListbox.c -- + * + * This module implements listbox widgets for the Tk + * toolkit. A listbox displays a collection of strings, + * one per line, and provides scrolling and selection. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkListbox.c 1.120 97/10/29 13:06:59 + */ + +#include "tkPort.h" +#include "default.h" +#include "tkInt.h" + +/* + * One record of the following type is kept for each element + * associated with a listbox widget: + */ + +typedef struct Element { + int textLength; /* # non-NULL characters in text. */ + int lBearing; /* Distance from first character's + * origin to left edge of character. */ + int pixelWidth; /* Total width of element in pixels (including + * left bearing and right bearing). */ + int selected; /* 1 means this item is selected, 0 means + * it isn't. */ + struct Element *nextPtr; /* Next in list of all elements of this + * listbox, or NULL for last element. */ + char text[4]; /* Characters of this element, NULL- + * terminated. The actual space allocated + * here will be as large as needed (> 4, + * most likely). Must be the last field + * of the record. */ +} Element; + +#define ElementSize(stringLength) \ + ((unsigned) (sizeof(Element) - 3 + stringLength)) + +/* + * A data structure of the following type is kept for each listbox + * widget managed by this file: + */ + +typedef struct { + Tk_Window tkwin; /* Window that embodies the listbox. NULL + * means that the window has been destroyed + * but the data structures haven't yet been + * cleaned up.*/ + Display *display; /* Display containing widget. Used, among + * other things, so that resources can be + * freed even after tkwin has gone away. */ + Tcl_Interp *interp; /* Interpreter associated with listbox. */ + Tcl_Command widgetCmd; /* Token for listbox's widget command. */ + int numElements; /* Total number of elements in this listbox. */ + Element *firstPtr; /* First in list of elements (NULL if no + * elements). */ + Element *lastPtr; /* Last in list of elements (NULL if no + * elements). */ + + /* + * Information used when displaying widget: + */ + + Tk_3DBorder normalBorder; /* Used for drawing border around whole + * window, plus used for background. */ + int borderWidth; /* Width of 3-D border around window. */ + int relief; /* 3-D effect: TK_RELIEF_RAISED, etc. */ + int highlightWidth; /* Width in pixels of highlight to draw + * around widget when it has the focus. + * <= 0 means don't draw a highlight. */ + XColor *highlightBgColorPtr; + /* Color for drawing traversal highlight + * area when highlight is off. */ + XColor *highlightColorPtr; /* Color for drawing traversal highlight. */ + int inset; /* Total width of all borders, including + * traversal highlight and 3-D border. + * Indicates how much interior stuff must + * be offset from outside edges to leave + * room for borders. */ + Tk_Font tkfont; /* Information about text font, or NULL. */ + XColor *fgColorPtr; /* Text color in normal mode. */ + GC textGC; /* For drawing normal text. */ + Tk_3DBorder selBorder; /* Borders and backgrounds for selected + * elements. */ + int selBorderWidth; /* Width of border around selection. */ + XColor *selFgColorPtr; /* Foreground color for selected elements. */ + GC selTextGC; /* For drawing selected text. */ + int width; /* Desired width of window, in characters. */ + int height; /* Desired height of window, in lines. */ + int lineHeight; /* Number of pixels allocated for each line + * in display. */ + int topIndex; /* Index of top-most element visible in + * window. */ + int fullLines; /* Number of lines that fit are completely + * visible in window. There may be one + * additional line at the bottom that is + * partially visible. */ + int partialLine; /* 0 means that the window holds exactly + * fullLines lines. 1 means that there is + * one additional line that is partially + * visble. */ + int setGrid; /* Non-zero means pass gridding information + * to window manager. */ + + /* + * Information to support horizontal scrolling: + */ + + int maxWidth; /* Width (in pixels) of widest string in + * listbox. */ + int xScrollUnit; /* Number of pixels in one "unit" for + * horizontal scrolling (window scrolls + * horizontally in increments of this size). + * This is an average character size. */ + int xOffset; /* The left edge of each string in the + * listbox is offset to the left by this + * many pixels (0 means no offset, positive + * means there is an offset). */ + + /* + * Information about what's selected or active, if any. + */ + + Tk_Uid selectMode; /* Selection style: single, browse, multiple, + * or extended. This value isn't used in C + * code, but the Tcl bindings use it. */ + int numSelected; /* Number of elements currently selected. */ + int selectAnchor; /* Fixed end of selection (i.e. element + * at which selection was started.) */ + int exportSelection; /* Non-zero means tie internal listbox + * to X selection. */ + int active; /* Index of "active" element (the one that + * has been selected by keyboard traversal). + * -1 means none. */ + + /* + * Information for scanning: + */ + + int scanMarkX; /* X-position at which scan started (e.g. + * button was pressed here). */ + int scanMarkY; /* Y-position at which scan started (e.g. + * button was pressed here). */ + int scanMarkXOffset; /* Value of "xOffset" field when scan + * started. */ + int scanMarkYIndex; /* Index of line that was at top of window + * when scan started. */ + + /* + * Miscellaneous information: + */ + + Tk_Cursor cursor; /* Current cursor for window, or None. */ + char *takeFocus; /* Value of -takefocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + char *yScrollCmd; /* Command prefix for communicating with + * vertical scrollbar. NULL means no command + * to issue. Malloc'ed. */ + char *xScrollCmd; /* Command prefix for communicating with + * horizontal scrollbar. NULL means no command + * to issue. Malloc'ed. */ + int flags; /* Various flag bits: see below for + * definitions. */ +} Listbox; + +/* + * Flag bits for listboxes: + * + * REDRAW_PENDING: Non-zero means a DoWhenIdle handler + * has already been queued to redraw + * this window. + * UPDATE_V_SCROLLBAR: Non-zero means vertical scrollbar needs + * to be updated. + * UPDATE_H_SCROLLBAR: Non-zero means horizontal scrollbar needs + * to be updated. + * GOT_FOCUS: Non-zero means this widget currently + * has the input focus. + */ + +#define REDRAW_PENDING 1 +#define UPDATE_V_SCROLLBAR 2 +#define UPDATE_H_SCROLLBAR 4 +#define GOT_FOCUS 8 + +/* + * Information used for argv parsing: + */ + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_LISTBOX_BG_COLOR, Tk_Offset(Listbox, normalBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_LISTBOX_BG_MONO, Tk_Offset(Listbox, normalBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_LISTBOX_BORDER_WIDTH, Tk_Offset(Listbox, borderWidth), 0}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_LISTBOX_CURSOR, Tk_Offset(Listbox, cursor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-exportselection", "exportSelection", + "ExportSelection", DEF_LISTBOX_EXPORT_SELECTION, + Tk_Offset(Listbox, exportSelection), 0}, + {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_FONT, "-font", "font", "Font", + DEF_LISTBOX_FONT, Tk_Offset(Listbox, tkfont), 0}, + {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground", + DEF_LISTBOX_FG, Tk_Offset(Listbox, fgColorPtr), 0}, + {TK_CONFIG_INT, "-height", "height", "Height", + DEF_LISTBOX_HEIGHT, Tk_Offset(Listbox, height), 0}, + {TK_CONFIG_COLOR, "-highlightbackground", "highlightBackground", + "HighlightBackground", DEF_LISTBOX_HIGHLIGHT_BG, + Tk_Offset(Listbox, highlightBgColorPtr), 0}, + {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor", + DEF_LISTBOX_HIGHLIGHT, Tk_Offset(Listbox, highlightColorPtr), 0}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", + DEF_LISTBOX_HIGHLIGHT_WIDTH, Tk_Offset(Listbox, highlightWidth), 0}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_LISTBOX_RELIEF, Tk_Offset(Listbox, relief), 0}, + {TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Foreground", + DEF_LISTBOX_SELECT_COLOR, Tk_Offset(Listbox, selBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Foreground", + DEF_LISTBOX_SELECT_MONO, Tk_Offset(Listbox, selBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_PIXELS, "-selectborderwidth", "selectBorderWidth", "BorderWidth", + DEF_LISTBOX_SELECT_BD, Tk_Offset(Listbox, selBorderWidth), 0}, + {TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Background", + DEF_LISTBOX_SELECT_FG_COLOR, Tk_Offset(Listbox, selFgColorPtr), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Background", + DEF_LISTBOX_SELECT_FG_MONO, Tk_Offset(Listbox, selFgColorPtr), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_UID, "-selectmode", "selectMode", "SelectMode", + DEF_LISTBOX_SELECT_MODE, Tk_Offset(Listbox, selectMode), 0}, + {TK_CONFIG_BOOLEAN, "-setgrid", "setGrid", "SetGrid", + DEF_LISTBOX_SET_GRID, Tk_Offset(Listbox, setGrid), 0}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_LISTBOX_TAKE_FOCUS, Tk_Offset(Listbox, takeFocus), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_INT, "-width", "width", "Width", + DEF_LISTBOX_WIDTH, Tk_Offset(Listbox, width), 0}, + {TK_CONFIG_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand", + DEF_LISTBOX_SCROLL_COMMAND, Tk_Offset(Listbox, xScrollCmd), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-yscrollcommand", "yScrollCommand", "ScrollCommand", + DEF_LISTBOX_SCROLL_COMMAND, Tk_Offset(Listbox, yScrollCmd), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void ChangeListboxOffset _ANSI_ARGS_((Listbox *listPtr, + int offset)); +static void ChangeListboxView _ANSI_ARGS_((Listbox *listPtr, + int index)); +static int ConfigureListbox _ANSI_ARGS_((Tcl_Interp *interp, + Listbox *listPtr, int argc, char **argv, + int flags)); +static void DeleteEls _ANSI_ARGS_((Listbox *listPtr, int first, + int last)); +static void DestroyListbox _ANSI_ARGS_((char *memPtr)); +static void DisplayListbox _ANSI_ARGS_((ClientData clientData)); +static int GetListboxIndex _ANSI_ARGS_((Tcl_Interp *interp, + Listbox *listPtr, char *string, int endIsSize, + int *indexPtr)); +static void InsertEls _ANSI_ARGS_((Listbox *listPtr, int index, + int argc, char **argv)); +static void ListboxCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static void ListboxComputeGeometry _ANSI_ARGS_((Listbox *listPtr, + int fontChanged, int maxIsStale, int updateGrid)); +static void ListboxEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int ListboxFetchSelection _ANSI_ARGS_(( + ClientData clientData, int offset, char *buffer, + int maxBytes)); +static void ListboxLostSelection _ANSI_ARGS_(( + ClientData clientData)); +static void ListboxRedrawRange _ANSI_ARGS_((Listbox *listPtr, + int first, int last)); +static void ListboxScanTo _ANSI_ARGS_((Listbox *listPtr, + int x, int y)); +static void ListboxSelect _ANSI_ARGS_((Listbox *listPtr, + int first, int last, int select)); +static void ListboxUpdateHScrollbar _ANSI_ARGS_((Listbox *listPtr)); +static void ListboxUpdateVScrollbar _ANSI_ARGS_((Listbox *listPtr)); +static int ListboxWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void ListboxWorldChanged _ANSI_ARGS_(( + ClientData instanceData)); +static int NearestListboxElement _ANSI_ARGS_((Listbox *listPtr, + int y)); + +/* + * The structure below defines button class behavior by means of procedures + * that can be invoked from generic window code. + */ + +static TkClassProcs listboxClass = { + NULL, /* createProc. */ + ListboxWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + + +/* + *-------------------------------------------------------------- + * + * Tk_ListboxCmd -- + * + * This procedure is invoked to process the "listbox" Tcl + * command. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_ListboxCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register Listbox *listPtr; + Tk_Window new; + Tk_Window tkwin = (Tk_Window) clientData; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *) NULL); + if (new == NULL) { + return TCL_ERROR; + } + + /* + * Initialize the fields of the structure that won't be initialized + * by ConfigureListbox, or that ConfigureListbox requires to be + * initialized already (e.g. resource pointers). + */ + + listPtr = (Listbox *) ckalloc(sizeof(Listbox)); + listPtr->tkwin = new; + listPtr->display = Tk_Display(new); + listPtr->interp = interp; + listPtr->widgetCmd = Tcl_CreateCommand(interp, + Tk_PathName(listPtr->tkwin), ListboxWidgetCmd, + (ClientData) listPtr, ListboxCmdDeletedProc); + listPtr->numElements = 0; + listPtr->firstPtr = NULL; + listPtr->lastPtr = NULL; + listPtr->normalBorder = NULL; + listPtr->borderWidth = 0; + listPtr->relief = TK_RELIEF_RAISED; + listPtr->highlightWidth = 0; + listPtr->highlightBgColorPtr = NULL; + listPtr->highlightColorPtr = NULL; + listPtr->inset = 0; + listPtr->tkfont = NULL; + listPtr->fgColorPtr = NULL; + listPtr->textGC = None; + listPtr->selBorder = NULL; + listPtr->selBorderWidth = 0; + listPtr->selFgColorPtr = None; + listPtr->selTextGC = None; + listPtr->width = 0; + listPtr->height = 0; + listPtr->lineHeight = 0; + listPtr->topIndex = 0; + listPtr->fullLines = 1; + listPtr->partialLine = 0; + listPtr->setGrid = 0; + listPtr->maxWidth = 0; + listPtr->xScrollUnit = 1; + listPtr->xOffset = 0; + listPtr->selectMode = NULL; + listPtr->numSelected = 0; + listPtr->selectAnchor = 0; + listPtr->exportSelection = 1; + listPtr->active = 0; + listPtr->scanMarkX = 0; + listPtr->scanMarkY = 0; + listPtr->scanMarkXOffset = 0; + listPtr->scanMarkYIndex = 0; + listPtr->cursor = None; + listPtr->takeFocus = NULL; + listPtr->xScrollCmd = NULL; + listPtr->yScrollCmd = NULL; + listPtr->flags = 0; + + Tk_SetClass(listPtr->tkwin, "Listbox"); + TkSetClassProcs(listPtr->tkwin, &listboxClass, (ClientData) listPtr); + Tk_CreateEventHandler(listPtr->tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + ListboxEventProc, (ClientData) listPtr); + Tk_CreateSelHandler(listPtr->tkwin, XA_PRIMARY, XA_STRING, + ListboxFetchSelection, (ClientData) listPtr, XA_STRING); + if (ConfigureListbox(interp, listPtr, argc-2, argv+2, 0) != TCL_OK) { + goto error; + } + + interp->result = Tk_PathName(listPtr->tkwin); + return TCL_OK; + + error: + Tk_DestroyWindow(listPtr->tkwin); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * ListboxWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a widget managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +ListboxWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about listbox widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register Listbox *listPtr = (Listbox *) clientData; + int result = TCL_OK; + size_t length; + int c; + Tk_FontMetrics fm; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) listPtr); + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'a') && (strncmp(argv[1], "activate", length) == 0)) { + int index; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " activate index\"", + (char *) NULL); + goto error; + } + ListboxRedrawRange(listPtr, listPtr->active, listPtr->active); + if (GetListboxIndex(interp, listPtr, argv[2], 0, &index) != TCL_OK) { + goto error; + } + if (index >= listPtr->numElements) { + index = listPtr->numElements-1; + } + if (index < 0) { + index = 0; + } + listPtr->active = index; + ListboxRedrawRange(listPtr, listPtr->active, listPtr->active); + } else if ((c == 'b') && (strncmp(argv[1], "bbox", length) == 0)) { + int index, x, y, i; + Element *elPtr; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " bbox index\"", (char *) NULL); + goto error; + } + if (GetListboxIndex(interp, listPtr, argv[2], 0, &index) != TCL_OK) { + goto error; + } + if ((index >= listPtr->numElements) || (index < 0)) { + goto done; + } + for (i = 0, elPtr = listPtr->firstPtr; i < index; + i++, elPtr = elPtr->nextPtr) { + /* Empty loop body. */ + } + if ((index >= listPtr->topIndex) && (index < listPtr->numElements) + && (index < (listPtr->topIndex + listPtr->fullLines + + listPtr->partialLine))) { + x = listPtr->inset + listPtr->selBorderWidth - listPtr->xOffset; + y = ((index - listPtr->topIndex)*listPtr->lineHeight) + + listPtr->inset + listPtr->selBorderWidth; + Tk_GetFontMetrics(listPtr->tkfont, &fm); + sprintf(interp->result, "%d %d %d %d", x, y, elPtr->pixelWidth, + fm.linespace); + } + } else if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + goto error; + } + result = Tk_ConfigureValue(interp, listPtr->tkwin, configSpecs, + (char *) listPtr, argv[2], 0); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 2)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, listPtr->tkwin, configSpecs, + (char *) listPtr, (char *) NULL, 0); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, listPtr->tkwin, configSpecs, + (char *) listPtr, argv[2], 0); + } else { + result = ConfigureListbox(interp, listPtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else if ((c == 'c') && (strncmp(argv[1], "curselection", length) == 0) + && (length >= 2)) { + int i, count; + char index[20]; + Element *elPtr; + + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " curselection\"", + (char *) NULL); + goto error; + } + count = 0; + for (i = 0, elPtr = listPtr->firstPtr; elPtr != NULL; + i++, elPtr = elPtr->nextPtr) { + if (elPtr->selected) { + sprintf(index, "%d", i); + Tcl_AppendElement(interp, index); + count++; + } + } + if (count != listPtr->numSelected) { + panic("ListboxWidgetCmd: selection count incorrect"); + } + } else if ((c == 'd') && (strncmp(argv[1], "delete", length) == 0)) { + int first, last; + + if ((argc < 3) || (argc > 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " delete firstIndex ?lastIndex?\"", + (char *) NULL); + goto error; + } + if (GetListboxIndex(interp, listPtr, argv[2], 0, &first) != TCL_OK) { + goto error; + } + if (first < listPtr->numElements) { + if (argc == 3) { + last = first; + } else { + if (GetListboxIndex(interp, listPtr, argv[3], 0, + &last) != TCL_OK) { + goto error; + } + if (last >= listPtr->numElements) { + last = listPtr->numElements-1; + } + } + DeleteEls(listPtr, first, last); + } + } else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) { + int first, last, i; + Element *elPtr; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " get first ?last?\"", (char *) NULL); + goto error; + } + if (GetListboxIndex(interp, listPtr, argv[2], 0, &first) != TCL_OK) { + goto error; + } + if ((argc == 4) && (GetListboxIndex(interp, listPtr, argv[3], + 0, &last) != TCL_OK)) { + goto error; + } + if (first >= listPtr->numElements) { + goto done; + } + if (last >= listPtr->numElements) { + last = listPtr->numElements-1; + } + + for (elPtr = listPtr->firstPtr, i = 0; i < first; + i++, elPtr = elPtr->nextPtr) { + /* Empty loop body. */ + } + if (elPtr != NULL) { + if (argc == 3) { + if (first >= 0) { + interp->result = elPtr->text; + } + } else { + for ( ; i <= last; i++, elPtr = elPtr->nextPtr) { + Tcl_AppendElement(interp, elPtr->text); + } + } + } + } else if ((c == 'i') && (strncmp(argv[1], "index", length) == 0) + && (length >= 3)) { + int index; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " index index\"", + (char *) NULL); + goto error; + } + if (GetListboxIndex(interp, listPtr, argv[2], 1, &index) + != TCL_OK) { + goto error; + } + sprintf(interp->result, "%d", index); + } else if ((c == 'i') && (strncmp(argv[1], "insert", length) == 0) + && (length >= 3)) { + int index; + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " insert index ?element element ...?\"", + (char *) NULL); + goto error; + } + if (GetListboxIndex(interp, listPtr, argv[2], 1, &index) + != TCL_OK) { + goto error; + } + InsertEls(listPtr, index, argc-3, argv+3); + } else if ((c == 'n') && (strncmp(argv[1], "nearest", length) == 0)) { + int index, y; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " nearest y\"", (char *) NULL); + goto error; + } + if (Tcl_GetInt(interp, argv[2], &y) != TCL_OK) { + goto error; + } + index = NearestListboxElement(listPtr, y); + sprintf(interp->result, "%d", index); + } else if ((c == 's') && (length >= 2) + && (strncmp(argv[1], "scan", length) == 0)) { + int x, y; + + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " scan mark|dragto x y\"", (char *) NULL); + goto error; + } + if ((Tcl_GetInt(interp, argv[3], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &y) != TCL_OK)) { + goto error; + } + if ((argv[2][0] == 'm') + && (strncmp(argv[2], "mark", strlen(argv[2])) == 0)) { + listPtr->scanMarkX = x; + listPtr->scanMarkY = y; + listPtr->scanMarkXOffset = listPtr->xOffset; + listPtr->scanMarkYIndex = listPtr->topIndex; + } else if ((argv[2][0] == 'd') + && (strncmp(argv[2], "dragto", strlen(argv[2])) == 0)) { + ListboxScanTo(listPtr, x, y); + } else { + Tcl_AppendResult(interp, "bad scan option \"", argv[2], + "\": must be mark or dragto", (char *) NULL); + goto error; + } + } else if ((c == 's') && (strncmp(argv[1], "see", length) == 0) + && (length >= 3)) { + int index, diff; + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " see index\"", + (char *) NULL); + goto error; + } + if (GetListboxIndex(interp, listPtr, argv[2], 0, &index) != TCL_OK) { + goto error; + } + if (index >= listPtr->numElements) { + index = listPtr->numElements-1; + } + if (index < 0) { + index = 0; + } + diff = listPtr->topIndex-index; + if (diff > 0) { + if (diff <= (listPtr->fullLines/3)) { + ChangeListboxView(listPtr, index); + } else { + ChangeListboxView(listPtr, index - (listPtr->fullLines-1)/2); + } + } else { + diff = index - (listPtr->topIndex + listPtr->fullLines - 1); + if (diff > 0) { + if (diff <= (listPtr->fullLines/3)) { + ChangeListboxView(listPtr, listPtr->topIndex + diff); + } else { + ChangeListboxView(listPtr, + index - (listPtr->fullLines-1)/2); + } + } + } + } else if ((c == 's') && (length >= 3) + && (strncmp(argv[1], "selection", length) == 0)) { + int first, last; + + if ((argc != 4) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " selection option index ?index?\"", + (char *) NULL); + goto error; + } + if (GetListboxIndex(interp, listPtr, argv[3], 0, &first) != TCL_OK) { + goto error; + } + if (argc == 5) { + if (GetListboxIndex(interp, listPtr, argv[4], 0, &last) != TCL_OK) { + goto error; + } + } else { + last = first; + } + length = strlen(argv[2]); + c = argv[2][0]; + if ((c == 'a') && (strncmp(argv[2], "anchor", length) == 0)) { + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " selection anchor index\"", (char *) NULL); + goto error; + } + if (first >= listPtr->numElements) { + first = listPtr->numElements-1; + } + if (first < 0) { + first = 0; + } + listPtr->selectAnchor = first; + } else if ((c == 'c') && (strncmp(argv[2], "clear", length) == 0)) { + ListboxSelect(listPtr, first, last, 0); + } else if ((c == 'i') && (strncmp(argv[2], "includes", length) == 0)) { + int i; + Element *elPtr; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " selection includes index\"", (char *) NULL); + goto error; + } + if ((first < 0) || (first >= listPtr->numElements)) { + interp->result = "0"; + goto done; + } + for (elPtr = listPtr->firstPtr, i = 0; i < first; + i++, elPtr = elPtr->nextPtr) { + /* Empty loop body. */ + } + if (elPtr->selected) { + interp->result = "1"; + } else { + interp->result = "0"; + } + } else if ((c == 's') && (strncmp(argv[2], "set", length) == 0)) { + ListboxSelect(listPtr, first, last, 1); + } else { + Tcl_AppendResult(interp, "bad selection option \"", argv[2], + "\": must be anchor, clear, includes, or set", + (char *) NULL); + goto error; + } + } else if ((c == 's') && (length >= 2) + && (strncmp(argv[1], "size", length) == 0)) { + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " size\"", (char *) NULL); + goto error; + } + sprintf(interp->result, "%d", listPtr->numElements); + } else if ((c == 'x') && (strncmp(argv[1], "xview", length) == 0)) { + int index, count, type, windowWidth, windowUnits; + int offset = 0; /* Initialized to stop gcc warnings. */ + double fraction, fraction2; + + windowWidth = Tk_Width(listPtr->tkwin) + - 2*(listPtr->inset + listPtr->selBorderWidth); + if (argc == 2) { + if (listPtr->maxWidth == 0) { + interp->result = "0 1"; + } else { + fraction = listPtr->xOffset/((double) listPtr->maxWidth); + fraction2 = (listPtr->xOffset + windowWidth) + /((double) listPtr->maxWidth); + if (fraction2 > 1.0) { + fraction2 = 1.0; + } + sprintf(interp->result, "%g %g", fraction, fraction2); + } + } else if (argc == 3) { + if (Tcl_GetInt(interp, argv[2], &index) != TCL_OK) { + goto error; + } + ChangeListboxOffset(listPtr, index*listPtr->xScrollUnit); + } else { + type = Tk_GetScrollInfo(interp, argc, argv, &fraction, &count); + switch (type) { + case TK_SCROLL_ERROR: + goto error; + case TK_SCROLL_MOVETO: + offset = (int) (fraction*listPtr->maxWidth + 0.5); + break; + case TK_SCROLL_PAGES: + windowUnits = windowWidth/listPtr->xScrollUnit; + if (windowUnits > 2) { + offset = listPtr->xOffset + + count*listPtr->xScrollUnit*(windowUnits-2); + } else { + offset = listPtr->xOffset + count*listPtr->xScrollUnit; + } + break; + case TK_SCROLL_UNITS: + offset = listPtr->xOffset + count*listPtr->xScrollUnit; + break; + } + ChangeListboxOffset(listPtr, offset); + } + } else if ((c == 'y') && (strncmp(argv[1], "yview", length) == 0)) { + int index, count, type; + double fraction, fraction2; + + if (argc == 2) { + if (listPtr->numElements == 0) { + interp->result = "0 1"; + } else { + fraction = listPtr->topIndex/((double) listPtr->numElements); + fraction2 = (listPtr->topIndex+listPtr->fullLines) + /((double) listPtr->numElements); + if (fraction2 > 1.0) { + fraction2 = 1.0; + } + sprintf(interp->result, "%g %g", fraction, fraction2); + } + } else if (argc == 3) { + if (GetListboxIndex(interp, listPtr, argv[2], 0, &index) + != TCL_OK) { + goto error; + } + ChangeListboxView(listPtr, index); + } else { + type = Tk_GetScrollInfo(interp, argc, argv, &fraction, &count); + switch (type) { + case TK_SCROLL_ERROR: + goto error; + case TK_SCROLL_MOVETO: + index = (int) (listPtr->numElements*fraction + 0.5); + break; + case TK_SCROLL_PAGES: + if (listPtr->fullLines > 2) { + index = listPtr->topIndex + + count*(listPtr->fullLines-2); + } else { + index = listPtr->topIndex + count; + } + break; + case TK_SCROLL_UNITS: + index = listPtr->topIndex + count; + break; + } + ChangeListboxView(listPtr, index); + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be activate, bbox, cget, configure, ", + "curselection, delete, get, index, insert, nearest, ", + "scan, see, selection, size, ", + "xview, or yview", (char *) NULL); + goto error; + } + done: + Tcl_Release((ClientData) listPtr); + return result; + + error: + Tcl_Release((ClientData) listPtr); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyListbox -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a listbox at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the listbox is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyListbox(memPtr) + char *memPtr; /* Info about listbox widget. */ +{ + register Listbox *listPtr = (Listbox *) memPtr; + register Element *elPtr, *nextPtr; + + /* + * Free up all of the list elements. + */ + + for (elPtr = listPtr->firstPtr; elPtr != NULL; ) { + nextPtr = elPtr->nextPtr; + ckfree((char *) elPtr); + elPtr = nextPtr; + } + + /* + * Free up all the stuff that requires special handling, then + * let Tk_FreeOptions handle all the standard option-related + * stuff. + */ + + if (listPtr->textGC != None) { + Tk_FreeGC(listPtr->display, listPtr->textGC); + } + if (listPtr->selTextGC != None) { + Tk_FreeGC(listPtr->display, listPtr->selTextGC); + } + Tk_FreeOptions(configSpecs, (char *) listPtr, listPtr->display, 0); + ckfree((char *) listPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureListbox -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or reconfigure) + * a listbox widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as colors, border width, + * etc. get set for listPtr; old resources get freed, + * if there were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureListbox(interp, listPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + register Listbox *listPtr; /* Information about widget; may or may + * not already have values for some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + int oldExport; + + oldExport = listPtr->exportSelection; + if (Tk_ConfigureWidget(interp, listPtr->tkwin, configSpecs, + argc, argv, (char *) listPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few options need special processing, such as setting the + * background from a 3-D border. + */ + + Tk_SetBackgroundFromBorder(listPtr->tkwin, listPtr->normalBorder); + + if (listPtr->highlightWidth < 0) { + listPtr->highlightWidth = 0; + } + listPtr->inset = listPtr->highlightWidth + listPtr->borderWidth; + + /* + * Claim the selection if we've suddenly started exporting it and + * there is a selection to export. + */ + + if (listPtr->exportSelection && !oldExport + && (listPtr->numSelected != 0)) { + Tk_OwnSelection(listPtr->tkwin, XA_PRIMARY, ListboxLostSelection, + (ClientData) listPtr); + } + + ListboxWorldChanged((ClientData) listPtr); + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * ListboxWorldChanged -- + * + * This procedure is called when the world has changed in some + * way and the widget needs to recompute all its graphics contexts + * and determine its new geometry. + * + * Results: + * None. + * + * Side effects: + * Listbox will be relayed out and redisplayed. + * + *--------------------------------------------------------------------------- + */ + +static void +ListboxWorldChanged(instanceData) + ClientData instanceData; /* Information about widget. */ +{ + XGCValues gcValues; + GC gc; + unsigned long mask; + Listbox *listPtr; + + listPtr = (Listbox *) instanceData; + + gcValues.foreground = listPtr->fgColorPtr->pixel; + gcValues.font = Tk_FontId(listPtr->tkfont); + gcValues.graphics_exposures = False; + mask = GCForeground | GCFont | GCGraphicsExposures; + gc = Tk_GetGC(listPtr->tkwin, mask, &gcValues); + if (listPtr->textGC != None) { + Tk_FreeGC(listPtr->display, listPtr->textGC); + } + listPtr->textGC = gc; + + gcValues.foreground = listPtr->selFgColorPtr->pixel; + gcValues.font = Tk_FontId(listPtr->tkfont); + mask = GCForeground | GCFont; + gc = Tk_GetGC(listPtr->tkwin, mask, &gcValues); + if (listPtr->selTextGC != None) { + Tk_FreeGC(listPtr->display, listPtr->selTextGC); + } + listPtr->selTextGC = gc; + + /* + * Register the desired geometry for the window and arrange for + * the window to be redisplayed. + */ + + ListboxComputeGeometry(listPtr, 1, 1, 1); + listPtr->flags |= UPDATE_V_SCROLLBAR|UPDATE_H_SCROLLBAR; + ListboxRedrawRange(listPtr, 0, listPtr->numElements-1); +} + +/* + *-------------------------------------------------------------- + * + * DisplayListbox -- + * + * This procedure redraws the contents of a listbox window. + * + * Results: + * None. + * + * Side effects: + * Information appears on the screen. + * + *-------------------------------------------------------------- + */ + +static void +DisplayListbox(clientData) + ClientData clientData; /* Information about window. */ +{ + register Listbox *listPtr = (Listbox *) clientData; + register Tk_Window tkwin = listPtr->tkwin; + register Element *elPtr; + GC gc; + int i, limit, x, y, width, prevSelected; + Tk_FontMetrics fm; + int left, right; /* Non-zero values here indicate + * that the left or right edge of + * the listbox is off-screen. */ + Pixmap pixmap; + + listPtr->flags &= ~REDRAW_PENDING; + if (listPtr->flags & UPDATE_V_SCROLLBAR) { + ListboxUpdateVScrollbar(listPtr); + } + if (listPtr->flags & UPDATE_H_SCROLLBAR) { + ListboxUpdateHScrollbar(listPtr); + } + listPtr->flags &= ~(REDRAW_PENDING|UPDATE_V_SCROLLBAR|UPDATE_H_SCROLLBAR); + if ((listPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + return; + } + + /* + * Redrawing is done in a temporary pixmap that is allocated + * here and freed at the end of the procedure. All drawing is + * done to the pixmap, and the pixmap is copied to the screen + * at the end of the procedure. This provides the smoothest + * possible visual effects (no flashing on the screen). + */ + + pixmap = Tk_GetPixmap(listPtr->display, Tk_WindowId(tkwin), + Tk_Width(tkwin), Tk_Height(tkwin), Tk_Depth(tkwin)); + Tk_Fill3DRectangle(tkwin, pixmap, listPtr->normalBorder, 0, 0, + Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); + + /* + * Iterate through all of the elements of the listbox, displaying each + * in turn. Selected elements use a different GC and have a raised + * background. + */ + + limit = listPtr->topIndex + listPtr->fullLines + listPtr->partialLine - 1; + if (limit >= listPtr->numElements) { + limit = listPtr->numElements-1; + } + left = right = 0; + if (listPtr->xOffset > 0) { + left = listPtr->selBorderWidth+1; + } + if ((listPtr->maxWidth - listPtr->xOffset) > (Tk_Width(listPtr->tkwin) + - 2*(listPtr->inset + listPtr->selBorderWidth))) { + right = listPtr->selBorderWidth+1; + } + prevSelected = 0; + for (elPtr = listPtr->firstPtr, i = 0; (elPtr != NULL) && (i <= limit); + prevSelected = elPtr->selected, elPtr = elPtr->nextPtr, i++) { + if (i < listPtr->topIndex) { + continue; + } + x = listPtr->inset; + y = ((i - listPtr->topIndex) * listPtr->lineHeight) + + listPtr->inset; + gc = listPtr->textGC; + if (elPtr->selected) { + gc = listPtr->selTextGC; + width = Tk_Width(tkwin) - 2*listPtr->inset; + Tk_Fill3DRectangle(tkwin, pixmap, listPtr->selBorder, x, y, + width, listPtr->lineHeight, 0, TK_RELIEF_FLAT); + + /* + * Draw beveled edges around the selection, if there are visible + * edges next to this element. Special considerations: + * 1. The left and right bevels may not be visible if horizontal + * scrolling is enabled (the "left" and "right" variables + * are zero to indicate that the corresponding bevel is + * visible). + * 2. Top and bottom bevels are only drawn if this is the + * first or last seleted item. + * 3. If the left or right bevel isn't visible, then the "left" + * and "right" variables, computed above, have non-zero values + * that extend the top and bottom bevels so that the mitered + * corners are off-screen. + */ + + if (left == 0) { + Tk_3DVerticalBevel(tkwin, pixmap, listPtr->selBorder, + x, y, listPtr->selBorderWidth, listPtr->lineHeight, + 1, TK_RELIEF_RAISED); + } + if (right == 0) { + Tk_3DVerticalBevel(tkwin, pixmap, listPtr->selBorder, + x + width - listPtr->selBorderWidth, y, + listPtr->selBorderWidth, listPtr->lineHeight, + 0, TK_RELIEF_RAISED); + } + if (!prevSelected) { + Tk_3DHorizontalBevel(tkwin, pixmap, listPtr->selBorder, + x-left, y, width+left+right, listPtr->selBorderWidth, + 1, 1, 1, TK_RELIEF_RAISED); + } + if ((elPtr->nextPtr == NULL) || !elPtr->nextPtr->selected) { + Tk_3DHorizontalBevel(tkwin, pixmap, listPtr->selBorder, x-left, + y + listPtr->lineHeight - listPtr->selBorderWidth, + width+left+right, listPtr->selBorderWidth, 0, 0, 0, + TK_RELIEF_RAISED); + } + } + Tk_GetFontMetrics(listPtr->tkfont, &fm); + y += fm.ascent + listPtr->selBorderWidth; + x = listPtr->inset + listPtr->selBorderWidth - elPtr->lBearing + - listPtr->xOffset; + Tk_DrawChars(listPtr->display, pixmap, gc, listPtr->tkfont, + elPtr->text, elPtr->textLength, x, y); + + /* + * If this is the active element, underline it. + */ + + if ((i == listPtr->active) && (listPtr->flags & GOT_FOCUS)) { + Tk_UnderlineChars(listPtr->display, pixmap, gc, listPtr->tkfont, + elPtr->text, x, y, 0, elPtr->textLength); + } + } + + /* + * Redraw the border for the listbox to make sure that it's on top + * of any of the text of the listbox entries. + */ + + Tk_Draw3DRectangle(tkwin, pixmap, listPtr->normalBorder, + listPtr->highlightWidth, listPtr->highlightWidth, + Tk_Width(tkwin) - 2*listPtr->highlightWidth, + Tk_Height(tkwin) - 2*listPtr->highlightWidth, + listPtr->borderWidth, listPtr->relief); + if (listPtr->highlightWidth > 0) { + GC gc; + + if (listPtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(listPtr->highlightColorPtr, pixmap); + } else { + gc = Tk_GCForColor(listPtr->highlightBgColorPtr, pixmap); + } + Tk_DrawFocusHighlight(tkwin, gc, listPtr->highlightWidth, pixmap); + } + XCopyArea(listPtr->display, pixmap, Tk_WindowId(tkwin), + listPtr->textGC, 0, 0, (unsigned) Tk_Width(tkwin), + (unsigned) Tk_Height(tkwin), 0, 0); + Tk_FreePixmap(listPtr->display, pixmap); +} + +/* + *---------------------------------------------------------------------- + * + * ListboxComputeGeometry -- + * + * This procedure is invoked to recompute geometry information + * such as the sizes of the elements and the overall dimensions + * desired for the listbox. + * + * Results: + * None. + * + * Side effects: + * Geometry information is updated and a new requested size is + * registered for the widget. Internal border and gridding + * information is also set. + * + *---------------------------------------------------------------------- + */ + +static void +ListboxComputeGeometry(listPtr, fontChanged, maxIsStale, updateGrid) + Listbox *listPtr; /* Listbox whose geometry is to be + * recomputed. */ + int fontChanged; /* Non-zero means the font may have changed + * so per-element width information also + * has to be computed. */ + int maxIsStale; /* Non-zero means the "maxWidth" field may + * no longer be up-to-date and must + * be recomputed. If fontChanged is 1 then + * this must be 1. */ + int updateGrid; /* Non-zero means call Tk_SetGrid or + * Tk_UnsetGrid to update gridding for + * the window. */ +{ + register Element *elPtr; + int width, height, pixelWidth, pixelHeight; + Tk_FontMetrics fm; + + if (fontChanged || maxIsStale) { + listPtr->xScrollUnit = Tk_TextWidth(listPtr->tkfont, "0", 1); + if (listPtr->xScrollUnit == 0) { + listPtr->xScrollUnit = 1; + } + listPtr->maxWidth = 0; + for (elPtr = listPtr->firstPtr; elPtr != NULL; elPtr = elPtr->nextPtr) { + if (fontChanged) { + elPtr->pixelWidth = Tk_TextWidth(listPtr->tkfont, + elPtr->text, elPtr->textLength); + elPtr->lBearing = 0; + } + if (elPtr->pixelWidth > listPtr->maxWidth) { + listPtr->maxWidth = elPtr->pixelWidth; + } + } + } + + Tk_GetFontMetrics(listPtr->tkfont, &fm); + listPtr->lineHeight = fm.linespace + 1 + 2*listPtr->selBorderWidth; + width = listPtr->width; + if (width <= 0) { + width = (listPtr->maxWidth + listPtr->xScrollUnit - 1) + /listPtr->xScrollUnit; + if (width < 1) { + width = 1; + } + } + pixelWidth = width*listPtr->xScrollUnit + 2*listPtr->inset + + 2*listPtr->selBorderWidth; + height = listPtr->height; + if (listPtr->height <= 0) { + height = listPtr->numElements; + if (height < 1) { + height = 1; + } + } + pixelHeight = height*listPtr->lineHeight + 2*listPtr->inset; + Tk_GeometryRequest(listPtr->tkwin, pixelWidth, pixelHeight); + Tk_SetInternalBorder(listPtr->tkwin, listPtr->inset); + if (updateGrid) { + if (listPtr->setGrid) { + Tk_SetGrid(listPtr->tkwin, width, height, listPtr->xScrollUnit, + listPtr->lineHeight); + } else { + Tk_UnsetGrid(listPtr->tkwin); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * InsertEls -- + * + * Add new elements to a listbox widget. + * + * Results: + * None. + * + * Side effects: + * New information gets added to listPtr; it will be redisplayed + * soon, but not immediately. + * + *---------------------------------------------------------------------- + */ + +static void +InsertEls(listPtr, index, argc, argv) + register Listbox *listPtr; /* Listbox that is to get the new + * elements. */ + int index; /* Add the new elements before this + * element. */ + int argc; /* Number of new elements to add. */ + char **argv; /* New elements (one per entry). */ +{ + register Element *prevPtr, *newPtr; + int length, i, oldMaxWidth; + + /* + * Find the element before which the new ones will be inserted. + */ + + if (index <= 0) { + index = 0; + } + if (index > listPtr->numElements) { + index = listPtr->numElements; + } + if (index == 0) { + prevPtr = NULL; + } else if (index == listPtr->numElements) { + prevPtr = listPtr->lastPtr; + } else { + for (prevPtr = listPtr->firstPtr, i = index - 1; i > 0; i--) { + prevPtr = prevPtr->nextPtr; + } + } + + /* + * For each new element, create a record, initialize it, and link + * it into the list of elements. + */ + + oldMaxWidth = listPtr->maxWidth; + for (i = argc ; i > 0; i--, argv++, prevPtr = newPtr) { + length = strlen(*argv); + newPtr = (Element *) ckalloc(ElementSize(length)); + newPtr->textLength = length; + strcpy(newPtr->text, *argv); + newPtr->pixelWidth = Tk_TextWidth(listPtr->tkfont, newPtr->text, + newPtr->textLength); + newPtr->lBearing = 0; + if (newPtr->pixelWidth > listPtr->maxWidth) { + listPtr->maxWidth = newPtr->pixelWidth; + } + newPtr->selected = 0; + if (prevPtr == NULL) { + newPtr->nextPtr = listPtr->firstPtr; + listPtr->firstPtr = newPtr; + } else { + newPtr->nextPtr = prevPtr->nextPtr; + prevPtr->nextPtr = newPtr; + } + } + if ((prevPtr != NULL) && (prevPtr->nextPtr == NULL)) { + listPtr->lastPtr = prevPtr; + } + listPtr->numElements += argc; + + /* + * Update the selection and other indexes to account for the + * renumbering that has just occurred. Then arrange for the new + * information to be displayed. + */ + + if (index <= listPtr->selectAnchor) { + listPtr->selectAnchor += argc; + } + if (index < listPtr->topIndex) { + listPtr->topIndex += argc; + } + if (index <= listPtr->active) { + listPtr->active += argc; + if ((listPtr->active >= listPtr->numElements) + && (listPtr->numElements > 0)) { + listPtr->active = listPtr->numElements-1; + } + } + listPtr->flags |= UPDATE_V_SCROLLBAR; + if (listPtr->maxWidth != oldMaxWidth) { + listPtr->flags |= UPDATE_H_SCROLLBAR; + } + ListboxComputeGeometry(listPtr, 0, 0, 0); + ListboxRedrawRange(listPtr, index, listPtr->numElements-1); +} + +/* + *---------------------------------------------------------------------- + * + * DeleteEls -- + * + * Remove one or more elements from a listbox widget. + * + * Results: + * None. + * + * Side effects: + * Memory gets freed, the listbox gets modified and (eventually) + * redisplayed. + * + *---------------------------------------------------------------------- + */ + +static void +DeleteEls(listPtr, first, last) + register Listbox *listPtr; /* Listbox widget to modify. */ + int first; /* Index of first element to delete. */ + int last; /* Index of last element to delete. */ +{ + register Element *prevPtr, *elPtr; + int count, i, widthChanged; + + /* + * Adjust the range to fit within the existing elements of the + * listbox, and make sure there's something to delete. + */ + + if (first < 0) { + first = 0; + } + if (last >= listPtr->numElements) { + last = listPtr->numElements-1; + } + count = last + 1 - first; + if (count <= 0) { + return; + } + + /* + * Find the element just before the ones to delete. + */ + + if (first == 0) { + prevPtr = NULL; + } else { + for (i = first-1, prevPtr = listPtr->firstPtr; i > 0; i--) { + prevPtr = prevPtr->nextPtr; + } + } + + /* + * Delete the requested number of elements. + */ + + widthChanged = 0; + for (i = count; i > 0; i--) { + if (prevPtr == NULL) { + elPtr = listPtr->firstPtr; + listPtr->firstPtr = elPtr->nextPtr; + if (listPtr->firstPtr == NULL) { + listPtr->lastPtr = NULL; + } + } else { + elPtr = prevPtr->nextPtr; + prevPtr->nextPtr = elPtr->nextPtr; + if (prevPtr->nextPtr == NULL) { + listPtr->lastPtr = prevPtr; + } + } + if (elPtr->pixelWidth == listPtr->maxWidth) { + widthChanged = 1; + } + if (elPtr->selected) { + listPtr->numSelected -= 1; + } + ckfree((char *) elPtr); + } + listPtr->numElements -= count; + + /* + * Update the selection and viewing information to reflect the change + * in the element numbering, and redisplay to slide information up over + * the elements that were deleted. + */ + + if (first <= listPtr->selectAnchor) { + listPtr->selectAnchor -= count; + if (listPtr->selectAnchor < first) { + listPtr->selectAnchor = first; + } + } + if (first <= listPtr->topIndex) { + listPtr->topIndex -= count; + if (listPtr->topIndex < first) { + listPtr->topIndex = first; + } + } + if (listPtr->topIndex > (listPtr->numElements - listPtr->fullLines)) { + listPtr->topIndex = listPtr->numElements - listPtr->fullLines; + if (listPtr->topIndex < 0) { + listPtr->topIndex = 0; + } + } + if (listPtr->active > last) { + listPtr->active -= count; + } else if (listPtr->active >= first) { + listPtr->active = first; + if ((listPtr->active >= listPtr->numElements) + && (listPtr->numElements > 0)) { + listPtr->active = listPtr->numElements-1; + } + } + listPtr->flags |= UPDATE_V_SCROLLBAR; + ListboxComputeGeometry(listPtr, 0, widthChanged, 0); + if (widthChanged) { + listPtr->flags |= UPDATE_H_SCROLLBAR; + } + ListboxRedrawRange(listPtr, first, listPtr->numElements-1); +} + +/* + *-------------------------------------------------------------- + * + * ListboxEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on listboxes. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +ListboxEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + Listbox *listPtr = (Listbox *) clientData; + + if (eventPtr->type == Expose) { + ListboxRedrawRange(listPtr, + NearestListboxElement(listPtr, eventPtr->xexpose.y), + NearestListboxElement(listPtr, eventPtr->xexpose.y + + eventPtr->xexpose.height)); + } else if (eventPtr->type == DestroyNotify) { + if (listPtr->tkwin != NULL) { + if (listPtr->setGrid) { + Tk_UnsetGrid(listPtr->tkwin); + } + listPtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(listPtr->interp, listPtr->widgetCmd); + } + if (listPtr->flags & REDRAW_PENDING) { + Tcl_CancelIdleCall(DisplayListbox, (ClientData) listPtr); + } + Tcl_EventuallyFree((ClientData) listPtr, DestroyListbox); + } else if (eventPtr->type == ConfigureNotify) { + int vertSpace; + + vertSpace = Tk_Height(listPtr->tkwin) - 2*listPtr->inset; + listPtr->fullLines = vertSpace / listPtr->lineHeight; + if ((listPtr->fullLines*listPtr->lineHeight) < vertSpace) { + listPtr->partialLine = 1; + } else { + listPtr->partialLine = 0; + } + listPtr->flags |= UPDATE_V_SCROLLBAR|UPDATE_H_SCROLLBAR; + ChangeListboxView(listPtr, listPtr->topIndex); + ChangeListboxOffset(listPtr, listPtr->xOffset); + + /* + * Redraw the whole listbox. It's hard to tell what needs + * to be redrawn (e.g. if the listbox has shrunk then we + * may only need to redraw the borders), so just redraw + * everything for safety. + */ + + ListboxRedrawRange(listPtr, 0, listPtr->numElements-1); + } else if (eventPtr->type == FocusIn) { + if (eventPtr->xfocus.detail != NotifyInferior) { + listPtr->flags |= GOT_FOCUS; + ListboxRedrawRange(listPtr, 0, listPtr->numElements-1); + } + } else if (eventPtr->type == FocusOut) { + if (eventPtr->xfocus.detail != NotifyInferior) { + listPtr->flags &= ~GOT_FOCUS; + ListboxRedrawRange(listPtr, 0, listPtr->numElements-1); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * ListboxCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +ListboxCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + Listbox *listPtr = (Listbox *) clientData; + Tk_Window tkwin = listPtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + if (listPtr->setGrid) { + Tk_UnsetGrid(listPtr->tkwin); + } + listPtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *-------------------------------------------------------------- + * + * GetListboxIndex -- + * + * Parse an index into a listbox and return either its value + * or an error. + * + * Results: + * A standard Tcl result. If all went well, then *indexPtr is + * filled in with the index (into listPtr) corresponding to + * string. Otherwise an error message is left in interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +GetListboxIndex(interp, listPtr, string, endIsSize, indexPtr) + Tcl_Interp *interp; /* For error messages. */ + Listbox *listPtr; /* Listbox for which the index is being + * specified. */ + char *string; /* Specifies an element in the listbox. */ + int endIsSize; /* If 1, "end" refers to the number of + * entries in the listbox. If 0, "end" + * refers to 1 less than the number of + * entries. */ + int *indexPtr; /* Where to store converted index. */ +{ + int c; + size_t length; + + length = strlen(string); + c = string[0]; + if ((c == 'a') && (strncmp(string, "active", length) == 0) + && (length >= 2)) { + *indexPtr = listPtr->active; + } else if ((c == 'a') && (strncmp(string, "anchor", length) == 0) + && (length >= 2)) { + *indexPtr = listPtr->selectAnchor; + } else if ((c == 'e') && (strncmp(string, "end", length) == 0)) { + if (endIsSize) { + *indexPtr = listPtr->numElements; + } else { + *indexPtr = listPtr->numElements - 1; + } + } else if (c == '@') { + int y; + char *p, *end; + + p = string+1; + strtol(p, &end, 0); + if ((end == p) || (*end != ',')) { + goto badIndex; + } + p = end+1; + y = strtol(p, &end, 0); + if ((end == p) || (*end != 0)) { + goto badIndex; + } + *indexPtr = NearestListboxElement(listPtr, y); + } else { + if (Tcl_GetInt(interp, string, indexPtr) != TCL_OK) { + Tcl_ResetResult(interp); + goto badIndex; + } + } + return TCL_OK; + + badIndex: + Tcl_AppendResult(interp, "bad listbox index \"", string, + "\": must be active, anchor, end, @x,y, or a number", + (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * ChangeListboxView -- + * + * Change the view on a listbox widget so that a given element + * is displayed at the top. + * + * Results: + * None. + * + * Side effects: + * What's displayed on the screen is changed. If there is a + * scrollbar associated with this widget, then the scrollbar + * is instructed to change its display too. + * + *---------------------------------------------------------------------- + */ + +static void +ChangeListboxView(listPtr, index) + register Listbox *listPtr; /* Information about widget. */ + int index; /* Index of element in listPtr + * that should now appear at the + * top of the listbox. */ +{ + if (index >= (listPtr->numElements - listPtr->fullLines)) { + index = listPtr->numElements - listPtr->fullLines; + } + if (index < 0) { + index = 0; + } + if (listPtr->topIndex != index) { + listPtr->topIndex = index; + if (!(listPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayListbox, (ClientData) listPtr); + listPtr->flags |= REDRAW_PENDING; + } + listPtr->flags |= UPDATE_V_SCROLLBAR; + } +} + +/* + *---------------------------------------------------------------------- + * + * ChangListboxOffset -- + * + * Change the horizontal offset for a listbox. + * + * Results: + * None. + * + * Side effects: + * The listbox may be redrawn to reflect its new horizontal + * offset. + * + *---------------------------------------------------------------------- + */ + +static void +ChangeListboxOffset(listPtr, offset) + register Listbox *listPtr; /* Information about widget. */ + int offset; /* Desired new "xOffset" for + * listbox. */ +{ + int maxOffset; + + /* + * Make sure that the new offset is within the allowable range, and + * round it off to an even multiple of xScrollUnit. + */ + + maxOffset = listPtr->maxWidth - (Tk_Width(listPtr->tkwin) - + 2*listPtr->inset - 2*listPtr->selBorderWidth) + + listPtr->xScrollUnit - 1; + if (offset > maxOffset) { + offset = maxOffset; + } + if (offset < 0) { + offset = 0; + } + offset -= offset % listPtr->xScrollUnit; + if (offset != listPtr->xOffset) { + listPtr->xOffset = offset; + listPtr->flags |= UPDATE_H_SCROLLBAR; + ListboxRedrawRange(listPtr, 0, listPtr->numElements); + } +} + +/* + *---------------------------------------------------------------------- + * + * ListboxScanTo -- + * + * Given a point (presumably of the curent mouse location) + * drag the view in the window to implement the scan operation. + * + * Results: + * None. + * + * Side effects: + * The view in the window may change. + * + *---------------------------------------------------------------------- + */ + +static void +ListboxScanTo(listPtr, x, y) + register Listbox *listPtr; /* Information about widget. */ + int x; /* X-coordinate to use for scan + * operation. */ + int y; /* Y-coordinate to use for scan + * operation. */ +{ + int newTopIndex, newOffset, maxIndex, maxOffset; + + maxIndex = listPtr->numElements - listPtr->fullLines; + maxOffset = listPtr->maxWidth + (listPtr->xScrollUnit - 1) + - (Tk_Width(listPtr->tkwin) - 2*listPtr->inset + - 2*listPtr->selBorderWidth - listPtr->xScrollUnit); + + /* + * Compute new top line for screen by amplifying the difference + * between the current position and the place where the scan + * started (the "mark" position). If we run off the top or bottom + * of the list, then reset the mark point so that the current + * position continues to correspond to the edge of the window. + * This means that the picture will start dragging as soon as the + * mouse reverses direction (without this reset, might have to slide + * mouse a long ways back before the picture starts moving again). + */ + + newTopIndex = listPtr->scanMarkYIndex + - (10*(y - listPtr->scanMarkY))/listPtr->lineHeight; + if (newTopIndex > maxIndex) { + newTopIndex = listPtr->scanMarkYIndex = maxIndex; + listPtr->scanMarkY = y; + } else if (newTopIndex < 0) { + newTopIndex = listPtr->scanMarkYIndex = 0; + listPtr->scanMarkY = y; + } + ChangeListboxView(listPtr, newTopIndex); + + /* + * Compute new left edge for display in a similar fashion by amplifying + * the difference between the current position and the place where the + * scan started. + */ + + newOffset = listPtr->scanMarkXOffset - (10*(x - listPtr->scanMarkX)); + if (newOffset > maxOffset) { + newOffset = listPtr->scanMarkXOffset = maxOffset; + listPtr->scanMarkX = x; + } else if (newOffset < 0) { + newOffset = listPtr->scanMarkXOffset = 0; + listPtr->scanMarkX = x; + } + ChangeListboxOffset(listPtr, newOffset); +} + +/* + *---------------------------------------------------------------------- + * + * NearestListboxElement -- + * + * Given a y-coordinate inside a listbox, compute the index of + * the element under that y-coordinate (or closest to that + * y-coordinate). + * + * Results: + * The return value is an index of an element of listPtr. If + * listPtr has no elements, then 0 is always returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +NearestListboxElement(listPtr, y) + register Listbox *listPtr; /* Information about widget. */ + int y; /* Y-coordinate in listPtr's window. */ +{ + int index; + + index = (y - listPtr->inset)/listPtr->lineHeight; + if (index >= (listPtr->fullLines + listPtr->partialLine)) { + index = listPtr->fullLines + listPtr->partialLine - 1; + } + if (index < 0) { + index = 0; + } + index += listPtr->topIndex; + if (index >= listPtr->numElements) { + index = listPtr->numElements-1; + } + return index; +} + +/* + *---------------------------------------------------------------------- + * + * ListboxSelect -- + * + * Select or deselect one or more elements in a listbox.. + * + * Results: + * None. + * + * Side effects: + * All of the elements in the range between first and last are + * marked as either selected or deselected, depending on the + * "select" argument. Any items whose state changes are redisplayed. + * The selection is claimed from X when the number of selected + * elements changes from zero to non-zero. + * + *---------------------------------------------------------------------- + */ + +static void +ListboxSelect(listPtr, first, last, select) + register Listbox *listPtr; /* Information about widget. */ + int first; /* Index of first element to + * select or deselect. */ + int last; /* Index of last element to + * select or deselect. */ + int select; /* 1 means select items, 0 means + * deselect them. */ +{ + int i, firstRedisplay, increment, oldCount; + Element *elPtr; + + if (last < first) { + i = first; + first = last; + last = i; + } + if ((last < 0) || (first >= listPtr->numElements)) { + return; + } + if (first < 0) { + first = 0; + } + if (last >= listPtr->numElements) { + last = listPtr->numElements - 1; + } + oldCount = listPtr->numSelected; + firstRedisplay = -1; + increment = select ? 1 : -1; + for (i = 0, elPtr = listPtr->firstPtr; i < first; + i++, elPtr = elPtr->nextPtr) { + /* Empty loop body. */ + } + for ( ; i <= last; i++, elPtr = elPtr->nextPtr) { + if (elPtr->selected == select) { + continue; + } + listPtr->numSelected += increment; + elPtr->selected = select; + if (firstRedisplay < 0) { + firstRedisplay = i; + } + } + if (firstRedisplay >= 0) { + ListboxRedrawRange(listPtr, first, last); + } + if ((oldCount == 0) && (listPtr->numSelected > 0) + && (listPtr->exportSelection)) { + Tk_OwnSelection(listPtr->tkwin, XA_PRIMARY, ListboxLostSelection, + (ClientData) listPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * ListboxFetchSelection -- + * + * This procedure is called back by Tk when the selection is + * requested by someone. It returns part or all of the selection + * in a buffer provided by the caller. + * + * Results: + * The return value is the number of non-NULL bytes stored + * at buffer. Buffer is filled (or partially filled) with a + * NULL-terminated string containing part or all of the selection, + * as given by offset and maxBytes. The selection is returned + * as a Tcl list with one list element for each element in the + * listbox. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +ListboxFetchSelection(clientData, offset, buffer, maxBytes) + ClientData clientData; /* Information about listbox widget. */ + int offset; /* Offset within selection of first + * byte to be returned. */ + char *buffer; /* Location in which to place + * selection. */ + int maxBytes; /* Maximum number of bytes to place + * at buffer, not including terminating + * NULL character. */ +{ + register Listbox *listPtr = (Listbox *) clientData; + register Element *elPtr; + Tcl_DString selection; + int length, count, needNewline; + + if (!listPtr->exportSelection) { + return -1; + } + + /* + * Use a dynamic string to accumulate the contents of the selection. + */ + + needNewline = 0; + Tcl_DStringInit(&selection); + for (elPtr = listPtr->firstPtr; elPtr != NULL; elPtr = elPtr->nextPtr) { + if (elPtr->selected) { + if (needNewline) { + Tcl_DStringAppend(&selection, "\n", 1); + } + Tcl_DStringAppend(&selection, elPtr->text, elPtr->textLength); + needNewline = 1; + } + } + + length = Tcl_DStringLength(&selection); + if (length == 0) { + return -1; + } + + /* + * Copy the requested portion of the selection to the buffer. + */ + + count = length - offset; + if (count <= 0) { + count = 0; + } else { + if (count > maxBytes) { + count = maxBytes; + } + memcpy((VOID *) buffer, + (VOID *) (Tcl_DStringValue(&selection) + offset), + (size_t) count); + } + buffer[count] = '\0'; + Tcl_DStringFree(&selection); + return count; +} + +/* + *---------------------------------------------------------------------- + * + * ListboxLostSelection -- + * + * This procedure is called back by Tk when the selection is + * grabbed away from a listbox widget. + * + * Results: + * None. + * + * Side effects: + * The existing selection is unhighlighted, and the window is + * marked as not containing a selection. + * + *---------------------------------------------------------------------- + */ + +static void +ListboxLostSelection(clientData) + ClientData clientData; /* Information about listbox widget. */ +{ + register Listbox *listPtr = (Listbox *) clientData; + + if ((listPtr->exportSelection) && (listPtr->numElements > 0)) { + ListboxSelect(listPtr, 0, listPtr->numElements-1, 0); + } +} + +/* + *---------------------------------------------------------------------- + * + * ListboxRedrawRange -- + * + * Ensure that a given range of elements is eventually redrawn on + * the display (if those elements in fact appear on the display). + * + * Results: + * None. + * + * Side effects: + * Information gets redisplayed. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +ListboxRedrawRange(listPtr, first, last) + register Listbox *listPtr; /* Information about widget. */ + int first; /* Index of first element in list + * that needs to be redrawn. */ + int last; /* Index of last element in list + * that needs to be redrawn. May + * be less than first; + * these just bracket a range. */ +{ + if ((listPtr->tkwin == NULL) || !Tk_IsMapped(listPtr->tkwin) + || (listPtr->flags & REDRAW_PENDING)) { + return; + } + Tcl_DoWhenIdle(DisplayListbox, (ClientData) listPtr); + listPtr->flags |= REDRAW_PENDING; +} + +/* + *---------------------------------------------------------------------- + * + * ListboxUpdateVScrollbar -- + * + * This procedure is invoked whenever information has changed in + * a listbox in a way that would invalidate a vertical scrollbar + * display. If there is an associated scrollbar, then this command + * updates it by invoking a Tcl command. + * + * Results: + * None. + * + * Side effects: + * A Tcl command is invoked, and an additional command may be + * invoked to process errors in the command. + * + *---------------------------------------------------------------------- + */ + +static void +ListboxUpdateVScrollbar(listPtr) + register Listbox *listPtr; /* Information about widget. */ +{ + char string[100]; + double first, last; + int result; + Tcl_Interp *interp; + + if (listPtr->yScrollCmd == NULL) { + return; + } + if (listPtr->numElements == 0) { + first = 0.0; + last = 1.0; + } else { + first = listPtr->topIndex/((double) listPtr->numElements); + last = (listPtr->topIndex+listPtr->fullLines) + /((double) listPtr->numElements); + if (last > 1.0) { + last = 1.0; + } + } + sprintf(string, " %g %g", first, last); + + /* + * We must hold onto the interpreter from the listPtr because the data + * at listPtr might be freed as a result of the Tcl_VarEval. + */ + + interp = listPtr->interp; + Tcl_Preserve((ClientData) interp); + result = Tcl_VarEval(interp, listPtr->yScrollCmd, string, + (char *) NULL); + if (result != TCL_OK) { + Tcl_AddErrorInfo(interp, + "\n (vertical scrolling command executed by listbox)"); + Tcl_BackgroundError(interp); + } + Tcl_Release((ClientData) interp); +} + +/* + *---------------------------------------------------------------------- + * + * ListboxUpdateHScrollbar -- + * + * This procedure is invoked whenever information has changed in + * a listbox in a way that would invalidate a horizontal scrollbar + * display. If there is an associated horizontal scrollbar, then + * this command updates it by invoking a Tcl command. + * + * Results: + * None. + * + * Side effects: + * A Tcl command is invoked, and an additional command may be + * invoked to process errors in the command. + * + *---------------------------------------------------------------------- + */ + +static void +ListboxUpdateHScrollbar(listPtr) + register Listbox *listPtr; /* Information about widget. */ +{ + char string[60]; + int result, windowWidth; + double first, last; + Tcl_Interp *interp; + + if (listPtr->xScrollCmd == NULL) { + return; + } + windowWidth = Tk_Width(listPtr->tkwin) - 2*(listPtr->inset + + listPtr->selBorderWidth); + if (listPtr->maxWidth == 0) { + first = 0; + last = 1.0; + } else { + first = listPtr->xOffset/((double) listPtr->maxWidth); + last = (listPtr->xOffset + windowWidth) + /((double) listPtr->maxWidth); + if (last > 1.0) { + last = 1.0; + } + } + sprintf(string, " %g %g", first, last); + + /* + * We must hold onto the interpreter because the data referred to at + * listPtr might be freed as a result of the call to Tcl_VarEval. + */ + + interp = listPtr->interp; + Tcl_Preserve((ClientData) interp); + result = Tcl_VarEval(interp, listPtr->xScrollCmd, string, + (char *) NULL); + if (result != TCL_OK) { + Tcl_AddErrorInfo(interp, + "\n (horizontal scrolling command executed by listbox)"); + Tcl_BackgroundError(interp); + } + Tcl_Release((ClientData) interp); +} diff --git a/generic/tkMacWinMenu.c b/generic/tkMacWinMenu.c new file mode 100644 index 0000000..8ae403b --- /dev/null +++ b/generic/tkMacWinMenu.c @@ -0,0 +1,134 @@ +/* + * tkMacWinMenu.c -- + * + * This module implements the common elements of the Mac and Windows + * specific features of menus. This file is not used for UNIX. + * + * Copyright (c) 1996-1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacWinMenu.c 1.39 97/04/09 14:56:59 + */ + +#include "tkMenu.h" + +static int postCommandGeneration; + +static int PreprocessMenu _ANSI_ARGS_((TkMenu *menuPtr)); + + +/* + *---------------------------------------------------------------------- + * + * PreprocessMenu -- + * + * The guts of the preprocessing. Recursive. + * + * Results: + * The return value is a standard Tcl result (errors can occur + * while the postcommands are being processed). + * + * Side effects: + * Since commands can get executed while this routine is being executed, + * the entire world can change. + * + *---------------------------------------------------------------------- + */ + +static int +PreprocessMenu(menuPtr) + TkMenu *menuPtr; +{ + int index, result, finished; + TkMenu *cascadeMenuPtr; + + Tcl_Preserve((ClientData) menuPtr); + + /* + * First, let's process the post command on ourselves. If this command + * destroys this menu, or if there was an error, we are done. + */ + + result = TkPostCommand(menuPtr); + if ((result != TCL_OK) || (menuPtr->tkwin == NULL)) { + goto done; + } + + /* + * Now, we go through structure and process all of the commands. + * Since the structure is changing, we stop after we do one command, + * and start over. When we get through without doing any, we are done. + */ + + + do { + finished = 1; + for (index = 0; index < menuPtr->numEntries; index++) { + if ((menuPtr->entries[index]->type == CASCADE_ENTRY) + && (menuPtr->entries[index]->name != NULL)) { + if ((menuPtr->entries[index]->childMenuRefPtr != NULL) + && (menuPtr->entries[index]->childMenuRefPtr->menuPtr + != NULL)) { + cascadeMenuPtr = + menuPtr->entries[index]->childMenuRefPtr->menuPtr; + if (cascadeMenuPtr->postCommandGeneration != + postCommandGeneration) { + cascadeMenuPtr->postCommandGeneration = + postCommandGeneration; + result = PreprocessMenu(cascadeMenuPtr); + if (result != TCL_OK) { + goto done; + } + finished = 0; + break; + } + } + } + } + } while (!finished); + + done: + Tcl_Release((ClientData)menuPtr); + return result; +} + +/* + *---------------------------------------------------------------------- + * + * TkPreprocessMenu -- + * + * On the Mac and on Windows, all of the postcommand processing has + * to be done on the entire tree underneath the main window to be + * posted. This means that we have to traverse the menu tree and + * issue the postcommands for all of the menus that have cascades + * attached. Since the postcommands can change the menu structure while + * we are traversing, we have to be extremely careful. Basically, the + * idea is to traverse the structure until we succesfully process + * one postcommand. Then we start over, and do it again until + * we traverse the whole structure without processing any postcommands. + * + * We are also going to set up the cascade back pointers in here + * since we have to traverse the entire structure underneath the menu + * anyway, We can clear the postcommand marks while we do that. + * + * Results: + * The return value is a standard Tcl result (errors can occur + * while the postcommands are being processed). + * + * Side effects: + * Since commands can get executed while this routine is being executed, + * the entire world can change. + * + *---------------------------------------------------------------------- + */ + +int +TkPreprocessMenu(menuPtr) + TkMenu *menuPtr; +{ + postCommandGeneration++; + menuPtr->postCommandGeneration = postCommandGeneration; + return PreprocessMenu(menuPtr); +} diff --git a/generic/tkMain.c b/generic/tkMain.c new file mode 100644 index 0000000..ed823bd --- /dev/null +++ b/generic/tkMain.c @@ -0,0 +1,390 @@ +/* + * tkMain.c -- + * + * This file contains a generic main program for Tk-based applications. + * It can be used as-is for many applications, just by supplying a + * different appInitProc procedure for each specific application. + * Or, it can be used as a template for creating new main programs + * for Tk applications. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMain.c 1.154 97/08/29 10:40:43 + */ + +#include <ctype.h> +#include <stdio.h> +#include <string.h> +#include <tcl.h> +#include <tk.h> +#ifdef NO_STDLIB_H +# include "../compat/stdlib.h" +#else +# include <stdlib.h> +#endif + +/* + * Declarations for various library procedures and variables (don't want + * to include tkInt.h or tkPort.h here, because people might copy this + * file out of the Tk source directory to make their own modified versions). + * Note: don't declare "exit" here even though a declaration is really + * needed, because it will conflict with a declaration elsewhere on + * some systems. + */ + +extern int isatty _ANSI_ARGS_((int fd)); +#if !defined(__WIN32__) && !defined(_WIN32) +extern char * strrchr _ANSI_ARGS_((CONST char *string, int c)); +#endif +extern void TkpDisplayWarning _ANSI_ARGS_((char *msg, + char *title)); + +/* + * Global variables used by the main program: + */ + +static Tcl_Interp *interp; /* Interpreter for this application. */ +static Tcl_DString command; /* Used to assemble lines of terminal input + * into Tcl commands. */ +static Tcl_DString line; /* Used to read the next line from the + * terminal input. */ +static int tty; /* Non-zero means standard input is a + * terminal-like device. Zero means it's + * a file. */ + +/* + * Forward declarations for procedures defined later in this file. + */ + +static void Prompt _ANSI_ARGS_((Tcl_Interp *interp, int partial)); +static void StdinProc _ANSI_ARGS_((ClientData clientData, + int mask)); + +/* + *---------------------------------------------------------------------- + * + * Tk_Main -- + * + * Main program for Wish and most other Tk-based applications. + * + * Results: + * None. This procedure never returns (it exits the process when + * it's done. + * + * Side effects: + * This procedure initializes the Tk world and then starts + * interpreting commands; almost anything could happen, depending + * on the script being interpreted. + * + *---------------------------------------------------------------------- + */ + +void +Tk_Main(argc, argv, appInitProc) + int argc; /* Number of arguments. */ + char **argv; /* Array of argument strings. */ + Tcl_AppInitProc *appInitProc; /* Application-specific initialization + * procedure to call after most + * initialization but before starting + * to execute commands. */ +{ + char *args, *fileName; + char buf[20]; + int code; + size_t length; + Tcl_Channel inChannel, outChannel; + + Tcl_FindExecutable(argv[0]); + interp = Tcl_CreateInterp(); +#ifdef TCL_MEM_DEBUG + Tcl_InitMemory(interp); +#endif + + /* + * Parse command-line arguments. A leading "-file" argument is + * ignored (a historical relic from the distant past). If the + * next argument doesn't start with a "-" then strip it off and + * use it as the name of a script file to process. + */ + + fileName = NULL; + if (argc > 1) { + length = strlen(argv[1]); + if ((length >= 2) && (strncmp(argv[1], "-file", length) == 0)) { + argc--; + argv++; + } + } + if ((argc > 1) && (argv[1][0] != '-')) { + fileName = argv[1]; + argc--; + argv++; + } + + /* + * Make command-line arguments available in the Tcl variables "argc" + * and "argv". + */ + + args = Tcl_Merge(argc-1, argv+1); + Tcl_SetVar(interp, "argv", args, TCL_GLOBAL_ONLY); + ckfree(args); + sprintf(buf, "%d", argc-1); + Tcl_SetVar(interp, "argc", buf, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "argv0", (fileName != NULL) ? fileName : argv[0], + TCL_GLOBAL_ONLY); + + /* + * Set the "tcl_interactive" variable. + */ + + /* + * For now, under Windows, we assume we are not running as a console mode + * app, so we need to use the GUI console. In order to enable this, we + * always claim to be running on a tty. This probably isn't the right + * way to do it. + */ + +#ifdef __WIN32__ + tty = 1; +#else + tty = isatty(0); +#endif + Tcl_SetVar(interp, "tcl_interactive", + ((fileName == NULL) && tty) ? "1" : "0", TCL_GLOBAL_ONLY); + + /* + * Invoke application-specific initialization. + */ + + if ((*appInitProc)(interp) != TCL_OK) { + TkpDisplayWarning(interp->result, "Application initialization failed"); + } + + /* + * Invoke the script specified on the command line, if any. + */ + + if (fileName != NULL) { + code = Tcl_EvalFile(interp, fileName); + if (code != TCL_OK) { + /* + * The following statement guarantees that the errorInfo + * variable is set properly. + */ + + Tcl_AddErrorInfo(interp, ""); + TkpDisplayWarning(Tcl_GetVar(interp, "errorInfo", + TCL_GLOBAL_ONLY), "Error in startup script"); + Tcl_DeleteInterp(interp); + Tcl_Exit(1); + } + tty = 0; + } else { + + /* + * Evaluate the .rc file, if one has been specified. + */ + + Tcl_SourceRCFile(interp); + + /* + * Establish a channel handler for stdin. + */ + + inChannel = Tcl_GetStdChannel(TCL_STDIN); + if (inChannel) { + Tcl_CreateChannelHandler(inChannel, TCL_READABLE, StdinProc, + (ClientData) inChannel); + } + if (tty) { + Prompt(interp, 0); + } + } + + outChannel = Tcl_GetStdChannel(TCL_STDOUT); + if (outChannel) { + Tcl_Flush(outChannel); + } + Tcl_DStringInit(&command); + Tcl_DStringInit(&line); + Tcl_ResetResult(interp); + + /* + * Loop infinitely, waiting for commands to execute. When there + * are no windows left, Tk_MainLoop returns and we exit. + */ + + Tk_MainLoop(); + Tcl_DeleteInterp(interp); + Tcl_Exit(0); +} + +/* + *---------------------------------------------------------------------- + * + * StdinProc -- + * + * This procedure is invoked by the event dispatcher whenever + * standard input becomes readable. It grabs the next line of + * input characters, adds them to a command being assembled, and + * executes the command if it's complete. + * + * Results: + * None. + * + * Side effects: + * Could be almost arbitrary, depending on the command that's + * typed. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +StdinProc(clientData, mask) + ClientData clientData; /* Not used. */ + int mask; /* Not used. */ +{ + static int gotPartial = 0; + char *cmd; + int code, count; + Tcl_Channel chan = (Tcl_Channel) clientData; + + count = Tcl_Gets(chan, &line); + + if (count < 0) { + if (!gotPartial) { + if (tty) { + Tcl_Exit(0); + } else { + Tcl_DeleteChannelHandler(chan, StdinProc, (ClientData) chan); + } + return; + } + } + + (void) Tcl_DStringAppend(&command, Tcl_DStringValue(&line), -1); + cmd = Tcl_DStringAppend(&command, "\n", -1); + Tcl_DStringFree(&line); + if (!Tcl_CommandComplete(cmd)) { + gotPartial = 1; + goto prompt; + } + gotPartial = 0; + + /* + * Disable the stdin channel handler while evaluating the command; + * otherwise if the command re-enters the event loop we might + * process commands from stdin before the current command is + * finished. Among other things, this will trash the text of the + * command being evaluated. + */ + + Tcl_CreateChannelHandler(chan, 0, StdinProc, (ClientData) chan); + code = Tcl_RecordAndEval(interp, cmd, TCL_EVAL_GLOBAL); + + chan = Tcl_GetStdChannel(TCL_STDIN); + if (chan) { + Tcl_CreateChannelHandler(chan, TCL_READABLE, StdinProc, + (ClientData) chan); + } + Tcl_DStringFree(&command); + if (*interp->result != 0) { + if ((code != TCL_OK) || (tty)) { + /* + * The statement below used to call "printf", but that resulted + * in core dumps under Solaris 2.3 if the result was very long. + * + * NOTE: This probably will not work under Windows either. + */ + + puts(interp->result); + } + } + + /* + * Output a prompt. + */ + + prompt: + if (tty) { + Prompt(interp, gotPartial); + } + Tcl_ResetResult(interp); +} + +/* + *---------------------------------------------------------------------- + * + * Prompt -- + * + * Issue a prompt on standard output, or invoke a script + * to issue the prompt. + * + * Results: + * None. + * + * Side effects: + * A prompt gets output, and a Tcl script may be evaluated + * in interp. + * + *---------------------------------------------------------------------- + */ + +static void +Prompt(interp, partial) + Tcl_Interp *interp; /* Interpreter to use for prompting. */ + int partial; /* Non-zero means there already + * exists a partial command, so use + * the secondary prompt. */ +{ + char *promptCmd; + int code; + Tcl_Channel outChannel, errChannel; + + promptCmd = Tcl_GetVar(interp, + partial ? "tcl_prompt2" : "tcl_prompt1", TCL_GLOBAL_ONLY); + if (promptCmd == NULL) { +defaultPrompt: + if (!partial) { + + /* + * We must check that outChannel is a real channel - it + * is possible that someone has transferred stdout out of + * this interpreter with "interp transfer". + */ + + outChannel = Tcl_GetChannel(interp, "stdout", NULL); + if (outChannel != (Tcl_Channel) NULL) { + Tcl_Write(outChannel, "% ", 2); + } + } + } else { + code = Tcl_Eval(interp, promptCmd); + if (code != TCL_OK) { + Tcl_AddErrorInfo(interp, + "\n (script that generates prompt)"); + /* + * We must check that errChannel is a real channel - it + * is possible that someone has transferred stderr out of + * this interpreter with "interp transfer". + */ + + errChannel = Tcl_GetChannel(interp, "stderr", NULL); + if (errChannel != (Tcl_Channel) NULL) { + Tcl_Write(errChannel, interp->result, -1); + Tcl_Write(errChannel, "\n", 1); + } + goto defaultPrompt; + } + } + outChannel = Tcl_GetChannel(interp, "stdout", NULL); + if (outChannel != (Tcl_Channel) NULL) { + Tcl_Flush(outChannel); + } +} diff --git a/generic/tkMenu.c b/generic/tkMenu.c new file mode 100644 index 0000000..05a6b4a --- /dev/null +++ b/generic/tkMenu.c @@ -0,0 +1,3057 @@ +/* + * tkMenu.c -- + * + * This file contains most of the code for implementing menus in Tk. It takes + * care of all of the generic (platform-independent) parts of menus, and + * is supplemented by platform-specific files. The geometry calculation + * and drawing code for menus is in the file tkMenuDraw.c + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMenu.c 1.148 97/10/29 09:22:00 + */ + +/* + * Notes on implementation of menus: + * + * Menus can be used in three ways: + * - as a popup menu, either as part of a menubutton or standalone. + * - as a menubar. The menu's cascade items are arranged according to + * the specific platform to provide the user access to the menus at all + * times + * - as a tearoff palette. This is a window with the menu's items in it. + * + * The goal is to provide the Tk developer with a way to use a common + * set of menus for all of these tasks. + * + * In order to make the bindings for cascade menus work properly under Unix, + * the cascade menus' pathnames must be proper children of the menu that + * they are cascade from. So if there is a menu .m, and it has two + * cascades labelled "File" and "Edit", the cascade menus might have + * the pathnames .m.file and .m.edit. Another constraint is that the menus + * used for menubars must be children of the toplevel widget that they + * are attached to. And on the Macintosh, the platform specific menu handle + * for cascades attached to a menu bar must have a title that matches the + * label for the cascade menu. + * + * To handle all of the constraints, Tk menubars and tearoff menus are + * implemented using menu clones. Menu clones are full menus in their own + * right; they have a Tk window and pathname associated with them; they have + * a TkMenu structure and array of entries. However, they are linked with the + * original menu that they were cloned from. The reflect the attributes of + * the original, or "master", menu. So if an item is added to a menu, and + * that menu has clones, then the item must be added to all of its clones + * also. Menus are cloned when a menu is torn-off or when a menu is assigned + * as a menubar using the "-menu" option of the toplevel's pathname configure + * subcommand. When a clone is destroyed, only the clone is destroyed, but + * when the master menu is destroyed, all clones are also destroyed. This + * allows the developer to just deal with one set of menus when creating + * and destroying. + * + * Clones are rather tricky when a menu with cascade entries is cloned (such + * as a menubar). Not only does the menu have to be cloned, but each cascade + * entry's corresponding menu must also be cloned. This maintains the pathname + * parent-child hierarchy necessary for menubars and toplevels to work. + * This leads to several special cases: + * + * 1. When a new menu is created, and it is pointed to by cascade entries in + * cloned menus, the new menu has to be cloned to parallel the cascade + * structure. + * 2. When a cascade item is added to a menu that has been cloned, and the + * menu that the cascade item points to exists, that menu has to be cloned. + * 3. When the menu that a cascade entry points to is changed, the old + * cloned cascade menu has to be discarded, and the new one has to be cloned. + * + */ + +#include "tkPort.h" +#include "tkMenu.h" + +#define MENU_HASH_KEY "tkMenus" + +static int menusInitialized; /* Whether or not the hash tables, etc., have + * been setup */ + +/* + * Configuration specs for individual menu entries. If this changes, be sure + * to update code in TkpMenuInit that changes the font string entry. + */ + +Tk_ConfigSpec tkMenuEntryConfigSpecs[] = { + {TK_CONFIG_BORDER, "-activebackground", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_ACTIVE_BG, Tk_Offset(TkMenuEntry, activeBorder), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-activeforeground", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_ACTIVE_FG, Tk_Offset(TkMenuEntry, activeFg), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-accelerator", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_ACCELERATOR, Tk_Offset(TkMenuEntry, accel), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |TK_CONFIG_NULL_OK}, + {TK_CONFIG_BORDER, "-background", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_BG, Tk_Offset(TkMenuEntry, border), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |SEPARATOR_MASK|TEAROFF_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_BITMAP, "-bitmap", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_BITMAP, Tk_Offset(TkMenuEntry, bitmap), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-columnbreak", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_COLUMN_BREAK, Tk_Offset(TkMenuEntry, columnBreak), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK}, + {TK_CONFIG_STRING, "-command", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_COMMAND, Tk_Offset(TkMenuEntry, command), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |TK_CONFIG_NULL_OK}, + {TK_CONFIG_FONT, "-font", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_FONT, Tk_Offset(TkMenuEntry, tkfont), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-foreground", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_FG, Tk_Offset(TkMenuEntry, fg), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-hidemargin", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_HIDE_MARGIN, Tk_Offset(TkMenuEntry, hideMargin), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |SEPARATOR_MASK|TEAROFF_MASK}, + {TK_CONFIG_STRING, "-image", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_IMAGE, Tk_Offset(TkMenuEntry, imageString), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-indicatoron", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_INDICATOR, Tk_Offset(TkMenuEntry, indicatorOn), + CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_STRING, "-label", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_LABEL, Tk_Offset(TkMenuEntry, label), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK}, + {TK_CONFIG_STRING, "-menu", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_MENU, Tk_Offset(TkMenuEntry, name), + CASCADE_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-offvalue", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_OFF_VALUE, Tk_Offset(TkMenuEntry, offValue), + CHECK_BUTTON_MASK}, + {TK_CONFIG_STRING, "-onvalue", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_ON_VALUE, Tk_Offset(TkMenuEntry, onValue), + CHECK_BUTTON_MASK}, + {TK_CONFIG_COLOR, "-selectcolor", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_SELECT, Tk_Offset(TkMenuEntry, indicatorFg), + CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-selectimage", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_SELECT_IMAGE, Tk_Offset(TkMenuEntry, selectImageString), + CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_UID, "-state", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_STATE, Tk_Offset(TkMenuEntry, state), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |TEAROFF_MASK|TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_STRING, "-value", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_VALUE, Tk_Offset(TkMenuEntry, onValue), + RADIO_BUTTON_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-variable", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_CHECK_VARIABLE, Tk_Offset(TkMenuEntry, name), + CHECK_BUTTON_MASK|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-variable", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_RADIO_VARIABLE, Tk_Offset(TkMenuEntry, name), + RADIO_BUTTON_MASK}, + {TK_CONFIG_INT, "-underline", (char *) NULL, (char *) NULL, + DEF_MENU_ENTRY_UNDERLINE, Tk_Offset(TkMenuEntry, underline), + COMMAND_MASK|CHECK_BUTTON_MASK|RADIO_BUTTON_MASK|CASCADE_MASK + |TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Configuration specs valid for the menu as a whole. If this changes, be sure + * to update code in TkpMenuInit that changes the font string entry. + */ + +Tk_ConfigSpec tkMenuConfigSpecs[] = { + {TK_CONFIG_BORDER, "-activebackground", "activeBackground", "Foreground", + DEF_MENU_ACTIVE_BG_COLOR, Tk_Offset(TkMenu, activeBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-activebackground", "activeBackground", "Foreground", + DEF_MENU_ACTIVE_BG_MONO, Tk_Offset(TkMenu, activeBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_PIXELS, "-activeborderwidth", "activeBorderWidth", + "BorderWidth", DEF_MENU_ACTIVE_BORDER_WIDTH, + Tk_Offset(TkMenu, activeBorderWidth), 0}, + {TK_CONFIG_COLOR, "-activeforeground", "activeForeground", "Background", + DEF_MENU_ACTIVE_FG_COLOR, Tk_Offset(TkMenu, activeFg), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-activeforeground", "activeForeground", "Background", + DEF_MENU_ACTIVE_FG_MONO, Tk_Offset(TkMenu, activeFg), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_MENU_BG_COLOR, Tk_Offset(TkMenu, border), TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_MENU_BG_MONO, Tk_Offset(TkMenu, border), TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_MENU_BORDER_WIDTH, Tk_Offset(TkMenu, borderWidth), 0}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_MENU_CURSOR, Tk_Offset(TkMenu, cursor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-disabledforeground", "disabledForeground", + "DisabledForeground", DEF_MENU_DISABLED_FG_COLOR, + Tk_Offset(TkMenu, disabledFg), TK_CONFIG_COLOR_ONLY|TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-disabledforeground", "disabledForeground", + "DisabledForeground", DEF_MENU_DISABLED_FG_MONO, + Tk_Offset(TkMenu, disabledFg), TK_CONFIG_MONO_ONLY|TK_CONFIG_NULL_OK}, + {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_FONT, "-font", "font", "Font", + DEF_MENU_FONT, Tk_Offset(TkMenu, tkfont), 0}, + {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground", + DEF_MENU_FG, Tk_Offset(TkMenu, fg), 0}, + {TK_CONFIG_STRING, "-postcommand", "postCommand", "Command", + DEF_MENU_POST_COMMAND, Tk_Offset(TkMenu, postCommand), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_MENU_RELIEF, Tk_Offset(TkMenu, relief), 0}, + {TK_CONFIG_COLOR, "-selectcolor", "selectColor", "Background", + DEF_MENU_SELECT_COLOR, Tk_Offset(TkMenu, indicatorFg), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-selectcolor", "selectColor", "Background", + DEF_MENU_SELECT_MONO, Tk_Offset(TkMenu, indicatorFg), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_MENU_TAKE_FOCUS, Tk_Offset(TkMenu, takeFocus), TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-tearoff", "tearOff", "TearOff", + DEF_MENU_TEAROFF, Tk_Offset(TkMenu, tearOff), 0}, + {TK_CONFIG_STRING, "-tearoffcommand", "tearOffCommand", "TearOffCommand", + DEF_MENU_TEAROFF_CMD, Tk_Offset(TkMenu, tearOffCommand), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-title", "title", "Title", + DEF_MENU_TITLE, Tk_Offset(TkMenu, title), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-type", "type", "Type", + DEF_MENU_TYPE, Tk_Offset(TkMenu, menuTypeName), TK_CONFIG_NULL_OK}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Prototypes for static procedures in this file: + */ + +static int CloneMenu _ANSI_ARGS_((TkMenu *menuPtr, + char *newMenuName, char *newMenuTypeString)); +static int ConfigureMenu _ANSI_ARGS_((Tcl_Interp *interp, + TkMenu *menuPtr, int argc, char **argv, + int flags)); +static int ConfigureMenuCloneEntries _ANSI_ARGS_(( + Tcl_Interp *interp, TkMenu *menuPtr, int index, + int argc, char **argv, int flags)); +static int ConfigureMenuEntry _ANSI_ARGS_((TkMenuEntry *mePtr, + int argc, char **argv, int flags)); +static void DeleteMenuCloneEntries _ANSI_ARGS_((TkMenu *menuPtr, + int first, int last)); +static void DestroyMenuHashTable _ANSI_ARGS_(( + ClientData clientData, Tcl_Interp *interp)); +static void DestroyMenuInstance _ANSI_ARGS_((TkMenu *menuPtr)); +static void DestroyMenuEntry _ANSI_ARGS_((char *memPtr)); +static int GetIndexFromCoords + _ANSI_ARGS_((Tcl_Interp *interp, TkMenu *menuPtr, + char *string, int *indexPtr)); +static int MenuDoYPosition _ANSI_ARGS_((Tcl_Interp *interp, + TkMenu *menuPtr, char *arg)); +static int MenuAddOrInsert _ANSI_ARGS_((Tcl_Interp *interp, + TkMenu *menuPtr, char *indexString, int argc, + char **argv)); +static void MenuCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static TkMenuEntry * MenuNewEntry _ANSI_ARGS_((TkMenu *menuPtr, int index, + int type)); +static char * MenuVarProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, char *name1, char *name2, + int flags)); +static int MenuWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void MenuWorldChanged _ANSI_ARGS_(( + ClientData instanceData)); +static void RecursivelyDeleteMenu _ANSI_ARGS_((TkMenu *menuPtr)); +static void UnhookCascadeEntry _ANSI_ARGS_((TkMenuEntry *mePtr)); + +/* + * The structure below is a list of procs that respond to certain window + * manager events. One of these includes a font change, which forces + * the geometry proc to be called. + */ + +static TkClassProcs menuClass = { + NULL, /* createProc. */ + MenuWorldChanged /* geometryProc. */ +}; + + + +/* + *-------------------------------------------------------------- + * + * Tk_MenuCmd -- + * + * This procedure is invoked to process the "menu" Tcl + * command. See the user documentation for details on + * what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_MenuCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + Tk_Window new; + register TkMenu *menuPtr; + TkMenuReferences *menuRefPtr; + int i, len; + char *arg, c; + int toplevel; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + TkMenuInit(); + + toplevel = 1; + for (i = 2; i < argc; i += 2) { + arg = argv[i]; + len = strlen(arg); + if (len < 2) { + continue; + } + c = arg[1]; + if ((c == 't') && (strncmp(arg, "-type", strlen(arg)) == 0) + && (len >= 3)) { + if (strcmp(argv[i + 1], "menubar") == 0) { + toplevel = 0; + } + break; + } + } + + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], toplevel ? "" + : NULL); + if (new == NULL) { + return TCL_ERROR; + } + + /* + * Initialize the data structure for the menu. + */ + + menuPtr = (TkMenu *) ckalloc(sizeof(TkMenu)); + menuPtr->tkwin = new; + menuPtr->display = Tk_Display(new); + menuPtr->interp = interp; + menuPtr->widgetCmd = Tcl_CreateCommand(interp, + Tk_PathName(menuPtr->tkwin), MenuWidgetCmd, + (ClientData) menuPtr, MenuCmdDeletedProc); + menuPtr->entries = NULL; + menuPtr->numEntries = 0; + menuPtr->active = -1; + menuPtr->border = NULL; + menuPtr->borderWidth = 0; + menuPtr->relief = TK_RELIEF_FLAT; + menuPtr->activeBorder = NULL; + menuPtr->activeBorderWidth = 0; + menuPtr->tkfont = NULL; + menuPtr->fg = NULL; + menuPtr->disabledFg = NULL; + menuPtr->activeFg = NULL; + menuPtr->indicatorFg = NULL; + menuPtr->tearOff = 1; + menuPtr->tearOffCommand = NULL; + menuPtr->cursor = None; + menuPtr->takeFocus = NULL; + menuPtr->postCommand = NULL; + menuPtr->postCommandGeneration = 0; + menuPtr->postedCascade = NULL; + menuPtr->nextInstancePtr = NULL; + menuPtr->masterMenuPtr = menuPtr; + menuPtr->menuType = UNKNOWN_TYPE; + menuPtr->menuFlags = 0; + menuPtr->parentTopLevelPtr = NULL; + menuPtr->menuTypeName = NULL; + menuPtr->title = NULL; + TkMenuInitializeDrawingFields(menuPtr); + + menuRefPtr = TkCreateMenuReferences(menuPtr->interp, + Tk_PathName(menuPtr->tkwin)); + menuRefPtr->menuPtr = menuPtr; + menuPtr->menuRefPtr = menuRefPtr; + if (TCL_OK != TkpNewMenu(menuPtr)) { + goto error; + } + + Tk_SetClass(menuPtr->tkwin, "Menu"); + TkSetClassProcs(menuPtr->tkwin, &menuClass, (ClientData) menuPtr); + Tk_CreateEventHandler(new, ExposureMask|StructureNotifyMask|ActivateMask, + TkMenuEventProc, (ClientData) menuPtr); + if (ConfigureMenu(interp, menuPtr, argc-2, argv+2, 0) != TCL_OK) { + goto error; + } + + /* + * If a menu has a parent menu pointing to it as a cascade entry, the + * parent menu needs to be told that this menu now exists so that + * the platform-part of the menu is correctly updated. + * + * If a menu has an instance and has cascade entries, then each cascade + * menu must also have a parallel instance. This is especially true on + * the Mac, where each menu has to have a separate title everytime it is in + * a menubar. For instance, say you have a menu .m1 with a cascade entry + * for .m2, where .m2 does not exist yet. You then put .m1 into a menubar. + * This creates a menubar instance for .m1, but since .m2 is not there, + * nothing else happens. When we go to create .m2, we hook it up properly + * with .m1. However, we now need to clone .m2 and assign the clone of .m2 + * to be the cascade entry for the clone of .m1. This is special case + * #1 listed in the introductory comment. + */ + + if (menuRefPtr->parentEntryPtr != NULL) { + TkMenuEntry *cascadeListPtr = menuRefPtr->parentEntryPtr; + TkMenuEntry *nextCascadePtr; + char *newMenuName; + char *newArgv[2]; + + while (cascadeListPtr != NULL) { + + nextCascadePtr = cascadeListPtr->nextCascadePtr; + + /* + * If we have a new master menu, and an existing cloned menu + * points to this menu in a cascade entry, we have to clone + * the new menu and point the entry to the clone instead + * of the menu we are creating. Otherwise, ConfigureMenuEntry + * will hook up the platform-specific cascade linkages now + * that the menu we are creating exists. + */ + + if ((menuPtr->masterMenuPtr != menuPtr) + || ((menuPtr->masterMenuPtr == menuPtr) + && ((cascadeListPtr->menuPtr->masterMenuPtr + == cascadeListPtr->menuPtr)))) { + newArgv[0] = "-menu"; + newArgv[1] = Tk_PathName(menuPtr->tkwin); + ConfigureMenuEntry(cascadeListPtr, 2, newArgv, + TK_CONFIG_ARGV_ONLY); + } else { + newMenuName = TkNewMenuName(menuPtr->interp, + Tk_PathName(cascadeListPtr->menuPtr->tkwin), + menuPtr); + CloneMenu(menuPtr, newMenuName, "normal"); + + /* + * Now we can set the new menu instance to be the cascade entry + * of the parent's instance. + */ + + newArgv[0] = "-menu"; + newArgv[1] = newMenuName; + ConfigureMenuEntry(cascadeListPtr, 2, newArgv, + TK_CONFIG_ARGV_ONLY); + if (newMenuName != NULL) { + ckfree(newMenuName); + } + } + cascadeListPtr = nextCascadePtr; + } + } + + /* + * If there already exist toplevel widgets that refer to this menu, + * find them and notify them so that they can reconfigure their + * geometry to reflect the menu. + */ + + if (menuRefPtr->topLevelListPtr != NULL) { + TkMenuTopLevelList *topLevelListPtr = menuRefPtr->topLevelListPtr; + TkMenuTopLevelList *nextPtr; + Tk_Window listtkwin; + while (topLevelListPtr != NULL) { + + /* + * Need to get the next pointer first. TkSetWindowMenuBar + * changes the list, so that the next pointer is different + * after calling it. + */ + + nextPtr = topLevelListPtr->nextPtr; + listtkwin = topLevelListPtr->tkwin; + TkSetWindowMenuBar(menuPtr->interp, listtkwin, + Tk_PathName(menuPtr->tkwin), Tk_PathName(menuPtr->tkwin)); + topLevelListPtr = nextPtr; + } + } + + interp->result = Tk_PathName(menuPtr->tkwin); + return TCL_OK; + + error: + Tk_DestroyWindow(menuPtr->tkwin); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * MenuWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a widget managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +MenuWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about menu widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register TkMenu *menuPtr = (TkMenu *) clientData; + register TkMenuEntry *mePtr; + int result = TCL_OK; + size_t length; + int c; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) menuPtr); + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'a') && (strncmp(argv[1], "activate", length) == 0) + && (length >= 2)) { + int index; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " activate index\"", (char *) NULL); + goto error; + } + if (TkGetMenuIndex(interp, menuPtr, argv[2], 0, &index) != TCL_OK) { + goto error; + } + if (menuPtr->active == index) { + goto done; + } + if (index >= 0) { + if ((menuPtr->entries[index]->type == SEPARATOR_ENTRY) + || (menuPtr->entries[index]->state == tkDisabledUid)) { + index = -1; + } + } + result = TkActivateMenuEntry(menuPtr, index); + } else if ((c == 'a') && (strncmp(argv[1], "add", length) == 0) + && (length >= 2)) { + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " add type ?options?\"", (char *) NULL); + goto error; + } + if (MenuAddOrInsert(interp, menuPtr, (char *) NULL, + argc-2, argv+2) != TCL_OK) { + goto error; + } + } else if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + goto error; + } + result = Tk_ConfigureValue(interp, menuPtr->tkwin, tkMenuConfigSpecs, + (char *) menuPtr, argv[2], 0); + } else if ((c == 'c') && (strncmp(argv[1], "clone", length) == 0) + && (length >=2)) { + if ((argc < 3) || (argc > 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " clone newMenuName ?menuType?\"", + (char *) NULL); + goto error; + } + result = CloneMenu(menuPtr, argv[2], (argc == 3) ? NULL : argv[3]); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 2)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, menuPtr->tkwin, + tkMenuConfigSpecs, (char *) menuPtr, (char *) NULL, 0); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, menuPtr->tkwin, + tkMenuConfigSpecs, (char *) menuPtr, argv[2], 0); + } else { + result = ConfigureMenu(interp, menuPtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else if ((c == 'd') && (strncmp(argv[1], "delete", length) == 0)) { + int first, last; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " delete first ?last?\"", (char *) NULL); + goto error; + } + if (TkGetMenuIndex(interp, menuPtr, argv[2], 0, &first) != TCL_OK) { + goto error; + } + if (argc == 3) { + last = first; + } else { + if (TkGetMenuIndex(interp, menuPtr, argv[3], 0, &last) != TCL_OK) { + goto error; + } + } + if (menuPtr->tearOff && (first == 0)) { + + /* + * Sorry, can't delete the tearoff entry; must reconfigure + * the menu. + */ + + first = 1; + } + if ((first < 0) || (last < first)) { + goto done; + } + DeleteMenuCloneEntries(menuPtr, first, last); + } else if ((c == 'e') && (length >= 7) + && (strncmp(argv[1], "entrycget", length) == 0)) { + int index; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " entrycget index option\"", + (char *) NULL); + goto error; + } + if (TkGetMenuIndex(interp, menuPtr, argv[2], 0, &index) != TCL_OK) { + goto error; + } + if (index < 0) { + goto done; + } + mePtr = menuPtr->entries[index]; + Tcl_Preserve((ClientData) mePtr); + result = Tk_ConfigureValue(interp, menuPtr->tkwin, + tkMenuEntryConfigSpecs, (char *) mePtr, argv[3], + COMMAND_MASK << mePtr->type); + Tcl_Release((ClientData) mePtr); + } else if ((c == 'e') && (length >= 7) + && (strncmp(argv[1], "entryconfigure", length) == 0)) { + int index; + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " entryconfigure index ?option value ...?\"", + (char *) NULL); + goto error; + } + if (TkGetMenuIndex(interp, menuPtr, argv[2], 0, &index) != TCL_OK) { + goto error; + } + if (index < 0) { + goto done; + } + mePtr = menuPtr->entries[index]; + Tcl_Preserve((ClientData) mePtr); + if (argc == 3) { + result = Tk_ConfigureInfo(interp, menuPtr->tkwin, + tkMenuEntryConfigSpecs, (char *) mePtr, (char *) NULL, + COMMAND_MASK << mePtr->type); + } else if (argc == 4) { + result = Tk_ConfigureInfo(interp, menuPtr->tkwin, + tkMenuEntryConfigSpecs, (char *) mePtr, argv[3], + COMMAND_MASK << mePtr->type); + } else { + result = ConfigureMenuCloneEntries(interp, menuPtr, index, + argc-3, argv+3, + TK_CONFIG_ARGV_ONLY | COMMAND_MASK << mePtr->type); + } + Tcl_Release((ClientData) mePtr); + } else if ((c == 'i') && (strncmp(argv[1], "index", length) == 0) + && (length >= 3)) { + int index; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " index string\"", (char *) NULL); + goto error; + } + if (TkGetMenuIndex(interp, menuPtr, argv[2], 0, &index) != TCL_OK) { + goto error; + } + if (index < 0) { + interp->result = "none"; + } else { + sprintf(interp->result, "%d", index); + } + } else if ((c == 'i') && (strncmp(argv[1], "insert", length) == 0) + && (length >= 3)) { + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " insert index type ?options?\"", (char *) NULL); + goto error; + } + if (MenuAddOrInsert(interp, menuPtr, argv[2], + argc-3, argv+3) != TCL_OK) { + goto error; + } + } else if ((c == 'i') && (strncmp(argv[1], "invoke", length) == 0) + && (length >= 3)) { + int index; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " invoke index\"", (char *) NULL); + goto error; + } + if (TkGetMenuIndex(interp, menuPtr, argv[2], 0, &index) != TCL_OK) { + goto error; + } + if (index < 0) { + goto done; + } + result = TkInvokeMenu(interp, menuPtr, index); + } else if ((c == 'p') && (strncmp(argv[1], "post", length) == 0) + && (length == 4)) { + int x, y; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " post x y\"", (char *) NULL); + goto error; + } + if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[3], &y) != TCL_OK)) { + goto error; + } + + /* + * Tearoff menus are posted differently on Mac and Windows than + * non-tearoffs. TkpPostMenu does not actually map the menu's + * window on those platforms, and popup menus have to be + * handled specially. + */ + + if (menuPtr->menuType != TEAROFF_MENU) { + result = TkpPostMenu(interp, menuPtr, x, y); + } else { + result = TkPostTearoffMenu(interp, menuPtr, x, y); + } + } else if ((c == 'p') && (strncmp(argv[1], "postcascade", length) == 0) + && (length > 4)) { + int index; + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " postcascade index\"", (char *) NULL); + goto error; + } + if (TkGetMenuIndex(interp, menuPtr, argv[2], 0, &index) != TCL_OK) { + goto error; + } + if ((index < 0) || (menuPtr->entries[index]->type != CASCADE_ENTRY)) { + result = TkPostSubmenu(interp, menuPtr, (TkMenuEntry *) NULL); + } else { + result = TkPostSubmenu(interp, menuPtr, menuPtr->entries[index]); + } + } else if ((c == 't') && (strncmp(argv[1], "type", length) == 0)) { + int index; + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " type index\"", (char *) NULL); + goto error; + } + if (TkGetMenuIndex(interp, menuPtr, argv[2], 0, &index) != TCL_OK) { + goto error; + } + if (index < 0) { + goto done; + } + mePtr = menuPtr->entries[index]; + switch (mePtr->type) { + case COMMAND_ENTRY: + interp->result = "command"; + break; + case SEPARATOR_ENTRY: + interp->result = "separator"; + break; + case CHECK_BUTTON_ENTRY: + interp->result = "checkbutton"; + break; + case RADIO_BUTTON_ENTRY: + interp->result = "radiobutton"; + break; + case CASCADE_ENTRY: + interp->result = "cascade"; + break; + case TEAROFF_ENTRY: + interp->result = "tearoff"; + break; + } + } else if ((c == 'u') && (strncmp(argv[1], "unpost", length) == 0)) { + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " unpost\"", (char *) NULL); + goto error; + } + Tk_UnmapWindow(menuPtr->tkwin); + result = TkPostSubmenu(interp, menuPtr, (TkMenuEntry *) NULL); + } else if ((c == 'y') && (strncmp(argv[1], "yposition", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " yposition index\"", (char *) NULL); + goto error; + } + result = MenuDoYPosition(interp, menuPtr, argv[2]); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be activate, add, cget, clone, configure, delete, ", + "entrycget, entryconfigure, index, insert, invoke, ", + "post, postcascade, type, unpost, or yposition", + (char *) NULL); + goto error; + } + done: + Tcl_Release((ClientData) menuPtr); + return result; + + error: + Tcl_Release((ClientData) menuPtr); + return TCL_ERROR; +} + + +/* + *---------------------------------------------------------------------- + * + * TkInvokeMenu -- + * + * Given a menu and an index, takes the appropriate action for the + * entry associated with that index. + * + * Results: + * Standard Tcl result. + * + * Side effects: + * Commands may get excecuted; variables may get set; sub-menus may + * get posted. + * + *---------------------------------------------------------------------- + */ + +int +TkInvokeMenu(interp, menuPtr, index) + Tcl_Interp *interp; /* The interp that the menu lives in. */ + TkMenu *menuPtr; /* The menu we are invoking. */ + int index; /* The zero based index of the item we + * are invoking */ +{ + int result = TCL_OK; + TkMenuEntry *mePtr; + + if (index < 0) { + goto done; + } + mePtr = menuPtr->entries[index]; + if (mePtr->state == tkDisabledUid) { + goto done; + } + Tcl_Preserve((ClientData) mePtr); + if (mePtr->type == TEAROFF_ENTRY) { + Tcl_DString commandDString; + + Tcl_DStringInit(&commandDString); + Tcl_DStringAppendElement(&commandDString, "tkTearOffMenu"); + Tcl_DStringAppendElement(&commandDString, Tk_PathName(menuPtr->tkwin)); + result = Tcl_Eval(interp, Tcl_DStringValue(&commandDString)); + Tcl_DStringFree(&commandDString); + } else if (mePtr->type == CHECK_BUTTON_ENTRY) { + if (mePtr->entryFlags & ENTRY_SELECTED) { + if (Tcl_SetVar(interp, mePtr->name, mePtr->offValue, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + result = TCL_ERROR; + } + } else { + if (Tcl_SetVar(interp, mePtr->name, mePtr->onValue, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + result = TCL_ERROR; + } + } + } else if (mePtr->type == RADIO_BUTTON_ENTRY) { + if (Tcl_SetVar(interp, mePtr->name, mePtr->onValue, + TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { + result = TCL_ERROR; + } + } + if ((result == TCL_OK) && (mePtr->command != NULL)) { + result = TkCopyAndGlobalEval(interp, mePtr->command); + } + Tcl_Release((ClientData) mePtr); + done: + return result; +} + + + +/* + *---------------------------------------------------------------------- + * + * DestroyMenuInstance -- + * + * This procedure is invoked by TkDestroyMenu + * to clean up the internal structure of a menu at a safe time + * (when no-one is using it anymore). Only takes care of one instance + * of the menu. + * + * Results: + * None. + * + * Side effects: + * Everything associated with the menu is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyMenuInstance(menuPtr) + TkMenu *menuPtr; /* Info about menu widget. */ +{ + int i, numEntries = menuPtr->numEntries; + TkMenu *menuInstancePtr; + TkMenuEntry *cascadePtr, *nextCascadePtr; + char *newArgv[2]; + TkMenu *parentMasterMenuPtr; + TkMenuEntry *parentMasterEntryPtr; + TkMenu *parentMenuPtr; + + /* + * If the menu has any cascade menu entries pointing to it, the cascade + * entries need to be told that the menu is going away. We need to clear + * the menu ptr field in the menu reference at this point in the code + * so that everything else can forget about this menu properly. We also + * need to reset -menu field of all entries that are not master menus + * back to this entry name if this is a master menu pointed to by another + * master menu. If there is a clone menu that points to this menu, + * then this menu is itself a clone, so when this menu goes away, + * the -menu field of the pointing entry must be set back to this + * menu's master menu name so that later if another menu is created + * the cascade hierarchy can be maintained. + */ + + TkpDestroyMenu(menuPtr); + cascadePtr = menuPtr->menuRefPtr->parentEntryPtr; + menuPtr->menuRefPtr->menuPtr = NULL; + TkFreeMenuReferences(menuPtr->menuRefPtr); + + for (; cascadePtr != NULL; cascadePtr = nextCascadePtr) { + parentMenuPtr = cascadePtr->menuPtr; + nextCascadePtr = cascadePtr->nextCascadePtr; + + if (menuPtr->masterMenuPtr != menuPtr) { + parentMasterMenuPtr = cascadePtr->menuPtr->masterMenuPtr; + parentMasterEntryPtr = + parentMasterMenuPtr->entries[cascadePtr->index]; + newArgv[0] = "-menu"; + newArgv[1] = parentMasterEntryPtr->name; + ConfigureMenuEntry(cascadePtr, 2, newArgv, TK_CONFIG_ARGV_ONLY); + } else { + ConfigureMenuEntry(cascadePtr, 0, (char **) NULL, 0); + } + } + + if (menuPtr->masterMenuPtr != menuPtr) { + for (menuInstancePtr = menuPtr->masterMenuPtr; + menuInstancePtr != NULL; + menuInstancePtr = menuInstancePtr->nextInstancePtr) { + if (menuInstancePtr->nextInstancePtr == menuPtr) { + menuInstancePtr->nextInstancePtr = + menuInstancePtr->nextInstancePtr->nextInstancePtr; + break; + } + } + } else if (menuPtr->nextInstancePtr != NULL) { + panic("Attempting to delete master menu when there are still clones."); + } + + /* + * Free up all the stuff that requires special handling, then + * let Tk_FreeOptions handle all the standard option-related + * stuff. + */ + + for (i = numEntries - 1; i >= 0; i--) { + DestroyMenuEntry((char *) menuPtr->entries[i]); + } + if (menuPtr->entries != NULL) { + ckfree((char *) menuPtr->entries); + } + TkMenuFreeDrawOptions(menuPtr); + Tk_FreeOptions(tkMenuConfigSpecs, (char *) menuPtr, menuPtr->display, 0); + + Tcl_EventuallyFree((ClientData) menuPtr, TCL_DYNAMIC); +} + +/* + *---------------------------------------------------------------------- + * + * TkDestroyMenu -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a menu at a safe time + * (when no-one is using it anymore). If called on a master instance, + * destroys all of the slave instances. If called on a non-master + * instance, just destroys that instance. + * + * Results: + * None. + * + * Side effects: + * Everything associated with the menu is freed up. + * + *---------------------------------------------------------------------- + */ + +void +TkDestroyMenu(menuPtr) + TkMenu *menuPtr; /* Info about menu widget. */ +{ + TkMenu *menuInstancePtr; + TkMenuTopLevelList *topLevelListPtr, *nextTopLevelPtr; + + if (menuPtr->menuFlags & MENU_DELETION_PENDING) { + return; + } + + /* + * Now destroy all non-tearoff instances of this menu if this is a + * parent menu. Is this loop safe enough? Are there going to be + * destroy bindings on child menus which kill the parent? If not, + * we have to do a slightly more complex scheme. + */ + + if (menuPtr->masterMenuPtr == menuPtr) { + menuPtr->menuFlags |= MENU_DELETION_PENDING; + while (menuPtr->nextInstancePtr != NULL) { + menuInstancePtr = menuPtr->nextInstancePtr; + menuPtr->nextInstancePtr = menuInstancePtr->nextInstancePtr; + if (menuInstancePtr->tkwin != NULL) { + Tk_DestroyWindow(menuInstancePtr->tkwin); + } + } + menuPtr->menuFlags &= ~MENU_DELETION_PENDING; + } + + /* + * If any toplevel widgets have this menu as their menubar, + * the geometry of the window may have to be recalculated. + */ + + topLevelListPtr = menuPtr->menuRefPtr->topLevelListPtr; + while (topLevelListPtr != NULL) { + nextTopLevelPtr = topLevelListPtr->nextPtr; + TkpSetWindowMenuBar(topLevelListPtr->tkwin, NULL); + topLevelListPtr = nextTopLevelPtr; + } + DestroyMenuInstance(menuPtr); +} + +/* + *---------------------------------------------------------------------- + * + * UnhookCascadeEntry -- + * + * This entry is removed from the list of entries that point to the + * cascade menu. This is done in preparation for changing the menu + * that this entry points to. + * + * Results: + * None + * + * Side effects: + * The appropriate lists are modified. + * + *---------------------------------------------------------------------- + */ + +static void +UnhookCascadeEntry(mePtr) + TkMenuEntry *mePtr; /* The cascade entry we are removing + * from the cascade list. */ +{ + TkMenuEntry *cascadeEntryPtr; + TkMenuEntry *prevCascadePtr; + TkMenuReferences *menuRefPtr; + + menuRefPtr = mePtr->childMenuRefPtr; + if (menuRefPtr == NULL) { + return; + } + + cascadeEntryPtr = menuRefPtr->parentEntryPtr; + if (cascadeEntryPtr == NULL) { + return; + } + + /* + * Singularly linked list deletion. The two special cases are + * 1. one element; 2. The first element is the one we want. + */ + + if (cascadeEntryPtr == mePtr) { + if (cascadeEntryPtr->nextCascadePtr == NULL) { + + /* + * This is the last menu entry which points to this + * menu, so we need to clear out the list pointer in the + * cascade itself. + */ + + menuRefPtr->parentEntryPtr = NULL; + TkFreeMenuReferences(menuRefPtr); + } else { + menuRefPtr->parentEntryPtr = cascadeEntryPtr->nextCascadePtr; + } + mePtr->nextCascadePtr = NULL; + } else { + for (prevCascadePtr = cascadeEntryPtr, + cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr; + cascadeEntryPtr != NULL; + prevCascadePtr = cascadeEntryPtr, + cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr) { + if (cascadeEntryPtr == mePtr){ + prevCascadePtr->nextCascadePtr = + cascadeEntryPtr->nextCascadePtr; + cascadeEntryPtr->nextCascadePtr = NULL; + break; + } + } + } + mePtr->childMenuRefPtr = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyMenuEntry -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a menu entry at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the menu entry is freed. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyMenuEntry(memPtr) + char *memPtr; /* Pointer to entry to be freed. */ +{ + register TkMenuEntry *mePtr = (TkMenuEntry *) memPtr; + TkMenu *menuPtr = mePtr->menuPtr; + + if (menuPtr->postedCascade == mePtr) { + + /* + * Ignore errors while unposting the menu, since it's possible + * that the menu has already been deleted and the unpost will + * generate an error. + */ + + TkPostSubmenu(menuPtr->interp, menuPtr, (TkMenuEntry *) NULL); + } + + /* + * Free up all the stuff that requires special handling, then + * let Tk_FreeOptions handle all the standard option-related + * stuff. + */ + + if (mePtr->type == CASCADE_ENTRY) { + UnhookCascadeEntry(mePtr); + } + if (mePtr->image != NULL) { + Tk_FreeImage(mePtr->image); + } + if (mePtr->selectImage != NULL) { + Tk_FreeImage(mePtr->selectImage); + } + if (mePtr->name != NULL) { + Tcl_UntraceVar(menuPtr->interp, mePtr->name, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuVarProc, (ClientData) mePtr); + } + TkpDestroyMenuEntry(mePtr); + TkMenuEntryFreeDrawOptions(mePtr); + Tk_FreeOptions(tkMenuEntryConfigSpecs, (char *) mePtr, menuPtr->display, + (COMMAND_MASK << mePtr->type)); + ckfree((char *) mePtr); +} + +/* + *--------------------------------------------------------------------------- + * + * MenuWorldChanged -- + * + * This procedure is called when the world has changed in some + * way (such as the fonts in the system changing) and the widget needs + * to recompute all its graphics contexts and determine its new geometry. + * + * Results: + * None. + * + * Side effects: + * Menu will be relayed out and redisplayed. + * + *--------------------------------------------------------------------------- + */ + +static void +MenuWorldChanged(instanceData) + ClientData instanceData; /* Information about widget. */ +{ + TkMenu *menuPtr = (TkMenu *) instanceData; + int i; + + TkMenuConfigureDrawOptions(menuPtr); + for (i = 0; i < menuPtr->numEntries; i++) { + TkMenuConfigureEntryDrawOptions(menuPtr->entries[i], + menuPtr->entries[i]->index); + TkpConfigureMenuEntry(menuPtr->entries[i]); + } +} + + +/* + *---------------------------------------------------------------------- + * + * ConfigureMenu -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or + * reconfigure) a menu widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as colors, font, etc. get set + * for menuPtr; old resources get freed, if there were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureMenu(interp, menuPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + register TkMenu *menuPtr; /* Information about widget; may or may + * not already have values for some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + int i; + TkMenu* menuListPtr; + + for (menuListPtr = menuPtr->masterMenuPtr; menuListPtr != NULL; + menuListPtr = menuListPtr->nextInstancePtr) { + + if (Tk_ConfigureWidget(interp, menuListPtr->tkwin, + tkMenuConfigSpecs, argc, argv, (char *) menuListPtr, + flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * When a menu is created, the type is in all of the arguments + * to the menu command. Let Tk_ConfigureWidget take care of + * parsing them, and then set the type after we can look at + * the type string. Once set, a menu's type cannot be changed + */ + + if (menuListPtr->menuType == UNKNOWN_TYPE) { + if (strcmp(menuListPtr->menuTypeName, "menubar") == 0) { + menuListPtr->menuType = MENUBAR; + } else if (strcmp(menuListPtr->menuTypeName, "tearoff") == 0) { + menuListPtr->menuType = TEAROFF_MENU; + } else { + menuListPtr->menuType = MASTER_MENU; + } + } + + /* + * Depending on the -tearOff option, make sure that there is or + * isn't an initial tear-off entry at the beginning of the menu. + */ + + if (menuListPtr->tearOff) { + if ((menuListPtr->numEntries == 0) + || (menuListPtr->entries[0]->type != TEAROFF_ENTRY)) { + if (MenuNewEntry(menuListPtr, 0, TEAROFF_ENTRY) == NULL) { + return TCL_ERROR; + } + } + } else if ((menuListPtr->numEntries > 0) + && (menuListPtr->entries[0]->type == TEAROFF_ENTRY)) { + int i; + + Tcl_EventuallyFree((ClientData) menuListPtr->entries[0], + DestroyMenuEntry); + for (i = 0; i < menuListPtr->numEntries - 1; i++) { + menuListPtr->entries[i] = menuListPtr->entries[i + 1]; + menuListPtr->entries[i]->index = i; + } + menuListPtr->numEntries--; + if (menuListPtr->numEntries == 0) { + ckfree((char *) menuListPtr->entries); + menuListPtr->entries = NULL; + } + } + + TkMenuConfigureDrawOptions(menuListPtr); + + /* + * Configure the new window to be either a pop-up menu + * or a tear-off menu. + * We don't do this for menubars since they are not toplevel + * windows. Also, since this gets called before CloneMenu has + * a chance to set the menuType field, we have to look at the + * menuTypeName field to tell that this is a menu bar. + */ + + if (strcmp(menuListPtr->menuTypeName, "normal") == 0) { + TkpMakeMenuWindow(menuListPtr->tkwin, 1); + } else if (strcmp(menuListPtr->menuTypeName, "tearoff") == 0) { + TkpMakeMenuWindow(menuListPtr->tkwin, 0); + } + + /* + * After reconfiguring a menu, we need to reconfigure all of the + * entries in the menu, since some of the things in the children + * (such as graphics contexts) may have to change to reflect changes + * in the parent. + */ + + for (i = 0; i < menuListPtr->numEntries; i++) { + TkMenuEntry *mePtr; + + mePtr = menuListPtr->entries[i]; + ConfigureMenuEntry(mePtr, 0, + (char **) NULL, TK_CONFIG_ARGV_ONLY + | COMMAND_MASK << mePtr->type); + } + + TkEventuallyRecomputeMenu(menuListPtr); + } + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureMenuEntry -- + * + * This procedure is called to process an argv/argc list in order + * to configure (or reconfigure) one entry in a menu. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information such as label and accelerator get + * set for mePtr; old resources get freed, if there were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureMenuEntry(mePtr, argc, argv, flags) + register TkMenuEntry *mePtr; /* Information about menu entry; may + * or may not already have values for + * some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Additional flags to pass to + * Tk_ConfigureWidget. */ +{ + TkMenu *menuPtr = mePtr->menuPtr; + int index = mePtr->index; + Tk_Image image; + + /* + * If this entry is a check button or radio button, then remove + * its old trace procedure. + */ + + if ((mePtr->name != NULL) + && ((mePtr->type == CHECK_BUTTON_ENTRY) + || (mePtr->type == RADIO_BUTTON_ENTRY))) { + Tcl_UntraceVar(menuPtr->interp, mePtr->name, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuVarProc, (ClientData) mePtr); + } + + if (menuPtr->tkwin != NULL) { + if (Tk_ConfigureWidget(menuPtr->interp, menuPtr->tkwin, + tkMenuEntryConfigSpecs, argc, argv, (char *) mePtr, + flags | (COMMAND_MASK << mePtr->type)) != TCL_OK) { + return TCL_ERROR; + } + } + + /* + * The code below handles special configuration stuff not taken + * care of by Tk_ConfigureWidget, such as special processing for + * defaults, sizing strings, graphics contexts, etc. + */ + + if (mePtr->label == NULL) { + mePtr->labelLength = 0; + } else { + mePtr->labelLength = strlen(mePtr->label); + } + if (mePtr->accel == NULL) { + mePtr->accelLength = 0; + } else { + mePtr->accelLength = strlen(mePtr->accel); + } + + /* + * If this is a cascade entry, the platform-specific data of the child + * menu has to be updated. Also, the links that point to parents and + * cascades have to be updated. + */ + + if ((mePtr->type == CASCADE_ENTRY) && (mePtr->name != NULL)) { + TkMenuEntry *cascadeEntryPtr; + TkMenu *cascadeMenuPtr; + int alreadyThere; + TkMenuReferences *menuRefPtr; + char *oldHashKey = NULL; /* Initialization only needed to + * prevent compiler warning. */ + + /* + * This is a cascade entry. If the menu that the cascade entry + * is pointing to has changed, we need to remove this entry + * from the list of entries pointing to the old menu, and add a + * cascade reference to the list of entries pointing to the + * new menu. + * + * BUG: We are not recloning for special case #3 yet. + */ + + if (mePtr->childMenuRefPtr != NULL) { + oldHashKey = Tcl_GetHashKey(TkGetMenuHashTable(menuPtr->interp), + mePtr->childMenuRefPtr->hashEntryPtr); + if (strcmp(oldHashKey, mePtr->name) != 0) { + UnhookCascadeEntry(mePtr); + } + } + + if ((mePtr->childMenuRefPtr == NULL) + || (strcmp(oldHashKey, mePtr->name) != 0)) { + menuRefPtr = TkCreateMenuReferences(menuPtr->interp, + mePtr->name); + cascadeMenuPtr = menuRefPtr->menuPtr; + mePtr->childMenuRefPtr = menuRefPtr; + + if (menuRefPtr->parentEntryPtr == NULL) { + menuRefPtr->parentEntryPtr = mePtr; + } else { + alreadyThere = 0; + for (cascadeEntryPtr = menuRefPtr->parentEntryPtr; + cascadeEntryPtr != NULL; + cascadeEntryPtr = + cascadeEntryPtr->nextCascadePtr) { + if (cascadeEntryPtr == mePtr) { + alreadyThere = 1; + break; + } + } + + /* + * Put the item at the front of the list. + */ + + if (!alreadyThere) { + mePtr->nextCascadePtr = menuRefPtr->parentEntryPtr; + menuRefPtr->parentEntryPtr = mePtr; + } + } + } + } + + if (TkMenuConfigureEntryDrawOptions(mePtr, index) != TCL_OK) { + return TCL_ERROR; + } + + if (TkpConfigureMenuEntry(mePtr) != TCL_OK) { + return TCL_ERROR; + } + + if ((mePtr->type == CHECK_BUTTON_ENTRY) + || (mePtr->type == RADIO_BUTTON_ENTRY)) { + char *value; + + if (mePtr->name == NULL) { + mePtr->name = + (char *) ckalloc((unsigned) (mePtr->labelLength + 1)); + strcpy(mePtr->name, (mePtr->label == NULL) ? "" : mePtr->label); + } + if (mePtr->onValue == NULL) { + mePtr->onValue = (char *) ckalloc((unsigned) + (mePtr->labelLength + 1)); + strcpy(mePtr->onValue, (mePtr->label == NULL) ? "" : mePtr->label); + } + + /* + * Select the entry if the associated variable has the + * appropriate value, initialize the variable if it doesn't + * exist, then set a trace on the variable to monitor future + * changes to its value. + */ + + value = Tcl_GetVar(menuPtr->interp, mePtr->name, TCL_GLOBAL_ONLY); + mePtr->entryFlags &= ~ENTRY_SELECTED; + if (value != NULL) { + if (strcmp(value, mePtr->onValue) == 0) { + mePtr->entryFlags |= ENTRY_SELECTED; + } + } else { + Tcl_SetVar(menuPtr->interp, mePtr->name, + (mePtr->type == CHECK_BUTTON_ENTRY) ? mePtr->offValue : "", + TCL_GLOBAL_ONLY); + } + Tcl_TraceVar(menuPtr->interp, mePtr->name, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuVarProc, (ClientData) mePtr); + } + + /* + * Get the images for the entry, if there are any. Allocate the + * new images before freeing the old ones, so that the reference + * counts don't go to zero and cause image data to be discarded. + */ + + if (mePtr->imageString != NULL) { + image = Tk_GetImage(menuPtr->interp, menuPtr->tkwin, mePtr->imageString, + TkMenuImageProc, (ClientData) mePtr); + if (image == NULL) { + return TCL_ERROR; + } + } else { + image = NULL; + } + if (mePtr->image != NULL) { + Tk_FreeImage(mePtr->image); + } + mePtr->image = image; + if (mePtr->selectImageString != NULL) { + image = Tk_GetImage(menuPtr->interp, menuPtr->tkwin, mePtr->selectImageString, + TkMenuSelectImageProc, (ClientData) mePtr); + if (image == NULL) { + return TCL_ERROR; + } + } else { + image = NULL; + } + if (mePtr->selectImage != NULL) { + Tk_FreeImage(mePtr->selectImage); + } + mePtr->selectImage = image; + + TkEventuallyRecomputeMenu(menuPtr); + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureMenuCloneEntries -- + * + * Calls ConfigureMenuEntry for each menu in the clone chain. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information such as label and accelerator get + * set for mePtr; old resources get freed, if there were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureMenuCloneEntries(interp, menuPtr, index, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + TkMenu *menuPtr; /* Information about whole menu. */ + int index; /* Index of mePtr within menuPtr's + * entries. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Additional flags to pass to + * Tk_ConfigureWidget. */ +{ + TkMenuEntry *mePtr; + TkMenu *menuListPtr; + char *oldCascadeName = NULL, *newMenuName = NULL; + int cascadeEntryChanged; + TkMenuReferences *oldCascadeMenuRefPtr, *cascadeMenuRefPtr = NULL; + + /* + * Cascades are kind of tricky here. This is special case #3 in the comment + * at the top of this file. Basically, if a menu is the master menu of a + * clone chain, and has an entry with a cascade menu, the clones of + * the menu will point to clones of the cascade menu. We have + * to destroy the clones of the cascades, clone the new cascade + * menu, and configure the entry to point to the new clone. + */ + + mePtr = menuPtr->masterMenuPtr->entries[index]; + if (mePtr->type == CASCADE_ENTRY) { + oldCascadeName = mePtr->name; + } + + if (ConfigureMenuEntry(mePtr, argc, argv, flags) != TCL_OK) { + return TCL_ERROR; + } + + cascadeEntryChanged = (mePtr->type == CASCADE_ENTRY) + && (oldCascadeName != mePtr->name); + + if (cascadeEntryChanged) { + newMenuName = mePtr->name; + if (newMenuName != NULL) { + cascadeMenuRefPtr = TkFindMenuReferences(menuPtr->interp, + mePtr->name); + } + } + + for (menuListPtr = menuPtr->masterMenuPtr->nextInstancePtr; + menuListPtr != NULL; + menuListPtr = menuListPtr->nextInstancePtr) { + + mePtr = menuListPtr->entries[index]; + + if (cascadeEntryChanged && (mePtr->name != NULL)) { + oldCascadeMenuRefPtr = TkFindMenuReferences(menuPtr->interp, + mePtr->name); + + if ((oldCascadeMenuRefPtr != NULL) + && (oldCascadeMenuRefPtr->menuPtr != NULL)) { + RecursivelyDeleteMenu(oldCascadeMenuRefPtr->menuPtr); + } + } + + if (ConfigureMenuEntry(mePtr, argc, argv, flags) != TCL_OK) { + return TCL_ERROR; + } + + if (cascadeEntryChanged && (newMenuName != NULL)) { + if (cascadeMenuRefPtr->menuPtr != NULL) { + char *newArgV[2]; + char *newCloneName; + + newCloneName = TkNewMenuName(menuPtr->interp, + Tk_PathName(menuListPtr->tkwin), + cascadeMenuRefPtr->menuPtr); + CloneMenu(cascadeMenuRefPtr->menuPtr, newCloneName, + "normal"); + + newArgV[0] = "-menu"; + newArgV[1] = newCloneName; + ConfigureMenuEntry(mePtr, 2, newArgV, flags); + ckfree(newCloneName); + } + } + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * TkGetMenuIndex -- + * + * Parse a textual index into a menu and return the numerical + * index of the indicated entry. + * + * Results: + * A standard Tcl result. If all went well, then *indexPtr is + * filled in with the entry index corresponding to string + * (ranges from -1 to the number of entries in the menu minus + * one). Otherwise an error message is left in interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkGetMenuIndex(interp, menuPtr, string, lastOK, indexPtr) + Tcl_Interp *interp; /* For error messages. */ + TkMenu *menuPtr; /* Menu for which the index is being + * specified. */ + char *string; /* Specification of an entry in menu. See + * manual entry for valid .*/ + int lastOK; /* Non-zero means its OK to return index + * just *after* last entry. */ + int *indexPtr; /* Where to store converted relief. */ +{ + int i; + + if ((string[0] == 'a') && (strcmp(string, "active") == 0)) { + *indexPtr = menuPtr->active; + return TCL_OK; + } + + if (((string[0] == 'l') && (strcmp(string, "last") == 0)) + || ((string[0] == 'e') && (strcmp(string, "end") == 0))) { + *indexPtr = menuPtr->numEntries - ((lastOK) ? 0 : 1); + return TCL_OK; + } + + if ((string[0] == 'n') && (strcmp(string, "none") == 0)) { + *indexPtr = -1; + return TCL_OK; + } + + if (string[0] == '@') { + if (GetIndexFromCoords(interp, menuPtr, string, indexPtr) + == TCL_OK) { + return TCL_OK; + } + } + + if (isdigit(UCHAR(string[0]))) { + if (Tcl_GetInt(interp, string, &i) == TCL_OK) { + if (i >= menuPtr->numEntries) { + if (lastOK) { + i = menuPtr->numEntries; + } else { + i = menuPtr->numEntries-1; + } + } else if (i < 0) { + i = -1; + } + *indexPtr = i; + return TCL_OK; + } + Tcl_SetResult(interp, (char *) NULL, TCL_STATIC); + } + + for (i = 0; i < menuPtr->numEntries; i++) { + char *label; + + label = menuPtr->entries[i]->label; + if ((label != NULL) + && (Tcl_StringMatch(menuPtr->entries[i]->label, string))) { + *indexPtr = i; + return TCL_OK; + } + } + + Tcl_AppendResult(interp, "bad menu entry index \"", + string, "\"", (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * MenuCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +MenuCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + TkMenu *menuPtr = (TkMenu *) clientData; + Tk_Window tkwin = menuPtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + menuPtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *---------------------------------------------------------------------- + * + * MenuNewEntry -- + * + * This procedure allocates and initializes a new menu entry. + * + * Results: + * The return value is a pointer to a new menu entry structure, + * which has been malloc-ed, initialized, and entered into the + * entry array for the menu. + * + * Side effects: + * Storage gets allocated. + * + *---------------------------------------------------------------------- + */ + +static TkMenuEntry * +MenuNewEntry(menuPtr, index, type) + TkMenu *menuPtr; /* Menu that will hold the new entry. */ + int index; /* Where in the menu the new entry is to + * go. */ + int type; /* The type of the new entry. */ +{ + TkMenuEntry *mePtr; + TkMenuEntry **newEntries; + int i; + + /* + * Create a new array of entries with an empty slot for the + * new entry. + */ + + newEntries = (TkMenuEntry **) ckalloc((unsigned) + ((menuPtr->numEntries+1)*sizeof(TkMenuEntry *))); + for (i = 0; i < index; i++) { + newEntries[i] = menuPtr->entries[i]; + } + for ( ; i < menuPtr->numEntries; i++) { + newEntries[i+1] = menuPtr->entries[i]; + newEntries[i+1]->index = i + 1; + } + if (menuPtr->numEntries != 0) { + ckfree((char *) menuPtr->entries); + } + menuPtr->entries = newEntries; + menuPtr->numEntries++; + mePtr = (TkMenuEntry *) ckalloc(sizeof(TkMenuEntry)); + menuPtr->entries[index] = mePtr; + mePtr->type = type; + mePtr->menuPtr = menuPtr; + mePtr->label = NULL; + mePtr->labelLength = 0; + mePtr->underline = -1; + mePtr->bitmap = None; + mePtr->imageString = NULL; + mePtr->image = NULL; + mePtr->selectImageString = NULL; + mePtr->selectImage = NULL; + mePtr->accel = NULL; + mePtr->accelLength = 0; + mePtr->state = tkNormalUid; + mePtr->border = NULL; + mePtr->fg = NULL; + mePtr->activeBorder = NULL; + mePtr->activeFg = NULL; + mePtr->tkfont = NULL; + mePtr->indicatorOn = 1; + mePtr->indicatorFg = NULL; + mePtr->columnBreak = 0; + mePtr->hideMargin = 0; + mePtr->command = NULL; + mePtr->name = NULL; + mePtr->childMenuRefPtr = NULL; + mePtr->onValue = NULL; + mePtr->offValue = NULL; + mePtr->entryFlags = 0; + mePtr->index = index; + mePtr->nextCascadePtr = NULL; + TkMenuInitializeEntryDrawingFields(mePtr); + if (TkpMenuNewEntry(mePtr) != TCL_OK) { + ckfree((char *) mePtr); + return NULL; + } + + return mePtr; +} + +/* + *---------------------------------------------------------------------- + * + * MenuAddOrInsert -- + * + * This procedure does all of the work of the "add" and "insert" + * widget commands, allowing the code for these to be shared. + * + * Results: + * A standard Tcl return value. + * + * Side effects: + * A new menu entry is created in menuPtr. + * + *---------------------------------------------------------------------- + */ + +static int +MenuAddOrInsert(interp, menuPtr, indexString, argc, argv) + Tcl_Interp *interp; /* Used for error reporting. */ + TkMenu *menuPtr; /* Widget in which to create new + * entry. */ + char *indexString; /* String describing index at which + * to insert. NULL means insert at + * end. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Arguments to command: first arg + * is type of entry, others are + * config options. */ +{ + int c, type, index; + size_t length; + TkMenuEntry *mePtr; + TkMenu *menuListPtr; + + if (indexString != NULL) { + if (TkGetMenuIndex(interp, menuPtr, indexString, 1, &index) + != TCL_OK) { + return TCL_ERROR; + } + } else { + index = menuPtr->numEntries; + } + if (index < 0) { + Tcl_AppendResult(interp, "bad index \"", indexString, "\"", + (char *) NULL); + return TCL_ERROR; + } + if (menuPtr->tearOff && (index == 0)) { + index = 1; + } + + /* + * Figure out the type of the new entry. + */ + + c = argv[0][0]; + length = strlen(argv[0]); + if ((c == 'c') && (strncmp(argv[0], "cascade", length) == 0) + && (length >= 2)) { + type = CASCADE_ENTRY; + } else if ((c == 'c') && (strncmp(argv[0], "checkbutton", length) == 0) + && (length >= 2)) { + type = CHECK_BUTTON_ENTRY; + } else if ((c == 'c') && (strncmp(argv[0], "command", length) == 0) + && (length >= 2)) { + type = COMMAND_ENTRY; + } else if ((c == 'r') + && (strncmp(argv[0], "radiobutton", length) == 0)) { + type = RADIO_BUTTON_ENTRY; + } else if ((c == 's') + && (strncmp(argv[0], "separator", length) == 0)) { + type = SEPARATOR_ENTRY; + } else { + Tcl_AppendResult(interp, "bad menu entry type \"", + argv[0], "\": must be cascade, checkbutton, ", + "command, radiobutton, or separator", (char *) NULL); + return TCL_ERROR; + } + + /* + * Now we have to add an entry for every instance related to this menu. + */ + + for (menuListPtr = menuPtr->masterMenuPtr; menuListPtr != NULL; + menuListPtr = menuListPtr->nextInstancePtr) { + + mePtr = MenuNewEntry(menuListPtr, index, type); + if (mePtr == NULL) { + return TCL_ERROR; + } + if (ConfigureMenuEntry(mePtr, argc-1, argv+1, 0) != TCL_OK) { + TkMenu *errorMenuPtr; + int i; + + for (errorMenuPtr = menuPtr->masterMenuPtr; + errorMenuPtr != NULL; + errorMenuPtr = errorMenuPtr->nextInstancePtr) { + Tcl_EventuallyFree((ClientData) errorMenuPtr->entries[index], + DestroyMenuEntry); + for (i = index; i < errorMenuPtr->numEntries - 1; i++) { + errorMenuPtr->entries[i] = errorMenuPtr->entries[i + 1]; + errorMenuPtr->entries[i]->index = i; + } + errorMenuPtr->numEntries--; + if (errorMenuPtr->numEntries == 0) { + ckfree((char *) errorMenuPtr->entries); + errorMenuPtr->entries = NULL; + } + if (errorMenuPtr == menuListPtr) { + break; + } + } + return TCL_ERROR; + } + + /* + * If a menu has cascades, then every instance of the menu has + * to have its own parallel cascade structure. So adding an + * entry to a menu with clones means that the menu that the + * entry points to has to be cloned for every clone the + * master menu has. This is special case #2 in the comment + * at the top of this file. + */ + + if ((menuPtr != menuListPtr) && (type == CASCADE_ENTRY)) { + if ((mePtr->name != NULL) && (mePtr->childMenuRefPtr != NULL) + && (mePtr->childMenuRefPtr->menuPtr != NULL)) { + TkMenu *cascadeMenuPtr = + mePtr->childMenuRefPtr->menuPtr->masterMenuPtr; + char *newCascadeName; + char *newArgv[2]; + TkMenuReferences *menuRefPtr; + + newCascadeName = TkNewMenuName(menuListPtr->interp, + Tk_PathName(menuListPtr->tkwin), + cascadeMenuPtr); + CloneMenu(cascadeMenuPtr, newCascadeName, "normal"); + + menuRefPtr = TkFindMenuReferences(menuListPtr->interp, + newCascadeName); + if (menuRefPtr == NULL) { + panic("CloneMenu failed inside of MenuAddOrInsert."); + } + newArgv[0] = "-menu"; + newArgv[1] = newCascadeName; + ConfigureMenuEntry(mePtr, 2, newArgv, 0); + ckfree(newCascadeName); + } + } + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * MenuVarProc -- + * + * This procedure is invoked when someone changes the + * state variable associated with a radiobutton or checkbutton + * menu entry. The entry's selected state is set to match + * the value of the variable. + * + * Results: + * NULL is always returned. + * + * Side effects: + * The menu entry may become selected or deselected. + * + *-------------------------------------------------------------- + */ + +static char * +MenuVarProc(clientData, interp, name1, name2, flags) + ClientData clientData; /* Information about menu entry. */ + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *name1; /* First part of variable's name. */ + char *name2; /* Second part of variable's name. */ + int flags; /* Describes what just happened. */ +{ + TkMenuEntry *mePtr = (TkMenuEntry *) clientData; + TkMenu *menuPtr; + char *value; + + menuPtr = mePtr->menuPtr; + + /* + * If the variable is being unset, then re-establish the + * trace unless the whole interpreter is going away. + */ + + if (flags & TCL_TRACE_UNSETS) { + mePtr->entryFlags &= ~ENTRY_SELECTED; + if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + Tcl_TraceVar(interp, mePtr->name, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuVarProc, clientData); + } + TkpConfigureMenuEntry(mePtr); + TkEventuallyRedrawMenu(menuPtr, (TkMenuEntry *) NULL); + return (char *) NULL; + } + + /* + * Use the value of the variable to update the selected status of + * the menu entry. + */ + + value = Tcl_GetVar(interp, mePtr->name, TCL_GLOBAL_ONLY); + if (value == NULL) { + value = ""; + } + if (strcmp(value, mePtr->onValue) == 0) { + if (mePtr->entryFlags & ENTRY_SELECTED) { + return (char *) NULL; + } + mePtr->entryFlags |= ENTRY_SELECTED; + } else if (mePtr->entryFlags & ENTRY_SELECTED) { + mePtr->entryFlags &= ~ENTRY_SELECTED; + } else { + return (char *) NULL; + } + TkpConfigureMenuEntry(mePtr); + TkEventuallyRedrawMenu(menuPtr, mePtr); + return (char *) NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TkActivateMenuEntry -- + * + * This procedure is invoked to make a particular menu entry + * the active one, deactivating any other entry that might + * currently be active. + * + * Results: + * The return value is a standard Tcl result (errors can occur + * while posting and unposting submenus). + * + * Side effects: + * Menu entries get redisplayed, and the active entry changes. + * Submenus may get posted and unposted. + * + *---------------------------------------------------------------------- + */ + +int +TkActivateMenuEntry(menuPtr, index) + register TkMenu *menuPtr; /* Menu in which to activate. */ + int index; /* Index of entry to activate, or + * -1 to deactivate all entries. */ +{ + register TkMenuEntry *mePtr; + int result = TCL_OK; + + if (menuPtr->active >= 0) { + mePtr = menuPtr->entries[menuPtr->active]; + + /* + * Don't change the state unless it's currently active (state + * might already have been changed to disabled). + */ + + if (mePtr->state == tkActiveUid) { + mePtr->state = tkNormalUid; + } + TkEventuallyRedrawMenu(menuPtr, menuPtr->entries[menuPtr->active]); + } + menuPtr->active = index; + if (index >= 0) { + mePtr = menuPtr->entries[index]; + mePtr->state = tkActiveUid; + TkEventuallyRedrawMenu(menuPtr, mePtr); + } + return result; +} + +/* + *---------------------------------------------------------------------- + * + * TkPostCommand -- + * + * Execute the postcommand for the given menu. + * + * Results: + * The return value is a standard Tcl result (errors can occur + * while the postcommands are being processed). + * + * Side effects: + * Since commands can get executed while this routine is being executed, + * the entire world can change. + * + *---------------------------------------------------------------------- + */ + +int +TkPostCommand(menuPtr) + TkMenu *menuPtr; +{ + int result; + + /* + * If there is a command for the menu, execute it. This + * may change the size of the menu, so be sure to recompute + * the menu's geometry if needed. + */ + + if (menuPtr->postCommand != NULL) { + result = TkCopyAndGlobalEval(menuPtr->interp, + menuPtr->postCommand); + if (result != TCL_OK) { + return result; + } + TkRecomputeMenu(menuPtr); + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * CloneMenu -- + * + * Creates a child copy of the menu. It will be inserted into + * the menu's instance chain. All attributes and entry + * attributes will be duplicated. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * Allocates storage. After the menu is created, any + * configuration done with this menu or any related one + * will be reflected in all of them. + * + *-------------------------------------------------------------- + */ + +static int +CloneMenu(menuPtr, newMenuName, newMenuTypeString) + TkMenu *menuPtr; /* The menu we are going to clone */ + char *newMenuName; /* The name to give the new menu */ + char *newMenuTypeString; /* What kind of menu is this, a normal menu + * a menubar, or a tearoff? */ +{ + int returnResult; + int menuType; + size_t length; + TkMenuReferences *menuRefPtr; + Tcl_Obj *commandObjPtr; + + if (newMenuTypeString == NULL) { + menuType = MASTER_MENU; + } else { + length = strlen(newMenuTypeString); + if (strncmp(newMenuTypeString, "normal", length) == 0) { + menuType = MASTER_MENU; + } else if (strncmp(newMenuTypeString, "tearoff", length) == 0) { + menuType = TEAROFF_MENU; + } else if (strncmp(newMenuTypeString, "menubar", length) == 0) { + menuType = MENUBAR; + } else { + Tcl_AppendResult(menuPtr->interp, + "bad menu type - must be normal, tearoff, or menubar", + (char *) NULL); + return TCL_ERROR; + } + } + + commandObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL); + Tcl_ListObjAppendElement(menuPtr->interp, commandObjPtr, + Tcl_NewStringObj("tkMenuDup", -1)); + Tcl_ListObjAppendElement(menuPtr->interp, commandObjPtr, + Tcl_NewStringObj(Tk_PathName(menuPtr->tkwin), -1)); + Tcl_ListObjAppendElement(menuPtr->interp, commandObjPtr, + Tcl_NewStringObj(newMenuName, -1)); + if ((newMenuTypeString == NULL) || (newMenuTypeString[0] == '\0')) { + Tcl_ListObjAppendElement(menuPtr->interp, commandObjPtr, + Tcl_NewStringObj("normal", -1)); + } else { + Tcl_ListObjAppendElement(menuPtr->interp, commandObjPtr, + Tcl_NewStringObj(newMenuTypeString, -1)); + } + Tcl_IncrRefCount(commandObjPtr); + Tcl_Preserve((ClientData) menuPtr); + returnResult = Tcl_EvalObj(menuPtr->interp, commandObjPtr); + Tcl_DecrRefCount(commandObjPtr); + + /* + * Make sure the tcl command actually created the clone. + */ + + if ((returnResult == TCL_OK) && + ((menuRefPtr = TkFindMenuReferences(menuPtr->interp, newMenuName)) + != (TkMenuReferences *) NULL) + && (menuPtr->numEntries == menuRefPtr->menuPtr->numEntries)) { + TkMenu *newMenuPtr = menuRefPtr->menuPtr; + char *newArgv[3]; + int i, numElements; + + /* + * Now put this newly created menu into the parent menu's instance + * chain. + */ + + if (menuPtr->nextInstancePtr == NULL) { + menuPtr->nextInstancePtr = newMenuPtr; + newMenuPtr->masterMenuPtr = menuPtr->masterMenuPtr; + } else { + TkMenu *masterMenuPtr; + + masterMenuPtr = menuPtr->masterMenuPtr; + newMenuPtr->nextInstancePtr = masterMenuPtr->nextInstancePtr; + masterMenuPtr->nextInstancePtr = newMenuPtr; + newMenuPtr->masterMenuPtr = masterMenuPtr; + } + + /* + * Add the master menu's window to the bind tags for this window + * after this window's tag. This is so the user can bind to either + * this clone (which may not be easy to do) or the entire menu + * clone structure. + */ + + newArgv[0] = "bindtags"; + newArgv[1] = Tk_PathName(newMenuPtr->tkwin); + if (Tk_BindtagsCmd((ClientData)newMenuPtr->tkwin, + newMenuPtr->interp, 2, newArgv) == TCL_OK) { + char *windowName; + Tcl_Obj *bindingsPtr = + Tcl_NewStringObj(newMenuPtr->interp->result, -1); + Tcl_Obj *elementPtr; + + Tcl_ListObjLength(newMenuPtr->interp, bindingsPtr, &numElements); + for (i = 0; i < numElements; i++) { + Tcl_ListObjIndex(newMenuPtr->interp, bindingsPtr, i, + &elementPtr); + windowName = Tcl_GetStringFromObj(elementPtr, NULL); + if (strcmp(windowName, Tk_PathName(newMenuPtr->tkwin)) + == 0) { + Tcl_Obj *newElementPtr = Tcl_NewStringObj( + Tk_PathName(newMenuPtr->masterMenuPtr->tkwin), -1); + Tcl_ListObjReplace(menuPtr->interp, bindingsPtr, + i + 1, 0, 1, &newElementPtr); + newArgv[2] = Tcl_GetStringFromObj(bindingsPtr, NULL); + Tk_BindtagsCmd((ClientData)newMenuPtr->tkwin, + menuPtr->interp, 3, newArgv); + break; + } + } + Tcl_DecrRefCount(bindingsPtr); + } + Tcl_ResetResult(menuPtr->interp); + + /* + * Clone all of the cascade menus that this menu points to. + */ + + for (i = 0; i < menuPtr->numEntries; i++) { + char *newCascadeName; + TkMenuReferences *cascadeRefPtr; + TkMenu *oldCascadePtr; + + if ((menuPtr->entries[i]->type == CASCADE_ENTRY) + && (menuPtr->entries[i]->name != NULL)) { + cascadeRefPtr = + TkFindMenuReferences(menuPtr->interp, + menuPtr->entries[i]->name); + if ((cascadeRefPtr != NULL) && (cascadeRefPtr->menuPtr)) { + char *nameString; + + oldCascadePtr = cascadeRefPtr->menuPtr; + + nameString = Tk_PathName(newMenuPtr->tkwin); + newCascadeName = TkNewMenuName(menuPtr->interp, + nameString, oldCascadePtr); + CloneMenu(oldCascadePtr, newCascadeName, NULL); + + newArgv[0] = "-menu"; + newArgv[1] = newCascadeName; + ConfigureMenuEntry(newMenuPtr->entries[i], 2, newArgv, + TK_CONFIG_ARGV_ONLY); + ckfree(newCascadeName); + } + } + } + + returnResult = TCL_OK; + } else { + returnResult = TCL_ERROR; + } + Tcl_Release((ClientData) menuPtr); + return returnResult; +} + +/* + *---------------------------------------------------------------------- + * + * MenuDoYPosition -- + * + * Given arguments from an option command line, returns the Y position. + * + * Results: + * Returns TCL_OK or TCL_Error + * + * Side effects: + * yPosition is set to the Y-position of the menu entry. + * + *---------------------------------------------------------------------- + */ + +static int +MenuDoYPosition(interp, menuPtr, arg) + Tcl_Interp *interp; + TkMenu *menuPtr; + char *arg; +{ + int index; + + TkRecomputeMenu(menuPtr); + if (TkGetMenuIndex(interp, menuPtr, arg, 0, &index) != TCL_OK) { + goto error; + } + if (index < 0) { + interp->result = "0"; + } else { + sprintf(interp->result, "%d", menuPtr->entries[index]->y); + } + return TCL_OK; + +error: + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * GetIndexFromCoords -- + * + * Given a string of the form "@int", return the menu item corresponding + * to int. + * + * Results: + * If int is a valid number, *indexPtr will be the number of the menuentry + * that is the correct height. If int is invaled, *indexPtr will be + * unchanged. Returns appropriate Tcl error number. + * + * Side effects: + * If int is invalid, interp's result will set to NULL. + * + *---------------------------------------------------------------------- + */ + +static int +GetIndexFromCoords(interp, menuPtr, string, indexPtr) + Tcl_Interp *interp; /* interp of menu */ + TkMenu *menuPtr; /* the menu we are searching */ + char *string; /* The @string we are parsing */ + int *indexPtr; /* The index of the item that matches */ +{ + int x, y, i; + char *p, *end; + + TkRecomputeMenu(menuPtr); + p = string + 1; + y = strtol(p, &end, 0); + if (end == p) { + goto error; + } + if (*end == ',') { + x = y; + p = end + 1; + y = strtol(p, &end, 0); + if (end == p) { + goto error; + } + } else { + x = menuPtr->borderWidth; + } + + for (i = 0; i < menuPtr->numEntries; i++) { + if ((x >= menuPtr->entries[i]->x) && (y >= menuPtr->entries[i]->y) + && (x < (menuPtr->entries[i]->x + menuPtr->entries[i]->width)) + && (y < (menuPtr->entries[i]->y + + menuPtr->entries[i]->height))) { + break; + } + } + if (i >= menuPtr->numEntries) { + /* i = menuPtr->numEntries - 1; */ + i = -1; + } + *indexPtr = i; + return TCL_OK; + + error: + Tcl_SetResult(interp, (char *) NULL, TCL_STATIC); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * RecursivelyDeleteMenu -- + * + * Deletes a menu and any cascades underneath it. Used for deleting + * instances when a menu is no longer being used as a menubar, + * for instance. + * + * Results: + * None. + * + * Side effects: + * Destroys the menu and all cascade menus underneath it. + * + *---------------------------------------------------------------------- + */ + +static void +RecursivelyDeleteMenu(menuPtr) + TkMenu *menuPtr; /* The menubar instance we are deleting */ +{ + int i; + TkMenuEntry *mePtr; + + for (i = 0; i < menuPtr->numEntries; i++) { + mePtr = menuPtr->entries[i]; + if ((mePtr->type == CASCADE_ENTRY) + && (mePtr->childMenuRefPtr != NULL) + && (mePtr->childMenuRefPtr->menuPtr != NULL)) { + RecursivelyDeleteMenu(mePtr->childMenuRefPtr->menuPtr); + } + } + Tk_DestroyWindow(menuPtr->tkwin); +} + +/* + *---------------------------------------------------------------------- + * + * TkNewMenuName -- + * + * Makes a new unique name for a cloned menu. Will be a child + * of oldName. + * + * Results: + * Returns a char * which has been allocated; caller must free. + * + * Side effects: + * Memory is allocated. + * + *---------------------------------------------------------------------- + */ + +char * +TkNewMenuName(interp, parentName, menuPtr) + Tcl_Interp *interp; /* The interp the new name has to live in.*/ + char *parentName; /* The prefix path of the new name. */ + TkMenu *menuPtr; /* The menu we are cloning. */ +{ + Tcl_DString resultDString; + Tcl_DString childDString; + char *destString; + int offset, i; + int doDot = parentName[strlen(parentName) - 1] != '.'; + Tcl_CmdInfo cmdInfo; + char *returnString; + Tcl_HashTable *nameTablePtr = NULL; + TkWindow *winPtr = (TkWindow *) menuPtr->tkwin; + if (winPtr->mainPtr != NULL) { + nameTablePtr = &(winPtr->mainPtr->nameTable); + } + + Tcl_DStringInit(&childDString); + Tcl_DStringAppend(&childDString, Tk_PathName(menuPtr->tkwin), -1); + for (destString = Tcl_DStringValue(&childDString); + *destString != '\0'; destString++) { + if (*destString == '.') { + *destString = '#'; + } + } + + offset = 0; + + for (i = 0; ; i++) { + if (i == 0) { + Tcl_DStringInit(&resultDString); + Tcl_DStringAppend(&resultDString, parentName, -1); + if (doDot) { + Tcl_DStringAppend(&resultDString, ".", -1); + } + Tcl_DStringAppend(&resultDString, + Tcl_DStringValue(&childDString), -1); + destString = Tcl_DStringValue(&resultDString); + } else { + if (i == 1) { + offset = Tcl_DStringLength(&resultDString); + Tcl_DStringSetLength(&resultDString, offset + 10); + destString = Tcl_DStringValue(&resultDString); + } + sprintf(destString + offset, "%d", i); + } + if ((Tcl_GetCommandInfo(interp, destString, &cmdInfo) == 0) + && ((nameTablePtr == NULL) + || (Tcl_FindHashEntry(nameTablePtr, destString) == NULL))) { + break; + } + } + returnString = ckalloc(strlen(destString) + 1); + strcpy(returnString, destString); + Tcl_DStringFree(&resultDString); + Tcl_DStringFree(&childDString); + return returnString; +} + +/* + *---------------------------------------------------------------------- + * + * TkSetWindowMenuBar -- + * + * Associates a menu with a window. Called by ConfigureFrame in + * in response to a "-menu .foo" configuration option for a top + * level. + * + * Results: + * None. + * + * Side effects: + * The old menu clones for the menubar are thrown away, and a + * handler is set up to allocate the new ones. + * + *---------------------------------------------------------------------- + */ +void +TkSetWindowMenuBar(interp, tkwin, oldMenuName, menuName) + Tcl_Interp *interp; /* The interpreter the toplevel lives in. */ + Tk_Window tkwin; /* The toplevel window */ + char *oldMenuName; /* The name of the menubar previously set in + * this toplevel. NULL means no menu was + * set previously. */ + char *menuName; /* The name of the new menubar that the + * toplevel needs to be set to. NULL means + * that their is no menu now. */ +{ + TkMenuTopLevelList *topLevelListPtr, *prevTopLevelPtr; + TkMenu *menuPtr; + TkMenuReferences *menuRefPtr; + + TkMenuInit(); + + /* + * Destroy the menubar instances of the old menu. Take this window + * out of the old menu's top level reference list. + */ + + if (oldMenuName != NULL) { + menuRefPtr = TkFindMenuReferences(interp, oldMenuName); + if (menuRefPtr != NULL) { + + /* + * Find the menubar instance that is to be removed. Destroy + * it and all of the cascades underneath it. + */ + + if (menuRefPtr->menuPtr != NULL) { + TkMenu *instancePtr; + + menuPtr = menuRefPtr->menuPtr; + + for (instancePtr = menuPtr->masterMenuPtr; + instancePtr != NULL; + instancePtr = instancePtr->nextInstancePtr) { + if (instancePtr->menuType == MENUBAR + && instancePtr->parentTopLevelPtr == tkwin) { + RecursivelyDeleteMenu(instancePtr); + break; + } + } + } + + /* + * Now we need to remove this toplevel from the list of toplevels + * that reference this menu. + */ + + for (topLevelListPtr = menuRefPtr->topLevelListPtr, + prevTopLevelPtr = NULL; + (topLevelListPtr != NULL) + && (topLevelListPtr->tkwin != tkwin); + prevTopLevelPtr = topLevelListPtr, + topLevelListPtr = topLevelListPtr->nextPtr) { + + /* + * Empty loop body. + */ + + } + + /* + * Now we have found the toplevel reference that matches the + * tkwin; remove this reference from the list. + */ + + if (topLevelListPtr != NULL) { + if (prevTopLevelPtr == NULL) { + menuRefPtr->topLevelListPtr = + menuRefPtr->topLevelListPtr->nextPtr; + } else { + prevTopLevelPtr->nextPtr = topLevelListPtr->nextPtr; + } + ckfree((char *) topLevelListPtr); + TkFreeMenuReferences(menuRefPtr); + } + } + } + + /* + * Now, add the clone references for the new menu. + */ + + if (menuName != NULL && menuName[0] != 0) { + TkMenu *menuBarPtr = NULL; + + menuRefPtr = TkCreateMenuReferences(interp, menuName); + + menuPtr = menuRefPtr->menuPtr; + if (menuPtr != NULL) { + char *cloneMenuName; + TkMenuReferences *cloneMenuRefPtr; + char *newArgv[4]; + + /* + * Clone the menu and all of the cascades underneath it. + */ + + cloneMenuName = TkNewMenuName(interp, Tk_PathName(tkwin), + menuPtr); + CloneMenu(menuPtr, cloneMenuName, "menubar"); + + cloneMenuRefPtr = TkFindMenuReferences(interp, cloneMenuName); + if ((cloneMenuRefPtr != NULL) + && (cloneMenuRefPtr->menuPtr != NULL)) { + cloneMenuRefPtr->menuPtr->parentTopLevelPtr = tkwin; + menuBarPtr = cloneMenuRefPtr->menuPtr; + newArgv[0] = "-cursor"; + newArgv[1] = ""; + ConfigureMenu(menuPtr->interp, cloneMenuRefPtr->menuPtr, + 2, newArgv, TK_CONFIG_ARGV_ONLY); + } + + TkpSetWindowMenuBar(tkwin, menuBarPtr); + + ckfree(cloneMenuName); + } else { + TkpSetWindowMenuBar(tkwin, NULL); + } + + + /* + * Add this window to the menu's list of windows that refer + * to this menu. + */ + + topLevelListPtr = (TkMenuTopLevelList *) + ckalloc(sizeof(TkMenuTopLevelList)); + topLevelListPtr->tkwin = tkwin; + topLevelListPtr->nextPtr = menuRefPtr->topLevelListPtr; + menuRefPtr->topLevelListPtr = topLevelListPtr; + } else { + TkpSetWindowMenuBar(tkwin, NULL); + } + TkpSetMainMenubar(interp, tkwin, menuName); +} + +/* + *---------------------------------------------------------------------- + * + * DestroyMenuHashTable -- + * + * Called when an interp is deleted and a menu hash table has + * been set in it. + * + * Results: + * None. + * + * Side effects: + * The hash table is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyMenuHashTable(clientData, interp) + ClientData clientData; /* The menu hash table we are destroying */ + Tcl_Interp *interp; /* The interpreter we are destroying */ +{ + Tcl_DeleteHashTable((Tcl_HashTable *) clientData); + ckfree((char *) clientData); +} + +/* + *---------------------------------------------------------------------- + * + * TkGetMenuHashTable -- + * + * For a given interp, give back the menu hash table that goes with + * it. If the hash table does not exist, it is created. + * + * Results: + * Returns a hash table pointer. + * + * Side effects: + * A new hash table is created if there were no table in the interp + * originally. + * + *---------------------------------------------------------------------- + */ + +Tcl_HashTable * +TkGetMenuHashTable(interp) + Tcl_Interp *interp; /* The interp we need the hash table in.*/ +{ + Tcl_HashTable *menuTablePtr; + + menuTablePtr = (Tcl_HashTable *) Tcl_GetAssocData(interp, MENU_HASH_KEY, + NULL); + if (menuTablePtr == NULL) { + menuTablePtr = (Tcl_HashTable *) ckalloc(sizeof(Tcl_HashTable)); + Tcl_InitHashTable(menuTablePtr, TCL_STRING_KEYS); + Tcl_SetAssocData(interp, MENU_HASH_KEY, DestroyMenuHashTable, + (ClientData) menuTablePtr); + } + return menuTablePtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkCreateMenuReferences -- + * + * Given a pathname, gives back a pointer to a TkMenuReferences structure. + * If a reference is not already in the hash table, one is created. + * + * Results: + * Returns a pointer to a menu reference structure. Should not + * be freed by calller; when a field of the reference is cleared, + * TkFreeMenuReferences should be called. + * + * Side effects: + * A new hash table entry is created if there were no references + * to the menu originally. + * + *---------------------------------------------------------------------- + */ + +TkMenuReferences * +TkCreateMenuReferences(interp, pathName) + Tcl_Interp *interp; + char *pathName; /* The path of the menu widget */ +{ + Tcl_HashEntry *hashEntryPtr; + TkMenuReferences *menuRefPtr; + int newEntry; + Tcl_HashTable *menuTablePtr = TkGetMenuHashTable(interp); + + hashEntryPtr = Tcl_CreateHashEntry(menuTablePtr, pathName, &newEntry); + if (newEntry) { + menuRefPtr = (TkMenuReferences *) ckalloc(sizeof(TkMenuReferences)); + menuRefPtr->menuPtr = NULL; + menuRefPtr->topLevelListPtr = NULL; + menuRefPtr->parentEntryPtr = NULL; + menuRefPtr->hashEntryPtr = hashEntryPtr; + Tcl_SetHashValue(hashEntryPtr, (char *) menuRefPtr); + } else { + menuRefPtr = (TkMenuReferences *) Tcl_GetHashValue(hashEntryPtr); + } + return menuRefPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkFindMenuReferences -- + * + * Given a pathname, gives back a pointer to the TkMenuReferences + * structure. + * + * Results: + * Returns a pointer to a menu reference structure. Should not + * be freed by calller; when a field of the reference is cleared, + * TkFreeMenuReferences should be called. Returns NULL if no reference + * with this pathname exists. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkMenuReferences * +TkFindMenuReferences(interp, pathName) + Tcl_Interp *interp; /* The interp the menu is living in. */ + char *pathName; /* The path of the menu widget */ +{ + Tcl_HashEntry *hashEntryPtr; + TkMenuReferences *menuRefPtr = NULL; + Tcl_HashTable *menuTablePtr; + + menuTablePtr = TkGetMenuHashTable(interp); + hashEntryPtr = Tcl_FindHashEntry(menuTablePtr, pathName); + if (hashEntryPtr != NULL) { + menuRefPtr = (TkMenuReferences *) Tcl_GetHashValue(hashEntryPtr); + } + return menuRefPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkFreeMenuReferences -- + * + * This is called after one of the fields in a menu reference + * is cleared. It cleans up the ref if it is now empty. + * + * Results: + * None. + * + * Side effects: + * If this is the last field to be cleared, the menu ref is + * taken out of the hash table. + * + *---------------------------------------------------------------------- + */ + +void +TkFreeMenuReferences(menuRefPtr) + TkMenuReferences *menuRefPtr; /* The menu reference to + * free */ +{ + if ((menuRefPtr->menuPtr == NULL) + && (menuRefPtr->parentEntryPtr == NULL) + && (menuRefPtr->topLevelListPtr == NULL)) { + Tcl_DeleteHashEntry(menuRefPtr->hashEntryPtr); + ckfree((char *) menuRefPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * DeleteMenuCloneEntries -- + * + * For every clone in this clone chain, delete the menu entries + * given by the parameters. + * + * Results: + * None. + * + * Side effects: + * The appropriate entries are deleted from all clones of this menu. + * + *---------------------------------------------------------------------- + */ + +static void +DeleteMenuCloneEntries(menuPtr, first, last) + TkMenu *menuPtr; /* the menu the command was issued with */ + int first; /* the zero-based first entry in the set + * of entries to delete. */ + int last; /* the zero-based last entry */ +{ + + TkMenu *menuListPtr; + int numDeleted, i; + + numDeleted = last + 1 - first; + for (menuListPtr = menuPtr->masterMenuPtr; menuListPtr != NULL; + menuListPtr = menuListPtr->nextInstancePtr) { + for (i = last; i >= first; i--) { + Tcl_EventuallyFree((ClientData) menuListPtr->entries[i], + DestroyMenuEntry); + } + for (i = last + 1; i < menuListPtr->numEntries; i++) { + menuListPtr->entries[i - numDeleted] = menuListPtr->entries[i]; + menuListPtr->entries[i - numDeleted]->index = i; + } + menuListPtr->numEntries -= numDeleted; + if (menuListPtr->numEntries == 0) { + ckfree((char *) menuListPtr->entries); + menuListPtr->entries = NULL; + } + if ((menuListPtr->active >= first) + && (menuListPtr->active <= last)) { + menuListPtr->active = -1; + } else if (menuListPtr->active > last) { + menuListPtr->active -= numDeleted; + } + TkEventuallyRecomputeMenu(menuListPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMenuInit -- + * + * Sets up the hash tables and the variables used by the menu package. + * + * Results: + * None. + * + * Side effects: + * lastMenuID gets initialized, and the parent hash and the command hash + * are allocated. + * + *---------------------------------------------------------------------- + */ + +void +TkMenuInit() +{ + if (!menusInitialized) { + TkpMenuInit(); + menusInitialized = 1; + } +} diff --git a/generic/tkMenu.h b/generic/tkMenu.h new file mode 100644 index 0000000..6f30d72 --- /dev/null +++ b/generic/tkMenu.h @@ -0,0 +1,541 @@ +/* + * tkMenu.h -- + * + * Declarations shared among all of the files that implement menu widgets. + * + * Copyright (c) 1996-1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMenu.h 1.60 97/06/20 14:43:21 + */ + +#ifndef _TKMENU +#define _TKMENU + +#ifndef _TK +#include "tk.h" +#endif + +#ifndef _TKINT +#include "tkInt.h" +#endif + +#ifndef _DEFAULT +#include "default.h" +#endif + +/* + * Dummy types used by the platform menu code. + */ + +typedef struct TkMenuPlatformData_ *TkMenuPlatformData; +typedef struct TkMenuPlatformEntryData_ *TkMenuPlatformEntryData; + +/* + * One of the following data structures is kept for each entry of each + * menu managed by this file: + */ + +typedef struct TkMenuEntry { + int type; /* Type of menu entry; see below for + * valid types. */ + struct TkMenu *menuPtr; /* Menu with which this entry is associated. */ + char *label; /* Main text label displayed in entry (NULL + * if no label). Malloc'ed. */ + int labelLength; /* Number of non-NULL characters in label. */ + Tk_Uid state; /* State of button for display purposes: + * normal, active, or disabled. */ + int underline; /* Index of character to underline. */ + Pixmap bitmap; /* Bitmap to display in menu entry, or None. + * If not None then label is ignored. */ + char *imageString; /* Name of image to display (malloc'ed), or + * NULL. If non-NULL, bitmap, text, and + * textVarName are ignored. */ + Tk_Image image; /* Image to display in menu entry, or NULL if + * none. */ + char *selectImageString; /* Name of image to display when selected + * (malloc'ed), or NULL. */ + Tk_Image selectImage; /* Image to display in entry when selected, + * or NULL if none. Ignored if image is + * NULL. */ + char *accel; /* Accelerator string displayed at right + * of menu entry. NULL means no such + * accelerator. Malloc'ed. */ + int accelLength; /* Number of non-NULL characters in + * accelerator. */ + int indicatorOn; /* True means draw indicator, false means + * don't draw it. */ + /* + * Display attributes + */ + + Tk_3DBorder border; /* Structure used to draw background for + * entry. NULL means use overall border + * for menu. */ + XColor *fg; /* Foreground color to use for entry. NULL + * means use foreground color from menu. */ + Tk_3DBorder activeBorder; /* Used to draw background and border when + * element is active. NULL means use + * activeBorder from menu. */ + XColor *activeFg; /* Foreground color to use when entry is + * active. NULL means use active foreground + * from menu. */ + XColor *indicatorFg; /* Color for indicators in radio and check + * button entries. NULL means use indicatorFg + * GC from menu. */ + Tk_Font tkfont; /* Text font for menu entries. NULL means + * use overall font for menu. */ + int columnBreak; /* If this is 0, this item appears below + * the item in front of it. If this is + * 1, this item starts a new column. */ + int hideMargin; /* If this is 0, then the item has enough + * margin to accomodate a standard check + * mark and a default right margin. If this + * is 1, then the item has no such margins. + * and checkbuttons and radiobuttons with + * this set will have a rectangle drawn + * in the indicator around the item if + * the item is checked. + * This is useful palette menus.*/ + int indicatorSpace; /* The width of the indicator space for this + * entry. + */ + int labelWidth; /* Number of pixels to allow for displaying + * labels in menu entries. */ + + /* + * Information used to implement this entry's action: + */ + + char *command; /* Command to invoke when entry is invoked. + * Malloc'ed. */ + char *name; /* Name of variable (for check buttons and + * radio buttons) or menu (for cascade + * entries). Malloc'ed.*/ + char *onValue; /* Value to store in variable when selected + * (only for radio and check buttons). + * Malloc'ed. */ + char *offValue; /* Value to store in variable when not + * selected (only for check buttons). + * Malloc'ed. */ + + /* + * Information used for drawing this menu entry. + */ + + int width; /* Number of pixels occupied by entry in + * horizontal dimension. Not used except + * in menubars. The width of norma menus + * is dependent on the rest of the menu. */ + int x; /* X-coordinate of leftmost pixel in entry */ + int height; /* Number of pixels occupied by entry in + * vertical dimension, including raised + * border drawn around entry when active. */ + int y; /* Y-coordinate of topmost pixel in entry. */ + GC textGC; /* GC for drawing text in entry. NULL means + * use overall textGC for menu. */ + GC activeGC; /* GC for drawing text in entry when active. + * NULL means use overall activeGC for + * menu. */ + GC disabledGC; /* Used to produce disabled effect for entry. + * NULL means use overall disabledGC from + * menu structure. See comments for + * disabledFg in menu structure for more + * information. */ + GC indicatorGC; /* For drawing indicators. None means use + * GC from menu. */ + + /* + * Miscellaneous fields. + */ + + int entryFlags; /* Various flags. See below for + definitions. */ + int index; /* Need to know which index we are. This + * is zero-based. This is the top-left entry + * of the menu. */ + + /* + * Bookeeping for master menus and cascade menus. + */ + + struct TkMenuReferences *childMenuRefPtr; + /* A pointer to the hash table entry for + * the child menu. Stored here when the menu + * entry is configured so that a hash lookup + * is not necessary later.*/ + struct TkMenuEntry *nextCascadePtr; + /* The next cascade entry that is a parent of + * this entry's child cascade menu. NULL + * end of list, this is not a cascade entry, + * or the menu that this entry point to + * does not yet exist. */ + TkMenuPlatformEntryData platformEntryData; + /* The data for the specific type of menu. + * Depends on platform and menu type what + * kind of options are in this structure. + */ +} TkMenuEntry; + +/* + * Flag values defined for menu entries: + * + * ENTRY_SELECTED: Non-zero means this is a radio or check + * button and that it should be drawn in + * the "selected" state. + * ENTRY_NEEDS_REDISPLAY: Non-zero means the entry should be redisplayed. + * ENTRY_LAST_COLUMN: Used by the drawing code. If the entry is in the + * last column, the space to its right needs to + * be filled. + * ENTRY_PLATFORM_FLAG1 - 4 These flags are reserved for use by the + * platform-dependent implementation of menus + * and should not be used by anything else. + */ + +#define ENTRY_SELECTED 1 +#define ENTRY_NEEDS_REDISPLAY 2 +#define ENTRY_LAST_COLUMN 4 +#define ENTRY_PLATFORM_FLAG1 (1 << 30) +#define ENTRY_PLATFORM_FLAG2 (1 << 29) +#define ENTRY_PLATFORM_FLAG3 (1 << 28) +#define ENTRY_PLATFORM_FLAG4 (1 << 27) + +/* + * Types defined for MenuEntries: + */ + +#define COMMAND_ENTRY 0 +#define SEPARATOR_ENTRY 1 +#define CHECK_BUTTON_ENTRY 2 +#define RADIO_BUTTON_ENTRY 3 +#define CASCADE_ENTRY 4 +#define TEAROFF_ENTRY 5 + +/* + * Mask bits for above types: + */ + +#define COMMAND_MASK TK_CONFIG_USER_BIT +#define SEPARATOR_MASK (TK_CONFIG_USER_BIT << 1) +#define CHECK_BUTTON_MASK (TK_CONFIG_USER_BIT << 2) +#define RADIO_BUTTON_MASK (TK_CONFIG_USER_BIT << 3) +#define CASCADE_MASK (TK_CONFIG_USER_BIT << 4) +#define TEAROFF_MASK (TK_CONFIG_USER_BIT << 5) +#define ALL_MASK (COMMAND_MASK | SEPARATOR_MASK \ + | CHECK_BUTTON_MASK | RADIO_BUTTON_MASK | CASCADE_MASK | TEAROFF_MASK) + +/* + * A data structure of the following type is kept for each + * menu widget: + */ + +typedef struct TkMenu { + Tk_Window tkwin; /* Window that embodies the pane. NULL + * means that the window has been destroyed + * but the data structures haven't yet been + * cleaned up.*/ + Display *display; /* Display containing widget. Needed, among + * other things, so that resources can be + * freed up even after tkwin has gone away. */ + Tcl_Interp *interp; /* Interpreter associated with menu. */ + Tcl_Command widgetCmd; /* Token for menu's widget command. */ + TkMenuEntry **entries; /* Array of pointers to all the entries + * in the menu. NULL means no entries. */ + int numEntries; /* Number of elements in entries. */ + int active; /* Index of active entry. -1 means + * nothing active. */ + int menuType; /* MASTER_MENU, TEAROFF_MENU, or MENUBAR. + * See below for definitions. */ + char *menuTypeName; /* Used to control whether created tkwin + * is a toplevel or not. "normal", "menubar", + * or "toplevel" */ + + /* + * Information used when displaying widget: + */ + + Tk_3DBorder border; /* Structure used to draw 3-D + * border and background for menu. */ + int borderWidth; /* Width of border around whole menu. */ + Tk_3DBorder activeBorder; /* Used to draw background and border for + * active element (if any). */ + int activeBorderWidth; /* Width of border around active element. */ + int relief; /* 3-d effect: TK_RELIEF_RAISED, etc. */ + Tk_Font tkfont; /* Text font for menu entries. */ + XColor *fg; /* Foreground color for entries. */ + XColor *disabledFg; /* Foreground color when disabled. NULL + * means use normalFg with a 50% stipple + * instead. */ + XColor *activeFg; /* Foreground color for active entry. */ + XColor *indicatorFg; /* Color for indicators in radio and check + * button entries. */ + Pixmap gray; /* Bitmap for drawing disabled entries in + * a stippled fashion. None means not + * allocated yet. */ + GC textGC; /* GC for drawing text and other features + * of menu entries. */ + GC disabledGC; /* Used to produce disabled effect. If + * disabledFg isn't NULL, this GC is used to + * draw text and icons for disabled entries. + * Otherwise text and icons are drawn with + * normalGC and this GC is used to stipple + * background across them. */ + GC activeGC; /* GC for drawing active entry. */ + GC indicatorGC; /* For drawing indicators. */ + GC disabledImageGC; /* Used for drawing disabled images. They + * have to be stippled. This is created + * when the image is about to be drawn the + * first time. */ + + /* + * Information about geometry of menu. + */ + + int totalWidth; /* Width of entire menu */ + int totalHeight; /* Height of entire menu */ + + /* + * Miscellaneous information: + */ + + int tearOff; /* 1 means this menu can be torn off. On some + * platforms, the user can drag an outline + * of the menu by just dragging outside of + * the menu, and the tearoff is created where + * the mouse is released. On others, an + * indicator (such as a dashed stripe) is + * drawn, and when the menu is selected, the + * tearoff is created. */ + char *title; /* The title to use when this menu is torn + * off. If this is NULL, a default scheme + * will be used to generate a title for + * tearoff. */ + char *tearOffCommand; /* If non-NULL, points to a command to + * run whenever the menu is torn-off. */ + char *takeFocus; /* Value of -takefocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + Tk_Cursor cursor; /* Current cursor for window, or None. */ + char *postCommand; /* Used to detect cycles in cascade hierarchy + * trees when preprocessing postcommands + * on some platforms. See PostMenu for + * more details. */ + int postCommandGeneration; /* Need to do pre-invocation post command + * traversal */ + int menuFlags; /* Flags for use by X; see below for + definition */ + TkMenuEntry *postedCascade; /* Points to menu entry for cascaded submenu + * that is currently posted or NULL if no + * submenu posted. */ + struct TkMenu *nextInstancePtr; + /* The next instance of this menu in the + * chain. */ + struct TkMenu *masterMenuPtr; + /* A pointer to the original menu for this + * clone chain. Points back to this structure + * if this menu is a master menu. */ + Tk_Window parentTopLevelPtr;/* If this menu is a menubar, this is the + * toplevel that owns the menu. Only applicable + * for menubar clones. + */ + struct TkMenuReferences *menuRefPtr; + /* Each menu is hashed into a table with the + * name of the menu's window as the key. + * The information in this hash table includes + * a pointer to the menu (so that cascades + * can find this menu), a pointer to the + * list of toplevel widgets that have this + * menu as its menubar, and a list of menu + * entries that have this menu specified + * as a cascade. */ + TkMenuPlatformData platformData; + /* The data for the specific type of menu. + * Depends on platform and menu type what + * kind of options are in this structure. + */ +} TkMenu; + +/* + * When the toplevel configure -menu command is executed, the menu may not + * exist yet. We need to keep a linked list of windows that reference + * a particular menu. + */ + +typedef struct TkMenuTopLevelList { + struct TkMenuTopLevelList *nextPtr; + /* The next window in the list */ + Tk_Window tkwin; /* The window that has this menu as its + * menubar. */ +} TkMenuTopLevelList; + +/* + * The following structure is used to keep track of things which + * reference a menu. It is created when: + * - a menu is created. + * - a cascade entry is added to a menu with a non-null name + * - the "-menu" configuration option is used on a toplevel widget + * with a non-null parameter. + * + * One of these three fields must be non-NULL, but any of the fields may + * be NULL. This structure makes it easy to determine whether or not + * anything like recalculating platform data or geometry is necessary + * when one of the three actions above is performed. + */ + +typedef struct TkMenuReferences { + struct TkMenu *menuPtr; /* The menu data structure. This is NULL + * if the menu does not exist. */ + TkMenuTopLevelList *topLevelListPtr; + /* First in the list of all toplevels that + * have this menu as its menubar. NULL if no + * toplevel widgets have this menu as its + * menubar. */ + TkMenuEntry *parentEntryPtr;/* First in the list of all cascade menu + * entries that have this menu as their child. + * NULL means no cascade entries. */ + Tcl_HashEntry *hashEntryPtr;/* This is needed because the pathname of the + * window (which is what we hash on) may not + * be around when we are deleting. + */ +} TkMenuReferences; + +/* + * Flag bits for menus: + * + * REDRAW_PENDING: Non-zero means a DoWhenIdle handler + * has already been queued to redraw + * this window. + * RESIZE_PENDING: Non-zero means a call to ComputeMenuGeometry + * has already been scheduled. + * MENU_DELETION_PENDING Non-zero means that we are currently destroying + * this menu. This is useful when we are in the + * middle of cleaning this master menu's chain of + * menus up when TkDestroyMenu was called again on + * this menu (via a destroy binding or somesuch). + * MENU_PLATFORM_FLAG1... Reserved for use by the platform-specific menu + * code. + */ + +#define REDRAW_PENDING 1 +#define RESIZE_PENDING 2 +#define MENU_DELETION_PENDING 4 +#define MENU_PLATFORM_FLAG1 (1 << 30) +#define MENU_PLATFORM_FLAG2 (1 << 29) +#define MENU_PLATFORM_FLAG3 (1 << 28) + +/* + * Each menu created by the user is a MASTER_MENU. When a menu is torn off, + * a TEAROFF_MENU instance is created. When a menu is assigned to a toplevel + * as a menu bar, a MENUBAR instance is created. All instances have the same + * configuration information. If the master instance is deleted, all instances + * are deleted. If one of the other instances is deleted, only that instance + * is deleted. + */ + +#define UNKNOWN_TYPE -1 +#define MASTER_MENU 0 +#define TEAROFF_MENU 1 +#define MENUBAR 2 + +/* + * Various geometry definitions: + */ + +#define CASCADE_ARROW_HEIGHT 10 +#define CASCADE_ARROW_WIDTH 8 +#define DECORATION_BORDER_WIDTH 2 + +/* + * Configuration specs. Needed for platform-specific default initializations. + */ + +EXTERN Tk_ConfigSpec tkMenuEntryConfigSpecs[]; +EXTERN Tk_ConfigSpec tkMenuConfigSpecs[]; + +/* + * Menu-related procedures that are shared among Tk modules but not exported + * to the outside world: + */ + +EXTERN int TkActivateMenuEntry _ANSI_ARGS_((TkMenu *menuPtr, + int index)); +EXTERN void TkBindMenu _ANSI_ARGS_(( + Tk_Window tkwin, TkMenu *menuPtr)); +EXTERN TkMenuReferences * + TkCreateMenuReferences _ANSI_ARGS_((Tcl_Interp *interp, + char *pathName)); +EXTERN void TkDestroyMenu _ANSI_ARGS_((TkMenu *menuPtr)); +EXTERN void TkEventuallyRecomputeMenu _ANSI_ARGS_((TkMenu *menuPtr)); +EXTERN void TkEventuallyRedrawMenu _ANSI_ARGS_(( + TkMenu *menuPtr, TkMenuEntry *mePtr)); +EXTERN TkMenuReferences * + TkFindMenuReferences _ANSI_ARGS_((Tcl_Interp *interp, + char *pathName)); +EXTERN void TkFreeMenuReferences _ANSI_ARGS_(( + TkMenuReferences *menuRefPtr)); +EXTERN Tcl_HashTable * TkGetMenuHashTable _ANSI_ARGS_((Tcl_Interp *interp)); +EXTERN int TkGetMenuIndex _ANSI_ARGS_((Tcl_Interp *interp, + TkMenu *menuPtr, char *string, int lastOK, + int *indexPtr)); +EXTERN void TkMenuInitializeDrawingFields _ANSI_ARGS_((TkMenu *menuPtr)); +EXTERN void TkMenuInitializeEntryDrawingFields _ANSI_ARGS_(( + TkMenuEntry *mePtr)); +EXTERN int TkInvokeMenu _ANSI_ARGS_((Tcl_Interp *interp, + TkMenu *menuPtr, int index)); +EXTERN void TkMenuConfigureDrawOptions _ANSI_ARGS_(( + TkMenu *menuPtr)); +EXTERN int TkMenuConfigureEntryDrawOptions _ANSI_ARGS_(( + TkMenuEntry *mePtr, int index)); +EXTERN void TkMenuFreeDrawOptions _ANSI_ARGS_((TkMenu *menuPtr)); +EXTERN void TkMenuEntryFreeDrawOptions _ANSI_ARGS_(( + TkMenuEntry *mePtr)); +EXTERN void TkMenuEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +EXTERN void TkMenuImageProc _ANSI_ARGS_(( + ClientData clientData, int x, int y, int width, + int height, int imgWidth, int imgHeight)); +EXTERN void TkMenuInit _ANSI_ARGS_((void)); +EXTERN void TkMenuSelectImageProc _ANSI_ARGS_ + ((ClientData clientData, int x, int y, + int width, int height, int imgWidth, + int imgHeight)); +EXTERN char * TkNewMenuName _ANSI_ARGS_((Tcl_Interp *interp, + char *parentName, TkMenu *menuPtr)); +EXTERN int TkPostCommand _ANSI_ARGS_((TkMenu *menuPtr)); +EXTERN int TkPostSubmenu _ANSI_ARGS_((Tcl_Interp *interp, + TkMenu *menuPtr, TkMenuEntry *mePtr)); +EXTERN int TkPostTearoffMenu _ANSI_ARGS_((Tcl_Interp *interp, + TkMenu *menuPtr, int x, int y)); +EXTERN int TkPreprocessMenu _ANSI_ARGS_((TkMenu *menuPtr)); +EXTERN void TkRecomputeMenu _ANSI_ARGS_((TkMenu *menuPtr)); + +/* + * These routines are the platform-dependent routines called by the + * common code. + */ + +EXTERN void TkpComputeMenubarGeometry _ANSI_ARGS_((TkMenu *menuPtr)); +EXTERN void TkpComputeStandardMenuGeometry _ANSI_ARGS_ + ((TkMenu *menuPtr)); +EXTERN int TkpConfigureMenuEntry + _ANSI_ARGS_((TkMenuEntry *mePtr)); +EXTERN void TkpDestroyMenu _ANSI_ARGS_((TkMenu *menuPtr)); +EXTERN void TkpDestroyMenuEntry + _ANSI_ARGS_((TkMenuEntry *mEntryPtr)); +EXTERN void TkpDrawMenuEntry _ANSI_ARGS_((TkMenuEntry *mePtr, + Drawable d, Tk_Font tkfont, + CONST Tk_FontMetrics *menuMetricsPtr, int x, + int y, int width, int height, int strictMotif, + int drawArrow)); +EXTERN void TkpMenuInit _ANSI_ARGS_((void)); +EXTERN int TkpMenuNewEntry _ANSI_ARGS_((TkMenuEntry *mePtr)); +EXTERN int TkpNewMenu _ANSI_ARGS_((TkMenu *menuPtr)); +EXTERN int TkpPostMenu _ANSI_ARGS_((Tcl_Interp *interp, + TkMenu *menuPtr, int x, int y)); +EXTERN void TkpSetWindowMenuBar _ANSI_ARGS_((Tk_Window tkwin, + TkMenu *menuPtr)); + +#endif /* _TKMENU */ + diff --git a/generic/tkMenuDraw.c b/generic/tkMenuDraw.c new file mode 100644 index 0000000..be218a0 --- /dev/null +++ b/generic/tkMenuDraw.c @@ -0,0 +1,1018 @@ +/* + * tkMenuDraw.c -- + * + * This module implements the platform-independent drawing and + * geometry calculations of menu widgets. + * + * Copyright (c) 1996-1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMenuDraw.c 1.46 97/10/28 14:26:00 + */ + +#include "tkMenu.h" + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void AdjustMenuCoords _ANSI_ARGS_ ((TkMenu *menuPtr, + TkMenuEntry *mePtr, int *xPtr, int *yPtr, + char *string)); +static void ComputeMenuGeometry _ANSI_ARGS_(( + ClientData clientData)); +static void DisplayMenu _ANSI_ARGS_((ClientData clientData)); + +/* + *---------------------------------------------------------------------- + * + * TkMenuInitializeDrawingFields -- + * + * Fills in drawing fields of a new menu. Called when new menu is + * created by Tk_MenuCmd. + * + * Results: + * None. + * + * Side effects: + * menuPtr fields are initialized. + * + *---------------------------------------------------------------------- + */ + +void +TkMenuInitializeDrawingFields(menuPtr) + TkMenu *menuPtr; /* The menu we are initializing. */ +{ + menuPtr->textGC = None; + menuPtr->gray = None; + menuPtr->disabledGC = None; + menuPtr->activeGC = None; + menuPtr->indicatorGC = None; + menuPtr->disabledImageGC = None; + menuPtr->totalWidth = menuPtr->totalHeight = 0; +} + +/* + *---------------------------------------------------------------------- + * + * TkMenuInitializeEntryDrawingFields -- + * + * Fills in drawing fields of a new menu entry. Called when an + * entry is created. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkMenuInitializeEntryDrawingFields(mePtr) + TkMenuEntry *mePtr; /* The menu we are initializing. */ +{ + mePtr->width = 0; + mePtr->height = 0; + mePtr->x = 0; + mePtr->y = 0; + mePtr->indicatorSpace = 0; + mePtr->labelWidth = 0; + mePtr->textGC = None; + mePtr->activeGC = None; + mePtr->disabledGC = None; + mePtr->indicatorGC = None; +} + +/* + *---------------------------------------------------------------------- + * + * TkMenuFreeDrawOptions -- + * + * Frees up any structures allocated for the drawing of a menu. + * Called when menu is deleted. + * + * Results: + * None. + * + * Side effects: + * Storage is released. + * + *---------------------------------------------------------------------- + */ + +void +TkMenuFreeDrawOptions(menuPtr) + TkMenu *menuPtr; +{ + if (menuPtr->textGC != None) { + Tk_FreeGC(menuPtr->display, menuPtr->textGC); + } + if (menuPtr->disabledImageGC != None) { + Tk_FreeGC(menuPtr->display, menuPtr->disabledImageGC); + } + if (menuPtr->gray != None) { + Tk_FreeBitmap(menuPtr->display, menuPtr->gray); + } + if (menuPtr->disabledGC != None) { + Tk_FreeGC(menuPtr->display, menuPtr->disabledGC); + } + if (menuPtr->activeGC != None) { + Tk_FreeGC(menuPtr->display, menuPtr->activeGC); + } + if (menuPtr->indicatorGC != None) { + Tk_FreeGC(menuPtr->display, menuPtr->indicatorGC); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMenuEntryFreeDrawOptions -- + * + * Frees up drawing structures for a menu entry. Called when + * menu entry is freed. + * + * RESULTS: + * None. + * + * Side effects: + * Storage is freed. + * + *---------------------------------------------------------------------- + */ + +void +TkMenuEntryFreeDrawOptions(mePtr) + TkMenuEntry *mePtr; +{ + if (mePtr->textGC != None) { + Tk_FreeGC(mePtr->menuPtr->display, mePtr->textGC); + } + if (mePtr->disabledGC != None) { + Tk_FreeGC(mePtr->menuPtr->display, mePtr->disabledGC); + } + if (mePtr->activeGC != None) { + Tk_FreeGC(mePtr->menuPtr->display, mePtr->activeGC); + } + if (mePtr->indicatorGC != None) { + Tk_FreeGC(mePtr->menuPtr->display, mePtr->indicatorGC); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMenuConfigureDrawOptions -- + * + * Sets the menu's drawing attributes in preparation for drawing + * the menu. + * + * RESULTS: + * None. + * + * Side effects: + * Storage is allocated. + * + *---------------------------------------------------------------------- + */ + +void +TkMenuConfigureDrawOptions(menuPtr) + TkMenu *menuPtr; /* The menu we are configuring. */ +{ + XGCValues gcValues; + GC newGC; + unsigned long mask; + + /* + * A few options need special processing, such as setting the + * background from a 3-D border, or filling in complicated + * defaults that couldn't be specified to Tk_ConfigureWidget. + */ + + Tk_SetBackgroundFromBorder(menuPtr->tkwin, menuPtr->border); + + gcValues.font = Tk_FontId(menuPtr->tkfont); + gcValues.foreground = menuPtr->fg->pixel; + gcValues.background = Tk_3DBorderColor(menuPtr->border)->pixel; + newGC = Tk_GetGC(menuPtr->tkwin, GCForeground|GCBackground|GCFont, + &gcValues); + if (menuPtr->textGC != None) { + Tk_FreeGC(menuPtr->display, menuPtr->textGC); + } + menuPtr->textGC = newGC; + + gcValues.font = Tk_FontId(menuPtr->tkfont); + gcValues.background = Tk_3DBorderColor(menuPtr->border)->pixel; + if (menuPtr->disabledFg != NULL) { + gcValues.foreground = menuPtr->disabledFg->pixel; + mask = GCForeground|GCBackground|GCFont; + } else { + gcValues.foreground = gcValues.background; + mask = GCForeground; + if (menuPtr->gray == None) { + menuPtr->gray = Tk_GetBitmap(menuPtr->interp, menuPtr->tkwin, + Tk_GetUid("gray50")); + } + if (menuPtr->gray != None) { + gcValues.fill_style = FillStippled; + gcValues.stipple = menuPtr->gray; + mask = GCForeground|GCFillStyle|GCStipple; + } + } + newGC = Tk_GetGC(menuPtr->tkwin, mask, &gcValues); + if (menuPtr->disabledGC != None) { + Tk_FreeGC(menuPtr->display, menuPtr->disabledGC); + } + menuPtr->disabledGC = newGC; + + gcValues.foreground = Tk_3DBorderColor(menuPtr->border)->pixel; + if (menuPtr->gray == None) { + menuPtr->gray = Tk_GetBitmap(menuPtr->interp, menuPtr->tkwin, + Tk_GetUid("gray50")); + } + if (menuPtr->gray != None) { + gcValues.fill_style = FillStippled; + gcValues.stipple = menuPtr->gray; + newGC = Tk_GetGC(menuPtr->tkwin, + GCForeground|GCFillStyle|GCStipple, &gcValues); + } + if (menuPtr->disabledImageGC != None) { + Tk_FreeGC(menuPtr->display, menuPtr->disabledImageGC); + } + menuPtr->disabledImageGC = newGC; + + gcValues.font = Tk_FontId(menuPtr->tkfont); + gcValues.foreground = menuPtr->activeFg->pixel; + gcValues.background = + Tk_3DBorderColor(menuPtr->activeBorder)->pixel; + newGC = Tk_GetGC(menuPtr->tkwin, GCForeground|GCBackground|GCFont, + &gcValues); + if (menuPtr->activeGC != None) { + Tk_FreeGC(menuPtr->display, menuPtr->activeGC); + } + menuPtr->activeGC = newGC; + + gcValues.foreground = menuPtr->indicatorFg->pixel; + gcValues.background = Tk_3DBorderColor(menuPtr->border)->pixel; + newGC = Tk_GetGC(menuPtr->tkwin, GCForeground|GCBackground|GCFont, + &gcValues); + if (menuPtr->indicatorGC != None) { + Tk_FreeGC(menuPtr->display, menuPtr->indicatorGC); + } + menuPtr->indicatorGC = newGC; +} + +/* + *---------------------------------------------------------------------- + * + * TkMenuConfigureEntryDrawOptions -- + * + * Calculates any entry-specific draw options for the given menu + * entry. + * + * Results: + * Returns a standard Tcl error. + * + * Side effects: + * Storage may be allocated. + * + *---------------------------------------------------------------------- + */ + +int +TkMenuConfigureEntryDrawOptions(mePtr, index) + TkMenuEntry *mePtr; + int index; +{ + + XGCValues gcValues; + GC newGC, newActiveGC, newDisabledGC, newIndicatorGC; + unsigned long mask; + Tk_Font tkfont; + TkMenu *menuPtr = mePtr->menuPtr; + + tkfont = (mePtr->tkfont == NULL) ? menuPtr->tkfont : mePtr->tkfont; + + if (mePtr->state == tkActiveUid) { + if (index != menuPtr->active) { + TkActivateMenuEntry(menuPtr, index); + } + } else { + if (index == menuPtr->active) { + TkActivateMenuEntry(menuPtr, -1); + } + if ((mePtr->state != tkNormalUid) + && (mePtr->state != tkDisabledUid)) { + Tcl_AppendResult(menuPtr->interp, "bad state value \"", + mePtr->state, + "\": must be normal, active, or disabled", (char *) NULL); + mePtr->state = tkNormalUid; + return TCL_ERROR; + } + } + + if ((mePtr->tkfont != NULL) + || (mePtr->border != NULL) + || (mePtr->fg != NULL) + || (mePtr->activeBorder != NULL) + || (mePtr->activeFg != NULL) + || (mePtr->indicatorFg != NULL)) { + gcValues.foreground = (mePtr->fg != NULL) + ? mePtr->fg->pixel + : menuPtr->fg->pixel; + gcValues.background = Tk_3DBorderColor( + (mePtr->border != NULL) + ? mePtr->border + : menuPtr->border) + ->pixel; + + gcValues.font = Tk_FontId(tkfont); + + /* + * Note: disable GraphicsExpose events; we know there won't be + * obscured areas when copying from an off-screen pixmap to the + * screen and this gets rid of unnecessary events. + */ + + gcValues.graphics_exposures = False; + newGC = Tk_GetGC(menuPtr->tkwin, + GCForeground|GCBackground|GCFont|GCGraphicsExposures, + &gcValues); + + if (mePtr->indicatorFg != NULL) { + gcValues.foreground = mePtr->indicatorFg->pixel; + } else if (menuPtr->indicatorFg != NULL) { + gcValues.foreground = menuPtr->indicatorFg->pixel; + } + newIndicatorGC = Tk_GetGC(menuPtr->tkwin, + GCForeground|GCBackground|GCGraphicsExposures, + &gcValues); + + if ((menuPtr->disabledFg != NULL) || (mePtr->image != NULL)) { + gcValues.foreground = menuPtr->disabledFg->pixel; + mask = GCForeground|GCBackground|GCFont|GCGraphicsExposures; + } else { + gcValues.foreground = gcValues.background; + gcValues.fill_style = FillStippled; + gcValues.stipple = menuPtr->gray; + mask = GCForeground|GCFillStyle|GCStipple; + } + newDisabledGC = Tk_GetGC(menuPtr->tkwin, mask, &gcValues); + + gcValues.foreground = (mePtr->activeFg != NULL) + ? mePtr->activeFg->pixel + : menuPtr->activeFg->pixel; + gcValues.background = Tk_3DBorderColor( + (mePtr->activeBorder != NULL) + ? mePtr->activeBorder + : menuPtr->activeBorder)->pixel; + newActiveGC = Tk_GetGC(menuPtr->tkwin, + GCForeground|GCBackground|GCFont|GCGraphicsExposures, + &gcValues); + } else { + newGC = None; + newActiveGC = None; + newDisabledGC = None; + newIndicatorGC = None; + } + if (mePtr->textGC != None) { + Tk_FreeGC(menuPtr->display, mePtr->textGC); + } + mePtr->textGC = newGC; + if (mePtr->activeGC != None) { + Tk_FreeGC(menuPtr->display, mePtr->activeGC); + } + mePtr->activeGC = newActiveGC; + if (mePtr->disabledGC != None) { + Tk_FreeGC(menuPtr->display, mePtr->disabledGC); + } + mePtr->disabledGC = newDisabledGC; + if (mePtr->indicatorGC != None) { + Tk_FreeGC(menuPtr->display, mePtr->indicatorGC); + } + mePtr->indicatorGC = newIndicatorGC; + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkEventuallyRecomputeMenu -- + * + * Tells Tcl to redo the geometry because this menu has changed. + * + * Results: + * None. + * + * Side effects: + * Menu geometry is recomputed at idle time, and the menu will be + * redisplayed. + * + *---------------------------------------------------------------------- + */ + +void +TkEventuallyRecomputeMenu(menuPtr) + TkMenu *menuPtr; +{ + if (!(menuPtr->menuFlags & RESIZE_PENDING)) { + menuPtr->menuFlags |= RESIZE_PENDING; + Tcl_DoWhenIdle(ComputeMenuGeometry, (ClientData) menuPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkRecomputeMenu -- + * + * Tells Tcl to redo the geometry because this menu has changed. + * Does it now; removes any ComputeMenuGeometries from the idler. + * + * Results: + * None. + * + * Side effects: + * Menu geometry is immediately reconfigured. + * + *---------------------------------------------------------------------- + */ + +void +TkRecomputeMenu(menuPtr) + TkMenu *menuPtr; +{ + if (menuPtr->menuFlags & RESIZE_PENDING) { + Tcl_CancelIdleCall(ComputeMenuGeometry, (ClientData) menuPtr); + ComputeMenuGeometry((ClientData) menuPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkEventuallyRedrawMenu -- + * + * Arrange for an entry of a menu, or the whole menu, to be + * redisplayed at some point in the future. + * + * Results: + * None. + * + * Side effects: + * A when-idle hander is scheduled to do the redisplay, if there + * isn't one already scheduled. + * + *---------------------------------------------------------------------- + */ + +void +TkEventuallyRedrawMenu(menuPtr, mePtr) + register TkMenu *menuPtr; /* Information about menu to redraw. */ + register TkMenuEntry *mePtr; /* Entry to redraw. NULL means redraw + * all the entries in the menu. */ +{ + int i; + + if (menuPtr->tkwin == NULL) { + return; + } + if (mePtr != NULL) { + mePtr->entryFlags |= ENTRY_NEEDS_REDISPLAY; + } else { + for (i = 0; i < menuPtr->numEntries; i++) { + menuPtr->entries[i]->entryFlags |= ENTRY_NEEDS_REDISPLAY; + } + } + if (!Tk_IsMapped(menuPtr->tkwin) + || (menuPtr->menuFlags & REDRAW_PENDING)) { + return; + } + Tcl_DoWhenIdle(DisplayMenu, (ClientData) menuPtr); + menuPtr->menuFlags |= REDRAW_PENDING; +} + +/* + *-------------------------------------------------------------- + * + * ComputeMenuGeometry -- + * + * This procedure is invoked to recompute the size and + * layout of a menu. It is called as a when-idle handler so + * that it only gets done once, even if a group of changes is + * made to the menu. + * + * 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. + * + *-------------------------------------------------------------- + */ + +static void +ComputeMenuGeometry(clientData) + ClientData clientData; /* Structure describing menu. */ +{ + TkMenu *menuPtr = (TkMenu *) clientData; + + if (menuPtr->tkwin == NULL) { + return; + } + + if (menuPtr->menuType == MENUBAR) { + TkpComputeMenubarGeometry(menuPtr); + } else { + TkpComputeStandardMenuGeometry(menuPtr); + } + + if ((menuPtr->totalWidth != Tk_ReqWidth(menuPtr->tkwin)) || + (menuPtr->totalHeight != Tk_ReqHeight(menuPtr->tkwin))) { + Tk_GeometryRequest(menuPtr->tkwin, menuPtr->totalWidth, + menuPtr->totalHeight); + } + + /* + * Must always force a redisplay here if the window is mapped + * (even if the size didn't change, something else might have + * changed in the menu, such as a label or accelerator). The + * resize will force a redisplay above. + */ + + TkEventuallyRedrawMenu(menuPtr, (TkMenuEntry *) NULL); + + menuPtr->menuFlags &= ~RESIZE_PENDING; +} + +/* + *---------------------------------------------------------------------- + * + * TkMenuSelectImageProc -- + * + * This procedure is invoked by the image code whenever the manager + * for an image does something that affects the size of contents + * of an image displayed in a menu entry when it is selected. + * + * Results: + * None. + * + * Side effects: + * Arranges for the menu to get redisplayed. + * + *---------------------------------------------------------------------- + */ + +void +TkMenuSelectImageProc(clientData, x, y, width, height, imgWidth, + imgHeight) + ClientData clientData; /* Pointer to widget record. */ + int x, y; /* Upper left pixel (within image) + * that must be redisplayed. */ + int width, height; /* Dimensions of area to redisplay + * (may be <= 0). */ + int imgWidth, imgHeight; /* New dimensions of image. */ +{ + register TkMenuEntry *mePtr = (TkMenuEntry *) clientData; + + if ((mePtr->entryFlags & ENTRY_SELECTED) + && !(mePtr->menuPtr->menuFlags & + REDRAW_PENDING)) { + mePtr->menuPtr->menuFlags |= REDRAW_PENDING; + Tcl_DoWhenIdle(DisplayMenu, (ClientData) mePtr->menuPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * DisplayMenu -- + * + * This procedure is invoked to display a menu widget. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static void +DisplayMenu(clientData) + ClientData clientData; /* Information about widget. */ +{ + register TkMenu *menuPtr = (TkMenu *) clientData; + register TkMenuEntry *mePtr; + register Tk_Window tkwin = menuPtr->tkwin; + int index, strictMotif; + Tk_Font tkfont = menuPtr->tkfont; + Tk_FontMetrics menuMetrics; + int width; + + menuPtr->menuFlags &= ~REDRAW_PENDING; + if ((menuPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + return; + } + + if (menuPtr->menuType == MENUBAR) { + Tk_Fill3DRectangle(tkwin, Tk_WindowId(tkwin), menuPtr->border, + menuPtr->borderWidth, menuPtr->borderWidth, + Tk_Width(tkwin) - 2 * menuPtr->borderWidth, + Tk_Height(tkwin) - 2 * menuPtr->borderWidth, 0, + TK_RELIEF_FLAT); + } + + strictMotif = Tk_StrictMotif(menuPtr->tkwin); + + /* + * See note in ComputeMenuGeometry. We don't want to be doing font metrics + * all of the time. + */ + + Tk_GetFontMetrics(menuPtr->tkfont, &menuMetrics); + + /* + * Loop through all of the entries, drawing them one at a time. + */ + + for (index = 0; index < menuPtr->numEntries; index++) { + mePtr = menuPtr->entries[index]; + if (menuPtr->menuType != MENUBAR) { + if (!(mePtr->entryFlags & ENTRY_NEEDS_REDISPLAY)) { + continue; + } + } + mePtr->entryFlags &= ~ENTRY_NEEDS_REDISPLAY; + + if (menuPtr->menuType == MENUBAR) { + width = mePtr->width; + } else { + if (mePtr->entryFlags & ENTRY_LAST_COLUMN) { + width = Tk_Width(menuPtr->tkwin) - mePtr->x + - menuPtr->activeBorderWidth; + } else { + width = mePtr->width + menuPtr->borderWidth; + } + } + TkpDrawMenuEntry(mePtr, Tk_WindowId(menuPtr->tkwin), tkfont, + &menuMetrics, mePtr->x, mePtr->y, width, + mePtr->height, strictMotif, 1); + if ((index > 0) && (menuPtr->menuType != MENUBAR) + && mePtr->columnBreak) { + mePtr = menuPtr->entries[index - 1]; + Tk_Fill3DRectangle(tkwin, Tk_WindowId(tkwin), menuPtr->border, + mePtr->x, mePtr->y + mePtr->height, + mePtr->width, + Tk_Height(tkwin) - mePtr->y - mePtr->height + - menuPtr->activeBorderWidth, 0, + TK_RELIEF_FLAT); + } + } + + if (menuPtr->menuType != MENUBAR) { + int x, y, height; + + if (menuPtr->numEntries == 0) { + x = y = menuPtr->borderWidth; + width = Tk_Width(tkwin) - 2 * menuPtr->activeBorderWidth; + height = Tk_Height(tkwin) - 2 * menuPtr->activeBorderWidth; + } else { + mePtr = menuPtr->entries[menuPtr->numEntries - 1]; + Tk_Fill3DRectangle(tkwin, Tk_WindowId(tkwin), + menuPtr->border, mePtr->x, mePtr->y + mePtr->height, + mePtr->width, Tk_Height(tkwin) - mePtr->y - mePtr->height + - menuPtr->activeBorderWidth, 0, + TK_RELIEF_FLAT); + x = mePtr->x + mePtr->width; + y = mePtr->y + mePtr->height; + width = Tk_Width(tkwin) - x - menuPtr->activeBorderWidth; + height = Tk_Height(tkwin) - y - menuPtr->activeBorderWidth; + } + Tk_Fill3DRectangle(tkwin, Tk_WindowId(tkwin), menuPtr->border, x, y, + width, height, 0, TK_RELIEF_FLAT); + } + + Tk_Draw3DRectangle(menuPtr->tkwin, Tk_WindowId(tkwin), + menuPtr->border, 0, 0, Tk_Width(tkwin), Tk_Height(tkwin), + menuPtr->borderWidth, menuPtr->relief); +} + +/* + *-------------------------------------------------------------- + * + * TkMenuEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on menus. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +void +TkMenuEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + TkMenu *menuPtr = (TkMenu *) clientData; + + if ((eventPtr->type == Expose) && (eventPtr->xexpose.count == 0)) { + TkEventuallyRedrawMenu(menuPtr, (TkMenuEntry *) NULL); + } else if (eventPtr->type == ConfigureNotify) { + TkEventuallyRecomputeMenu(menuPtr); + TkEventuallyRedrawMenu(menuPtr, (TkMenuEntry *) NULL); + } else if (eventPtr->type == ActivateNotify) { + if (menuPtr->menuType == TEAROFF_MENU) { + TkpSetMainMenubar(menuPtr->interp, menuPtr->tkwin, NULL); + } + } else if (eventPtr->type == DestroyNotify) { + if (menuPtr->tkwin != NULL) { + menuPtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(menuPtr->interp, menuPtr->widgetCmd); + } + if (menuPtr->menuFlags & REDRAW_PENDING) { + Tcl_CancelIdleCall(DisplayMenu, (ClientData) menuPtr); + } + if (menuPtr->menuFlags & RESIZE_PENDING) { + Tcl_CancelIdleCall(ComputeMenuGeometry, (ClientData) menuPtr); + } + TkDestroyMenu(menuPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMenuImageProc -- + * + * This procedure is invoked by the image code whenever the manager + * for an image does something that affects the size of contents + * of an image displayed in a menu entry. + * + * Results: + * None. + * + * Side effects: + * Arranges for the menu to get redisplayed. + * + *---------------------------------------------------------------------- + */ + +void +TkMenuImageProc(clientData, x, y, width, height, imgWidth, + imgHeight) + ClientData clientData; /* Pointer to widget record. */ + int x, y; /* Upper left pixel (within image) + * that must be redisplayed. */ + int width, height; /* Dimensions of area to redisplay + * (may be <= 0). */ + int imgWidth, imgHeight; /* New dimensions of image. */ +{ + register TkMenu *menuPtr = ((TkMenuEntry *)clientData)->menuPtr; + + if ((menuPtr->tkwin != NULL) && !(menuPtr->menuFlags + & RESIZE_PENDING)) { + menuPtr->menuFlags |= RESIZE_PENDING; + Tcl_DoWhenIdle(ComputeMenuGeometry, (ClientData) menuPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkPostTearoffMenu -- + * + * Posts a menu on the screen. Used to post tearoff menus. On Unix, + * all menus are posted this way. Adjusts the menu's position + * so that it fits on the screen, and maps and raises the menu. + * + * Results: + * Returns a standard Tcl Error. + * + * Side effects: + * The menu is posted. + * + *---------------------------------------------------------------------- + */ + +int +TkPostTearoffMenu(interp, menuPtr, x, y) + Tcl_Interp *interp; /* The interpreter of the menu */ + TkMenu *menuPtr; /* The menu we are posting */ + int x; /* The root X coordinate where we + * are posting */ + int y; /* The root Y coordinate where we + * are posting */ +{ + int vRootX, vRootY, vRootWidth, vRootHeight; + int tmp, result; + + TkActivateMenuEntry(menuPtr, -1); + TkRecomputeMenu(menuPtr); + result = TkPostCommand(menuPtr); + if (result != TCL_OK) { + return result; + } + + /* + * The post commands could have deleted the menu, which means + * we are dead and should go away. + */ + + if (menuPtr->tkwin == NULL) { + return TCL_OK; + } + + /* + * Adjust the position of the menu if necessary to keep it + * visible on the screen. There are two special tricks to + * make this work right: + * + * 1. If a virtual root window manager is being used then + * the coordinates are in the virtual root window of + * menuPtr's parent; since the menu uses override-redirect + * mode it will be in the *real* root window for the screen, + * so we have to map the coordinates from the virtual root + * (if any) to the real root. Can't get the virtual root + * from the menu itself (it will never be seen by the wm) + * so use its parent instead (it would be better to have an + * an option that names a window to use for this...). + * 2. The menu may not have been mapped yet, so its current size + * might be the default 1x1. To compute how much space it + * needs, use its requested size, not its actual size. + * + * Note that this code assumes square screen regions and all + * positive coordinates. This does not work on a Mac with + * multiple monitors. But then again, Tk has other problems + * with this. + */ + + Tk_GetVRootGeometry(Tk_Parent(menuPtr->tkwin), &vRootX, &vRootY, + &vRootWidth, &vRootHeight); + x += vRootX; + y += vRootY; + tmp = WidthOfScreen(Tk_Screen(menuPtr->tkwin)) + - Tk_ReqWidth(menuPtr->tkwin); + if (x > tmp) { + x = tmp; + } + if (x < 0) { + x = 0; + } + tmp = HeightOfScreen(Tk_Screen(menuPtr->tkwin)) + - Tk_ReqHeight(menuPtr->tkwin); + if (y > tmp) { + y = tmp; + } + if (y < 0) { + y = 0; + } + Tk_MoveToplevelWindow(menuPtr->tkwin, x, y); + if (!Tk_IsMapped(menuPtr->tkwin)) { + Tk_MapWindow(menuPtr->tkwin); + } + TkWmRestackToplevel((TkWindow *) menuPtr->tkwin, Above, NULL); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * TkPostSubmenu -- + * + * This procedure arranges for a particular submenu (i.e. the + * menu corresponding to a given cascade entry) to be + * posted. + * + * Results: + * A standard Tcl return result. Errors may occur in the + * Tcl commands generated to post and unpost submenus. + * + * Side effects: + * If there is already a submenu posted, it is unposted. + * The new submenu is then posted. + * + *-------------------------------------------------------------- + */ + +int +TkPostSubmenu(interp, menuPtr, mePtr) + Tcl_Interp *interp; /* Used for invoking sub-commands and + * reporting errors. */ + register TkMenu *menuPtr; /* Information about menu as a whole. */ + register TkMenuEntry *mePtr; /* Info about submenu that is to be + * posted. NULL means make sure that + * no submenu is posted. */ +{ + char string[30]; + int result, x, y; + + if (mePtr == menuPtr->postedCascade) { + return TCL_OK; + } + + if (menuPtr->postedCascade != NULL) { + + /* + * Note: when unposting a submenu, we have to redraw the entire + * parent menu. This is because of a combination of the following + * things: + * (a) the submenu partially overlaps the parent. + * (b) the submenu specifies "save under", which causes the X + * server to make a copy of the information under it when it + * is posted. When the submenu is unposted, the X server + * copies this data back and doesn't generate any Expose + * events for the parent. + * (c) the parent may have redisplayed itself after the submenu + * was posted, in which case the saved information is no + * longer correct. + * The simplest solution is just force a complete redisplay of + * the parent. + */ + + TkEventuallyRedrawMenu(menuPtr, (TkMenuEntry *) NULL); + result = Tcl_VarEval(interp, menuPtr->postedCascade->name, + " unpost", (char *) NULL); + menuPtr->postedCascade = NULL; + if (result != TCL_OK) { + return result; + } + } + + if ((mePtr != NULL) && (mePtr->name != NULL) + && Tk_IsMapped(menuPtr->tkwin)) { + + /* + * Position the cascade with its upper left corner slightly + * below and to the left of the upper right corner of the + * menu entry (this is an attempt to match Motif behavior). + * + * The menu has to redrawn so that the entry can change relief. + */ + + Tk_GetRootCoords(menuPtr->tkwin, &x, &y); + AdjustMenuCoords(menuPtr, mePtr, &x, &y, string); + result = Tcl_VarEval(interp, mePtr->name, " post ", string, + (char *) NULL); + if (result != TCL_OK) { + return result; + } + menuPtr->postedCascade = mePtr; + TkEventuallyRedrawMenu(menuPtr, mePtr); + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * AdjustMenuCoords -- + * + * Adjusts the given coordinates down and the left to give a Motif + * look. + * + * Results: + * None. + * + * Side effects: + * The menu is eventually redrawn if necessary. + * + *---------------------------------------------------------------------- + */ + +static void +AdjustMenuCoords(menuPtr, mePtr, xPtr, yPtr, string) + TkMenu *menuPtr; + TkMenuEntry *mePtr; + int *xPtr; + int *yPtr; + char *string; +{ + if (menuPtr->menuType == MENUBAR) { + *xPtr += mePtr->x; + *yPtr += mePtr->y + mePtr->height; + } else { + *xPtr += Tk_Width(menuPtr->tkwin) - menuPtr->borderWidth + - menuPtr->activeBorderWidth - 2; + *yPtr += mePtr->y + + menuPtr->activeBorderWidth + 2; + } + sprintf(string, "%d %d", *xPtr, *yPtr); +} diff --git a/generic/tkMenubutton.c b/generic/tkMenubutton.c new file mode 100644 index 0000000..ca2070e --- /dev/null +++ b/generic/tkMenubutton.c @@ -0,0 +1,865 @@ +/* + * tkMenubutton.c -- + * + * This module implements button-like widgets that are used + * to invoke pull-down menus. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMenubutton.c 1.94 97/07/31 09:10:37 + */ + +#include "tkMenubutton.h" +#include "tkPort.h" +#include "default.h" + +/* + * Uids internal to menubuttons. + */ + +static Tk_Uid aboveUid = NULL; +static Tk_Uid belowUid = NULL; +static Tk_Uid leftUid = NULL; +static Tk_Uid rightUid = NULL; +static Tk_Uid flushUid = NULL; + +/* + * Information used for parsing configuration specs: + */ + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_BORDER, "-activebackground", "activeBackground", "Foreground", + DEF_MENUBUTTON_ACTIVE_BG_COLOR, Tk_Offset(TkMenuButton, activeBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-activebackground", "activeBackground", "Foreground", + DEF_MENUBUTTON_ACTIVE_BG_MONO, Tk_Offset(TkMenuButton, activeBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_COLOR, "-activeforeground", "activeForeground", "Background", + DEF_MENUBUTTON_ACTIVE_FG_COLOR, Tk_Offset(TkMenuButton, activeFg), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-activeforeground", "activeForeground", "Background", + DEF_MENUBUTTON_ACTIVE_FG_MONO, Tk_Offset(TkMenuButton, activeFg), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_ANCHOR, "-anchor", "anchor", "Anchor", + DEF_MENUBUTTON_ANCHOR, Tk_Offset(TkMenuButton, anchor), 0}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_MENUBUTTON_BG_COLOR, Tk_Offset(TkMenuButton, normalBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_MENUBUTTON_BG_MONO, Tk_Offset(TkMenuButton, normalBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_BITMAP, "-bitmap", "bitmap", "Bitmap", + DEF_MENUBUTTON_BITMAP, Tk_Offset(TkMenuButton, bitmap), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_MENUBUTTON_BORDER_WIDTH, Tk_Offset(TkMenuButton, borderWidth), 0}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_MENUBUTTON_CURSOR, Tk_Offset(TkMenuButton, cursor), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_UID, "-direction", "direction", "Direction", + DEF_MENUBUTTON_DIRECTION, Tk_Offset(TkMenuButton, direction), + 0}, + {TK_CONFIG_COLOR, "-disabledforeground", "disabledForeground", + "DisabledForeground", DEF_MENUBUTTON_DISABLED_FG_COLOR, + Tk_Offset(TkMenuButton, disabledFg), + TK_CONFIG_COLOR_ONLY|TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-disabledforeground", "disabledForeground", + "DisabledForeground", DEF_MENUBUTTON_DISABLED_FG_MONO, + Tk_Offset(TkMenuButton, disabledFg), + TK_CONFIG_MONO_ONLY|TK_CONFIG_NULL_OK}, + {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_FONT, "-font", "font", "Font", + DEF_MENUBUTTON_FONT, Tk_Offset(TkMenuButton, tkfont), 0}, + {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground", + DEF_MENUBUTTON_FG, Tk_Offset(TkMenuButton, normalFg), 0}, + {TK_CONFIG_STRING, "-height", "height", "Height", + DEF_MENUBUTTON_HEIGHT, Tk_Offset(TkMenuButton, heightString), 0}, + {TK_CONFIG_COLOR, "-highlightbackground", "highlightBackground", + "HighlightBackground", DEF_MENUBUTTON_HIGHLIGHT_BG, + Tk_Offset(TkMenuButton, highlightBgColorPtr), 0}, + {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor", + DEF_MENUBUTTON_HIGHLIGHT, Tk_Offset(TkMenuButton, highlightColorPtr), + 0}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", DEF_MENUBUTTON_HIGHLIGHT_WIDTH, + Tk_Offset(TkMenuButton, highlightWidth), 0}, + {TK_CONFIG_STRING, "-image", "image", "Image", + DEF_MENUBUTTON_IMAGE, Tk_Offset(TkMenuButton, imageString), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-indicatoron", "indicatorOn", "IndicatorOn", + DEF_MENUBUTTON_INDICATOR, Tk_Offset(TkMenuButton, indicatorOn), 0}, + {TK_CONFIG_JUSTIFY, "-justify", "justify", "Justify", + DEF_MENUBUTTON_JUSTIFY, Tk_Offset(TkMenuButton, justify), 0}, + {TK_CONFIG_STRING, "-menu", "menu", "Menu", + DEF_MENUBUTTON_MENU, Tk_Offset(TkMenuButton, menuName), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-padx", "padX", "Pad", + DEF_MENUBUTTON_PADX, Tk_Offset(TkMenuButton, padX), 0}, + {TK_CONFIG_PIXELS, "-pady", "padY", "Pad", + DEF_MENUBUTTON_PADY, Tk_Offset(TkMenuButton, padY), 0}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_MENUBUTTON_RELIEF, Tk_Offset(TkMenuButton, relief), 0}, + {TK_CONFIG_UID, "-state", "state", "State", + DEF_MENUBUTTON_STATE, Tk_Offset(TkMenuButton, state), 0}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_MENUBUTTON_TAKE_FOCUS, Tk_Offset(TkMenuButton, takeFocus), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-text", "text", "Text", + DEF_MENUBUTTON_TEXT, Tk_Offset(TkMenuButton, text), 0}, + {TK_CONFIG_STRING, "-textvariable", "textVariable", "Variable", + DEF_MENUBUTTON_TEXT_VARIABLE, Tk_Offset(TkMenuButton, textVarName), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_INT, "-underline", "underline", "Underline", + DEF_MENUBUTTON_UNDERLINE, Tk_Offset(TkMenuButton, underline), 0}, + {TK_CONFIG_STRING, "-width", "width", "Width", + DEF_MENUBUTTON_WIDTH, Tk_Offset(TkMenuButton, widthString), 0}, + {TK_CONFIG_PIXELS, "-wraplength", "wrapLength", "WrapLength", + DEF_MENUBUTTON_WRAP_LENGTH, Tk_Offset(TkMenuButton, wrapLength), 0}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void MenuButtonCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static void MenuButtonEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void MenuButtonImageProc _ANSI_ARGS_((ClientData clientData, + int x, int y, int width, int height, int imgWidth, + int imgHeight)); +static char * MenuButtonTextVarProc _ANSI_ARGS_(( + ClientData clientData, Tcl_Interp *interp, + char *name1, char *name2, int flags)); +static int MenuButtonWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static int ConfigureMenuButton _ANSI_ARGS_((Tcl_Interp *interp, + TkMenuButton *mbPtr, int argc, char **argv, + int flags)); +static void DestroyMenuButton _ANSI_ARGS_((char *memPtr)); + +/* + *-------------------------------------------------------------- + * + * Tk_MenubuttonCmd -- + * + * This procedure is invoked to process the "button", "label", + * "radiobutton", and "checkbutton" Tcl commands. See the + * user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_MenubuttonCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register TkMenuButton *mbPtr; + Tk_Window tkwin = (Tk_Window) clientData; + Tk_Window new; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + /* + * Create the new window. + */ + + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *) NULL); + if (new == NULL) { + return TCL_ERROR; + } + + Tk_SetClass(new, "Menubutton"); + mbPtr = TkpCreateMenuButton(new); + + TkSetClassProcs(new, &tkpMenubuttonClass, (ClientData) mbPtr); + + /* + * Initialize the data structure for the button. + */ + + mbPtr->tkwin = new; + mbPtr->display = Tk_Display (new); + mbPtr->interp = interp; + mbPtr->widgetCmd = Tcl_CreateCommand(interp, Tk_PathName(mbPtr->tkwin), + MenuButtonWidgetCmd, (ClientData) mbPtr, MenuButtonCmdDeletedProc); + mbPtr->menuName = NULL; + mbPtr->text = NULL; + mbPtr->underline = -1; + mbPtr->textVarName = NULL; + mbPtr->bitmap = None; + mbPtr->imageString = NULL; + mbPtr->image = NULL; + mbPtr->state = tkNormalUid; + mbPtr->normalBorder = NULL; + mbPtr->activeBorder = NULL; + mbPtr->borderWidth = 0; + mbPtr->relief = TK_RELIEF_FLAT; + mbPtr->highlightWidth = 0; + mbPtr->highlightBgColorPtr = NULL; + mbPtr->highlightColorPtr = NULL; + mbPtr->inset = 0; + mbPtr->tkfont = NULL; + mbPtr->normalFg = NULL; + mbPtr->activeFg = NULL; + mbPtr->disabledFg = NULL; + mbPtr->normalTextGC = None; + mbPtr->activeTextGC = None; + mbPtr->gray = None; + mbPtr->disabledGC = None; + mbPtr->leftBearing = 0; + mbPtr->rightBearing = 0; + mbPtr->widthString = NULL; + mbPtr->heightString = NULL; + mbPtr->width = 0; + mbPtr->width = 0; + mbPtr->wrapLength = 0; + mbPtr->padX = 0; + mbPtr->padY = 0; + mbPtr->anchor = TK_ANCHOR_CENTER; + mbPtr->justify = TK_JUSTIFY_CENTER; + mbPtr->textLayout = NULL; + mbPtr->indicatorOn = 0; + mbPtr->indicatorWidth = 0; + mbPtr->indicatorHeight = 0; + mbPtr->cursor = None; + mbPtr->takeFocus = NULL; + mbPtr->flags = 0; + if (aboveUid == NULL) { + aboveUid = Tk_GetUid("above"); + belowUid = Tk_GetUid("below"); + leftUid = Tk_GetUid("left"); + rightUid = Tk_GetUid("right"); + flushUid = Tk_GetUid("flush"); + } + mbPtr->direction = flushUid; + + Tk_CreateEventHandler(mbPtr->tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + MenuButtonEventProc, (ClientData) mbPtr); + if (ConfigureMenuButton(interp, mbPtr, argc-2, argv+2, 0) != TCL_OK) { + Tk_DestroyWindow(mbPtr->tkwin); + return TCL_ERROR; + } + + interp->result = Tk_PathName(mbPtr->tkwin); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * MenuButtonWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a widget managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +MenuButtonWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about button widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register TkMenuButton *mbPtr = (TkMenuButton *) clientData; + int result; + size_t length; + int c; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) mbPtr); + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + result = TCL_ERROR; + } else { + result = Tk_ConfigureValue(interp, mbPtr->tkwin, configSpecs, + (char *) mbPtr, argv[2], 0); + } + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 2)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, mbPtr->tkwin, configSpecs, + (char *) mbPtr, (char *) NULL, 0); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, mbPtr->tkwin, configSpecs, + (char *) mbPtr, argv[2], 0); + } else { + result = ConfigureMenuButton(interp, mbPtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be cget or configure", + (char *) NULL); + result = TCL_ERROR; + } + Tcl_Release((ClientData) mbPtr); + return result; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyMenuButton -- + * + * This procedure is invoked to recycle all of the resources + * associated with a button widget. It is invoked as a + * when-idle handler in order to make sure that there is no + * other use of the button pending at the time of the deletion. + * + * Results: + * None. + * + * Side effects: + * Everything associated with the widget is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyMenuButton(memPtr) + char *memPtr; /* Info about button widget. */ +{ + register TkMenuButton *mbPtr = (TkMenuButton *) memPtr; + + /* + * Free up all the stuff that requires special handling, then + * let Tk_FreeOptions handle all the standard option-related + * stuff. + */ + + if (mbPtr->textVarName != NULL) { + Tcl_UntraceVar(mbPtr->interp, mbPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuButtonTextVarProc, (ClientData) mbPtr); + } + if (mbPtr->image != NULL) { + Tk_FreeImage(mbPtr->image); + } + if (mbPtr->normalTextGC != None) { + Tk_FreeGC(mbPtr->display, mbPtr->normalTextGC); + } + if (mbPtr->activeTextGC != None) { + Tk_FreeGC(mbPtr->display, mbPtr->activeTextGC); + } + if (mbPtr->gray != None) { + Tk_FreeBitmap(mbPtr->display, mbPtr->gray); + } + if (mbPtr->disabledGC != None) { + Tk_FreeGC(mbPtr->display, mbPtr->disabledGC); + } + Tk_FreeTextLayout(mbPtr->textLayout); + Tk_FreeOptions(configSpecs, (char *) mbPtr, mbPtr->display, 0); + ckfree((char *) mbPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureMenuButton -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or + * reconfigure) a menubutton widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as text string, colors, font, + * etc. get set for mbPtr; old resources get freed, if there + * were any. The menubutton is redisplayed. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureMenuButton(interp, mbPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + register TkMenuButton *mbPtr; /* Information about widget; may or may + * not already have values for some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + int result; + Tk_Image image; + + /* + * Eliminate any existing trace on variables monitored by the menubutton. + */ + + if (mbPtr->textVarName != NULL) { + Tcl_UntraceVar(interp, mbPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuButtonTextVarProc, (ClientData) mbPtr); + } + + result = Tk_ConfigureWidget(interp, mbPtr->tkwin, configSpecs, + argc, argv, (char *) mbPtr, flags); + if (result != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few options need special processing, such as setting the + * background from a 3-D border, or filling in complicated + * defaults that couldn't be specified to Tk_ConfigureWidget. + */ + + if ((mbPtr->state == tkActiveUid) && !Tk_StrictMotif(mbPtr->tkwin)) { + Tk_SetBackgroundFromBorder(mbPtr->tkwin, mbPtr->activeBorder); + } else { + Tk_SetBackgroundFromBorder(mbPtr->tkwin, mbPtr->normalBorder); + if ((mbPtr->state != tkNormalUid) && (mbPtr->state != tkActiveUid) + && (mbPtr->state != tkDisabledUid)) { + Tcl_AppendResult(interp, "bad state value \"", mbPtr->state, + "\": must be normal, active, or disabled", (char *) NULL); + mbPtr->state = tkNormalUid; + return TCL_ERROR; + } + } + + if ((mbPtr->direction != aboveUid) && (mbPtr->direction != belowUid) + && (mbPtr->direction != leftUid) && (mbPtr->direction != rightUid) + && (mbPtr->direction != flushUid)) { + Tcl_AppendResult(interp, "bad direction value \"", mbPtr->direction, + "\": must be above, below, left, right, or flush", + (char *) NULL); + mbPtr->direction = belowUid; + return TCL_ERROR; + } + + if (mbPtr->highlightWidth < 0) { + mbPtr->highlightWidth = 0; + } + + if (mbPtr->padX < 0) { + mbPtr->padX = 0; + } + if (mbPtr->padY < 0) { + mbPtr->padY = 0; + } + + /* + * Get the image for the widget, if there is one. Allocate the + * new image before freeing the old one, so that the reference + * count doesn't go to zero and cause image data to be discarded. + */ + + if (mbPtr->imageString != NULL) { + image = Tk_GetImage(mbPtr->interp, mbPtr->tkwin, + mbPtr->imageString, MenuButtonImageProc, (ClientData) mbPtr); + if (image == NULL) { + return TCL_ERROR; + } + } else { + image = NULL; + } + if (mbPtr->image != NULL) { + Tk_FreeImage(mbPtr->image); + } + mbPtr->image = image; + + if ((mbPtr->image == NULL) && (mbPtr->bitmap == None) + && (mbPtr->textVarName != NULL)) { + /* + * The menubutton displays a variable. Set up a trace to watch + * for any changes in it. + */ + + char *value; + + value = Tcl_GetVar(interp, mbPtr->textVarName, TCL_GLOBAL_ONLY); + if (value == NULL) { + Tcl_SetVar(interp, mbPtr->textVarName, mbPtr->text, + TCL_GLOBAL_ONLY); + } else { + if (mbPtr->text != NULL) { + ckfree(mbPtr->text); + } + mbPtr->text = (char *) ckalloc((unsigned) (strlen(value) + 1)); + strcpy(mbPtr->text, value); + } + Tcl_TraceVar(interp, mbPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuButtonTextVarProc, (ClientData) mbPtr); + } + + /* + * Recompute the geometry for the button. + */ + + if ((mbPtr->bitmap != None) || (mbPtr->image != NULL)) { + if (Tk_GetPixels(interp, mbPtr->tkwin, mbPtr->widthString, + &mbPtr->width) != TCL_OK) { + widthError: + Tcl_AddErrorInfo(interp, "\n (processing -width option)"); + return TCL_ERROR; + } + if (Tk_GetPixels(interp, mbPtr->tkwin, mbPtr->heightString, + &mbPtr->height) != TCL_OK) { + heightError: + Tcl_AddErrorInfo(interp, "\n (processing -height option)"); + return TCL_ERROR; + } + } else { + if (Tcl_GetInt(interp, mbPtr->widthString, &mbPtr->width) + != TCL_OK) { + goto widthError; + } + if (Tcl_GetInt(interp, mbPtr->heightString, &mbPtr->height) + != TCL_OK) { + goto heightError; + } + } + TkMenuButtonWorldChanged((ClientData) mbPtr); + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * TkMenuButtonWorldChanged -- + * + * This procedure is called when the world has changed in some + * way and the widget needs to recompute all its graphics contexts + * and determine its new geometry. + * + * Results: + * None. + * + * Side effects: + * TkMenuButton will be relayed out and redisplayed. + * + *--------------------------------------------------------------------------- + */ + +void +TkMenuButtonWorldChanged(instanceData) + ClientData instanceData; /* Information about widget. */ +{ + XGCValues gcValues; + GC gc; + unsigned long mask; + TkMenuButton *mbPtr; + + mbPtr = (TkMenuButton *) instanceData; + + gcValues.font = Tk_FontId(mbPtr->tkfont); + gcValues.foreground = mbPtr->normalFg->pixel; + gcValues.background = Tk_3DBorderColor(mbPtr->normalBorder)->pixel; + + /* + * Note: GraphicsExpose events are disabled in GC's because they're + * used to copy stuff from an off-screen pixmap onto the screen (we know + * that there's no problem with obscured areas). + */ + + gcValues.graphics_exposures = False; + mask = GCForeground | GCBackground | GCFont | GCGraphicsExposures; + gc = Tk_GetGC(mbPtr->tkwin, mask, &gcValues); + if (mbPtr->normalTextGC != None) { + Tk_FreeGC(mbPtr->display, mbPtr->normalTextGC); + } + mbPtr->normalTextGC = gc; + + gcValues.font = Tk_FontId(mbPtr->tkfont); + gcValues.foreground = mbPtr->activeFg->pixel; + gcValues.background = Tk_3DBorderColor(mbPtr->activeBorder)->pixel; + mask = GCForeground | GCBackground | GCFont; + gc = Tk_GetGC(mbPtr->tkwin, mask, &gcValues); + if (mbPtr->activeTextGC != None) { + Tk_FreeGC(mbPtr->display, mbPtr->activeTextGC); + } + mbPtr->activeTextGC = gc; + + gcValues.font = Tk_FontId(mbPtr->tkfont); + gcValues.background = Tk_3DBorderColor(mbPtr->normalBorder)->pixel; + if ((mbPtr->disabledFg != NULL) && (mbPtr->imageString == NULL)) { + gcValues.foreground = mbPtr->disabledFg->pixel; + mask = GCForeground | GCBackground | GCFont; + } else { + gcValues.foreground = gcValues.background; + mask = GCForeground; + if (mbPtr->gray == None) { + mbPtr->gray = Tk_GetBitmap(NULL, mbPtr->tkwin, + Tk_GetUid("gray50")); + } + if (mbPtr->gray != None) { + gcValues.fill_style = FillStippled; + gcValues.stipple = mbPtr->gray; + mask |= GCFillStyle | GCStipple; + } + } + gc = Tk_GetGC(mbPtr->tkwin, mask, &gcValues); + if (mbPtr->disabledGC != None) { + Tk_FreeGC(mbPtr->display, mbPtr->disabledGC); + } + mbPtr->disabledGC = gc; + + TkpComputeMenuButtonGeometry(mbPtr); + + /* + * Lastly, arrange for the button to be redisplayed. + */ + + if (Tk_IsMapped(mbPtr->tkwin) && !(mbPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(TkpDisplayMenuButton, (ClientData) mbPtr); + mbPtr->flags |= REDRAW_PENDING; + } +} + +/* + *-------------------------------------------------------------- + * + * MenuButtonEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on buttons. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +MenuButtonEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + TkMenuButton *mbPtr = (TkMenuButton *) clientData; + if ((eventPtr->type == Expose) && (eventPtr->xexpose.count == 0)) { + goto redraw; + } else if (eventPtr->type == ConfigureNotify) { + /* + * Must redraw after size changes, since layout could have changed + * and borders will need to be redrawn. + */ + + goto redraw; + } else if (eventPtr->type == DestroyNotify) { + TkpDestroyMenuButton(mbPtr); + if (mbPtr->tkwin != NULL) { + mbPtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(mbPtr->interp, mbPtr->widgetCmd); + } + if (mbPtr->flags & REDRAW_PENDING) { + Tcl_CancelIdleCall(TkpDisplayMenuButton, (ClientData) mbPtr); + } + Tcl_EventuallyFree((ClientData) mbPtr, DestroyMenuButton); + } else if (eventPtr->type == FocusIn) { + if (eventPtr->xfocus.detail != NotifyInferior) { + mbPtr->flags |= GOT_FOCUS; + if (mbPtr->highlightWidth > 0) { + goto redraw; + } + } + } else if (eventPtr->type == FocusOut) { + if (eventPtr->xfocus.detail != NotifyInferior) { + mbPtr->flags &= ~GOT_FOCUS; + if (mbPtr->highlightWidth > 0) { + goto redraw; + } + } + } + return; + + redraw: + if ((mbPtr->tkwin != NULL) && !(mbPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(TkpDisplayMenuButton, (ClientData) mbPtr); + mbPtr->flags |= REDRAW_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * MenuButtonCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +MenuButtonCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + TkMenuButton *mbPtr = (TkMenuButton *) clientData; + Tk_Window tkwin = mbPtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + mbPtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *-------------------------------------------------------------- + * + * MenuButtonTextVarProc -- + * + * This procedure is invoked when someone changes the variable + * whose contents are to be displayed in a menu button. + * + * Results: + * NULL is always returned. + * + * Side effects: + * The text displayed in the menu button will change to match the + * variable. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static char * +MenuButtonTextVarProc(clientData, interp, name1, name2, flags) + ClientData clientData; /* Information about button. */ + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *name1; /* Name of variable. */ + char *name2; /* Second part of variable name. */ + int flags; /* Information about what happened. */ +{ + register TkMenuButton *mbPtr = (TkMenuButton *) clientData; + char *value; + + /* + * If the variable is unset, then immediately recreate it unless + * the whole interpreter is going away. + */ + + if (flags & TCL_TRACE_UNSETS) { + if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + Tcl_SetVar(interp, mbPtr->textVarName, mbPtr->text, + TCL_GLOBAL_ONLY); + Tcl_TraceVar(interp, mbPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuButtonTextVarProc, clientData); + } + return (char *) NULL; + } + + value = Tcl_GetVar(interp, mbPtr->textVarName, TCL_GLOBAL_ONLY); + if (value == NULL) { + value = ""; + } + if (mbPtr->text != NULL) { + ckfree(mbPtr->text); + } + mbPtr->text = (char *) ckalloc((unsigned) (strlen(value) + 1)); + strcpy(mbPtr->text, value); + TkpComputeMenuButtonGeometry(mbPtr); + + if ((mbPtr->tkwin != NULL) && Tk_IsMapped(mbPtr->tkwin) + && !(mbPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(TkpDisplayMenuButton, (ClientData) mbPtr); + mbPtr->flags |= REDRAW_PENDING; + } + return (char *) NULL; +} + +/* + *---------------------------------------------------------------------- + * + * MenuButtonImageProc -- + * + * This procedure is invoked by the image code whenever the manager + * for an image does something that affects the size of contents + * of an image displayed in a button. + * + * Results: + * None. + * + * Side effects: + * Arranges for the button to get redisplayed. + * + *---------------------------------------------------------------------- + */ + +static void +MenuButtonImageProc(clientData, x, y, width, height, imgWidth, imgHeight) + ClientData clientData; /* Pointer to widget record. */ + int x, y; /* Upper left pixel (within image) + * that must be redisplayed. */ + int width, height; /* Dimensions of area to redisplay + * (may be <= 0). */ + int imgWidth, imgHeight; /* New dimensions of image. */ +{ + register TkMenuButton *mbPtr = (TkMenuButton *) clientData; + + if (mbPtr->tkwin != NULL) { + TkpComputeMenuButtonGeometry(mbPtr); + if (Tk_IsMapped(mbPtr->tkwin) && !(mbPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(TkpDisplayMenuButton, (ClientData) mbPtr); + mbPtr->flags |= REDRAW_PENDING; + } + } +} diff --git a/generic/tkMenubutton.h b/generic/tkMenubutton.h new file mode 100644 index 0000000..0fb0f65 --- /dev/null +++ b/generic/tkMenubutton.h @@ -0,0 +1,207 @@ +/* + * tkMenubutton.h -- + * + * Declarations of types and functions used to implement + * the menubutton widget. + * + * Copyright (c) 1996-1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMenubutton.h 1.3 97/04/11 11:24:15 + */ + +#ifndef _TKMENUBUTTON +#define _TKMENUBUTTON + +#ifndef _TKINT +#include "tkInt.h" +#endif + +/* + * A data structure of the following type is kept for each + * widget managed by this file: + */ + +typedef struct { + Tk_Window tkwin; /* Window that embodies the widget. NULL + * means that the window has been destroyed + * but the data structures haven't yet been + * cleaned up.*/ + Display *display; /* Display containing widget. Needed, among + * other things, so that resources can bee + * freed up even after tkwin has gone away. */ + Tcl_Interp *interp; /* Interpreter associated with menubutton. */ + Tcl_Command widgetCmd; /* Token for menubutton's widget command. */ + char *menuName; /* Name of menu associated with widget. + * Malloc-ed. */ + + /* + * Information about what's displayed in the menu button: + */ + + char *text; /* Text to display in button (malloc'ed) + * or NULL. */ + int underline; /* Index of character to underline. */ + char *textVarName; /* Name of variable (malloc'ed) or NULL. + * If non-NULL, button displays the contents + * of this variable. */ + Pixmap bitmap; /* Bitmap to display or None. If not None + * then text and textVar and underline + * are ignored. */ + char *imageString; /* Name of image to display (malloc'ed), or + * NULL. If non-NULL, bitmap, text, and + * textVarName are ignored. */ + Tk_Image image; /* Image to display in window, or NULL if + * none. */ + + /* + * Information used when displaying widget: + */ + + Tk_Uid state; /* State of button for display purposes: + * normal, active, or disabled. */ + Tk_3DBorder normalBorder; /* Structure used to draw 3-D + * border and background when window + * isn't active. NULL means no such + * border exists. */ + Tk_3DBorder activeBorder; /* Structure used to draw 3-D + * border and background when window + * is active. NULL means no such + * border exists. */ + int borderWidth; /* Width of border. */ + int relief; /* 3-d effect: TK_RELIEF_RAISED, etc. */ + int highlightWidth; /* Width in pixels of highlight to draw + * around widget when it has the focus. + * <= 0 means don't draw a highlight. */ + XColor *highlightBgColorPtr; + /* Color for drawing traversal highlight + * area when highlight is off. */ + XColor *highlightColorPtr; /* Color for drawing traversal highlight. */ + int inset; /* Total width of all borders, including + * traversal highlight and 3-D border. + * Indicates how much interior stuff must + * be offset from outside edges to leave + * room for borders. */ + Tk_Font tkfont; /* Information about text font, or NULL. */ + XColor *normalFg; /* Foreground color in normal mode. */ + XColor *activeFg; /* Foreground color in active mode. NULL + * means use normalFg instead. */ + XColor *disabledFg; /* Foreground color when disabled. NULL + * means use normalFg with a 50% stipple + * instead. */ + GC normalTextGC; /* GC for drawing text in normal mode. */ + GC activeTextGC; /* GC for drawing text in active mode (NULL + * means use normalTextGC). */ + Pixmap gray; /* Pixmap for displaying disabled text/icon if + * disabledFg is NULL. */ + GC disabledGC; /* Used to produce disabled effect. If + * disabledFg isn't NULL, this GC is used to + * draw button text or icon. Otherwise + * text or icon is drawn with normalGC and + * this GC is used to stipple background + * across it. */ + int leftBearing; /* Distance from text origin to leftmost drawn + * pixel (positive means to right). */ + int rightBearing; /* Amount text sticks right from its origin. */ + char *widthString; /* Value of -width option. Malloc'ed. */ + char *heightString; /* Value of -height option. Malloc'ed. */ + int width, height; /* If > 0, these specify dimensions to request + * for window, in characters for text and in + * pixels for bitmaps. In this case the actual + * size of the text string or bitmap is + * ignored in computing desired window size. */ + int wrapLength; /* Line length (in pixels) at which to wrap + * onto next line. <= 0 means don't wrap + * except at newlines. */ + int padX, padY; /* Extra space around text or bitmap (pixels + * on each side). */ + Tk_Anchor anchor; /* Where text/bitmap should be displayed + * inside window region. */ + Tk_Justify justify; /* Justification to use for multi-line text. */ + int textWidth; /* Width needed to display text as requested, + * in pixels. */ + int textHeight; /* Height needed to display text as requested, + * in pixels. */ + Tk_TextLayout textLayout; /* Saved text layout information. */ + int indicatorOn; /* Non-zero means display indicator; 0 means + * don't display. */ + int indicatorHeight; /* Height of indicator in pixels. This same + * amount of extra space is also left on each + * side of the indicator. 0 if no indicator. */ + int indicatorWidth; /* Width of indicator in pixels, including + * indicatorHeight in padding on each side. + * 0 if no indicator. */ + + /* + * Miscellaneous information: + */ + + Tk_Uid direction; /* Direction for where to pop the menu. + * Valid directions are "above", "below", + * "left", "right", and "flush". "flush" + * means that the upper left corner of the + * menubutton is where the menu pops up. + * "above" and "below" will attempt to pop + * the menu compleletly above or below + * the menu respectively. + * "left" and "right" will pop the menu + * left or right, and the active item + * will be next to the button. */ + Tk_Cursor cursor; /* Current cursor for window, or None. */ + char *takeFocus; /* Value of -takefocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + int flags; /* Various flags; see below for + * definitions. */ +} TkMenuButton; + +/* + * Flag bits for buttons: + * + * REDRAW_PENDING: Non-zero means a DoWhenIdle handler + * has already been queued to redraw + * this window. + * POSTED: Non-zero means that the menu associated + * with this button has been posted (typically + * because of an active button press). + * GOT_FOCUS: Non-zero means this button currently + * has the input focus. + */ + +#define REDRAW_PENDING 1 +#define POSTED 2 +#define GOT_FOCUS 4 + +/* + * The following constants define the dimensions of the cascade indicator, + * which is displayed if the "-indicatoron" option is true. The units for + * these options are 1/10 millimeters. + */ + +#define INDICATOR_WIDTH 40 +#define INDICATOR_HEIGHT 17 + +/* + * Declaration of variables shared between the files in the button module. + */ + +extern TkClassProcs tkpMenubuttonClass; + +/* + * Declaration of procedures used in the implementation of the button + * widget. + */ + +EXTERN void TkpComputeMenuButtonGeometry _ANSI_ARGS_(( + TkMenuButton *mbPtr)); +EXTERN TkMenuButton * TkpCreateMenuButton _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN void TkpDisplayMenuButton _ANSI_ARGS_(( + ClientData clientData)); +EXTERN void TkpDestroyMenuButton _ANSI_ARGS_(( + TkMenuButton *mbPtr)); +EXTERN void TkMenuButtonWorldChanged _ANSI_ARGS_(( + ClientData instanceData)); + +#endif /* _TKMENUBUTTON */ diff --git a/generic/tkMessage.c b/generic/tkMessage.c new file mode 100644 index 0000000..1984bac --- /dev/null +++ b/generic/tkMessage.c @@ -0,0 +1,848 @@ +/* + * tkMessage.c -- + * + * This module implements a message widgets for the Tk + * toolkit. A message widget displays a multi-line string + * in a window according to a particular aspect ratio. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMessage.c 1.75 97/07/31 09:11:14 + */ + +#include "tkPort.h" +#include "default.h" +#include "tkInt.h" + +/* + * A data structure of the following type is kept for each message + * widget managed by this file: + */ + +typedef struct { + Tk_Window tkwin; /* Window that embodies the message. NULL + * means that the window has been destroyed + * but the data structures haven't yet been + * cleaned up.*/ + Display *display; /* Display containing widget. Used, among + * other things, so that resources can be + * freed even after tkwin has gone away. */ + Tcl_Interp *interp; /* Interpreter associated with message. */ + Tcl_Command widgetCmd; /* Token for message's widget command. */ + + /* + * Information used when displaying widget: + */ + + char *string; /* String displayed in message. */ + int numChars; /* Number of characters in string, not + * including terminating NULL character. */ + char *textVarName; /* Name of variable (malloc'ed) or NULL. + * If non-NULL, message displays the contents + * of this variable. */ + Tk_3DBorder border; /* Structure used to draw 3-D border and + * background. NULL means a border hasn't + * been created yet. */ + int borderWidth; /* Width of border. */ + int relief; /* 3-D effect: TK_RELIEF_RAISED, etc. */ + int highlightWidth; /* Width in pixels of highlight to draw + * around widget when it has the focus. + * <= 0 means don't draw a highlight. */ + XColor *highlightBgColorPtr; + /* Color for drawing traversal highlight + * area when highlight is off. */ + XColor *highlightColorPtr; /* Color for drawing traversal highlight. */ + Tk_Font tkfont; /* Information about text font, or NULL. */ + XColor *fgColorPtr; /* Foreground color in normal mode. */ + int padX, padY; /* User-requested extra space around text. */ + int width; /* User-requested width, in pixels. 0 means + * compute width using aspect ratio below. */ + int aspect; /* Desired aspect ratio for window + * (100*width/height). */ + int msgWidth; /* Width in pixels needed to display + * message. */ + int msgHeight; /* Height in pixels needed to display + * message. */ + Tk_Anchor anchor; /* Where to position text within window region + * if window is larger or smaller than + * needed. */ + Tk_Justify justify; /* Justification for text. */ + + GC textGC; /* GC for drawing text in normal mode. */ + Tk_TextLayout textLayout; /* Saved layout information. */ + + /* + * Miscellaneous information: + */ + + Tk_Cursor cursor; /* Current cursor for window, or None. */ + char *takeFocus; /* Value of -takefocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + int flags; /* Various flags; see below for + * definitions. */ +} Message; + +/* + * Flag bits for messages: + * + * REDRAW_PENDING: Non-zero means a DoWhenIdle handler + * has already been queued to redraw + * this window. + * GOT_FOCUS: Non-zero means this button currently + * has the input focus. + */ + +#define REDRAW_PENDING 1 +#define GOT_FOCUS 4 + +/* + * Information used for argv parsing. + */ + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_ANCHOR, "-anchor", "anchor", "Anchor", + DEF_MESSAGE_ANCHOR, Tk_Offset(Message, anchor), 0}, + {TK_CONFIG_INT, "-aspect", "aspect", "Aspect", + DEF_MESSAGE_ASPECT, Tk_Offset(Message, aspect), 0}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_MESSAGE_BG_COLOR, Tk_Offset(Message, border), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_MESSAGE_BG_MONO, Tk_Offset(Message, border), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_MESSAGE_BORDER_WIDTH, Tk_Offset(Message, borderWidth), 0}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_MESSAGE_CURSOR, Tk_Offset(Message, cursor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_FONT, "-font", "font", "Font", + DEF_MESSAGE_FONT, Tk_Offset(Message, tkfont), 0}, + {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground", + DEF_MESSAGE_FG, Tk_Offset(Message, fgColorPtr), 0}, + {TK_CONFIG_COLOR, "-highlightbackground", "highlightBackground", + "HighlightBackground", DEF_MESSAGE_HIGHLIGHT_BG, + Tk_Offset(Message, highlightBgColorPtr), 0}, + {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor", + DEF_MESSAGE_HIGHLIGHT, Tk_Offset(Message, highlightColorPtr), 0}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", + DEF_MESSAGE_HIGHLIGHT_WIDTH, Tk_Offset(Message, highlightWidth), 0}, + {TK_CONFIG_JUSTIFY, "-justify", "justify", "Justify", + DEF_MESSAGE_JUSTIFY, Tk_Offset(Message, justify), 0}, + {TK_CONFIG_PIXELS, "-padx", "padX", "Pad", + DEF_MESSAGE_PADX, Tk_Offset(Message, padX), 0}, + {TK_CONFIG_PIXELS, "-pady", "padY", "Pad", + DEF_MESSAGE_PADY, Tk_Offset(Message, padY), 0}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_MESSAGE_RELIEF, Tk_Offset(Message, relief), 0}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_MESSAGE_TAKE_FOCUS, Tk_Offset(Message, takeFocus), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-text", "text", "Text", + DEF_MESSAGE_TEXT, Tk_Offset(Message, string), 0}, + {TK_CONFIG_STRING, "-textvariable", "textVariable", "Variable", + DEF_MESSAGE_TEXT_VARIABLE, Tk_Offset(Message, textVarName), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-width", "width", "Width", + DEF_MESSAGE_WIDTH, Tk_Offset(Message, width), 0}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void MessageCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static void MessageEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static char * MessageTextVarProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, char *name1, char *name2, + int flags)); +static int MessageWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void MessageWorldChanged _ANSI_ARGS_(( + ClientData instanceData)); +static void ComputeMessageGeometry _ANSI_ARGS_((Message *msgPtr)); +static int ConfigureMessage _ANSI_ARGS_((Tcl_Interp *interp, + Message *msgPtr, int argc, char **argv, + int flags)); +static void DestroyMessage _ANSI_ARGS_((char *memPtr)); +static void DisplayMessage _ANSI_ARGS_((ClientData clientData)); + +/* + * The structure below defines message class behavior by means of procedures + * that can be invoked from generic window code. + */ + +static TkClassProcs messageClass = { + NULL, /* createProc. */ + MessageWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + + +/* + *-------------------------------------------------------------- + * + * Tk_MessageCmd -- + * + * This procedure is invoked to process the "message" Tcl + * command. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_MessageCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register Message *msgPtr; + Tk_Window new; + Tk_Window tkwin = (Tk_Window) clientData; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *) NULL); + if (new == NULL) { + return TCL_ERROR; + } + + msgPtr = (Message *) ckalloc(sizeof(Message)); + msgPtr->tkwin = new; + msgPtr->display = Tk_Display(new); + msgPtr->interp = interp; + msgPtr->widgetCmd = Tcl_CreateCommand(interp, Tk_PathName(msgPtr->tkwin), + MessageWidgetCmd, (ClientData) msgPtr, MessageCmdDeletedProc); + msgPtr->textLayout = NULL; + msgPtr->string = NULL; + msgPtr->numChars = 0; + msgPtr->textVarName = NULL; + msgPtr->border = NULL; + msgPtr->borderWidth = 0; + msgPtr->relief = TK_RELIEF_FLAT; + msgPtr->highlightWidth = 0; + msgPtr->highlightBgColorPtr = NULL; + msgPtr->highlightColorPtr = NULL; + msgPtr->tkfont = NULL; + msgPtr->fgColorPtr = NULL; + msgPtr->textGC = None; + msgPtr->padX = 0; + msgPtr->padY = 0; + msgPtr->anchor = TK_ANCHOR_CENTER; + msgPtr->width = 0; + msgPtr->aspect = 150; + msgPtr->msgWidth = 0; + msgPtr->msgHeight = 0; + msgPtr->justify = TK_JUSTIFY_LEFT; + msgPtr->cursor = None; + msgPtr->takeFocus = NULL; + msgPtr->flags = 0; + + Tk_SetClass(msgPtr->tkwin, "Message"); + TkSetClassProcs(msgPtr->tkwin, &messageClass, (ClientData) msgPtr); + Tk_CreateEventHandler(msgPtr->tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + MessageEventProc, (ClientData) msgPtr); + if (ConfigureMessage(interp, msgPtr, argc-2, argv+2, 0) != TCL_OK) { + goto error; + } + + interp->result = Tk_PathName(msgPtr->tkwin); + return TCL_OK; + + error: + Tk_DestroyWindow(msgPtr->tkwin); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * MessageWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a widget managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +MessageWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about message widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register Message *msgPtr = (Message *) clientData; + size_t length; + int c; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + return TCL_ERROR; + } + return Tk_ConfigureValue(interp, msgPtr->tkwin, configSpecs, + (char *) msgPtr, argv[2], 0); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 2)) { + if (argc == 2) { + return Tk_ConfigureInfo(interp, msgPtr->tkwin, configSpecs, + (char *) msgPtr, (char *) NULL, 0); + } else if (argc == 3) { + return Tk_ConfigureInfo(interp, msgPtr->tkwin, configSpecs, + (char *) msgPtr, argv[2], 0); + } else { + return ConfigureMessage(interp, msgPtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be cget or configure", (char *) NULL); + return TCL_ERROR; + } +} + +/* + *---------------------------------------------------------------------- + * + * DestroyMessage -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a message at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the message is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyMessage(memPtr) + char *memPtr; /* Info about message widget. */ +{ + register Message *msgPtr = (Message *) memPtr; + + /* + * Free up all the stuff that requires special handling, then + * let Tk_FreeOptions handle all the standard option-related + * stuff. + */ + + Tk_FreeTextLayout(msgPtr->textLayout); + if (msgPtr->textVarName != NULL) { + Tcl_UntraceVar(msgPtr->interp, msgPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MessageTextVarProc, (ClientData) msgPtr); + } + if (msgPtr->textGC != None) { + Tk_FreeGC(msgPtr->display, msgPtr->textGC); + } + Tk_FreeOptions(configSpecs, (char *) msgPtr, msgPtr->display, 0); + ckfree((char *) msgPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureMessage -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or + * reconfigure) a message widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as text string, colors, font, + * etc. get set for msgPtr; old resources get freed, if there + * were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureMessage(interp, msgPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + register Message *msgPtr; /* Information about widget; may or may + * not already have values for some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + /* + * Eliminate any existing trace on a variable monitored by the message. + */ + + if (msgPtr->textVarName != NULL) { + Tcl_UntraceVar(interp, msgPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MessageTextVarProc, (ClientData) msgPtr); + } + + if (Tk_ConfigureWidget(interp, msgPtr->tkwin, configSpecs, + argc, argv, (char *) msgPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * If the message is to display the value of a variable, then set up + * a trace on the variable's value, create the variable if it doesn't + * exist, and fetch its current value. + */ + + if (msgPtr->textVarName != NULL) { + char *value; + + value = Tcl_GetVar(interp, msgPtr->textVarName, TCL_GLOBAL_ONLY); + if (value == NULL) { + Tcl_SetVar(interp, msgPtr->textVarName, msgPtr->string, + TCL_GLOBAL_ONLY); + } else { + if (msgPtr->string != NULL) { + ckfree(msgPtr->string); + } + msgPtr->string = strcpy(ckalloc(strlen(value) + 1), value); + } + Tcl_TraceVar(interp, msgPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MessageTextVarProc, (ClientData) msgPtr); + } + + /* + * A few other options need special processing, such as setting + * the background from a 3-D border or handling special defaults + * that couldn't be specified to Tk_ConfigureWidget. + */ + + msgPtr->numChars = strlen(msgPtr->string); + + Tk_SetBackgroundFromBorder(msgPtr->tkwin, msgPtr->border); + + if (msgPtr->highlightWidth < 0) { + msgPtr->highlightWidth = 0; + } + + MessageWorldChanged((ClientData) msgPtr); + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * MessageWorldChanged -- + * + * This procedure is called when the world has changed in some + * way and the widget needs to recompute all its graphics contexts + * and determine its new geometry. + * + * Results: + * None. + * + * Side effects: + * Message will be relayed out and redisplayed. + * + *--------------------------------------------------------------------------- + */ + +static void +MessageWorldChanged(instanceData) + ClientData instanceData; /* Information about widget. */ +{ + XGCValues gcValues; + GC gc; + Tk_FontMetrics fm; + Message *msgPtr; + + msgPtr = (Message *) instanceData; + + gcValues.font = Tk_FontId(msgPtr->tkfont); + gcValues.foreground = msgPtr->fgColorPtr->pixel; + gc = Tk_GetGC(msgPtr->tkwin, GCForeground | GCFont, &gcValues); + if (msgPtr->textGC != None) { + Tk_FreeGC(msgPtr->display, msgPtr->textGC); + } + msgPtr->textGC = gc; + + Tk_GetFontMetrics(msgPtr->tkfont, &fm); + if (msgPtr->padX < 0) { + msgPtr->padX = fm.ascent / 2; + } + if (msgPtr->padY == -1) { + msgPtr->padY = fm.ascent / 4; + } + + /* + * Recompute the desired geometry for the window, and arrange for + * the window to be redisplayed. + */ + + ComputeMessageGeometry(msgPtr); + if ((msgPtr->tkwin != NULL) && Tk_IsMapped(msgPtr->tkwin) + && !(msgPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayMessage, (ClientData) msgPtr); + msgPtr->flags |= REDRAW_PENDING; + } +} + +/* + *-------------------------------------------------------------- + * + * ComputeMessageGeometry -- + * + * Compute the desired geometry for a message window, + * taking into account the desired aspect ratio for the + * window. + * + * Results: + * None. + * + * Side effects: + * Tk_GeometryRequest is called to inform the geometry + * manager of the desired geometry for this window. + * + *-------------------------------------------------------------- + */ + +static void +ComputeMessageGeometry(msgPtr) + register Message *msgPtr; /* Information about window. */ +{ + int width, inc, height; + int thisWidth, thisHeight, maxWidth; + int aspect, lowerBound, upperBound, inset; + + Tk_FreeTextLayout(msgPtr->textLayout); + + inset = msgPtr->borderWidth + msgPtr->highlightWidth; + + /* + * Compute acceptable bounds for the final aspect ratio. + */ + + aspect = msgPtr->aspect/10; + if (aspect < 5) { + aspect = 5; + } + lowerBound = msgPtr->aspect - aspect; + upperBound = msgPtr->aspect + aspect; + + /* + * Do the computation in multiple passes: start off with + * a very wide window, and compute its height. Then change + * the width and try again. Reduce the size of the change + * and iterate until dimensions are found that approximate + * the desired aspect ratio. Or, if the user gave an explicit + * width then just use that. + */ + + if (msgPtr->width > 0) { + width = msgPtr->width; + inc = 0; + } else { + width = WidthOfScreen(Tk_Screen(msgPtr->tkwin))/2; + inc = width/2; + } + + for ( ; ; inc /= 2) { + msgPtr->textLayout = Tk_ComputeTextLayout(msgPtr->tkfont, + msgPtr->string, msgPtr->numChars, width, msgPtr->justify, + 0, &thisWidth, &thisHeight); + maxWidth = thisWidth + 2 * (inset + msgPtr->padX); + height = thisHeight + 2 * (inset + msgPtr->padY); + + if (inc <= 2) { + break; + } + aspect = (100 * maxWidth) / height; + + if (aspect < lowerBound) { + width += inc; + } else if (aspect > upperBound) { + width -= inc; + } else { + break; + } + Tk_FreeTextLayout(msgPtr->textLayout); + } + msgPtr->msgWidth = thisWidth; + msgPtr->msgHeight = thisHeight; + Tk_GeometryRequest(msgPtr->tkwin, maxWidth, height); + Tk_SetInternalBorder(msgPtr->tkwin, inset); +} + +/* + *-------------------------------------------------------------- + * + * DisplayMessage -- + * + * This procedure redraws the contents of a message window. + * + * Results: + * None. + * + * Side effects: + * Information appears on the screen. + * + *-------------------------------------------------------------- + */ + +static void +DisplayMessage(clientData) + ClientData clientData; /* Information about window. */ +{ + register Message *msgPtr = (Message *) clientData; + register Tk_Window tkwin = msgPtr->tkwin; + int x, y; + + msgPtr->flags &= ~REDRAW_PENDING; + if ((msgPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + return; + } + Tk_Fill3DRectangle(tkwin, Tk_WindowId(tkwin), msgPtr->border, 0, 0, + Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); + + /* + * Compute starting y-location for message based on message size + * and anchor option. + */ + + TkComputeAnchor(msgPtr->anchor, tkwin, msgPtr->padX, msgPtr->padY, + msgPtr->msgWidth, msgPtr->msgHeight, &x, &y); + Tk_DrawTextLayout(Tk_Display(tkwin), Tk_WindowId(tkwin), msgPtr->textGC, + msgPtr->textLayout, x, y, 0, -1); + + if (msgPtr->relief != TK_RELIEF_FLAT) { + Tk_Draw3DRectangle(tkwin, Tk_WindowId(tkwin), msgPtr->border, + msgPtr->highlightWidth, msgPtr->highlightWidth, + Tk_Width(tkwin) - 2*msgPtr->highlightWidth, + Tk_Height(tkwin) - 2*msgPtr->highlightWidth, + msgPtr->borderWidth, msgPtr->relief); + } + if (msgPtr->highlightWidth != 0) { + GC gc; + + if (msgPtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(msgPtr->highlightColorPtr, Tk_WindowId(tkwin)); + } else { + gc = Tk_GCForColor(msgPtr->highlightBgColorPtr, Tk_WindowId(tkwin)); + } + Tk_DrawFocusHighlight(tkwin, gc, msgPtr->highlightWidth, + Tk_WindowId(tkwin)); + } +} + +/* + *-------------------------------------------------------------- + * + * MessageEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on messages. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +MessageEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + Message *msgPtr = (Message *) clientData; + + if (((eventPtr->type == Expose) && (eventPtr->xexpose.count == 0)) + || (eventPtr->type == ConfigureNotify)) { + goto redraw; + } else if (eventPtr->type == DestroyNotify) { + if (msgPtr->tkwin != NULL) { + msgPtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(msgPtr->interp, msgPtr->widgetCmd); + } + if (msgPtr->flags & REDRAW_PENDING) { + Tcl_CancelIdleCall(DisplayMessage, (ClientData) msgPtr); + } + Tcl_EventuallyFree((ClientData) msgPtr, DestroyMessage); + } else if (eventPtr->type == FocusIn) { + if (eventPtr->xfocus.detail != NotifyInferior) { + msgPtr->flags |= GOT_FOCUS; + if (msgPtr->highlightWidth > 0) { + goto redraw; + } + } + } else if (eventPtr->type == FocusOut) { + if (eventPtr->xfocus.detail != NotifyInferior) { + msgPtr->flags &= ~GOT_FOCUS; + if (msgPtr->highlightWidth > 0) { + goto redraw; + } + } + } + return; + + redraw: + if ((msgPtr->tkwin != NULL) && !(msgPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayMessage, (ClientData) msgPtr); + msgPtr->flags |= REDRAW_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * MessageCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +MessageCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + Message *msgPtr = (Message *) clientData; + Tk_Window tkwin = msgPtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + msgPtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *-------------------------------------------------------------- + * + * MessageTextVarProc -- + * + * This procedure is invoked when someone changes the variable + * whose contents are to be displayed in a message. + * + * Results: + * NULL is always returned. + * + * Side effects: + * The text displayed in the message will change to match the + * variable. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static char * +MessageTextVarProc(clientData, interp, name1, name2, flags) + ClientData clientData; /* Information about message. */ + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *name1; /* Name of variable. */ + char *name2; /* Second part of variable name. */ + int flags; /* Information about what happened. */ +{ + register Message *msgPtr = (Message *) clientData; + char *value; + + /* + * If the variable is unset, then immediately recreate it unless + * the whole interpreter is going away. + */ + + if (flags & TCL_TRACE_UNSETS) { + if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + Tcl_SetVar(interp, msgPtr->textVarName, msgPtr->string, + TCL_GLOBAL_ONLY); + Tcl_TraceVar(interp, msgPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MessageTextVarProc, clientData); + } + return (char *) NULL; + } + + value = Tcl_GetVar(interp, msgPtr->textVarName, TCL_GLOBAL_ONLY); + if (value == NULL) { + value = ""; + } + if (msgPtr->string != NULL) { + ckfree(msgPtr->string); + } + msgPtr->numChars = strlen(value); + msgPtr->string = (char *) ckalloc((unsigned) (msgPtr->numChars + 1)); + strcpy(msgPtr->string, value); + ComputeMessageGeometry(msgPtr); + + if ((msgPtr->tkwin != NULL) && Tk_IsMapped(msgPtr->tkwin) + && !(msgPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayMessage, (ClientData) msgPtr); + msgPtr->flags |= REDRAW_PENDING; + } + return (char *) NULL; +} diff --git a/generic/tkOption.c b/generic/tkOption.c new file mode 100644 index 0000000..b2bef64 --- /dev/null +++ b/generic/tkOption.c @@ -0,0 +1,1397 @@ +/* + * tkOption.c -- + * + * This module contains procedures to manage the option + * database, which allows various strings to be associated + * with windows either by name or by class or both. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkOption.c 1.57 96/10/17 15:16:45 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * The option database is stored as one tree for each main window. + * Each name or class field in an option is associated with a node or + * leaf of the tree. For example, the options "x.y.z" and "x.y*a" + * each correspond to three nodes in the tree; they share the nodes + * "x" and "x.y", but have different leaf nodes. One of the following + * structures exists for each node or leaf in the option tree. It is + * actually stored as part of the parent node, and describes a particular + * child of the parent. + */ + +typedef struct Element { + Tk_Uid nameUid; /* Name or class from one element of + * an option spec. */ + union { + struct ElArray *arrayPtr; /* If this is an intermediate node, + * a pointer to a structure describing + * the remaining elements of all + * options whose prefixes are the + * same up through this element. */ + Tk_Uid valueUid; /* For leaf nodes, this is the string + * value of the option. */ + } child; + int priority; /* Used to select among matching + * options. Includes both the + * priority level and a serial #. + * Greater value means higher + * priority. Irrelevant except in + * leaf nodes. */ + int flags; /* OR-ed combination of bits. See + * below for values. */ +} Element; + +/* + * Flags in Element structures: + * + * CLASS - Non-zero means this element refers to a class, + * Zero means this element refers to a name. + * NODE - Zero means this is a leaf element (the child + * field is a value, not a pointer to another node). + * One means this is a node element. + * WILDCARD - Non-zero means this there was a star in the + * original specification just before this element. + * Zero means there was a dot. + */ + +#define TYPE_MASK 0x7 + +#define CLASS 0x1 +#define NODE 0x2 +#define WILDCARD 0x4 + +#define EXACT_LEAF_NAME 0x0 +#define EXACT_LEAF_CLASS 0x1 +#define EXACT_NODE_NAME 0x2 +#define EXACT_NODE_CLASS 0x3 +#define WILDCARD_LEAF_NAME 0x4 +#define WILDCARD_LEAF_CLASS 0x5 +#define WILDCARD_NODE_NAME 0x6 +#define WILDCARD_NODE_CLASS 0x7 + +/* + * The following structure is used to manage a dynamic array of + * Elements. These structures are used for two purposes: to store + * the contents of a node in the option tree, and for the option + * stacks described below. + */ + +typedef struct ElArray { + int arraySize; /* Number of elements actually + * allocated in the "els" array. */ + int numUsed; /* Number of elements currently in + * use out of els. */ + Element *nextToUse; /* Pointer to &els[numUsed]. */ + Element els[1]; /* Array of structures describing + * children of this node. The + * array will actually contain enough + * elements for all of the children + * (and even a few extras, perhaps). + * This must be the last field in + * the structure. */ +} ElArray; + +#define EL_ARRAY_SIZE(numEls) ((unsigned) (sizeof(ElArray) \ + + ((numEls)-1)*sizeof(Element))) +#define INITIAL_SIZE 5 + +/* + * In addition to the option tree, which is a relatively static structure, + * there are eight additional structures called "stacks", which are used + * to speed up queries into the option database. The stack structures + * are designed for the situation where an individual widget makes repeated + * requests for its particular options. The requests differ only in + * their last name/class, so during the first request we extract all + * the options pertaining to the particular widget and save them in a + * stack-like cache; subsequent requests for the same widget can search + * the cache relatively quickly. In fact, the cache is a hierarchical + * one, storing a list of relevant options for this widget and all of + * its ancestors up to the application root; hence the name "stack". + * + * Each of the eight stacks consists of an array of Elements, ordered in + * terms of levels in the window hierarchy. All the elements relevant + * for the top-level widget appear first in the array, followed by all + * those from the next-level widget on the path to the current widget, + * etc. down to those for the current widget. + * + * Cached information is divided into eight stacks according to the + * CLASS, NODE, and WILDCARD flags. Leaf and non-leaf information is + * kept separate to speed up individual probes (non-leaf information is + * only relevant when building the stacks, but isn't relevant when + * making probes; similarly, only non-leaf information is relevant + * when the stacks are being extended to the next widget down in the + * widget hierarchy). Wildcard elements are handled separately from + * "exact" elements because once they appear at a particular level in + * the stack they remain active for all deeper levels; exact elements + * are only relevant at a particular level. For example, when searching + * for options relevant in a particular window, the entire wildcard + * stacks get checked, but only the portions of the exact stacks that + * pertain to the window's parent. Lastly, name and class stacks are + * kept separate because different search keys are used when searching + * them; keeping them separate speeds up the searches. + */ + +#define NUM_STACKS 8 +static ElArray *stacks[NUM_STACKS]; +static TkWindow *cachedWindow = NULL; /* Lowest-level window currently + * loaded in stacks at present. + * NULL means stacks have never + * been used, or have been + * invalidated because of a change + * to the database. */ + +/* + * One of the following structures is used to keep track of each + * level in the stacks. + */ + +typedef struct StackLevel { + TkWindow *winPtr; /* Window corresponding to this stack + * level. */ + int bases[NUM_STACKS]; /* For each stack, index of first + * element on stack corresponding to + * this level (used to restore "numUsed" + * fields when popping out of a level. */ +} StackLevel; + +/* + * Information about all of the stack levels that are currently + * active. This array grows dynamically to become as large as needed. + */ + +static StackLevel *levels = NULL; + /* Array describing current stack. */ +static int numLevels = 0; /* Total space allocated. */ +static int curLevel = -1; /* Highest level currently in use. Note: + * curLevel is never 0! (I don't remember + * why anymore...) */ + +/* + * The variable below is a serial number for all options entered into + * the database so far. It increments on each addition to the option + * database. It is used in computing option priorities, so that the + * most recent entry wins when choosing between options at the same + * priority level. + */ + +static int serial = 0; + +/* + * Special "no match" Element to use as default for searches. + */ + +static Element defaultMatch; + +/* + * Forward declarations for procedures defined in this file: + */ + +static int AddFromString _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *string, int priority)); +static void ClearOptionTree _ANSI_ARGS_((ElArray *arrayPtr)); +static ElArray * ExtendArray _ANSI_ARGS_((ElArray *arrayPtr, + Element *elPtr)); +static void ExtendStacks _ANSI_ARGS_((ElArray *arrayPtr, + int leaf)); +static int GetDefaultOptions _ANSI_ARGS_((Tcl_Interp *interp, + TkWindow *winPtr)); +static ElArray * NewArray _ANSI_ARGS_((int numEls)); +static void OptionInit _ANSI_ARGS_((TkMainInfo *mainPtr)); +static int ParsePriority _ANSI_ARGS_((Tcl_Interp *interp, + char *string)); +static int ReadOptionFile _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *fileName, int priority)); +static void SetupStacks _ANSI_ARGS_((TkWindow *winPtr, int leaf)); + +/* + *-------------------------------------------------------------- + * + * Tk_AddOption -- + * + * Add a new option to the option database. + * + * Results: + * None. + * + * Side effects: + * Information is added to the option database. + * + *-------------------------------------------------------------- + */ + +void +Tk_AddOption(tkwin, name, value, priority) + Tk_Window tkwin; /* Window token; option will be associated + * with main window for this window. */ + char *name; /* Multi-element name of option. */ + char *value; /* String value for option. */ + int priority; /* Overall priority level to use for + * this option, such as TK_USER_DEFAULT_PRIO + * or TK_INTERACTIVE_PRIO. Must be between + * 0 and TK_MAX_PRIO. */ +{ + TkWindow *winPtr = ((TkWindow *) tkwin)->mainPtr->winPtr; + register ElArray **arrayPtrPtr; + register Element *elPtr; + Element newEl; + register char *p; + char *field; + int count, firstField, length; +#define TMP_SIZE 100 + char tmp[TMP_SIZE+1]; + + if (winPtr->mainPtr->optionRootPtr == NULL) { + OptionInit(winPtr->mainPtr); + } + cachedWindow = NULL; /* Invalidate the cache. */ + + /* + * Compute the priority for the new element, including both the + * overall level and the serial number (to disambiguate with the + * level). + */ + + if (priority < 0) { + priority = 0; + } else if (priority > TK_MAX_PRIO) { + priority = TK_MAX_PRIO; + } + newEl.priority = (priority << 24) + serial; + serial++; + + /* + * Parse the option one field at a time. + */ + + arrayPtrPtr = &(((TkWindow *) tkwin)->mainPtr->optionRootPtr); + p = name; + for (firstField = 1; ; firstField = 0) { + + /* + * Scan the next field from the name and convert it to a Tk_Uid. + * Must copy the field before calling Tk_Uid, so that a terminating + * NULL may be added without modifying the source string. + */ + + if (*p == '*') { + newEl.flags = WILDCARD; + p++; + } else { + newEl.flags = 0; + } + field = p; + while ((*p != 0) && (*p != '.') && (*p != '*')) { + p++; + } + length = p - field; + if (length > TMP_SIZE) { + length = TMP_SIZE; + } + strncpy(tmp, field, (size_t) length); + tmp[length] = 0; + newEl.nameUid = Tk_GetUid(tmp); + if (isupper(UCHAR(*field))) { + newEl.flags |= CLASS; + } + + if (*p != 0) { + + /* + * New element will be a node. If this option can't possibly + * apply to this main window, then just skip it. Otherwise, + * add it to the parent, if it isn't already there, and descend + * into it. + */ + + newEl.flags |= NODE; + if (firstField && !(newEl.flags & WILDCARD) + && (newEl.nameUid != winPtr->nameUid) + && (newEl.nameUid != winPtr->classUid)) { + return; + } + for (elPtr = (*arrayPtrPtr)->els, count = (*arrayPtrPtr)->numUsed; + ; elPtr++, count--) { + if (count == 0) { + newEl.child.arrayPtr = NewArray(5); + *arrayPtrPtr = ExtendArray(*arrayPtrPtr, &newEl); + arrayPtrPtr = &((*arrayPtrPtr)->nextToUse[-1].child.arrayPtr); + break; + } + if ((elPtr->nameUid == newEl.nameUid) + && (elPtr->flags == newEl.flags)) { + arrayPtrPtr = &(elPtr->child.arrayPtr); + break; + } + } + if (*p == '.') { + p++; + } + } else { + + /* + * New element is a leaf. Add it to the parent, if it isn't + * already there. If it exists already, keep whichever value + * has highest priority. + */ + + newEl.child.valueUid = Tk_GetUid(value); + for (elPtr = (*arrayPtrPtr)->els, count = (*arrayPtrPtr)->numUsed; + ; elPtr++, count--) { + if (count == 0) { + *arrayPtrPtr = ExtendArray(*arrayPtrPtr, &newEl); + return; + } + if ((elPtr->nameUid == newEl.nameUid) + && (elPtr->flags == newEl.flags)) { + if (elPtr->priority < newEl.priority) { + elPtr->priority = newEl.priority; + elPtr->child.valueUid = newEl.child.valueUid; + } + return; + } + } + } + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_GetOption -- + * + * Retrieve an option from the option database. + * + * Results: + * The return value is the value specified in the option + * database for the given name and class on the given + * window. If there is nothing specified in the database + * for that option, then NULL is returned. + * + * Side effects: + * The internal caches used to speed up option mapping + * may be modified, if this tkwin is different from the + * last tkwin used for option retrieval. + * + *-------------------------------------------------------------- + */ + +Tk_Uid +Tk_GetOption(tkwin, name, className) + Tk_Window tkwin; /* Token for window that option is + * associated with. */ + char *name; /* Name of option. */ + char *className; /* Class of option. NULL means there + * is no class for this option: just + * check for name. */ +{ + Tk_Uid nameId, classId; + register Element *elPtr, *bestPtr; + register int count; + + /* + * Note: no need to call OptionInit here: it will be done by + * the SetupStacks call below (squeeze out those nanoseconds). + */ + + if (tkwin != (Tk_Window) cachedWindow) { + SetupStacks((TkWindow *) tkwin, 1); + } + + nameId = Tk_GetUid(name); + bestPtr = &defaultMatch; + for (elPtr = stacks[EXACT_LEAF_NAME]->els, + count = stacks[EXACT_LEAF_NAME]->numUsed; count > 0; + elPtr++, count--) { + if ((elPtr->nameUid == nameId) + && (elPtr->priority > bestPtr->priority)) { + bestPtr = elPtr; + } + } + for (elPtr = stacks[WILDCARD_LEAF_NAME]->els, + count = stacks[WILDCARD_LEAF_NAME]->numUsed; count > 0; + elPtr++, count--) { + if ((elPtr->nameUid == nameId) + && (elPtr->priority > bestPtr->priority)) { + bestPtr = elPtr; + } + } + if (className != NULL) { + classId = Tk_GetUid(className); + for (elPtr = stacks[EXACT_LEAF_CLASS]->els, + count = stacks[EXACT_LEAF_CLASS]->numUsed; count > 0; + elPtr++, count--) { + if ((elPtr->nameUid == classId) + && (elPtr->priority > bestPtr->priority)) { + bestPtr = elPtr; + } + } + for (elPtr = stacks[WILDCARD_LEAF_CLASS]->els, + count = stacks[WILDCARD_LEAF_CLASS]->numUsed; count > 0; + elPtr++, count--) { + if ((elPtr->nameUid == classId) + && (elPtr->priority > bestPtr->priority)) { + bestPtr = elPtr; + } + } + } + return bestPtr->child.valueUid; +} + +/* + *-------------------------------------------------------------- + * + * Tk_OptionCmd -- + * + * This procedure is invoked to process the "option" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_OptionCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + size_t length; + char c; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " cmd arg ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'a') && (strncmp(argv[1], "add", length) == 0)) { + int priority; + + if ((argc != 4) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " add pattern value ?priority?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 4) { + priority = TK_INTERACTIVE_PRIO; + } else { + priority = ParsePriority(interp, argv[4]); + if (priority < 0) { + return TCL_ERROR; + } + } + Tk_AddOption(tkwin, argv[2], argv[3], priority); + return TCL_OK; + } else if ((c == 'c') && (strncmp(argv[1], "clear", length) == 0)) { + TkMainInfo *mainPtr; + + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " clear\"", (char *) NULL); + return TCL_ERROR; + } + mainPtr = ((TkWindow *) tkwin)->mainPtr; + if (mainPtr->optionRootPtr != NULL) { + ClearOptionTree(mainPtr->optionRootPtr); + mainPtr->optionRootPtr = NULL; + } + cachedWindow = NULL; + return TCL_OK; + } else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) { + Tk_Window window; + Tk_Uid value; + + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " get window name class\"", (char *) NULL); + return TCL_ERROR; + } + window = Tk_NameToWindow(interp, argv[2], tkwin); + if (window == NULL) { + return TCL_ERROR; + } + value = Tk_GetOption(window, argv[3], argv[4]); + if (value != NULL) { + interp->result = value; + } + return TCL_OK; + } else if ((c == 'r') && (strncmp(argv[1], "readfile", length) == 0)) { + int priority; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " readfile fileName ?priority?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 4) { + priority = ParsePriority(interp, argv[3]); + if (priority < 0) { + return TCL_ERROR; + } + } else { + priority = TK_INTERACTIVE_PRIO; + } + return ReadOptionFile(interp, tkwin, argv[2], priority); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be add, clear, get, or readfile", (char *) NULL); + return TCL_ERROR; + } +} + +/* + *-------------------------------------------------------------- + * + * TkOptionDeadWindow -- + * + * This procedure is called whenever a window is deleted. + * It cleans up any option-related stuff associated with + * the window. + * + * Results: + * None. + * + * Side effects: + * Option-related resources are freed. See code below + * for details. + * + *-------------------------------------------------------------- + */ + +void +TkOptionDeadWindow(winPtr) + register TkWindow *winPtr; /* Window to be cleaned up. */ +{ + /* + * If this window is in the option stacks, then clear the stacks. + */ + + if (winPtr->optionLevel != -1) { + int i; + + for (i = 1; i <= curLevel; i++) { + levels[i].winPtr->optionLevel = -1; + } + curLevel = -1; + cachedWindow = NULL; + } + + /* + * If this window was a main window, then delete its option + * database. + */ + + if ((winPtr->mainPtr->winPtr == winPtr) + && (winPtr->mainPtr->optionRootPtr != NULL)) { + ClearOptionTree(winPtr->mainPtr->optionRootPtr); + winPtr->mainPtr->optionRootPtr = NULL; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkOptionClassChanged -- + * + * This procedure is invoked when a window's class changes. If + * the window is on the option cache, this procedure flushes + * any information for the window, since the new class could change + * what is relevant. + * + * Results: + * None. + * + * Side effects: + * The option cache may be flushed in part or in whole. + * + *---------------------------------------------------------------------- + */ + +void +TkOptionClassChanged(winPtr) + TkWindow *winPtr; /* Window whose class changed. */ +{ + int i, j, *basePtr; + ElArray *arrayPtr; + + if (winPtr->optionLevel == -1) { + return; + } + + /* + * Find the lowest stack level that refers to this window, then + * flush all of the levels above the matching one. + */ + + for (i = 1; i <= curLevel; i++) { + if (levels[i].winPtr == winPtr) { + for (j = i; j <= curLevel; j++) { + levels[j].winPtr->optionLevel = -1; + } + curLevel = i-1; + basePtr = levels[i].bases; + for (j = 0; j < NUM_STACKS; j++) { + arrayPtr = stacks[j]; + arrayPtr->numUsed = basePtr[j]; + arrayPtr->nextToUse = &arrayPtr->els[arrayPtr->numUsed]; + } + if (curLevel <= 0) { + cachedWindow = NULL; + } else { + cachedWindow = levels[curLevel].winPtr; + } + break; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * ParsePriority -- + * + * Parse a string priority value. + * + * Results: + * The return value is the integer priority level corresponding + * to string, or -1 if string doesn't point to a valid priority level. + * In this case, an error message is left in interp->result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +ParsePriority(interp, string) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + char *string; /* Describes a priority level, either + * symbolically or numerically. */ +{ + int priority, c; + size_t length; + + c = string[0]; + length = strlen(string); + if ((c == 'w') + && (strncmp(string, "widgetDefault", length) == 0)) { + return TK_WIDGET_DEFAULT_PRIO; + } else if ((c == 's') + && (strncmp(string, "startupFile", length) == 0)) { + return TK_STARTUP_FILE_PRIO; + } else if ((c == 'u') + && (strncmp(string, "userDefault", length) == 0)) { + return TK_USER_DEFAULT_PRIO; + } else if ((c == 'i') + && (strncmp(string, "interactive", length) == 0)) { + return TK_INTERACTIVE_PRIO; + } else { + char *end; + + priority = strtoul(string, &end, 0); + if ((end == string) || (*end != 0) || (priority < 0) + || (priority > 100)) { + Tcl_AppendResult(interp, "bad priority level \"", string, + "\": must be widgetDefault, startupFile, userDefault, ", + "interactive, or a number between 0 and 100", + (char *) NULL); + return -1; + } + } + return priority; +} + +/* + *---------------------------------------------------------------------- + * + * AddFromString -- + * + * Given a string containing lines in the standard format for + * X resources (see other documentation for details on what this + * is), parse the resource specifications and enter them as options + * for tkwin's main window. + * + * Results: + * The return value is a standard Tcl return code. In the case of + * an error in parsing string, TCL_ERROR will be returned and an + * error message will be left in interp->result. The memory at + * string is totally trashed by this procedure. If you care about + * its contents, make a copy before calling here. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +AddFromString(interp, tkwin, string, priority) + Tcl_Interp *interp; /* Interpreter to use for reporting results. */ + Tk_Window tkwin; /* Token for window: options are entered + * for this window's main window. */ + char *string; /* String containing option specifiers. */ + int priority; /* Priority level to use for options in + * this string, such as TK_USER_DEFAULT_PRIO + * or TK_INTERACTIVE_PRIO. Must be between + * 0 and TK_MAX_PRIO. */ +{ + register char *src, *dst; + char *name, *value; + int lineNum; + + src = string; + lineNum = 1; + while (1) { + + /* + * Skip leading white space and empty lines and comment lines, and + * check for the end of the spec. + */ + + while ((*src == ' ') || (*src == '\t')) { + src++; + } + if ((*src == '#') || (*src == '!')) { + do { + src++; + if ((src[0] == '\\') && (src[1] == '\n')) { + src += 2; + lineNum++; + } + } while ((*src != '\n') && (*src != 0)); + } + if (*src == '\n') { + src++; + lineNum++; + continue; + } + if (*src == '\0') { + break; + } + + /* + * Parse off the option name, collapsing out backslash-newline + * sequences of course. + */ + + dst = name = src; + while (*src != ':') { + if ((*src == '\0') || (*src == '\n')) { + sprintf(interp->result, "missing colon on line %d", + lineNum); + return TCL_ERROR; + } + if ((src[0] == '\\') && (src[1] == '\n')) { + src += 2; + lineNum++; + } else { + *dst = *src; + dst++; + src++; + } + } + + /* + * Eliminate trailing white space on the name, and null-terminate + * it. + */ + + while ((dst != name) && ((dst[-1] == ' ') || (dst[-1] == '\t'))) { + dst--; + } + *dst = '\0'; + + /* + * Skip white space between the name and the value. + */ + + src++; + while ((*src == ' ') || (*src == '\t')) { + src++; + } + if (*src == '\0') { + sprintf(interp->result, "missing value on line %d", lineNum); + return TCL_ERROR; + } + + /* + * Parse off the value, squeezing out backslash-newline sequences + * along the way. + */ + + dst = value = src; + while (*src != '\n') { + if (*src == '\0') { + sprintf(interp->result, "missing newline on line %d", + lineNum); + return TCL_ERROR; + } + if ((src[0] == '\\') && (src[1] == '\n')) { + src += 2; + lineNum++; + } else { + *dst = *src; + dst++; + src++; + } + } + *dst = 0; + + /* + * Enter the option into the database. + */ + + Tk_AddOption(tkwin, name, value, priority); + src++; + lineNum++; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ReadOptionFile -- + * + * Read a file of options ("resources" in the old X terminology) + * and load them into the option database. + * + * Results: + * The return value is a standard Tcl return code. In the case of + * an error in parsing string, TCL_ERROR will be returned and an + * error message will be left in interp->result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +ReadOptionFile(interp, tkwin, fileName, priority) + Tcl_Interp *interp; /* Interpreter to use for reporting results. */ + Tk_Window tkwin; /* Token for window: options are entered + * for this window's main window. */ + char *fileName; /* Name of file containing options. */ + int priority; /* Priority level to use for options in + * this file, such as TK_USER_DEFAULT_PRIO + * or TK_INTERACTIVE_PRIO. Must be between + * 0 and TK_MAX_PRIO. */ +{ + char *realName, *buffer; + int result, bufferSize; + Tcl_Channel chan; + Tcl_DString newName; + + /* + * Prevent file system access in a safe interpreter. + */ + + if (Tcl_IsSafe(interp)) { + Tcl_AppendResult(interp, "can't read options from a file in a", + " safe interpreter", (char *) NULL); + return TCL_ERROR; + } + + realName = Tcl_TranslateFileName(interp, fileName, &newName); + if (realName == NULL) { + return TCL_ERROR; + } + chan = Tcl_OpenFileChannel(interp, realName, "r", 0); + Tcl_DStringFree(&newName); + if (chan == NULL) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "couldn't open \"", fileName, + "\": ", Tcl_PosixError(interp), (char *) NULL); + return TCL_ERROR; + } + + /* + * Compute size of file by seeking to the end of the file. This will + * overallocate if we are performing CRLF translation. + */ + + bufferSize = Tcl_Seek(chan, 0L, SEEK_END); + (void) Tcl_Seek(chan, 0L, SEEK_SET); + + if (bufferSize < 0) { + Tcl_AppendResult(interp, "error seeking to end of file \"", + fileName, "\":", Tcl_PosixError(interp), (char *) NULL); + Tcl_Close(NULL, chan); + return TCL_ERROR; + + } + buffer = (char *) ckalloc((unsigned) bufferSize+1); + bufferSize = Tcl_Read(chan, buffer, bufferSize); + if (bufferSize < 0) { + Tcl_AppendResult(interp, "error reading file \"", fileName, "\":", + Tcl_PosixError(interp), (char *) NULL); + Tcl_Close(NULL, chan); + return TCL_ERROR; + } + Tcl_Close(NULL, chan); + buffer[bufferSize] = 0; + result = AddFromString(interp, tkwin, buffer, priority); + ckfree(buffer); + return result; +} + +/* + *-------------------------------------------------------------- + * + * NewArray -- + * + * Create a new ElArray structure of a given size. + * + * Results: + * The return value is a pointer to a properly initialized + * element array with "numEls" space. The array is marked + * as having no active elements. + * + * Side effects: + * Memory is allocated. + * + *-------------------------------------------------------------- + */ + +static ElArray * +NewArray(numEls) + int numEls; /* How many elements of space to allocate. */ +{ + register ElArray *arrayPtr; + + arrayPtr = (ElArray *) ckalloc(EL_ARRAY_SIZE(numEls)); + arrayPtr->arraySize = numEls; + arrayPtr->numUsed = 0; + arrayPtr->nextToUse = arrayPtr->els; + return arrayPtr; +} + +/* + *-------------------------------------------------------------- + * + * ExtendArray -- + * + * Add a new element to an array, extending the array if + * necessary. + * + * Results: + * The return value is a pointer to the new array, which + * will be different from arrayPtr if the array got expanded. + * + * Side effects: + * Memory may be allocated or freed. + * + *-------------------------------------------------------------- + */ + +static ElArray * +ExtendArray(arrayPtr, elPtr) + register ElArray *arrayPtr; /* Array to be extended. */ + register Element *elPtr; /* Element to be copied into array. */ +{ + /* + * If the current array has filled up, make it bigger. + */ + + if (arrayPtr->numUsed >= arrayPtr->arraySize) { + register ElArray *newPtr; + + newPtr = (ElArray *) ckalloc(EL_ARRAY_SIZE(2*arrayPtr->arraySize)); + newPtr->arraySize = 2*arrayPtr->arraySize; + newPtr->numUsed = arrayPtr->numUsed; + newPtr->nextToUse = &newPtr->els[newPtr->numUsed]; + memcpy((VOID *) newPtr->els, (VOID *) arrayPtr->els, + (arrayPtr->arraySize*sizeof(Element))); + ckfree((char *) arrayPtr); + arrayPtr = newPtr; + } + + *arrayPtr->nextToUse = *elPtr; + arrayPtr->nextToUse++; + arrayPtr->numUsed++; + return arrayPtr; +} + +/* + *-------------------------------------------------------------- + * + * SetupStacks -- + * + * Arrange the stacks so that they cache all the option + * information for a particular window. + * + * Results: + * None. + * + * Side effects: + * The stacks are modified to hold information for tkwin + * and all its ancestors in the window hierarchy. + * + *-------------------------------------------------------------- + */ + +static void +SetupStacks(winPtr, leaf) + TkWindow *winPtr; /* Window for which information is to + * be cached. */ + int leaf; /* Non-zero means this is the leaf + * window being probed. Zero means this + * is an ancestor of the desired leaf. */ +{ + int level, i, *iPtr; + register StackLevel *levelPtr; + register ElArray *arrayPtr; + + /* + * The following array defines the order in which the current + * stacks are searched to find matching entries to add to the + * stacks. Given the current priority-based scheme, the order + * below is no longer relevant; all that matters is that an + * element is on the list *somewhere*. The ordering is a relic + * of the old days when priorities were determined differently. + */ + + static int searchOrder[] = {WILDCARD_NODE_CLASS, WILDCARD_NODE_NAME, + EXACT_NODE_CLASS, EXACT_NODE_NAME, -1}; + + if (winPtr->mainPtr->optionRootPtr == NULL) { + OptionInit(winPtr->mainPtr); + } + + /* + * Step 1: make sure that options are cached for this window's + * parent. + */ + + if (winPtr->parentPtr != NULL) { + level = winPtr->parentPtr->optionLevel; + if ((level == -1) || (cachedWindow == NULL)) { + SetupStacks(winPtr->parentPtr, 0); + level = winPtr->parentPtr->optionLevel; + } + level++; + } else { + level = 1; + } + + /* + * Step 2: pop extra unneeded information off the stacks and + * mark those windows as no longer having cached information. + */ + + if (curLevel >= level) { + while (curLevel >= level) { + levels[curLevel].winPtr->optionLevel = -1; + curLevel--; + } + levelPtr = &levels[level]; + for (i = 0; i < NUM_STACKS; i++) { + arrayPtr = stacks[i]; + arrayPtr->numUsed = levelPtr->bases[i]; + arrayPtr->nextToUse = &arrayPtr->els[arrayPtr->numUsed]; + } + } + curLevel = winPtr->optionLevel = level; + + /* + * Step 3: if the root database information isn't loaded or + * isn't valid, initialize level 0 of the stack from the + * database root (this only happens if winPtr is a main window). + */ + + if ((curLevel == 1) + && ((cachedWindow == NULL) + || (cachedWindow->mainPtr != winPtr->mainPtr))) { + for (i = 0; i < NUM_STACKS; i++) { + arrayPtr = stacks[i]; + arrayPtr->numUsed = 0; + arrayPtr->nextToUse = arrayPtr->els; + } + ExtendStacks(winPtr->mainPtr->optionRootPtr, 0); + } + + /* + * Step 4: create a new stack level; grow the level array if + * we've run out of levels. Clear the stacks for EXACT_LEAF_NAME + * and EXACT_LEAF_CLASS (anything that was there is of no use + * any more). + */ + + if (curLevel >= numLevels) { + StackLevel *newLevels; + + newLevels = (StackLevel *) ckalloc((unsigned) + (numLevels*2*sizeof(StackLevel))); + memcpy((VOID *) newLevels, (VOID *) levels, + (numLevels*sizeof(StackLevel))); + ckfree((char *) levels); + numLevels *= 2; + levels = newLevels; + } + levelPtr = &levels[curLevel]; + levelPtr->winPtr = winPtr; + arrayPtr = stacks[EXACT_LEAF_NAME]; + arrayPtr->numUsed = 0; + arrayPtr->nextToUse = arrayPtr->els; + arrayPtr = stacks[EXACT_LEAF_CLASS]; + arrayPtr->numUsed = 0; + arrayPtr->nextToUse = arrayPtr->els; + levelPtr->bases[EXACT_LEAF_NAME] = stacks[EXACT_LEAF_NAME]->numUsed; + levelPtr->bases[EXACT_LEAF_CLASS] = stacks[EXACT_LEAF_CLASS]->numUsed; + levelPtr->bases[EXACT_NODE_NAME] = stacks[EXACT_NODE_NAME]->numUsed; + levelPtr->bases[EXACT_NODE_CLASS] = stacks[EXACT_NODE_CLASS]->numUsed; + levelPtr->bases[WILDCARD_LEAF_NAME] = stacks[WILDCARD_LEAF_NAME]->numUsed; + levelPtr->bases[WILDCARD_LEAF_CLASS] = stacks[WILDCARD_LEAF_CLASS]->numUsed; + levelPtr->bases[WILDCARD_NODE_NAME] = stacks[WILDCARD_NODE_NAME]->numUsed; + levelPtr->bases[WILDCARD_NODE_CLASS] = stacks[WILDCARD_NODE_CLASS]->numUsed; + + + /* + * Step 5: scan the current stack level looking for matches to this + * window's name or class; where found, add new information to the + * stacks. + */ + + for (iPtr = searchOrder; *iPtr != -1; iPtr++) { + register Element *elPtr; + int count; + Tk_Uid id; + + i = *iPtr; + if (i & CLASS) { + id = winPtr->classUid; + } else { + id = winPtr->nameUid; + } + elPtr = stacks[i]->els; + count = levelPtr->bases[i]; + + /* + * For wildcard stacks, check all entries; for non-wildcard + * stacks, only check things that matched in the parent. + */ + + if (!(i & WILDCARD)) { + elPtr += levelPtr[-1].bases[i]; + count -= levelPtr[-1].bases[i]; + } + for ( ; count > 0; elPtr++, count--) { + if (elPtr->nameUid != id) { + continue; + } + ExtendStacks(elPtr->child.arrayPtr, leaf); + } + } + cachedWindow = winPtr; +} + +/* + *-------------------------------------------------------------- + * + * ExtendStacks -- + * + * Given an element array, copy all the elements from the + * array onto the system stacks (except for irrelevant leaf + * elements). + * + * Results: + * None. + * + * Side effects: + * The option stacks are extended. + * + *-------------------------------------------------------------- + */ + +static void +ExtendStacks(arrayPtr, leaf) + ElArray *arrayPtr; /* Array of elements to copy onto stacks. */ + int leaf; /* If zero, then don't copy exact leaf + * elements. */ +{ + register int count; + register Element *elPtr; + + for (elPtr = arrayPtr->els, count = arrayPtr->numUsed; + count > 0; elPtr++, count--) { + if (!(elPtr->flags & (NODE|WILDCARD)) && !leaf) { + continue; + } + stacks[elPtr->flags] = ExtendArray(stacks[elPtr->flags], elPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * OptionInit -- + * + * Initialize data structures for option handling. + * + * Results: + * None. + * + * Side effects: + * Option-related data structures get initialized. + * + *-------------------------------------------------------------- + */ + +static void +OptionInit(mainPtr) + register TkMainInfo *mainPtr; /* Top-level information about + * window that isn't initialized + * yet. */ +{ + int i; + Tcl_Interp *interp; + + /* + * First, once-only initialization. + */ + + if (numLevels == 0) { + + numLevels = 5; + levels = (StackLevel *) ckalloc((unsigned) (5*sizeof(StackLevel))); + for (i = 0; i < NUM_STACKS; i++) { + stacks[i] = NewArray(10); + levels[0].bases[i] = 0; + } + + defaultMatch.nameUid = NULL; + defaultMatch.child.valueUid = NULL; + defaultMatch.priority = -1; + defaultMatch.flags = 0; + } + + /* + * Then, per-main-window initialization. Create and delete dummy + * interpreter for message logging. + */ + + mainPtr->optionRootPtr = NewArray(20); + interp = Tcl_CreateInterp(); + (void) GetDefaultOptions(interp, mainPtr->winPtr); + Tcl_DeleteInterp(interp); +} + +/* + *-------------------------------------------------------------- + * + * ClearOptionTree -- + * + * This procedure is called to erase everything in a + * hierarchical option database. + * + * Results: + * None. + * + * Side effects: + * All the options associated with arrayPtr are deleted, + * along with all option subtrees. The space pointed to + * by arrayPtr is freed. + * + *-------------------------------------------------------------- + */ + +static void +ClearOptionTree(arrayPtr) + ElArray *arrayPtr; /* Array of options; delete everything + * referred to recursively by this. */ +{ + register Element *elPtr; + int count; + + for (count = arrayPtr->numUsed, elPtr = arrayPtr->els; count > 0; + count--, elPtr++) { + if (elPtr->flags & NODE) { + ClearOptionTree(elPtr->child.arrayPtr); + } + } + ckfree((char *) arrayPtr); +} + +/* + *-------------------------------------------------------------- + * + * GetDefaultOptions -- + * + * This procedure is invoked to load the default set of options + * for a window. + * + * Results: + * None. + * + * Side effects: + * Options are added to those for winPtr's main window. If + * there exists a RESOURCE_MANAGER proprety for winPtr's + * display, that is used. Otherwise, the .Xdefaults file in + * the user's home directory is used. + * + *-------------------------------------------------------------- + */ + +static int +GetDefaultOptions(interp, winPtr) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + TkWindow *winPtr; /* Fetch option defaults for main window + * associated with this. */ +{ + char *regProp; + int result, actualFormat; + unsigned long numItems, bytesAfter; + Atom actualType; + + /* + * Try the RESOURCE_MANAGER property on the root window first. + */ + + regProp = NULL; + result = XGetWindowProperty(winPtr->display, + RootWindow(winPtr->display, 0), + XA_RESOURCE_MANAGER, 0, 100000, + False, XA_STRING, &actualType, &actualFormat, + &numItems, &bytesAfter, (unsigned char **) ®Prop); + + if ((result == Success) && (actualType == XA_STRING) + && (actualFormat == 8)) { + result = AddFromString(interp, (Tk_Window) winPtr, regProp, + TK_USER_DEFAULT_PRIO); + XFree(regProp); + return result; + } + + /* + * No luck there. Try a .Xdefaults file in the user's home + * directory. + */ + + if (regProp != NULL) { + XFree(regProp); + } + result = ReadOptionFile(interp, (Tk_Window) winPtr, "~/.Xdefaults", + TK_USER_DEFAULT_PRIO); + return result; +} diff --git a/generic/tkPack.c b/generic/tkPack.c new file mode 100644 index 0000000..4ff1049 --- /dev/null +++ b/generic/tkPack.c @@ -0,0 +1,1727 @@ +/* + * tkPack.c -- + * + * This file contains code to implement the "packer" + * geometry manager for Tk. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkPack.c 1.64 96/05/03 10:51:52 + */ + +#include "tkPort.h" +#include "tkInt.h" + +typedef enum {TOP, BOTTOM, LEFT, RIGHT} Side; + +/* For each window that the packer cares about (either because + * the window is managed by the packer or because the window + * has slaves that are managed by the packer), there is a + * structure of the following type: + */ + +typedef struct Packer { + Tk_Window tkwin; /* Tk token for window. NULL means that + * the window has been deleted, but the + * packet hasn't had a chance to clean up + * yet because the structure is still in + * use. */ + struct Packer *masterPtr; /* Master window within which this window + * is packed (NULL means this window + * isn't managed by the packer). */ + struct Packer *nextPtr; /* Next window packed within same + * parent. List is priority-ordered: + * first on list gets packed first. */ + struct Packer *slavePtr; /* First in list of slaves packed + * inside this window (NULL means + * no packed slaves). */ + Side side; /* Side of parent against which + * this window is packed. */ + Tk_Anchor anchor; /* If frame allocated for window is larger + * than window needs, this indicates how + * where to position window in frame. */ + int padX, padY; /* Total additional pixels to leave around the + * window (half of this space is left on each + * side). This is space *outside* the window: + * we'll allocate extra space in frame but + * won't enlarge window). */ + int iPadX, iPadY; /* Total extra pixels to allocate inside the + * window (half this amount will appear on + * each side). */ + int doubleBw; /* Twice the window's last known border + * width. If this changes, the window + * must be repacked within its parent. */ + int *abortPtr; /* If non-NULL, it means that there is a nested + * call to ArrangePacking already working on + * this window. *abortPtr may be set to 1 to + * abort that nested call. This happens, for + * example, if tkwin or any of its slaves + * is deleted. */ + int flags; /* Miscellaneous flags; see below + * for definitions. */ +} Packer; + +/* + * Flag values for Packer structures: + * + * REQUESTED_REPACK: 1 means a Tcl_DoWhenIdle request + * has already been made to repack + * all the slaves of this window. + * FILLX: 1 means if frame allocated for window + * is wider than window needs, expand window + * to fill frame. 0 means don't make window + * any larger than needed. + * FILLY: Same as FILLX, except for height. + * EXPAND: 1 means this window's frame will absorb any + * extra space in the parent window. + * OLD_STYLE: 1 means this window is being managed with + * the old-style packer algorithms (before + * Tk version 3.3). The main difference is + * that padding and filling are done differently. + * DONT_PROPAGATE: 1 means don't set this window's requested + * size. 0 means if this window is a master + * then Tk will set its requested size to fit + * the needs of its slaves. + */ + +#define REQUESTED_REPACK 1 +#define FILLX 2 +#define FILLY 4 +#define EXPAND 8 +#define OLD_STYLE 16 +#define DONT_PROPAGATE 32 + +/* + * Hash table used to map from Tk_Window tokens to corresponding + * Packer structures: + */ + +static Tcl_HashTable packerHashTable; + +/* + * Have statics in this module been initialized? + */ + +static int initialized = 0; + +/* + * The following structure is the official type record for the + * packer: + */ + +static void PackReqProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); +static void PackLostSlaveProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); + +static Tk_GeomMgr packerType = { + "pack", /* name */ + PackReqProc, /* requestProc */ + PackLostSlaveProc, /* lostSlaveProc */ +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void ArrangePacking _ANSI_ARGS_((ClientData clientData)); +static int ConfigureSlaves _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, int argc, char *argv[])); +static void DestroyPacker _ANSI_ARGS_((char *memPtr)); +static Packer * GetPacker _ANSI_ARGS_((Tk_Window tkwin)); +static int PackAfter _ANSI_ARGS_((Tcl_Interp *interp, + Packer *prevPtr, Packer *masterPtr, int argc, + char **argv)); +static void PackReqProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); +static void PackStructureProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void Unlink _ANSI_ARGS_((Packer *packPtr)); +static int XExpansion _ANSI_ARGS_((Packer *slavePtr, + int cavityWidth)); +static int YExpansion _ANSI_ARGS_((Packer *slavePtr, + int cavityHeight)); + +/* + *-------------------------------------------------------------- + * + * Tk_PackCmd -- + * + * This procedure is invoked to process the "pack" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_PackCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + size_t length; + int c; + + if ((argc >= 2) && (argv[1][0] == '.')) { + return ConfigureSlaves(interp, tkwin, argc-1, argv+1); + } + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option arg ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'a') && (length >= 2) + && (strncmp(argv[1], "after", length) == 0)) { + Packer *prevPtr; + Tk_Window tkwin2; + + tkwin2 = Tk_NameToWindow(interp, argv[2], tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + prevPtr = GetPacker(tkwin2); + if (prevPtr->masterPtr == NULL) { + Tcl_AppendResult(interp, "window \"", argv[2], + "\" isn't packed", (char *) NULL); + return TCL_ERROR; + } + return PackAfter(interp, prevPtr, prevPtr->masterPtr, argc-3, argv+3); + } else if ((c == 'a') && (length >= 2) + && (strncmp(argv[1], "append", length) == 0)) { + Packer *masterPtr; + register Packer *prevPtr; + Tk_Window tkwin2; + + tkwin2 = Tk_NameToWindow(interp, argv[2], tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + masterPtr = GetPacker(tkwin2); + prevPtr = masterPtr->slavePtr; + if (prevPtr != NULL) { + while (prevPtr->nextPtr != NULL) { + prevPtr = prevPtr->nextPtr; + } + } + return PackAfter(interp, prevPtr, masterPtr, argc-3, argv+3); + } else if ((c == 'b') && (strncmp(argv[1], "before", length) == 0)) { + Packer *packPtr, *masterPtr; + register Packer *prevPtr; + Tk_Window tkwin2; + + tkwin2 = Tk_NameToWindow(interp, argv[2], tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + packPtr = GetPacker(tkwin2); + if (packPtr->masterPtr == NULL) { + Tcl_AppendResult(interp, "window \"", argv[2], + "\" isn't packed", (char *) NULL); + return TCL_ERROR; + } + masterPtr = packPtr->masterPtr; + prevPtr = masterPtr->slavePtr; + if (prevPtr == packPtr) { + prevPtr = NULL; + } else { + for ( ; ; prevPtr = prevPtr->nextPtr) { + if (prevPtr == NULL) { + panic("\"pack before\" couldn't find predecessor"); + } + if (prevPtr->nextPtr == packPtr) { + break; + } + } + } + return PackAfter(interp, prevPtr, masterPtr, argc-3, argv+3); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0)) { + if (argv[2][0] != '.') { + Tcl_AppendResult(interp, "bad argument \"", argv[2], + "\": must be name of window", (char *) NULL); + return TCL_ERROR; + } + return ConfigureSlaves(interp, tkwin, argc-2, argv+2); + } else if ((c == 'f') && (strncmp(argv[1], "forget", length) == 0)) { + Tk_Window slave; + Packer *slavePtr; + int i; + + for (i = 2; i < argc; i++) { + slave = Tk_NameToWindow(interp, argv[i], tkwin); + if (slave == NULL) { + continue; + } + slavePtr = GetPacker(slave); + if ((slavePtr != NULL) && (slavePtr->masterPtr != NULL)) { + Tk_ManageGeometry(slave, (Tk_GeomMgr *) NULL, + (ClientData) NULL); + if (slavePtr->masterPtr->tkwin != Tk_Parent(slavePtr->tkwin)) { + Tk_UnmaintainGeometry(slavePtr->tkwin, + slavePtr->masterPtr->tkwin); + } + Unlink(slavePtr); + Tk_UnmapWindow(slavePtr->tkwin); + } + } + } else if ((c == 'i') && (strncmp(argv[1], "info", length) == 0)) { + register Packer *slavePtr; + Tk_Window slave; + char buffer[300]; + static char *sideNames[] = {"top", "bottom", "left", "right"}; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " info window\"", (char *) NULL); + return TCL_ERROR; + } + slave = Tk_NameToWindow(interp, argv[2], tkwin); + if (slave == NULL) { + return TCL_ERROR; + } + slavePtr = GetPacker(slave); + if (slavePtr->masterPtr == NULL) { + Tcl_AppendResult(interp, "window \"", argv[2], + "\" isn't packed", (char *) NULL); + return TCL_ERROR; + } + Tcl_AppendElement(interp, "-in"); + Tcl_AppendElement(interp, Tk_PathName(slavePtr->masterPtr->tkwin)); + Tcl_AppendElement(interp, "-anchor"); + Tcl_AppendElement(interp, Tk_NameOfAnchor(slavePtr->anchor)); + Tcl_AppendResult(interp, " -expand ", + (slavePtr->flags & EXPAND) ? "1" : "0", " -fill ", + (char *) NULL); + switch (slavePtr->flags & (FILLX|FILLY)) { + case 0: + Tcl_AppendResult(interp, "none", (char *) NULL); + break; + case FILLX: + Tcl_AppendResult(interp, "x", (char *) NULL); + break; + case FILLY: + Tcl_AppendResult(interp, "y", (char *) NULL); + break; + case FILLX|FILLY: + Tcl_AppendResult(interp, "both", (char *) NULL); + break; + } + sprintf(buffer, " -ipadx %d -ipady %d -padx %d -pady %d", + slavePtr->iPadX/2, slavePtr->iPadY/2, slavePtr->padX/2, + slavePtr->padY/2); + Tcl_AppendResult(interp, buffer, " -side ", sideNames[slavePtr->side], + (char *) NULL); + } else if ((c == 'p') && (strncmp(argv[1], "propagate", length) == 0)) { + Tk_Window master; + Packer *masterPtr; + int propagate; + + if (argc > 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " propagate window ?boolean?\"", (char *) NULL); + return TCL_ERROR; + } + master = Tk_NameToWindow(interp, argv[2], tkwin); + if (master == NULL) { + return TCL_ERROR; + } + masterPtr = GetPacker(master); + if (argc == 3) { + if (masterPtr->flags & DONT_PROPAGATE) { + interp->result = "0"; + } else { + interp->result = "1"; + } + return TCL_OK; + } + if (Tcl_GetBoolean(interp, argv[3], &propagate) != TCL_OK) { + return TCL_ERROR; + } + if (propagate) { + masterPtr->flags &= ~DONT_PROPAGATE; + + /* + * Repack the master to allow new geometry information to + * propagate upwards to the master's master. + */ + + if (masterPtr->abortPtr != NULL) { + *masterPtr->abortPtr = 1; + } + if (!(masterPtr->flags & REQUESTED_REPACK)) { + masterPtr->flags |= REQUESTED_REPACK; + Tcl_DoWhenIdle(ArrangePacking, (ClientData) masterPtr); + } + } else { + masterPtr->flags |= DONT_PROPAGATE; + } + } else if ((c == 's') && (strncmp(argv[1], "slaves", length) == 0)) { + Tk_Window master; + Packer *masterPtr, *slavePtr; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " slaves window\"", (char *) NULL); + return TCL_ERROR; + } + master = Tk_NameToWindow(interp, argv[2], tkwin); + if (master == NULL) { + return TCL_ERROR; + } + masterPtr = GetPacker(master); + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + Tcl_AppendElement(interp, Tk_PathName(slavePtr->tkwin)); + } + } else if ((c == 'u') && (strncmp(argv[1], "unpack", length) == 0)) { + Tk_Window tkwin2; + Packer *packPtr; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " unpack window\"", (char *) NULL); + return TCL_ERROR; + } + tkwin2 = Tk_NameToWindow(interp, argv[2], tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + packPtr = GetPacker(tkwin2); + if ((packPtr != NULL) && (packPtr->masterPtr != NULL)) { + Tk_ManageGeometry(tkwin2, (Tk_GeomMgr *) NULL, + (ClientData) NULL); + if (packPtr->masterPtr->tkwin != Tk_Parent(packPtr->tkwin)) { + Tk_UnmaintainGeometry(packPtr->tkwin, + packPtr->masterPtr->tkwin); + } + Unlink(packPtr); + Tk_UnmapWindow(packPtr->tkwin); + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be configure, forget, info, ", + "propagate, or slaves", (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * PackReqProc -- + * + * This procedure is invoked by Tk_GeometryRequest for + * windows managed by the packer. + * + * Results: + * None. + * + * Side effects: + * Arranges for tkwin, and all its managed siblings, to + * be re-packed at the next idle point. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +PackReqProc(clientData, tkwin) + ClientData clientData; /* Packer's information about + * window that got new preferred + * geometry. */ + Tk_Window tkwin; /* Other Tk-related information + * about the window. */ +{ + register Packer *packPtr = (Packer *) clientData; + + packPtr = packPtr->masterPtr; + if (!(packPtr->flags & REQUESTED_REPACK)) { + packPtr->flags |= REQUESTED_REPACK; + Tcl_DoWhenIdle(ArrangePacking, (ClientData) packPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * PackLostSlaveProc -- + * + * This procedure is invoked by Tk whenever some other geometry + * claims control over a slave that used to be managed by us. + * + * Results: + * None. + * + * Side effects: + * Forgets all packer-related information about the slave. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +PackLostSlaveProc(clientData, tkwin) + ClientData clientData; /* Packer structure for slave window that + * was stolen away. */ + Tk_Window tkwin; /* Tk's handle for the slave window. */ +{ + register Packer *slavePtr = (Packer *) clientData; + + if (slavePtr->masterPtr->tkwin != Tk_Parent(slavePtr->tkwin)) { + Tk_UnmaintainGeometry(slavePtr->tkwin, slavePtr->masterPtr->tkwin); + } + Unlink(slavePtr); + Tk_UnmapWindow(slavePtr->tkwin); +} + +/* + *-------------------------------------------------------------- + * + * ArrangePacking -- + * + * This procedure is invoked (using the Tcl_DoWhenIdle + * mechanism) to re-layout a set of windows managed by + * the packer. It is invoked at idle time so that a + * series of packer requests can be merged into a single + * layout operation. + * + * Results: + * None. + * + * Side effects: + * The packed slaves of masterPtr may get resized or + * moved. + * + *-------------------------------------------------------------- + */ + +static void +ArrangePacking(clientData) + ClientData clientData; /* Structure describing parent whose slaves + * are to be re-layed out. */ +{ + register Packer *masterPtr = (Packer *) clientData; + register Packer *slavePtr; + int cavityX, cavityY, cavityWidth, cavityHeight; + /* These variables keep track of the + * as-yet-unallocated space remaining in + * the middle of the parent window. */ + int frameX, frameY, frameWidth, frameHeight; + /* These variables keep track of the frame + * allocated to the current window. */ + int x, y, width, height; /* These variables are used to hold the + * actual geometry of the current window. */ + int intBWidth; /* Width of internal border in parent window, + * if any. */ + int abort; /* May get set to non-zero to abort this + * repacking operation. */ + int borderX, borderY; + int maxWidth, maxHeight, tmp; + + masterPtr->flags &= ~REQUESTED_REPACK; + + /* + * If the parent has no slaves anymore, then don't do anything + * at all: just leave the parent's size as-is. + */ + + if (masterPtr->slavePtr == NULL) { + return; + } + + /* + * Abort any nested call to ArrangePacking for this window, since + * we'll do everything necessary here, and set up so this call + * can be aborted if necessary. + */ + + if (masterPtr->abortPtr != NULL) { + *masterPtr->abortPtr = 1; + } + masterPtr->abortPtr = &abort; + abort = 0; + Tcl_Preserve((ClientData) masterPtr); + + /* + * Pass #1: scan all the slaves to figure out the total amount + * of space needed. Two separate width and height values are + * computed: + * + * width - Holds the sum of the widths (plus padding) of + * all the slaves seen so far that were packed LEFT + * or RIGHT. + * height - Holds the sum of the heights (plus padding) of + * all the slaves seen so far that were packed TOP + * or BOTTOM. + * + * maxWidth - Gradually builds up the width needed by the master + * to just barely satisfy all the slave's needs. For + * each slave, the code computes the width needed for + * all the slaves so far and updates maxWidth if the + * new value is greater. + * maxHeight - Same as maxWidth, except keeps height info. + */ + + intBWidth = Tk_InternalBorderWidth(masterPtr->tkwin); + width = height = maxWidth = maxHeight = 2*intBWidth; + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + if ((slavePtr->side == TOP) || (slavePtr->side == BOTTOM)) { + tmp = Tk_ReqWidth(slavePtr->tkwin) + slavePtr->doubleBw + + slavePtr->padX + slavePtr->iPadX + width; + if (tmp > maxWidth) { + maxWidth = tmp; + } + height += Tk_ReqHeight(slavePtr->tkwin) + slavePtr->doubleBw + + slavePtr->padY + slavePtr->iPadY; + } else { + tmp = Tk_ReqHeight(slavePtr->tkwin) + slavePtr->doubleBw + + slavePtr->padY + slavePtr->iPadY + height; + if (tmp > maxHeight) { + maxHeight = tmp; + } + width += Tk_ReqWidth(slavePtr->tkwin) + slavePtr->doubleBw + + slavePtr->padX + slavePtr->iPadX; + } + } + if (width > maxWidth) { + maxWidth = width; + } + if (height > maxHeight) { + maxHeight = height; + } + + /* + * If the total amount of space needed in the parent window has + * changed, and if we're propagating geometry information, then + * notify the next geometry manager up and requeue ourselves to + * start again after the parent has had a chance to + * resize us. + */ + + if (((maxWidth != Tk_ReqWidth(masterPtr->tkwin)) + || (maxHeight != Tk_ReqHeight(masterPtr->tkwin))) + && !(masterPtr->flags & DONT_PROPAGATE)) { + Tk_GeometryRequest(masterPtr->tkwin, maxWidth, maxHeight); + masterPtr->flags |= REQUESTED_REPACK; + Tcl_DoWhenIdle(ArrangePacking, (ClientData) masterPtr); + goto done; + } + + /* + * Pass #2: scan the slaves a second time assigning + * new sizes. The "cavity" variables keep track of the + * unclaimed space in the cavity of the window; this + * shrinks inward as we allocate windows around the + * edges. The "frame" variables keep track of the space + * allocated to the current window and its frame. The + * current window is then placed somewhere inside the + * frame, depending on anchor. + */ + + cavityX = cavityY = x = y = intBWidth; + cavityWidth = Tk_Width(masterPtr->tkwin) - 2*intBWidth; + cavityHeight = Tk_Height(masterPtr->tkwin) - 2*intBWidth; + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + if ((slavePtr->side == TOP) || (slavePtr->side == BOTTOM)) { + frameWidth = cavityWidth; + frameHeight = Tk_ReqHeight(slavePtr->tkwin) + slavePtr->doubleBw + + slavePtr->padY + slavePtr->iPadY; + if (slavePtr->flags & EXPAND) { + frameHeight += YExpansion(slavePtr, cavityHeight); + } + cavityHeight -= frameHeight; + if (cavityHeight < 0) { + frameHeight += cavityHeight; + cavityHeight = 0; + } + frameX = cavityX; + if (slavePtr->side == TOP) { + frameY = cavityY; + cavityY += frameHeight; + } else { + frameY = cavityY + cavityHeight; + } + } else { + frameHeight = cavityHeight; + frameWidth = Tk_ReqWidth(slavePtr->tkwin) + slavePtr->doubleBw + + slavePtr->padX + slavePtr->iPadX; + if (slavePtr->flags & EXPAND) { + frameWidth += XExpansion(slavePtr, cavityWidth); + } + cavityWidth -= frameWidth; + if (cavityWidth < 0) { + frameWidth += cavityWidth; + cavityWidth = 0; + } + frameY = cavityY; + if (slavePtr->side == LEFT) { + frameX = cavityX; + cavityX += frameWidth; + } else { + frameX = cavityX + cavityWidth; + } + } + + /* + * Now that we've got the size of the frame for the window, + * compute the window's actual size and location using the + * fill, padding, and frame factors. The variables "borderX" + * and "borderY" are used to handle the differences between + * old-style packing and the new style (in old-style, iPadX + * and iPadY are always zero and padding is completely ignored + * except when computing frame size). + */ + + if (slavePtr->flags & OLD_STYLE) { + borderX = borderY = 0; + } else { + borderX = slavePtr->padX; + borderY = slavePtr->padY; + } + width = Tk_ReqWidth(slavePtr->tkwin) + slavePtr->doubleBw + + slavePtr->iPadX; + if ((slavePtr->flags & FILLX) + || (width > (frameWidth - borderX))) { + width = frameWidth - borderX; + } + height = Tk_ReqHeight(slavePtr->tkwin) + slavePtr->doubleBw + + slavePtr->iPadY; + if ((slavePtr->flags & FILLY) + || (height > (frameHeight - borderY))) { + height = frameHeight - borderY; + } + borderX /= 2; + borderY /= 2; + switch (slavePtr->anchor) { + case TK_ANCHOR_N: + x = frameX + (frameWidth - width)/2; + y = frameY + borderY; + break; + case TK_ANCHOR_NE: + x = frameX + frameWidth - width - borderX; + y = frameY + borderY; + break; + case TK_ANCHOR_E: + x = frameX + frameWidth - width - borderX; + y = frameY + (frameHeight - height)/2; + break; + case TK_ANCHOR_SE: + x = frameX + frameWidth - width - borderX; + y = frameY + frameHeight - height - borderY; + break; + case TK_ANCHOR_S: + x = frameX + (frameWidth - width)/2; + y = frameY + frameHeight - height - borderY; + break; + case TK_ANCHOR_SW: + x = frameX + borderX; + y = frameY + frameHeight - height - borderY; + break; + case TK_ANCHOR_W: + x = frameX + borderX; + y = frameY + (frameHeight - height)/2; + break; + case TK_ANCHOR_NW: + x = frameX + borderX; + y = frameY + borderY; + break; + case TK_ANCHOR_CENTER: + x = frameX + (frameWidth - width)/2; + y = frameY + (frameHeight - height)/2; + break; + default: + panic("bad frame factor in ArrangePacking"); + } + width -= slavePtr->doubleBw; + height -= slavePtr->doubleBw; + + /* + * The final step is to set the position, size, and mapped/unmapped + * state of the slave. If the slave is a child of the master, then + * do this here. Otherwise let Tk_MaintainGeometry do the work. + */ + + if (masterPtr->tkwin == Tk_Parent(slavePtr->tkwin)) { + if ((width <= 0) || (height <= 0)) { + Tk_UnmapWindow(slavePtr->tkwin); + } else { + if ((x != Tk_X(slavePtr->tkwin)) + || (y != Tk_Y(slavePtr->tkwin)) + || (width != Tk_Width(slavePtr->tkwin)) + || (height != Tk_Height(slavePtr->tkwin))) { + Tk_MoveResizeWindow(slavePtr->tkwin, x, y, width, height); + } + if (abort) { + goto done; + } + + /* + * Don't map the slave if the master isn't mapped: wait + * until the master gets mapped later. + */ + + if (Tk_IsMapped(masterPtr->tkwin)) { + Tk_MapWindow(slavePtr->tkwin); + } + } + } else { + if ((width <= 0) || (height <= 0)) { + Tk_UnmaintainGeometry(slavePtr->tkwin, masterPtr->tkwin); + Tk_UnmapWindow(slavePtr->tkwin); + } else { + Tk_MaintainGeometry(slavePtr->tkwin, masterPtr->tkwin, + x, y, width, height); + } + } + + /* + * Changes to the window's structure could cause almost anything + * to happen, including deleting the parent or child. If this + * happens, we'll be told to abort. + */ + + if (abort) { + goto done; + } + } + + done: + masterPtr->abortPtr = NULL; + Tcl_Release((ClientData) masterPtr); +} + +/* + *---------------------------------------------------------------------- + * + * XExpansion -- + * + * Given a list of packed slaves, the first of which is packed + * on the left or right and is expandable, compute how much to + * expand the child. + * + * Results: + * The return value is the number of additional pixels to give to + * the child. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +XExpansion(slavePtr, cavityWidth) + register Packer *slavePtr; /* First in list of remaining + * slaves. */ + int cavityWidth; /* Horizontal space left for all + * remaining slaves. */ +{ + int numExpand, minExpand, curExpand; + int childWidth; + + /* + * This procedure is tricky because windows packed top or bottom can + * be interspersed among expandable windows packed left or right. + * Scan through the list, keeping a running sum of the widths of + * all left and right windows (actually, count the cavity space not + * allocated) and a running count of all expandable left and right + * windows. At each top or bottom window, and at the end of the + * list, compute the expansion factor that seems reasonable at that + * point. Return the smallest factor seen at any of these points. + */ + + minExpand = cavityWidth; + numExpand = 0; + for ( ; slavePtr != NULL; slavePtr = slavePtr->nextPtr) { + childWidth = Tk_ReqWidth(slavePtr->tkwin) + slavePtr->doubleBw + + slavePtr->padX + slavePtr->iPadX; + if ((slavePtr->side == TOP) || (slavePtr->side == BOTTOM)) { + curExpand = (cavityWidth - childWidth)/numExpand; + if (curExpand < minExpand) { + minExpand = curExpand; + } + } else { + cavityWidth -= childWidth; + if (slavePtr->flags & EXPAND) { + numExpand++; + } + } + } + curExpand = cavityWidth/numExpand; + if (curExpand < minExpand) { + minExpand = curExpand; + } + return (minExpand < 0) ? 0 : minExpand; +} + +/* + *---------------------------------------------------------------------- + * + * YExpansion -- + * + * Given a list of packed slaves, the first of which is packed + * on the top or bottom and is expandable, compute how much to + * expand the child. + * + * Results: + * The return value is the number of additional pixels to give to + * the child. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +YExpansion(slavePtr, cavityHeight) + register Packer *slavePtr; /* First in list of remaining + * slaves. */ + int cavityHeight; /* Vertical space left for all + * remaining slaves. */ +{ + int numExpand, minExpand, curExpand; + int childHeight; + + /* + * See comments for XExpansion. + */ + + minExpand = cavityHeight; + numExpand = 0; + for ( ; slavePtr != NULL; slavePtr = slavePtr->nextPtr) { + childHeight = Tk_ReqHeight(slavePtr->tkwin) + slavePtr->doubleBw + + slavePtr->padY + slavePtr->iPadY; + if ((slavePtr->side == LEFT) || (slavePtr->side == RIGHT)) { + curExpand = (cavityHeight - childHeight)/numExpand; + if (curExpand < minExpand) { + minExpand = curExpand; + } + } else { + cavityHeight -= childHeight; + if (slavePtr->flags & EXPAND) { + numExpand++; + } + } + } + curExpand = cavityHeight/numExpand; + if (curExpand < minExpand) { + minExpand = curExpand; + } + return (minExpand < 0) ? 0 : minExpand; +} + +/* + *-------------------------------------------------------------- + * + * GetPacker -- + * + * This internal procedure is used to locate a Packer + * structure for a given window, creating one if one + * doesn't exist already. + * + * Results: + * The return value is a pointer to the Packer structure + * corresponding to tkwin. + * + * Side effects: + * A new packer structure may be created. If so, then + * a callback is set up to clean things up when the + * window is deleted. + * + *-------------------------------------------------------------- + */ + +static Packer * +GetPacker(tkwin) + Tk_Window tkwin; /* Token for window for which + * packer structure is desired. */ +{ + register Packer *packPtr; + Tcl_HashEntry *hPtr; + int new; + + if (!initialized) { + initialized = 1; + Tcl_InitHashTable(&packerHashTable, TCL_ONE_WORD_KEYS); + } + + /* + * See if there's already packer for this window. If not, + * then create a new one. + */ + + hPtr = Tcl_CreateHashEntry(&packerHashTable, (char *) tkwin, &new); + if (!new) { + return (Packer *) Tcl_GetHashValue(hPtr); + } + packPtr = (Packer *) ckalloc(sizeof(Packer)); + packPtr->tkwin = tkwin; + packPtr->masterPtr = NULL; + packPtr->nextPtr = NULL; + packPtr->slavePtr = NULL; + packPtr->side = TOP; + packPtr->anchor = TK_ANCHOR_CENTER; + packPtr->padX = packPtr->padY = 0; + packPtr->iPadX = packPtr->iPadY = 0; + packPtr->doubleBw = 2*Tk_Changes(tkwin)->border_width; + packPtr->abortPtr = NULL; + packPtr->flags = 0; + Tcl_SetHashValue(hPtr, packPtr); + Tk_CreateEventHandler(tkwin, StructureNotifyMask, + PackStructureProc, (ClientData) packPtr); + return packPtr; +} + +/* + *-------------------------------------------------------------- + * + * PackAfter -- + * + * This procedure does most of the real work of adding + * one or more windows into the packing order for its parent. + * + * Results: + * A standard Tcl return value. + * + * Side effects: + * The geometry of the specified windows may change, both now and + * again in the future. + * + *-------------------------------------------------------------- + */ + +static int +PackAfter(interp, prevPtr, masterPtr, argc, argv) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Packer *prevPtr; /* Pack windows in argv just after this + * window; NULL means pack as first + * child of masterPtr. */ + Packer *masterPtr; /* Master in which to pack windows. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Array of lists, each containing 2 + * elements: window name and side + * against which to pack. */ +{ + register Packer *packPtr; + Tk_Window tkwin, ancestor, parent; + size_t length; + char **options; + int index, tmp, optionCount, c; + + /* + * Iterate over all of the window specifiers, each consisting of + * two arguments. The first argument contains the window name and + * the additional arguments contain options such as "top" or + * "padx 20". + */ + + for ( ; argc > 0; argc -= 2, argv += 2, prevPtr = packPtr) { + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: window \"", + argv[0], "\" should be followed by options", + (char *) NULL); + return TCL_ERROR; + } + + /* + * Find the packer for the window to be packed, and make sure + * that the window in which it will be packed is either its + * or a descendant of its parent. + */ + + tkwin = Tk_NameToWindow(interp, argv[0], masterPtr->tkwin); + if (tkwin == NULL) { + return TCL_ERROR; + } + + parent = Tk_Parent(tkwin); + for (ancestor = masterPtr->tkwin; ; ancestor = Tk_Parent(ancestor)) { + if (ancestor == parent) { + break; + } + if (((Tk_FakeWin *) (ancestor))->flags & TK_TOP_LEVEL) { + badWindow: + Tcl_AppendResult(interp, "can't pack ", argv[0], + " inside ", Tk_PathName(masterPtr->tkwin), + (char *) NULL); + return TCL_ERROR; + } + } + if (((Tk_FakeWin *) (tkwin))->flags & TK_TOP_LEVEL) { + goto badWindow; + } + if (tkwin == masterPtr->tkwin) { + goto badWindow; + } + packPtr = GetPacker(tkwin); + + /* + * Process options for this window. + */ + + if (Tcl_SplitList(interp, argv[1], &optionCount, &options) != TCL_OK) { + return TCL_ERROR; + } + packPtr->side = TOP; + packPtr->anchor = TK_ANCHOR_CENTER; + packPtr->padX = packPtr->padY = 0; + packPtr->iPadX = packPtr->iPadY = 0; + packPtr->flags &= ~(FILLX|FILLY|EXPAND); + packPtr->flags |= OLD_STYLE; + for (index = 0 ; index < optionCount; index++) { + char *curOpt = options[index]; + + c = curOpt[0]; + length = strlen(curOpt); + + if ((c == 't') + && (strncmp(curOpt, "top", length)) == 0) { + packPtr->side = TOP; + } else if ((c == 'b') + && (strncmp(curOpt, "bottom", length)) == 0) { + packPtr->side = BOTTOM; + } else if ((c == 'l') + && (strncmp(curOpt, "left", length)) == 0) { + packPtr->side = LEFT; + } else if ((c == 'r') + && (strncmp(curOpt, "right", length)) == 0) { + packPtr->side = RIGHT; + } else if ((c == 'e') + && (strncmp(curOpt, "expand", length)) == 0) { + packPtr->flags |= EXPAND; + } else if ((c == 'f') + && (strcmp(curOpt, "fill")) == 0) { + packPtr->flags |= FILLX|FILLY; + } else if ((length == 5) && (strcmp(curOpt, "fillx")) == 0) { + packPtr->flags |= FILLX; + } else if ((length == 5) && (strcmp(curOpt, "filly")) == 0) { + packPtr->flags |= FILLY; + } else if ((c == 'p') && (strcmp(curOpt, "padx")) == 0) { + if (optionCount < (index+2)) { + missingPad: + Tcl_AppendResult(interp, "wrong # args: \"", curOpt, + "\" option must be followed by screen distance", + (char *) NULL); + goto error; + } + if ((Tk_GetPixels(interp, tkwin, options[index+1], &tmp) + != TCL_OK) || (tmp < 0)) { + badPad: + Tcl_AppendResult(interp, "bad pad value \"", + options[index+1], + "\": must be positive screen distance", + (char *) NULL); + goto error; + } + packPtr->padX = tmp; + packPtr->iPadX = 0; + index++; + } else if ((c == 'p') && (strcmp(curOpt, "pady")) == 0) { + if (optionCount < (index+2)) { + goto missingPad; + } + if ((Tk_GetPixels(interp, tkwin, options[index+1], &tmp) + != TCL_OK) || (tmp < 0)) { + goto badPad; + } + packPtr->padY = tmp; + packPtr->iPadY = 0; + index++; + } else if ((c == 'f') && (length > 1) + && (strncmp(curOpt, "frame", length) == 0)) { + if (optionCount < (index+2)) { + Tcl_AppendResult(interp, "wrong # args: \"frame\" ", + "option must be followed by anchor point", + (char *) NULL); + goto error; + } + if (Tk_GetAnchor(interp, options[index+1], + &packPtr->anchor) != TCL_OK) { + goto error; + } + index++; + } else { + Tcl_AppendResult(interp, "bad option \"", curOpt, + "\": should be top, bottom, left, right, ", + "expand, fill, fillx, filly, padx, pady, or frame", + (char *) NULL); + goto error; + } + } + + if (packPtr != prevPtr) { + + /* + * Unpack this window if it's currently packed. + */ + + if (packPtr->masterPtr != NULL) { + if ((packPtr->masterPtr != masterPtr) && + (packPtr->masterPtr->tkwin + != Tk_Parent(packPtr->tkwin))) { + Tk_UnmaintainGeometry(packPtr->tkwin, + packPtr->masterPtr->tkwin); + } + Unlink(packPtr); + } + + /* + * Add the window in the correct place in its parent's + * packing order, then make sure that the window is + * managed by us. + */ + + packPtr->masterPtr = masterPtr; + if (prevPtr == NULL) { + packPtr->nextPtr = masterPtr->slavePtr; + masterPtr->slavePtr = packPtr; + } else { + packPtr->nextPtr = prevPtr->nextPtr; + prevPtr->nextPtr = packPtr; + } + Tk_ManageGeometry(tkwin, &packerType, (ClientData) packPtr); + } + ckfree((char *) options); + } + + /* + * Arrange for the parent to be re-packed at the first + * idle moment. + */ + + if (masterPtr->abortPtr != NULL) { + *masterPtr->abortPtr = 1; + } + if (!(masterPtr->flags & REQUESTED_REPACK)) { + masterPtr->flags |= REQUESTED_REPACK; + Tcl_DoWhenIdle(ArrangePacking, (ClientData) masterPtr); + } + return TCL_OK; + + error: + ckfree((char *) options); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * Unlink -- + * + * Remove a packer from its parent's list of slaves. + * + * Results: + * None. + * + * Side effects: + * The parent will be scheduled for repacking. + * + *---------------------------------------------------------------------- + */ + +static void +Unlink(packPtr) + register Packer *packPtr; /* Window to unlink. */ +{ + register Packer *masterPtr, *packPtr2; + + masterPtr = packPtr->masterPtr; + if (masterPtr == NULL) { + return; + } + if (masterPtr->slavePtr == packPtr) { + masterPtr->slavePtr = packPtr->nextPtr; + } else { + for (packPtr2 = masterPtr->slavePtr; ; packPtr2 = packPtr2->nextPtr) { + if (packPtr2 == NULL) { + panic("Unlink couldn't find previous window"); + } + if (packPtr2->nextPtr == packPtr) { + packPtr2->nextPtr = packPtr->nextPtr; + break; + } + } + } + if (!(masterPtr->flags & REQUESTED_REPACK)) { + masterPtr->flags |= REQUESTED_REPACK; + Tcl_DoWhenIdle(ArrangePacking, (ClientData) masterPtr); + } + if (masterPtr->abortPtr != NULL) { + *masterPtr->abortPtr = 1; + } + + packPtr->masterPtr = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyPacker -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a packer at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the packer is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyPacker(memPtr) + char *memPtr; /* Info about packed window that + * is now dead. */ +{ + register Packer *packPtr = (Packer *) memPtr; + ckfree((char *) packPtr); +} + +/* + *---------------------------------------------------------------------- + * + * PackStructureProc -- + * + * This procedure is invoked by the Tk event dispatcher in response + * to StructureNotify events. + * + * Results: + * None. + * + * Side effects: + * If a window was just deleted, clean up all its packer-related + * information. If it was just resized, repack its slaves, if + * any. + * + *---------------------------------------------------------------------- + */ + +static void +PackStructureProc(clientData, eventPtr) + ClientData clientData; /* Our information about window + * referred to by eventPtr. */ + XEvent *eventPtr; /* Describes what just happened. */ +{ + register Packer *packPtr = (Packer *) clientData; + if (eventPtr->type == ConfigureNotify) { + if ((packPtr->slavePtr != NULL) + && !(packPtr->flags & REQUESTED_REPACK)) { + packPtr->flags |= REQUESTED_REPACK; + Tcl_DoWhenIdle(ArrangePacking, (ClientData) packPtr); + } + if (packPtr->doubleBw != 2*Tk_Changes(packPtr->tkwin)->border_width) { + if ((packPtr->masterPtr != NULL) + && !(packPtr->masterPtr->flags & REQUESTED_REPACK)) { + packPtr->doubleBw = 2*Tk_Changes(packPtr->tkwin)->border_width; + packPtr->masterPtr->flags |= REQUESTED_REPACK; + Tcl_DoWhenIdle(ArrangePacking, (ClientData) packPtr->masterPtr); + } + } + } else if (eventPtr->type == DestroyNotify) { + register Packer *slavePtr, *nextPtr; + + if (packPtr->masterPtr != NULL) { + Unlink(packPtr); + } + for (slavePtr = packPtr->slavePtr; slavePtr != NULL; + slavePtr = nextPtr) { + Tk_ManageGeometry(slavePtr->tkwin, (Tk_GeomMgr *) NULL, + (ClientData) NULL); + Tk_UnmapWindow(slavePtr->tkwin); + slavePtr->masterPtr = NULL; + nextPtr = slavePtr->nextPtr; + slavePtr->nextPtr = NULL; + } + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&packerHashTable, + (char *) packPtr->tkwin)); + if (packPtr->flags & REQUESTED_REPACK) { + Tcl_CancelIdleCall(ArrangePacking, (ClientData) packPtr); + } + packPtr->tkwin = NULL; + Tcl_EventuallyFree((ClientData) packPtr, DestroyPacker); + } else if (eventPtr->type == MapNotify) { + /* + * When a master gets mapped, must redo the geometry computation + * so that all of its slaves get remapped. + */ + + if ((packPtr->slavePtr != NULL) + && !(packPtr->flags & REQUESTED_REPACK)) { + packPtr->flags |= REQUESTED_REPACK; + Tcl_DoWhenIdle(ArrangePacking, (ClientData) packPtr); + } + } else if (eventPtr->type == UnmapNotify) { + Packer *packPtr2; + + /* + * Unmap all of the slaves when the master gets unmapped, + * so that they don't bother to keep redisplaying + * themselves. + */ + + for (packPtr2 = packPtr->slavePtr; packPtr2 != NULL; + packPtr2 = packPtr2->nextPtr) { + Tk_UnmapWindow(packPtr2->tkwin); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureSlaves -- + * + * This implements the guts of the "pack configure" command. Given + * a list of slaves and configuration options, it arranges for the + * packer to manage the slaves and sets the specified options. + * + * Results: + * TCL_OK is returned if all went well. Otherwise, TCL_ERROR is + * returned and interp->result is set to contain an error message. + * + * Side effects: + * Slave windows get taken over by the packer. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureSlaves(interp, tkwin, argc, argv) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Window tkwin; /* Any window in application containing + * slaves. Used to look up slave names. */ + int argc; /* Number of elements in argv. */ + char *argv[]; /* Argument strings: contains one or more + * window names followed by any number + * of "option value" pairs. Caller must + * make sure that there is at least one + * window name. */ +{ + Packer *masterPtr, *slavePtr, *prevPtr, *otherPtr; + Tk_Window other, slave, parent, ancestor; + int i, j, numWindows, c, tmp, positionGiven; + size_t length; + + /* + * Find out how many windows are specified. + */ + + for (numWindows = 0; numWindows < argc; numWindows++) { + if (argv[numWindows][0] != '.') { + break; + } + } + + /* + * Iterate over all of the slave windows, parsing the configuration + * options for each slave. It's a bit wasteful to re-parse the + * options for each slave, but things get too messy if we try to + * parse the arguments just once at the beginning. For example, + * if a slave already is packed we want to just change a few + * existing values without resetting everything. If there are + * multiple windows, the -after, -before, and -in options only + * get processed for the first window. + */ + + masterPtr = NULL; + prevPtr = NULL; + positionGiven = 0; + for (j = 0; j < numWindows; j++) { + slave = Tk_NameToWindow(interp, argv[j], tkwin); + if (slave == NULL) { + return TCL_ERROR; + } + if (Tk_IsTopLevel(slave)) { + Tcl_AppendResult(interp, "can't pack \"", argv[j], + "\": it's a top-level window", (char *) NULL); + return TCL_ERROR; + } + slavePtr = GetPacker(slave); + slavePtr->flags &= ~OLD_STYLE; + + /* + * If the slave isn't currently packed, reset all of its + * configuration information to default values (there could + * be old values left from a previous packing). + */ + + if (slavePtr->masterPtr == NULL) { + slavePtr->side = TOP; + slavePtr->anchor = TK_ANCHOR_CENTER; + slavePtr->padX = slavePtr->padY = 0; + slavePtr->iPadX = slavePtr->iPadY = 0; + slavePtr->flags &= ~(FILLX|FILLY|EXPAND); + } + + for (i = numWindows; i < argc; i+=2) { + if ((i+2) > argc) { + Tcl_AppendResult(interp, "extra option \"", argv[i], + "\" (option with no value?)", (char *) NULL); + return TCL_ERROR; + } + length = strlen(argv[i]); + if (length < 2) { + goto badOption; + } + c = argv[i][1]; + if ((c == 'a') && (strncmp(argv[i], "-after", length) == 0) + && (length >= 2)) { + if (j == 0) { + other = Tk_NameToWindow(interp, argv[i+1], tkwin); + if (other == NULL) { + return TCL_ERROR; + } + prevPtr = GetPacker(other); + if (prevPtr->masterPtr == NULL) { + notPacked: + Tcl_AppendResult(interp, "window \"", argv[i+1], + "\" isn't packed", (char *) NULL); + return TCL_ERROR; + } + masterPtr = prevPtr->masterPtr; + positionGiven = 1; + } + } else if ((c == 'a') && (strncmp(argv[i], "-anchor", length) == 0) + && (length >= 2)) { + if (Tk_GetAnchor(interp, argv[i+1], &slavePtr->anchor) + != TCL_OK) { + return TCL_ERROR; + } + } else if ((c == 'b') + && (strncmp(argv[i], "-before", length) == 0)) { + if (j == 0) { + other = Tk_NameToWindow(interp, argv[i+1], tkwin); + if (other == NULL) { + return TCL_ERROR; + } + otherPtr = GetPacker(other); + if (otherPtr->masterPtr == NULL) { + goto notPacked; + } + masterPtr = otherPtr->masterPtr; + prevPtr = masterPtr->slavePtr; + if (prevPtr == otherPtr) { + prevPtr = NULL; + } else { + while (prevPtr->nextPtr != otherPtr) { + prevPtr = prevPtr->nextPtr; + } + } + positionGiven = 1; + } + } else if ((c == 'e') + && (strncmp(argv[i], "-expand", length) == 0)) { + if (Tcl_GetBoolean(interp, argv[i+1], &tmp) != TCL_OK) { + return TCL_ERROR; + } + slavePtr->flags &= ~EXPAND; + if (tmp) { + slavePtr->flags |= EXPAND; + } + } else if ((c == 'f') && (strncmp(argv[i], "-fill", length) == 0)) { + if (strcmp(argv[i+1], "none") == 0) { + slavePtr->flags &= ~(FILLX|FILLY); + } else if (strcmp(argv[i+1], "x") == 0) { + slavePtr->flags = (slavePtr->flags & ~FILLY) | FILLX; + } else if (strcmp(argv[i+1], "y") == 0) { + slavePtr->flags = (slavePtr->flags & ~FILLX) | FILLY; + } else if (strcmp(argv[i+1], "both") == 0) { + slavePtr->flags |= FILLX|FILLY; + } else { + Tcl_AppendResult(interp, "bad fill style \"", argv[i+1], + "\": must be none, x, y, or both", (char *) NULL); + return TCL_ERROR; + } + } else if ((c == 'i') && (strcmp(argv[i], "-in") == 0)) { + if (j == 0) { + other = Tk_NameToWindow(interp, argv[i+1], tkwin); + if (other == NULL) { + return TCL_ERROR; + } + masterPtr = GetPacker(other); + prevPtr = masterPtr->slavePtr; + if (prevPtr != NULL) { + while (prevPtr->nextPtr != NULL) { + prevPtr = prevPtr->nextPtr; + } + } + positionGiven = 1; + } + } else if ((c == 'i') && (strcmp(argv[i], "-ipadx") == 0)) { + if ((Tk_GetPixels(interp, slave, argv[i+1], &tmp) != TCL_OK) + || (tmp < 0)) { + badPad: + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad pad value \"", argv[i+1], + "\": must be positive screen distance", + (char *) NULL); + return TCL_ERROR; + } + slavePtr->iPadX = tmp*2; + } else if ((c == 'i') && (strcmp(argv[i], "-ipady") == 0)) { + if ((Tk_GetPixels(interp, slave, argv[i+1], &tmp) != TCL_OK) + || (tmp< 0)) { + goto badPad; + } + slavePtr->iPadY = tmp*2; + } else if ((c == 'p') && (strcmp(argv[i], "-padx") == 0)) { + if ((Tk_GetPixels(interp, slave, argv[i+1], &tmp) != TCL_OK) + || (tmp< 0)) { + goto badPad; + } + slavePtr->padX = tmp*2; + } else if ((c == 'p') && (strcmp(argv[i], "-pady") == 0)) { + if ((Tk_GetPixels(interp, slave, argv[i+1], &tmp) != TCL_OK) + || (tmp< 0)) { + goto badPad; + } + slavePtr->padY = tmp*2; + } else if ((c == 's') && (strncmp(argv[i], "-side", length) == 0)) { + c = argv[i+1][0]; + if ((c == 't') && (strcmp(argv[i+1], "top") == 0)) { + slavePtr->side = TOP; + } else if ((c == 'b') && (strcmp(argv[i+1], "bottom") == 0)) { + slavePtr->side = BOTTOM; + } else if ((c == 'l') && (strcmp(argv[i+1], "left") == 0)) { + slavePtr->side = LEFT; + } else if ((c == 'r') && (strcmp(argv[i+1], "right") == 0)) { + slavePtr->side = RIGHT; + } else { + Tcl_AppendResult(interp, "bad side \"", argv[i+1], + "\": must be top, bottom, left, or right", + (char *) NULL); + return TCL_ERROR; + } + } else { + badOption: + Tcl_AppendResult(interp, "unknown or ambiguous option \"", + argv[i], "\": must be -after, -anchor, -before, ", + "-expand, -fill, -in, -ipadx, -ipady, -padx, ", + "-pady, or -side", (char *) NULL); + return TCL_ERROR; + } + } + + /* + * If no position in a packing list was specified and the slave + * is already packed, then leave it in its current location in + * its current packing list. + */ + + if (!positionGiven && (slavePtr->masterPtr != NULL)) { + masterPtr = slavePtr->masterPtr; + goto scheduleLayout; + } + + /* + * If the slave is going to be put back after itself then + * skip the whole operation, since it won't work anyway. + */ + + if (prevPtr == slavePtr) { + masterPtr = slavePtr->masterPtr; + goto scheduleLayout; + } + + /* + * If none of the "-in", "-before", or "-after" options has + * been specified, arrange for the slave to go at the end of + * the order for its parent. + */ + + if (!positionGiven) { + masterPtr = GetPacker(Tk_Parent(slave)); + prevPtr = masterPtr->slavePtr; + if (prevPtr != NULL) { + while (prevPtr->nextPtr != NULL) { + prevPtr = prevPtr->nextPtr; + } + } + } + + /* + * Make sure that the slave's parent is either the master or + * an ancestor of the master, and that the master and slave + * aren't the same. + */ + + parent = Tk_Parent(slave); + for (ancestor = masterPtr->tkwin; ; ancestor = Tk_Parent(ancestor)) { + if (ancestor == parent) { + break; + } + if (Tk_IsTopLevel(ancestor)) { + Tcl_AppendResult(interp, "can't pack ", argv[j], + " inside ", Tk_PathName(masterPtr->tkwin), + (char *) NULL); + return TCL_ERROR; + } + } + if (slave == masterPtr->tkwin) { + Tcl_AppendResult(interp, "can't pack ", argv[j], + " inside itself", (char *) NULL); + return TCL_ERROR; + } + + /* + * Unpack the slave if it's currently packed, then position it + * after prevPtr. + */ + + if (slavePtr->masterPtr != NULL) { + if ((slavePtr->masterPtr != masterPtr) && + (slavePtr->masterPtr->tkwin + != Tk_Parent(slavePtr->tkwin))) { + Tk_UnmaintainGeometry(slavePtr->tkwin, + slavePtr->masterPtr->tkwin); + } + Unlink(slavePtr); + } + slavePtr->masterPtr = masterPtr; + if (prevPtr == NULL) { + slavePtr->nextPtr = masterPtr->slavePtr; + masterPtr->slavePtr = slavePtr; + } else { + slavePtr->nextPtr = prevPtr->nextPtr; + prevPtr->nextPtr = slavePtr; + } + Tk_ManageGeometry(slave, &packerType, (ClientData) slavePtr); + prevPtr = slavePtr; + + /* + * Arrange for the parent to be re-packed at the first + * idle moment. + */ + + scheduleLayout: + if (masterPtr->abortPtr != NULL) { + *masterPtr->abortPtr = 1; + } + if (!(masterPtr->flags & REQUESTED_REPACK)) { + masterPtr->flags |= REQUESTED_REPACK; + Tcl_DoWhenIdle(ArrangePacking, (ClientData) masterPtr); + } + } + return TCL_OK; +} diff --git a/generic/tkPlace.c b/generic/tkPlace.c new file mode 100644 index 0000000..15ddcef --- /dev/null +++ b/generic/tkPlace.c @@ -0,0 +1,1060 @@ +/* + * tkPlace.c -- + * + * This file contains code to implement a simple geometry manager + * for Tk based on absolute placement or "rubber-sheet" placement. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkPlace.c 1.27 96/08/20 17:05:31 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * Border modes for relative placement: + * + * BM_INSIDE: relative distances computed using area inside + * all borders of master window. + * BM_OUTSIDE: relative distances computed using outside area + * that includes all borders of master. + * BM_IGNORE: border issues are ignored: place relative to + * master's actual window size. + */ + +typedef enum {BM_INSIDE, BM_OUTSIDE, BM_IGNORE} BorderMode; + +/* + * For each window whose geometry is managed by the placer there is + * a structure of the following type: + */ + +typedef struct Slave { + Tk_Window tkwin; /* Tk's token for window. */ + struct Master *masterPtr; /* Pointer to information for window + * relative to which tkwin is placed. + * This isn't necessarily the logical + * parent of tkwin. NULL means the + * master was deleted or never assigned. */ + struct Slave *nextPtr; /* Next in list of windows placed relative + * to same master (NULL for end of list). */ + + /* + * Geometry information for window; where there are both relative + * and absolute values for the same attribute (e.g. x and relX) only + * one of them is actually used, depending on flags. + */ + + int x, y; /* X and Y pixel coordinates for tkwin. */ + float relX, relY; /* X and Y coordinates relative to size of + * master. */ + int width, height; /* Absolute dimensions for tkwin. */ + float relWidth, relHeight; /* Dimensions for tkwin relative to size of + * master. */ + Tk_Anchor anchor; /* Which point on tkwin is placed at the + * given position. */ + BorderMode borderMode; /* How to treat borders of master window. */ + int flags; /* Various flags; see below for bit + * definitions. */ +} Slave; + +/* + * Flag definitions for Slave structures: + * + * CHILD_WIDTH - 1 means -width was specified; + * CHILD_REL_WIDTH - 1 means -relwidth was specified. + * CHILD_HEIGHT - 1 means -height was specified; + * CHILD_REL_HEIGHT - 1 means -relheight was specified. + */ + +#define CHILD_WIDTH 1 +#define CHILD_REL_WIDTH 2 +#define CHILD_HEIGHT 4 +#define CHILD_REL_HEIGHT 8 + +/* + * For each master window that has a slave managed by the placer there + * is a structure of the following form: + */ + +typedef struct Master { + Tk_Window tkwin; /* Tk's token for master window. */ + struct Slave *slavePtr; /* First in linked list of slaves + * placed relative to this master. */ + int flags; /* See below for bit definitions. */ +} Master; + +/* + * Flag definitions for masters: + * + * PARENT_RECONFIG_PENDING - 1 means that a call to RecomputePlacement + * is already pending via a Do_When_Idle handler. + */ + +#define PARENT_RECONFIG_PENDING 1 + +/* + * The hash tables below both use Tk_Window tokens as keys. They map + * from Tk_Windows to Slave and Master structures for windows, if they + * exist. + */ + +static int initialized = 0; +static Tcl_HashTable masterTable; +static Tcl_HashTable slaveTable; +/* + * The following structure is the official type record for the + * placer: + */ + +static void PlaceRequestProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); +static void PlaceLostSlaveProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); + +static Tk_GeomMgr placerType = { + "place", /* name */ + PlaceRequestProc, /* requestProc */ + PlaceLostSlaveProc, /* lostSlaveProc */ +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void SlaveStructureProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int ConfigureSlave _ANSI_ARGS_((Tcl_Interp *interp, + Slave *slavePtr, int argc, char **argv)); +static Slave * FindSlave _ANSI_ARGS_((Tk_Window tkwin)); +static Master * FindMaster _ANSI_ARGS_((Tk_Window tkwin)); +static void MasterStructureProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void RecomputePlacement _ANSI_ARGS_((ClientData clientData)); +static void UnlinkSlave _ANSI_ARGS_((Slave *slavePtr)); + +/* + *-------------------------------------------------------------- + * + * Tk_PlaceCmd -- + * + * This procedure is invoked to process the "place" Tcl + * commands. See the user documentation for details on + * what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_PlaceCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin; + Slave *slavePtr; + Tcl_HashEntry *hPtr; + size_t length; + int c; + + /* + * Initialize, if that hasn't been done yet. + */ + + if (!initialized) { + Tcl_InitHashTable(&masterTable, TCL_ONE_WORD_KEYS); + Tcl_InitHashTable(&slaveTable, TCL_ONE_WORD_KEYS); + initialized = 1; + } + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option|pathName args", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + + /* + * Handle special shortcut where window name is first argument. + */ + + if (c == '.') { + tkwin = Tk_NameToWindow(interp, argv[1], (Tk_Window) clientData); + if (tkwin == NULL) { + return TCL_ERROR; + } + slavePtr = FindSlave(tkwin); + return ConfigureSlave(interp, slavePtr, argc-2, argv+2); + } + + /* + * Handle more general case of option followed by window name followed + * by possible additional arguments. + */ + + tkwin = Tk_NameToWindow(interp, argv[2], (Tk_Window) clientData); + if (tkwin == NULL) { + return TCL_ERROR; + } + if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0)) { + if (argc < 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], + " configure pathName option value ?option value ...?\"", + (char *) NULL); + return TCL_ERROR; + } + slavePtr = FindSlave(tkwin); + return ConfigureSlave(interp, slavePtr, argc-3, argv+3); + } else if ((c == 'f') && (strncmp(argv[1], "forget", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " forget pathName\"", (char *) NULL); + return TCL_ERROR; + } + hPtr = Tcl_FindHashEntry(&slaveTable, (char *) tkwin); + if (hPtr == NULL) { + return TCL_OK; + } + slavePtr = (Slave *) Tcl_GetHashValue(hPtr); + if ((slavePtr->masterPtr != NULL) && + (slavePtr->masterPtr->tkwin != Tk_Parent(slavePtr->tkwin))) { + Tk_UnmaintainGeometry(slavePtr->tkwin, + slavePtr->masterPtr->tkwin); + } + UnlinkSlave(slavePtr); + Tcl_DeleteHashEntry(hPtr); + Tk_DeleteEventHandler(tkwin, StructureNotifyMask, SlaveStructureProc, + (ClientData) slavePtr); + Tk_ManageGeometry(tkwin, (Tk_GeomMgr *) NULL, (ClientData) NULL); + Tk_UnmapWindow(tkwin); + ckfree((char *) slavePtr); + } else if ((c == 'i') && (strncmp(argv[1], "info", length) == 0)) { + char buffer[50]; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " info pathName\"", (char *) NULL); + return TCL_ERROR; + } + hPtr = Tcl_FindHashEntry(&slaveTable, (char *) tkwin); + if (hPtr == NULL) { + return TCL_OK; + } + slavePtr = (Slave *) Tcl_GetHashValue(hPtr); + sprintf(buffer, "-x %d", slavePtr->x); + Tcl_AppendResult(interp, buffer, (char *) NULL); + sprintf(buffer, " -relx %.4g", slavePtr->relX); + Tcl_AppendResult(interp, buffer, (char *) NULL); + sprintf(buffer, " -y %d", slavePtr->y); + Tcl_AppendResult(interp, buffer, (char *) NULL); + sprintf(buffer, " -rely %.4g", slavePtr->relY); + Tcl_AppendResult(interp, buffer, (char *) NULL); + if (slavePtr->flags & CHILD_WIDTH) { + sprintf(buffer, " -width %d", slavePtr->width); + Tcl_AppendResult(interp, buffer, (char *) NULL); + } else { + Tcl_AppendResult(interp, " -width {}", (char *) NULL); + } + if (slavePtr->flags & CHILD_REL_WIDTH) { + sprintf(buffer, " -relwidth %.4g", slavePtr->relWidth); + Tcl_AppendResult(interp, buffer, (char *) NULL); + } else { + Tcl_AppendResult(interp, " -relwidth {}", (char *) NULL); + } + if (slavePtr->flags & CHILD_HEIGHT) { + sprintf(buffer, " -height %d", slavePtr->height); + Tcl_AppendResult(interp, buffer, (char *) NULL); + } else { + Tcl_AppendResult(interp, " -height {}", (char *) NULL); + } + if (slavePtr->flags & CHILD_REL_HEIGHT) { + sprintf(buffer, " -relheight %.4g", slavePtr->relHeight); + Tcl_AppendResult(interp, buffer, (char *) NULL); + } else { + Tcl_AppendResult(interp, " -relheight {}", (char *) NULL); + } + + Tcl_AppendResult(interp, " -anchor ", Tk_NameOfAnchor(slavePtr->anchor), + (char *) NULL); + if (slavePtr->borderMode == BM_OUTSIDE) { + Tcl_AppendResult(interp, " -bordermode outside", (char *) NULL); + } else if (slavePtr->borderMode == BM_IGNORE) { + Tcl_AppendResult(interp, " -bordermode ignore", (char *) NULL); + } + if ((slavePtr->masterPtr != NULL) + && (slavePtr->masterPtr->tkwin != Tk_Parent(slavePtr->tkwin))) { + Tcl_AppendResult(interp, " -in ", + Tk_PathName(slavePtr->masterPtr->tkwin), (char *) NULL); + } + } else if ((c == 's') && (strncmp(argv[1], "slaves", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " slaves pathName\"", (char *) NULL); + return TCL_ERROR; + } + hPtr = Tcl_FindHashEntry(&masterTable, (char *) tkwin); + if (hPtr != NULL) { + Master *masterPtr; + masterPtr = (Master *) Tcl_GetHashValue(hPtr); + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + Tcl_AppendElement(interp, Tk_PathName(slavePtr->tkwin)); + } + } + } else { + Tcl_AppendResult(interp, "unknown or ambiguous option \"", argv[1], + "\": must be configure, forget, info, or slaves", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FindSlave -- + * + * Given a Tk_Window token, find the Slave structure corresponding + * to that token (making a new one if necessary). + * + * Results: + * None. + * + * Side effects: + * A new Slave structure may be created. + * + *---------------------------------------------------------------------- + */ + +static Slave * +FindSlave(tkwin) + Tk_Window tkwin; /* Token for desired slave. */ +{ + Tcl_HashEntry *hPtr; + register Slave *slavePtr; + int new; + + hPtr = Tcl_CreateHashEntry(&slaveTable, (char *) tkwin, &new); + if (new) { + slavePtr = (Slave *) ckalloc(sizeof(Slave)); + slavePtr->tkwin = tkwin; + slavePtr->masterPtr = NULL; + slavePtr->nextPtr = NULL; + slavePtr->x = slavePtr->y = 0; + slavePtr->relX = slavePtr->relY = (float) 0.0; + slavePtr->width = slavePtr->height = 0; + slavePtr->relWidth = slavePtr->relHeight = (float) 0.0; + slavePtr->anchor = TK_ANCHOR_NW; + slavePtr->borderMode = BM_INSIDE; + slavePtr->flags = 0; + Tcl_SetHashValue(hPtr, slavePtr); + Tk_CreateEventHandler(tkwin, StructureNotifyMask, SlaveStructureProc, + (ClientData) slavePtr); + Tk_ManageGeometry(tkwin, &placerType, (ClientData) slavePtr); + } else { + slavePtr = (Slave *) Tcl_GetHashValue(hPtr); + } + return slavePtr; +} + +/* + *---------------------------------------------------------------------- + * + * UnlinkSlave -- + * + * This procedure removes a slave window from the chain of slaves + * in its master. + * + * Results: + * None. + * + * Side effects: + * The slave list of slavePtr's master changes. + * + *---------------------------------------------------------------------- + */ + +static void +UnlinkSlave(slavePtr) + Slave *slavePtr; /* Slave structure to be unlinked. */ +{ + register Master *masterPtr; + register Slave *prevPtr; + + masterPtr = slavePtr->masterPtr; + if (masterPtr == NULL) { + return; + } + if (masterPtr->slavePtr == slavePtr) { + masterPtr->slavePtr = slavePtr->nextPtr; + } else { + for (prevPtr = masterPtr->slavePtr; ; + prevPtr = prevPtr->nextPtr) { + if (prevPtr == NULL) { + panic("UnlinkSlave couldn't find slave to unlink"); + } + if (prevPtr->nextPtr == slavePtr) { + prevPtr->nextPtr = slavePtr->nextPtr; + break; + } + } + } + slavePtr->masterPtr = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * FindMaster -- + * + * Given a Tk_Window token, find the Master structure corresponding + * to that token (making a new one if necessary). + * + * Results: + * None. + * + * Side effects: + * A new Master structure may be created. + * + *---------------------------------------------------------------------- + */ + +static Master * +FindMaster(tkwin) + Tk_Window tkwin; /* Token for desired master. */ +{ + Tcl_HashEntry *hPtr; + register Master *masterPtr; + int new; + + hPtr = Tcl_CreateHashEntry(&masterTable, (char *) tkwin, &new); + if (new) { + masterPtr = (Master *) ckalloc(sizeof(Master)); + masterPtr->tkwin = tkwin; + masterPtr->slavePtr = NULL; + masterPtr->flags = 0; + Tcl_SetHashValue(hPtr, masterPtr); + Tk_CreateEventHandler(masterPtr->tkwin, StructureNotifyMask, + MasterStructureProc, (ClientData) masterPtr); + } else { + masterPtr = (Master *) Tcl_GetHashValue(hPtr); + } + return masterPtr; +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureSlave -- + * + * This procedure is called to process an argv/argc list to + * reconfigure the placement of a window. + * + * Results: + * A standard Tcl result. If an error occurs then a message is + * left in interp->result. + * + * Side effects: + * Information in slavePtr may change, and slavePtr's master is + * scheduled for reconfiguration. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureSlave(interp, slavePtr, argc, argv) + Tcl_Interp *interp; /* Used for error reporting. */ + Slave *slavePtr; /* Pointer to current information + * about slave. */ + int argc; /* Number of config arguments. */ + char **argv; /* String values for arguments. */ +{ + register Master *masterPtr; + int c, result; + size_t length; + double d; + + result = TCL_OK; + if (Tk_IsTopLevel(slavePtr->tkwin)) { + Tcl_AppendResult(interp, "can't use placer on top-level window \"", + Tk_PathName(slavePtr->tkwin), "\"; use wm command instead", + (char *) NULL); + return TCL_ERROR; + } + for ( ; argc > 0; argc -= 2, argv += 2) { + if (argc < 2) { + Tcl_AppendResult(interp, "extra option \"", argv[0], + "\" (option with no value?)", (char *) NULL); + result = TCL_ERROR; + goto done; + } + length = strlen(argv[0]); + c = argv[0][1]; + if ((c == 'a') && (strncmp(argv[0], "-anchor", length) == 0)) { + if (Tk_GetAnchor(interp, argv[1], &slavePtr->anchor) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + } else if ((c == 'b') + && (strncmp(argv[0], "-bordermode", length) == 0)) { + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'i') && (strncmp(argv[1], "ignore", length) == 0) + && (length >= 2)) { + slavePtr->borderMode = BM_IGNORE; + } else if ((c == 'i') && (strncmp(argv[1], "inside", length) == 0) + && (length >= 2)) { + slavePtr->borderMode = BM_INSIDE; + } else if ((c == 'o') + && (strncmp(argv[1], "outside", length) == 0)) { + slavePtr->borderMode = BM_OUTSIDE; + } else { + Tcl_AppendResult(interp, "bad border mode \"", argv[1], + "\": must be ignore, inside, or outside", + (char *) NULL); + result = TCL_ERROR; + goto done; + } + } else if ((c == 'h') && (strncmp(argv[0], "-height", length) == 0)) { + if (argv[1][0] == 0) { + slavePtr->flags &= ~CHILD_HEIGHT; + } else { + if (Tk_GetPixels(interp, slavePtr->tkwin, argv[1], + &slavePtr->height) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + slavePtr->flags |= CHILD_HEIGHT; + } + } else if ((c == 'i') && (strncmp(argv[0], "-in", length) == 0)) { + Tk_Window tkwin; + Tk_Window ancestor; + + tkwin = Tk_NameToWindow(interp, argv[1], slavePtr->tkwin); + if (tkwin == NULL) { + result = TCL_ERROR; + goto done; + } + + /* + * Make sure that the new master is either the logical parent + * of the slave or a descendant of that window, and that the + * master and slave aren't the same. + */ + + for (ancestor = tkwin; ; ancestor = Tk_Parent(ancestor)) { + if (ancestor == Tk_Parent(slavePtr->tkwin)) { + break; + } + if (Tk_IsTopLevel(ancestor)) { + Tcl_AppendResult(interp, "can't place ", + Tk_PathName(slavePtr->tkwin), " relative to ", + Tk_PathName(tkwin), (char *) NULL); + result = TCL_ERROR; + goto done; + } + } + if (slavePtr->tkwin == tkwin) { + Tcl_AppendResult(interp, "can't place ", + Tk_PathName(slavePtr->tkwin), " relative to itself", + (char *) NULL); + result = TCL_ERROR; + goto done; + } + if ((slavePtr->masterPtr != NULL) + && (slavePtr->masterPtr->tkwin == tkwin)) { + /* + * Re-using same old master. Nothing to do. + */ + } else { + if ((slavePtr->masterPtr != NULL) + && (slavePtr->masterPtr->tkwin + != Tk_Parent(slavePtr->tkwin))) { + Tk_UnmaintainGeometry(slavePtr->tkwin, + slavePtr->masterPtr->tkwin); + } + UnlinkSlave(slavePtr); + slavePtr->masterPtr = FindMaster(tkwin); + slavePtr->nextPtr = slavePtr->masterPtr->slavePtr; + slavePtr->masterPtr->slavePtr = slavePtr; + } + } else if ((c == 'r') && (strncmp(argv[0], "-relheight", length) == 0) + && (length >= 5)) { + if (argv[1][0] == 0) { + slavePtr->flags &= ~CHILD_REL_HEIGHT; + } else { + if (Tcl_GetDouble(interp, argv[1], &d) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + slavePtr->relHeight = (float) d; + slavePtr->flags |= CHILD_REL_HEIGHT; + } + } else if ((c == 'r') && (strncmp(argv[0], "-relwidth", length) == 0) + && (length >= 5)) { + if (argv[1][0] == 0) { + slavePtr->flags &= ~CHILD_REL_WIDTH; + } else { + if (Tcl_GetDouble(interp, argv[1], &d) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + slavePtr->relWidth = (float) d; + slavePtr->flags |= CHILD_REL_WIDTH; + } + } else if ((c == 'r') && (strncmp(argv[0], "-relx", length) == 0) + && (length >= 5)) { + if (Tcl_GetDouble(interp, argv[1], &d) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + slavePtr->relX = (float) d; + } else if ((c == 'r') && (strncmp(argv[0], "-rely", length) == 0) + && (length >= 5)) { + if (Tcl_GetDouble(interp, argv[1], &d) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + slavePtr->relY = (float) d; + } else if ((c == 'w') && (strncmp(argv[0], "-width", length) == 0)) { + if (argv[1][0] == 0) { + slavePtr->flags &= ~CHILD_WIDTH; + } else { + if (Tk_GetPixels(interp, slavePtr->tkwin, argv[1], + &slavePtr->width) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + slavePtr->flags |= CHILD_WIDTH; + } + } else if ((c == 'x') && (strncmp(argv[0], "-x", length) == 0)) { + if (Tk_GetPixels(interp, slavePtr->tkwin, argv[1], + &slavePtr->x) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + } else if ((c == 'y') && (strncmp(argv[0], "-y", length) == 0)) { + if (Tk_GetPixels(interp, slavePtr->tkwin, argv[1], + &slavePtr->y) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + } else { + Tcl_AppendResult(interp, "unknown or ambiguous option \"", + argv[0], "\": must be -anchor, -bordermode, -height, ", + "-in, -relheight, -relwidth, -relx, -rely, -width, ", + "-x, or -y", (char *) NULL); + result = TCL_ERROR; + goto done; + } + } + + /* + * If there's no master specified for this slave, use its Tk_Parent. + * Then arrange for a placement recalculation in the master. + */ + + done: + masterPtr = slavePtr->masterPtr; + if (masterPtr == NULL) { + masterPtr = FindMaster(Tk_Parent(slavePtr->tkwin)); + slavePtr->masterPtr = masterPtr; + slavePtr->nextPtr = masterPtr->slavePtr; + masterPtr->slavePtr = slavePtr; + } + if (!(masterPtr->flags & PARENT_RECONFIG_PENDING)) { + masterPtr->flags |= PARENT_RECONFIG_PENDING; + Tcl_DoWhenIdle(RecomputePlacement, (ClientData) masterPtr); + } + return result; +} + +/* + *---------------------------------------------------------------------- + * + * RecomputePlacement -- + * + * This procedure is called as a when-idle handler. It recomputes + * the geometries of all the slaves of a given master. + * + * Results: + * None. + * + * Side effects: + * Windows may change size or shape. + * + *---------------------------------------------------------------------- + */ + +static void +RecomputePlacement(clientData) + ClientData clientData; /* Pointer to Master record. */ +{ + register Master *masterPtr = (Master *) clientData; + register Slave *slavePtr; + int x, y, width, height, tmp; + int masterWidth, masterHeight, masterBW; + double x1, y1, x2, y2; + + masterPtr->flags &= ~PARENT_RECONFIG_PENDING; + + /* + * Iterate over all the slaves for the master. Each slave's + * geometry can be computed independently of the other slaves. + */ + + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + /* + * Step 1: compute size and borderwidth of master, taking into + * account desired border mode. + */ + + masterBW = 0; + masterWidth = Tk_Width(masterPtr->tkwin); + masterHeight = Tk_Height(masterPtr->tkwin); + if (slavePtr->borderMode == BM_INSIDE) { + masterBW = Tk_InternalBorderWidth(masterPtr->tkwin); + } else if (slavePtr->borderMode == BM_OUTSIDE) { + masterBW = -Tk_Changes(masterPtr->tkwin)->border_width; + } + masterWidth -= 2*masterBW; + masterHeight -= 2*masterBW; + + /* + * Step 2: compute size of slave (outside dimensions including + * border) and location of anchor point within master. + */ + + x1 = slavePtr->x + masterBW + (slavePtr->relX*masterWidth); + x = (int) (x1 + ((x1 > 0) ? 0.5 : -0.5)); + y1 = slavePtr->y + masterBW + (slavePtr->relY*masterHeight); + y = (int) (y1 + ((y1 > 0) ? 0.5 : -0.5)); + if (slavePtr->flags & (CHILD_WIDTH|CHILD_REL_WIDTH)) { + width = 0; + if (slavePtr->flags & CHILD_WIDTH) { + width += slavePtr->width; + } + if (slavePtr->flags & CHILD_REL_WIDTH) { + /* + * The code below is a bit tricky. In order to round + * correctly when both relX and relWidth are specified, + * compute the location of the right edge and round that, + * then compute width. If we compute the width and round + * it, rounding errors in relX and relWidth accumulate. + */ + + x2 = x1 + (slavePtr->relWidth*masterWidth); + tmp = (int) (x2 + ((x2 > 0) ? 0.5 : -0.5)); + width += tmp - x; + } + } else { + width = Tk_ReqWidth(slavePtr->tkwin) + + 2*Tk_Changes(slavePtr->tkwin)->border_width; + } + if (slavePtr->flags & (CHILD_HEIGHT|CHILD_REL_HEIGHT)) { + height = 0; + if (slavePtr->flags & CHILD_HEIGHT) { + height += slavePtr->height; + } + if (slavePtr->flags & CHILD_REL_HEIGHT) { + /* + * See note above for rounding errors in width computation. + */ + + y2 = y1 + (slavePtr->relHeight*masterHeight); + tmp = (int) (y2 + ((y2 > 0) ? 0.5 : -0.5)); + height += tmp - y; + } + } else { + height = Tk_ReqHeight(slavePtr->tkwin) + + 2*Tk_Changes(slavePtr->tkwin)->border_width; + } + + /* + * Step 3: adjust the x and y positions so that the desired + * anchor point on the slave appears at that position. Also + * adjust for the border mode and master's border. + */ + + switch (slavePtr->anchor) { + case TK_ANCHOR_N: + x -= width/2; + break; + case TK_ANCHOR_NE: + x -= width; + break; + case TK_ANCHOR_E: + x -= width; + y -= height/2; + break; + case TK_ANCHOR_SE: + x -= width; + y -= height; + break; + case TK_ANCHOR_S: + x -= width/2; + y -= height; + break; + case TK_ANCHOR_SW: + y -= height; + break; + case TK_ANCHOR_W: + y -= height/2; + break; + case TK_ANCHOR_NW: + break; + case TK_ANCHOR_CENTER: + x -= width/2; + y -= height/2; + break; + } + + /* + * Step 4: adjust width and height again to reflect inside dimensions + * of window rather than outside. Also make sure that the width and + * height aren't zero. + */ + + width -= 2*Tk_Changes(slavePtr->tkwin)->border_width; + height -= 2*Tk_Changes(slavePtr->tkwin)->border_width; + if (width <= 0) { + width = 1; + } + if (height <= 0) { + height = 1; + } + + /* + * Step 5: reconfigure the window and map it if needed. If the + * slave is a child of the master, we do this ourselves. If the + * slave isn't a child of the master, let Tk_MaintainWindow do + * the work (it will re-adjust things as relevant windows map, + * unmap, and move). + */ + + if (masterPtr->tkwin == Tk_Parent(slavePtr->tkwin)) { + if ((x != Tk_X(slavePtr->tkwin)) + || (y != Tk_Y(slavePtr->tkwin)) + || (width != Tk_Width(slavePtr->tkwin)) + || (height != Tk_Height(slavePtr->tkwin))) { + Tk_MoveResizeWindow(slavePtr->tkwin, x, y, width, height); + } + + /* + * Don't map the slave unless the master is mapped: the slave + * will get mapped later, when the master is mapped. + */ + + if (Tk_IsMapped(masterPtr->tkwin)) { + Tk_MapWindow(slavePtr->tkwin); + } + } else { + if ((width <= 0) || (height <= 0)) { + Tk_UnmaintainGeometry(slavePtr->tkwin, masterPtr->tkwin); + Tk_UnmapWindow(slavePtr->tkwin); + } else { + Tk_MaintainGeometry(slavePtr->tkwin, masterPtr->tkwin, + x, y, width, height); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * MasterStructureProc -- + * + * This procedure is invoked by the Tk event handler when + * StructureNotify events occur for a master window. + * + * Results: + * None. + * + * Side effects: + * Structures get cleaned up if the window was deleted. If the + * window was resized then slave geometries get recomputed. + * + *---------------------------------------------------------------------- + */ + +static void +MasterStructureProc(clientData, eventPtr) + ClientData clientData; /* Pointer to Master structure for window + * referred to by eventPtr. */ + XEvent *eventPtr; /* Describes what just happened. */ +{ + register Master *masterPtr = (Master *) clientData; + register Slave *slavePtr, *nextPtr; + + if (eventPtr->type == ConfigureNotify) { + if ((masterPtr->slavePtr != NULL) + && !(masterPtr->flags & PARENT_RECONFIG_PENDING)) { + masterPtr->flags |= PARENT_RECONFIG_PENDING; + Tcl_DoWhenIdle(RecomputePlacement, (ClientData) masterPtr); + } + } else if (eventPtr->type == DestroyNotify) { + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = nextPtr) { + slavePtr->masterPtr = NULL; + nextPtr = slavePtr->nextPtr; + slavePtr->nextPtr = NULL; + } + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&masterTable, + (char *) masterPtr->tkwin)); + if (masterPtr->flags & PARENT_RECONFIG_PENDING) { + Tcl_CancelIdleCall(RecomputePlacement, (ClientData) masterPtr); + } + masterPtr->tkwin = NULL; + ckfree((char *) masterPtr); + } else if (eventPtr->type == MapNotify) { + /* + * When a master gets mapped, must redo the geometry computation + * so that all of its slaves get remapped. + */ + + if ((masterPtr->slavePtr != NULL) + && !(masterPtr->flags & PARENT_RECONFIG_PENDING)) { + masterPtr->flags |= PARENT_RECONFIG_PENDING; + Tcl_DoWhenIdle(RecomputePlacement, (ClientData) masterPtr); + } + } else if (eventPtr->type == UnmapNotify) { + /* + * Unmap all of the slaves when the master gets unmapped, + * so that they don't keep redisplaying themselves. + */ + + for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; + slavePtr = slavePtr->nextPtr) { + Tk_UnmapWindow(slavePtr->tkwin); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * SlaveStructureProc -- + * + * This procedure is invoked by the Tk event handler when + * StructureNotify events occur for a slave window. + * + * Results: + * None. + * + * Side effects: + * Structures get cleaned up if the window was deleted. + * + *---------------------------------------------------------------------- + */ + +static void +SlaveStructureProc(clientData, eventPtr) + ClientData clientData; /* Pointer to Slave structure for window + * referred to by eventPtr. */ + XEvent *eventPtr; /* Describes what just happened. */ +{ + register Slave *slavePtr = (Slave *) clientData; + + if (eventPtr->type == DestroyNotify) { + UnlinkSlave(slavePtr); + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&slaveTable, + (char *) slavePtr->tkwin)); + ckfree((char *) slavePtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * PlaceRequestProc -- + * + * This procedure is invoked by Tk whenever a slave managed by us + * changes its requested geometry. + * + * Results: + * None. + * + * Side effects: + * The window will get relayed out, if its requested size has + * anything to do with its actual size. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +PlaceRequestProc(clientData, tkwin) + ClientData clientData; /* Pointer to our record for slave. */ + Tk_Window tkwin; /* Window that changed its desired + * size. */ +{ + Slave *slavePtr = (Slave *) clientData; + Master *masterPtr; + + if (((slavePtr->flags & (CHILD_WIDTH|CHILD_REL_WIDTH)) != 0) + && ((slavePtr->flags & (CHILD_HEIGHT|CHILD_REL_HEIGHT)) != 0)) { + return; + } + masterPtr = slavePtr->masterPtr; + if (masterPtr == NULL) { + return; + } + if (!(masterPtr->flags & PARENT_RECONFIG_PENDING)) { + masterPtr->flags |= PARENT_RECONFIG_PENDING; + Tcl_DoWhenIdle(RecomputePlacement, (ClientData) masterPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * PlaceLostSlaveProc -- + * + * This procedure is invoked by Tk whenever some other geometry + * claims control over a slave that used to be managed by us. + * + * Results: + * None. + * + * Side effects: + * Forgets all placer-related information about the slave. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +PlaceLostSlaveProc(clientData, tkwin) + ClientData clientData; /* Slave structure for slave window that + * was stolen away. */ + Tk_Window tkwin; /* Tk's handle for the slave window. */ +{ + register Slave *slavePtr = (Slave *) clientData; + + if (slavePtr->masterPtr->tkwin != Tk_Parent(slavePtr->tkwin)) { + Tk_UnmaintainGeometry(slavePtr->tkwin, slavePtr->masterPtr->tkwin); + } + Tk_UnmapWindow(tkwin); + UnlinkSlave(slavePtr); + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&slaveTable, (char *) tkwin)); + Tk_DeleteEventHandler(tkwin, StructureNotifyMask, SlaveStructureProc, + (ClientData) slavePtr); + ckfree((char *) slavePtr); +} diff --git a/generic/tkPointer.c b/generic/tkPointer.c new file mode 100644 index 0000000..36814bf --- /dev/null +++ b/generic/tkPointer.c @@ -0,0 +1,623 @@ +/* + * tkPointer.c -- + * + * This file contains functions for emulating the X server + * pointer and grab state machine. This file is used by the + * Mac and Windows platforms to generate appropriate enter/leave + * events, and to update the global grab window information. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkPointer.c 1.12 97/10/31 17:06:24 + */ + +#include "tkInt.h" + +#ifdef MAC_TCL +#define Cursor XCursor +#endif + +/* + * Mask that selects any of the state bits corresponding to buttons, + * plus masks that select individual buttons' bits: + */ + +#define ALL_BUTTONS \ + (Button1Mask|Button2Mask|Button3Mask|Button4Mask|Button5Mask) +static unsigned int buttonMasks[] = { + Button1Mask, Button2Mask, Button3Mask, Button4Mask, Button5Mask +}; +#define ButtonMask(b) (buttonMasks[(b)-Button1]) + +/* + * Declarations of static variables used in the pointer module. + */ + +static TkWindow *cursorWinPtr = NULL; /* Window that is currently + * controlling the global cursor. */ +static TkWindow *grabWinPtr = NULL; /* Window that defines the top of the + * grab tree in a global grab. */ +static XPoint lastPos = { 0, 0}; /* Last reported mouse position. */ +static int lastState = 0; /* Last known state flags. */ +static TkWindow *lastWinPtr = NULL; /* Last reported mouse window. */ +static TkWindow *restrictWinPtr = NULL; /* Window to which all mouse events + * will be reported. */ + +/* + * Forward declarations of procedures used in this file. + */ + +static int GenerateEnterLeave _ANSI_ARGS_((TkWindow *winPtr, + int x, int y, int state)); +static void InitializeEvent _ANSI_ARGS_((XEvent* eventPtr, + TkWindow *winPtr, int type, int x, int y, + int state, int detail)); +static void UpdateCursor _ANSI_ARGS_((TkWindow *winPtr)); + +/* + *---------------------------------------------------------------------- + * + * InitializeEvent -- + * + * Initializes the common fields for several X events. + * + * Results: + * None. + * + * Side effects: + * Fills in the specified event structure. + * + *---------------------------------------------------------------------- + */ + +static void +InitializeEvent(eventPtr, winPtr, type, x, y, state, detail) + XEvent* eventPtr; /* Event structure to initialize. */ + TkWindow *winPtr; /* Window to make event relative to. */ + int type; /* Message type. */ + int x, y; /* Root coords of event. */ + int state; /* State flags. */ + int detail; /* Detail value. */ +{ + eventPtr->type = type; + eventPtr->xany.serial = LastKnownRequestProcessed(winPtr->display); + eventPtr->xany.send_event = False; + eventPtr->xany.display = winPtr->display; + + eventPtr->xcrossing.root = RootWindow(winPtr->display, winPtr->screenNum); + eventPtr->xcrossing.time = TkpGetMS(); + eventPtr->xcrossing.x_root = x; + eventPtr->xcrossing.y_root = y; + + switch (type) { + case EnterNotify: + case LeaveNotify: + eventPtr->xcrossing.mode = NotifyNormal; + eventPtr->xcrossing.state = state; + eventPtr->xcrossing.detail = detail; + eventPtr->xcrossing.focus = False; + break; + case MotionNotify: + eventPtr->xmotion.state = state; + eventPtr->xmotion.is_hint = detail; + break; + case ButtonPress: + case ButtonRelease: + eventPtr->xbutton.state = state; + eventPtr->xbutton.button = detail; + break; + } + TkChangeEventWindow(eventPtr, winPtr); +} + +/* + *---------------------------------------------------------------------- + * + * GenerateEnterLeave -- + * + * Update the current mouse window and position, and generate + * any enter/leave events that are needed. + * + * Results: + * Returns 1 if enter/leave events were generated. + * + * Side effects: + * May insert events into the Tk event queue. + * + *---------------------------------------------------------------------- + */ + +static int +GenerateEnterLeave(winPtr, x, y, state) + TkWindow *winPtr; /* Current Tk window (or NULL). */ + int x,y; /* Current mouse position in root coords. */ + int state; /* State flags. */ +{ + int crossed = 0; /* 1 if mouse crossed a window boundary */ + + if (winPtr != lastWinPtr) { + if (restrictWinPtr) { + int newPos, oldPos; + + newPos = TkPositionInTree(winPtr, restrictWinPtr); + oldPos = TkPositionInTree(lastWinPtr, restrictWinPtr); + + /* + * Check if the mouse crossed into or out of the restrict + * window. If so, we need to generate an Enter or Leave event. + */ + + if ((newPos != oldPos) && ((newPos == TK_GRAB_IN_TREE) + || (oldPos == TK_GRAB_IN_TREE))) { + XEvent event; + int type, detail; + + if (newPos == TK_GRAB_IN_TREE) { + type = EnterNotify; + } else { + type = LeaveNotify; + } + if ((oldPos == TK_GRAB_ANCESTOR) + || (newPos == TK_GRAB_ANCESTOR)) { + detail = NotifyAncestor; + } else { + detail = NotifyVirtual; + } + InitializeEvent(&event, restrictWinPtr, type, x, y, + state, detail); + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + } + + } else { + TkWindow *targetPtr; + + if ((lastWinPtr == NULL) + || (lastWinPtr->window == None)) { + targetPtr = winPtr; + } else { + targetPtr = lastWinPtr; + } + + if (targetPtr && (targetPtr->window != None)) { + XEvent event; + + /* + * Generate appropriate Enter/Leave events. + */ + + InitializeEvent(&event, targetPtr, LeaveNotify, x, y, state, + NotifyNormal); + + TkInOutEvents(&event, lastWinPtr, winPtr, LeaveNotify, + EnterNotify, TCL_QUEUE_TAIL); + crossed = 1; + } + } + lastWinPtr = winPtr; + } + + return crossed; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_UpdatePointer -- + * + * This function updates the pointer state machine given an + * the current window, position and modifier state. + * + * Results: + * None. + * + * Side effects: + * May queue new events and update the grab state. + * + *---------------------------------------------------------------------- + */ + +void +Tk_UpdatePointer(tkwin, x, y, state) + Tk_Window tkwin; /* Window to which pointer event + * is reported. May be NULL. */ + int x, y; /* Pointer location in root coords. */ + int state; /* Modifier state mask. */ +{ + TkWindow *winPtr = (TkWindow *)tkwin; + TkWindow *targetWinPtr; + XPoint pos; + XEvent event; + int changes = (state ^ lastState) & ALL_BUTTONS; + int type, b, mask; + + pos.x = x; + pos.y = y; + + /* + * Use the current keyboard state, but the old mouse button + * state since we haven't generated the button events yet. + */ + + lastState = (state & ~ALL_BUTTONS) | (lastState & ALL_BUTTONS); + + /* + * Generate Enter/Leave events. If the pointer has crossed window + * boundaries, update the current mouse position so we don't generate + * redundant motion events. + */ + + if (GenerateEnterLeave(winPtr, x, y, lastState)) { + lastPos = pos; + } + + /* + * Generate ButtonPress/ButtonRelease events based on the differences + * between the current button state and the last known button state. + */ + + for (b = Button1; b <= Button3; b++) { + mask = ButtonMask(b); + if (changes & mask) { + if (state & mask) { + type = ButtonPress; + + /* + * ButtonPress - Set restrict window if we aren't grabbed, or + * if this is the first button down. + */ + + if (!restrictWinPtr) { + if (!grabWinPtr) { + + /* + * Mouse is not grabbed, so set a button grab. + */ + + restrictWinPtr = winPtr; + TkpSetCapture(restrictWinPtr); + + } else if ((lastState & ALL_BUTTONS) == 0) { + + /* + * Mouse is in a non-button grab, so ensure + * the button grab is inside the grab tree. + */ + + if (TkPositionInTree(winPtr, grabWinPtr) + == TK_GRAB_IN_TREE) { + restrictWinPtr = winPtr; + } else { + restrictWinPtr = grabWinPtr; + } + TkpSetCapture(restrictWinPtr); + } + } + + } else { + type = ButtonRelease; + + /* + * ButtonRelease - Release the mouse capture and clear the + * restrict window when the last button is released and we + * aren't in a global grab. + */ + + if ((lastState & ALL_BUTTONS) == mask) { + if (!grabWinPtr) { + TkpSetCapture(NULL); + } + } + + /* + * If we are releasing a restrict window, then we need + * to send the button event followed by mouse motion from + * the restrict window to the current mouse position. + */ + + if (restrictWinPtr) { + InitializeEvent(&event, restrictWinPtr, type, x, y, + lastState, b); + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + lastState &= ~mask; + lastWinPtr = restrictWinPtr; + restrictWinPtr = NULL; + + GenerateEnterLeave(winPtr, x, y, lastState); + lastPos = pos; + continue; + } + } + + /* + * If a restrict window is set, make sure the pointer event + * is reported relative to that window. Otherwise, if a + * global grab is in effect then events outside of windows + * managed by Tk should be reported to the grab window. + */ + + if (restrictWinPtr) { + targetWinPtr = restrictWinPtr; + } else if (grabWinPtr && !winPtr) { + targetWinPtr = grabWinPtr; + } else { + targetWinPtr = winPtr; + } + + /* + * If we still have a target window, send the event. + */ + + if (winPtr != NULL) { + InitializeEvent(&event, targetWinPtr, type, x, y, + lastState, b); + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + } + + /* + * Update the state for the next iteration. + */ + + lastState = (type == ButtonPress) + ? (lastState | mask) : (lastState & ~mask); + lastPos = pos; + } + } + + /* + * Make sure the cursor window is up to date. + */ + + if (restrictWinPtr) { + targetWinPtr = restrictWinPtr; + } else if (grabWinPtr) { + targetWinPtr = (TkPositionInTree(winPtr, grabWinPtr) + == TK_GRAB_IN_TREE) ? winPtr : grabWinPtr; + } else { + targetWinPtr = winPtr; + } + UpdateCursor(targetWinPtr); + + /* + * If no other events caused the position to be updated, + * generate a motion event. + */ + + if (lastPos.x != pos.x || lastPos.y != pos.y) { + if (restrictWinPtr) { + targetWinPtr = restrictWinPtr; + } else if (grabWinPtr && !winPtr) { + targetWinPtr = grabWinPtr; + } + + if (targetWinPtr != NULL) { + InitializeEvent(&event, targetWinPtr, MotionNotify, x, y, + lastState, NotifyNormal); + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + } + lastPos = pos; + } +} + +/* + *---------------------------------------------------------------------- + * + * XGrabPointer -- + * + * Capture the mouse so event are reported outside of toplevels. + * Note that this is a very limited implementation that only + * supports GrabModeAsync and owner_events True. + * + * Results: + * Always returns GrabSuccess. + * + * Side effects: + * Turns on mouse capture, sets the global grab pointer, and + * clears any window restrictions. + * + *---------------------------------------------------------------------- + */ + +int +XGrabPointer(display, grab_window, owner_events, event_mask, pointer_mode, + keyboard_mode, confine_to, cursor, time) + Display* display; + Window grab_window; + Bool owner_events; + unsigned int event_mask; + int pointer_mode; + int keyboard_mode; + Window confine_to; + Cursor cursor; + Time time; +{ + display->request++; + grabWinPtr = (TkWindow *) Tk_IdToWindow(display, grab_window); + restrictWinPtr = NULL; + TkpSetCapture(grabWinPtr); + if (TkPositionInTree(lastWinPtr, grabWinPtr) != TK_GRAB_IN_TREE) { + UpdateCursor(grabWinPtr); + } + return GrabSuccess; +} + +/* + *---------------------------------------------------------------------- + * + * XUngrabPointer -- + * + * Release the current grab. + * + * Results: + * None. + * + * Side effects: + * Releases the mouse capture. + * + *---------------------------------------------------------------------- + */ + +void +XUngrabPointer(display, time) + Display* display; + Time time; +{ + display->request++; + grabWinPtr = NULL; + restrictWinPtr = NULL; + TkpSetCapture(NULL); + UpdateCursor(lastWinPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TkPointerDeadWindow -- + * + * Clean up pointer module state when a window is destroyed. + * + * Results: + * None. + * + * Side effects: + * May release the current capture window. + * + *---------------------------------------------------------------------- + */ + +void +TkPointerDeadWindow(winPtr) + TkWindow *winPtr; +{ + if (winPtr == lastWinPtr) { + lastWinPtr = NULL; + } + if (winPtr == grabWinPtr) { + grabWinPtr = NULL; + } + if (winPtr == restrictWinPtr) { + restrictWinPtr = NULL; + } + if (!(restrictWinPtr || grabWinPtr)) { + TkpSetCapture(NULL); + } +} + +/* + *---------------------------------------------------------------------- + * + * UpdateCursor -- + * + * Set the windows global cursor to the cursor associated with + * the given Tk window. + * + * Results: + * None. + * + * Side effects: + * Changes the mouse cursor. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateCursor(winPtr) + TkWindow *winPtr; +{ + Cursor cursor = None; + + /* + * A window inherits its cursor from its parent if it doesn't + * have one of its own. Top level windows inherit the default + * cursor. + */ + + cursorWinPtr = winPtr; + while (winPtr != NULL) { + if (winPtr->atts.cursor != None) { + cursor = winPtr->atts.cursor; + break; + } else if (winPtr->flags & TK_TOP_LEVEL) { + break; + } + winPtr = winPtr->parentPtr; + } + TkpSetCursor((TkpCursor) cursor); +} + +/* + *---------------------------------------------------------------------- + * + * XDefineCursor -- + * + * This function is called to update the cursor on a window. + * Since the mouse might be in the specified window, we need to + * check the specified window against the current mouse position + * and grab state. + * + * Results: + * None. + * + * Side effects: + * May update the cursor. + * + *---------------------------------------------------------------------- + */ + +void +XDefineCursor(display, w, cursor) + Display* display; + Window w; + Cursor cursor; +{ + TkWindow *winPtr = (TkWindow *)Tk_IdToWindow(display, w); + + if (cursorWinPtr == winPtr) { + UpdateCursor(winPtr); + } + display->request++; +} + +/* + *---------------------------------------------------------------------- + * + * TkGenerateActivateEvents -- + * + * This function is called by the Mac and Windows window manager + * routines when a toplevel window is activated or deactivated. + * Activate/Deactivate events will be sent to every subwindow of + * the toplevel followed by a FocusIn/FocusOut message. + * + * Results: + * None. + * + * Side effects: + * Generates X events. + * + *---------------------------------------------------------------------- + */ + +void +TkGenerateActivateEvents(winPtr, active) + TkWindow *winPtr; /* Toplevel to activate. */ + int active; /* Non-zero if the window is being + * activated, else 0.*/ +{ + XEvent event; + + /* + * Generate Activate and Deactivate events. This event + * is sent to every subwindow in a toplevel window. + */ + + event.xany.serial = winPtr->display->request++; + event.xany.send_event = False; + event.xany.display = winPtr->display; + event.xany.window = winPtr->window; + + event.xany.type = active ? ActivateNotify : DeactivateNotify; + TkQueueEventForAllChildren(winPtr, &event); + +} diff --git a/generic/tkPort.h b/generic/tkPort.h new file mode 100644 index 0000000..7051aa0 --- /dev/null +++ b/generic/tkPort.h @@ -0,0 +1,36 @@ +/* + * tkPort.h -- + * + * This header file handles porting issues that occur because of + * differences between systems. It reads in platform specific + * portability files. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkPort.h 1.7 96/02/11 16:42:10 + */ + +#ifndef _TKPORT +#define _TKPORT + +#ifndef _TK +#include "tk.h" +#endif +#ifndef _TCL +#include "tcl.h" +#endif + +#if defined(__WIN32__) || defined(_WIN32) +# include "tkWinPort.h" +#else +# if defined(MAC_TCL) +# include "tkMacPort.h" +# else +# include "../unix/tkUnixPort.h" +# endif +#endif + +#endif /* _TKPORT */ diff --git a/generic/tkRectOval.c b/generic/tkRectOval.c new file mode 100644 index 0000000..d1ba71c --- /dev/null +++ b/generic/tkRectOval.c @@ -0,0 +1,1030 @@ +/* + * tkRectOval.c -- + * + * This file implements rectangle and oval items for canvas + * widgets. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkRectOval.c 1.40 96/05/03 10:52:21 + */ + +#include <stdio.h> +#include "tk.h" +#include "tkInt.h" +#include "tkPort.h" + +/* + * The structure below defines the record for each rectangle/oval item. + */ + +typedef struct RectOvalItem { + Tk_Item header; /* Generic stuff that's the same for all + * types. MUST BE FIRST IN STRUCTURE. */ + double bbox[4]; /* Coordinates of bounding box for rectangle + * or oval (x1, y1, x2, y2). Item includes + * x1 and x2 but not y1 and y2. */ + int width; /* Width of outline. */ + XColor *outlineColor; /* Color for outline. */ + XColor *fillColor; /* Color for filling rectangle/oval. */ + Pixmap fillStipple; /* Stipple bitmap for filling item. */ + GC outlineGC; /* Graphics context for outline. */ + GC fillGC; /* Graphics context for filling item. */ +} RectOvalItem; + +/* + * Information used for parsing configuration specs: + */ + +static Tk_CustomOption tagsOption = {Tk_CanvasTagsParseProc, + Tk_CanvasTagsPrintProc, (ClientData) NULL +}; + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_COLOR, "-fill", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(RectOvalItem, fillColor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-outline", (char *) NULL, (char *) NULL, + "black", Tk_Offset(RectOvalItem, outlineColor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_BITMAP, "-stipple", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(RectOvalItem, fillStipple), TK_CONFIG_NULL_OK}, + {TK_CONFIG_CUSTOM, "-tags", (char *) NULL, (char *) NULL, + (char *) NULL, 0, TK_CONFIG_NULL_OK, &tagsOption}, + {TK_CONFIG_PIXELS, "-width", (char *) NULL, (char *) NULL, + "1", Tk_Offset(RectOvalItem, width), TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Prototypes for procedures defined in this file: + */ + +static void ComputeRectOvalBbox _ANSI_ARGS_((Tk_Canvas canvas, + RectOvalItem *rectOvalPtr)); +static int ConfigureRectOval _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv, int flags)); +static int CreateRectOval _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, struct Tk_Item *itemPtr, + int argc, char **argv)); +static void DeleteRectOval _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display)); +static void DisplayRectOval _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, Display *display, Drawable dst, + int x, int y, int width, int height)); +static int OvalToArea _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *areaPtr)); +static double OvalToPoint _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *pointPtr)); +static int RectOvalCoords _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int argc, + char **argv)); +static int RectOvalToPostscript _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Canvas canvas, Tk_Item *itemPtr, int prepass)); +static int RectToArea _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *areaPtr)); +static double RectToPoint _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double *pointPtr)); +static void ScaleRectOval _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double originX, double originY, + double scaleX, double scaleY)); +static void TranslateRectOval _ANSI_ARGS_((Tk_Canvas canvas, + Tk_Item *itemPtr, double deltaX, double deltaY)); + +/* + * The structures below defines the rectangle and oval item types + * by means of procedures that can be invoked by generic item code. + */ + +Tk_ItemType tkRectangleType = { + "rectangle", /* name */ + sizeof(RectOvalItem), /* itemSize */ + CreateRectOval, /* createProc */ + configSpecs, /* configSpecs */ + ConfigureRectOval, /* configureProc */ + RectOvalCoords, /* coordProc */ + DeleteRectOval, /* deleteProc */ + DisplayRectOval, /* displayProc */ + 0, /* alwaysRedraw */ + RectToPoint, /* pointProc */ + RectToArea, /* areaProc */ + RectOvalToPostscript, /* postscriptProc */ + ScaleRectOval, /* scaleProc */ + TranslateRectOval, /* translateProc */ + (Tk_ItemIndexProc *) NULL, /* indexProc */ + (Tk_ItemCursorProc *) NULL, /* icursorProc */ + (Tk_ItemSelectionProc *) NULL, /* selectionProc */ + (Tk_ItemInsertProc *) NULL, /* insertProc */ + (Tk_ItemDCharsProc *) NULL, /* dTextProc */ + (Tk_ItemType *) NULL /* nextPtr */ +}; + +Tk_ItemType tkOvalType = { + "oval", /* name */ + sizeof(RectOvalItem), /* itemSize */ + CreateRectOval, /* createProc */ + configSpecs, /* configSpecs */ + ConfigureRectOval, /* configureProc */ + RectOvalCoords, /* coordProc */ + DeleteRectOval, /* deleteProc */ + DisplayRectOval, /* displayProc */ + 0, /* alwaysRedraw */ + OvalToPoint, /* pointProc */ + OvalToArea, /* areaProc */ + RectOvalToPostscript, /* postscriptProc */ + ScaleRectOval, /* scaleProc */ + TranslateRectOval, /* translateProc */ + (Tk_ItemIndexProc *) NULL, /* indexProc */ + (Tk_ItemCursorProc *) NULL, /* cursorProc */ + (Tk_ItemSelectionProc *) NULL, /* selectionProc */ + (Tk_ItemInsertProc *) NULL, /* insertProc */ + (Tk_ItemDCharsProc *) NULL, /* dTextProc */ + (Tk_ItemType *) NULL /* nextPtr */ +}; + +/* + *-------------------------------------------------------------- + * + * CreateRectOval -- + * + * This procedure is invoked to create a new rectangle + * or oval item in a canvas. + * + * Results: + * A standard Tcl return value. If an error occurred in + * creating the item, then an error message is left in + * interp->result; in this case itemPtr is left uninitialized, + * so it can be safely freed by the caller. + * + * Side effects: + * A new rectangle or oval item is created. + * + *-------------------------------------------------------------- + */ + +static int +CreateRectOval(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* For error reporting. */ + Tk_Canvas canvas; /* Canvas to hold new item. */ + Tk_Item *itemPtr; /* Record to hold new item; header + * has been initialized by caller. */ + int argc; /* Number of arguments in argv. */ + char **argv; /* Arguments describing rectangle. */ +{ + RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; + + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tk_PathName(Tk_CanvasTkwin(canvas)), " create ", + itemPtr->typePtr->name, " x1 y1 x2 y2 ?options?\"", + (char *) NULL); + return TCL_ERROR; + } + + /* + * Carry out initialization that is needed in order to clean + * up after errors during the the remainder of this procedure. + */ + + rectOvalPtr->width = 1; + rectOvalPtr->outlineColor = NULL; + rectOvalPtr->fillColor = NULL; + rectOvalPtr->fillStipple = None; + rectOvalPtr->outlineGC = None; + rectOvalPtr->fillGC = None; + + /* + * Process the arguments to fill in the item record. + */ + + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], + &rectOvalPtr->bbox[0]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], + &rectOvalPtr->bbox[1]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[2], + &rectOvalPtr->bbox[2]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[3], + &rectOvalPtr->bbox[3]) != TCL_OK)) { + return TCL_ERROR; + } + + if (ConfigureRectOval(interp, canvas, itemPtr, argc-4, argv+4, 0) + != TCL_OK) { + DeleteRectOval(canvas, itemPtr, Tk_Display(Tk_CanvasTkwin(canvas))); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * RectOvalCoords -- + * + * This procedure is invoked to process the "coords" widget + * command on rectangles and ovals. See the user documentation + * for details on what it does. + * + * Results: + * Returns TCL_OK or TCL_ERROR, and sets interp->result. + * + * Side effects: + * The coordinates for the given item may be changed. + * + *-------------------------------------------------------------- + */ + +static int +RectOvalCoords(interp, canvas, itemPtr, argc, argv) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item whose coordinates are to be + * read or modified. */ + int argc; /* Number of coordinates supplied in + * argv. */ + char **argv; /* Array of coordinates: x1, y1, + * x2, y2, ... */ +{ + RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; + char c0[TCL_DOUBLE_SPACE], c1[TCL_DOUBLE_SPACE]; + char c2[TCL_DOUBLE_SPACE], c3[TCL_DOUBLE_SPACE]; + + if (argc == 0) { + Tcl_PrintDouble(interp, rectOvalPtr->bbox[0], c0); + Tcl_PrintDouble(interp, rectOvalPtr->bbox[1], c1); + Tcl_PrintDouble(interp, rectOvalPtr->bbox[2], c2); + Tcl_PrintDouble(interp, rectOvalPtr->bbox[3], c3); + Tcl_AppendResult(interp, c0, " ", c1, " ", c2, " ", c3, + (char *) NULL); + } else if (argc == 4) { + if ((Tk_CanvasGetCoord(interp, canvas, argv[0], + &rectOvalPtr->bbox[0]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[1], + &rectOvalPtr->bbox[1]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[2], + &rectOvalPtr->bbox[2]) != TCL_OK) + || (Tk_CanvasGetCoord(interp, canvas, argv[3], + &rectOvalPtr->bbox[3]) != TCL_OK)) { + return TCL_ERROR; + } + ComputeRectOvalBbox(canvas, rectOvalPtr); + } else { + sprintf(interp->result, + "wrong # coordinates: expected 0 or 4, got %d", + argc); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ConfigureRectOval -- + * + * This procedure is invoked to configure various aspects + * of a rectangle or oval item, such as its border and + * background colors. + * + * Results: + * A standard Tcl result code. If an error occurs, then + * an error message is left in interp->result. + * + * Side effects: + * Configuration information, such as colors and stipple + * patterns, may be set for itemPtr. + * + *-------------------------------------------------------------- + */ + +static int +ConfigureRectOval(interp, canvas, itemPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Canvas canvas; /* Canvas containing itemPtr. */ + Tk_Item *itemPtr; /* Rectangle item to reconfigure. */ + int argc; /* Number of elements in argv. */ + char **argv; /* Arguments describing things to configure. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; + XGCValues gcValues; + GC newGC; + unsigned long mask; + Tk_Window tkwin; + + tkwin = Tk_CanvasTkwin(canvas); + if (Tk_ConfigureWidget(interp, tkwin, configSpecs, argc, argv, + (char *) rectOvalPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few of the options require additional processing, such as + * graphics contexts. + */ + + if (rectOvalPtr->width < 1) { + rectOvalPtr->width = 1; + } + if (rectOvalPtr->outlineColor == NULL) { + newGC = None; + } else { + gcValues.foreground = rectOvalPtr->outlineColor->pixel; + gcValues.cap_style = CapProjecting; + gcValues.line_width = rectOvalPtr->width; + mask = GCForeground|GCCapStyle|GCLineWidth; + newGC = Tk_GetGC(tkwin, mask, &gcValues); + } + if (rectOvalPtr->outlineGC != None) { + Tk_FreeGC(Tk_Display(tkwin), rectOvalPtr->outlineGC); + } + rectOvalPtr->outlineGC = newGC; + + if (rectOvalPtr->fillColor == NULL) { + newGC = None; + } else { + gcValues.foreground = rectOvalPtr->fillColor->pixel; + if (rectOvalPtr->fillStipple != None) { + gcValues.stipple = rectOvalPtr->fillStipple; + gcValues.fill_style = FillStippled; + mask = GCForeground|GCStipple|GCFillStyle; + } else { + mask = GCForeground; + } + newGC = Tk_GetGC(tkwin, mask, &gcValues); + } + if (rectOvalPtr->fillGC != None) { + Tk_FreeGC(Tk_Display(tkwin), rectOvalPtr->fillGC); + } + rectOvalPtr->fillGC = newGC; + ComputeRectOvalBbox(canvas, rectOvalPtr); + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * DeleteRectOval -- + * + * This procedure is called to clean up the data structure + * associated with a rectangle or oval item. + * + * Results: + * None. + * + * Side effects: + * Resources associated with itemPtr are released. + * + *-------------------------------------------------------------- + */ + +static void +DeleteRectOval(canvas, itemPtr, display) + Tk_Canvas canvas; /* Info about overall widget. */ + Tk_Item *itemPtr; /* Item that is being deleted. */ + Display *display; /* Display containing window for + * canvas. */ +{ + RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; + + if (rectOvalPtr->outlineColor != NULL) { + Tk_FreeColor(rectOvalPtr->outlineColor); + } + if (rectOvalPtr->fillColor != NULL) { + Tk_FreeColor(rectOvalPtr->fillColor); + } + if (rectOvalPtr->fillStipple != None) { + Tk_FreeBitmap(display, rectOvalPtr->fillStipple); + } + if (rectOvalPtr->outlineGC != None) { + Tk_FreeGC(display, rectOvalPtr->outlineGC); + } + if (rectOvalPtr->fillGC != None) { + Tk_FreeGC(display, rectOvalPtr->fillGC); + } +} + +/* + *-------------------------------------------------------------- + * + * ComputeRectOvalBbox -- + * + * This procedure is invoked to compute the bounding box of + * all the pixels that may be drawn as part of a rectangle + * or oval. + * + * Results: + * None. + * + * Side effects: + * The fields x1, y1, x2, and y2 are updated in the header + * for itemPtr. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +ComputeRectOvalBbox(canvas, rectOvalPtr) + Tk_Canvas canvas; /* Canvas that contains item. */ + RectOvalItem *rectOvalPtr; /* Item whose bbox is to be + * recomputed. */ +{ + int bloat, tmp; + double dtmp; + + /* + * Make sure that the first coordinates are the lowest ones. + */ + + if (rectOvalPtr->bbox[1] > rectOvalPtr->bbox[3]) { + double tmp; + tmp = rectOvalPtr->bbox[3]; + rectOvalPtr->bbox[3] = rectOvalPtr->bbox[1]; + rectOvalPtr->bbox[1] = tmp; + } + if (rectOvalPtr->bbox[0] > rectOvalPtr->bbox[2]) { + double tmp; + tmp = rectOvalPtr->bbox[2]; + rectOvalPtr->bbox[2] = rectOvalPtr->bbox[0]; + rectOvalPtr->bbox[0] = tmp; + } + + if (rectOvalPtr->outlineColor == NULL) { + bloat = 0; + } else { + bloat = (rectOvalPtr->width+1)/2; + } + + /* + * Special note: the rectangle is always drawn at least 1x1 in + * size, so round up the upper coordinates to be at least 1 unit + * greater than the lower ones. + */ + + tmp = (int) ((rectOvalPtr->bbox[0] >= 0) ? rectOvalPtr->bbox[0] + .5 + : rectOvalPtr->bbox[0] - .5); + rectOvalPtr->header.x1 = tmp - bloat; + tmp = (int) ((rectOvalPtr->bbox[1] >= 0) ? rectOvalPtr->bbox[1] + .5 + : rectOvalPtr->bbox[1] - .5); + rectOvalPtr->header.y1 = tmp - bloat; + dtmp = rectOvalPtr->bbox[2]; + if (dtmp < (rectOvalPtr->bbox[0] + 1)) { + dtmp = rectOvalPtr->bbox[0] + 1; + } + tmp = (int) ((dtmp >= 0) ? dtmp + .5 : dtmp - .5); + rectOvalPtr->header.x2 = tmp + bloat; + dtmp = rectOvalPtr->bbox[3]; + if (dtmp < (rectOvalPtr->bbox[1] + 1)) { + dtmp = rectOvalPtr->bbox[1] + 1; + } + tmp = (int) ((dtmp >= 0) ? dtmp + .5 : dtmp - .5); + rectOvalPtr->header.y2 = tmp + bloat; +} + +/* + *-------------------------------------------------------------- + * + * DisplayRectOval -- + * + * This procedure is invoked to draw a rectangle or oval + * item in a given drawable. + * + * Results: + * None. + * + * Side effects: + * ItemPtr is drawn in drawable using the transformation + * information in canvas. + * + *-------------------------------------------------------------- + */ + +static void +DisplayRectOval(canvas, itemPtr, display, drawable, x, y, width, height) + Tk_Canvas canvas; /* Canvas that contains item. */ + Tk_Item *itemPtr; /* Item to be displayed. */ + Display *display; /* Display on which to draw item. */ + Drawable drawable; /* Pixmap or window in which to draw + * item. */ + int x, y, width, height; /* Describes region of canvas that + * must be redisplayed (not used). */ +{ + RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; + short x1, y1, x2, y2; + + /* + * Compute the screen coordinates of the bounding box for the item. + * Make sure that the bbox is at least one pixel large, since some + * X servers will die if it isn't. + */ + + Tk_CanvasDrawableCoords(canvas, rectOvalPtr->bbox[0], rectOvalPtr->bbox[1], + &x1, &y1); + Tk_CanvasDrawableCoords(canvas, rectOvalPtr->bbox[2], rectOvalPtr->bbox[3], + &x2, &y2); + if (x2 <= x1) { + x2 = x1+1; + } + if (y2 <= y1) { + y2 = y1+1; + } + + /* + * Display filled part first (if wanted), then outline. If we're + * stippling, then modify the stipple offset in the GC. Be sure to + * reset the offset when done, since the GC is supposed to be + * read-only. + */ + + if (rectOvalPtr->fillGC != None) { + if (rectOvalPtr->fillStipple != None) { + Tk_CanvasSetStippleOrigin(canvas, rectOvalPtr->fillGC); + } + if (rectOvalPtr->header.typePtr == &tkRectangleType) { + XFillRectangle(display, drawable, rectOvalPtr->fillGC, + x1, y1, (unsigned int) (x2-x1), (unsigned int) (y2-y1)); + } else { + XFillArc(display, drawable, rectOvalPtr->fillGC, + x1, y1, (unsigned) (x2-x1), (unsigned) (y2-y1), + 0, 360*64); + } + if (rectOvalPtr->fillStipple != None) { + XSetTSOrigin(display, rectOvalPtr->fillGC, 0, 0); + } + } + if (rectOvalPtr->outlineGC != None) { + if (rectOvalPtr->header.typePtr == &tkRectangleType) { + XDrawRectangle(display, drawable, rectOvalPtr->outlineGC, + x1, y1, (unsigned) (x2-x1), (unsigned) (y2-y1)); + } else { + XDrawArc(display, drawable, rectOvalPtr->outlineGC, + x1, y1, (unsigned) (x2-x1), (unsigned) (y2-y1), 0, 360*64); + } + } +} + +/* + *-------------------------------------------------------------- + * + * RectToPoint -- + * + * Computes the distance from a given point to a given + * rectangle, in canvas units. + * + * Results: + * The return value is 0 if the point whose x and y coordinates + * are coordPtr[0] and coordPtr[1] is inside the rectangle. If the + * point isn't inside the rectangle then the return value is the + * distance from the point to the rectangle. If itemPtr is filled, + * then anywhere in the interior is considered "inside"; if + * itemPtr isn't filled, then "inside" means only the area + * occupied by the outline. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static double +RectToPoint(canvas, itemPtr, pointPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against point. */ + double *pointPtr; /* Pointer to x and y coordinates. */ +{ + RectOvalItem *rectPtr = (RectOvalItem *) itemPtr; + double xDiff, yDiff, x1, y1, x2, y2, inc, tmp; + + /* + * Generate a new larger rectangle that includes the border + * width, if there is one. + */ + + x1 = rectPtr->bbox[0]; + y1 = rectPtr->bbox[1]; + x2 = rectPtr->bbox[2]; + y2 = rectPtr->bbox[3]; + if (rectPtr->outlineGC != None) { + inc = rectPtr->width/2.0; + x1 -= inc; + y1 -= inc; + x2 += inc; + y2 += inc; + } + + /* + * If the point is inside the rectangle, handle specially: + * distance is 0 if rectangle is filled, otherwise compute + * distance to nearest edge of rectangle and subtract width + * of edge. + */ + + if ((pointPtr[0] >= x1) && (pointPtr[0] < x2) + && (pointPtr[1] >= y1) && (pointPtr[1] < y2)) { + if ((rectPtr->fillGC != None) || (rectPtr->outlineGC == None)) { + return 0.0; + } + xDiff = pointPtr[0] - x1; + tmp = x2 - pointPtr[0]; + if (tmp < xDiff) { + xDiff = tmp; + } + yDiff = pointPtr[1] - y1; + tmp = y2 - pointPtr[1]; + if (tmp < yDiff) { + yDiff = tmp; + } + if (yDiff < xDiff) { + xDiff = yDiff; + } + xDiff -= rectPtr->width; + if (xDiff < 0.0) { + return 0.0; + } + return xDiff; + } + + /* + * Point is outside rectangle. + */ + + if (pointPtr[0] < x1) { + xDiff = x1 - pointPtr[0]; + } else if (pointPtr[0] > x2) { + xDiff = pointPtr[0] - x2; + } else { + xDiff = 0; + } + + if (pointPtr[1] < y1) { + yDiff = y1 - pointPtr[1]; + } else if (pointPtr[1] > y2) { + yDiff = pointPtr[1] - y2; + } else { + yDiff = 0; + } + + return hypot(xDiff, yDiff); +} + +/* + *-------------------------------------------------------------- + * + * OvalToPoint -- + * + * Computes the distance from a given point to a given + * oval, in canvas units. + * + * Results: + * The return value is 0 if the point whose x and y coordinates + * are coordPtr[0] and coordPtr[1] is inside the oval. If the + * point isn't inside the oval then the return value is the + * distance from the point to the oval. If itemPtr is filled, + * then anywhere in the interior is considered "inside"; if + * itemPtr isn't filled, then "inside" means only the area + * occupied by the outline. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static double +OvalToPoint(canvas, itemPtr, pointPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against point. */ + double *pointPtr; /* Pointer to x and y coordinates. */ +{ + RectOvalItem *ovalPtr = (RectOvalItem *) itemPtr; + double width; + int filled; + + width = ovalPtr->width; + filled = ovalPtr->fillGC != None; + if (ovalPtr->outlineGC == None) { + width = 0.0; + filled = 1; + } + return TkOvalToPoint(ovalPtr->bbox, width, filled, pointPtr); +} + +/* + *-------------------------------------------------------------- + * + * RectToArea -- + * + * This procedure is called to determine whether an item + * lies entirely inside, entirely outside, or overlapping + * a given rectangle. + * + * Results: + * -1 is returned if the item is entirely outside the area + * given by rectPtr, 0 if it overlaps, and 1 if it is entirely + * inside the given area. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +RectToArea(canvas, itemPtr, areaPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against rectangle. */ + double *areaPtr; /* Pointer to array of four coordinates + * (x1, y1, x2, y2) describing rectangular + * area. */ +{ + RectOvalItem *rectPtr = (RectOvalItem *) itemPtr; + double halfWidth; + + halfWidth = rectPtr->width/2.0; + if (rectPtr->outlineGC == None) { + halfWidth = 0.0; + } + + if ((areaPtr[2] <= (rectPtr->bbox[0] - halfWidth)) + || (areaPtr[0] >= (rectPtr->bbox[2] + halfWidth)) + || (areaPtr[3] <= (rectPtr->bbox[1] - halfWidth)) + || (areaPtr[1] >= (rectPtr->bbox[3] + halfWidth))) { + return -1; + } + if ((rectPtr->fillGC == None) && (rectPtr->outlineGC != None) + && (areaPtr[0] >= (rectPtr->bbox[0] + halfWidth)) + && (areaPtr[1] >= (rectPtr->bbox[1] + halfWidth)) + && (areaPtr[2] <= (rectPtr->bbox[2] - halfWidth)) + && (areaPtr[3] <= (rectPtr->bbox[3] - halfWidth))) { + return -1; + } + if ((areaPtr[0] <= (rectPtr->bbox[0] - halfWidth)) + && (areaPtr[1] <= (rectPtr->bbox[1] - halfWidth)) + && (areaPtr[2] >= (rectPtr->bbox[2] + halfWidth)) + && (areaPtr[3] >= (rectPtr->bbox[3] + halfWidth))) { + return 1; + } + return 0; +} + +/* + *-------------------------------------------------------------- + * + * OvalToArea -- + * + * This procedure is called to determine whether an item + * lies entirely inside, entirely outside, or overlapping + * a given rectangular area. + * + * Results: + * -1 is returned if the item is entirely outside the area + * given by rectPtr, 0 if it overlaps, and 1 if it is entirely + * inside the given area. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +OvalToArea(canvas, itemPtr, areaPtr) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item to check against oval. */ + double *areaPtr; /* Pointer to array of four coordinates + * (x1, y1, x2, y2) describing rectangular + * area. */ +{ + RectOvalItem *ovalPtr = (RectOvalItem *) itemPtr; + double oval[4], halfWidth; + int result; + + /* + * Expand the oval to include the width of the outline, if any. + */ + + halfWidth = ovalPtr->width/2.0; + if (ovalPtr->outlineGC == None) { + halfWidth = 0.0; + } + oval[0] = ovalPtr->bbox[0] - halfWidth; + oval[1] = ovalPtr->bbox[1] - halfWidth; + oval[2] = ovalPtr->bbox[2] + halfWidth; + oval[3] = ovalPtr->bbox[3] + halfWidth; + + result = TkOvalToArea(oval, areaPtr); + + /* + * If the rectangle appears to overlap the oval and the oval + * isn't filled, do one more check to see if perhaps all four + * of the rectangle's corners are totally inside the oval's + * unfilled center, in which case we should return "outside". + */ + + if ((result == 0) && (ovalPtr->outlineGC != None) + && (ovalPtr->fillGC == None)) { + double centerX, centerY, width, height; + double xDelta1, yDelta1, xDelta2, yDelta2; + + centerX = (ovalPtr->bbox[0] + ovalPtr->bbox[2])/2.0; + centerY = (ovalPtr->bbox[1] + ovalPtr->bbox[3])/2.0; + width = (ovalPtr->bbox[2] - ovalPtr->bbox[0])/2.0 - halfWidth; + height = (ovalPtr->bbox[3] - ovalPtr->bbox[1])/2.0 - halfWidth; + xDelta1 = (areaPtr[0] - centerX)/width; + xDelta1 *= xDelta1; + yDelta1 = (areaPtr[1] - centerY)/height; + yDelta1 *= yDelta1; + xDelta2 = (areaPtr[2] - centerX)/width; + xDelta2 *= xDelta2; + yDelta2 = (areaPtr[3] - centerY)/height; + yDelta2 *= yDelta2; + if (((xDelta1 + yDelta1) < 1.0) + && ((xDelta1 + yDelta2) < 1.0) + && ((xDelta2 + yDelta1) < 1.0) + && ((xDelta2 + yDelta2) < 1.0)) { + return -1; + } + } + return result; +} + +/* + *-------------------------------------------------------------- + * + * ScaleRectOval -- + * + * This procedure is invoked to rescale a rectangle or oval + * item. + * + * Results: + * None. + * + * Side effects: + * The rectangle or oval referred to by itemPtr is rescaled + * so that the following transformation is applied to all + * point coordinates: + * x' = originX + scaleX*(x-originX) + * y' = originY + scaleY*(y-originY) + * + *-------------------------------------------------------------- + */ + +static void +ScaleRectOval(canvas, itemPtr, originX, originY, scaleX, scaleY) + Tk_Canvas canvas; /* Canvas containing rectangle. */ + Tk_Item *itemPtr; /* Rectangle to be scaled. */ + double originX, originY; /* Origin about which to scale rect. */ + double scaleX; /* Amount to scale in X direction. */ + double scaleY; /* Amount to scale in Y direction. */ +{ + RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; + + rectOvalPtr->bbox[0] = originX + scaleX*(rectOvalPtr->bbox[0] - originX); + rectOvalPtr->bbox[1] = originY + scaleY*(rectOvalPtr->bbox[1] - originY); + rectOvalPtr->bbox[2] = originX + scaleX*(rectOvalPtr->bbox[2] - originX); + rectOvalPtr->bbox[3] = originY + scaleY*(rectOvalPtr->bbox[3] - originY); + ComputeRectOvalBbox(canvas, rectOvalPtr); +} + +/* + *-------------------------------------------------------------- + * + * TranslateRectOval -- + * + * This procedure is called to move a rectangle or oval by a + * given amount. + * + * Results: + * None. + * + * Side effects: + * The position of the rectangle or oval is offset by + * (xDelta, yDelta), and the bounding box is updated in the + * generic part of the item structure. + * + *-------------------------------------------------------------- + */ + +static void +TranslateRectOval(canvas, itemPtr, deltaX, deltaY) + Tk_Canvas canvas; /* Canvas containing item. */ + Tk_Item *itemPtr; /* Item that is being moved. */ + double deltaX, deltaY; /* Amount by which item is to be + * moved. */ +{ + RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; + + rectOvalPtr->bbox[0] += deltaX; + rectOvalPtr->bbox[1] += deltaY; + rectOvalPtr->bbox[2] += deltaX; + rectOvalPtr->bbox[3] += deltaY; + ComputeRectOvalBbox(canvas, rectOvalPtr); +} + +/* + *-------------------------------------------------------------- + * + * RectOvalToPostscript -- + * + * This procedure is called to generate Postscript for + * rectangle and oval items. + * + * Results: + * The return value is a standard Tcl result. If an error + * occurs in generating Postscript then an error message is + * left in interp->result, replacing whatever used to be there. + * If no error occurs, then Postscript for the rectangle is + * appended to the result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +RectOvalToPostscript(interp, canvas, itemPtr, prepass) + Tcl_Interp *interp; /* Interpreter for error reporting. */ + Tk_Canvas canvas; /* Information about overall canvas. */ + Tk_Item *itemPtr; /* Item for which Postscript is + * wanted. */ + int prepass; /* 1 means this is a prepass to + * collect font information; 0 means + * final Postscript is being created. */ +{ + char pathCmd[500], string[100]; + RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; + double y1, y2; + + y1 = Tk_CanvasPsY(canvas, rectOvalPtr->bbox[1]); + y2 = Tk_CanvasPsY(canvas, rectOvalPtr->bbox[3]); + + /* + * Generate a string that creates a path for the rectangle or oval. + * This is the only part of the procedure's code that is type- + * specific. + */ + + + if (rectOvalPtr->header.typePtr == &tkRectangleType) { + sprintf(pathCmd, "%.15g %.15g moveto %.15g 0 rlineto 0 %.15g rlineto %.15g 0 rlineto closepath\n", + rectOvalPtr->bbox[0], y1, + rectOvalPtr->bbox[2]-rectOvalPtr->bbox[0], y2-y1, + rectOvalPtr->bbox[0]-rectOvalPtr->bbox[2]); + } else { + sprintf(pathCmd, "matrix currentmatrix\n%.15g %.15g translate %.15g %.15g scale 1 0 moveto 0 0 1 0 360 arc\nsetmatrix\n", + (rectOvalPtr->bbox[0] + rectOvalPtr->bbox[2])/2, (y1 + y2)/2, + (rectOvalPtr->bbox[2] - rectOvalPtr->bbox[0])/2, (y1 - y2)/2); + } + + /* + * First draw the filled area of the rectangle. + */ + + if (rectOvalPtr->fillColor != NULL) { + Tcl_AppendResult(interp, pathCmd, (char *) NULL); + if (Tk_CanvasPsColor(interp, canvas, rectOvalPtr->fillColor) + != TCL_OK) { + return TCL_ERROR; + } + if (rectOvalPtr->fillStipple != None) { + Tcl_AppendResult(interp, "clip ", (char *) NULL); + if (Tk_CanvasPsStipple(interp, canvas, rectOvalPtr->fillStipple) + != TCL_OK) { + return TCL_ERROR; + } + if (rectOvalPtr->outlineColor != NULL) { + Tcl_AppendResult(interp, "grestore gsave\n", (char *) NULL); + } + } else { + Tcl_AppendResult(interp, "fill\n", (char *) NULL); + } + } + + /* + * Now draw the outline, if there is one. + */ + + if (rectOvalPtr->outlineColor != NULL) { + Tcl_AppendResult(interp, pathCmd, (char *) NULL); + sprintf(string, "%d setlinewidth", rectOvalPtr->width); + Tcl_AppendResult(interp, string, + " 0 setlinejoin 2 setlinecap\n", (char *) NULL); + if (Tk_CanvasPsColor(interp, canvas, rectOvalPtr->outlineColor) + != TCL_OK) { + return TCL_ERROR; + } + Tcl_AppendResult(interp, "stroke\n", (char *) NULL); + } + return TCL_OK; +} diff --git a/generic/tkScale.c b/generic/tkScale.c new file mode 100644 index 0000000..6c78150 --- /dev/null +++ b/generic/tkScale.c @@ -0,0 +1,1143 @@ +/* + * tkScale.c -- + * + * This module implements a scale widgets for the Tk toolkit. + * A scale displays a slider that can be adjusted to change a + * value; it also displays numeric labels and a textual label, + * if desired. + * + * The modifications to use floating-point values are based on + * an implementation by Paul Mackerras. The -variable option + * is due to Henning Schulzrinne. All of these are used with + * permission. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkScale.c 1.88 97/07/31 09:11:57 + */ + +#include "tkPort.h" +#include "default.h" +#include "tkInt.h" +#include "tclMath.h" +#include "tkScale.h" + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_BORDER, "-activebackground", "activeBackground", "Foreground", + DEF_SCALE_ACTIVE_BG_COLOR, Tk_Offset(TkScale, activeBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-activebackground", "activeBackground", "Foreground", + DEF_SCALE_ACTIVE_BG_MONO, Tk_Offset(TkScale, activeBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_SCALE_BG_COLOR, Tk_Offset(TkScale, bgBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_SCALE_BG_MONO, Tk_Offset(TkScale, bgBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_DOUBLE, "-bigincrement", "bigIncrement", "BigIncrement", + DEF_SCALE_BIG_INCREMENT, Tk_Offset(TkScale, bigIncrement), 0}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_SCALE_BORDER_WIDTH, Tk_Offset(TkScale, borderWidth), 0}, + {TK_CONFIG_STRING, "-command", "command", "Command", + DEF_SCALE_COMMAND, Tk_Offset(TkScale, command), TK_CONFIG_NULL_OK}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_SCALE_CURSOR, Tk_Offset(TkScale, cursor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_INT, "-digits", "digits", "Digits", + DEF_SCALE_DIGITS, Tk_Offset(TkScale, digits), 0}, + {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_FONT, "-font", "font", "Font", + DEF_SCALE_FONT, Tk_Offset(TkScale, tkfont), + 0}, + {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground", + DEF_SCALE_FG_COLOR, Tk_Offset(TkScale, textColorPtr), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground", + DEF_SCALE_FG_MONO, Tk_Offset(TkScale, textColorPtr), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_DOUBLE, "-from", "from", "From", + DEF_SCALE_FROM, Tk_Offset(TkScale, fromValue), 0}, + {TK_CONFIG_COLOR, "-highlightbackground", "highlightBackground", + "HighlightBackground", DEF_SCALE_HIGHLIGHT_BG, + Tk_Offset(TkScale, highlightBgColorPtr), 0}, + {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor", + DEF_SCALE_HIGHLIGHT, Tk_Offset(TkScale, highlightColorPtr), 0}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", + DEF_SCALE_HIGHLIGHT_WIDTH, Tk_Offset(TkScale, highlightWidth), 0}, + {TK_CONFIG_STRING, "-label", "label", "Label", + DEF_SCALE_LABEL, Tk_Offset(TkScale, label), TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-length", "length", "Length", + DEF_SCALE_LENGTH, Tk_Offset(TkScale, length), 0}, + {TK_CONFIG_UID, "-orient", "orient", "Orient", + DEF_SCALE_ORIENT, Tk_Offset(TkScale, orientUid), 0}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_SCALE_RELIEF, Tk_Offset(TkScale, relief), 0}, + {TK_CONFIG_INT, "-repeatdelay", "repeatDelay", "RepeatDelay", + DEF_SCALE_REPEAT_DELAY, Tk_Offset(TkScale, repeatDelay), 0}, + {TK_CONFIG_INT, "-repeatinterval", "repeatInterval", "RepeatInterval", + DEF_SCALE_REPEAT_INTERVAL, Tk_Offset(TkScale, repeatInterval), 0}, + {TK_CONFIG_DOUBLE, "-resolution", "resolution", "Resolution", + DEF_SCALE_RESOLUTION, Tk_Offset(TkScale, resolution), 0}, + {TK_CONFIG_BOOLEAN, "-showvalue", "showValue", "ShowValue", + DEF_SCALE_SHOW_VALUE, Tk_Offset(TkScale, showValue), 0}, + {TK_CONFIG_PIXELS, "-sliderlength", "sliderLength", "SliderLength", + DEF_SCALE_SLIDER_LENGTH, Tk_Offset(TkScale, sliderLength), 0}, + {TK_CONFIG_RELIEF, "-sliderrelief", "sliderRelief", "SliderRelief", + DEF_SCALE_SLIDER_RELIEF, Tk_Offset(TkScale, sliderRelief), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_UID, "-state", "state", "State", + DEF_SCALE_STATE, Tk_Offset(TkScale, state), 0}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_SCALE_TAKE_FOCUS, Tk_Offset(TkScale, takeFocus), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_DOUBLE, "-tickinterval", "tickInterval", "TickInterval", + DEF_SCALE_TICK_INTERVAL, Tk_Offset(TkScale, tickInterval), 0}, + {TK_CONFIG_DOUBLE, "-to", "to", "To", + DEF_SCALE_TO, Tk_Offset(TkScale, toValue), 0}, + {TK_CONFIG_COLOR, "-troughcolor", "troughColor", "Background", + DEF_SCALE_TROUGH_COLOR, Tk_Offset(TkScale, troughColorPtr), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-troughcolor", "troughColor", "Background", + DEF_SCALE_TROUGH_MONO, Tk_Offset(TkScale, troughColorPtr), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_STRING, "-variable", "variable", "Variable", + DEF_SCALE_VARIABLE, Tk_Offset(TkScale, varName), TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-width", "width", "Width", + DEF_SCALE_WIDTH, Tk_Offset(TkScale, width), 0}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void ComputeFormat _ANSI_ARGS_((TkScale *scalePtr)); +static void ComputeScaleGeometry _ANSI_ARGS_((TkScale *scalePtr)); +static int ConfigureScale _ANSI_ARGS_((Tcl_Interp *interp, + TkScale *scalePtr, int argc, char **argv, + int flags)); +static void DestroyScale _ANSI_ARGS_((char *memPtr)); +static void ScaleCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static void ScaleEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static char * ScaleVarProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, char *name1, char *name2, + int flags)); +static int ScaleWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void ScaleWorldChanged _ANSI_ARGS_(( + ClientData instanceData)); + +/* + * The structure below defines scale class behavior by means of procedures + * that can be invoked from generic window code. + */ + +static TkClassProcs scaleClass = { + NULL, /* createProc. */ + ScaleWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + + +/* + *-------------------------------------------------------------- + * + * Tk_ScaleCmd -- + * + * This procedure is invoked to process the "scale" Tcl + * command. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_ScaleCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + register TkScale *scalePtr; + Tk_Window new; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *) NULL); + if (new == NULL) { + return TCL_ERROR; + } + scalePtr = TkpCreateScale(new); + + /* + * Initialize fields that won't be initialized by ConfigureScale, + * or which ConfigureScale expects to have reasonable values + * (e.g. resource pointers). + */ + + scalePtr->tkwin = new; + scalePtr->display = Tk_Display(new); + scalePtr->interp = interp; + scalePtr->widgetCmd = Tcl_CreateCommand(interp, + Tk_PathName(scalePtr->tkwin), ScaleWidgetCmd, + (ClientData) scalePtr, ScaleCmdDeletedProc); + scalePtr->orientUid = NULL; + scalePtr->vertical = 0; + scalePtr->width = 0; + scalePtr->length = 0; + scalePtr->value = 0; + scalePtr->varName = NULL; + scalePtr->fromValue = 0; + scalePtr->toValue = 0; + scalePtr->tickInterval = 0; + scalePtr->resolution = 1; + scalePtr->bigIncrement = 0.0; + scalePtr->command = NULL; + scalePtr->repeatDelay = 0; + scalePtr->repeatInterval = 0; + scalePtr->label = NULL; + scalePtr->labelLength = 0; + scalePtr->state = tkNormalUid; + scalePtr->borderWidth = 0; + scalePtr->bgBorder = NULL; + scalePtr->activeBorder = NULL; + scalePtr->sliderRelief = TK_RELIEF_RAISED; + scalePtr->troughColorPtr = NULL; + scalePtr->troughGC = None; + scalePtr->copyGC = None; + scalePtr->tkfont = NULL; + scalePtr->textColorPtr = NULL; + scalePtr->textGC = None; + scalePtr->relief = TK_RELIEF_FLAT; + scalePtr->highlightWidth = 0; + scalePtr->highlightBgColorPtr = NULL; + scalePtr->highlightColorPtr = NULL; + scalePtr->inset = 0; + scalePtr->sliderLength = 0; + scalePtr->showValue = 0; + scalePtr->horizLabelY = 0; + scalePtr->horizValueY = 0; + scalePtr->horizTroughY = 0; + scalePtr->horizTickY = 0; + scalePtr->vertTickRightX = 0; + scalePtr->vertValueRightX = 0; + scalePtr->vertTroughX = 0; + scalePtr->vertLabelX = 0; + scalePtr->cursor = None; + scalePtr->takeFocus = NULL; + scalePtr->flags = NEVER_SET; + + Tk_SetClass(scalePtr->tkwin, "Scale"); + TkSetClassProcs(scalePtr->tkwin, &scaleClass, (ClientData) scalePtr); + Tk_CreateEventHandler(scalePtr->tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + ScaleEventProc, (ClientData) scalePtr); + if (ConfigureScale(interp, scalePtr, argc-2, argv+2, 0) != TCL_OK) { + goto error; + } + + interp->result = Tk_PathName(scalePtr->tkwin); + return TCL_OK; + + error: + Tk_DestroyWindow(scalePtr->tkwin); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * ScaleWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a widget managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +ScaleWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about scale + * widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register TkScale *scalePtr = (TkScale *) clientData; + int result = TCL_OK; + size_t length; + int c; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) scalePtr); + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + goto error; + } + result = Tk_ConfigureValue(interp, scalePtr->tkwin, configSpecs, + (char *) scalePtr, argv[2], 0); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 3)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, scalePtr->tkwin, configSpecs, + (char *) scalePtr, (char *) NULL, 0); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, scalePtr->tkwin, configSpecs, + (char *) scalePtr, argv[2], 0); + } else { + result = ConfigureScale(interp, scalePtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else if ((c == 'c') && (strncmp(argv[1], "coords", length) == 0) + && (length >= 3)) { + int x, y ; + double value; + + if ((argc != 2) && (argc != 3)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " coords ?value?\"", (char *) NULL); + goto error; + } + if (argc == 3) { + if (Tcl_GetDouble(interp, argv[2], &value) != TCL_OK) { + goto error; + } + } else { + value = scalePtr->value; + } + if (scalePtr->vertical) { + x = scalePtr->vertTroughX + scalePtr->width/2 + + scalePtr->borderWidth; + y = TkpValueToPixel(scalePtr, value); + } else { + x = TkpValueToPixel(scalePtr, value); + y = scalePtr->horizTroughY + scalePtr->width/2 + + scalePtr->borderWidth; + } + sprintf(interp->result, "%d %d", x, y); + } else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) { + double value; + int x, y; + + if ((argc != 2) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " get ?x y?\"", (char *) NULL); + goto error; + } + if (argc == 2) { + value = scalePtr->value; + } else { + if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[3], &y) != TCL_OK)) { + goto error; + } + value = TkpPixelToValue(scalePtr, x, y); + } + sprintf(interp->result, scalePtr->format, value); + } else if ((c == 'i') && (strncmp(argv[1], "identify", length) == 0)) { + int x, y, thing; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " identify x y\"", (char *) NULL); + goto error; + } + if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[3], &y) != TCL_OK)) { + goto error; + } + thing = TkpScaleElement(scalePtr, x,y); + switch (thing) { + case TROUGH1: interp->result = "trough1"; break; + case SLIDER: interp->result = "slider"; break; + case TROUGH2: interp->result = "trough2"; break; + } + } else if ((c == 's') && (strncmp(argv[1], "set", length) == 0)) { + double value; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " set value\"", (char *) NULL); + goto error; + } + if (Tcl_GetDouble(interp, argv[2], &value) != TCL_OK) { + goto error; + } + if (scalePtr->state != tkDisabledUid) { + TkpSetScaleValue(scalePtr, value, 1, 1); + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be cget, configure, coords, get, identify, or set", + (char *) NULL); + goto error; + } + Tcl_Release((ClientData) scalePtr); + return result; + + error: + Tcl_Release((ClientData) scalePtr); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyScale -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a button at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the scale is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyScale(memPtr) + char *memPtr; /* Info about scale widget. */ +{ + register TkScale *scalePtr = (TkScale *) memPtr; + + /* + * Free up all the stuff that requires special handling, then + * let Tk_FreeOptions handle all the standard option-related + * stuff. + */ + + if (scalePtr->varName != NULL) { + Tcl_UntraceVar(scalePtr->interp, scalePtr->varName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ScaleVarProc, (ClientData) scalePtr); + } + if (scalePtr->troughGC != None) { + Tk_FreeGC(scalePtr->display, scalePtr->troughGC); + } + if (scalePtr->copyGC != None) { + Tk_FreeGC(scalePtr->display, scalePtr->copyGC); + } + if (scalePtr->textGC != None) { + Tk_FreeGC(scalePtr->display, scalePtr->textGC); + } + Tk_FreeOptions(configSpecs, (char *) scalePtr, scalePtr->display, 0); + TkpDestroyScale(scalePtr); +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureScale -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or + * reconfigure) a scale widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as colors, border width, + * etc. get set for scalePtr; old resources get freed, + * if there were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureScale(interp, scalePtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + register TkScale *scalePtr; /* Information about widget; may or may + * not already have values for some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + size_t length; + + /* + * Eliminate any existing trace on a variable monitored by the scale. + */ + + if (scalePtr->varName != NULL) { + Tcl_UntraceVar(interp, scalePtr->varName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ScaleVarProc, (ClientData) scalePtr); + } + + if (Tk_ConfigureWidget(interp, scalePtr->tkwin, configSpecs, + argc, argv, (char *) scalePtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * If the scale is tied to the value of a variable, then set up + * a trace on the variable's value and set the scale's value from + * the value of the variable, if it exists. + */ + + if (scalePtr->varName != NULL) { + char *stringValue, *end; + double value; + + stringValue = Tcl_GetVar(interp, scalePtr->varName, TCL_GLOBAL_ONLY); + if (stringValue != NULL) { + value = strtod(stringValue, &end); + if ((end != stringValue) && (*end == 0)) { + scalePtr->value = TkRoundToResolution(scalePtr, value); + } + } + Tcl_TraceVar(interp, scalePtr->varName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ScaleVarProc, (ClientData) scalePtr); + } + + /* + * Several options need special processing, such as parsing the + * orientation and creating GCs. + */ + + length = strlen(scalePtr->orientUid); + if (strncmp(scalePtr->orientUid, "vertical", length) == 0) { + scalePtr->vertical = 1; + } else if (strncmp(scalePtr->orientUid, "horizontal", length) == 0) { + scalePtr->vertical = 0; + } else { + Tcl_AppendResult(interp, "bad orientation \"", scalePtr->orientUid, + "\": must be vertical or horizontal", (char *) NULL); + return TCL_ERROR; + } + + scalePtr->fromValue = TkRoundToResolution(scalePtr, scalePtr->fromValue); + scalePtr->toValue = TkRoundToResolution(scalePtr, scalePtr->toValue); + scalePtr->tickInterval = TkRoundToResolution(scalePtr, + scalePtr->tickInterval); + + /* + * Make sure that the tick interval has the right sign so that + * addition moves from fromValue to toValue. + */ + + if ((scalePtr->tickInterval < 0) + ^ ((scalePtr->toValue - scalePtr->fromValue) < 0)) { + scalePtr->tickInterval = -scalePtr->tickInterval; + } + + /* + * Set the scale value to itself; all this does is to make sure + * that the scale's value is within the new acceptable range for + * the scale and reflect the value in the associated variable, + * if any. + */ + + ComputeFormat(scalePtr); + TkpSetScaleValue(scalePtr, scalePtr->value, 1, 1); + + if (scalePtr->label != NULL) { + scalePtr->labelLength = strlen(scalePtr->label); + } else { + scalePtr->labelLength = 0; + } + + if ((scalePtr->state != tkNormalUid) + && (scalePtr->state != tkDisabledUid) + && (scalePtr->state != tkActiveUid)) { + Tcl_AppendResult(interp, "bad state value \"", scalePtr->state, + "\": must be normal, active, or disabled", (char *) NULL); + scalePtr->state = tkNormalUid; + return TCL_ERROR; + } + + Tk_SetBackgroundFromBorder(scalePtr->tkwin, scalePtr->bgBorder); + + if (scalePtr->highlightWidth < 0) { + scalePtr->highlightWidth = 0; + } + scalePtr->inset = scalePtr->highlightWidth + scalePtr->borderWidth; + + ScaleWorldChanged((ClientData) scalePtr); + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * ScaleWorldChanged -- + * + * This procedure is called when the world has changed in some + * way and the widget needs to recompute all its graphics contexts + * and determine its new geometry. + * + * Results: + * None. + * + * Side effects: + * Scale will be relayed out and redisplayed. + * + *--------------------------------------------------------------------------- + */ + +static void +ScaleWorldChanged(instanceData) + ClientData instanceData; /* Information about widget. */ +{ + XGCValues gcValues; + GC gc; + TkScale *scalePtr; + + scalePtr = (TkScale *) instanceData; + + gcValues.foreground = scalePtr->troughColorPtr->pixel; + gc = Tk_GetGC(scalePtr->tkwin, GCForeground, &gcValues); + if (scalePtr->troughGC != None) { + Tk_FreeGC(scalePtr->display, scalePtr->troughGC); + } + scalePtr->troughGC = gc; + + gcValues.font = Tk_FontId(scalePtr->tkfont); + gcValues.foreground = scalePtr->textColorPtr->pixel; + gc = Tk_GetGC(scalePtr->tkwin, GCForeground | GCFont, &gcValues); + if (scalePtr->textGC != None) { + Tk_FreeGC(scalePtr->display, scalePtr->textGC); + } + scalePtr->textGC = gc; + + if (scalePtr->copyGC == None) { + gcValues.graphics_exposures = False; + scalePtr->copyGC = Tk_GetGC(scalePtr->tkwin, GCGraphicsExposures, + &gcValues); + } + scalePtr->inset = scalePtr->highlightWidth + scalePtr->borderWidth; + + /* + * Recompute display-related information, and let the geometry + * manager know how much space is needed now. + */ + + ComputeScaleGeometry(scalePtr); + + TkEventuallyRedrawScale(scalePtr, REDRAW_ALL); +} + +/* + *---------------------------------------------------------------------- + * + * ComputeFormat -- + * + * This procedure is invoked to recompute the "format" field + * of a scale's widget record, which determines how the value + * of the scale is converted to a string. + * + * Results: + * None. + * + * Side effects: + * The format field of scalePtr is modified. + * + *---------------------------------------------------------------------- + */ + +static void +ComputeFormat(scalePtr) + TkScale *scalePtr; /* Information about scale widget. */ +{ + double maxValue, x; + int mostSigDigit, numDigits, leastSigDigit, afterDecimal; + int eDigits, fDigits; + + /* + * Compute the displacement from the decimal of the most significant + * digit required for any number in the scale's range. + */ + + maxValue = fabs(scalePtr->fromValue); + x = fabs(scalePtr->toValue); + if (x > maxValue) { + maxValue = x; + } + if (maxValue == 0) { + maxValue = 1; + } + mostSigDigit = (int) floor(log10(maxValue)); + + /* + * If the number of significant digits wasn't specified explicitly, + * compute it. It's the difference between the most significant + * digit needed to represent any number on the scale and the + * most significant digit of the smallest difference between + * numbers on the scale. In other words, display enough digits so + * that at least one digit will be different between any two adjacent + * positions of the scale. + */ + + numDigits = scalePtr->digits; + if (numDigits <= 0) { + if (scalePtr->resolution > 0) { + /* + * A resolution was specified for the scale, so just use it. + */ + + leastSigDigit = (int) floor(log10(scalePtr->resolution)); + } else { + /* + * No resolution was specified, so compute the difference + * in value between adjacent pixels and use it for the least + * significant digit. + */ + + x = fabs(scalePtr->fromValue - scalePtr->toValue); + if (scalePtr->length > 0) { + x /= scalePtr->length; + } + if (x > 0){ + leastSigDigit = (int) floor(log10(x)); + } else { + leastSigDigit = 0; + } + } + numDigits = mostSigDigit - leastSigDigit + 1; + if (numDigits < 1) { + numDigits = 1; + } + } + + /* + * Compute the number of characters required using "e" format and + * "f" format, and then choose whichever one takes fewer characters. + */ + + eDigits = numDigits + 4; + if (numDigits > 1) { + eDigits++; /* Decimal point. */ + } + afterDecimal = numDigits - mostSigDigit - 1; + if (afterDecimal < 0) { + afterDecimal = 0; + } + fDigits = (mostSigDigit >= 0) ? mostSigDigit + afterDecimal : afterDecimal; + if (afterDecimal > 0) { + fDigits++; /* Decimal point. */ + } + if (mostSigDigit < 0) { + fDigits++; /* Zero to left of decimal point. */ + } + if (fDigits <= eDigits) { + sprintf(scalePtr->format, "%%.%df", afterDecimal); + } else { + sprintf(scalePtr->format, "%%.%de", numDigits-1); + } +} + +/* + *---------------------------------------------------------------------- + * + * ComputeScaleGeometry -- + * + * This procedure is called to compute various geometrical + * information for a scale, such as where various things get + * displayed. It's called when the window is reconfigured. + * + * Results: + * None. + * + * Side effects: + * Display-related numbers get changed in *scalePtr. The + * geometry manager gets told about the window's preferred size. + * + *---------------------------------------------------------------------- + */ + +static void +ComputeScaleGeometry(scalePtr) + register TkScale *scalePtr; /* Information about widget. */ +{ + char valueString[PRINT_CHARS]; + int tmp, valuePixels, x, y, extraSpace; + Tk_FontMetrics fm; + + /* + * Horizontal scales are simpler than vertical ones because + * all sizes are the same (the height of a line of text); + * handle them first and then quit. + */ + + Tk_GetFontMetrics(scalePtr->tkfont, &fm); + if (!scalePtr->vertical) { + y = scalePtr->inset; + extraSpace = 0; + if (scalePtr->labelLength != 0) { + scalePtr->horizLabelY = y + SPACING; + y += fm.linespace + SPACING; + extraSpace = SPACING; + } + if (scalePtr->showValue) { + scalePtr->horizValueY = y + SPACING; + y += fm.linespace + SPACING; + extraSpace = SPACING; + } else { + scalePtr->horizValueY = y; + } + y += extraSpace; + scalePtr->horizTroughY = y; + y += scalePtr->width + 2*scalePtr->borderWidth; + if (scalePtr->tickInterval != 0) { + scalePtr->horizTickY = y + SPACING; + y += fm.linespace + 2*SPACING; + } + Tk_GeometryRequest(scalePtr->tkwin, + scalePtr->length + 2*scalePtr->inset, y + scalePtr->inset); + Tk_SetInternalBorder(scalePtr->tkwin, scalePtr->inset); + return; + } + + /* + * Vertical scale: compute the amount of space needed to display + * the scales value by formatting strings for the two end points; + * use whichever length is longer. + */ + + sprintf(valueString, scalePtr->format, scalePtr->fromValue); + valuePixels = Tk_TextWidth(scalePtr->tkfont, valueString, -1); + + sprintf(valueString, scalePtr->format, scalePtr->toValue); + tmp = Tk_TextWidth(scalePtr->tkfont, valueString, -1); + if (valuePixels < tmp) { + valuePixels = tmp; + } + + /* + * Assign x-locations to the elements of the scale, working from + * left to right. + */ + + x = scalePtr->inset; + if ((scalePtr->tickInterval != 0) && (scalePtr->showValue)) { + scalePtr->vertTickRightX = x + SPACING + valuePixels; + scalePtr->vertValueRightX = scalePtr->vertTickRightX + valuePixels + + fm.ascent/2; + x = scalePtr->vertValueRightX + SPACING; + } else if (scalePtr->tickInterval != 0) { + scalePtr->vertTickRightX = x + SPACING + valuePixels; + scalePtr->vertValueRightX = scalePtr->vertTickRightX; + x = scalePtr->vertTickRightX + SPACING; + } else if (scalePtr->showValue) { + scalePtr->vertTickRightX = x; + scalePtr->vertValueRightX = x + SPACING + valuePixels; + x = scalePtr->vertValueRightX + SPACING; + } else { + scalePtr->vertTickRightX = x; + scalePtr->vertValueRightX = x; + } + scalePtr->vertTroughX = x; + x += 2*scalePtr->borderWidth + scalePtr->width; + if (scalePtr->labelLength == 0) { + scalePtr->vertLabelX = 0; + } else { + scalePtr->vertLabelX = x + fm.ascent/2; + x = scalePtr->vertLabelX + fm.ascent/2 + + Tk_TextWidth(scalePtr->tkfont, scalePtr->label, + scalePtr->labelLength); + } + Tk_GeometryRequest(scalePtr->tkwin, x + scalePtr->inset, + scalePtr->length + 2*scalePtr->inset); + Tk_SetInternalBorder(scalePtr->tkwin, scalePtr->inset); +} + +/* + *-------------------------------------------------------------- + * + * ScaleEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on scales. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +ScaleEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + TkScale *scalePtr = (TkScale *) clientData; + + if ((eventPtr->type == Expose) && (eventPtr->xexpose.count == 0)) { + TkEventuallyRedrawScale(scalePtr, REDRAW_ALL); + } else if (eventPtr->type == DestroyNotify) { + if (scalePtr->tkwin != NULL) { + scalePtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(scalePtr->interp, scalePtr->widgetCmd); + } + if (scalePtr->flags & REDRAW_ALL) { + Tcl_CancelIdleCall(TkpDisplayScale, (ClientData) scalePtr); + } + Tcl_EventuallyFree((ClientData) scalePtr, DestroyScale); + } else if (eventPtr->type == ConfigureNotify) { + ComputeScaleGeometry(scalePtr); + TkEventuallyRedrawScale(scalePtr, REDRAW_ALL); + } else if (eventPtr->type == FocusIn) { + if (eventPtr->xfocus.detail != NotifyInferior) { + scalePtr->flags |= GOT_FOCUS; + if (scalePtr->highlightWidth > 0) { + TkEventuallyRedrawScale(scalePtr, REDRAW_ALL); + } + } + } else if (eventPtr->type == FocusOut) { + if (eventPtr->xfocus.detail != NotifyInferior) { + scalePtr->flags &= ~GOT_FOCUS; + if (scalePtr->highlightWidth > 0) { + TkEventuallyRedrawScale(scalePtr, REDRAW_ALL); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * ScaleCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +ScaleCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + TkScale *scalePtr = (TkScale *) clientData; + Tk_Window tkwin = scalePtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + scalePtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *-------------------------------------------------------------- + * + * TkEventuallyRedrawScale -- + * + * Arrange for part or all of a scale widget to redrawn at + * the next convenient time in the future. + * + * Results: + * None. + * + * Side effects: + * If "what" is REDRAW_SLIDER then just the slider and the + * value readout will be redrawn; if "what" is REDRAW_ALL + * then the entire widget will be redrawn. + * + *-------------------------------------------------------------- + */ + +void +TkEventuallyRedrawScale(scalePtr, what) + register TkScale *scalePtr; /* Information about widget. */ + int what; /* What to redraw: REDRAW_SLIDER + * or REDRAW_ALL. */ +{ + if ((what == 0) || (scalePtr->tkwin == NULL) + || !Tk_IsMapped(scalePtr->tkwin)) { + return; + } + if ((scalePtr->flags & REDRAW_ALL) == 0) { + Tcl_DoWhenIdle(TkpDisplayScale, (ClientData) scalePtr); + } + scalePtr->flags |= what; +} + +/* + *-------------------------------------------------------------- + * + * TkRoundToResolution -- + * + * Round a given floating-point value to the nearest multiple + * of the scale's resolution. + * + * Results: + * The return value is the rounded result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +double +TkRoundToResolution(scalePtr, value) + TkScale *scalePtr; /* Information about scale widget. */ + double value; /* Value to round. */ +{ + double rem, new; + + if (scalePtr->resolution <= 0) { + return value; + } + new = scalePtr->resolution * floor(value/scalePtr->resolution); + rem = value - new; + if (rem < 0) { + if (rem <= -scalePtr->resolution/2) { + new -= scalePtr->resolution; + } + } else { + if (rem >= scalePtr->resolution/2) { + new += scalePtr->resolution; + } + } + return new; +} + +/* + *---------------------------------------------------------------------- + * + * ScaleVarProc -- + * + * This procedure is invoked by Tcl whenever someone modifies a + * variable associated with a scale widget. + * + * Results: + * NULL is always returned. + * + * Side effects: + * The value displayed in the scale will change to match the + * variable's new value. If the variable has a bogus value then + * it is reset to the value of the scale. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static char * +ScaleVarProc(clientData, interp, name1, name2, flags) + ClientData clientData; /* Information about button. */ + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *name1; /* Name of variable. */ + char *name2; /* Second part of variable name. */ + int flags; /* Information about what happened. */ +{ + register TkScale *scalePtr = (TkScale *) clientData; + char *stringValue, *end, *result; + double value; + + /* + * If the variable is unset, then immediately recreate it unless + * the whole interpreter is going away. + */ + + if (flags & TCL_TRACE_UNSETS) { + if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + Tcl_TraceVar(interp, scalePtr->varName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ScaleVarProc, clientData); + scalePtr->flags |= NEVER_SET; + TkpSetScaleValue(scalePtr, scalePtr->value, 1, 0); + } + return (char *) NULL; + } + + /* + * If we came here because we updated the variable (in TkpSetScaleValue), + * then ignore the trace. Otherwise update the scale with the value + * of the variable. + */ + + if (scalePtr->flags & SETTING_VAR) { + return (char *) NULL; + } + result = NULL; + stringValue = Tcl_GetVar(interp, scalePtr->varName, TCL_GLOBAL_ONLY); + if (stringValue != NULL) { + value = strtod(stringValue, &end); + if ((end == stringValue) || (*end != 0)) { + result = "can't assign non-numeric value to scale variable"; + } else { + scalePtr->value = TkRoundToResolution(scalePtr, value); + } + + /* + * This code is a bit tricky because it sets the scale's value before + * calling TkpSetScaleValue. This way, TkpSetScaleValue won't bother + * to set the variable again or to invoke the -command. However, it + * also won't redisplay the scale, so we have to ask for that + * explicitly. + */ + + TkpSetScaleValue(scalePtr, scalePtr->value, 1, 0); + TkEventuallyRedrawScale(scalePtr, REDRAW_SLIDER); + } + + return result; +} diff --git a/generic/tkScale.h b/generic/tkScale.h new file mode 100644 index 0000000..dba6f68 --- /dev/null +++ b/generic/tkScale.h @@ -0,0 +1,225 @@ +/* + * tkScale.h -- + * + * Declarations of types and functions used to implement + * the scale widget. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkScale.h 1.5 96/07/08 12:56:56 + */ + +#ifndef _TKSCALE +#define _TKSCALE + +#ifndef _TK +#include "tk.h" +#endif + +/* + * A data structure of the following type is kept for each scale + * widget managed by this file: + */ + +typedef struct TkScale { + Tk_Window tkwin; /* Window that embodies the scale. NULL + * means that the window has been destroyed + * but the data structures haven't yet been + * cleaned up.*/ + Display *display; /* Display containing widget. Used, among + * other things, so that resources can be + * freed even after tkwin has gone away. */ + Tcl_Interp *interp; /* Interpreter associated with scale. */ + Tcl_Command widgetCmd; /* Token for scale's widget command. */ + Tk_Uid orientUid; /* Orientation for window ("vertical" or + * "horizontal"). */ + int vertical; /* Non-zero means vertical orientation, + * zero means horizontal. */ + int width; /* Desired narrow dimension of scale, + * in pixels. */ + int length; /* Desired long dimension of scale, + * in pixels. */ + double value; /* Current value of scale. */ + char *varName; /* Name of variable (malloc'ed) or NULL. + * If non-NULL, scale's value tracks + * the contents of this variable and + * vice versa. */ + double fromValue; /* Value corresponding to left or top of + * scale. */ + double toValue; /* Value corresponding to right or bottom + * of scale. */ + double tickInterval; /* Distance between tick marks; 0 means + * don't display any tick marks. */ + double resolution; /* If > 0, all values are rounded to an + * even multiple of this value. */ + int digits; /* Number of significant digits to print + * in values. 0 means we get to choose the + * number based on resolution and/or the + * range of the scale. */ + char format[10]; /* Sprintf conversion specifier computed from + * digits and other information. */ + double bigIncrement; /* Amount to use for large increments to + * scale value. (0 means we pick a value). */ + char *command; /* Command prefix to use when invoking Tcl + * commands because the scale value changed. + * NULL means don't invoke commands. + * Malloc'ed. */ + int repeatDelay; /* How long to wait before auto-repeating + * on scrolling actions (in ms). */ + int repeatInterval; /* Interval between autorepeats (in ms). */ + char *label; /* Label to display above or to right of + * scale; NULL means don't display a + * label. Malloc'ed. */ + int labelLength; /* Number of non-NULL chars. in label. */ + Tk_Uid state; /* Normal or disabled. Value cannot be + * changed when scale is disabled. */ + + /* + * Information used when displaying widget: + */ + + int borderWidth; /* Width of 3-D border around window. */ + Tk_3DBorder bgBorder; /* Used for drawing slider and other + * background areas. */ + Tk_3DBorder activeBorder; /* For drawing the slider when active. */ + int sliderRelief; /* Is slider to be drawn raised, sunken, etc. */ + XColor *troughColorPtr; /* Color for drawing trough. */ + GC troughGC; /* For drawing trough. */ + GC copyGC; /* Used for copying from pixmap onto screen. */ + Tk_Font tkfont; /* Information about text font, or NULL. */ + XColor *textColorPtr; /* Color for drawing text. */ + GC textGC; /* GC for drawing text in normal mode. */ + int relief; /* Indicates whether window as a whole is + * raised, sunken, or flat. */ + int highlightWidth; /* Width in pixels of highlight to draw + * around widget when it has the focus. + * <= 0 means don't draw a highlight. */ + XColor *highlightBgColorPtr; + /* Color for drawing traversal highlight + * area when highlight is off. */ + XColor *highlightColorPtr; /* Color for drawing traversal highlight. */ + int inset; /* Total width of all borders, including + * traversal highlight and 3-D border. + * Indicates how much interior stuff must + * be offset from outside edges to leave + * room for borders. */ + int sliderLength; /* Length of slider, measured in pixels along + * long dimension of scale. */ + int showValue; /* Non-zero means to display the scale value + * below or to the left of the slider; zero + * means don't display the value. */ + + /* + * Layout information for horizontal scales, assuming that window + * gets the size it requested: + */ + + int horizLabelY; /* Y-coord at which to draw label. */ + int horizValueY; /* Y-coord at which to draw value text. */ + int horizTroughY; /* Y-coord of top of slider trough. */ + int horizTickY; /* Y-coord at which to draw tick text. */ + /* + * Layout information for vertical scales, assuming that window + * gets the size it requested: + */ + + int vertTickRightX; /* X-location of right side of tick-marks. */ + int vertValueRightX; /* X-location of right side of value string. */ + int vertTroughX; /* X-location of scale's slider trough. */ + int vertLabelX; /* X-location of origin of label. */ + + /* + * Miscellaneous information: + */ + + Tk_Cursor cursor; /* Current cursor for window, or None. */ + char *takeFocus; /* Value of -takefocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + int flags; /* Various flags; see below for + * definitions. */ +} TkScale; + +/* + * Flag bits for scales: + * + * REDRAW_SLIDER - 1 means slider (and numerical readout) need + * to be redrawn. + * REDRAW_OTHER - 1 means other stuff besides slider and value + * need to be redrawn. + * REDRAW_ALL - 1 means the entire widget needs to be redrawn. + * ACTIVE - 1 means the widget is active (the mouse is + * in its window). + * INVOKE_COMMAND - 1 means the scale's command needs to be + * invoked during the next redisplay (the + * value of the scale has changed since the + * last time the command was invoked). + * SETTING_VAR - 1 means that the associated variable is + * being set by us, so there's no need for + * ScaleVarProc to do anything. + * NEVER_SET - 1 means that the scale's value has never + * been set before (so must invoke -command and + * set associated variable even if the value + * doesn't appear to have changed). + * GOT_FOCUS - 1 means that the focus is currently in + * this widget. + */ + +#define REDRAW_SLIDER 1 +#define REDRAW_OTHER 2 +#define REDRAW_ALL 3 +#define ACTIVE 4 +#define INVOKE_COMMAND 0x10 +#define SETTING_VAR 0x20 +#define NEVER_SET 0x40 +#define GOT_FOCUS 0x80 + +/* + * Symbolic values for the active parts of a slider. These are + * the values that may be returned by the ScaleElement procedure. + */ + +#define OTHER 0 +#define TROUGH1 1 +#define SLIDER 2 +#define TROUGH2 3 + +/* + * Space to leave between scale area and text, and between text and + * edge of window. + */ + +#define SPACING 2 + +/* + * How many characters of space to provide when formatting the + * scale's value: + */ + +#define PRINT_CHARS 150 + +/* + * Declaration of procedures used in the implementation of the scrollbar + * widget. + */ + +EXTERN void TkEventuallyRedrawScale _ANSI_ARGS_((TkScale *scalePtr, + int what)); +EXTERN double TkRoundToResolution _ANSI_ARGS_((TkScale *scalePtr, + double value)); +EXTERN TkScale * TkpCreateScale _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN void TkpDestroyScale _ANSI_ARGS_((TkScale *scalePtr)); +EXTERN void TkpDisplayScale _ANSI_ARGS_((ClientData clientData)); +EXTERN double TkpPixelToValue _ANSI_ARGS_((TkScale *scalePtr, + int x, int y)); +EXTERN int TkpScaleElement _ANSI_ARGS_((TkScale *scalePtr, + int x, int y)); +EXTERN void TkpSetScaleValue _ANSI_ARGS_((TkScale *scalePtr, + double value, int setVar, int invokeCommand)); +EXTERN int TkpValueToPixel _ANSI_ARGS_((TkScale *scalePtr, + double value)); + +#endif /* _TKSCALE */ diff --git a/generic/tkScrollbar.c b/generic/tkScrollbar.c new file mode 100644 index 0000000..3025a78 --- /dev/null +++ b/generic/tkScrollbar.c @@ -0,0 +1,691 @@ +/* + * tkScrollbar.c -- + * + * This module implements a scrollbar widgets for the Tk + * toolkit. A scrollbar displays a slider and two arrows; + * mouse clicks on features within the scrollbar cause + * scrolling commands to be invoked. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkScrollbar.c 1.94 97/07/31 09:12:44 + */ + +#include "tkPort.h" +#include "tkScrollbar.h" +#include "default.h" + +/* + * Information used for argv parsing. + */ + +Tk_ConfigSpec tkpScrollbarConfigSpecs[] = { + {TK_CONFIG_BORDER, "-activebackground", "activeBackground", "Foreground", + DEF_SCROLLBAR_ACTIVE_BG_COLOR, Tk_Offset(TkScrollbar, activeBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-activebackground", "activeBackground", "Foreground", + DEF_SCROLLBAR_ACTIVE_BG_MONO, Tk_Offset(TkScrollbar, activeBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_RELIEF, "-activerelief", "activeRelief", "Relief", + DEF_SCROLLBAR_ACTIVE_RELIEF, Tk_Offset(TkScrollbar, activeRelief), 0}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_SCROLLBAR_BG_COLOR, Tk_Offset(TkScrollbar, bgBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_SCROLLBAR_BG_MONO, Tk_Offset(TkScrollbar, bgBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_SCROLLBAR_BORDER_WIDTH, Tk_Offset(TkScrollbar, borderWidth), 0}, + {TK_CONFIG_STRING, "-command", "command", "Command", + DEF_SCROLLBAR_COMMAND, Tk_Offset(TkScrollbar, command), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_SCROLLBAR_CURSOR, Tk_Offset(TkScrollbar, cursor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_PIXELS, "-elementborderwidth", "elementBorderWidth", + "BorderWidth", DEF_SCROLLBAR_EL_BORDER_WIDTH, + Tk_Offset(TkScrollbar, elementBorderWidth), 0}, + {TK_CONFIG_COLOR, "-highlightbackground", "highlightBackground", + "HighlightBackground", DEF_SCROLLBAR_HIGHLIGHT_BG, + Tk_Offset(TkScrollbar, highlightBgColorPtr), 0}, + {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor", + DEF_SCROLLBAR_HIGHLIGHT, + Tk_Offset(TkScrollbar, highlightColorPtr), 0}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", + DEF_SCROLLBAR_HIGHLIGHT_WIDTH, Tk_Offset(TkScrollbar, highlightWidth), 0}, + {TK_CONFIG_BOOLEAN, "-jump", "jump", "Jump", + DEF_SCROLLBAR_JUMP, Tk_Offset(TkScrollbar, jump), 0}, + {TK_CONFIG_UID, "-orient", "orient", "Orient", + DEF_SCROLLBAR_ORIENT, Tk_Offset(TkScrollbar, orientUid), 0}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_SCROLLBAR_RELIEF, Tk_Offset(TkScrollbar, relief), 0}, + {TK_CONFIG_INT, "-repeatdelay", "repeatDelay", "RepeatDelay", + DEF_SCROLLBAR_REPEAT_DELAY, Tk_Offset(TkScrollbar, repeatDelay), 0}, + {TK_CONFIG_INT, "-repeatinterval", "repeatInterval", "RepeatInterval", + DEF_SCROLLBAR_REPEAT_INTERVAL, Tk_Offset(TkScrollbar, repeatInterval), 0}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_SCROLLBAR_TAKE_FOCUS, Tk_Offset(TkScrollbar, takeFocus), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-troughcolor", "troughColor", "Background", + DEF_SCROLLBAR_TROUGH_COLOR, Tk_Offset(TkScrollbar, troughColorPtr), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-troughcolor", "troughColor", "Background", + DEF_SCROLLBAR_TROUGH_MONO, Tk_Offset(TkScrollbar, troughColorPtr), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_PIXELS, "-width", "width", "Width", + DEF_SCROLLBAR_WIDTH, Tk_Offset(TkScrollbar, width), 0}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int ConfigureScrollbar _ANSI_ARGS_((Tcl_Interp *interp, + TkScrollbar *scrollPtr, int argc, char **argv, + int flags)); +static void ScrollbarCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static int ScrollbarWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *, int argc, char **argv)); + +/* + *-------------------------------------------------------------- + * + * Tk_ScrollbarCmd -- + * + * This procedure is invoked to process the "scrollbar" Tcl + * command. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_ScrollbarCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + register TkScrollbar *scrollPtr; + Tk_Window new; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *) NULL); + if (new == NULL) { + return TCL_ERROR; + } + + Tk_SetClass(new, "Scrollbar"); + scrollPtr = TkpCreateScrollbar(new); + + TkSetClassProcs(new, &tkpScrollbarProcs, (ClientData) scrollPtr); + + /* + * Initialize fields that won't be initialized by ConfigureScrollbar, + * or which ConfigureScrollbar expects to have reasonable values + * (e.g. resource pointers). + */ + + scrollPtr->tkwin = new; + scrollPtr->display = Tk_Display(new); + scrollPtr->interp = interp; + scrollPtr->widgetCmd = Tcl_CreateCommand(interp, + Tk_PathName(scrollPtr->tkwin), ScrollbarWidgetCmd, + (ClientData) scrollPtr, ScrollbarCmdDeletedProc); + scrollPtr->orientUid = NULL; + scrollPtr->vertical = 0; + scrollPtr->width = 0; + scrollPtr->command = NULL; + scrollPtr->commandSize = 0; + scrollPtr->repeatDelay = 0; + scrollPtr->repeatInterval = 0; + scrollPtr->borderWidth = 0; + scrollPtr->bgBorder = NULL; + scrollPtr->activeBorder = NULL; + scrollPtr->troughColorPtr = NULL; + scrollPtr->relief = TK_RELIEF_FLAT; + scrollPtr->highlightWidth = 0; + scrollPtr->highlightBgColorPtr = NULL; + scrollPtr->highlightColorPtr = NULL; + scrollPtr->inset = 0; + scrollPtr->elementBorderWidth = -1; + scrollPtr->arrowLength = 0; + scrollPtr->sliderFirst = 0; + scrollPtr->sliderLast = 0; + scrollPtr->activeField = 0; + scrollPtr->activeRelief = TK_RELIEF_RAISED; + scrollPtr->totalUnits = 0; + scrollPtr->windowUnits = 0; + scrollPtr->firstUnit = 0; + scrollPtr->lastUnit = 0; + scrollPtr->firstFraction = 0.0; + scrollPtr->lastFraction = 0.0; + scrollPtr->cursor = None; + scrollPtr->takeFocus = NULL; + scrollPtr->flags = 0; + + if (ConfigureScrollbar(interp, scrollPtr, argc-2, argv+2, 0) != TCL_OK) { + Tk_DestroyWindow(scrollPtr->tkwin); + return TCL_ERROR; + } + + interp->result = Tk_PathName(scrollPtr->tkwin); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ScrollbarWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a widget managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +ScrollbarWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about scrollbar + * widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register TkScrollbar *scrollPtr = (TkScrollbar *) clientData; + int result = TCL_OK; + size_t length; + int c; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) scrollPtr); + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'a') && (strncmp(argv[1], "activate", length) == 0)) { + int oldActiveField; + if (argc == 2) { + switch (scrollPtr->activeField) { + case TOP_ARROW: interp->result = "arrow1"; break; + case SLIDER: interp->result = "slider"; break; + case BOTTOM_ARROW: interp->result = "arrow2"; break; + } + goto done; + } + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " activate element\"", (char *) NULL); + goto error; + } + c = argv[2][0]; + length = strlen(argv[2]); + oldActiveField = scrollPtr->activeField; + if ((c == 'a') && (strcmp(argv[2], "arrow1") == 0)) { + scrollPtr->activeField = TOP_ARROW; + } else if ((c == 'a') && (strcmp(argv[2], "arrow2") == 0)) { + scrollPtr->activeField = BOTTOM_ARROW; + } else if ((c == 's') && (strncmp(argv[2], "slider", length) == 0)) { + scrollPtr->activeField = SLIDER; + } else { + scrollPtr->activeField = OUTSIDE; + } + if (oldActiveField != scrollPtr->activeField) { + TkScrollbarEventuallyRedraw(scrollPtr); + } + } else if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + goto error; + } + result = Tk_ConfigureValue(interp, scrollPtr->tkwin, + tkpScrollbarConfigSpecs, (char *) scrollPtr, argv[2], 0); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 2)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, scrollPtr->tkwin, + tkpScrollbarConfigSpecs, (char *) scrollPtr, + (char *) NULL, 0); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, scrollPtr->tkwin, + tkpScrollbarConfigSpecs, (char *) scrollPtr, argv[2], 0); + } else { + result = ConfigureScrollbar(interp, scrollPtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else if ((c == 'd') && (strncmp(argv[1], "delta", length) == 0)) { + int xDelta, yDelta, pixels, length; + double fraction; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " delta xDelta yDelta\"", (char *) NULL); + goto error; + } + if ((Tcl_GetInt(interp, argv[2], &xDelta) != TCL_OK) + || (Tcl_GetInt(interp, argv[3], &yDelta) != TCL_OK)) { + goto error; + } + if (scrollPtr->vertical) { + pixels = yDelta; + length = Tk_Height(scrollPtr->tkwin) - 1 + - 2*(scrollPtr->arrowLength + scrollPtr->inset); + } else { + pixels = xDelta; + length = Tk_Width(scrollPtr->tkwin) - 1 + - 2*(scrollPtr->arrowLength + scrollPtr->inset); + } + if (length == 0) { + fraction = 0.0; + } else { + fraction = ((double) pixels / (double) length); + } + sprintf(interp->result, "%g", fraction); + } else if ((c == 'f') && (strncmp(argv[1], "fraction", length) == 0)) { + int x, y, pos, length; + double fraction; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " fraction x y\"", (char *) NULL); + goto error; + } + if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[3], &y) != TCL_OK)) { + goto error; + } + if (scrollPtr->vertical) { + pos = y - (scrollPtr->arrowLength + scrollPtr->inset); + length = Tk_Height(scrollPtr->tkwin) - 1 + - 2*(scrollPtr->arrowLength + scrollPtr->inset); + } else { + pos = x - (scrollPtr->arrowLength + scrollPtr->inset); + length = Tk_Width(scrollPtr->tkwin) - 1 + - 2*(scrollPtr->arrowLength + scrollPtr->inset); + } + if (length == 0) { + fraction = 0.0; + } else { + fraction = ((double) pos / (double) length); + } + if (fraction < 0) { + fraction = 0; + } else if (fraction > 1.0) { + fraction = 1.0; + } + sprintf(interp->result, "%g", fraction); + } else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) { + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " get\"", (char *) NULL); + goto error; + } + if (scrollPtr->flags & NEW_STYLE_COMMANDS) { + char first[TCL_DOUBLE_SPACE], last[TCL_DOUBLE_SPACE]; + + Tcl_PrintDouble(interp, scrollPtr->firstFraction, first); + Tcl_PrintDouble(interp, scrollPtr->lastFraction, last); + Tcl_AppendResult(interp, first, " ", last, (char *) NULL); + } else { + sprintf(interp->result, "%d %d %d %d", scrollPtr->totalUnits, + scrollPtr->windowUnits, scrollPtr->firstUnit, + scrollPtr->lastUnit); + } + } else if ((c == 'i') && (strncmp(argv[1], "identify", length) == 0)) { + int x, y, thing; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " identify x y\"", (char *) NULL); + goto error; + } + if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[3], &y) != TCL_OK)) { + goto error; + } + thing = TkpScrollbarPosition(scrollPtr, x,y); + switch (thing) { + case TOP_ARROW: interp->result = "arrow1"; break; + case TOP_GAP: interp->result = "trough1"; break; + case SLIDER: interp->result = "slider"; break; + case BOTTOM_GAP: interp->result = "trough2"; break; + case BOTTOM_ARROW: interp->result = "arrow2"; break; + } + } else if ((c == 's') && (strncmp(argv[1], "set", length) == 0)) { + int totalUnits, windowUnits, firstUnit, lastUnit; + + if (argc == 4) { + double first, last; + + if (Tcl_GetDouble(interp, argv[2], &first) != TCL_OK) { + goto error; + } + if (Tcl_GetDouble(interp, argv[3], &last) != TCL_OK) { + goto error; + } + if (first < 0) { + scrollPtr->firstFraction = 0; + } else if (first > 1.0) { + scrollPtr->firstFraction = 1.0; + } else { + scrollPtr->firstFraction = first; + } + if (last < scrollPtr->firstFraction) { + scrollPtr->lastFraction = scrollPtr->firstFraction; + } else if (last > 1.0) { + scrollPtr->lastFraction = 1.0; + } else { + scrollPtr->lastFraction = last; + } + scrollPtr->flags |= NEW_STYLE_COMMANDS; + } else if (argc == 6) { + if (Tcl_GetInt(interp, argv[2], &totalUnits) != TCL_OK) { + goto error; + } + if (totalUnits < 0) { + totalUnits = 0; + } + if (Tcl_GetInt(interp, argv[3], &windowUnits) != TCL_OK) { + goto error; + } + if (windowUnits < 0) { + windowUnits = 0; + } + if (Tcl_GetInt(interp, argv[4], &firstUnit) != TCL_OK) { + goto error; + } + if (Tcl_GetInt(interp, argv[5], &lastUnit) != TCL_OK) { + goto error; + } + if (totalUnits > 0) { + if (lastUnit < firstUnit) { + lastUnit = firstUnit; + } + } else { + firstUnit = lastUnit = 0; + } + scrollPtr->totalUnits = totalUnits; + scrollPtr->windowUnits = windowUnits; + scrollPtr->firstUnit = firstUnit; + scrollPtr->lastUnit = lastUnit; + if (scrollPtr->totalUnits == 0) { + scrollPtr->firstFraction = 0.0; + scrollPtr->lastFraction = 1.0; + } else { + scrollPtr->firstFraction = ((double) firstUnit)/totalUnits; + scrollPtr->lastFraction = ((double) (lastUnit+1))/totalUnits; + } + scrollPtr->flags &= ~NEW_STYLE_COMMANDS; + } else { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " set firstFraction lastFraction\" or \"", + argv[0], + " set totalUnits windowUnits firstUnit lastUnit\"", + (char *) NULL); + goto error; + } + TkpComputeScrollbarGeometry(scrollPtr); + TkScrollbarEventuallyRedraw(scrollPtr); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be activate, cget, configure, delta, fraction, ", + "get, identify, or set", (char *) NULL); + goto error; + } + done: + Tcl_Release((ClientData) scrollPtr); + return result; + + error: + Tcl_Release((ClientData) scrollPtr); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureScrollbar -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or + * reconfigure) a scrollbar widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as colors, border width, + * etc. get set for scrollPtr; old resources get freed, + * if there were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureScrollbar(interp, scrollPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + register TkScrollbar *scrollPtr; /* Information about widget; may or + * may not already have values for + * some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to + * Tk_ConfigureWidget. */ +{ + size_t length; + + if (Tk_ConfigureWidget(interp, scrollPtr->tkwin, tkpScrollbarConfigSpecs, + argc, argv, (char *) scrollPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few options need special processing, such as parsing the + * orientation or setting the background from a 3-D border. + */ + + length = strlen(scrollPtr->orientUid); + if (strncmp(scrollPtr->orientUid, "vertical", length) == 0) { + scrollPtr->vertical = 1; + } else if (strncmp(scrollPtr->orientUid, "horizontal", length) == 0) { + scrollPtr->vertical = 0; + } else { + Tcl_AppendResult(interp, "bad orientation \"", scrollPtr->orientUid, + "\": must be vertical or horizontal", (char *) NULL); + return TCL_ERROR; + } + + if (scrollPtr->command != NULL) { + scrollPtr->commandSize = strlen(scrollPtr->command); + } else { + scrollPtr->commandSize = 0; + } + + /* + * Configure platform specific options. + */ + + TkpConfigureScrollbar(scrollPtr); + + /* + * Register the desired geometry for the window (leave enough space + * for the two arrows plus a minimum-size slider, plus border around + * the whole window, if any). Then arrange for the window to be + * redisplayed. + */ + + TkpComputeScrollbarGeometry(scrollPtr); + TkScrollbarEventuallyRedraw(scrollPtr); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * TkScrollbarEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on scrollbars. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +void +TkScrollbarEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + TkScrollbar *scrollPtr = (TkScrollbar *) clientData; + + if ((eventPtr->type == Expose) && (eventPtr->xexpose.count == 0)) { + TkScrollbarEventuallyRedraw(scrollPtr); + } else if (eventPtr->type == DestroyNotify) { + TkpDestroyScrollbar(scrollPtr); + if (scrollPtr->tkwin != NULL) { + scrollPtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(scrollPtr->interp, + scrollPtr->widgetCmd); + } + if (scrollPtr->flags & REDRAW_PENDING) { + Tcl_CancelIdleCall(TkpDisplayScrollbar, (ClientData) scrollPtr); + } + /* + * Free up all the stuff that requires special handling, then + * let Tk_FreeOptions handle all the standard option-related + * stuff. + */ + + Tk_FreeOptions(tkpScrollbarConfigSpecs, (char *) scrollPtr, + scrollPtr->display, 0); + Tcl_EventuallyFree((ClientData) scrollPtr, TCL_DYNAMIC); + } else if (eventPtr->type == ConfigureNotify) { + TkpComputeScrollbarGeometry(scrollPtr); + TkScrollbarEventuallyRedraw(scrollPtr); + } else if (eventPtr->type == FocusIn) { + if (eventPtr->xfocus.detail != NotifyInferior) { + scrollPtr->flags |= GOT_FOCUS; + if (scrollPtr->highlightWidth > 0) { + TkScrollbarEventuallyRedraw(scrollPtr); + } + } + } else if (eventPtr->type == FocusOut) { + if (eventPtr->xfocus.detail != NotifyInferior) { + scrollPtr->flags &= ~GOT_FOCUS; + if (scrollPtr->highlightWidth > 0) { + TkScrollbarEventuallyRedraw(scrollPtr); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * ScrollbarCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +ScrollbarCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + TkScrollbar *scrollPtr = (TkScrollbar *) clientData; + Tk_Window tkwin = scrollPtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + scrollPtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *-------------------------------------------------------------- + * + * TkScrollbarEventuallyRedraw -- + * + * Arrange for one or more of the fields of a scrollbar + * to be redrawn. + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +TkScrollbarEventuallyRedraw(scrollPtr) + register TkScrollbar *scrollPtr; /* Information about widget. */ +{ + if ((scrollPtr->tkwin == NULL) || (!Tk_IsMapped(scrollPtr->tkwin))) { + return; + } + if ((scrollPtr->flags & REDRAW_PENDING) == 0) { + Tcl_DoWhenIdle(TkpDisplayScrollbar, (ClientData) scrollPtr); + scrollPtr->flags |= REDRAW_PENDING; + } +} diff --git a/generic/tkScrollbar.h b/generic/tkScrollbar.h new file mode 100644 index 0000000..48296a2 --- /dev/null +++ b/generic/tkScrollbar.h @@ -0,0 +1,200 @@ +/* + * tkScrollbar.h -- + * + * Declarations of types and functions used to implement + * the scrollbar widget. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkScrollbar.h 1.8 96/11/05 11:34:58 + */ + +#ifndef _TKSCROLLBAR +#define _TKSCROLLBAR + +#ifndef _TKINT +#include "tkInt.h" +#endif + +/* + * A data structure of the following type is kept for each scrollbar + * widget. + */ + +typedef struct TkScrollbar { + Tk_Window tkwin; /* Window that embodies the scrollbar. NULL + * means that the window has been destroyed + * but the data structures haven't yet been + * cleaned up.*/ + Display *display; /* Display containing widget. Used, among + * other things, so that resources can be + * freed even after tkwin has gone away. */ + Tcl_Interp *interp; /* Interpreter associated with scrollbar. */ + Tcl_Command widgetCmd; /* Token for scrollbar's widget command. */ + Tk_Uid orientUid; /* Orientation for window ("vertical" or + * "horizontal"). */ + int vertical; /* Non-zero means vertical orientation + * requested, zero means horizontal. */ + int width; /* Desired narrow dimension of scrollbar, + * in pixels. */ + char *command; /* Command prefix to use when invoking + * scrolling commands. NULL means don't + * invoke commands. Malloc'ed. */ + int commandSize; /* Number of non-NULL bytes in command. */ + int repeatDelay; /* How long to wait before auto-repeating + * on scrolling actions (in ms). */ + int repeatInterval; /* Interval between autorepeats (in ms). */ + int jump; /* Value of -jump option. */ + + /* + * Information used when displaying widget: + */ + + int borderWidth; /* Width of 3-D borders. */ + Tk_3DBorder bgBorder; /* Used for drawing background (all flat + * surfaces except for trough). */ + Tk_3DBorder activeBorder; /* For drawing backgrounds when active (i.e. + * when mouse is positioned over element). */ + XColor *troughColorPtr; /* Color for drawing trough. */ + int relief; /* Indicates whether window as a whole is + * raised, sunken, or flat. */ + int highlightWidth; /* Width in pixels of highlight to draw + * around widget when it has the focus. + * <= 0 means don't draw a highlight. */ + XColor *highlightBgColorPtr; + /* Color for drawing traversal highlight + * area when highlight is off. */ + XColor *highlightColorPtr; /* Color for drawing traversal highlight. */ + int inset; /* Total width of all borders, including + * traversal highlight and 3-D border. + * Indicates how much interior stuff must + * be offset from outside edges to leave + * room for borders. */ + int elementBorderWidth; /* Width of border to draw around elements + * inside scrollbar (arrows and slider). + * -1 means use borderWidth. */ + int arrowLength; /* Length of arrows along long dimension of + * scrollbar, including space for a small gap + * between the arrow and the slider. + * Recomputed on window size changes. */ + int sliderFirst; /* Pixel coordinate of top or left edge + * of slider area, including border. */ + int sliderLast; /* Coordinate of pixel just after bottom + * or right edge of slider area, including + * border. */ + int activeField; /* Names field to be displayed in active + * colors, such as TOP_ARROW, or 0 for + * no field. */ + int activeRelief; /* Value of -activeRelief option: relief + * to use for active element. */ + + /* + * Information describing the application related to the scrollbar. + * This information is provided by the application by invoking the + * "set" widget command. This information can now be provided in + * two ways: the "old" form (totalUnits, windowUnits, firstUnit, + * and lastUnit), or the "new" form (firstFraction and lastFraction). + * FirstFraction and lastFraction will always be valid, but + * the old-style information is only valid if the NEW_STYLE_COMMANDS + * flag is 0. + */ + + int totalUnits; /* Total dimension of application, in + * units. Valid only if the NEW_STYLE_COMMANDS + * flag isn't set. */ + int windowUnits; /* Maximum number of units that can be + * displayed in the window at once. Valid + * only if the NEW_STYLE_COMMANDS flag isn't + * set. */ + int firstUnit; /* Number of last unit visible in + * application's window. Valid only if the + * NEW_STYLE_COMMANDS flag isn't set. */ + int lastUnit; /* Index of last unit visible in window. + * Valid only if the NEW_STYLE_COMMANDS + * flag isn't set. */ + double firstFraction; /* Position of first visible thing in window, + * specified as a fraction between 0 and + * 1.0. */ + double lastFraction; /* Position of last visible thing in window, + * specified as a fraction between 0 and + * 1.0. */ + + /* + * Miscellaneous information: + */ + + Tk_Cursor cursor; /* Current cursor for window, or None. */ + char *takeFocus; /* Value of -takefocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + int flags; /* Various flags; see below for + * definitions. */ +} TkScrollbar; + +/* + * Legal values for "activeField" field of Scrollbar structures. These + * are also the return values from the ScrollbarPosition procedure. + */ + +#define OUTSIDE 0 +#define TOP_ARROW 1 +#define TOP_GAP 2 +#define SLIDER 3 +#define BOTTOM_GAP 4 +#define BOTTOM_ARROW 5 + +/* + * Flag bits for scrollbars: + * + * REDRAW_PENDING: Non-zero means a DoWhenIdle handler + * has already been queued to redraw + * this window. + * NEW_STYLE_COMMANDS: Non-zero means the new style of commands + * should be used to communicate with the + * widget: ".t yview scroll 2 lines", instead + * of ".t yview 40", for example. + * GOT_FOCUS: Non-zero means this window has the input + * focus. + */ + +#define REDRAW_PENDING 1 +#define NEW_STYLE_COMMANDS 2 +#define GOT_FOCUS 4 + +/* + * Declaration of scrollbar class procedures structure. + */ + +extern TkClassProcs tkpScrollbarProcs; + +/* + * Declaration of scrollbar configuration options. + */ + +extern Tk_ConfigSpec tkpScrollbarConfigSpecs[]; + +/* + * Declaration of procedures used in the implementation of the scrollbar + * widget. + */ + +EXTERN void TkScrollbarEventProc _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +EXTERN void TkScrollbarEventuallyRedraw _ANSI_ARGS_(( + TkScrollbar *scrollPtr)); +EXTERN void TkpComputeScrollbarGeometry _ANSI_ARGS_(( + TkScrollbar *scrollPtr)); +EXTERN TkScrollbar * TkpCreateScrollbar _ANSI_ARGS_((Tk_Window tkwin)); +EXTERN void TkpDestroyScrollbar _ANSI_ARGS_(( + TkScrollbar *scrollPtr)); +EXTERN void TkpDisplayScrollbar _ANSI_ARGS_(( + ClientData clientData)); +EXTERN void TkpConfigureScrollbar _ANSI_ARGS_(( + TkScrollbar *scrollPtr)); +EXTERN int TkpScrollbarPosition _ANSI_ARGS_(( + TkScrollbar *scrollPtr, int x, int y)); + +#endif /* _TKSCROLLBAR */ diff --git a/generic/tkSelect.c b/generic/tkSelect.c new file mode 100644 index 0000000..7263e30 --- /dev/null +++ b/generic/tkSelect.c @@ -0,0 +1,1341 @@ +/* + * tkSelect.c -- + * + * This file manages the selection for the Tk toolkit, + * translating between the standard X ICCCM conventions + * and Tcl commands. + * + * Copyright (c) 1990-1993 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkSelect.c 1.57 96/05/03 10:52:40 + */ + +#include "tkInt.h" +#include "tkSelect.h" + +/* + * When a selection handler is set up by invoking "selection handle", + * one of the following data structures is set up to hold information + * about the command to invoke and its interpreter. + */ + +typedef struct { + Tcl_Interp *interp; /* Interpreter in which to invoke command. */ + int cmdLength; /* # of non-NULL bytes in command. */ + char command[4]; /* Command to invoke. Actual space is + * allocated as large as necessary. This + * must be the last entry in the structure. */ +} CommandInfo; + +/* + * When selection ownership is claimed with the "selection own" Tcl command, + * one of the following structures is created to record the Tcl command + * to be executed when the selection is lost again. + */ + +typedef struct LostCommand { + Tcl_Interp *interp; /* Interpreter in which to invoke command. */ + char command[4]; /* Command to invoke. Actual space is + * allocated as large as necessary. This + * must be the last entry in the structure. */ +} LostCommand; + +/* + * Shared variables: + */ + +TkSelInProgress *pendingPtr = NULL; + /* Topmost search in progress, or + * NULL if none. */ + +/* + * Forward declarations for procedures defined in this file: + */ + +static int HandleTclCommand _ANSI_ARGS_((ClientData clientData, + int offset, char *buffer, int maxBytes)); +static void LostSelection _ANSI_ARGS_((ClientData clientData)); +static int SelGetProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, char *portion)); + +/* + *-------------------------------------------------------------- + * + * Tk_CreateSelHandler -- + * + * This procedure is called to register a procedure + * as the handler for selection requests of a particular + * target type on a particular window for a particular + * selection. + * + * Results: + * None. + * + * Side effects: + * In the future, whenever the selection is in tkwin's + * window and someone requests the selection in the + * form given by target, proc will be invoked to provide + * part or all of the selection in the given form. If + * there was already a handler declared for the given + * window, target and selection type, then it is replaced. + * Proc should have the following form: + * + * int + * proc(clientData, offset, buffer, maxBytes) + * ClientData clientData; + * int offset; + * char *buffer; + * int maxBytes; + * { + * } + * + * The clientData argument to proc will be the same as + * the clientData argument to this procedure. The offset + * argument indicates which portion of the selection to + * return: skip the first offset bytes. Buffer is a + * pointer to an area in which to place the converted + * selection, and maxBytes gives the number of bytes + * available at buffer. Proc should place the selection + * in buffer as a string, and return a count of the number + * of bytes of selection actually placed in buffer (not + * including the terminating NULL character). If the + * return value equals maxBytes, this is a sign that there + * is probably still more selection information available. + * + *-------------------------------------------------------------- + */ + +void +Tk_CreateSelHandler(tkwin, selection, target, proc, clientData, format) + Tk_Window tkwin; /* Token for window. */ + Atom selection; /* Selection to be handled. */ + Atom target; /* The kind of selection conversions + * that can be handled by proc, + * e.g. TARGETS or STRING. */ + Tk_SelectionProc *proc; /* Procedure to invoke to convert + * selection to type "target". */ + ClientData clientData; /* Value to pass to proc. */ + Atom format; /* Format in which the selection + * information should be returned to + * the requestor. XA_STRING is best by + * far, but anything listed in the ICCCM + * will be tolerated (blech). */ +{ + register TkSelHandler *selPtr; + TkWindow *winPtr = (TkWindow *) tkwin; + + if (winPtr->dispPtr->multipleAtom == None) { + TkSelInit(tkwin); + } + + /* + * See if there's already a handler for this target and selection on + * this window. If so, re-use it. If not, create a new one. + */ + + for (selPtr = winPtr->selHandlerList; ; selPtr = selPtr->nextPtr) { + if (selPtr == NULL) { + selPtr = (TkSelHandler *) ckalloc(sizeof(TkSelHandler)); + selPtr->nextPtr = winPtr->selHandlerList; + winPtr->selHandlerList = selPtr; + break; + } + if ((selPtr->selection == selection) && (selPtr->target == target)) { + + /* + * Special case: when replacing handler created by + * "selection handle", free up memory. Should there be a + * callback to allow other clients to do this too? + */ + + if (selPtr->proc == HandleTclCommand) { + ckfree((char *) selPtr->clientData); + } + break; + } + } + selPtr->selection = selection; + selPtr->target = target; + selPtr->format = format; + selPtr->proc = proc; + selPtr->clientData = clientData; + if (format == XA_STRING) { + selPtr->size = 8; + } else { + selPtr->size = 32; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_DeleteSelHandler -- + * + * Remove the selection handler for a given window, target, and + * selection, if it exists. + * + * Results: + * None. + * + * Side effects: + * The selection handler for tkwin and target is removed. If there + * is no such handler then nothing happens. + * + *---------------------------------------------------------------------- + */ + +void +Tk_DeleteSelHandler(tkwin, selection, target) + Tk_Window tkwin; /* Token for window. */ + Atom selection; /* The selection whose handler + * is to be removed. */ + Atom target; /* The target whose selection + * handler is to be removed. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + register TkSelHandler *selPtr, *prevPtr; + register TkSelInProgress *ipPtr; + + /* + * Find the selection handler to be deleted, or return if it doesn't + * exist. + */ + + for (selPtr = winPtr->selHandlerList, prevPtr = NULL; ; + prevPtr = selPtr, selPtr = selPtr->nextPtr) { + if (selPtr == NULL) { + return; + } + if ((selPtr->selection == selection) && (selPtr->target == target)) { + break; + } + } + + /* + * If ConvertSelection is processing this handler, tell it that the + * handler is dead. + */ + + for (ipPtr = pendingPtr; ipPtr != NULL; ipPtr = ipPtr->nextPtr) { + if (ipPtr->selPtr == selPtr) { + ipPtr->selPtr = NULL; + } + } + + /* + * Free resources associated with the handler. + */ + + if (prevPtr == NULL) { + winPtr->selHandlerList = selPtr->nextPtr; + } else { + prevPtr->nextPtr = selPtr->nextPtr; + } + if (selPtr->proc == HandleTclCommand) { + ckfree((char *) selPtr->clientData); + } + ckfree((char *) selPtr); +} + +/* + *-------------------------------------------------------------- + * + * Tk_OwnSelection -- + * + * Arrange for tkwin to become the owner of a selection. + * + * Results: + * None. + * + * Side effects: + * From now on, requests for the selection will be directed + * to procedures associated with tkwin (they must have been + * declared with calls to Tk_CreateSelHandler). When the + * selection is lost by this window, proc will be invoked + * (see the manual entry for details). This procedure may + * invoke callbacks, including Tcl scripts, so any calling + * function should be reentrant at the point where + * Tk_OwnSelection is invoked. + * + *-------------------------------------------------------------- + */ + +void +Tk_OwnSelection(tkwin, selection, proc, clientData) + Tk_Window tkwin; /* Window to become new selection + * owner. */ + Atom selection; /* Selection that window should own. */ + Tk_LostSelProc *proc; /* Procedure to call when selection + * is taken away from tkwin. */ + ClientData clientData; /* Arbitrary one-word argument to + * pass to proc. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr = winPtr->dispPtr; + TkSelectionInfo *infoPtr; + Tk_LostSelProc *clearProc = NULL; + ClientData clearData = NULL; /* Initialization needed only to + * prevent compiler warning. */ + + + if (dispPtr->multipleAtom == None) { + TkSelInit(tkwin); + } + Tk_MakeWindowExist(tkwin); + + /* + * This code is somewhat tricky. First, we find the specified selection + * on the selection list. If the previous owner is in this process, and + * is a different window, then we need to invoke the clearProc. However, + * it's dangerous to call the clearProc right now, because it could + * invoke a Tcl script that wrecks the current state (e.g. it could + * delete the window). To be safe, defer the call until the end of the + * procedure when we no longer care about the state. + */ + + for (infoPtr = dispPtr->selectionInfoPtr; infoPtr != NULL; + infoPtr = infoPtr->nextPtr) { + if (infoPtr->selection == selection) { + break; + } + } + if (infoPtr == NULL) { + infoPtr = (TkSelectionInfo*) ckalloc(sizeof(TkSelectionInfo)); + infoPtr->selection = selection; + infoPtr->nextPtr = dispPtr->selectionInfoPtr; + dispPtr->selectionInfoPtr = infoPtr; + } else if (infoPtr->clearProc != NULL) { + if (infoPtr->owner != tkwin) { + clearProc = infoPtr->clearProc; + clearData = infoPtr->clearData; + } else if (infoPtr->clearProc == LostSelection) { + /* + * If the selection handler is one created by "selection own", + * be sure to free the record for it; otherwise there will be + * a memory leak. + */ + + ckfree((char *) infoPtr->clearData); + } + } + + infoPtr->owner = tkwin; + infoPtr->serial = NextRequest(winPtr->display); + infoPtr->clearProc = proc; + infoPtr->clearData = clientData; + + /* + * Note that we are using CurrentTime, even though ICCCM recommends against + * this practice (the problem is that we don't necessarily have a valid + * time to use). We will not be able to retrieve a useful timestamp for + * the TIMESTAMP target later. + */ + + infoPtr->time = CurrentTime; + + /* + * Note that we are not checking to see if the selection claim succeeded. + * If the ownership does not change, then the clearProc may never be + * invoked, and we will return incorrect information when queried for the + * current selection owner. + */ + + XSetSelectionOwner(winPtr->display, infoPtr->selection, winPtr->window, + infoPtr->time); + + /* + * Now that we are done, we can invoke clearProc without running into + * reentrancy problems. + */ + + if (clearProc != NULL) { + (*clearProc)(clearData); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_ClearSelection -- + * + * Eliminate the specified selection on tkwin's display, if there is one. + * + * Results: + * None. + * + * Side effects: + * The specified selection is cleared, so that future requests to retrieve + * it will fail until some application owns it again. This procedure + * invokes callbacks, possibly including Tcl scripts, so any calling + * function should be reentrant at the point Tk_ClearSelection is invoked. + * + *---------------------------------------------------------------------- + */ + +void +Tk_ClearSelection(tkwin, selection) + Tk_Window tkwin; /* Window that selects a display. */ + Atom selection; /* Selection to be cancelled. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr = winPtr->dispPtr; + TkSelectionInfo *infoPtr; + TkSelectionInfo *prevPtr; + TkSelectionInfo *nextPtr; + Tk_LostSelProc *clearProc = NULL; + ClientData clearData = NULL; /* Initialization needed only to + * prevent compiler warning. */ + + if (dispPtr->multipleAtom == None) { + TkSelInit(tkwin); + } + + for (infoPtr = dispPtr->selectionInfoPtr, prevPtr = NULL; + infoPtr != NULL; infoPtr = nextPtr) { + nextPtr = infoPtr->nextPtr; + if (infoPtr->selection == selection) { + if (prevPtr == NULL) { + dispPtr->selectionInfoPtr = nextPtr; + } else { + prevPtr->nextPtr = nextPtr; + } + break; + } + prevPtr = infoPtr; + } + + if (infoPtr != NULL) { + clearProc = infoPtr->clearProc; + clearData = infoPtr->clearData; + ckfree((char *) infoPtr); + } + XSetSelectionOwner(winPtr->display, selection, None, CurrentTime); + + if (clearProc != NULL) { + (*clearProc)(clearData); + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_GetSelection -- + * + * Retrieve the value of a selection and pass it off (in + * pieces, possibly) to a given procedure. + * + * Results: + * The return value is a standard Tcl return value. + * If an error occurs (such as no selection exists) + * then an error message is left in interp->result. + * + * Side effects: + * The standard X11 protocols are used to retrieve the + * selection. When it arrives, it is passed to proc. If + * the selection is very large, it will be passed to proc + * in several pieces. Proc should have the following + * structure: + * + * int + * proc(clientData, interp, portion) + * ClientData clientData; + * Tcl_Interp *interp; + * char *portion; + * { + * } + * + * The interp and clientData arguments to proc will be the + * same as the corresponding arguments to Tk_GetSelection. + * The portion argument points to a character string + * containing part of the selection, and numBytes indicates + * the length of the portion, not including the terminating + * NULL character. If the selection arrives in several pieces, + * the "portion" arguments in separate calls will contain + * successive parts of the selection. Proc should normally + * return TCL_OK. If it detects an error then it should return + * TCL_ERROR and leave an error message in interp->result; the + * remainder of the selection retrieval will be aborted. + * + *-------------------------------------------------------------- + */ + +int +Tk_GetSelection(interp, tkwin, selection, target, proc, clientData) + Tcl_Interp *interp; /* Interpreter to use for reporting + * errors. */ + Tk_Window tkwin; /* Window on whose behalf to retrieve + * the selection (determines display + * from which to retrieve). */ + Atom selection; /* Selection to retrieve. */ + Atom target; /* Desired form in which selection + * is to be returned. */ + Tk_GetSelProc *proc; /* Procedure to call to process the + * selection, once it has been retrieved. */ + ClientData clientData; /* Arbitrary value to pass to proc. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr = winPtr->dispPtr; + TkSelectionInfo *infoPtr; + + if (dispPtr->multipleAtom == None) { + TkSelInit(tkwin); + } + + /* + * If the selection is owned by a window managed by this + * process, then call the retrieval procedure directly, + * rather than going through the X server (it's dangerous + * to go through the X server in this case because it could + * result in deadlock if an INCR-style selection results). + */ + + for (infoPtr = dispPtr->selectionInfoPtr; infoPtr != NULL; + infoPtr = infoPtr->nextPtr) { + if (infoPtr->selection == selection) + break; + } + if (infoPtr != NULL) { + register TkSelHandler *selPtr; + int offset, result, count; + char buffer[TK_SEL_BYTES_AT_ONCE+1]; + TkSelInProgress ip; + + for (selPtr = ((TkWindow *) infoPtr->owner)->selHandlerList; + selPtr != NULL; selPtr = selPtr->nextPtr) { + if ((selPtr->target == target) + && (selPtr->selection == selection)) { + break; + } + } + if (selPtr == NULL) { + Atom type; + + count = TkSelDefaultSelection(infoPtr, target, buffer, + TK_SEL_BYTES_AT_ONCE, &type); + if (count > TK_SEL_BYTES_AT_ONCE) { + panic("selection handler returned too many bytes"); + } + if (count < 0) { + goto cantget; + } + buffer[count] = 0; + result = (*proc)(clientData, interp, buffer); + } else { + offset = 0; + result = TCL_OK; + ip.selPtr = selPtr; + ip.nextPtr = pendingPtr; + pendingPtr = &ip; + while (1) { + count = (selPtr->proc)(selPtr->clientData, offset, buffer, + TK_SEL_BYTES_AT_ONCE); + if ((count < 0) || (ip.selPtr == NULL)) { + pendingPtr = ip.nextPtr; + goto cantget; + } + if (count > TK_SEL_BYTES_AT_ONCE) { + panic("selection handler returned too many bytes"); + } + buffer[count] = '\0'; + result = (*proc)(clientData, interp, buffer); + if ((result != TCL_OK) || (count < TK_SEL_BYTES_AT_ONCE) + || (ip.selPtr == NULL)) { + break; + } + offset += count; + } + pendingPtr = ip.nextPtr; + } + return result; + } + + /* + * The selection is owned by some other process. + */ + + return TkSelGetSelection(interp, tkwin, selection, target, proc, + clientData); + + cantget: + Tcl_AppendResult(interp, Tk_GetAtomName(tkwin, selection), + " selection doesn't exist or form \"", Tk_GetAtomName(tkwin, target), + "\" not defined", (char *) NULL); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * Tk_SelectionCmd -- + * + * This procedure is invoked to process the "selection" Tcl + * command. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_SelectionCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + char *path = NULL; + Atom selection; + char *selName = NULL; + int c, count; + size_t length; + char **args; + + if (argc < 2) { + sprintf(interp->result, + "wrong # args: should be \"%.50s option ?arg arg ...?\"", + argv[0]); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'c') && (strncmp(argv[1], "clear", length) == 0)) { + for (count = argc-2, args = argv+2; count > 0; count -= 2, args += 2) { + if (args[0][0] != '-') { + break; + } + if (count < 2) { + Tcl_AppendResult(interp, "value for \"", *args, + "\" missing", (char *) NULL); + return TCL_ERROR; + } + c = args[0][1]; + length = strlen(args[0]); + if ((c == 'd') && (strncmp(args[0], "-displayof", length) == 0)) { + path = args[1]; + } else if ((c == 's') + && (strncmp(args[0], "-selection", length) == 0)) { + selName = args[1]; + } else { + Tcl_AppendResult(interp, "unknown option \"", args[0], + "\"", (char *) NULL); + return TCL_ERROR; + } + } + if (count == 1) { + path = args[0]; + } else if (count > 1) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " clear ?options?\"", (char *) NULL); + return TCL_ERROR; + } + if (path != NULL) { + tkwin = Tk_NameToWindow(interp, path, tkwin); + } + if (tkwin == NULL) { + return TCL_ERROR; + } + if (selName != NULL) { + selection = Tk_InternAtom(tkwin, selName); + } else { + selection = XA_PRIMARY; + } + + Tk_ClearSelection(tkwin, selection); + return TCL_OK; + } else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) { + Atom target; + char *targetName = NULL; + Tcl_DString selBytes; + int result; + + for (count = argc-2, args = argv+2; count > 0; count -= 2, args += 2) { + if (args[0][0] != '-') { + break; + } + if (count < 2) { + Tcl_AppendResult(interp, "value for \"", *args, + "\" missing", (char *) NULL); + return TCL_ERROR; + } + c = args[0][1]; + length = strlen(args[0]); + if ((c == 'd') && (strncmp(args[0], "-displayof", length) == 0)) { + path = args[1]; + } else if ((c == 's') + && (strncmp(args[0], "-selection", length) == 0)) { + selName = args[1]; + } else if ((c == 't') + && (strncmp(args[0], "-type", length) == 0)) { + targetName = args[1]; + } else { + Tcl_AppendResult(interp, "unknown option \"", args[0], + "\"", (char *) NULL); + return TCL_ERROR; + } + } + if (path != NULL) { + tkwin = Tk_NameToWindow(interp, path, tkwin); + } + if (tkwin == NULL) { + return TCL_ERROR; + } + if (selName != NULL) { + selection = Tk_InternAtom(tkwin, selName); + } else { + selection = XA_PRIMARY; + } + if (count > 1) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " get ?options?\"", (char *) NULL); + return TCL_ERROR; + } else if (count == 1) { + target = Tk_InternAtom(tkwin, args[0]); + } else if (targetName != NULL) { + target = Tk_InternAtom(tkwin, targetName); + } else { + target = XA_STRING; + } + + Tcl_DStringInit(&selBytes); + result = Tk_GetSelection(interp, tkwin, selection, target, SelGetProc, + (ClientData) &selBytes); + if (result == TCL_OK) { + Tcl_DStringResult(interp, &selBytes); + } else { + Tcl_DStringFree(&selBytes); + } + return result; + } else if ((c == 'h') && (strncmp(argv[1], "handle", length) == 0)) { + Atom target, format; + char *targetName = NULL; + char *formatName = NULL; + register CommandInfo *cmdInfoPtr; + int cmdLength; + + for (count = argc-2, args = argv+2; count > 0; count -= 2, args += 2) { + if (args[0][0] != '-') { + break; + } + if (count < 2) { + Tcl_AppendResult(interp, "value for \"", *args, + "\" missing", (char *) NULL); + return TCL_ERROR; + } + c = args[0][1]; + length = strlen(args[0]); + if ((c == 'f') && (strncmp(args[0], "-format", length) == 0)) { + formatName = args[1]; + } else if ((c == 's') + && (strncmp(args[0], "-selection", length) == 0)) { + selName = args[1]; + } else if ((c == 't') + && (strncmp(args[0], "-type", length) == 0)) { + targetName = args[1]; + } else { + Tcl_AppendResult(interp, "unknown option \"", args[0], + "\"", (char *) NULL); + return TCL_ERROR; + } + } + + if ((count < 2) || (count > 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " handle ?options? window command\"", (char *) NULL); + return TCL_ERROR; + } + tkwin = Tk_NameToWindow(interp, args[0], tkwin); + if (tkwin == NULL) { + return TCL_ERROR; + } + if (selName != NULL) { + selection = Tk_InternAtom(tkwin, selName); + } else { + selection = XA_PRIMARY; + } + + if (count > 2) { + target = Tk_InternAtom(tkwin, args[2]); + } else if (targetName != NULL) { + target = Tk_InternAtom(tkwin, targetName); + } else { + target = XA_STRING; + } + if (count > 3) { + format = Tk_InternAtom(tkwin, args[3]); + } else if (formatName != NULL) { + format = Tk_InternAtom(tkwin, formatName); + } else { + format = XA_STRING; + } + cmdLength = strlen(args[1]); + if (cmdLength == 0) { + Tk_DeleteSelHandler(tkwin, selection, target); + } else { + cmdInfoPtr = (CommandInfo *) ckalloc((unsigned) ( + sizeof(CommandInfo) - 3 + cmdLength)); + cmdInfoPtr->interp = interp; + cmdInfoPtr->cmdLength = cmdLength; + strcpy(cmdInfoPtr->command, args[1]); + Tk_CreateSelHandler(tkwin, selection, target, HandleTclCommand, + (ClientData) cmdInfoPtr, format); + } + return TCL_OK; + } else if ((c == 'o') && (strncmp(argv[1], "own", length) == 0)) { + register LostCommand *lostPtr; + char *script = NULL; + int cmdLength; + + for (count = argc-2, args = argv+2; count > 0; count -= 2, args += 2) { + if (args[0][0] != '-') { + break; + } + if (count < 2) { + Tcl_AppendResult(interp, "value for \"", *args, + "\" missing", (char *) NULL); + return TCL_ERROR; + } + c = args[0][1]; + length = strlen(args[0]); + if ((c == 'c') && (strncmp(args[0], "-command", length) == 0)) { + script = args[1]; + } else if ((c == 'd') + && (strncmp(args[0], "-displayof", length) == 0)) { + path = args[1]; + } else if ((c == 's') + && (strncmp(args[0], "-selection", length) == 0)) { + selName = args[1]; + } else { + Tcl_AppendResult(interp, "unknown option \"", args[0], + "\"", (char *) NULL); + return TCL_ERROR; + } + } + + if (count > 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " own ?options? ?window?\"", (char *) NULL); + return TCL_ERROR; + } + if (selName != NULL) { + selection = Tk_InternAtom(tkwin, selName); + } else { + selection = XA_PRIMARY; + } + if (count == 0) { + TkSelectionInfo *infoPtr; + TkWindow *winPtr; + if (path != NULL) { + tkwin = Tk_NameToWindow(interp, path, tkwin); + } + if (tkwin == NULL) { + return TCL_ERROR; + } + winPtr = (TkWindow *)tkwin; + for (infoPtr = winPtr->dispPtr->selectionInfoPtr; infoPtr != NULL; + infoPtr = infoPtr->nextPtr) { + if (infoPtr->selection == selection) + break; + } + + /* + * Ignore the internal clipboard window. + */ + + if ((infoPtr != NULL) + && (infoPtr->owner != winPtr->dispPtr->clipWindow)) { + interp->result = Tk_PathName(infoPtr->owner); + } + return TCL_OK; + } + tkwin = Tk_NameToWindow(interp, args[0], tkwin); + if (tkwin == NULL) { + return TCL_ERROR; + } + if (count == 2) { + script = args[1]; + } + if (script == NULL) { + Tk_OwnSelection(tkwin, selection, (Tk_LostSelProc *) NULL, + (ClientData) NULL); + return TCL_OK; + } + cmdLength = strlen(script); + lostPtr = (LostCommand *) ckalloc((unsigned) (sizeof(LostCommand) + -3 + cmdLength)); + lostPtr->interp = interp; + strcpy(lostPtr->command, script); + Tk_OwnSelection(tkwin, selection, LostSelection, (ClientData) lostPtr); + return TCL_OK; + } else { + sprintf(interp->result, + "bad option \"%.50s\": must be clear, get, handle, or own", + argv[1]); + return TCL_ERROR; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkSelDeadWindow -- + * + * This procedure is invoked just before a TkWindow is deleted. + * It performs selection-related cleanup. + * + * Results: + * None. + * + * Side effects: + * Frees up memory associated with the selection. + * + *---------------------------------------------------------------------- + */ + +void +TkSelDeadWindow(winPtr) + register TkWindow *winPtr; /* Window that's being deleted. */ +{ + register TkSelHandler *selPtr; + register TkSelInProgress *ipPtr; + TkSelectionInfo *infoPtr, *prevPtr, *nextPtr; + + /* + * While deleting all the handlers, be careful to check whether + * ConvertSelection or TkSelPropProc are about to process one of the + * deleted handlers. + */ + + while (winPtr->selHandlerList != NULL) { + selPtr = winPtr->selHandlerList; + winPtr->selHandlerList = selPtr->nextPtr; + for (ipPtr = pendingPtr; ipPtr != NULL; ipPtr = ipPtr->nextPtr) { + if (ipPtr->selPtr == selPtr) { + ipPtr->selPtr = NULL; + } + } + if (selPtr->proc == HandleTclCommand) { + ckfree((char *) selPtr->clientData); + } + ckfree((char *) selPtr); + } + + /* + * Remove selections owned by window being deleted. + */ + + for (infoPtr = winPtr->dispPtr->selectionInfoPtr, prevPtr = NULL; + infoPtr != NULL; infoPtr = nextPtr) { + nextPtr = infoPtr->nextPtr; + if (infoPtr->owner == (Tk_Window) winPtr) { + if (infoPtr->clearProc == LostSelection) { + ckfree((char *) infoPtr->clearData); + } + ckfree((char *) infoPtr); + infoPtr = prevPtr; + if (prevPtr == NULL) { + winPtr->dispPtr->selectionInfoPtr = nextPtr; + } else { + prevPtr->nextPtr = nextPtr; + } + } + prevPtr = infoPtr; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkSelInit -- + * + * Initialize selection-related information for a display. + * + * Results: + * None. + * + * Side effects: + * Selection-related information is initialized. + * + *---------------------------------------------------------------------- + */ + +void +TkSelInit(tkwin) + Tk_Window tkwin; /* Window token (used to find + * display to initialize). */ +{ + register TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr; + + /* + * Fetch commonly-used atoms. + */ + + dispPtr->multipleAtom = Tk_InternAtom(tkwin, "MULTIPLE"); + dispPtr->incrAtom = Tk_InternAtom(tkwin, "INCR"); + dispPtr->targetsAtom = Tk_InternAtom(tkwin, "TARGETS"); + dispPtr->timestampAtom = Tk_InternAtom(tkwin, "TIMESTAMP"); + dispPtr->textAtom = Tk_InternAtom(tkwin, "TEXT"); + dispPtr->compoundTextAtom = Tk_InternAtom(tkwin, "COMPOUND_TEXT"); + dispPtr->applicationAtom = Tk_InternAtom(tkwin, "TK_APPLICATION"); + dispPtr->windowAtom = Tk_InternAtom(tkwin, "TK_WINDOW"); + dispPtr->clipboardAtom = Tk_InternAtom(tkwin, "CLIPBOARD"); +} + +/* + *---------------------------------------------------------------------- + * + * TkSelClearSelection -- + * + * This procedure is invoked to process a SelectionClear event. + * + * Results: + * None. + * + * Side effects: + * Invokes the clear procedure for the window which lost the + * selection. + * + *---------------------------------------------------------------------- + */ + +void +TkSelClearSelection(tkwin, eventPtr) + Tk_Window tkwin; /* Window for which event was targeted. */ + register XEvent *eventPtr; /* X SelectionClear event. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr = winPtr->dispPtr; + TkSelectionInfo *infoPtr; + TkSelectionInfo *prevPtr; + + /* + * Invoke clear procedure for window that just lost the selection. This + * code is a bit tricky, because any callbacks due to selection changes + * between windows managed by the process have already been made. Thus, + * ignore the event unless it refers to the window that's currently the + * selection owner and the event was generated after the server saw the + * SetSelectionOwner request. + */ + + for (infoPtr = dispPtr->selectionInfoPtr, prevPtr = NULL; + infoPtr != NULL; infoPtr = infoPtr->nextPtr) { + if (infoPtr->selection == eventPtr->xselectionclear.selection) { + break; + } + prevPtr = infoPtr; + } + + if (infoPtr != NULL && (infoPtr->owner == tkwin) + && (eventPtr->xselectionclear.serial >= (unsigned) infoPtr->serial)) { + if (prevPtr == NULL) { + dispPtr->selectionInfoPtr = infoPtr->nextPtr; + } else { + prevPtr->nextPtr = infoPtr->nextPtr; + } + + /* + * Because of reentrancy problems, calling clearProc must be done + * after the infoPtr has been removed from the selectionInfoPtr + * list (clearProc could modify the list, e.g. by creating + * a new selection). + */ + + if (infoPtr->clearProc != NULL) { + (*infoPtr->clearProc)(infoPtr->clearData); + } + ckfree((char *) infoPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * SelGetProc -- + * + * This procedure is invoked to process pieces of the selection + * as they arrive during "selection get" commands. + * + * Results: + * Always returns TCL_OK. + * + * Side effects: + * Bytes get appended to the dynamic string pointed to by the + * clientData argument. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +SelGetProc(clientData, interp, portion) + ClientData clientData; /* Dynamic string holding partially + * assembled selection. */ + Tcl_Interp *interp; /* Interpreter used for error + * reporting (not used). */ + char *portion; /* New information to be appended. */ +{ + Tcl_DStringAppend((Tcl_DString *) clientData, portion, -1); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * HandleTclCommand -- + * + * This procedure acts as selection handler for handlers created + * by the "selection handle" command. It invokes a Tcl command to + * retrieve the selection. + * + * Results: + * The return value is a count of the number of bytes actually + * stored at buffer, or -1 if an error occurs while executing + * the Tcl command to retrieve the selection. + * + * Side effects: + * None except for things done by the Tcl command. + * + *---------------------------------------------------------------------- + */ + +static int +HandleTclCommand(clientData, offset, buffer, maxBytes) + ClientData clientData; /* Information about command to execute. */ + int offset; /* Return selection bytes starting at this + * offset. */ + char *buffer; /* Place to store converted selection. */ + int maxBytes; /* Maximum # of bytes to store at buffer. */ +{ + CommandInfo *cmdInfoPtr = (CommandInfo *) clientData; + int spaceNeeded, length; +#define MAX_STATIC_SIZE 100 + char staticSpace[MAX_STATIC_SIZE]; + char *command; + Tcl_Interp *interp; + Tcl_DString oldResult; + + /* + * We must copy the interpreter pointer from CommandInfo because the + * command could delete the handler, freeing the CommandInfo data before we + * are done using it. We must also protect the interpreter from being + * deleted too soo. + */ + + interp = cmdInfoPtr->interp; + Tcl_Preserve((ClientData) interp); + + /* + * First, generate a command by taking the command string + * and appending the offset and maximum # of bytes. + */ + + spaceNeeded = cmdInfoPtr->cmdLength + 30; + if (spaceNeeded < MAX_STATIC_SIZE) { + command = staticSpace; + } else { + command = (char *) ckalloc((unsigned) spaceNeeded); + } + sprintf(command, "%s %d %d", cmdInfoPtr->command, offset, maxBytes); + + /* + * Execute the command. Be sure to restore the state of the + * interpreter after executing the command. + */ + + Tcl_DStringInit(&oldResult); + Tcl_DStringGetResult(interp, &oldResult); + if (TkCopyAndGlobalEval(interp, command) == TCL_OK) { + length = strlen(interp->result); + if (length > maxBytes) { + length = maxBytes; + } + memcpy((VOID *) buffer, (VOID *) interp->result, (size_t) length); + buffer[length] = '\0'; + } else { + length = -1; + } + Tcl_DStringResult(interp, &oldResult); + + if (command != staticSpace) { + ckfree(command); + } + + Tcl_Release((ClientData) interp); + return length; +} + +/* + *---------------------------------------------------------------------- + * + * TkSelDefaultSelection -- + * + * This procedure is called to generate selection information + * for a few standard targets such as TIMESTAMP and TARGETS. + * It is invoked only if no handler has been declared by the + * application. + * + * Results: + * If "target" is a standard target understood by this procedure, + * the selection is converted to that form and stored as a + * character string in buffer. The type of the selection (e.g. + * STRING or ATOM) is stored in *typePtr, and the return value is + * a count of the # of non-NULL bytes at buffer. If the target + * wasn't understood, or if there isn't enough space at buffer + * to hold the entire selection (no INCR-mode transfers for this + * stuff!), then -1 is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkSelDefaultSelection(infoPtr, target, buffer, maxBytes, typePtr) + TkSelectionInfo *infoPtr; /* Info about selection being retrieved. */ + Atom target; /* Desired form of selection. */ + char *buffer; /* Place to put selection characters. */ + int maxBytes; /* Maximum # of bytes to store at buffer. */ + Atom *typePtr; /* Store here the type of the selection, + * for use in converting to proper X format. */ +{ + register TkWindow *winPtr = (TkWindow *) infoPtr->owner; + TkDisplay *dispPtr = winPtr->dispPtr; + + if (target == dispPtr->timestampAtom) { + if (maxBytes < 20) { + return -1; + } + sprintf(buffer, "0x%x", (unsigned int) infoPtr->time); + *typePtr = XA_INTEGER; + return strlen(buffer); + } + + if (target == dispPtr->targetsAtom) { + register TkSelHandler *selPtr; + char *atomString; + int length, atomLength; + + if (maxBytes < 50) { + return -1; + } + strcpy(buffer, "MULTIPLE TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW"); + length = strlen(buffer); + for (selPtr = winPtr->selHandlerList; selPtr != NULL; + selPtr = selPtr->nextPtr) { + if ((selPtr->selection == infoPtr->selection) + && (selPtr->target != dispPtr->applicationAtom) + && (selPtr->target != dispPtr->windowAtom)) { + atomString = Tk_GetAtomName((Tk_Window) winPtr, + selPtr->target); + atomLength = strlen(atomString) + 1; + if ((length + atomLength) >= maxBytes) { + return -1; + } + sprintf(buffer+length, " %s", atomString); + length += atomLength; + } + } + *typePtr = XA_ATOM; + return length; + } + + if (target == dispPtr->applicationAtom) { + int length; + char *name = winPtr->mainPtr->winPtr->nameUid; + + length = strlen(name); + if (maxBytes <= length) { + return -1; + } + strcpy(buffer, name); + *typePtr = XA_STRING; + return length; + } + + if (target == dispPtr->windowAtom) { + int length; + char *name = winPtr->pathName; + + length = strlen(name); + if (maxBytes <= length) { + return -1; + } + strcpy(buffer, name); + *typePtr = XA_STRING; + return length; + } + + return -1; +} + +/* + *---------------------------------------------------------------------- + * + * LostSelection -- + * + * This procedure is invoked when a window has lost ownership of + * the selection and the ownership was claimed with the command + * "selection own". + * + * Results: + * None. + * + * Side effects: + * A Tcl script is executed; it can do almost anything. + * + *---------------------------------------------------------------------- + */ + +static void +LostSelection(clientData) + ClientData clientData; /* Pointer to CommandInfo structure. */ +{ + LostCommand *lostPtr = (LostCommand *) clientData; + char *oldResultString; + Tcl_FreeProc *oldFreeProc; + Tcl_Interp *interp; + + interp = lostPtr->interp; + Tcl_Preserve((ClientData) interp); + + /* + * Execute the command. Save the interpreter's result, if any, and + * restore it after executing the command. + */ + + oldFreeProc = interp->freeProc; + if (oldFreeProc != TCL_STATIC) { + oldResultString = interp->result; + } else { + oldResultString = (char *) ckalloc((unsigned) + (strlen(interp->result) + 1)); + strcpy(oldResultString, interp->result); + oldFreeProc = TCL_DYNAMIC; + } + interp->freeProc = TCL_STATIC; + if (TkCopyAndGlobalEval(interp, lostPtr->command) != TCL_OK) { + Tcl_BackgroundError(interp); + } + Tcl_FreeResult(interp); + interp->result = oldResultString; + interp->freeProc = oldFreeProc; + + Tcl_Release((ClientData) interp); + + /* + * Free the storage for the command, since we're done with it now. + */ + + ckfree((char *) lostPtr); +} diff --git a/generic/tkSelect.h b/generic/tkSelect.h new file mode 100644 index 0000000..8595599 --- /dev/null +++ b/generic/tkSelect.h @@ -0,0 +1,184 @@ +/* + * tkSelect.h -- + * + * Declarations of types shared among the files that implement + * selection support. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkSelect.h 1.4 95/11/03 13:22:41 + */ + +#ifndef _TKSELECT +#define _TKSELECT + +/* + * When a selection is owned by a window on a given display, one of the + * following structures is present on a list of current selections in the + * display structure. The structure is used to record the current owner of + * a selection for use in later retrieval requests. There is a list of + * such structures because a display can have multiple different selections + * active at the same time. + */ + +typedef struct TkSelectionInfo { + Atom selection; /* Selection name, e.g. XA_PRIMARY. */ + Tk_Window owner; /* Current owner of this selection. */ + int serial; /* Serial number of last XSelectionSetOwner + * request made to server for this + * selection (used to filter out redundant + * SelectionClear events). */ + Time time; /* Timestamp used to acquire selection. */ + Tk_LostSelProc *clearProc; /* Procedure to call when owner loses + * selection. */ + ClientData clearData; /* Info to pass to clearProc. */ + struct TkSelectionInfo *nextPtr; + /* Next in list of current selections on + * this display. NULL means end of list */ +} TkSelectionInfo; + +/* + * One of the following structures exists for each selection handler + * created for a window by calling Tk_CreateSelHandler. The handlers + * are linked in a list rooted in the TkWindow structure. + */ + +typedef struct TkSelHandler { + Atom selection; /* Selection name, e.g. XA_PRIMARY */ + Atom target; /* Target type for selection + * conversion, such as TARGETS or + * STRING. */ + Atom format; /* Format in which selection + * info will be returned, such + * as STRING or ATOM. */ + Tk_SelectionProc *proc; /* Procedure to generate selection + * in this format. */ + ClientData clientData; /* Argument to pass to proc. */ + int size; /* Size of units returned by proc + * (8 for STRING, 32 for almost + * anything else). */ + struct TkSelHandler *nextPtr; + /* Next selection handler associated + * with same window (NULL for end of + * list). */ +} TkSelHandler; + +/* + * When the selection is being retrieved, one of the following + * structures is present on a list of pending selection retrievals. + * The structure is used to communicate between the background + * procedure that requests the selection and the foreground + * event handler that processes the events in which the selection + * is returned. There is a list of such structures so that there + * can be multiple simultaneous selection retrievals (e.g. on + * different displays). + */ + +typedef struct TkSelRetrievalInfo { + Tcl_Interp *interp; /* Interpreter for error reporting. */ + TkWindow *winPtr; /* Window used as requestor for + * selection. */ + Atom selection; /* Selection being requested. */ + Atom property; /* Property where selection will appear. */ + Atom target; /* Desired form for selection. */ + int (*proc) _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, + char *portion)); /* Procedure to call to handle pieces + * of selection. */ + ClientData clientData; /* Argument for proc. */ + int result; /* Initially -1. Set to a Tcl + * return value once the selection + * has been retrieved. */ + Tcl_TimerToken timeout; /* Token for current timeout procedure. */ + int idleTime; /* Number of seconds that have gone by + * without hearing anything from the + * selection owner. */ + struct TkSelRetrievalInfo *nextPtr; + /* Next in list of all pending + * selection retrievals. NULL means + * end of list. */ +} TkSelRetrievalInfo; + +/* + * The clipboard contains a list of buffers of various types and formats. + * All of the buffers of a given type will be returned in sequence when the + * CLIPBOARD selection is retrieved. All buffers of a given type on the + * same clipboard must have the same format. The TkClipboardTarget structure + * is used to record the information about a chain of buffers of the same + * type. + */ + +typedef struct TkClipboardBuffer { + char *buffer; /* Null terminated data buffer. */ + long length; /* Length of string in buffer. */ + struct TkClipboardBuffer *nextPtr; /* Next in list of buffers. NULL + * means end of list . */ +} TkClipboardBuffer; + +typedef struct TkClipboardTarget { + Atom type; /* Type conversion supported. */ + Atom format; /* Representation used for data. */ + TkClipboardBuffer *firstBufferPtr; /* First in list of data buffers. */ + TkClipboardBuffer *lastBufferPtr; /* Last in list of clipboard buffers. + * Used to speed up appends. */ + struct TkClipboardTarget *nextPtr; /* Next in list of targets on + * clipboard. NULL means end of + * list. */ +} TkClipboardTarget; + +/* + * It is possible for a Tk_SelectionProc to delete the handler that it + * represents. If this happens, the code that is retrieving the selection + * needs to know about it so it doesn't use the now-defunct handler + * structure. One structure of the following form is created for each + * retrieval in progress, so that the retriever can find out if its + * handler is deleted. All of the pending retrievals (if there are more + * than one) are linked into a list. + */ + +typedef struct TkSelInProgress { + TkSelHandler *selPtr; /* Handler being executed. If this handler + * is deleted, the field is set to NULL. */ + struct TkSelInProgress *nextPtr; + /* Next higher nested search. */ +} TkSelInProgress; + +/* + * Declarations for variables shared among the selection-related files: + */ + +extern TkSelInProgress *pendingPtr; + /* Topmost search in progress, or + * NULL if none. */ + +/* + * Chunk size for retrieving selection. It's defined both in + * words and in bytes; the word size is used to allocate + * buffer space that's guaranteed to be word-aligned and that + * has an extra character for the terminating NULL. + */ + +#define TK_SEL_BYTES_AT_ONCE 4000 +#define TK_SEL_WORDS_AT_ONCE 1001 + +/* + * Declarations for procedures that are used by the selection-related files + * but shouldn't be used anywhere else in Tk (or by Tk clients): + */ + +extern void TkSelClearSelection _ANSI_ARGS_((Tk_Window tkwin, + XEvent *eventPtr)); +extern int TkSelDefaultSelection _ANSI_ARGS_(( + TkSelectionInfo *infoPtr, Atom target, + char *buffer, int maxBytes, Atom *typePtr)); +extern int TkSelGetSelection _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, Atom selection, Atom target, + Tk_GetSelProc *proc, ClientData clientData)); +#ifndef TkSelUpdateClipboard +extern void TkSelUpdateClipboard _ANSI_ARGS_((TkWindow *winPtr, + TkClipboardTarget *targetPtr)); +#endif + +#endif /* _TKSELECT */ diff --git a/generic/tkSquare.c b/generic/tkSquare.c new file mode 100644 index 0000000..eff8181 --- /dev/null +++ b/generic/tkSquare.c @@ -0,0 +1,587 @@ +/* + * tkSquare.c -- + * + * This module implements "square" widgets. A "square" is + * a widget that displays a single square that can be moved + * around and resized. This file is intended as an example + * of how to build a widget; it isn't included in the + * normal wish, but it is included in "tktest". + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkSquare.c 1.19 97/07/31 09:13:13 + */ + +#include "tkPort.h" +#include "tk.h" + +/* + * A data structure of the following type is kept for each square + * widget managed by this file: + */ + +typedef struct { + Tk_Window tkwin; /* Window that embodies the square. NULL + * means window has been deleted but + * widget record hasn't been cleaned up yet. */ + Display *display; /* X's token for the window's display. */ + Tcl_Interp *interp; /* Interpreter associated with widget. */ + Tcl_Command widgetCmd; /* Token for square's widget command. */ + int x, y; /* Position of square's upper-left corner + * within widget. */ + int size; /* Width and height of square. */ + + /* + * Information used when displaying widget: + */ + + int borderWidth; /* Width of 3-D border around whole widget. */ + Tk_3DBorder bgBorder; /* Used for drawing background. */ + Tk_3DBorder fgBorder; /* For drawing square. */ + int relief; /* Indicates whether window as a whole is + * raised, sunken, or flat. */ + GC gc; /* Graphics context for copying from + * off-screen pixmap onto screen. */ + int doubleBuffer; /* Non-zero means double-buffer redisplay + * with pixmap; zero means draw straight + * onto the display. */ + int updatePending; /* Non-zero means a call to SquareDisplay + * has already been scheduled. */ +} Square; + +/* + * Information used for argv parsing. + */ + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_BORDER, "-background", "background", "Background", + "#d9d9d9", Tk_Offset(Square, bgBorder), TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + "white", Tk_Offset(Square, bgBorder), TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + "2", Tk_Offset(Square, borderWidth), 0}, + {TK_CONFIG_INT, "-dbl", "doubleBuffer", "DoubleBuffer", + "1", Tk_Offset(Square, doubleBuffer), 0}, + {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_BORDER, "-foreground", "foreground", "Foreground", + "#b03060", Tk_Offset(Square, fgBorder), TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-foreground", "foreground", "Foreground", + "black", Tk_Offset(Square, fgBorder), TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + "raised", Tk_Offset(Square, relief), 0}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +int SquareCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void SquareCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static int SquareConfigure _ANSI_ARGS_((Tcl_Interp *interp, + Square *squarePtr, int argc, char **argv, + int flags)); +static void SquareDestroy _ANSI_ARGS_((char *memPtr)); +static void SquareDisplay _ANSI_ARGS_((ClientData clientData)); +static void KeepInWindow _ANSI_ARGS_((Square *squarePtr)); +static void SquareEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int SquareWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *, int argc, char **argv)); + +/* + *-------------------------------------------------------------- + * + * SquareCmd -- + * + * This procedure is invoked to process the "square" Tcl + * command. It creates a new "square" widget. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * A new widget is created and configured. + * + *-------------------------------------------------------------- + */ + +int +SquareCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window main = (Tk_Window) clientData; + Square *squarePtr; + Tk_Window tkwin; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + tkwin = Tk_CreateWindowFromPath(interp, main, argv[1], (char *) NULL); + if (tkwin == NULL) { + return TCL_ERROR; + } + Tk_SetClass(tkwin, "Square"); + + /* + * Allocate and initialize the widget record. + */ + + squarePtr = (Square *) ckalloc(sizeof(Square)); + squarePtr->tkwin = tkwin; + squarePtr->display = Tk_Display(tkwin); + squarePtr->interp = interp; + squarePtr->widgetCmd = Tcl_CreateCommand(interp, + Tk_PathName(squarePtr->tkwin), SquareWidgetCmd, + (ClientData) squarePtr, SquareCmdDeletedProc); + squarePtr->x = 0; + squarePtr->y = 0; + squarePtr->size = 20; + squarePtr->borderWidth = 0; + squarePtr->bgBorder = NULL; + squarePtr->fgBorder = NULL; + squarePtr->relief = TK_RELIEF_FLAT; + squarePtr->gc = None; + squarePtr->doubleBuffer = 1; + squarePtr->updatePending = 0; + + Tk_CreateEventHandler(squarePtr->tkwin, ExposureMask|StructureNotifyMask, + SquareEventProc, (ClientData) squarePtr); + if (SquareConfigure(interp, squarePtr, argc-2, argv+2, 0) != TCL_OK) { + Tk_DestroyWindow(squarePtr->tkwin); + return TCL_ERROR; + } + + interp->result = Tk_PathName(squarePtr->tkwin); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * SquareWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a widget managed by this module. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +SquareWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about square widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Square *squarePtr = (Square *) clientData; + int result = TCL_OK; + size_t length; + char c; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) squarePtr); + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + goto error; + } + result = Tk_ConfigureValue(interp, squarePtr->tkwin, configSpecs, + (char *) squarePtr, argv[2], 0); + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 2)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, squarePtr->tkwin, configSpecs, + (char *) squarePtr, (char *) NULL, 0); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, squarePtr->tkwin, configSpecs, + (char *) squarePtr, argv[2], 0); + } else { + result = SquareConfigure(interp, squarePtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else if ((c == 'p') && (strncmp(argv[1], "position", length) == 0)) { + if ((argc != 2) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " position ?x y?\"", (char *) NULL); + goto error; + } + if (argc == 4) { + if ((Tk_GetPixels(interp, squarePtr->tkwin, argv[2], + &squarePtr->x) != TCL_OK) || (Tk_GetPixels(interp, + squarePtr->tkwin, argv[3], &squarePtr->y) != TCL_OK)) { + goto error; + } + KeepInWindow(squarePtr); + } + sprintf(interp->result, "%d %d", squarePtr->x, squarePtr->y); + } else if ((c == 's') && (strncmp(argv[1], "size", length) == 0)) { + if ((argc != 2) && (argc != 3)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " size ?amount?\"", (char *) NULL); + goto error; + } + if (argc == 3) { + int i; + + if (Tk_GetPixels(interp, squarePtr->tkwin, argv[2], &i) != TCL_OK) { + goto error; + } + if ((i <= 0) || (i > 100)) { + Tcl_AppendResult(interp, "bad size \"", argv[2], + "\"", (char *) NULL); + goto error; + } + squarePtr->size = i; + KeepInWindow(squarePtr); + } + sprintf(interp->result, "%d", squarePtr->size); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be cget, configure, position, or size", + (char *) NULL); + goto error; + } + if (!squarePtr->updatePending) { + Tcl_DoWhenIdle(SquareDisplay, (ClientData) squarePtr); + squarePtr->updatePending = 1; + } + Tcl_Release((ClientData) squarePtr); + return result; + + error: + Tcl_Release((ClientData) squarePtr); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * SquareConfigure -- + * + * This procedure is called to process an argv/argc list in + * conjunction with the Tk option database to configure (or + * reconfigure) a square widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as colors, border width, + * etc. get set for squarePtr; old resources get freed, + * if there were any. + * + *---------------------------------------------------------------------- + */ + +static int +SquareConfigure(interp, squarePtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + Square *squarePtr; /* Information about widget. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to + * Tk_ConfigureWidget. */ +{ + if (Tk_ConfigureWidget(interp, squarePtr->tkwin, configSpecs, + argc, argv, (char *) squarePtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * Set the background for the window and create a graphics context + * for use during redisplay. + */ + + Tk_SetWindowBackground(squarePtr->tkwin, + Tk_3DBorderColor(squarePtr->bgBorder)->pixel); + if ((squarePtr->gc == None) && (squarePtr->doubleBuffer)) { + XGCValues gcValues; + gcValues.function = GXcopy; + gcValues.graphics_exposures = False; + squarePtr->gc = Tk_GetGC(squarePtr->tkwin, + GCFunction|GCGraphicsExposures, &gcValues); + } + + /* + * Register the desired geometry for the window. Then arrange for + * the window to be redisplayed. + */ + + Tk_GeometryRequest(squarePtr->tkwin, 200, 150); + Tk_SetInternalBorder(squarePtr->tkwin, squarePtr->borderWidth); + if (!squarePtr->updatePending) { + Tcl_DoWhenIdle(SquareDisplay, (ClientData) squarePtr); + squarePtr->updatePending = 1; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * SquareEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on squares. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +SquareEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + Square *squarePtr = (Square *) clientData; + + if (eventPtr->type == Expose) { + if (!squarePtr->updatePending) { + Tcl_DoWhenIdle(SquareDisplay, (ClientData) squarePtr); + squarePtr->updatePending = 1; + } + } else if (eventPtr->type == ConfigureNotify) { + KeepInWindow(squarePtr); + if (!squarePtr->updatePending) { + Tcl_DoWhenIdle(SquareDisplay, (ClientData) squarePtr); + squarePtr->updatePending = 1; + } + } else if (eventPtr->type == DestroyNotify) { + if (squarePtr->tkwin != NULL) { + squarePtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(squarePtr->interp, + squarePtr->widgetCmd); + } + if (squarePtr->updatePending) { + Tcl_CancelIdleCall(SquareDisplay, (ClientData) squarePtr); + } + Tcl_EventuallyFree((ClientData) squarePtr, SquareDestroy); + } +} + +/* + *---------------------------------------------------------------------- + * + * SquareCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +SquareCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + Square *squarePtr = (Square *) clientData; + Tk_Window tkwin = squarePtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + squarePtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *-------------------------------------------------------------- + * + * SquareDisplay -- + * + * This procedure redraws the contents of a square window. + * It is invoked as a do-when-idle handler, so it only runs + * when there's nothing else for the application to do. + * + * Results: + * None. + * + * Side effects: + * Information appears on the screen. + * + *-------------------------------------------------------------- + */ + +static void +SquareDisplay(clientData) + ClientData clientData; /* Information about window. */ +{ + Square *squarePtr = (Square *) clientData; + Tk_Window tkwin = squarePtr->tkwin; + Pixmap pm = None; + Drawable d; + + squarePtr->updatePending = 0; + if (!Tk_IsMapped(tkwin)) { + return; + } + + /* + * Create a pixmap for double-buffering, if necessary. + */ + + if (squarePtr->doubleBuffer) { + pm = Tk_GetPixmap(Tk_Display(tkwin), Tk_WindowId(tkwin), + Tk_Width(tkwin), Tk_Height(tkwin), + DefaultDepthOfScreen(Tk_Screen(tkwin))); + d = pm; + } else { + d = Tk_WindowId(tkwin); + } + + /* + * Redraw the widget's background and border. + */ + + Tk_Fill3DRectangle(tkwin, d, squarePtr->bgBorder, 0, 0, Tk_Width(tkwin), + Tk_Height(tkwin), squarePtr->borderWidth, squarePtr->relief); + + /* + * Display the square. + */ + + Tk_Fill3DRectangle(tkwin, d, squarePtr->fgBorder, squarePtr->x, + squarePtr->y, squarePtr->size, squarePtr->size, + squarePtr->borderWidth, TK_RELIEF_RAISED); + + /* + * If double-buffered, copy to the screen and release the pixmap. + */ + + if (squarePtr->doubleBuffer) { + XCopyArea(Tk_Display(tkwin), pm, Tk_WindowId(tkwin), squarePtr->gc, + 0, 0, (unsigned) Tk_Width(tkwin), (unsigned) Tk_Height(tkwin), + 0, 0); + Tk_FreePixmap(Tk_Display(tkwin), pm); + } +} + +/* + *---------------------------------------------------------------------- + * + * SquareDestroy -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a square at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the square is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +SquareDestroy(memPtr) + char *memPtr; /* Info about square widget. */ +{ + Square *squarePtr = (Square *) memPtr; + + Tk_FreeOptions(configSpecs, (char *) squarePtr, squarePtr->display, 0); + if (squarePtr->gc != None) { + Tk_FreeGC(squarePtr->display, squarePtr->gc); + } + ckfree((char *) squarePtr); +} + +/* + *---------------------------------------------------------------------- + * + * KeepInWindow -- + * + * Adjust the position of the square if necessary to keep it in + * the widget's window. + * + * Results: + * None. + * + * Side effects: + * The x and y position of the square are adjusted if necessary + * to keep the square in the window. + * + *---------------------------------------------------------------------- + */ + +static void +KeepInWindow(squarePtr) + register Square *squarePtr; /* Pointer to widget record. */ +{ + int i, bd; + bd = 0; + if (squarePtr->relief != TK_RELIEF_FLAT) { + bd = squarePtr->borderWidth; + } + i = (Tk_Width(squarePtr->tkwin) - bd) - (squarePtr->x + squarePtr->size); + if (i < 0) { + squarePtr->x += i; + } + i = (Tk_Height(squarePtr->tkwin) - bd) - (squarePtr->y + squarePtr->size); + if (i < 0) { + squarePtr->y += i; + } + if (squarePtr->x < bd) { + squarePtr->x = bd; + } + if (squarePtr->y < bd) { + squarePtr->y = bd; + } +} diff --git a/generic/tkTest.c b/generic/tkTest.c new file mode 100644 index 0000000..dab43d0 --- /dev/null +++ b/generic/tkTest.c @@ -0,0 +1,1134 @@ +/* + * tkTest.c -- + * + * This file contains C command procedures for a bunch of additional + * Tcl commands that are used for testing out Tcl's C interfaces. + * These commands are not normally included in Tcl applications; + * they're only used for testing. + * + * Copyright (c) 1993-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkTest.c 1.50 97/11/06 16:56:32 + */ + +#include "tkInt.h" +#include "tkPort.h" + +#ifdef __WIN32__ +#include "tkWinInt.h" +#endif + +#ifdef MAC_TCL +#include "tkScrollbar.h" +#endif + +#ifdef __UNIX__ +#include "tkUnixInt.h" +#endif + +/* + * The following data structure represents the master for a test + * image: + */ + +typedef struct TImageMaster { + Tk_ImageMaster master; /* Tk's token for image master. */ + Tcl_Interp *interp; /* Interpreter for application. */ + int width, height; /* Dimensions of image. */ + char *imageName; /* Name of image (malloc-ed). */ + char *varName; /* Name of variable in which to log + * events for image (malloc-ed). */ +} TImageMaster; + +/* + * The following data structure represents a particular use of a + * particular test image. + */ + +typedef struct TImageInstance { + TImageMaster *masterPtr; /* Pointer to master for image. */ + XColor *fg; /* Foreground color for drawing in image. */ + GC gc; /* Graphics context for drawing in image. */ +} TImageInstance; + +/* + * The type record for test images: + */ + +static int ImageCreate _ANSI_ARGS_((Tcl_Interp *interp, + char *name, int argc, char **argv, + Tk_ImageType *typePtr, Tk_ImageMaster master, + ClientData *clientDataPtr)); +static ClientData ImageGet _ANSI_ARGS_((Tk_Window tkwin, + ClientData clientData)); +static void ImageDisplay _ANSI_ARGS_((ClientData clientData, + Display *display, Drawable drawable, + int imageX, int imageY, int width, + int height, int drawableX, + int drawableY)); +static void ImageFree _ANSI_ARGS_((ClientData clientData, + Display *display)); +static void ImageDelete _ANSI_ARGS_((ClientData clientData)); + +static Tk_ImageType imageType = { + "test", /* name */ + ImageCreate, /* createProc */ + ImageGet, /* getProc */ + ImageDisplay, /* displayProc */ + ImageFree, /* freeProc */ + ImageDelete, /* deleteProc */ + (Tk_ImageType *) NULL /* nextPtr */ +}; + +/* + * One of the following structures describes each of the interpreters + * created by the "testnewapp" command. This information is used by + * the "testdeleteinterps" command to destroy all of those interpreters. + */ + +typedef struct NewApp { + Tcl_Interp *interp; /* Token for interpreter. */ + struct NewApp *nextPtr; /* Next in list of new interpreters. */ +} NewApp; + +static NewApp *newAppPtr = NULL; + /* First in list of all new interpreters. */ + +/* + * Declaration for the square widget's class command procedure: + */ + +extern int SquareCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char *argv[])); + +typedef struct CBinding { + Tcl_Interp *interp; + char *command; + char *delete; +} CBinding; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int CBindingEvalProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, XEvent *eventPtr, + Tk_Window tkwin, KeySym keySym)); +static void CBindingFreeProc _ANSI_ARGS_((ClientData clientData)); +int Tktest_Init _ANSI_ARGS_((Tcl_Interp *interp)); +static int ImageCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); +static int TestcbindCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); +#ifdef __WIN32__ +static int TestclipboardCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); +#endif +static int TestdeleteappsCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); +static int TestmakeexistCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); +static int TestmenubarCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); +#if defined(__WIN32__) || defined(MAC_TCL) +static int TestmetricsCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); +#endif +static int TestsendCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); +static int TestpropCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); +#if !(defined(__WIN32__) || defined(MAC_TCL)) +static int TestwrapperCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); +#endif + +/* + * External (platform specific) initialization routine: + */ + +EXTERN int TkplatformtestInit _ANSI_ARGS_(( + Tcl_Interp *interp)); +#ifndef MAC_TCL +#define TkplatformtestInit(x) TCL_OK +#endif + +/* + *---------------------------------------------------------------------- + * + * Tktest_Init -- + * + * This procedure performs intialization for the Tk test + * suite exensions. + * + * Results: + * Returns a standard Tcl completion code, and leaves an error + * message in interp->result if an error occurs. + * + * Side effects: + * Creates several test commands. + * + *---------------------------------------------------------------------- + */ + +int +Tktest_Init(interp) + Tcl_Interp *interp; /* Interpreter for application. */ +{ + static int initialized = 0; + + /* + * Create additional commands for testing Tk. + */ + + if (Tcl_PkgProvide(interp, "Tktest", TK_VERSION) == TCL_ERROR) { + return TCL_ERROR; + } + + Tcl_CreateCommand(interp, "square", SquareCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); +#ifdef __WIN32__ + Tcl_CreateCommand(interp, "testclipboard", TestclipboardCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); +#endif + Tcl_CreateCommand(interp, "testcbind", TestcbindCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); + Tcl_CreateCommand(interp, "testdeleteapps", TestdeleteappsCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); + Tcl_CreateCommand(interp, "testembed", TkpTestembedCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); + Tcl_CreateCommand(interp, "testmakeexist", TestmakeexistCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); + Tcl_CreateCommand(interp, "testmenubar", TestmenubarCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); +#if defined(__WIN32__) || defined(MAC_TCL) + Tcl_CreateCommand(interp, "testmetrics", TestmetricsCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); +#endif + Tcl_CreateCommand(interp, "testprop", TestpropCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); + Tcl_CreateCommand(interp, "testsend", TestsendCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); +#if !(defined(__WIN32__) || defined(MAC_TCL)) + Tcl_CreateCommand(interp, "testwrapper", TestwrapperCmd, + (ClientData) Tk_MainWindow(interp), (Tcl_CmdDeleteProc *) NULL); +#endif + +/* + * Create test image type. + */ + + if (!initialized) { + initialized = 1; + Tk_CreateImageType(&imageType); + } + + /* + * And finally add any platform specific test commands. + */ + + return TkplatformtestInit(interp); +} + +/* + *---------------------------------------------------------------------- + * + * TestclipboardCmd -- + * + * This procedure implements the testclipboard command. It provides + * a way to determine the actual contents of the Windows clipboard. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +#ifdef __WIN32__ +static int +TestclipboardCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + TkWindow *winPtr = (TkWindow *) clientData; + HGLOBAL handle; + char *data; + + if (OpenClipboard(NULL)) { + handle = GetClipboardData(CF_TEXT); + if (handle != NULL) { + data = GlobalLock(handle); + Tcl_AppendResult(interp, data, (char *) NULL); + GlobalUnlock(handle); + } + CloseClipboard(); + } + return TCL_OK; +} +#endif + +/* + *---------------------------------------------------------------------- + * + * TestcbindCmd -- + * + * This procedure implements the "testcbinding" command. It provides + * a set of functions for testing C bindings in tkBind.c. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * Depends on option; see below. + * + *---------------------------------------------------------------------- + */ + +static int +TestcbindCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + TkWindow *winPtr; + Tk_Window tkwin; + ClientData object; + CBinding *cbindPtr; + + + if (argc < 4 || argc > 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " bindtag pattern command ?deletecommand?", (char *) NULL); + return TCL_ERROR; + } + + tkwin = (Tk_Window) clientData; + + if (argv[1][0] == '.') { + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[1], tkwin); + if (winPtr == NULL) { + return TCL_ERROR; + } + object = (ClientData) winPtr->pathName; + } else { + winPtr = (TkWindow *) clientData; + object = (ClientData) Tk_GetUid(argv[1]); + } + + if (argv[3][0] == '\0') { + return Tk_DeleteBinding(interp, winPtr->mainPtr->bindingTable, + object, argv[2]); + } + + cbindPtr = (CBinding *) ckalloc(sizeof(CBinding)); + cbindPtr->interp = interp; + cbindPtr->command = + strcpy((char *) ckalloc(strlen(argv[3]) + 1), argv[3]); + if (argc == 4) { + cbindPtr->delete = NULL; + } else { + cbindPtr->delete = + strcpy((char *) ckalloc(strlen(argv[4]) + 1), argv[4]); + } + + if (TkCreateBindingProcedure(interp, winPtr->mainPtr->bindingTable, + object, argv[2], CBindingEvalProc, CBindingFreeProc, + (ClientData) cbindPtr) == 0) { + ckfree((char *) cbindPtr->command); + if (cbindPtr->delete != NULL) { + ckfree((char *) cbindPtr->delete); + } + ckfree((char *) cbindPtr); + return TCL_ERROR; + } + return TCL_OK; +} + +static int +CBindingEvalProc(clientData, interp, eventPtr, tkwin, keySym) + ClientData clientData; + Tcl_Interp *interp; + XEvent *eventPtr; + Tk_Window tkwin; + KeySym keySym; +{ + CBinding *cbindPtr; + + cbindPtr = (CBinding *) clientData; + + return Tcl_GlobalEval(interp, cbindPtr->command); +} + +static void +CBindingFreeProc(clientData) + ClientData clientData; +{ + CBinding *cbindPtr = (CBinding *) clientData; + + if (cbindPtr->delete != NULL) { + Tcl_GlobalEval(cbindPtr->interp, cbindPtr->delete); + ckfree((char *) cbindPtr->delete); + } + ckfree((char *) cbindPtr->command); + ckfree((char *) cbindPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TestdeleteappsCmd -- + * + * This procedure implements the "testdeleteapps" command. It cleans + * up all the interpreters left behind by the "testnewapp" command. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * All the intepreters created by previous calls to "testnewapp" + * get deleted. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +TestdeleteappsCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + NewApp *nextPtr; + + while (newAppPtr != NULL) { + nextPtr = newAppPtr->nextPtr; + Tcl_DeleteInterp(newAppPtr->interp); + ckfree((char *) newAppPtr); + newAppPtr = nextPtr; + } + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ImageCreate -- + * + * This procedure is called by the Tk image code to create "test" + * images. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * The data structure for a new image is allocated. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +ImageCreate(interp, name, argc, argv, typePtr, master, clientDataPtr) + Tcl_Interp *interp; /* Interpreter for application containing + * image. */ + char *name; /* Name to use for image. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings for options (doesn't + * include image name or type). */ + Tk_ImageType *typePtr; /* Pointer to our type record (not used). */ + Tk_ImageMaster master; /* Token for image, to be used by us in + * later callbacks. */ + ClientData *clientDataPtr; /* Store manager's token for image here; + * it will be returned in later callbacks. */ +{ + TImageMaster *timPtr; + char *varName; + int i; + + varName = "log"; + for (i = 0; i < argc; i += 2) { + if (strcmp(argv[i], "-variable") != 0) { + Tcl_AppendResult(interp, "bad option name \"", argv[i], + "\"", (char *) NULL); + return TCL_ERROR; + } + if ((i+1) == argc) { + Tcl_AppendResult(interp, "no value given for \"", argv[i], + "\" option", (char *) NULL); + return TCL_ERROR; + } + varName = argv[i+1]; + } + timPtr = (TImageMaster *) ckalloc(sizeof(TImageMaster)); + timPtr->master = master; + timPtr->interp = interp; + timPtr->width = 30; + timPtr->height = 15; + timPtr->imageName = (char *) ckalloc((unsigned) (strlen(name) + 1)); + strcpy(timPtr->imageName, name); + timPtr->varName = (char *) ckalloc((unsigned) (strlen(varName) + 1)); + strcpy(timPtr->varName, varName); + Tcl_CreateCommand(interp, name, ImageCmd, (ClientData) timPtr, + (Tcl_CmdDeleteProc *) NULL); + *clientDataPtr = (ClientData) timPtr; + Tk_ImageChanged(master, 0, 0, 30, 15, 30, 15); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ImageCmd -- + * + * This procedure implements the commands corresponding to individual + * images. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * Forces windows to be created. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +ImageCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + TImageMaster *timPtr = (TImageMaster *) clientData; + int x, y, width, height; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], "option ?arg arg ...?", (char *) NULL); + return TCL_ERROR; + } + if (strcmp(argv[1], "changed") == 0) { + if (argc != 8) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " changed x y width height imageWidth imageHeight", + (char *) NULL); + return TCL_ERROR; + } + if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[3], &y) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &width) != TCL_OK) + || (Tcl_GetInt(interp, argv[5], &height) != TCL_OK) + || (Tcl_GetInt(interp, argv[6], &timPtr->width) != TCL_OK) + || (Tcl_GetInt(interp, argv[7], &timPtr->height) != TCL_OK)) { + return TCL_ERROR; + } + Tk_ImageChanged(timPtr->master, x, y, width, height, timPtr->width, + timPtr->height); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be changed", (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ImageGet -- + * + * This procedure is called by Tk to set things up for using a + * test image in a particular widget. + * + * Results: + * The return value is a token for the image instance, which is + * used in future callbacks to ImageDisplay and ImageFree. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static ClientData +ImageGet(tkwin, clientData) + Tk_Window tkwin; /* Token for window in which image will + * be used. */ + ClientData clientData; /* Pointer to TImageMaster for image. */ +{ + TImageMaster *timPtr = (TImageMaster *) clientData; + TImageInstance *instPtr; + char buffer[100]; + XGCValues gcValues; + + sprintf(buffer, "%s get", timPtr->imageName); + Tcl_SetVar(timPtr->interp, timPtr->varName, buffer, + TCL_GLOBAL_ONLY|TCL_APPEND_VALUE|TCL_LIST_ELEMENT); + + instPtr = (TImageInstance *) ckalloc(sizeof(TImageInstance)); + instPtr->masterPtr = timPtr; + instPtr->fg = Tk_GetColor(timPtr->interp, tkwin, "#ff0000"); + gcValues.foreground = instPtr->fg->pixel; + instPtr->gc = Tk_GetGC(tkwin, GCForeground, &gcValues); + return (ClientData) instPtr; +} + +/* + *---------------------------------------------------------------------- + * + * ImageDisplay -- + * + * This procedure is invoked to redisplay part or all of an + * image in a given drawable. + * + * Results: + * None. + * + * Side effects: + * The image gets partially redrawn, as an "X" that shows the + * exact redraw area. + * + *---------------------------------------------------------------------- + */ + +static void +ImageDisplay(clientData, display, drawable, imageX, imageY, width, height, + drawableX, drawableY) + ClientData clientData; /* Pointer to TImageInstance for image. */ + Display *display; /* Display to use for drawing. */ + Drawable drawable; /* Where to redraw image. */ + int imageX, imageY; /* Origin of area to redraw, relative to + * origin of image. */ + int width, height; /* Dimensions of area to redraw. */ + int drawableX, drawableY; /* Coordinates in drawable corresponding to + * imageX and imageY. */ +{ + TImageInstance *instPtr = (TImageInstance *) clientData; + char buffer[200]; + + sprintf(buffer, "%s display %d %d %d %d %d %d", + instPtr->masterPtr->imageName, imageX, imageY, width, height, + drawableX, drawableY); + Tcl_SetVar(instPtr->masterPtr->interp, instPtr->masterPtr->varName, buffer, + TCL_GLOBAL_ONLY|TCL_APPEND_VALUE|TCL_LIST_ELEMENT); + if (width > (instPtr->masterPtr->width - imageX)) { + width = instPtr->masterPtr->width - imageX; + } + if (height > (instPtr->masterPtr->height - imageY)) { + height = instPtr->masterPtr->height - imageY; + } + XDrawRectangle(display, drawable, instPtr->gc, drawableX, drawableY, + (unsigned) (width-1), (unsigned) (height-1)); + XDrawLine(display, drawable, instPtr->gc, drawableX, drawableY, + (int) (drawableX + width - 1), (int) (drawableY + height - 1)); + XDrawLine(display, drawable, instPtr->gc, drawableX, + (int) (drawableY + height - 1), + (int) (drawableX + width - 1), drawableY); +} + +/* + *---------------------------------------------------------------------- + * + * ImageFree -- + * + * This procedure is called when an instance of an image is + * no longer used. + * + * Results: + * None. + * + * Side effects: + * Information related to the instance is freed. + * + *---------------------------------------------------------------------- + */ + +static void +ImageFree(clientData, display) + ClientData clientData; /* Pointer to TImageInstance for instance. */ + Display *display; /* Display where image was to be drawn. */ +{ + TImageInstance *instPtr = (TImageInstance *) clientData; + char buffer[200]; + + sprintf(buffer, "%s free", instPtr->masterPtr->imageName); + Tcl_SetVar(instPtr->masterPtr->interp, instPtr->masterPtr->varName, buffer, + TCL_GLOBAL_ONLY|TCL_APPEND_VALUE|TCL_LIST_ELEMENT); + Tk_FreeColor(instPtr->fg); + Tk_FreeGC(display, instPtr->gc); + ckfree((char *) instPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ImageDelete -- + * + * This procedure is called to clean up a test image when + * an application goes away. + * + * Results: + * None. + * + * Side effects: + * Information about the image is deleted. + * + *---------------------------------------------------------------------- + */ + +static void +ImageDelete(clientData) + ClientData clientData; /* Pointer to TImageMaster for image. When + * this procedure is called, no more + * instances exist. */ +{ + TImageMaster *timPtr = (TImageMaster *) clientData; + char buffer[100]; + + sprintf(buffer, "%s delete", timPtr->imageName); + Tcl_SetVar(timPtr->interp, timPtr->varName, buffer, + TCL_GLOBAL_ONLY|TCL_APPEND_VALUE|TCL_LIST_ELEMENT); + + Tcl_DeleteCommand(timPtr->interp, timPtr->imageName); + ckfree(timPtr->imageName); + ckfree(timPtr->varName); + ckfree((char *) timPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TestmakeexistCmd -- + * + * This procedure implements the "testmakeexist" command. It calls + * Tk_MakeWindowExist on each of its arguments to force the windows + * to be created. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * Forces windows to be created. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +TestmakeexistCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window main = (Tk_Window) clientData; + int i; + Tk_Window tkwin; + + for (i = 1; i < argc; i++) { + tkwin = Tk_NameToWindow(interp, argv[i], main); + if (tkwin == NULL) { + return TCL_ERROR; + } + Tk_MakeWindowExist(tkwin); + } + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TestmenubarCmd -- + * + * This procedure implements the "testmenubar" command. It is used + * to test the Unix facilities for creating space above a toplevel + * window for a menubar. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * Changes menubar related stuff. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +TestmenubarCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ +#ifdef __UNIX__ + Tk_Window main = (Tk_Window) clientData; + Tk_Window tkwin, menubar; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args; must be \"", argv[0], + " option ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + + if (strcmp(argv[1], "window") == 0) { + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args; must be \"", argv[0], + "window toplevel menubar\"", (char *) NULL); + return TCL_ERROR; + } + tkwin = Tk_NameToWindow(interp, argv[2], main); + if (tkwin == NULL) { + return TCL_ERROR; + } + if (argv[3][0] == 0) { + TkUnixSetMenubar(tkwin, NULL); + } else { + menubar = Tk_NameToWindow(interp, argv[3], main); + if (menubar == NULL) { + return TCL_ERROR; + } + TkUnixSetMenubar(tkwin, menubar); + } + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be window", (char *) NULL); + return TCL_ERROR; + } + + return TCL_OK; +#else + interp->result = "testmenubar is supported only under Unix"; + return TCL_ERROR; +#endif +} + +/* + *---------------------------------------------------------------------- + * + * TestmetricsCmd -- + * + * This procedure implements the testmetrics command. It provides + * a way to determine the size of various widget components. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +#ifdef __WIN32__ +static int +TestmetricsCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + char buf[200]; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args; must be \"", argv[0], + " option ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + + if (strcmp(argv[1], "cyvscroll") == 0) { + sprintf(buf, "%d", GetSystemMetrics(SM_CYVSCROLL)); + Tcl_AppendResult(interp, buf, (char *) NULL); + } else if (strcmp(argv[1], "cxhscroll") == 0) { + sprintf(buf, "%d", GetSystemMetrics(SM_CXHSCROLL)); + Tcl_AppendResult(interp, buf, (char *) NULL); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be cxhscroll or cyvscroll", (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} +#endif +#ifdef MAC_TCL +static int +TestmetricsCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + TkWindow *winPtr; + char buf[200]; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args; must be \"", argv[0], + " option window\"", (char *) NULL); + return TCL_ERROR; + } + + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[2], tkwin); + if (winPtr == NULL) { + return TCL_ERROR; + } + + if (strcmp(argv[1], "cyvscroll") == 0) { + sprintf(buf, "%d", ((TkScrollbar *) winPtr->instanceData)->width); + Tcl_AppendResult(interp, buf, (char *) NULL); + } else if (strcmp(argv[1], "cxhscroll") == 0) { + sprintf(buf, "%d", ((TkScrollbar *) winPtr->instanceData)->width); + Tcl_AppendResult(interp, buf, (char *) NULL); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be cxhscroll or cyvscroll", (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} +#endif + +/* + *---------------------------------------------------------------------- + * + * TestpropCmd -- + * + * This procedure implements the "testprop" command. It fetches + * and prints the value of a property on a window. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +TestpropCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window main = (Tk_Window) clientData; + int result, actualFormat; + unsigned long bytesAfter, length, value; + Atom actualType, propName; + char *property, *p, *end; + Window w; + char buffer[30]; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args; must be \"", argv[0], + " window property\"", (char *) NULL); + return TCL_ERROR; + } + + w = strtoul(argv[1], &end, 0); + propName = Tk_InternAtom(main, argv[2]); + property = NULL; + result = XGetWindowProperty(Tk_Display(main), + w, propName, 0, 100000, False, AnyPropertyType, + &actualType, &actualFormat, &length, + &bytesAfter, (unsigned char **) &property); + if ((result == Success) && (actualType != None)) { + if ((actualFormat == 8) && (actualType == XA_STRING)) { + for (p = property; ((unsigned long)(p-property)) < length; p++) { + if (*p == 0) { + *p = '\n'; + } + } + Tcl_SetResult(interp, property, TCL_VOLATILE); + } else { + for (p = property; length > 0; length--) { + if (actualFormat == 32) { + value = *((long *) p); + p += sizeof(long); + } else if (actualFormat == 16) { + value = 0xffff & (*((short *) p)); + p += sizeof(short); + } else { + value = 0xff & *p; + p += 1; + } + sprintf(buffer, "0x%lx", value); + Tcl_AppendElement(interp, buffer); + } + } + } + if (property != NULL) { + XFree(property); + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TestsendCmd -- + * + * This procedure implements the "testsend" command. It provides + * a set of functions for testing the "send" command and support + * procedure in tkSend.c. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * Depends on option; see below. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +TestsendCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + TkWindow *winPtr = (TkWindow *) clientData; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args; must be \"", argv[0], + " option ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + +#if !(defined(__WIN32__) || defined(MAC_TCL)) + if (strcmp(argv[1], "bogus") == 0) { + XChangeProperty(winPtr->dispPtr->display, + RootWindow(winPtr->dispPtr->display, 0), + winPtr->dispPtr->registryProperty, XA_INTEGER, 32, + PropModeReplace, + (unsigned char *) "This is bogus information", 6); + } else if (strcmp(argv[1], "prop") == 0) { + int result, actualFormat; + unsigned long length, bytesAfter; + Atom actualType, propName; + char *property, *p, *end; + Window w; + + if ((argc != 4) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # args; must be \"", argv[0], + " prop window name ?value ?\"", (char *) NULL); + return TCL_ERROR; + } + if (strcmp(argv[2], "root") == 0) { + w = RootWindow(winPtr->dispPtr->display, 0); + } else if (strcmp(argv[2], "comm") == 0) { + w = Tk_WindowId(winPtr->dispPtr->commTkwin); + } else { + w = strtoul(argv[2], &end, 0); + } + propName = Tk_InternAtom((Tk_Window) winPtr, argv[3]); + if (argc == 4) { + property = NULL; + result = XGetWindowProperty(winPtr->dispPtr->display, + w, propName, 0, 100000, False, XA_STRING, + &actualType, &actualFormat, &length, + &bytesAfter, (unsigned char **) &property); + if ((result == Success) && (actualType != None) + && (actualFormat == 8) && (actualType == XA_STRING)) { + for (p = property; (p-property) < length; p++) { + if (*p == 0) { + *p = '\n'; + } + } + Tcl_SetResult(interp, property, TCL_VOLATILE); + } + if (property != NULL) { + XFree(property); + } + } else { + if (argv[4][0] == 0) { + XDeleteProperty(winPtr->dispPtr->display, w, propName); + } else { + for (p = argv[4]; *p != 0; p++) { + if (*p == '\n') { + *p = 0; + } + } + XChangeProperty(winPtr->dispPtr->display, + w, propName, XA_STRING, 8, PropModeReplace, + (unsigned char *) argv[4], p-argv[4]); + } + } + } else if (strcmp(argv[1], "serial") == 0) { + sprintf(interp->result, "%d", tkSendSerial+1); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be bogus, prop, or serial", (char *) NULL); + return TCL_ERROR; + } +#endif + return TCL_OK; +} + +#if !(defined(__WIN32__) || defined(MAC_TCL)) +/* + *---------------------------------------------------------------------- + * + * TestwrapperCmd -- + * + * This procedure implements the "testwrapper" command. It + * provides a way from Tcl to determine the extra window Tk adds + * in between the toplevel window and the window decorations. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +TestwrapperCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + TkWindow *winPtr, *wrapperPtr; + Tk_Window tkwin; + + if (argc != 2) { + Tcl_AppendResult(interp, "wrong # args; must be \"", argv[0], + " window\"", (char *) NULL); + return TCL_ERROR; + } + + tkwin = (Tk_Window) clientData; + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[1], tkwin); + if (winPtr == NULL) { + return TCL_ERROR; + } + + wrapperPtr = TkpGetWrapperWindow(winPtr); + if (wrapperPtr != NULL) { + TkpPrintWindowId(interp->result, Tk_WindowId(wrapperPtr)); + } + return TCL_OK; +} +#endif diff --git a/generic/tkText.c b/generic/tkText.c new file mode 100644 index 0000000..643aea0 --- /dev/null +++ b/generic/tkText.c @@ -0,0 +1,2264 @@ +/* + * tkText.c -- + * + * This module provides a big chunk of the implementation of + * multi-line editable text widgets for Tk. Among other things, + * it provides the Tcl command interfaces to text widgets and + * the display code. The B-tree representation of text is + * implemented elsewhere. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkText.c 1.104 97/10/13 15:18:24 + */ + +#include "default.h" +#include "tkPort.h" +#include "tkInt.h" + +#ifdef MAC_TCL +#define Style TkStyle +#define DInfo TkDInfo +#endif + +#include "tkText.h" + +/* + * Information used to parse text configuration options: + */ + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_TEXT_BG_COLOR, Tk_Offset(TkText, border), TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-background", "background", "Background", + DEF_TEXT_BG_MONO, Tk_Offset(TkText, border), TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth", + DEF_TEXT_BORDER_WIDTH, Tk_Offset(TkText, borderWidth), 0}, + {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor", + DEF_TEXT_CURSOR, Tk_Offset(TkText, cursor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_BOOLEAN, "-exportselection", "exportSelection", + "ExportSelection", DEF_TEXT_EXPORT_SELECTION, + Tk_Offset(TkText, exportSelection), 0}, + {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, + (char *) NULL, 0, 0}, + {TK_CONFIG_FONT, "-font", "font", "Font", + DEF_TEXT_FONT, Tk_Offset(TkText, tkfont), 0}, + {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground", + DEF_TEXT_FG, Tk_Offset(TkText, fgColor), 0}, + {TK_CONFIG_PIXELS, "-height", "height", "Height", + DEF_TEXT_HEIGHT, Tk_Offset(TkText, height), 0}, + {TK_CONFIG_COLOR, "-highlightbackground", "highlightBackground", + "HighlightBackground", DEF_TEXT_HIGHLIGHT_BG, + Tk_Offset(TkText, highlightBgColorPtr), 0}, + {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor", + DEF_TEXT_HIGHLIGHT, Tk_Offset(TkText, highlightColorPtr), 0}, + {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness", + "HighlightThickness", + DEF_TEXT_HIGHLIGHT_WIDTH, Tk_Offset(TkText, highlightWidth), 0}, + {TK_CONFIG_BORDER, "-insertbackground", "insertBackground", "Foreground", + DEF_TEXT_INSERT_BG, Tk_Offset(TkText, insertBorder), 0}, + {TK_CONFIG_PIXELS, "-insertborderwidth", "insertBorderWidth", "BorderWidth", + DEF_TEXT_INSERT_BD_COLOR, Tk_Offset(TkText, insertBorderWidth), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_PIXELS, "-insertborderwidth", "insertBorderWidth", "BorderWidth", + DEF_TEXT_INSERT_BD_MONO, Tk_Offset(TkText, insertBorderWidth), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_INT, "-insertofftime", "insertOffTime", "OffTime", + DEF_TEXT_INSERT_OFF_TIME, Tk_Offset(TkText, insertOffTime), 0}, + {TK_CONFIG_INT, "-insertontime", "insertOnTime", "OnTime", + DEF_TEXT_INSERT_ON_TIME, Tk_Offset(TkText, insertOnTime), 0}, + {TK_CONFIG_PIXELS, "-insertwidth", "insertWidth", "InsertWidth", + DEF_TEXT_INSERT_WIDTH, Tk_Offset(TkText, insertWidth), 0}, + {TK_CONFIG_PIXELS, "-padx", "padX", "Pad", + DEF_TEXT_PADX, Tk_Offset(TkText, padX), 0}, + {TK_CONFIG_PIXELS, "-pady", "padY", "Pad", + DEF_TEXT_PADY, Tk_Offset(TkText, padY), 0}, + {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", + DEF_TEXT_RELIEF, Tk_Offset(TkText, relief), 0}, + {TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Foreground", + DEF_TEXT_SELECT_COLOR, Tk_Offset(TkText, selBorder), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Foreground", + DEF_TEXT_SELECT_MONO, Tk_Offset(TkText, selBorder), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_STRING, "-selectborderwidth", "selectBorderWidth", "BorderWidth", + DEF_TEXT_SELECT_BD_COLOR, Tk_Offset(TkText, selBdString), + TK_CONFIG_COLOR_ONLY|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-selectborderwidth", "selectBorderWidth", "BorderWidth", + DEF_TEXT_SELECT_BD_MONO, Tk_Offset(TkText, selBdString), + TK_CONFIG_MONO_ONLY|TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Background", + DEF_TEXT_SELECT_FG_COLOR, Tk_Offset(TkText, selFgColorPtr), + TK_CONFIG_COLOR_ONLY}, + {TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Background", + DEF_TEXT_SELECT_FG_MONO, Tk_Offset(TkText, selFgColorPtr), + TK_CONFIG_MONO_ONLY}, + {TK_CONFIG_BOOLEAN, "-setgrid", "setGrid", "SetGrid", + DEF_TEXT_SET_GRID, Tk_Offset(TkText, setGrid), 0}, + {TK_CONFIG_PIXELS, "-spacing1", "spacing1", "Spacing", + DEF_TEXT_SPACING1, Tk_Offset(TkText, spacing1), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_PIXELS, "-spacing2", "spacing2", "Spacing", + DEF_TEXT_SPACING2, Tk_Offset(TkText, spacing2), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_PIXELS, "-spacing3", "spacing3", "Spacing", + DEF_TEXT_SPACING3, Tk_Offset(TkText, spacing3), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_UID, "-state", "state", "State", + DEF_TEXT_STATE, Tk_Offset(TkText, state), 0}, + {TK_CONFIG_STRING, "-tabs", "tabs", "Tabs", + DEF_TEXT_TABS, Tk_Offset(TkText, tabOptionString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus", + DEF_TEXT_TAKE_FOCUS, Tk_Offset(TkText, takeFocus), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_INT, "-width", "width", "Width", + DEF_TEXT_WIDTH, Tk_Offset(TkText, width), 0}, + {TK_CONFIG_UID, "-wrap", "wrap", "Wrap", + DEF_TEXT_WRAP, Tk_Offset(TkText, wrapMode), 0}, + {TK_CONFIG_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand", + DEF_TEXT_XSCROLL_COMMAND, Tk_Offset(TkText, xScrollCmd), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-yscrollcommand", "yScrollCommand", "ScrollCommand", + DEF_TEXT_YSCROLL_COMMAND, Tk_Offset(TkText, yScrollCmd), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Tk_Uid's used to represent text states: + */ + +Tk_Uid tkTextCharUid = NULL; +Tk_Uid tkTextDisabledUid = NULL; +Tk_Uid tkTextNoneUid = NULL; +Tk_Uid tkTextNormalUid = NULL; +Tk_Uid tkTextWordUid = NULL; + +/* + * Boolean variable indicating whether or not special debugging code + * should be executed. + */ + +int tkTextDebug = 0; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int ConfigureText _ANSI_ARGS_((Tcl_Interp *interp, + TkText *textPtr, int argc, char **argv, int flags)); +static int DeleteChars _ANSI_ARGS_((TkText *textPtr, + char *index1String, char *index2String)); +static void DestroyText _ANSI_ARGS_((char *memPtr)); +static void InsertChars _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *indexPtr, char *string)); +static void TextBlinkProc _ANSI_ARGS_((ClientData clientData)); +static void TextCmdDeletedProc _ANSI_ARGS_(( + ClientData clientData)); +static void TextEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int TextFetchSelection _ANSI_ARGS_((ClientData clientData, + int offset, char *buffer, int maxBytes)); +static int TextSearchCmd _ANSI_ARGS_((TkText *textPtr, + Tcl_Interp *interp, int argc, char **argv)); +static int TextWidgetCmd _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv)); +static void TextWorldChanged _ANSI_ARGS_(( + ClientData instanceData)); +static int TextDumpCmd _ANSI_ARGS_((TkText *textPtr, + Tcl_Interp *interp, int argc, char **argv)); +static void DumpLine _ANSI_ARGS_((Tcl_Interp *interp, + TkText *textPtr, int what, TkTextLine *linePtr, + int start, int end, int lineno, char *command)); +static int DumpSegment _ANSI_ARGS_((Tcl_Interp *interp, char *key, + char *value, char * command, int lineno, int offset, + int what)); + +/* + * The structure below defines text class behavior by means of procedures + * that can be invoked from generic window code. + */ + +static TkClassProcs textClass = { + NULL, /* createProc. */ + TextWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + + +/* + *-------------------------------------------------------------- + * + * Tk_TextCmd -- + * + * This procedure is invoked to process the "text" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_TextCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + Tk_Window new; + register TkText *textPtr; + TkTextIndex startIndex; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " pathName ?options?\"", (char *) NULL); + return TCL_ERROR; + } + + /* + * Perform once-only initialization: + */ + + if (tkTextNormalUid == NULL) { + tkTextCharUid = Tk_GetUid("char"); + tkTextDisabledUid = Tk_GetUid("disabled"); + tkTextNoneUid = Tk_GetUid("none"); + tkTextNormalUid = Tk_GetUid("normal"); + tkTextWordUid = Tk_GetUid("word"); + } + + /* + * Create the window. + */ + + new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *) NULL); + if (new == NULL) { + return TCL_ERROR; + } + + textPtr = (TkText *) ckalloc(sizeof(TkText)); + textPtr->tkwin = new; + textPtr->display = Tk_Display(new); + textPtr->interp = interp; + textPtr->widgetCmd = Tcl_CreateCommand(interp, + Tk_PathName(textPtr->tkwin), TextWidgetCmd, + (ClientData) textPtr, TextCmdDeletedProc); + textPtr->tree = TkBTreeCreate(textPtr); + Tcl_InitHashTable(&textPtr->tagTable, TCL_STRING_KEYS); + textPtr->numTags = 0; + Tcl_InitHashTable(&textPtr->markTable, TCL_STRING_KEYS); + Tcl_InitHashTable(&textPtr->windowTable, TCL_STRING_KEYS); + Tcl_InitHashTable(&textPtr->imageTable, TCL_STRING_KEYS); + textPtr->state = tkTextNormalUid; + textPtr->border = NULL; + textPtr->borderWidth = 0; + textPtr->padX = 0; + textPtr->padY = 0; + textPtr->relief = TK_RELIEF_FLAT; + textPtr->highlightWidth = 0; + textPtr->highlightBgColorPtr = NULL; + textPtr->highlightColorPtr = NULL; + textPtr->cursor = None; + textPtr->fgColor = NULL; + textPtr->tkfont = NULL; + textPtr->charWidth = 1; + textPtr->spacing1 = 0; + textPtr->spacing2 = 0; + textPtr->spacing3 = 0; + textPtr->tabOptionString = NULL; + textPtr->tabArrayPtr = NULL; + textPtr->wrapMode = tkTextCharUid; + textPtr->width = 0; + textPtr->height = 0; + textPtr->setGrid = 0; + textPtr->prevWidth = Tk_Width(new); + textPtr->prevHeight = Tk_Height(new); + TkTextCreateDInfo(textPtr); + TkTextMakeIndex(textPtr->tree, 0, 0, &startIndex); + TkTextSetYView(textPtr, &startIndex, 0); + textPtr->selTagPtr = NULL; + textPtr->selBorder = NULL; + textPtr->selBdString = NULL; + textPtr->selFgColorPtr = NULL; + textPtr->exportSelection = 1; + textPtr->abortSelections = 0; + textPtr->insertMarkPtr = NULL; + textPtr->insertBorder = NULL; + textPtr->insertWidth = 0; + textPtr->insertBorderWidth = 0; + textPtr->insertOnTime = 0; + textPtr->insertOffTime = 0; + textPtr->insertBlinkHandler = (Tcl_TimerToken) NULL; + textPtr->bindingTable = NULL; + textPtr->currentMarkPtr = NULL; + textPtr->pickEvent.type = LeaveNotify; + textPtr->pickEvent.xcrossing.x = 0; + textPtr->pickEvent.xcrossing.y = 0; + textPtr->numCurTags = 0; + textPtr->curTagArrayPtr = NULL; + textPtr->takeFocus = NULL; + textPtr->xScrollCmd = NULL; + textPtr->yScrollCmd = NULL; + textPtr->flags = 0; + + /* + * Create the "sel" tag and the "current" and "insert" marks. + */ + + textPtr->selTagPtr = TkTextCreateTag(textPtr, "sel"); + textPtr->selTagPtr->reliefString = (char *) ckalloc(7); + strcpy(textPtr->selTagPtr->reliefString, DEF_TEXT_SELECT_RELIEF); + textPtr->selTagPtr->relief = TK_RELIEF_RAISED; + textPtr->currentMarkPtr = TkTextSetMark(textPtr, "current", &startIndex); + textPtr->insertMarkPtr = TkTextSetMark(textPtr, "insert", &startIndex); + + Tk_SetClass(textPtr->tkwin, "Text"); + TkSetClassProcs(textPtr->tkwin, &textClass, (ClientData) textPtr); + Tk_CreateEventHandler(textPtr->tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + TextEventProc, (ClientData) textPtr); + Tk_CreateEventHandler(textPtr->tkwin, KeyPressMask|KeyReleaseMask + |ButtonPressMask|ButtonReleaseMask|EnterWindowMask + |LeaveWindowMask|PointerMotionMask|VirtualEventMask, + TkTextBindProc, (ClientData) textPtr); + Tk_CreateSelHandler(textPtr->tkwin, XA_PRIMARY, XA_STRING, + TextFetchSelection, (ClientData) textPtr, XA_STRING); + if (ConfigureText(interp, textPtr, argc-2, argv+2, 0) != TCL_OK) { + Tk_DestroyWindow(textPtr->tkwin); + return TCL_ERROR; + } + interp->result = Tk_PathName(textPtr->tkwin); + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * TextWidgetCmd -- + * + * This procedure is invoked to process the Tcl command + * that corresponds to a text widget. See the user + * documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +static int +TextWidgetCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + register TkText *textPtr = (TkText *) clientData; + int result = TCL_OK; + size_t length; + int c; + TkTextIndex index1, index2; + + if (argc < 2) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + Tcl_Preserve((ClientData) textPtr); + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 'b') && (strncmp(argv[1], "bbox", length) == 0)) { + int x, y, width, height; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " bbox index\"", (char *) NULL); + result = TCL_ERROR; + goto done; + } + if (TkTextGetIndex(interp, textPtr, argv[2], &index1) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + if (TkTextCharBbox(textPtr, &index1, &x, &y, &width, &height) == 0) { + sprintf(interp->result, "%d %d %d %d", x, y, width, height); + } + } else if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " cget option\"", + (char *) NULL); + result = TCL_ERROR; + goto done; + } + result = Tk_ConfigureValue(interp, textPtr->tkwin, configSpecs, + (char *) textPtr, argv[2], 0); + } else if ((c == 'c') && (strncmp(argv[1], "compare", length) == 0) + && (length >= 3)) { + int relation, value; + char *p; + + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " compare index1 op index2\"", (char *) NULL); + result = TCL_ERROR; + goto done; + } + if ((TkTextGetIndex(interp, textPtr, argv[2], &index1) != TCL_OK) + || (TkTextGetIndex(interp, textPtr, argv[4], &index2) + != TCL_OK)) { + result = TCL_ERROR; + goto done; + } + relation = TkTextIndexCmp(&index1, &index2); + p = argv[3]; + if (p[0] == '<') { + value = (relation < 0); + if ((p[1] == '=') && (p[2] == 0)) { + value = (relation <= 0); + } else if (p[1] != 0) { + compareError: + Tcl_AppendResult(interp, "bad comparison operator \"", + argv[3], "\": must be <, <=, ==, >=, >, or !=", + (char *) NULL); + result = TCL_ERROR; + goto done; + } + } else if (p[0] == '>') { + value = (relation > 0); + if ((p[1] == '=') && (p[2] == 0)) { + value = (relation >= 0); + } else if (p[1] != 0) { + goto compareError; + } + } else if ((p[0] == '=') && (p[1] == '=') && (p[2] == 0)) { + value = (relation == 0); + } else if ((p[0] == '!') && (p[1] == '=') && (p[2] == 0)) { + value = (relation != 0); + } else { + goto compareError; + } + interp->result = (value) ? "1" : "0"; + } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0) + && (length >= 3)) { + if (argc == 2) { + result = Tk_ConfigureInfo(interp, textPtr->tkwin, configSpecs, + (char *) textPtr, (char *) NULL, 0); + } else if (argc == 3) { + result = Tk_ConfigureInfo(interp, textPtr->tkwin, configSpecs, + (char *) textPtr, argv[2], 0); + } else { + result = ConfigureText(interp, textPtr, argc-2, argv+2, + TK_CONFIG_ARGV_ONLY); + } + } else if ((c == 'd') && (strncmp(argv[1], "debug", length) == 0) + && (length >= 3)) { + if (argc > 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " debug boolean\"", (char *) NULL); + result = TCL_ERROR; + goto done; + } + if (argc == 2) { + interp->result = (tkBTreeDebug) ? "1" : "0"; + } else { + if (Tcl_GetBoolean(interp, argv[2], &tkBTreeDebug) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + tkTextDebug = tkBTreeDebug; + } + } else if ((c == 'd') && (strncmp(argv[1], "delete", length) == 0) + && (length >= 3)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " delete index1 ?index2?\"", (char *) NULL); + result = TCL_ERROR; + goto done; + } + if (textPtr->state == tkTextNormalUid) { + result = DeleteChars(textPtr, argv[2], + (argc == 4) ? argv[3] : (char *) NULL); + } + } else if ((c == 'd') && (strncmp(argv[1], "dlineinfo", length) == 0) + && (length >= 2)) { + int x, y, width, height, base; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " dlineinfo index\"", (char *) NULL); + result = TCL_ERROR; + goto done; + } + if (TkTextGetIndex(interp, textPtr, argv[2], &index1) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + if (TkTextDLineInfo(textPtr, &index1, &x, &y, &width, &height, &base) + == 0) { + sprintf(interp->result, "%d %d %d %d %d", x, y, width, + height, base); + } + } else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " get index1 ?index2?\"", (char *) NULL); + result = TCL_ERROR; + goto done; + } + if (TkTextGetIndex(interp, textPtr, argv[2], &index1) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + if (argc == 3) { + index2 = index1; + TkTextIndexForwChars(&index2, 1, &index2); + } else if (TkTextGetIndex(interp, textPtr, argv[3], &index2) + != TCL_OK) { + result = TCL_ERROR; + goto done; + } + if (TkTextIndexCmp(&index1, &index2) >= 0) { + goto done; + } + while (1) { + int offset, last, savedChar; + TkTextSegment *segPtr; + + segPtr = TkTextIndexToSeg(&index1, &offset); + last = segPtr->size; + if (index1.linePtr == index2.linePtr) { + int last2; + + if (index2.charIndex == index1.charIndex) { + break; + } + last2 = index2.charIndex - index1.charIndex + offset; + if (last2 < last) { + last = last2; + } + } + if (segPtr->typePtr == &tkTextCharType) { + savedChar = segPtr->body.chars[last]; + segPtr->body.chars[last] = 0; + Tcl_AppendResult(interp, segPtr->body.chars + offset, + (char *) NULL); + segPtr->body.chars[last] = savedChar; + } + TkTextIndexForwChars(&index1, last-offset, &index1); + } + } else if ((c == 'i') && (strncmp(argv[1], "index", length) == 0) + && (length >= 3)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " index index\"", + (char *) NULL); + result = TCL_ERROR; + goto done; + } + if (TkTextGetIndex(interp, textPtr, argv[2], &index1) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + TkTextPrintIndex(&index1, interp->result); + } else if ((c == 'i') && (strncmp(argv[1], "insert", length) == 0) + && (length >= 3)) { + int i, j, numTags; + char **tagNames; + TkTextTag **oldTagArrayPtr; + + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], + " insert index chars ?tagList chars tagList ...?\"", + (char *) NULL); + result = TCL_ERROR; + goto done; + } + if (TkTextGetIndex(interp, textPtr, argv[2], &index1) != TCL_OK) { + result = TCL_ERROR; + goto done; + } + if (textPtr->state == tkTextNormalUid) { + for (j = 3; j < argc; j += 2) { + InsertChars(textPtr, &index1, argv[j]); + if (argc > (j+1)) { + TkTextIndexForwChars(&index1, (int) strlen(argv[j]), + &index2); + oldTagArrayPtr = TkBTreeGetTags(&index1, &numTags); + if (oldTagArrayPtr != NULL) { + for (i = 0; i < numTags; i++) { + TkBTreeTag(&index1, &index2, oldTagArrayPtr[i], 0); + } + ckfree((char *) oldTagArrayPtr); + } + if (Tcl_SplitList(interp, argv[j+1], &numTags, &tagNames) + != TCL_OK) { + result = TCL_ERROR; + goto done; + } + for (i = 0; i < numTags; i++) { + TkBTreeTag(&index1, &index2, + TkTextCreateTag(textPtr, tagNames[i]), 1); + } + ckfree((char *) tagNames); + index1 = index2; + } + } + } + } else if ((c == 'd') && (strncmp(argv[1], "dump", length) == 0)) { + result = TextDumpCmd(textPtr, interp, argc, argv); + } else if ((c == 'i') && (strncmp(argv[1], "image", length) == 0)) { + result = TkTextImageCmd(textPtr, interp, argc, argv); + } else if ((c == 'm') && (strncmp(argv[1], "mark", length) == 0)) { + result = TkTextMarkCmd(textPtr, interp, argc, argv); + } else if ((c == 's') && (strcmp(argv[1], "scan") == 0) && (length >= 2)) { + result = TkTextScanCmd(textPtr, interp, argc, argv); + } else if ((c == 's') && (strcmp(argv[1], "search") == 0) + && (length >= 3)) { + result = TextSearchCmd(textPtr, interp, argc, argv); + } else if ((c == 's') && (strcmp(argv[1], "see") == 0) && (length >= 3)) { + result = TkTextSeeCmd(textPtr, interp, argc, argv); + } else if ((c == 't') && (strcmp(argv[1], "tag") == 0)) { + result = TkTextTagCmd(textPtr, interp, argc, argv); + } else if ((c == 'w') && (strncmp(argv[1], "window", length) == 0)) { + result = TkTextWindowCmd(textPtr, interp, argc, argv); + } else if ((c == 'x') && (strncmp(argv[1], "xview", length) == 0)) { + result = TkTextXviewCmd(textPtr, interp, argc, argv); + } else if ((c == 'y') && (strncmp(argv[1], "yview", length) == 0) + && (length >= 2)) { + result = TkTextYviewCmd(textPtr, interp, argc, argv); + } else { + Tcl_AppendResult(interp, "bad option \"", argv[1], + "\": must be bbox, cget, compare, configure, debug, delete, ", + "dlineinfo, get, image, index, insert, mark, scan, search, see, ", + "tag, window, xview, or yview", + (char *) NULL); + result = TCL_ERROR; + } + + done: + Tcl_Release((ClientData) textPtr); + return result; +} + +/* + *---------------------------------------------------------------------- + * + * DestroyText -- + * + * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release + * to clean up the internal structure of a text at a safe time + * (when no-one is using it anymore). + * + * Results: + * None. + * + * Side effects: + * Everything associated with the text is freed up. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyText(memPtr) + char *memPtr; /* Info about text widget. */ +{ + register TkText *textPtr = (TkText *) memPtr; + Tcl_HashSearch search; + Tcl_HashEntry *hPtr; + TkTextTag *tagPtr; + + /* + * Free up all the stuff that requires special handling, then + * let Tk_FreeOptions handle all the standard option-related + * stuff. Special note: free up display-related information + * before deleting the B-tree, since display-related stuff + * may refer to stuff in the B-tree. + */ + + TkTextFreeDInfo(textPtr); + TkBTreeDestroy(textPtr->tree); + for (hPtr = Tcl_FirstHashEntry(&textPtr->tagTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + tagPtr = (TkTextTag *) Tcl_GetHashValue(hPtr); + TkTextFreeTag(textPtr, tagPtr); + } + Tcl_DeleteHashTable(&textPtr->tagTable); + for (hPtr = Tcl_FirstHashEntry(&textPtr->markTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + ckfree((char *) Tcl_GetHashValue(hPtr)); + } + Tcl_DeleteHashTable(&textPtr->markTable); + if (textPtr->tabArrayPtr != NULL) { + ckfree((char *) textPtr->tabArrayPtr); + } + if (textPtr->insertBlinkHandler != NULL) { + Tcl_DeleteTimerHandler(textPtr->insertBlinkHandler); + } + if (textPtr->bindingTable != NULL) { + Tk_DeleteBindingTable(textPtr->bindingTable); + } + + /* + * NOTE: do NOT free up selBorder, selBdString, or selFgColorPtr: + * they are duplicates of information in the "sel" tag, which was + * freed up as part of deleting the tags above. + */ + + textPtr->selBorder = NULL; + textPtr->selBdString = NULL; + textPtr->selFgColorPtr = NULL; + Tk_FreeOptions(configSpecs, (char *) textPtr, textPtr->display, 0); + ckfree((char *) textPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureText -- + * + * This procedure is called to process an argv/argc list, plus + * the Tk option database, in order to configure (or + * reconfigure) a text widget. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message. + * + * Side effects: + * Configuration information, such as text string, colors, font, + * etc. get set for textPtr; old resources get freed, if there + * were any. + * + *---------------------------------------------------------------------- + */ + +static int +ConfigureText(interp, textPtr, argc, argv, flags) + Tcl_Interp *interp; /* Used for error reporting. */ + register TkText *textPtr; /* Information about widget; may or may + * not already have values for some fields. */ + int argc; /* Number of valid entries in argv. */ + char **argv; /* Arguments. */ + int flags; /* Flags to pass to Tk_ConfigureWidget. */ +{ + int oldExport = textPtr->exportSelection; + + if (Tk_ConfigureWidget(interp, textPtr->tkwin, configSpecs, + argc, argv, (char *) textPtr, flags) != TCL_OK) { + return TCL_ERROR; + } + + /* + * A few other options also need special processing, such as parsing + * the geometry and setting the background from a 3-D border. + */ + + if ((textPtr->state != tkTextNormalUid) + && (textPtr->state != tkTextDisabledUid)) { + Tcl_AppendResult(interp, "bad state value \"", textPtr->state, + "\": must be normal or disabled", (char *) NULL); + textPtr->state = tkTextNormalUid; + return TCL_ERROR; + } + + if ((textPtr->wrapMode != tkTextCharUid) + && (textPtr->wrapMode != tkTextNoneUid) + && (textPtr->wrapMode != tkTextWordUid)) { + Tcl_AppendResult(interp, "bad wrap mode \"", textPtr->wrapMode, + "\": must be char, none, or word", (char *) NULL); + textPtr->wrapMode = tkTextCharUid; + return TCL_ERROR; + } + + Tk_SetBackgroundFromBorder(textPtr->tkwin, textPtr->border); + + /* + * Don't allow negative spacings. + */ + + if (textPtr->spacing1 < 0) { + textPtr->spacing1 = 0; + } + if (textPtr->spacing2 < 0) { + textPtr->spacing2 = 0; + } + if (textPtr->spacing3 < 0) { + textPtr->spacing3 = 0; + } + + /* + * Parse tab stops. + */ + + if (textPtr->tabArrayPtr != NULL) { + ckfree((char *) textPtr->tabArrayPtr); + textPtr->tabArrayPtr = NULL; + } + if (textPtr->tabOptionString != NULL) { + textPtr->tabArrayPtr = TkTextGetTabs(interp, textPtr->tkwin, + textPtr->tabOptionString); + if (textPtr->tabArrayPtr == NULL) { + Tcl_AddErrorInfo(interp,"\n (while processing -tabs option)"); + return TCL_ERROR; + } + } + + /* + * Make sure that configuration options are properly mirrored + * between the widget record and the "sel" tags. NOTE: we don't + * have to free up information during the mirroring; old + * information was freed when it was replaced in the widget + * record. + */ + + textPtr->selTagPtr->border = textPtr->selBorder; + if (textPtr->selTagPtr->bdString != textPtr->selBdString) { + textPtr->selTagPtr->bdString = textPtr->selBdString; + if (textPtr->selBdString != NULL) { + if (Tk_GetPixels(interp, textPtr->tkwin, textPtr->selBdString, + &textPtr->selTagPtr->borderWidth) != TCL_OK) { + return TCL_ERROR; + } + if (textPtr->selTagPtr->borderWidth < 0) { + textPtr->selTagPtr->borderWidth = 0; + } + } + } + textPtr->selTagPtr->fgColor = textPtr->selFgColorPtr; + textPtr->selTagPtr->affectsDisplay = 0; + if ((textPtr->selTagPtr->border != NULL) + || (textPtr->selTagPtr->bdString != NULL) + || (textPtr->selTagPtr->reliefString != NULL) + || (textPtr->selTagPtr->bgStipple != None) + || (textPtr->selTagPtr->fgColor != NULL) + || (textPtr->selTagPtr->tkfont != None) + || (textPtr->selTagPtr->fgStipple != None) + || (textPtr->selTagPtr->justifyString != NULL) + || (textPtr->selTagPtr->lMargin1String != NULL) + || (textPtr->selTagPtr->lMargin2String != NULL) + || (textPtr->selTagPtr->offsetString != NULL) + || (textPtr->selTagPtr->overstrikeString != NULL) + || (textPtr->selTagPtr->rMarginString != NULL) + || (textPtr->selTagPtr->spacing1String != NULL) + || (textPtr->selTagPtr->spacing2String != NULL) + || (textPtr->selTagPtr->spacing3String != NULL) + || (textPtr->selTagPtr->tabString != NULL) + || (textPtr->selTagPtr->underlineString != NULL) + || (textPtr->selTagPtr->wrapMode != NULL)) { + textPtr->selTagPtr->affectsDisplay = 1; + } + TkTextRedrawTag(textPtr, (TkTextIndex *) NULL, (TkTextIndex *) NULL, + textPtr->selTagPtr, 1); + + /* + * Claim the selection if we've suddenly started exporting it and there + * are tagged characters. + */ + + if (textPtr->exportSelection && (!oldExport)) { + TkTextSearch search; + TkTextIndex first, last; + + TkTextMakeIndex(textPtr->tree, 0, 0, &first); + TkTextMakeIndex(textPtr->tree, + TkBTreeNumLines(textPtr->tree), 0, &last); + TkBTreeStartSearch(&first, &last, textPtr->selTagPtr, &search); + if (TkBTreeCharTagged(&first, textPtr->selTagPtr) + || TkBTreeNextTag(&search)) { + Tk_OwnSelection(textPtr->tkwin, XA_PRIMARY, TkTextLostSelection, + (ClientData) textPtr); + textPtr->flags |= GOT_SELECTION; + } + } + + /* + * Register the desired geometry for the window, and arrange for + * the window to be redisplayed. + */ + + if (textPtr->width <= 0) { + textPtr->width = 1; + } + if (textPtr->height <= 0) { + textPtr->height = 1; + } + TextWorldChanged((ClientData) textPtr); + return TCL_OK; +} + +/* + *--------------------------------------------------------------------------- + * + * TextWorldChanged -- + * + * This procedure is called when the world has changed in some + * way and the widget needs to recompute all its graphics contexts + * and determine its new geometry. + * + * Results: + * None. + * + * Side effects: + * Configures all tags in the Text with a empty argc/argv, for + * the side effect of causing all the items to recompute their + * geometry and to be redisplayed. + * + *--------------------------------------------------------------------------- + */ + +static void +TextWorldChanged(instanceData) + ClientData instanceData; /* Information about widget. */ +{ + TkText *textPtr; + Tk_FontMetrics fm; + + textPtr = (TkText *) instanceData; + + textPtr->charWidth = Tk_TextWidth(textPtr->tkfont, "0", 1); + if (textPtr->charWidth <= 0) { + textPtr->charWidth = 1; + } + Tk_GetFontMetrics(textPtr->tkfont, &fm); + Tk_GeometryRequest(textPtr->tkwin, + textPtr->width * textPtr->charWidth + 2*textPtr->borderWidth + + 2*textPtr->padX + 2*textPtr->highlightWidth, + textPtr->height * (fm.linespace + textPtr->spacing1 + + textPtr->spacing3) + 2*textPtr->borderWidth + + 2*textPtr->padY + 2*textPtr->highlightWidth); + Tk_SetInternalBorder(textPtr->tkwin, + textPtr->borderWidth + textPtr->highlightWidth); + if (textPtr->setGrid) { + Tk_SetGrid(textPtr->tkwin, textPtr->width, textPtr->height, + textPtr->charWidth, fm.linespace); + } else { + Tk_UnsetGrid(textPtr->tkwin); + } + + TkTextRelayoutWindow(textPtr); +} + +/* + *-------------------------------------------------------------- + * + * TextEventProc -- + * + * This procedure is invoked by the Tk dispatcher on + * structure changes to a text. For texts with 3D + * borders, this procedure is also invoked for exposures. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +TextEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + register XEvent *eventPtr; /* Information about event. */ +{ + register TkText *textPtr = (TkText *) clientData; + TkTextIndex index, index2; + + if (eventPtr->type == Expose) { + TkTextRedrawRegion(textPtr, eventPtr->xexpose.x, + eventPtr->xexpose.y, eventPtr->xexpose.width, + eventPtr->xexpose.height); + } else if (eventPtr->type == ConfigureNotify) { + if ((textPtr->prevWidth != Tk_Width(textPtr->tkwin)) + || (textPtr->prevHeight != Tk_Height(textPtr->tkwin))) { + TkTextRelayoutWindow(textPtr); + textPtr->prevWidth = Tk_Width(textPtr->tkwin); + textPtr->prevHeight = Tk_Height(textPtr->tkwin); + } + } else if (eventPtr->type == DestroyNotify) { + if (textPtr->tkwin != NULL) { + if (textPtr->setGrid) { + Tk_UnsetGrid(textPtr->tkwin); + } + textPtr->tkwin = NULL; + Tcl_DeleteCommandFromToken(textPtr->interp, + textPtr->widgetCmd); + } + Tcl_EventuallyFree((ClientData) textPtr, DestroyText); + } else if ((eventPtr->type == FocusIn) || (eventPtr->type == FocusOut)) { + if (eventPtr->xfocus.detail != NotifyInferior) { + Tcl_DeleteTimerHandler(textPtr->insertBlinkHandler); + if (eventPtr->type == FocusIn) { + textPtr->flags |= GOT_FOCUS | INSERT_ON; + if (textPtr->insertOffTime != 0) { + textPtr->insertBlinkHandler = Tcl_CreateTimerHandler( + textPtr->insertOnTime, TextBlinkProc, + (ClientData) textPtr); + } + } else { + textPtr->flags &= ~(GOT_FOCUS | INSERT_ON); + textPtr->insertBlinkHandler = (Tcl_TimerToken) NULL; + } +#ifndef ALWAYS_SHOW_SELECTION + TkTextRedrawTag(textPtr, NULL, NULL, textPtr->selTagPtr, 1); +#endif + TkTextMarkSegToIndex(textPtr, textPtr->insertMarkPtr, &index); + TkTextIndexForwChars(&index, 1, &index2); + TkTextChanged(textPtr, &index, &index2); + if (textPtr->highlightWidth > 0) { + TkTextRedrawRegion(textPtr, 0, 0, textPtr->highlightWidth, + textPtr->highlightWidth); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TextCmdDeletedProc -- + * + * This procedure is invoked when a widget command is deleted. If + * the widget isn't already in the process of being destroyed, + * this command destroys it. + * + * Results: + * None. + * + * Side effects: + * The widget is destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +TextCmdDeletedProc(clientData) + ClientData clientData; /* Pointer to widget record for widget. */ +{ + TkText *textPtr = (TkText *) clientData; + Tk_Window tkwin = textPtr->tkwin; + + /* + * This procedure could be invoked either because the window was + * destroyed and the command was then deleted (in which case tkwin + * is NULL) or because the command was deleted, and then this procedure + * destroys the widget. + */ + + if (tkwin != NULL) { + if (textPtr->setGrid) { + Tk_UnsetGrid(textPtr->tkwin); + } + textPtr->tkwin = NULL; + Tk_DestroyWindow(tkwin); + } +} + +/* + *---------------------------------------------------------------------- + * + * InsertChars -- + * + * This procedure implements most of the functionality of the + * "insert" widget command. + * + * Results: + * None. + * + * Side effects: + * The characters in "string" get added to the text just before + * the character indicated by "indexPtr". + * + *---------------------------------------------------------------------- + */ + +static void +InsertChars(textPtr, indexPtr, string) + TkText *textPtr; /* Overall information about text widget. */ + TkTextIndex *indexPtr; /* Where to insert new characters. May be + * modified and/or invalidated. */ + char *string; /* Null-terminated string containing new + * information to add to text. */ +{ + int lineIndex, resetView, offset; + TkTextIndex newTop; + + /* + * Don't allow insertions on the last (dummy) line of the text. + */ + + lineIndex = TkBTreeLineIndex(indexPtr->linePtr); + if (lineIndex == TkBTreeNumLines(textPtr->tree)) { + lineIndex--; + TkTextMakeIndex(textPtr->tree, lineIndex, 1000000, indexPtr); + } + + /* + * Notify the display module that lines are about to change, then do + * the insertion. If the insertion occurs on the top line of the + * widget (textPtr->topIndex), then we have to recompute topIndex + * after the insertion, since the insertion could invalidate it. + */ + + resetView = offset = 0; + if (indexPtr->linePtr == textPtr->topIndex.linePtr) { + resetView = 1; + offset = textPtr->topIndex.charIndex; + if (offset > indexPtr->charIndex) { + offset += strlen(string); + } + } + TkTextChanged(textPtr, indexPtr, indexPtr); + TkBTreeInsertChars(indexPtr, string); + if (resetView) { + TkTextMakeIndex(textPtr->tree, lineIndex, 0, &newTop); + TkTextIndexForwChars(&newTop, offset, &newTop); + TkTextSetYView(textPtr, &newTop, 0); + } + + /* + * Invalidate any selection retrievals in progress. + */ + + textPtr->abortSelections = 1; +} + +/* + *---------------------------------------------------------------------- + * + * DeleteChars -- + * + * This procedure implements most of the functionality of the + * "delete" widget command. + * + * Results: + * Returns a standard Tcl result, and leaves an error message + * in textPtr->interp if there is an error. + * + * Side effects: + * Characters get deleted from the text. + * + *---------------------------------------------------------------------- + */ + +static int +DeleteChars(textPtr, index1String, index2String) + TkText *textPtr; /* Overall information about text widget. */ + char *index1String; /* String describing location of first + * character to delete. */ + char *index2String; /* String describing location of last + * character to delete. NULL means just + * delete the one character given by + * index1String. */ +{ + int line1, line2, line, charIndex, resetView; + TkTextIndex index1, index2; + + /* + * Parse the starting and stopping indices. + */ + + if (TkTextGetIndex(textPtr->interp, textPtr, index1String, &index1) + != TCL_OK) { + return TCL_ERROR; + } + if (index2String != NULL) { + if (TkTextGetIndex(textPtr->interp, textPtr, index2String, &index2) + != TCL_OK) { + return TCL_ERROR; + } + } else { + index2 = index1; + TkTextIndexForwChars(&index2, 1, &index2); + } + + /* + * Make sure there's really something to delete. + */ + + if (TkTextIndexCmp(&index1, &index2) >= 0) { + return TCL_OK; + } + + /* + * The code below is ugly, but it's needed to make sure there + * is always a dummy empty line at the end of the text. If the + * final newline of the file (just before the dummy line) is being + * deleted, then back up index to just before the newline. If + * there is a newline just before the first character being deleted, + * then back up the first index too, so that an even number of lines + * gets deleted. Furthermore, remove any tags that are present on + * the newline that isn't going to be deleted after all (this simulates + * deleting the newline and then adding a "clean" one back again). + */ + + line1 = TkBTreeLineIndex(index1.linePtr); + line2 = TkBTreeLineIndex(index2.linePtr); + if (line2 == TkBTreeNumLines(textPtr->tree)) { + TkTextTag **arrayPtr; + int arraySize, i; + TkTextIndex oldIndex2; + + oldIndex2 = index2; + TkTextIndexBackChars(&oldIndex2, 1, &index2); + line2--; + if ((index1.charIndex == 0) && (line1 != 0)) { + TkTextIndexBackChars(&index1, 1, &index1); + line1--; + } + arrayPtr = TkBTreeGetTags(&index2, &arraySize); + if (arrayPtr != NULL) { + for (i = 0; i < arraySize; i++) { + TkBTreeTag(&index2, &oldIndex2, arrayPtr[i], 0); + } + ckfree((char *) arrayPtr); + } + } + + /* + * Tell the display what's about to happen so it can discard + * obsolete display information, then do the deletion. Also, + * if the deletion involves the top line on the screen, then + * we have to reset the view (the deletion will invalidate + * textPtr->topIndex). Compute what the new first character + * will be, then do the deletion, then reset the view. + */ + + TkTextChanged(textPtr, &index1, &index2); + resetView = line = charIndex = 0; + if (TkTextIndexCmp(&index2, &textPtr->topIndex) >= 0) { + if (TkTextIndexCmp(&index1, &textPtr->topIndex) <= 0) { + /* + * Deletion range straddles topIndex: use the beginning + * of the range as the new topIndex. + */ + + resetView = 1; + line = line1; + charIndex = index1.charIndex; + } else if (index1.linePtr == textPtr->topIndex.linePtr) { + /* + * Deletion range starts on top line but after topIndex. + * Use the current topIndex as the new one. + */ + + resetView = 1; + line = line1; + charIndex = textPtr->topIndex.charIndex; + } + } else if (index2.linePtr == textPtr->topIndex.linePtr) { + /* + * Deletion range ends on top line but before topIndex. + * Figure out what will be the new character index for + * the character currently pointed to by topIndex. + */ + + resetView = 1; + line = line2; + charIndex = textPtr->topIndex.charIndex; + if (index1.linePtr != index2.linePtr) { + charIndex -= index2.charIndex; + } else { + charIndex -= (index2.charIndex - index1.charIndex); + } + } + TkBTreeDeleteChars(&index1, &index2); + if (resetView) { + TkTextMakeIndex(textPtr->tree, line, charIndex, &index1); + TkTextSetYView(textPtr, &index1, 0); + } + + /* + * Invalidate any selection retrievals in progress. + */ + + textPtr->abortSelections = 1; + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TextFetchSelection -- + * + * This procedure is called back by Tk when the selection is + * requested by someone. It returns part or all of the selection + * in a buffer provided by the caller. + * + * Results: + * The return value is the number of non-NULL bytes stored + * at buffer. Buffer is filled (or partially filled) with a + * NULL-terminated string containing part or all of the selection, + * as given by offset and maxBytes. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +TextFetchSelection(clientData, offset, buffer, maxBytes) + ClientData clientData; /* Information about text widget. */ + int offset; /* Offset within selection of first + * character to be returned. */ + char *buffer; /* Location in which to place + * selection. */ + int maxBytes; /* Maximum number of bytes to place + * at buffer, not including terminating + * NULL character. */ +{ + register TkText *textPtr = (TkText *) clientData; + TkTextIndex eof; + int count, chunkSize, offsetInSeg; + TkTextSearch search; + TkTextSegment *segPtr; + + if (!textPtr->exportSelection) { + return -1; + } + + /* + * Find the beginning of the next range of selected text. Note: if + * the selection is being retrieved in multiple pieces (offset != 0) + * and some modification has been made to the text that affects the + * selection then reject the selection request (make 'em start over + * again). + */ + + if (offset == 0) { + TkTextMakeIndex(textPtr->tree, 0, 0, &textPtr->selIndex); + textPtr->abortSelections = 0; + } else if (textPtr->abortSelections) { + return 0; + } + TkTextMakeIndex(textPtr->tree, TkBTreeNumLines(textPtr->tree), 0, &eof); + TkBTreeStartSearch(&textPtr->selIndex, &eof, textPtr->selTagPtr, &search); + if (!TkBTreeCharTagged(&textPtr->selIndex, textPtr->selTagPtr)) { + if (!TkBTreeNextTag(&search)) { + if (offset == 0) { + return -1; + } else { + return 0; + } + } + textPtr->selIndex = search.curIndex; + } + + /* + * Each iteration through the outer loop below scans one selected range. + * Each iteration through the inner loop scans one segment in the + * selected range. + */ + + count = 0; + while (1) { + /* + * Find the end of the current range of selected text. + */ + + if (!TkBTreeNextTag(&search)) { + panic("TextFetchSelection couldn't find end of range"); + } + + /* + * Copy information from character segments into the buffer + * until either we run out of space in the buffer or we get + * to the end of this range of text. + */ + + while (1) { + if (maxBytes == 0) { + goto done; + } + segPtr = TkTextIndexToSeg(&textPtr->selIndex, &offsetInSeg); + chunkSize = segPtr->size - offsetInSeg; + if (chunkSize > maxBytes) { + chunkSize = maxBytes; + } + if (textPtr->selIndex.linePtr == search.curIndex.linePtr) { + int leftInRange; + + leftInRange = search.curIndex.charIndex + - textPtr->selIndex.charIndex; + if (leftInRange < chunkSize) { + chunkSize = leftInRange; + if (chunkSize <= 0) { + break; + } + } + } + if (segPtr->typePtr == &tkTextCharType) { + memcpy((VOID *) buffer, (VOID *) (segPtr->body.chars + + offsetInSeg), (size_t) chunkSize); + buffer += chunkSize; + maxBytes -= chunkSize; + count += chunkSize; + } + TkTextIndexForwChars(&textPtr->selIndex, chunkSize, + &textPtr->selIndex); + } + + /* + * Find the beginning of the next range of selected text. + */ + + if (!TkBTreeNextTag(&search)) { + break; + } + textPtr->selIndex = search.curIndex; + } + + done: + *buffer = 0; + return count; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextLostSelection -- + * + * This procedure is called back by Tk when the selection is + * grabbed away from a text widget. On Windows and Mac systems, we + * want to remember the selection for the next time the focus + * enters the window. On Unix, just remove the "sel" tag from + * everything in the widget. + * + * Results: + * None. + * + * Side effects: + * The "sel" tag is cleared from the window. + * + *---------------------------------------------------------------------- + */ + +void +TkTextLostSelection(clientData) + ClientData clientData; /* Information about text widget. */ +{ + register TkText *textPtr = (TkText *) clientData; +#ifdef ALWAYS_SHOW_SELECTION + TkTextIndex start, end; + + if (!textPtr->exportSelection) { + return; + } + + /* + * On Windows and Mac systems, we want to remember the selection + * for the next time the focus enters the window. On Unix, + * just remove the "sel" tag from everything in the widget. + */ + + TkTextMakeIndex(textPtr->tree, 0, 0, &start); + TkTextMakeIndex(textPtr->tree, TkBTreeNumLines(textPtr->tree), 0, &end); + TkTextRedrawTag(textPtr, &start, &end, textPtr->selTagPtr, 1); + TkBTreeTag(&start, &end, textPtr->selTagPtr, 0); +#endif + textPtr->flags &= ~GOT_SELECTION; +} + +/* + *---------------------------------------------------------------------- + * + * TextBlinkProc -- + * + * This procedure is called as a timer handler to blink the + * insertion cursor off and on. + * + * Results: + * None. + * + * Side effects: + * The cursor gets turned on or off, redisplay gets invoked, + * and this procedure reschedules itself. + * + *---------------------------------------------------------------------- + */ + +static void +TextBlinkProc(clientData) + ClientData clientData; /* Pointer to record describing text. */ +{ + register TkText *textPtr = (TkText *) clientData; + TkTextIndex index; + int x, y, w, h; + + if (!(textPtr->flags & GOT_FOCUS) || (textPtr->insertOffTime == 0)) { + return; + } + if (textPtr->flags & INSERT_ON) { + textPtr->flags &= ~INSERT_ON; + textPtr->insertBlinkHandler = Tcl_CreateTimerHandler( + textPtr->insertOffTime, TextBlinkProc, (ClientData) textPtr); + } else { + textPtr->flags |= INSERT_ON; + textPtr->insertBlinkHandler = Tcl_CreateTimerHandler( + textPtr->insertOnTime, TextBlinkProc, (ClientData) textPtr); + } + TkTextMarkSegToIndex(textPtr, textPtr->insertMarkPtr, &index); + TkTextCharBbox(textPtr, &index, &x, &y, &w, &h); + TkTextRedrawRegion(textPtr, x - textPtr->insertWidth / 2, y, + textPtr->insertWidth, h); +} + +/* + *---------------------------------------------------------------------- + * + * TextSearchCmd -- + * + * This procedure is invoked to process the "search" widget command + * for text widgets. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +static int +TextSearchCmd(textPtr, interp, argc, argv) + TkText *textPtr; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + int backwards, exact, c, i, argsLeft, noCase, leftToScan; + size_t length; + int numLines, startingLine, startingChar, lineNum, firstChar, lastChar; + int code, matchLength, matchChar, passes, stopLine, searchWholeText; + int patLength; + char *arg, *pattern, *varName, *p, *startOfLine; + char buffer[20]; + TkTextIndex index, stopIndex; + Tcl_DString line, patDString; + TkTextSegment *segPtr; + TkTextLine *linePtr; + Tcl_RegExp regexp = NULL; /* Initialization needed only to + * prevent compiler warning. */ + + /* + * Parse switches and other arguments. + */ + + exact = 1; + backwards = 0; + noCase = 0; + varName = NULL; + for (i = 2; i < argc; i++) { + arg = argv[i]; + if (arg[0] != '-') { + break; + } + length = strlen(arg); + if (length < 2) { + badSwitch: + Tcl_AppendResult(interp, "bad switch \"", arg, + "\": must be -forward, -backward, -exact, -regexp, ", + "-nocase, -count, or --", (char *) NULL); + return TCL_ERROR; + } + c = arg[1]; + if ((c == 'b') && (strncmp(argv[i], "-backwards", length) == 0)) { + backwards = 1; + } else if ((c == 'c') && (strncmp(argv[i], "-count", length) == 0)) { + if (i >= (argc-1)) { + interp->result = "no value given for \"-count\" option"; + return TCL_ERROR; + } + i++; + varName = argv[i]; + } else if ((c == 'e') && (strncmp(argv[i], "-exact", length) == 0)) { + exact = 1; + } else if ((c == 'f') && (strncmp(argv[i], "-forwards", length) == 0)) { + backwards = 0; + } else if ((c == 'n') && (strncmp(argv[i], "-nocase", length) == 0)) { + noCase = 1; + } else if ((c == 'r') && (strncmp(argv[i], "-regexp", length) == 0)) { + exact = 0; + } else if ((c == '-') && (strncmp(argv[i], "--", length) == 0)) { + i++; + break; + } else { + goto badSwitch; + } + } + argsLeft = argc - (i+2); + if ((argsLeft != 0) && (argsLeft != 1)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " search ?switches? pattern index ?stopIndex?", + (char *) NULL); + return TCL_ERROR; + } + pattern = argv[i]; + + /* + * Convert the pattern to lower-case if we're supposed to ignore case. + */ + + if (noCase) { + Tcl_DStringInit(&patDString); + Tcl_DStringAppend(&patDString, pattern, -1); + pattern = Tcl_DStringValue(&patDString); + for (p = pattern; *p != 0; p++) { + if (isupper(UCHAR(*p))) { + *p = tolower(UCHAR(*p)); + } + } + } + + if (TkTextGetIndex(interp, textPtr, argv[i+1], &index) != TCL_OK) { + return TCL_ERROR; + } + numLines = TkBTreeNumLines(textPtr->tree); + startingLine = TkBTreeLineIndex(index.linePtr); + startingChar = index.charIndex; + if (startingLine >= numLines) { + if (backwards) { + startingLine = TkBTreeNumLines(textPtr->tree) - 1; + startingChar = TkBTreeCharsInLine(TkBTreeFindLine(textPtr->tree, + startingLine)); + } else { + startingLine = 0; + startingChar = 0; + } + } + if (argsLeft == 1) { + if (TkTextGetIndex(interp, textPtr, argv[i+2], &stopIndex) != TCL_OK) { + return TCL_ERROR; + } + stopLine = TkBTreeLineIndex(stopIndex.linePtr); + if (!backwards && (stopLine == numLines)) { + stopLine = numLines-1; + } + searchWholeText = 0; + } else { + stopLine = 0; + searchWholeText = 1; + } + + /* + * Scan through all of the lines of the text circularly, starting + * at the given index. + */ + + matchLength = patLength = 0; /* Only needed to prevent compiler + * warnings. */ + if (exact) { + patLength = strlen(pattern); + } else { + regexp = Tcl_RegExpCompile(interp, pattern); + if (regexp == NULL) { + return TCL_ERROR; + } + } + lineNum = startingLine; + code = TCL_OK; + Tcl_DStringInit(&line); + for (passes = 0; passes < 2; ) { + if (lineNum >= numLines) { + /* + * Don't search the dummy last line of the text. + */ + + goto nextLine; + } + + /* + * Extract the text from the line. If we're doing regular + * expression matching, drop the newline from the line, so + * that "$" can be used to match the end of the line. + */ + + linePtr = TkBTreeFindLine(textPtr->tree, lineNum); + for (segPtr = linePtr->segPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + if (segPtr->typePtr != &tkTextCharType) { + continue; + } + Tcl_DStringAppend(&line, segPtr->body.chars, segPtr->size); + } + if (!exact) { + Tcl_DStringSetLength(&line, Tcl_DStringLength(&line)-1); + } + startOfLine = Tcl_DStringValue(&line); + + /* + * If we're ignoring case, convert the line to lower case. + */ + + if (noCase) { + for (p = Tcl_DStringValue(&line); *p != 0; p++) { + if (isupper(UCHAR(*p))) { + *p = tolower(UCHAR(*p)); + } + } + } + + /* + * Check for matches within the current line. If so, and if we're + * searching backwards, repeat the search to find the last match + * in the line. + */ + + matchChar = -1; + firstChar = 0; + lastChar = INT_MAX; + if (lineNum == startingLine) { + int indexInDString; + + /* + * The starting line is tricky: the first time we see it + * we check one part of the line, and the second pass through + * we check the other part of the line. We have to be very + * careful here because there could be embedded windows or + * other things that are not in the extracted line. Rescan + * the original line to compute the index in it of the first + * character. + */ + + indexInDString = startingChar; + for (segPtr = linePtr->segPtr, leftToScan = startingChar; + leftToScan > 0; segPtr = segPtr->nextPtr) { + if (segPtr->typePtr != &tkTextCharType) { + indexInDString -= segPtr->size; + } + leftToScan -= segPtr->size; + } + + passes++; + if ((passes == 1) ^ backwards) { + /* + * Only use the last part of the line. + */ + + firstChar = indexInDString; + if (firstChar >= Tcl_DStringLength(&line)) { + goto nextLine; + } + } else { + /* + * Use only the first part of the line. + */ + + lastChar = indexInDString; + } + } + do { + int thisLength; + if (exact) { + p = strstr(startOfLine + firstChar, pattern); + if (p == NULL) { + break; + } + i = p - startOfLine; + thisLength = patLength; + } else { + char *start, *end; + int match; + + match = Tcl_RegExpExec(interp, regexp, + startOfLine + firstChar, startOfLine); + if (match < 0) { + code = TCL_ERROR; + goto done; + } + if (!match) { + break; + } + Tcl_RegExpRange(regexp, 0, &start, &end); + i = start - startOfLine; + thisLength = end - start; + } + if (i >= lastChar) { + break; + } + matchChar = i; + matchLength = thisLength; + firstChar = matchChar+1; + } while (backwards); + + /* + * If we found a match then we're done. Make sure that + * the match occurred before the stopping index, if one was + * specified. + */ + + if (matchChar >= 0) { + /* + * The index information returned by the regular expression + * parser only considers textual information: it doesn't + * account for embedded windows or any other non-textual info. + * Scan through the line's segments again to adjust both + * matchChar and matchCount. + */ + + for (segPtr = linePtr->segPtr, leftToScan = matchChar; + leftToScan >= 0; segPtr = segPtr->nextPtr) { + if (segPtr->typePtr != &tkTextCharType) { + matchChar += segPtr->size; + continue; + } + leftToScan -= segPtr->size; + } + for (leftToScan += matchLength; leftToScan > 0; + segPtr = segPtr->nextPtr) { + if (segPtr->typePtr != &tkTextCharType) { + matchLength += segPtr->size; + continue; + } + leftToScan -= segPtr->size; + } + TkTextMakeIndex(textPtr->tree, lineNum, matchChar, &index); + if (!searchWholeText) { + if (!backwards && (TkTextIndexCmp(&index, &stopIndex) >= 0)) { + goto done; + } + if (backwards && (TkTextIndexCmp(&index, &stopIndex) < 0)) { + goto done; + } + } + if (varName != NULL) { + sprintf(buffer, "%d", matchLength); + if (Tcl_SetVar(interp, varName, buffer, TCL_LEAVE_ERR_MSG) + == NULL) { + code = TCL_ERROR; + goto done; + } + } + TkTextPrintIndex(&index, interp->result); + goto done; + } + + /* + * Go to the next (or previous) line; + */ + + nextLine: + if (backwards) { + lineNum--; + if (!searchWholeText) { + if (lineNum < stopLine) { + break; + } + } else if (lineNum < 0) { + lineNum = numLines-1; + } + } else { + lineNum++; + if (!searchWholeText) { + if (lineNum > stopLine) { + break; + } + } else if (lineNum >= numLines) { + lineNum = 0; + } + } + Tcl_DStringSetLength(&line, 0); + } + done: + Tcl_DStringFree(&line); + if (noCase) { + Tcl_DStringFree(&patDString); + } + return code; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextGetTabs -- + * + * Parses a string description of a set of tab stops. + * + * Results: + * The return value is a pointer to a malloc'ed structure holding + * parsed information about the tab stops. If an error occurred + * then the return value is NULL and an error message is left in + * interp->result. + * + * Side effects: + * Memory is allocated for the structure that is returned. It is + * up to the caller to free this structure when it is no longer + * needed. + * + *---------------------------------------------------------------------- + */ + +TkTextTabArray * +TkTextGetTabs(interp, tkwin, string) + Tcl_Interp *interp; /* Used for error reporting. */ + Tk_Window tkwin; /* Window in which the tabs will be + * used. */ + char *string; /* Description of the tab stops. See + * the text manual entry for details. */ +{ + int argc, i, count, c; + char **argv; + TkTextTabArray *tabArrayPtr; + TkTextTab *tabPtr; + + if (Tcl_SplitList(interp, string, &argc, &argv) != TCL_OK) { + return NULL; + } + + /* + * First find out how many entries we need to allocate in the + * tab array. + */ + + count = 0; + for (i = 0; i < argc; i++) { + c = argv[i][0]; + if ((c != 'l') && (c != 'r') && (c != 'c') && (c != 'n')) { + count++; + } + } + + /* + * Parse the elements of the list one at a time to fill in the + * array. + */ + + tabArrayPtr = (TkTextTabArray *) ckalloc((unsigned) + (sizeof(TkTextTabArray) + (count-1)*sizeof(TkTextTab))); + tabArrayPtr->numTabs = 0; + for (i = 0, tabPtr = &tabArrayPtr->tabs[0]; i < argc; i++, tabPtr++) { + if (Tk_GetPixels(interp, tkwin, argv[i], &tabPtr->location) + != TCL_OK) { + goto error; + } + tabArrayPtr->numTabs++; + + /* + * See if there is an explicit alignment in the next list + * element. Otherwise just use "left". + */ + + tabPtr->alignment = LEFT; + if ((i+1) == argc) { + continue; + } + c = UCHAR(argv[i+1][0]); + if (!isalpha(c)) { + continue; + } + i += 1; + if ((c == 'l') && (strncmp(argv[i], "left", + strlen(argv[i])) == 0)) { + tabPtr->alignment = LEFT; + } else if ((c == 'r') && (strncmp(argv[i], "right", + strlen(argv[i])) == 0)) { + tabPtr->alignment = RIGHT; + } else if ((c == 'c') && (strncmp(argv[i], "center", + strlen(argv[i])) == 0)) { + tabPtr->alignment = CENTER; + } else if ((c == 'n') && (strncmp(argv[i], + "numeric", strlen(argv[i])) == 0)) { + tabPtr->alignment = NUMERIC; + } else { + Tcl_AppendResult(interp, "bad tab alignment \"", + argv[i], "\": must be left, right, center, or numeric", + (char *) NULL); + goto error; + } + } + ckfree((char *) argv); + return tabArrayPtr; + + error: + ckfree((char *) tabArrayPtr); + ckfree((char *) argv); + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TextDumpCmd -- + * + * Return information about the text, tags, marks, and embedded windows + * and images in a text widget. See the man page for the description + * of the text dump operation for all the details. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * Memory is allocated for the result, if needed (standard Tcl result + * side effects). + * + *---------------------------------------------------------------------- + */ + +static int +TextDumpCmd(textPtr, interp, argc, argv) + register TkText *textPtr; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. Someone else has already + * parsed this command enough to know that + * argv[1] is "dump". */ +{ + TkTextIndex index1, index2; + int arg; + int lineno; /* Current line number */ + int what = 0; /* bitfield to select segment types */ + int atEnd; /* True if dumping up to logical end */ + TkTextLine *linePtr; + char *command = NULL; /* Script callback to apply to segments */ +#define TK_DUMP_TEXT 0x1 +#define TK_DUMP_MARK 0x2 +#define TK_DUMP_TAG 0x4 +#define TK_DUMP_WIN 0x8 +#define TK_DUMP_IMG 0x10 +#define TK_DUMP_ALL (TK_DUMP_TEXT|TK_DUMP_MARK|TK_DUMP_TAG| \ + TK_DUMP_WIN|TK_DUMP_IMG) + + for (arg=2 ; argv[arg] != (char *) NULL ; arg++) { + size_t len; + if (argv[arg][0] != '-') { + break; + } + len = strlen(argv[arg]); + if (strncmp("-all", argv[arg], len) == 0) { + what = TK_DUMP_ALL; + } else if (strncmp("-text", argv[arg], len) == 0) { + what |= TK_DUMP_TEXT; + } else if (strncmp("-tag", argv[arg], len) == 0) { + what |= TK_DUMP_TAG; + } else if (strncmp("-mark", argv[arg], len) == 0) { + what |= TK_DUMP_MARK; + } else if (strncmp("-image", argv[arg], len) == 0) { + what |= TK_DUMP_IMG; + } else if (strncmp("-window", argv[arg], len) == 0) { + what |= TK_DUMP_WIN; + } else if (strncmp("-command", argv[arg], len) == 0) { + arg++; + if (arg >= argc) { + Tcl_AppendResult(interp, "Usage: ", argv[0], " dump ?-all -image -text -mark -tag -window? ?-command script? index ?index2?", NULL); + return TCL_ERROR; + } + command = argv[arg]; + } else { + Tcl_AppendResult(interp, "Usage: ", argv[0], " dump ?-all -image -text -mark -tag -window? ?-command script? index ?index2?", NULL); + return TCL_ERROR; + } + } + if (arg >= argc) { + Tcl_AppendResult(interp, "Usage: ", argv[0], " dump ?-all -image -text -mark -tag -window? ?-command script? index ?index2?", NULL); + return TCL_ERROR; + } + if (what == 0) { + what = TK_DUMP_ALL; + } + if (TkTextGetIndex(interp, textPtr, argv[arg], &index1) != TCL_OK) { + return TCL_ERROR; + } + lineno = TkBTreeLineIndex(index1.linePtr) + 1; + arg++; + atEnd = 0; + if (argc == arg) { + TkTextIndexForwChars(&index1, 1, &index2); + } else { + if (TkTextGetIndex(interp, textPtr, argv[arg], &index2) != TCL_OK) { + return TCL_ERROR; + } + if (strncmp(argv[arg], "end", strlen(argv[arg])) == 0) { + atEnd = 1; + } + } + if (TkTextIndexCmp(&index1, &index2) >= 0) { + return TCL_OK; + } + if (index1.linePtr == index2.linePtr) { + DumpLine(interp, textPtr, what, index1.linePtr, + index1.charIndex, index2.charIndex, lineno, command); + } else { + DumpLine(interp, textPtr, what, index1.linePtr, + index1.charIndex, 32000000, lineno, command); + linePtr = index1.linePtr; + while ((linePtr = TkBTreeNextLine(linePtr)) != (TkTextLine *)NULL) { + lineno++; + if (linePtr == index2.linePtr) { + break; + } + DumpLine(interp, textPtr, what, linePtr, 0, 32000000, + lineno, command); + } + DumpLine(interp, textPtr, what, index2.linePtr, 0, + index2.charIndex, lineno, command); + } + /* + * Special case to get the leftovers hiding at the end mark. + */ + if (atEnd) { + DumpLine(interp, textPtr, what & ~TK_DUMP_TEXT, index2.linePtr, + 0, 1, lineno, command); + + } + return TCL_OK; +} + +/* + * DumpLine + * Return information about a given text line from character + * position "start" up to, but not including, "end". + * + * Results: + * A standard Tcl result. + * + * Side effects: + * None, but see DumpSegment. + */ +static void +DumpLine(interp, textPtr, what, linePtr, start, end, lineno, command) + Tcl_Interp *interp; + TkText *textPtr; + int what; /* bit flags to select segment types */ + TkTextLine *linePtr; /* The current line */ + int start, end; /* Character range to dump */ + int lineno; /* Line number for indices dump */ + char *command; /* Script to apply to the segment */ +{ + int offset; + TkTextSegment *segPtr; + /* + * Must loop through line looking at its segments. + * character + * toggleOn, toggleOff + * mark + * image + * window + */ + for (offset = 0, segPtr = linePtr->segPtr ; + (offset < end) && (segPtr != (TkTextSegment *)NULL) ; + offset += segPtr->size, segPtr = segPtr->nextPtr) { + if ((what & TK_DUMP_TEXT) && (segPtr->typePtr == &tkTextCharType) && + (offset + segPtr->size > start)) { + char savedChar; /* Last char used in the seg */ + int last = segPtr->size; /* Index of savedChar */ + int first = 0; /* Index of first char in seg */ + if (offset + segPtr->size > end) { + last = end - offset; + } + if (start > offset) { + first = start - offset; + } + savedChar = segPtr->body.chars[last]; + segPtr->body.chars[last] = '\0'; + DumpSegment(interp, "text", segPtr->body.chars + first, + command, lineno, offset + first, what); + segPtr->body.chars[last] = savedChar; + } else if ((offset >= start)) { + if ((what & TK_DUMP_MARK) && (segPtr->typePtr->name[0] == 'm')) { + TkTextMark *markPtr = (TkTextMark *)&segPtr->body; + char *name = Tcl_GetHashKey(&textPtr->markTable, markPtr->hPtr); + DumpSegment(interp, "mark", name, + command, lineno, offset, what); + } else if ((what & TK_DUMP_TAG) && + (segPtr->typePtr == &tkTextToggleOnType)) { + DumpSegment(interp, "tagon", + segPtr->body.toggle.tagPtr->name, + command, lineno, offset, what); + } else if ((what & TK_DUMP_TAG) && + (segPtr->typePtr == &tkTextToggleOffType)) { + DumpSegment(interp, "tagoff", + segPtr->body.toggle.tagPtr->name, + command, lineno, offset, what); + } else if ((what & TK_DUMP_IMG) && + (segPtr->typePtr->name[0] == 'i')) { + TkTextEmbImage *eiPtr = (TkTextEmbImage *)&segPtr->body; + char *name = (eiPtr->name == NULL) ? "" : eiPtr->name; + DumpSegment(interp, "image", name, + command, lineno, offset, what); + } else if ((what & TK_DUMP_WIN) && + (segPtr->typePtr->name[0] == 'w')) { + TkTextEmbWindow *ewPtr = (TkTextEmbWindow *)&segPtr->body; + char *pathname; + if (ewPtr->tkwin == (Tk_Window) NULL) { + pathname = ""; + } else { + pathname = Tk_PathName(ewPtr->tkwin); + } + DumpSegment(interp, "window", pathname, + command, lineno, offset, what); + } + } + } +} + +/* + * DumpSegment + * Either append information about the current segment to the result, + * or make a script callback with that information as arguments. + * + * Results: + * None + * + * Side effects: + * Either evals the callback or appends elements to the result string. + */ +static int +DumpSegment(interp, key, value, command, lineno, offset, what) + Tcl_Interp *interp; + char *key; /* Segment type key */ + char *value; /* Segment value */ + char *command; /* Script callback */ + int lineno; /* Line number for indices dump */ + int offset; /* Character position */ + int what; /* Look for TK_DUMP_INDEX bit */ +{ + char buffer[30]; + sprintf(buffer, "%d.%d", lineno, offset); + if (command == (char *) NULL) { + Tcl_AppendElement(interp, key); + Tcl_AppendElement(interp, value); + Tcl_AppendElement(interp, buffer); + return TCL_OK; + } else { + char *argv[4]; + char *list; + int result; + argv[0] = key; + argv[1] = value; + argv[2] = buffer; + argv[3] = (char *) NULL; + list = Tcl_Merge(3, argv); + result = Tcl_VarEval(interp, command, " ", list, (char *) NULL); + ckfree(list); + return result; + } +} + diff --git a/generic/tkText.h b/generic/tkText.h new file mode 100644 index 0000000..a7999d2 --- /dev/null +++ b/generic/tkText.h @@ -0,0 +1,848 @@ +/* + * tkText.h -- + * + * Declarations shared among the files that implement text + * widgets. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkText.h 1.46 96/11/25 11:26:12 + */ + +#ifndef _TKTEXT +#define _TKTEXT + +#ifndef _TK +#include "tk.h" +#endif + +/* + * Opaque types for structures whose guts are only needed by a single + * file: + */ + +typedef struct TkTextBTree *TkTextBTree; + +/* + * The data structure below defines a single line of text (from newline + * to newline, not necessarily what appears on one line of the screen). + */ + +typedef struct TkTextLine { + struct Node *parentPtr; /* Pointer to parent node containing + * line. */ + struct TkTextLine *nextPtr; /* Next in linked list of lines with + * same parent node in B-tree. NULL + * means end of list. */ + struct TkTextSegment *segPtr; /* First in ordered list of segments + * that make up the line. */ +} TkTextLine; + +/* + * ----------------------------------------------------------------------- + * Segments: each line is divided into one or more segments, where each + * segment is one of several things, such as a group of characters, a + * tag toggle, a mark, or an embedded widget. Each segment starts with + * a standard header followed by a body that varies from type to type. + * ----------------------------------------------------------------------- + */ + +/* + * The data structure below defines the body of a segment that represents + * a tag toggle. There is one of these structures at both the beginning + * and end of each tagged range. + */ + +typedef struct TkTextToggle { + struct TkTextTag *tagPtr; /* Tag that starts or ends here. */ + int inNodeCounts; /* 1 means this toggle has been + * accounted for in node toggle + * counts; 0 means it hasn't, yet. */ +} TkTextToggle; + +/* + * The data structure below defines line segments that represent + * marks. There is one of these for each mark in the text. + */ + +typedef struct TkTextMark { + struct TkText *textPtr; /* Overall information about text + * widget. */ + TkTextLine *linePtr; /* Line structure that contains the + * segment. */ + Tcl_HashEntry *hPtr; /* Pointer to hash table entry for mark + * (in textPtr->markTable). */ +} TkTextMark; + +/* + * A structure of the following type holds information for each window + * embedded in a text widget. This information is only used by the + * file tkTextWind.c + */ + +typedef struct TkTextEmbWindow { + struct TkText *textPtr; /* Information about the overall text + * widget. */ + TkTextLine *linePtr; /* Line structure that contains this + * window. */ + Tk_Window tkwin; /* Window for this segment. NULL + * means that the window hasn't + * been created yet. */ + char *create; /* Script to create window on-demand. + * NULL means no such script. + * Malloc-ed. */ + int align; /* How to align window in vertical + * space. See definitions in + * tkTextWind.c. */ + int padX, padY; /* Padding to leave around each side + * of window, in pixels. */ + int stretch; /* Should window stretch to fill + * vertical space of line (except for + * pady)? 0 or 1. */ + int chunkCount; /* Number of display chunks that + * refer to this window. */ + int displayed; /* Non-zero means that the window + * has been displayed on the screen + * recently. */ +} TkTextEmbWindow; + +/* + * A structure of the following type holds information for each image + * embedded in a text widget. This information is only used by the + * file tkTextImage.c + */ + +typedef struct TkTextEmbImage { + struct TkText *textPtr; /* Information about the overall text + * widget. */ + TkTextLine *linePtr; /* Line structure that contains this + * image. */ + char *imageString; /* Name of the image for this segment */ + char *imageName; /* Name used by text widget to identify + * this image. May be unique-ified */ + char *name; /* Name used in the hash table. + * used by "image names" to identify + * this instance of the image */ + Tk_Image image; /* Image for this segment. NULL + * means that the image hasn't + * been created yet. */ + int align; /* How to align image in vertical + * space. See definitions in + * tkTextImage.c. */ + int padX, padY; /* Padding to leave around each side + * of image, in pixels. */ + int chunkCount; /* Number of display chunks that + * refer to this image. */ +} TkTextEmbImage; + +/* + * The data structure below defines line segments. + */ + +typedef struct TkTextSegment { + struct Tk_SegType *typePtr; /* Pointer to record describing + * segment's type. */ + struct TkTextSegment *nextPtr; /* Next in list of segments for this + * line, or NULL for end of list. */ + int size; /* Size of this segment (# of bytes + * of index space it occupies). */ + union { + char chars[4]; /* Characters that make up character + * info. Actual length varies to + * hold as many characters as needed.*/ + TkTextToggle toggle; /* Information about tag toggle. */ + TkTextMark mark; /* Information about mark. */ + TkTextEmbWindow ew; /* Information about embedded + * window. */ + TkTextEmbImage ei; /* Information about embedded + * image. */ + } body; +} TkTextSegment; + +/* + * Data structures of the type defined below are used during the + * execution of Tcl commands to keep track of various interesting + * places in a text. An index is only valid up until the next + * modification to the character structure of the b-tree so they + * can't be retained across Tcl commands. However, mods to marks + * or tags don't invalidate indices. + */ + +typedef struct TkTextIndex { + TkTextBTree tree; /* Tree containing desired position. */ + TkTextLine *linePtr; /* Pointer to line containing position + * of interest. */ + int charIndex; /* Index within line of desired + * character (0 means first one). */ +} TkTextIndex; + +/* + * Types for procedure pointers stored in TkTextDispChunk strutures: + */ + +typedef struct TkTextDispChunk TkTextDispChunk; + +typedef void Tk_ChunkDisplayProc _ANSI_ARGS_(( + TkTextDispChunk *chunkPtr, int x, int y, + int height, int baseline, Display *display, + Drawable dst, int screenY)); +typedef void Tk_ChunkUndisplayProc _ANSI_ARGS_(( + struct TkText *textPtr, + TkTextDispChunk *chunkPtr)); +typedef int Tk_ChunkMeasureProc _ANSI_ARGS_(( + TkTextDispChunk *chunkPtr, int x)); +typedef void Tk_ChunkBboxProc _ANSI_ARGS_(( + TkTextDispChunk *chunkPtr, int index, int y, + int lineHeight, int baseline, int *xPtr, + int *yPtr, int *widthPtr, int *heightPtr)); + +/* + * The structure below represents a chunk of stuff that is displayed + * together on the screen. This structure is allocated and freed by + * generic display code but most of its fields are filled in by + * segment-type-specific code. + */ + +struct TkTextDispChunk { + /* + * The fields below are set by the type-independent code before + * calling the segment-type-specific layoutProc. They should not + * be modified by segment-type-specific code. + */ + + int x; /* X position of chunk, in pixels. + * This position is measured from the + * left edge of the logical line, + * not from the left edge of the + * window (i.e. it doesn't change + * under horizontal scrolling). */ + struct TkTextDispChunk *nextPtr; /* Next chunk in the display line + * or NULL for the end of the list. */ + struct TextStyle *stylePtr; /* Display information, known only + * to tkTextDisp.c. */ + + /* + * The fields below are set by the layoutProc that creates the + * chunk. + */ + + Tk_ChunkDisplayProc *displayProc; /* Procedure to invoke to draw this + * chunk on the display or an + * off-screen pixmap. */ + Tk_ChunkUndisplayProc *undisplayProc; + /* Procedure to invoke when segment + * ceases to be displayed on screen + * anymore. */ + Tk_ChunkMeasureProc *measureProc; /* Procedure to find character under + * a given x-location. */ + Tk_ChunkBboxProc *bboxProc; /* Procedure to find bounding box + * of character in chunk. */ + int numChars; /* Number of characters that will be + * displayed in the chunk. */ + int minAscent; /* Minimum space above the baseline + * needed by this chunk. */ + int minDescent; /* Minimum space below the baseline + * needed by this chunk. */ + int minHeight; /* Minimum total line height needed + * by this chunk. */ + int width; /* Width of this chunk, in pixels. + * Initially set by chunk-specific + * code, but may be increased to + * include tab or extra space at end + * of line. */ + int breakIndex; /* Index within chunk of last + * acceptable position for a line + * (break just before this character). + * <= 0 means don't break during or + * immediately after this chunk. */ + ClientData clientData; /* Additional information for use + * of displayProc and undisplayProc. */ +}; + +/* + * One data structure of the following type is used for each tag in a + * text widget. These structures are kept in textPtr->tagTable and + * referred to in other structures. + */ + +typedef struct TkTextTag { + char *name; /* Name of this tag. This field is actually + * a pointer to the key from the entry in + * textPtr->tagTable, so it needn't be freed + * explicitly. */ + int priority; /* Priority of this tag within widget. 0 + * means lowest priority. Exactly one tag + * has each integer value between 0 and + * numTags-1. */ + struct Node *tagRootPtr; /* Pointer into the B-Tree at the lowest + * node that completely dominates the ranges + * of text occupied by the tag. At this + * node there is no information about the + * tag. One or more children of the node + * do contain information about the tag. */ + int toggleCount; /* Total number of tag toggles */ + + /* + * Information for displaying text with this tag. The information + * belows acts as an override on information specified by lower-priority + * tags. If no value is specified, then the next-lower-priority tag + * on the text determins the value. The text widget itself provides + * defaults if no tag specifies an override. + */ + + Tk_3DBorder border; /* Used for drawing background. NULL means + * no value specified here. */ + char *bdString; /* -borderwidth option string (malloc-ed). + * NULL means option not specified. */ + int borderWidth; /* Width of 3-D border for background. */ + char *reliefString; /* -relief option string (malloc-ed). + * NULL means option not specified. */ + int relief; /* 3-D relief for background. */ + Pixmap bgStipple; /* Stipple bitmap for background. None + * means no value specified here. */ + XColor *fgColor; /* Foreground color for text. NULL means + * no value specified here. */ + Tk_Font tkfont; /* Font for displaying text. NULL means + * no value specified here. */ + Pixmap fgStipple; /* Stipple bitmap for text and other + * foreground stuff. None means no value + * specified here.*/ + char *justifyString; /* -justify option string (malloc-ed). + * NULL means option not specified. */ + Tk_Justify justify; /* How to justify text: TK_JUSTIFY_LEFT, + * TK_JUSTIFY_RIGHT, or TK_JUSTIFY_CENTER. + * Only valid if justifyString is non-NULL. */ + char *lMargin1String; /* -lmargin1 option string (malloc-ed). + * NULL means option not specified. */ + int lMargin1; /* Left margin for first display line of + * each text line, in pixels. Only valid + * if lMargin1String is non-NULL. */ + char *lMargin2String; /* -lmargin2 option string (malloc-ed). + * NULL means option not specified. */ + int lMargin2; /* Left margin for second and later display + * lines of each text line, in pixels. Only + * valid if lMargin2String is non-NULL. */ + char *offsetString; /* -offset option string (malloc-ed). + * NULL means option not specified. */ + int offset; /* Vertical offset of text's baseline from + * baseline of line. Used for superscripts + * and subscripts. Only valid if + * offsetString is non-NULL. */ + char *overstrikeString; /* -overstrike option string (malloc-ed). + * NULL means option not specified. */ + int overstrike; /* Non-zero means draw horizontal line through + * middle of text. Only valid if + * overstrikeString is non-NULL. */ + char *rMarginString; /* -rmargin option string (malloc-ed). + * NULL means option not specified. */ + int rMargin; /* Right margin for text, in pixels. Only + * valid if rMarginString is non-NULL. */ + char *spacing1String; /* -spacing1 option string (malloc-ed). + * NULL means option not specified. */ + int spacing1; /* Extra spacing above first display + * line for text line. Only valid if + * spacing1String is non-NULL. */ + char *spacing2String; /* -spacing2 option string (malloc-ed). + * NULL means option not specified. */ + int spacing2; /* Extra spacing between display + * lines for the same text line. Only valid + * if spacing2String is non-NULL. */ + char *spacing3String; /* -spacing2 option string (malloc-ed). + * NULL means option not specified. */ + int spacing3; /* Extra spacing below last display + * line for text line. Only valid if + * spacing3String is non-NULL. */ + char *tabString; /* -tabs option string (malloc-ed). + * NULL means option not specified. */ + struct TkTextTabArray *tabArrayPtr; + /* Info about tabs for tag (malloc-ed) + * or NULL. Corresponds to tabString. */ + char *underlineString; /* -underline option string (malloc-ed). + * NULL means option not specified. */ + int underline; /* Non-zero means draw underline underneath + * text. Only valid if underlineString is + * non-NULL. */ + Tk_Uid wrapMode; /* How to handle wrap-around for this tag. + * Must be tkTextCharUid, tkTextNoneUid, + * tkTextWordUid, or NULL to use wrapMode + * for whole widget. */ + int affectsDisplay; /* Non-zero means that this tag affects the + * way information is displayed on the screen + * (so need to redisplay if tag changes). */ +} TkTextTag; + +#define TK_TAG_AFFECTS_DISPLAY 0x1 +#define TK_TAG_UNDERLINE 0x2 +#define TK_TAG_JUSTIFY 0x4 +#define TK_TAG_OFFSET 0x10 + +/* + * The data structure below is used for searching a B-tree for transitions + * on a single tag (or for all tag transitions). No code outside of + * tkTextBTree.c should ever modify any of the fields in these structures, + * but it's OK to use them for read-only information. + */ + +typedef struct TkTextSearch { + TkTextIndex curIndex; /* Position of last tag transition + * returned by TkBTreeNextTag, or + * index of start of segment + * containing starting position for + * search if TkBTreeNextTag hasn't + * been called yet, or same as + * stopIndex if search is over. */ + TkTextSegment *segPtr; /* Actual tag segment returned by last + * call to TkBTreeNextTag, or NULL if + * TkBTreeNextTag hasn't returned + * anything yet. */ + TkTextSegment *nextPtr; /* Where to resume search in next + * call to TkBTreeNextTag. */ + TkTextSegment *lastPtr; /* Stop search before just before + * considering this segment. */ + TkTextTag *tagPtr; /* Tag to search for (or tag found, if + * allTags is non-zero). */ + int linesLeft; /* Lines left to search (including + * curIndex and stopIndex). When + * this becomes <= 0 the search is + * over. */ + int allTags; /* Non-zero means ignore tag check: + * search for transitions on all + * tags. */ +} TkTextSearch; + +/* + * The following data structure describes a single tab stop. + */ + +typedef enum {LEFT, RIGHT, CENTER, NUMERIC} TkTextTabAlign; + +typedef struct TkTextTab { + int location; /* Offset in pixels of this tab stop + * from the left margin (lmargin2) of + * the text. */ + TkTextTabAlign alignment; /* Where the tab stop appears relative + * to the text. */ +} TkTextTab; + +typedef struct TkTextTabArray { + int numTabs; /* Number of tab stops. */ + TkTextTab tabs[1]; /* Array of tabs. The actual size + * will be numTabs. THIS FIELD MUST + * BE THE LAST IN THE STRUCTURE. */ +} TkTextTabArray; + +/* + * A data structure of the following type is kept for each text widget that + * currently exists for this process: + */ + +typedef struct TkText { + Tk_Window tkwin; /* Window that embodies the text. NULL + * means that the window has been destroyed + * but the data structures haven't yet been + * cleaned up.*/ + Display *display; /* Display for widget. Needed, among other + * things, to allow resources to be freed + * even after tkwin has gone away. */ + Tcl_Interp *interp; /* Interpreter associated with widget. Used + * to delete widget command. */ + Tcl_Command widgetCmd; /* Token for text's widget command. */ + TkTextBTree tree; /* B-tree representation of text and tags for + * widget. */ + Tcl_HashTable tagTable; /* Hash table that maps from tag names to + * pointers to TkTextTag structures. */ + int numTags; /* Number of tags currently defined for + * widget; needed to keep track of + * priorities. */ + Tcl_HashTable markTable; /* Hash table that maps from mark names to + * pointers to mark segments. */ + Tcl_HashTable windowTable; /* Hash table that maps from window names + * to pointers to window segments. If a + * window segment doesn't yet have an + * associated window, there is no entry for + * it here. */ + Tcl_HashTable imageTable; /* Hash table that maps from image names + * to pointers to image segments. If an + * image segment doesn't yet have an + * associated image, there is no entry for + * it here. */ + Tk_Uid state; /* Normal or disabled. Text is read-only + * when disabled. */ + + /* + * Default information for displaying (may be overridden by tags + * applied to ranges of characters). + */ + + Tk_3DBorder border; /* Structure used to draw 3-D border and + * default background. */ + int borderWidth; /* Width of 3-D border to draw around entire + * widget. */ + int padX, padY; /* Padding between text and window border. */ + int relief; /* 3-d effect for border around entire + * widget: TK_RELIEF_RAISED etc. */ + int highlightWidth; /* Width in pixels of highlight to draw + * around widget when it has the focus. + * <= 0 means don't draw a highlight. */ + XColor *highlightBgColorPtr; + /* Color for drawing traversal highlight + * area when highlight is off. */ + XColor *highlightColorPtr; /* Color for drawing traversal highlight. */ + Tk_Cursor cursor; /* Current cursor for window, or None. */ + XColor *fgColor; /* Default foreground color for text. */ + Tk_Font tkfont; /* Default font for displaying text. */ + int charWidth; /* Width of average character in default + * font. */ + int spacing1; /* Default extra spacing above first display + * line for each text line. */ + int spacing2; /* Default extra spacing between display lines + * for the same text line. */ + int spacing3; /* Default extra spacing below last display + * line for each text line. */ + char *tabOptionString; /* Value of -tabs option string (malloc'ed). */ + TkTextTabArray *tabArrayPtr; + /* Information about tab stops (malloc'ed). + * NULL means perform default tabbing + * behavior. */ + + /* + * Additional information used for displaying: + */ + + Tk_Uid wrapMode; /* How to handle wrap-around. Must be + * tkTextCharUid, tkTextNoneUid, or + * tkTextWordUid. */ + int width, height; /* Desired dimensions for window, measured + * in characters. */ + int setGrid; /* Non-zero means pass gridding information + * to window manager. */ + int prevWidth, prevHeight; /* Last known dimensions of window; used to + * detect changes in size. */ + TkTextIndex topIndex; /* Identifies first character in top display + * line of window. */ + struct TextDInfo *dInfoPtr; /* Information maintained by tkTextDisp.c. */ + + /* + * Information related to selection. + */ + + TkTextTag *selTagPtr; /* Pointer to "sel" tag. Used to tell when + * a new selection has been made. */ + Tk_3DBorder selBorder; /* Border and background for selected + * characters. This is a copy of information + * in *cursorTagPtr, so it shouldn't be + * explicitly freed. */ + char *selBdString; /* Value of -selectborderwidth option, or NULL + * if not specified (malloc'ed). */ + XColor *selFgColorPtr; /* Foreground color for selected text. + * This is a copy of information in + * *cursorTagPtr, so it shouldn't be + * explicitly freed. */ + int exportSelection; /* Non-zero means tie "sel" tag to X + * selection. */ + TkTextIndex selIndex; /* Used during multi-pass selection retrievals. + * This index identifies the next character + * to be returned from the selection. */ + int abortSelections; /* Set to 1 whenever the text is modified + * in a way that interferes with selection + * retrieval: used to abort incremental + * selection retrievals. */ + int selOffset; /* Offset in selection corresponding to + * selLine and selCh. -1 means neither + * this information nor selIndex is of any + * use. */ + + /* + * Information related to insertion cursor: + */ + + TkTextSegment *insertMarkPtr; + /* Points to segment for "insert" mark. */ + Tk_3DBorder insertBorder; /* Used to draw vertical bar for insertion + * cursor. */ + int insertWidth; /* Total width of insert cursor. */ + int insertBorderWidth; /* Width of 3-D border around insert cursor. */ + int insertOnTime; /* Number of milliseconds cursor should spend + * in "on" state for each blink. */ + int insertOffTime; /* Number of milliseconds cursor should spend + * in "off" state for each blink. */ + Tcl_TimerToken insertBlinkHandler; + /* Timer handler used to blink cursor on and + * off. */ + + /* + * Information used for event bindings associated with tags: + */ + + Tk_BindingTable bindingTable; + /* Table of all bindings currently defined + * for this widget. NULL means that no + * bindings exist, so the table hasn't been + * created. Each "object" used for this + * table is the address of a tag. */ + TkTextSegment *currentMarkPtr; + /* Pointer to segment for "current" mark, + * or NULL if none. */ + XEvent pickEvent; /* The event from which the current character + * was chosen. Must be saved so that we + * can repick after modifications to the + * text. */ + int numCurTags; /* Number of tags associated with character + * at current mark. */ + TkTextTag **curTagArrayPtr; /* Pointer to array of tags for current + * mark, or NULL if none. */ + + /* + * Miscellaneous additional information: + */ + + char *takeFocus; /* Value of -takeFocus option; not used in + * the C code, but used by keyboard traversal + * scripts. Malloc'ed, but may be NULL. */ + char *xScrollCmd; /* Prefix of command to issue to update + * horizontal scrollbar when view changes. */ + char *yScrollCmd; /* Prefix of command to issue to update + * vertical scrollbar when view changes. */ + int flags; /* Miscellaneous flags; see below for + * definitions. */ +} TkText; + +/* + * Flag values for TkText records: + * + * GOT_SELECTION: Non-zero means we've already claimed the + * selection. + * INSERT_ON: Non-zero means insertion cursor should be + * displayed on screen. + * GOT_FOCUS: Non-zero means this window has the input + * focus. + * BUTTON_DOWN: 1 means that a mouse button is currently + * down; this is used to implement grabs + * for the duration of button presses. + * UPDATE_SCROLLBARS: Non-zero means scrollbar(s) should be updated + * during next redisplay operation. + */ + +#define GOT_SELECTION 1 +#define INSERT_ON 2 +#define GOT_FOCUS 4 +#define BUTTON_DOWN 8 +#define UPDATE_SCROLLBARS 0x10 +#define NEED_REPICK 0x20 + +/* + * Records of the following type define segment types in terms of + * a collection of procedures that may be called to manipulate + * segments of that type. + */ + +typedef TkTextSegment * Tk_SegSplitProc _ANSI_ARGS_(( + struct TkTextSegment *segPtr, int index)); +typedef int Tk_SegDeleteProc _ANSI_ARGS_(( + struct TkTextSegment *segPtr, + TkTextLine *linePtr, int treeGone)); +typedef TkTextSegment * Tk_SegCleanupProc _ANSI_ARGS_(( + struct TkTextSegment *segPtr, TkTextLine *linePtr)); +typedef void Tk_SegLineChangeProc _ANSI_ARGS_(( + struct TkTextSegment *segPtr, TkTextLine *linePtr)); +typedef int Tk_SegLayoutProc _ANSI_ARGS_((struct TkText *textPtr, + struct TkTextIndex *indexPtr, TkTextSegment *segPtr, + int offset, int maxX, int maxChars, + int noCharsYet, Tk_Uid wrapMode, + struct TkTextDispChunk *chunkPtr)); +typedef void Tk_SegCheckProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); + +typedef struct Tk_SegType { + char *name; /* Name of this kind of segment. */ + int leftGravity; /* If a segment has zero size (e.g. a + * mark or tag toggle), does it + * attach to character to its left + * or right? 1 means left, 0 means + * right. */ + Tk_SegSplitProc *splitProc; /* Procedure to split large segment + * into two smaller ones. */ + Tk_SegDeleteProc *deleteProc; /* Procedure to call to delete + * segment. */ + Tk_SegCleanupProc *cleanupProc; /* After any change to a line, this + * procedure is invoked for all + * segments left in the line to + * perform any cleanup they wish + * (e.g. joining neighboring + * segments). */ + Tk_SegLineChangeProc *lineChangeProc; + /* Invoked when a segment is about + * to be moved from its current line + * to an earlier line because of + * a deletion. The linePtr is that + * for the segment's old line. + * CleanupProc will be invoked after + * the deletion is finished. */ + Tk_SegLayoutProc *layoutProc; /* Returns size information when + * figuring out what to display in + * window. */ + Tk_SegCheckProc *checkProc; /* Called during consistency checks + * to check internal consistency of + * segment. */ +} Tk_SegType; + +/* + * The constant below is used to specify a line when what is really + * wanted is the entire text. For now, just use a very big number. + */ + +#define TK_END_OF_TEXT 1000000 + +/* + * The following definition specifies the maximum number of characters + * needed in a string to hold a position specifier. + */ + +#define TK_POS_CHARS 30 + +/* + * Declarations for variables shared among the text-related files: + */ + +extern int tkBTreeDebug; +extern int tkTextDebug; +extern Tk_SegType tkTextCharType; +extern Tk_Uid tkTextCharUid; +extern Tk_Uid tkTextDisabledUid; +extern Tk_SegType tkTextLeftMarkType; +extern Tk_Uid tkTextNoneUid; +extern Tk_Uid tkTextNormalUid; +extern Tk_SegType tkTextRightMarkType; +extern Tk_SegType tkTextToggleOnType; +extern Tk_SegType tkTextToggleOffType; +extern Tk_Uid tkTextWordUid; + +/* + * Declarations for procedures that are used by the text-related files + * but shouldn't be used anywhere else in Tk (or by Tk clients): + */ + +extern int TkBTreeCharTagged _ANSI_ARGS_((TkTextIndex *indexPtr, + TkTextTag *tagPtr)); +extern void TkBTreeCheck _ANSI_ARGS_((TkTextBTree tree)); +extern int TkBTreeCharsInLine _ANSI_ARGS_((TkTextLine *linePtr)); +extern TkTextBTree TkBTreeCreate _ANSI_ARGS_((TkText *textPtr)); +extern void TkBTreeDestroy _ANSI_ARGS_((TkTextBTree tree)); +extern void TkBTreeDeleteChars _ANSI_ARGS_((TkTextIndex *index1Ptr, + TkTextIndex *index2Ptr)); +extern TkTextLine * TkBTreeFindLine _ANSI_ARGS_((TkTextBTree tree, + int line)); +extern TkTextTag ** TkBTreeGetTags _ANSI_ARGS_((TkTextIndex *indexPtr, + int *numTagsPtr)); +extern void TkBTreeInsertChars _ANSI_ARGS_((TkTextIndex *indexPtr, + char *string)); +extern int TkBTreeLineIndex _ANSI_ARGS_((TkTextLine *linePtr)); +extern void TkBTreeLinkSegment _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextIndex *indexPtr)); +extern TkTextLine * TkBTreeNextLine _ANSI_ARGS_((TkTextLine *linePtr)); +extern int TkBTreeNextTag _ANSI_ARGS_((TkTextSearch *searchPtr)); +extern int TkBTreeNumLines _ANSI_ARGS_((TkTextBTree tree)); +extern TkTextLine * TkBTreePreviousLine _ANSI_ARGS_((TkTextLine *linePtr)); +extern int TkBTreePrevTag _ANSI_ARGS_((TkTextSearch *searchPtr)); +extern void TkBTreeStartSearch _ANSI_ARGS_((TkTextIndex *index1Ptr, + TkTextIndex *index2Ptr, TkTextTag *tagPtr, + TkTextSearch *searchPtr)); +extern void TkBTreeStartSearchBack _ANSI_ARGS_((TkTextIndex *index1Ptr, + TkTextIndex *index2Ptr, TkTextTag *tagPtr, + TkTextSearch *searchPtr)); +extern void TkBTreeTag _ANSI_ARGS_((TkTextIndex *index1Ptr, + TkTextIndex *index2Ptr, TkTextTag *tagPtr, + int add)); +extern void TkBTreeUnlinkSegment _ANSI_ARGS_((TkTextBTree tree, + TkTextSegment *segPtr, TkTextLine *linePtr)); +extern void TkTextBindProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +extern void TkTextChanged _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *index1Ptr, TkTextIndex *index2Ptr)); +extern int TkTextCharBbox _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *indexPtr, int *xPtr, int *yPtr, + int *widthPtr, int *heightPtr)); +extern int TkTextCharLayoutProc _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *indexPtr, TkTextSegment *segPtr, + int offset, int maxX, int maxChars, int noBreakYet, + Tk_Uid wrapMode, TkTextDispChunk *chunkPtr)); +extern void TkTextCreateDInfo _ANSI_ARGS_((TkText *textPtr)); +extern int TkTextDLineInfo _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *indexPtr, int *xPtr, int *yPtr, + int *widthPtr, int *heightPtr, int *basePtr)); +extern TkTextTag * TkTextCreateTag _ANSI_ARGS_((TkText *textPtr, + char *tagName)); +extern void TkTextFreeDInfo _ANSI_ARGS_((TkText *textPtr)); +extern void TkTextFreeTag _ANSI_ARGS_((TkText *textPtr, + TkTextTag *tagPtr)); +extern int TkTextGetIndex _ANSI_ARGS_((Tcl_Interp *interp, + TkText *textPtr, char *string, + TkTextIndex *indexPtr)); +extern TkTextTabArray * TkTextGetTabs _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window tkwin, char *string)); +extern void TkTextIndexBackChars _ANSI_ARGS_((TkTextIndex *srcPtr, + int count, TkTextIndex *dstPtr)); +extern int TkTextIndexCmp _ANSI_ARGS_((TkTextIndex *index1Ptr, + TkTextIndex *index2Ptr)); +extern void TkTextIndexForwChars _ANSI_ARGS_((TkTextIndex *srcPtr, + int count, TkTextIndex *dstPtr)); +extern TkTextSegment * TkTextIndexToSeg _ANSI_ARGS_((TkTextIndex *indexPtr, + int *offsetPtr)); +extern void TkTextInsertDisplayProc _ANSI_ARGS_(( + TkTextDispChunk *chunkPtr, int x, int y, int height, + int baseline, Display *display, Drawable dst, + int screenY)); +extern void TkTextLostSelection _ANSI_ARGS_(( + ClientData clientData)); +extern TkTextIndex * TkTextMakeIndex _ANSI_ARGS_((TkTextBTree tree, + int lineIndex, int charIndex, + TkTextIndex *indexPtr)); +extern int TkTextMarkCmd _ANSI_ARGS_((TkText *textPtr, + Tcl_Interp *interp, int argc, char **argv)); +extern int TkTextMarkNameToIndex _ANSI_ARGS_((TkText *textPtr, + char *name, TkTextIndex *indexPtr)); +extern void TkTextMarkSegToIndex _ANSI_ARGS_((TkText *textPtr, + TkTextSegment *markPtr, TkTextIndex *indexPtr)); +extern void TkTextEventuallyRepick _ANSI_ARGS_((TkText *textPtr)); +extern void TkTextPickCurrent _ANSI_ARGS_((TkText *textPtr, + XEvent *eventPtr)); +extern void TkTextPixelIndex _ANSI_ARGS_((TkText *textPtr, + int x, int y, TkTextIndex *indexPtr)); +extern void TkTextPrintIndex _ANSI_ARGS_((TkTextIndex *indexPtr, + char *string)); +extern void TkTextRedrawRegion _ANSI_ARGS_((TkText *textPtr, + int x, int y, int width, int height)); +extern void TkTextRedrawTag _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *index1Ptr, TkTextIndex *index2Ptr, + TkTextTag *tagPtr, int withTag)); +extern void TkTextRelayoutWindow _ANSI_ARGS_((TkText *textPtr)); +extern int TkTextScanCmd _ANSI_ARGS_((TkText *textPtr, + Tcl_Interp *interp, int argc, char **argv)); +extern int TkTextSeeCmd _ANSI_ARGS_((TkText *textPtr, + Tcl_Interp *interp, int argc, char **argv)); +extern int TkTextSegToOffset _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +extern TkTextSegment * TkTextSetMark _ANSI_ARGS_((TkText *textPtr, char *name, + TkTextIndex *indexPtr)); +extern void TkTextSetYView _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *indexPtr, int pickPlace)); +extern int TkTextTagCmd _ANSI_ARGS_((TkText *textPtr, + Tcl_Interp *interp, int argc, char **argv)); +extern int TkTextImageCmd _ANSI_ARGS_((TkText *textPtr, + Tcl_Interp *interp, int argc, char **argv)); +extern int TkTextImageIndex _ANSI_ARGS_((TkText *textPtr, + char *name, TkTextIndex *indexPtr)); +extern int TkTextWindowCmd _ANSI_ARGS_((TkText *textPtr, + Tcl_Interp *interp, int argc, char **argv)); +extern int TkTextWindowIndex _ANSI_ARGS_((TkText *textPtr, + char *name, TkTextIndex *indexPtr)); +extern int TkTextXviewCmd _ANSI_ARGS_((TkText *textPtr, + Tcl_Interp *interp, int argc, char **argv)); +extern int TkTextYviewCmd _ANSI_ARGS_((TkText *textPtr, + Tcl_Interp *interp, int argc, char **argv)); + +#endif /* _TKTEXT */ diff --git a/generic/tkTextBTree.c b/generic/tkTextBTree.c new file mode 100644 index 0000000..2fd7deb --- /dev/null +++ b/generic/tkTextBTree.c @@ -0,0 +1,3594 @@ +/* + * tkTextBTree.c -- + * + * This file contains code that manages the B-tree representation + * of text for Tk's text widget and implements character and + * toggle segment types. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkTextBTree.c 1.37 97/04/25 16:52:00 + */ + +#include "tkInt.h" +#include "tkPort.h" +#include "tkText.h" + +/* + * The data structure below keeps summary information about one tag as part + * of the tag information in a node. + */ + +typedef struct Summary { + TkTextTag *tagPtr; /* Handle for tag. */ + int toggleCount; /* Number of transitions into or + * out of this tag that occur in + * the subtree rooted at this node. */ + struct Summary *nextPtr; /* Next in list of all tags for same + * node, or NULL if at end of list. */ +} Summary; + +/* + * The data structure below defines a node in the B-tree. + */ + +typedef struct Node { + struct Node *parentPtr; /* Pointer to parent node, or NULL if + * this is the root. */ + struct Node *nextPtr; /* Next in list of siblings with the + * same parent node, or NULL for end + * of list. */ + Summary *summaryPtr; /* First in malloc-ed list of info + * about tags in this subtree (NULL if + * no tag info in the subtree). */ + int level; /* Level of this node in the B-tree. + * 0 refers to the bottom of the tree + * (children are lines, not nodes). */ + union { /* First in linked list of children. */ + struct Node *nodePtr; /* Used if level > 0. */ + TkTextLine *linePtr; /* Used if level == 0. */ + } children; + int numChildren; /* Number of children of this node. */ + int numLines; /* Total number of lines (leaves) in + * the subtree rooted here. */ +} Node; + +/* + * Upper and lower bounds on how many children a node may have: + * rebalance when either of these limits is exceeded. MAX_CHILDREN + * should be twice MIN_CHILDREN and MIN_CHILDREN must be >= 2. + */ + +#define MAX_CHILDREN 12 +#define MIN_CHILDREN 6 + +/* + * The data structure below defines an entire B-tree. + */ + +typedef struct BTree { + Node *rootPtr; /* Pointer to root of B-tree. */ + TkText *textPtr; /* Used to find tagTable in consistency + * checking code */ +} BTree; + +/* + * The structure below is used to pass information between + * TkBTreeGetTags and IncCount: + */ + +typedef struct TagInfo { + int numTags; /* Number of tags for which there + * is currently information in + * tags and counts. */ + int arraySize; /* Number of entries allocated for + * tags and counts. */ + TkTextTag **tagPtrs; /* Array of tags seen so far. + * Malloc-ed. */ + int *counts; /* Toggle count (so far) for each + * entry in tags. Malloc-ed. */ +} TagInfo; + +/* + * Variable that indicates whether to enable consistency checks for + * debugging. + */ + +int tkBTreeDebug = 0; + +/* + * Macros that determine how much space to allocate for new segments: + */ + +#define CSEG_SIZE(chars) ((unsigned) (Tk_Offset(TkTextSegment, body) \ + + 1 + (chars))) +#define TSEG_SIZE ((unsigned) (Tk_Offset(TkTextSegment, body) \ + + sizeof(TkTextToggle))) + +/* + * Forward declarations for procedures defined in this file: + */ + +static void ChangeNodeToggleCount _ANSI_ARGS_((Node *nodePtr, + TkTextTag *tagPtr, int delta)); +static void CharCheckProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static int CharDeleteProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr, int treeGone)); +static TkTextSegment * CharCleanupProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static TkTextSegment * CharSplitProc _ANSI_ARGS_((TkTextSegment *segPtr, + int index)); +static void CheckNodeConsistency _ANSI_ARGS_((Node *nodePtr)); +static void CleanupLine _ANSI_ARGS_((TkTextLine *linePtr)); +static void DeleteSummaries _ANSI_ARGS_((Summary *tagPtr)); +static void DestroyNode _ANSI_ARGS_((Node *nodePtr)); +static TkTextSegment * FindTagEnd _ANSI_ARGS_((TkTextBTree tree, + TkTextTag *tagPtr, TkTextIndex *indexPtr)); +static void IncCount _ANSI_ARGS_((TkTextTag *tagPtr, int inc, + TagInfo *tagInfoPtr)); +static void Rebalance _ANSI_ARGS_((BTree *treePtr, Node *nodePtr)); +static void RecomputeNodeCounts _ANSI_ARGS_((Node *nodePtr)); +static TkTextSegment * SplitSeg _ANSI_ARGS_((TkTextIndex *indexPtr)); +static void ToggleCheckProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static TkTextSegment * ToggleCleanupProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static int ToggleDeleteProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr, int treeGone)); +static void ToggleLineChangeProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static TkTextSegment * FindTagStart _ANSI_ARGS_((TkTextBTree tree, + TkTextTag *tagPtr, TkTextIndex *indexPtr)); + +/* + * Type record for character segments: + */ + +Tk_SegType tkTextCharType = { + "character", /* name */ + 0, /* leftGravity */ + CharSplitProc, /* splitProc */ + CharDeleteProc, /* deleteProc */ + CharCleanupProc, /* cleanupProc */ + (Tk_SegLineChangeProc *) NULL, /* lineChangeProc */ + TkTextCharLayoutProc, /* layoutProc */ + CharCheckProc /* checkProc */ +}; + +/* + * Type record for segments marking the beginning of a tagged + * range: + */ + +Tk_SegType tkTextToggleOnType = { + "toggleOn", /* name */ + 0, /* leftGravity */ + (Tk_SegSplitProc *) NULL, /* splitProc */ + ToggleDeleteProc, /* deleteProc */ + ToggleCleanupProc, /* cleanupProc */ + ToggleLineChangeProc, /* lineChangeProc */ + (Tk_SegLayoutProc *) NULL, /* layoutProc */ + ToggleCheckProc /* checkProc */ +}; + +/* + * Type record for segments marking the end of a tagged + * range: + */ + +Tk_SegType tkTextToggleOffType = { + "toggleOff", /* name */ + 1, /* leftGravity */ + (Tk_SegSplitProc *) NULL, /* splitProc */ + ToggleDeleteProc, /* deleteProc */ + ToggleCleanupProc, /* cleanupProc */ + ToggleLineChangeProc, /* lineChangeProc */ + (Tk_SegLayoutProc *) NULL, /* layoutProc */ + ToggleCheckProc /* checkProc */ +}; + +/* + *---------------------------------------------------------------------- + * + * TkBTreeCreate -- + * + * This procedure is called to create a new text B-tree. + * + * Results: + * The return value is a pointer to a new B-tree containing + * one line with nothing but a newline character. + * + * Side effects: + * Memory is allocated and initialized. + * + *---------------------------------------------------------------------- + */ + +TkTextBTree +TkBTreeCreate(textPtr) + TkText *textPtr; +{ + register BTree *treePtr; + register Node *rootPtr; + register TkTextLine *linePtr, *linePtr2; + register TkTextSegment *segPtr; + + /* + * The tree will initially have two empty lines. The second line + * isn't actually part of the tree's contents, but its presence + * makes several operations easier. The tree will have one node, + * which is also the root of the tree. + */ + + rootPtr = (Node *) ckalloc(sizeof(Node)); + linePtr = (TkTextLine *) ckalloc(sizeof(TkTextLine)); + linePtr2 = (TkTextLine *) ckalloc(sizeof(TkTextLine)); + rootPtr->parentPtr = NULL; + rootPtr->nextPtr = NULL; + rootPtr->summaryPtr = NULL; + rootPtr->level = 0; + rootPtr->children.linePtr = linePtr; + rootPtr->numChildren = 2; + rootPtr->numLines = 2; + + linePtr->parentPtr = rootPtr; + linePtr->nextPtr = linePtr2; + segPtr = (TkTextSegment *) ckalloc(CSEG_SIZE(1)); + linePtr->segPtr = segPtr; + segPtr->typePtr = &tkTextCharType; + segPtr->nextPtr = NULL; + segPtr->size = 1; + segPtr->body.chars[0] = '\n'; + segPtr->body.chars[1] = 0; + + linePtr2->parentPtr = rootPtr; + linePtr2->nextPtr = NULL; + segPtr = (TkTextSegment *) ckalloc(CSEG_SIZE(1)); + linePtr2->segPtr = segPtr; + segPtr->typePtr = &tkTextCharType; + segPtr->nextPtr = NULL; + segPtr->size = 1; + segPtr->body.chars[0] = '\n'; + segPtr->body.chars[1] = 0; + + treePtr = (BTree *) ckalloc(sizeof(BTree)); + treePtr->rootPtr = rootPtr; + treePtr->textPtr = textPtr; + + return (TkTextBTree) treePtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeDestroy -- + * + * Delete a B-tree, recycling all of the storage it contains. + * + * Results: + * The tree given by treePtr is deleted. TreePtr should never + * again be used. + * + * Side effects: + * Memory is freed. + * + *---------------------------------------------------------------------- + */ + +void +TkBTreeDestroy(tree) + TkTextBTree tree; /* Pointer to tree to delete. */ +{ + BTree *treePtr = (BTree *) tree; + + DestroyNode(treePtr->rootPtr); + ckfree((char *) treePtr); +} + +/* + *---------------------------------------------------------------------- + * + * DestroyNode -- + * + * This is a recursive utility procedure used during the deletion + * of a B-tree. + * + * Results: + * None. + * + * Side effects: + * All the storage for nodePtr and its descendants is freed. + * + *---------------------------------------------------------------------- + */ + +static void +DestroyNode(nodePtr) + register Node *nodePtr; +{ + if (nodePtr->level == 0) { + TkTextLine *linePtr; + TkTextSegment *segPtr; + + while (nodePtr->children.linePtr != NULL) { + linePtr = nodePtr->children.linePtr; + nodePtr->children.linePtr = linePtr->nextPtr; + while (linePtr->segPtr != NULL) { + segPtr = linePtr->segPtr; + linePtr->segPtr = segPtr->nextPtr; + (*segPtr->typePtr->deleteProc)(segPtr, linePtr, 1); + } + ckfree((char *) linePtr); + } + } else { + register Node *childPtr; + + while (nodePtr->children.nodePtr != NULL) { + childPtr = nodePtr->children.nodePtr; + nodePtr->children.nodePtr = childPtr->nextPtr; + DestroyNode(childPtr); + } + } + DeleteSummaries(nodePtr->summaryPtr); + ckfree((char *) nodePtr); +} + +/* + *---------------------------------------------------------------------- + * + * DeleteSummaries -- + * + * Free up all of the memory in a list of tag summaries associated + * with a node. + * + * Results: + * None. + * + * Side effects: + * Storage is released. + * + *---------------------------------------------------------------------- + */ + +static void +DeleteSummaries(summaryPtr) + register Summary *summaryPtr; /* First in list of node's tag + * summaries. */ +{ + register Summary *nextPtr; + while (summaryPtr != NULL) { + nextPtr = summaryPtr->nextPtr; + ckfree((char *) summaryPtr); + summaryPtr = nextPtr; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeInsertChars -- + * + * Insert characters at a given position in a B-tree. + * + * Results: + * None. + * + * Side effects: + * Characters are added to the B-tree at the given position. + * If the string contains newlines, new lines will be added, + * which could cause the structure of the B-tree to change. + * + *---------------------------------------------------------------------- + */ + +void +TkBTreeInsertChars(indexPtr, string) + register TkTextIndex *indexPtr; /* Indicates where to insert text. + * When the procedure returns, this + * index is no longer valid because + * of changes to the segment + * structure. */ + char *string; /* Pointer to bytes to insert (may + * contain newlines, must be null- + * terminated). */ +{ + register Node *nodePtr; + register TkTextSegment *prevPtr; /* The segment just before the first + * new segment (NULL means new segment + * is at beginning of line). */ + TkTextSegment *curPtr; /* Current segment; new characters + * are inserted just after this one. + * NULL means insert at beginning of + * line. */ + TkTextLine *linePtr; /* Current line (new segments are + * added to this line). */ + register TkTextSegment *segPtr; + TkTextLine *newLinePtr; + int chunkSize; /* # characters in current chunk. */ + register char *eol; /* Pointer to character just after last + * one in current chunk. */ + int changeToLineCount; /* Counts change to total number of + * lines in file. */ + + prevPtr = SplitSeg(indexPtr); + linePtr = indexPtr->linePtr; + curPtr = prevPtr; + + /* + * Chop the string up into lines and create a new segment for + * each line, plus a new line for the leftovers from the + * previous line. + */ + + changeToLineCount = 0; + while (*string != 0) { + for (eol = string; *eol != 0; eol++) { + if (*eol == '\n') { + eol++; + break; + } + } + chunkSize = eol-string; + segPtr = (TkTextSegment *) ckalloc(CSEG_SIZE(chunkSize)); + segPtr->typePtr = &tkTextCharType; + if (curPtr == NULL) { + segPtr->nextPtr = linePtr->segPtr; + linePtr->segPtr = segPtr; + } else { + segPtr->nextPtr = curPtr->nextPtr; + curPtr->nextPtr = segPtr; + } + segPtr->size = chunkSize; + strncpy(segPtr->body.chars, string, (size_t) chunkSize); + segPtr->body.chars[chunkSize] = 0; + + if (eol[-1] != '\n') { + break; + } + + /* + * The chunk ended with a newline, so create a new TkTextLine + * and move the remainder of the old line to it. + */ + + newLinePtr = (TkTextLine *) ckalloc(sizeof(TkTextLine)); + newLinePtr->parentPtr = linePtr->parentPtr; + newLinePtr->nextPtr = linePtr->nextPtr; + linePtr->nextPtr = newLinePtr; + newLinePtr->segPtr = segPtr->nextPtr; + segPtr->nextPtr = NULL; + linePtr = newLinePtr; + curPtr = NULL; + changeToLineCount++; + + string = eol; + } + + /* + * Cleanup the starting line for the insertion, plus the ending + * line if it's different. + */ + + CleanupLine(indexPtr->linePtr); + if (linePtr != indexPtr->linePtr) { + CleanupLine(linePtr); + } + + /* + * Increment the line counts in all the parent nodes of the insertion + * point, then rebalance the tree if necessary. + */ + + for (nodePtr = linePtr->parentPtr ; nodePtr != NULL; + nodePtr = nodePtr->parentPtr) { + nodePtr->numLines += changeToLineCount; + } + nodePtr = linePtr->parentPtr; + nodePtr->numChildren += changeToLineCount; + if (nodePtr->numChildren > MAX_CHILDREN) { + Rebalance((BTree *) indexPtr->tree, nodePtr); + } + + if (tkBTreeDebug) { + TkBTreeCheck(indexPtr->tree); + } +} + +/* + *-------------------------------------------------------------- + * + * SplitSeg -- + * + * This procedure is called before adding or deleting + * segments. It does three things: (a) it finds the segment + * containing indexPtr; (b) if there are several such + * segments (because some segments have zero length) then + * it picks the first segment that does not have left + * gravity; (c) if the index refers to the middle of + * a segment then it splits the segment so that the + * index now refers to the beginning of a segment. + * + * Results: + * The return value is a pointer to the segment just + * before the segment corresponding to indexPtr (as + * described above). If the segment corresponding to + * indexPtr is the first in its line then the return + * value is NULL. + * + * Side effects: + * The segment referred to by indexPtr is split unless + * indexPtr refers to its first character. + * + *-------------------------------------------------------------- + */ + +static TkTextSegment * +SplitSeg(indexPtr) + TkTextIndex *indexPtr; /* Index identifying position + * at which to split a segment. */ +{ + TkTextSegment *prevPtr, *segPtr; + int count; + + for (count = indexPtr->charIndex, prevPtr = NULL, + segPtr = indexPtr->linePtr->segPtr; segPtr != NULL; + count -= segPtr->size, prevPtr = segPtr, segPtr = segPtr->nextPtr) { + if (segPtr->size > count) { + if (count == 0) { + return prevPtr; + } + segPtr = (*segPtr->typePtr->splitProc)(segPtr, count); + if (prevPtr == NULL) { + indexPtr->linePtr->segPtr = segPtr; + } else { + prevPtr->nextPtr = segPtr; + } + return segPtr; + } else if ((segPtr->size == 0) && (count == 0) + && !segPtr->typePtr->leftGravity) { + return prevPtr; + } + } + panic("SplitSeg reached end of line!"); + return NULL; +} + +/* + *-------------------------------------------------------------- + * + * CleanupLine -- + * + * This procedure is called after modifications have been + * made to a line. It scans over all of the segments in + * the line, giving each a chance to clean itself up, e.g. + * by merging with the following segments, updating internal + * information, etc. + * + * Results: + * None. + * + * Side effects: + * Depends on what the segment-specific cleanup procedures do. + * + *-------------------------------------------------------------- + */ + +static void +CleanupLine(linePtr) + TkTextLine *linePtr; /* Line to be cleaned up. */ +{ + TkTextSegment *segPtr, **prevPtrPtr; + int anyChanges; + + /* + * Make a pass over all of the segments in the line, giving each + * a chance to clean itself up. This could potentially change + * the structure of the line, e.g. by merging two segments + * together or having two segments cancel themselves; if so, + * then repeat the whole process again, since the first structure + * change might make other structure changes possible. Repeat + * until eventually there are no changes. + */ + + while (1) { + anyChanges = 0; + for (prevPtrPtr = &linePtr->segPtr, segPtr = *prevPtrPtr; + segPtr != NULL; + prevPtrPtr = &(*prevPtrPtr)->nextPtr, segPtr = *prevPtrPtr) { + if (segPtr->typePtr->cleanupProc != NULL) { + *prevPtrPtr = (*segPtr->typePtr->cleanupProc)(segPtr, linePtr); + if (segPtr != *prevPtrPtr) { + anyChanges = 1; + } + } + } + if (!anyChanges) { + break; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeDeleteChars -- + * + * Delete a range of characters from a B-tree. The caller + * must make sure that the final newline of the B-tree is + * never deleted. + * + * Results: + * None. + * + * Side effects: + * Information is deleted from the B-tree. This can cause the + * internal structure of the B-tree to change. Note: because + * of changes to the B-tree structure, the indices pointed + * to by index1Ptr and index2Ptr should not be used after this + * procedure returns. + * + *---------------------------------------------------------------------- + */ + +void +TkBTreeDeleteChars(index1Ptr, index2Ptr) + register TkTextIndex *index1Ptr; /* Indicates first character that is + * to be deleted. */ + register TkTextIndex *index2Ptr; /* Indicates character just after the + * last one that is to be deleted. */ +{ + TkTextSegment *prevPtr; /* The segment just before the start + * of the deletion range. */ + TkTextSegment *lastPtr; /* The segment just after the end + * of the deletion range. */ + TkTextSegment *segPtr, *nextPtr; + TkTextLine *curLinePtr; + Node *curNodePtr, *nodePtr; + + /* + * Tricky point: split at index2Ptr first; otherwise the split + * at index2Ptr may invalidate segPtr and/or prevPtr. + */ + + lastPtr = SplitSeg(index2Ptr); + if (lastPtr != NULL) { + lastPtr = lastPtr->nextPtr; + } else { + lastPtr = index2Ptr->linePtr->segPtr; + } + prevPtr = SplitSeg(index1Ptr); + if (prevPtr != NULL) { + segPtr = prevPtr->nextPtr; + prevPtr->nextPtr = lastPtr; + } else { + segPtr = index1Ptr->linePtr->segPtr; + index1Ptr->linePtr->segPtr = lastPtr; + } + + /* + * Delete all of the segments between prevPtr and lastPtr. + */ + + curLinePtr = index1Ptr->linePtr; + curNodePtr = curLinePtr->parentPtr; + while (segPtr != lastPtr) { + if (segPtr == NULL) { + TkTextLine *nextLinePtr; + + /* + * We just ran off the end of a line. First find the + * next line, then go back to the old line and delete it + * (unless it's the starting line for the range). + */ + + nextLinePtr = TkBTreeNextLine(curLinePtr); + if (curLinePtr != index1Ptr->linePtr) { + if (curNodePtr == index1Ptr->linePtr->parentPtr) { + index1Ptr->linePtr->nextPtr = curLinePtr->nextPtr; + } else { + curNodePtr->children.linePtr = curLinePtr->nextPtr; + } + for (nodePtr = curNodePtr; nodePtr != NULL; + nodePtr = nodePtr->parentPtr) { + nodePtr->numLines--; + } + curNodePtr->numChildren--; + ckfree((char *) curLinePtr); + } + curLinePtr = nextLinePtr; + segPtr = curLinePtr->segPtr; + + /* + * If the node is empty then delete it and its parents, + * recursively upwards until a non-empty node is found. + */ + + while (curNodePtr->numChildren == 0) { + Node *parentPtr; + + parentPtr = curNodePtr->parentPtr; + if (parentPtr->children.nodePtr == curNodePtr) { + parentPtr->children.nodePtr = curNodePtr->nextPtr; + } else { + Node *prevNodePtr = parentPtr->children.nodePtr; + while (prevNodePtr->nextPtr != curNodePtr) { + prevNodePtr = prevNodePtr->nextPtr; + } + prevNodePtr->nextPtr = curNodePtr->nextPtr; + } + parentPtr->numChildren--; + ckfree((char *) curNodePtr); + curNodePtr = parentPtr; + } + curNodePtr = curLinePtr->parentPtr; + continue; + } + + nextPtr = segPtr->nextPtr; + if ((*segPtr->typePtr->deleteProc)(segPtr, curLinePtr, 0) != 0) { + /* + * This segment refuses to die. Move it to prevPtr and + * advance prevPtr if the segment has left gravity. + */ + + if (prevPtr == NULL) { + segPtr->nextPtr = index1Ptr->linePtr->segPtr; + index1Ptr->linePtr->segPtr = segPtr; + } else { + segPtr->nextPtr = prevPtr->nextPtr; + prevPtr->nextPtr = segPtr; + } + if (segPtr->typePtr->leftGravity) { + prevPtr = segPtr; + } + } + segPtr = nextPtr; + } + + /* + * If the beginning and end of the deletion range are in different + * lines, join the two lines together and discard the ending line. + */ + + if (index1Ptr->linePtr != index2Ptr->linePtr) { + TkTextLine *prevLinePtr; + + for (segPtr = lastPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + if (segPtr->typePtr->lineChangeProc != NULL) { + (*segPtr->typePtr->lineChangeProc)(segPtr, index2Ptr->linePtr); + } + } + curNodePtr = index2Ptr->linePtr->parentPtr; + for (nodePtr = curNodePtr; nodePtr != NULL; + nodePtr = nodePtr->parentPtr) { + nodePtr->numLines--; + } + curNodePtr->numChildren--; + prevLinePtr = curNodePtr->children.linePtr; + if (prevLinePtr == index2Ptr->linePtr) { + curNodePtr->children.linePtr = index2Ptr->linePtr->nextPtr; + } else { + while (prevLinePtr->nextPtr != index2Ptr->linePtr) { + prevLinePtr = prevLinePtr->nextPtr; + } + prevLinePtr->nextPtr = index2Ptr->linePtr->nextPtr; + } + ckfree((char *) index2Ptr->linePtr); + Rebalance((BTree *) index2Ptr->tree, curNodePtr); + } + + /* + * Cleanup the segments in the new line. + */ + + CleanupLine(index1Ptr->linePtr); + + /* + * Lastly, rebalance the first node of the range. + */ + + Rebalance((BTree *) index1Ptr->tree, index1Ptr->linePtr->parentPtr); + if (tkBTreeDebug) { + TkBTreeCheck(index1Ptr->tree); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeFindLine -- + * + * Find a particular line in a B-tree based on its line number. + * + * Results: + * The return value is a pointer to the line structure for the + * line whose index is "line", or NULL if no such line exists. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkTextLine * +TkBTreeFindLine(tree, line) + TkTextBTree tree; /* B-tree in which to find line. */ + int line; /* Index of desired line. */ +{ + BTree *treePtr = (BTree *) tree; + register Node *nodePtr; + register TkTextLine *linePtr; + int linesLeft; + + nodePtr = treePtr->rootPtr; + linesLeft = line; + if ((line < 0) || (line >= nodePtr->numLines)) { + return NULL; + } + + /* + * Work down through levels of the tree until a node is found at + * level 0. + */ + + while (nodePtr->level != 0) { + for (nodePtr = nodePtr->children.nodePtr; + nodePtr->numLines <= linesLeft; + nodePtr = nodePtr->nextPtr) { + if (nodePtr == NULL) { + panic("TkBTreeFindLine ran out of nodes"); + } + linesLeft -= nodePtr->numLines; + } + } + + /* + * Work through the lines attached to the level-0 node. + */ + + for (linePtr = nodePtr->children.linePtr; linesLeft > 0; + linePtr = linePtr->nextPtr) { + if (linePtr == NULL) { + panic("TkBTreeFindLine ran out of lines"); + } + linesLeft -= 1; + } + return linePtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeNextLine -- + * + * Given an existing line in a B-tree, this procedure locates the + * next line in the B-tree. This procedure is used for scanning + * through the B-tree. + * + * Results: + * The return value is a pointer to the line that immediately + * follows linePtr, or NULL if there is no such line. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkTextLine * +TkBTreeNextLine(linePtr) + register TkTextLine *linePtr; /* Pointer to existing line in + * B-tree. */ +{ + register Node *nodePtr; + + if (linePtr->nextPtr != NULL) { + return linePtr->nextPtr; + } + + /* + * This was the last line associated with the particular parent node. + * Search up the tree for the next node, then search down from that + * node to find the first line. + */ + + for (nodePtr = linePtr->parentPtr; ; nodePtr = nodePtr->parentPtr) { + if (nodePtr->nextPtr != NULL) { + nodePtr = nodePtr->nextPtr; + break; + } + if (nodePtr->parentPtr == NULL) { + return (TkTextLine *) NULL; + } + } + while (nodePtr->level > 0) { + nodePtr = nodePtr->children.nodePtr; + } + return nodePtr->children.linePtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreePreviousLine -- + * + * Given an existing line in a B-tree, this procedure locates the + * previous line in the B-tree. This procedure is used for scanning + * through the B-tree in the reverse direction. + * + * Results: + * The return value is a pointer to the line that immediately + * preceeds linePtr, or NULL if there is no such line. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkTextLine * +TkBTreePreviousLine(linePtr) + register TkTextLine *linePtr; /* Pointer to existing line in + * B-tree. */ +{ + register Node *nodePtr; + register Node *node2Ptr; + register TkTextLine *prevPtr; + + /* + * Find the line under this node just before the starting line. + */ + prevPtr = linePtr->parentPtr->children.linePtr; /* First line at leaf */ + while (prevPtr != linePtr) { + if (prevPtr->nextPtr == linePtr) { + return prevPtr; + } + prevPtr = prevPtr->nextPtr; + if (prevPtr == (TkTextLine *) NULL) { + panic("TkBTreePreviousLine ran out of lines"); + } + } + + /* + * This was the first line associated with the particular parent node. + * Search up the tree for the previous node, then search down from that + * node to find its last line. + */ + for (nodePtr = linePtr->parentPtr; ; nodePtr = nodePtr->parentPtr) { + if (nodePtr == (Node *) NULL || nodePtr->parentPtr == (Node *) NULL) { + return (TkTextLine *) NULL; + } + if (nodePtr != nodePtr->parentPtr->children.nodePtr) { + break; + } + } + for (node2Ptr = nodePtr->parentPtr->children.nodePtr; ; + node2Ptr = node2Ptr->children.nodePtr) { + while (node2Ptr->nextPtr != nodePtr) { + node2Ptr = node2Ptr->nextPtr; + } + if (node2Ptr->level == 0) { + break; + } + nodePtr = (Node *)NULL; + } + for (prevPtr = node2Ptr->children.linePtr ; ; prevPtr = prevPtr->nextPtr) { + if (prevPtr->nextPtr == (TkTextLine *) NULL) { + return prevPtr; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeLineIndex -- + * + * Given a pointer to a line in a B-tree, return the numerical + * index of that line. + * + * Results: + * The result is the index of linePtr within the tree, where 0 + * corresponds to the first line in the tree. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkBTreeLineIndex(linePtr) + TkTextLine *linePtr; /* Pointer to existing line in + * B-tree. */ +{ + register TkTextLine *linePtr2; + register Node *nodePtr, *parentPtr, *nodePtr2; + int index; + + /* + * First count how many lines precede this one in its level-0 + * node. + */ + + nodePtr = linePtr->parentPtr; + index = 0; + for (linePtr2 = nodePtr->children.linePtr; linePtr2 != linePtr; + linePtr2 = linePtr2->nextPtr) { + if (linePtr2 == NULL) { + panic("TkBTreeLineIndex couldn't find line"); + } + index += 1; + } + + /* + * Now work up through the levels of the tree one at a time, + * counting how many lines are in nodes preceding the current + * node. + */ + + for (parentPtr = nodePtr->parentPtr ; parentPtr != NULL; + nodePtr = parentPtr, parentPtr = parentPtr->parentPtr) { + for (nodePtr2 = parentPtr->children.nodePtr; nodePtr2 != nodePtr; + nodePtr2 = nodePtr2->nextPtr) { + if (nodePtr2 == NULL) { + panic("TkBTreeLineIndex couldn't find node"); + } + index += nodePtr2->numLines; + } + } + return index; +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeLinkSegment -- + * + * This procedure adds a new segment to a B-tree at a given + * location. + * + * Results: + * None. + * + * Side effects: + * SegPtr will be linked into its tree. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +void +TkBTreeLinkSegment(segPtr, indexPtr) + TkTextSegment *segPtr; /* Pointer to new segment to be added to + * B-tree. Should be completely initialized + * by caller except for nextPtr field. */ + TkTextIndex *indexPtr; /* Where to add segment: it gets linked + * in just before the segment indicated + * here. */ +{ + register TkTextSegment *prevPtr; + + prevPtr = SplitSeg(indexPtr); + if (prevPtr == NULL) { + segPtr->nextPtr = indexPtr->linePtr->segPtr; + indexPtr->linePtr->segPtr = segPtr; + } else { + segPtr->nextPtr = prevPtr->nextPtr; + prevPtr->nextPtr = segPtr; + } + CleanupLine(indexPtr->linePtr); + if (tkBTreeDebug) { + TkBTreeCheck(indexPtr->tree); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeUnlinkSegment -- + * + * This procedure unlinks a segment from its line in a B-tree. + * + * Results: + * None. + * + * Side effects: + * SegPtr will be unlinked from linePtr. The segment itself + * isn't modified by this procedure. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +void +TkBTreeUnlinkSegment(tree, segPtr, linePtr) + TkTextBTree tree; /* Tree containing segment. */ + TkTextSegment *segPtr; /* Segment to be unlinked. */ + TkTextLine *linePtr; /* Line that currently contains + * segment. */ +{ + register TkTextSegment *prevPtr; + + if (linePtr->segPtr == segPtr) { + linePtr->segPtr = segPtr->nextPtr; + } else { + for (prevPtr = linePtr->segPtr; prevPtr->nextPtr != segPtr; + prevPtr = prevPtr->nextPtr) { + /* Empty loop body. */ + } + prevPtr->nextPtr = segPtr->nextPtr; + } + CleanupLine(linePtr); +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeTag -- + * + * Turn a given tag on or off for a given range of characters in + * a B-tree of text. + * + * Results: + * None. + * + * Side effects: + * The given tag is added to the given range of characters + * in the tree or removed from all those characters, depending + * on the "add" argument. The structure of the btree is modified + * enough that index1Ptr and index2Ptr are no longer valid after + * this procedure returns, and the indexes may be modified by + * this procedure. + * + *---------------------------------------------------------------------- + */ + +void +TkBTreeTag(index1Ptr, index2Ptr, tagPtr, add) + register TkTextIndex *index1Ptr; /* Indicates first character in + * range. */ + register TkTextIndex *index2Ptr; /* Indicates character just after the + * last one in range. */ + TkTextTag *tagPtr; /* Tag to add or remove. */ + int add; /* One means add tag to the given + * range of characters; zero means + * remove the tag from the range. */ +{ + TkTextSegment *segPtr, *prevPtr; + TkTextSearch search; + TkTextLine *cleanupLinePtr; + int oldState; + int changed; + + /* + * See whether the tag is present at the start of the range. If + * the state doesn't already match what we want then add a toggle + * there. + */ + + oldState = TkBTreeCharTagged(index1Ptr, tagPtr); + if ((add != 0) ^ oldState) { + segPtr = (TkTextSegment *) ckalloc(TSEG_SIZE); + segPtr->typePtr = (add) ? &tkTextToggleOnType : &tkTextToggleOffType; + prevPtr = SplitSeg(index1Ptr); + if (prevPtr == NULL) { + segPtr->nextPtr = index1Ptr->linePtr->segPtr; + index1Ptr->linePtr->segPtr = segPtr; + } else { + segPtr->nextPtr = prevPtr->nextPtr; + prevPtr->nextPtr = segPtr; + } + segPtr->size = 0; + segPtr->body.toggle.tagPtr = tagPtr; + segPtr->body.toggle.inNodeCounts = 0; + } + + /* + * Scan the range of characters and delete any internal tag + * transitions. Keep track of what the old state was at the end + * of the range, and add a toggle there if it's needed. + */ + + TkBTreeStartSearch(index1Ptr, index2Ptr, tagPtr, &search); + cleanupLinePtr = index1Ptr->linePtr; + while (TkBTreeNextTag(&search)) { + oldState ^= 1; + segPtr = search.segPtr; + prevPtr = search.curIndex.linePtr->segPtr; + if (prevPtr == segPtr) { + search.curIndex.linePtr->segPtr = segPtr->nextPtr; + } else { + while (prevPtr->nextPtr != segPtr) { + prevPtr = prevPtr->nextPtr; + } + prevPtr->nextPtr = segPtr->nextPtr; + } + if (segPtr->body.toggle.inNodeCounts) { + ChangeNodeToggleCount(search.curIndex.linePtr->parentPtr, + segPtr->body.toggle.tagPtr, -1); + segPtr->body.toggle.inNodeCounts = 0; + changed = 1; + } else { + changed = 0; + } + ckfree((char *) segPtr); + + /* + * The code below is a bit tricky. After deleting a toggle + * we eventually have to call CleanupLine, in order to allow + * character segments to be merged together. To do this, we + * remember in cleanupLinePtr a line that needs to be + * cleaned up, but we don't clean it up until we've moved + * on to a different line. That way the cleanup process + * won't goof up segPtr. + */ + + if (cleanupLinePtr != search.curIndex.linePtr) { + CleanupLine(cleanupLinePtr); + cleanupLinePtr = search.curIndex.linePtr; + } + /* + * Quick hack. ChangeNodeToggleCount may move the tag's root + * location around and leave the search in the void. This resets + * the search. + */ + if (changed) { + TkBTreeStartSearch(index1Ptr, index2Ptr, tagPtr, &search); + } + } + if ((add != 0) ^ oldState) { + segPtr = (TkTextSegment *) ckalloc(TSEG_SIZE); + segPtr->typePtr = (add) ? &tkTextToggleOffType : &tkTextToggleOnType; + prevPtr = SplitSeg(index2Ptr); + if (prevPtr == NULL) { + segPtr->nextPtr = index2Ptr->linePtr->segPtr; + index2Ptr->linePtr->segPtr = segPtr; + } else { + segPtr->nextPtr = prevPtr->nextPtr; + prevPtr->nextPtr = segPtr; + } + segPtr->size = 0; + segPtr->body.toggle.tagPtr = tagPtr; + segPtr->body.toggle.inNodeCounts = 0; + } + + /* + * Cleanup cleanupLinePtr and the last line of the range, if + * these are different. + */ + + CleanupLine(cleanupLinePtr); + if (cleanupLinePtr != index2Ptr->linePtr) { + CleanupLine(index2Ptr->linePtr); + } + + if (tkBTreeDebug) { + TkBTreeCheck(index1Ptr->tree); + } +} + +/* + *---------------------------------------------------------------------- + * + * ChangeNodeToggleCount -- + * + * This procedure increments or decrements the toggle count for + * a particular tag in a particular node and all its ancestors + * up to the per-tag root node. + * + * Results: + * None. + * + * Side effects: + * The toggle count for tag is adjusted up or down by "delta" in + * nodePtr. This routine maintains the tagRootPtr that identifies + * the root node for the tag, moving it up or down the tree as needed. + * + *---------------------------------------------------------------------- + */ + +static void +ChangeNodeToggleCount(nodePtr, tagPtr, delta) + register Node *nodePtr; /* Node whose toggle count for a tag + * must be changed. */ + TkTextTag *tagPtr; /* Information about tag. */ + int delta; /* Amount to add to current toggle + * count for tag (may be negative). */ +{ + register Summary *summaryPtr, *prevPtr; + register Node *node2Ptr; + int rootLevel; /* Level of original tag root */ + + tagPtr->toggleCount += delta; + if (tagPtr->tagRootPtr == (Node *) NULL) { + tagPtr->tagRootPtr = nodePtr; + return; + } + + /* + * Note the level of the existing root for the tag so we can detect + * if it needs to be moved because of the toggle count change. + */ + + rootLevel = tagPtr->tagRootPtr->level; + + /* + * Iterate over the node and its ancestors up to the tag root, adjusting + * summary counts at each node and moving the tag's root upwards if + * necessary. + */ + + for ( ; nodePtr != tagPtr->tagRootPtr; nodePtr = nodePtr->parentPtr) { + /* + * See if there's already an entry for this tag for this node. If so, + * perhaps all we have to do is adjust its count. + */ + + for (prevPtr = NULL, summaryPtr = nodePtr->summaryPtr; + summaryPtr != NULL; + prevPtr = summaryPtr, summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr->tagPtr == tagPtr) { + break; + } + } + if (summaryPtr != NULL) { + summaryPtr->toggleCount += delta; + if (summaryPtr->toggleCount > 0 && + summaryPtr->toggleCount < tagPtr->toggleCount) { + continue; + } + if (summaryPtr->toggleCount != 0) { + /* + * Should never find a node with max toggle count at this + * point (there shouldn't have been a summary entry in the + * first place). + */ + + panic("ChangeNodeToggleCount: bad toggle count (%d) max (%d)", + summaryPtr->toggleCount, tagPtr->toggleCount); + } + + /* + * Zero toggle count; must remove this tag from the list. + */ + + if (prevPtr == NULL) { + nodePtr->summaryPtr = summaryPtr->nextPtr; + } else { + prevPtr->nextPtr = summaryPtr->nextPtr; + } + ckfree((char *) summaryPtr); + } else { + /* + * This tag isn't currently in the summary information list. + */ + + if (rootLevel == nodePtr->level) { + + /* + * The old tag root is at the same level in the tree as this + * node, but it isn't at this node. Move the tag root up + * a level, in the hopes that it will now cover this node + * as well as the old root (if not, we'll move it up again + * the next time through the loop). To push it up one level + * we copy the original toggle count into the summary + * information at the old root and change the root to its + * parent node. + */ + + Node *rootNodePtr = tagPtr->tagRootPtr; + summaryPtr = (Summary *) ckalloc(sizeof(Summary)); + summaryPtr->tagPtr = tagPtr; + summaryPtr->toggleCount = tagPtr->toggleCount - delta; + summaryPtr->nextPtr = rootNodePtr->summaryPtr; + rootNodePtr->summaryPtr = summaryPtr; + rootNodePtr = rootNodePtr->parentPtr; + rootLevel = rootNodePtr->level; + tagPtr->tagRootPtr = rootNodePtr; + } + summaryPtr = (Summary *) ckalloc(sizeof(Summary)); + summaryPtr->tagPtr = tagPtr; + summaryPtr->toggleCount = delta; + summaryPtr->nextPtr = nodePtr->summaryPtr; + nodePtr->summaryPtr = summaryPtr; + } + } + + /* + * If we've decremented the toggle count, then it may be necessary + * to push the tag root down one or more levels. + */ + + if (delta >= 0) { + return; + } + if (tagPtr->toggleCount == 0) { + tagPtr->tagRootPtr = (Node *) NULL; + return; + } + nodePtr = tagPtr->tagRootPtr; + while (nodePtr->level > 0) { + /* + * See if a single child node accounts for all of the tag's + * toggles. If so, push the root down one level. + */ + + for (node2Ptr = nodePtr->children.nodePtr; + node2Ptr != (Node *)NULL ; + node2Ptr = node2Ptr->nextPtr) { + for (prevPtr = NULL, summaryPtr = node2Ptr->summaryPtr; + summaryPtr != NULL; + prevPtr = summaryPtr, summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr->tagPtr == tagPtr) { + break; + } + } + if (summaryPtr == NULL) { + continue; + } + if (summaryPtr->toggleCount != tagPtr->toggleCount) { + /* + * No node has all toggles, so the root is still valid. + */ + + return; + } + + /* + * This node has all the toggles, so push down the root. + */ + + if (prevPtr == NULL) { + node2Ptr->summaryPtr = summaryPtr->nextPtr; + } else { + prevPtr->nextPtr = summaryPtr->nextPtr; + } + ckfree((char *) summaryPtr); + tagPtr->tagRootPtr = node2Ptr; + break; + } + nodePtr = tagPtr->tagRootPtr; + } +} + +/* + *---------------------------------------------------------------------- + * + * FindTagStart -- + * + * Find the start of the first range of a tag. + * + * Results: + * The return value is a pointer to the first tag toggle segment + * for the tag. This can be either a tagon or tagoff segments because + * of the way TkBTreeAdd removes a tag. + * Sets *indexPtr to be the index of the tag toggle. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static TkTextSegment * +FindTagStart(tree, tagPtr, indexPtr) + TkTextBTree tree; /* Tree to search within */ + TkTextTag *tagPtr; /* Tag to search for. */ + TkTextIndex *indexPtr; /* Return - index information */ +{ + register Node *nodePtr; + register TkTextLine *linePtr; + register TkTextSegment *segPtr; + register Summary *summaryPtr; + int offset; + + nodePtr = tagPtr->tagRootPtr; + if (nodePtr == (Node *) NULL) { + return NULL; + } + + /* + * Search from the root of the subtree that contains the tag down + * to the level 0 node. + */ + + while (nodePtr->level > 0) { + for (nodePtr = nodePtr->children.nodePtr ; nodePtr != (Node *) NULL; + nodePtr = nodePtr->nextPtr) { + for (summaryPtr = nodePtr->summaryPtr ; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr->tagPtr == tagPtr) { + goto gotNodeWithTag; + } + } + } + gotNodeWithTag: + continue; + } + + /* + * Work through the lines attached to the level-0 node. + */ + + for (linePtr = nodePtr->children.linePtr; linePtr != (TkTextLine *) NULL; + linePtr = linePtr->nextPtr) { + for (offset = 0, segPtr = linePtr->segPtr ; segPtr != NULL; + offset += segPtr->size, segPtr = segPtr->nextPtr) { + if (((segPtr->typePtr == &tkTextToggleOnType) + || (segPtr->typePtr == &tkTextToggleOffType)) + && (segPtr->body.toggle.tagPtr == tagPtr)) { + /* + * It is possible that this is a tagoff tag, but that + * gets cleaned up later. + */ + indexPtr->tree = tree; + indexPtr->linePtr = linePtr; + indexPtr->charIndex = offset; + return segPtr; + } + } + } + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * FindTagEnd -- + * + * Find the end of the last range of a tag. + * + * Results: + * The return value is a pointer to the last tag toggle segment + * for the tag. This can be either a tagon or tagoff segments because + * of the way TkBTreeAdd removes a tag. + * Sets *indexPtr to be the index of the tag toggle. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static TkTextSegment * +FindTagEnd(tree, tagPtr, indexPtr) + TkTextBTree tree; /* Tree to search within */ + TkTextTag *tagPtr; /* Tag to search for. */ + TkTextIndex *indexPtr; /* Return - index information */ +{ + register Node *nodePtr, *lastNodePtr; + register TkTextLine *linePtr ,*lastLinePtr; + register TkTextSegment *segPtr, *lastSegPtr, *last2SegPtr; + register Summary *summaryPtr; + int lastoffset, lastoffset2, offset; + + nodePtr = tagPtr->tagRootPtr; + if (nodePtr == (Node *) NULL) { + return NULL; + } + + /* + * Search from the root of the subtree that contains the tag down + * to the level 0 node. + */ + + while (nodePtr->level > 0) { + for (lastNodePtr = NULL, nodePtr = nodePtr->children.nodePtr ; + nodePtr != (Node *) NULL; nodePtr = nodePtr->nextPtr) { + for (summaryPtr = nodePtr->summaryPtr ; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr->tagPtr == tagPtr) { + lastNodePtr = nodePtr; + break; + } + } + } + nodePtr = lastNodePtr; + } + + /* + * Work through the lines attached to the level-0 node. + */ + last2SegPtr = NULL; + lastoffset2 = 0; + lastoffset = 0; + for (lastLinePtr = NULL, linePtr = nodePtr->children.linePtr; + linePtr != (TkTextLine *) NULL; linePtr = linePtr->nextPtr) { + for (offset = 0, lastSegPtr = NULL, segPtr = linePtr->segPtr ; + segPtr != NULL; + offset += segPtr->size, segPtr = segPtr->nextPtr) { + if (((segPtr->typePtr == &tkTextToggleOnType) + || (segPtr->typePtr == &tkTextToggleOffType)) + && (segPtr->body.toggle.tagPtr == tagPtr)) { + lastSegPtr = segPtr; + lastoffset = offset; + } + } + if (lastSegPtr != NULL) { + lastLinePtr = linePtr; + last2SegPtr = lastSegPtr; + lastoffset2 = lastoffset; + } + } + indexPtr->tree = tree; + indexPtr->linePtr = lastLinePtr; + indexPtr->charIndex = lastoffset2; + return last2SegPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeStartSearch -- + * + * This procedure sets up a search for tag transitions involving + * a given tag (or all tags) in a given range of the text. + * + * Results: + * None. + * + * Side effects: + * The information at *searchPtr is set up so that subsequent calls + * to TkBTreeNextTag or TkBTreePrevTag will return information about the + * locations of tag transitions. Note that TkBTreeNextTag or + * TkBTreePrevTag must be called to get the first transition. + * Note: unlike TkBTreeNextTag and TkBTreePrevTag, this routine does not + * guarantee that searchPtr->curIndex is equal to *index1Ptr. It may be + * greater than that if *index1Ptr is less than the first tag transition. + * + *---------------------------------------------------------------------- + */ + +void +TkBTreeStartSearch(index1Ptr, index2Ptr, tagPtr, searchPtr) + TkTextIndex *index1Ptr; /* Search starts here. Tag toggles + * at this position will not be + * returned. */ + TkTextIndex *index2Ptr; /* Search stops here. Tag toggles + * at this position *will* be + * returned. */ + TkTextTag *tagPtr; /* Tag to search for. NULL means + * search for any tag. */ + register TkTextSearch *searchPtr; /* Where to store information about + * search's progress. */ +{ + int offset; + TkTextIndex index0; /* First index of the tag */ + TkTextSegment *seg0Ptr; /* First segment of the tag */ + + /* + * Find the segment that contains the first toggle for the tag. This + * may become the starting point in the search. + */ + + seg0Ptr = FindTagStart(index1Ptr->tree, tagPtr, &index0); + if (seg0Ptr == (TkTextSegment *) NULL) { + /* + * Even though there are no toggles, the display code still + * uses the search curIndex, so initialize that anyway. + */ + + searchPtr->linesLeft = 0; + searchPtr->curIndex = *index1Ptr; + searchPtr->segPtr = NULL; + searchPtr->nextPtr = NULL; + return; + } + if (TkTextIndexCmp(index1Ptr, &index0) < 0) { + /* + * Adjust start of search up to the first range of the tag + */ + + searchPtr->curIndex = index0; + searchPtr->segPtr = NULL; + searchPtr->nextPtr = seg0Ptr; /* Will be returned by NextTag */ + index1Ptr = &index0; + } else { + searchPtr->curIndex = *index1Ptr; + searchPtr->segPtr = NULL; + searchPtr->nextPtr = TkTextIndexToSeg(index1Ptr, &offset); + searchPtr->curIndex.charIndex -= offset; + } + searchPtr->lastPtr = TkTextIndexToSeg(index2Ptr, (int *) NULL); + searchPtr->tagPtr = tagPtr; + searchPtr->linesLeft = TkBTreeLineIndex(index2Ptr->linePtr) + 1 + - TkBTreeLineIndex(index1Ptr->linePtr); + searchPtr->allTags = (tagPtr == NULL); + if (searchPtr->linesLeft == 1) { + /* + * Starting and stopping segments are in the same line; mark the + * search as over immediately if the second segment is before the + * first. A search does not return a toggle at the very start of + * the range, unless the range is artificially moved up to index0. + */ + if (((index1Ptr == &index0) && + (index1Ptr->charIndex > index2Ptr->charIndex)) || + ((index1Ptr != &index0) && + (index1Ptr->charIndex >= index2Ptr->charIndex))) { + searchPtr->linesLeft = 0; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeStartSearchBack -- + * + * This procedure sets up a search backwards for tag transitions involving + * a given tag (or all tags) in a given range of the text. In the + * normal case the first index (*index1Ptr) is beyond the second + * index (*index2Ptr). + * + * + * Results: + * None. + * + * Side effects: + * The information at *searchPtr is set up so that subsequent calls + * to TkBTreePrevTag will return information about the + * locations of tag transitions. Note that TkBTreePrevTag must be called + * to get the first transition. + * Note: unlike TkBTreeNextTag and TkBTreePrevTag, this routine does not + * guarantee that searchPtr->curIndex is equal to *index1Ptr. It may be + * less than that if *index1Ptr is greater than the last tag transition. + * + *---------------------------------------------------------------------- + */ + +void +TkBTreeStartSearchBack(index1Ptr, index2Ptr, tagPtr, searchPtr) + TkTextIndex *index1Ptr; /* Search starts here. Tag toggles + * at this position will not be + * returned. */ + TkTextIndex *index2Ptr; /* Search stops here. Tag toggles + * at this position *will* be + * returned. */ + TkTextTag *tagPtr; /* Tag to search for. NULL means + * search for any tag. */ + register TkTextSearch *searchPtr; /* Where to store information about + * search's progress. */ +{ + int offset; + TkTextIndex index0; /* Last index of the tag */ + TkTextIndex backOne; /* One character before starting index */ + TkTextSegment *seg0Ptr; /* Last segment of the tag */ + + /* + * Find the segment that contains the last toggle for the tag. This + * may become the starting point in the search. + */ + + seg0Ptr = FindTagEnd(index1Ptr->tree, tagPtr, &index0); + if (seg0Ptr == (TkTextSegment *) NULL) { + /* + * Even though there are no toggles, the display code still + * uses the search curIndex, so initialize that anyway. + */ + + searchPtr->linesLeft = 0; + searchPtr->curIndex = *index1Ptr; + searchPtr->segPtr = NULL; + searchPtr->nextPtr = NULL; + return; + } + + /* + * Adjust the start of the search so it doesn't find any tag toggles + * that are right at the index specified by the user. + */ + + if (TkTextIndexCmp(index1Ptr, &index0) > 0) { + searchPtr->curIndex = index0; + index1Ptr = &index0; + } else { + TkTextIndexBackChars(index1Ptr, 1, &searchPtr->curIndex); + } + searchPtr->segPtr = NULL; + searchPtr->nextPtr = TkTextIndexToSeg(&searchPtr->curIndex, &offset); + searchPtr->curIndex.charIndex -= offset; + + /* + * Adjust the end of the search so it does find toggles that are right + * at the second index specified by the user. + */ + + if ((TkBTreeLineIndex(index2Ptr->linePtr) == 0) && + (index2Ptr->charIndex == 0)) { + backOne = *index2Ptr; + searchPtr->lastPtr = NULL; /* Signals special case for 1.0 */ + } else { + TkTextIndexBackChars(index2Ptr, 1, &backOne); + searchPtr->lastPtr = TkTextIndexToSeg(&backOne, (int *) NULL); + } + searchPtr->tagPtr = tagPtr; + searchPtr->linesLeft = TkBTreeLineIndex(index1Ptr->linePtr) + 1 + - TkBTreeLineIndex(backOne.linePtr); + searchPtr->allTags = (tagPtr == NULL); + if (searchPtr->linesLeft == 1) { + /* + * Starting and stopping segments are in the same line; mark the + * search as over immediately if the second segment is after the + * first. + */ + + if (index1Ptr->charIndex <= backOne.charIndex) { + searchPtr->linesLeft = 0; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeNextTag -- + * + * Once a tag search has begun, successive calls to this procedure + * return successive tag toggles. Note: it is NOT SAFE to call this + * procedure if characters have been inserted into or deleted from + * the B-tree since the call to TkBTreeStartSearch. + * + * Results: + * The return value is 1 if another toggle was found that met the + * criteria specified in the call to TkBTreeStartSearch; in this + * case searchPtr->curIndex gives the toggle's position and + * searchPtr->curTagPtr points to its segment. 0 is returned if + * no more matching tag transitions were found; in this case + * searchPtr->curIndex is the same as searchPtr->stopIndex. + * + * Side effects: + * Information in *searchPtr is modified to update the state of the + * search and indicate where the next tag toggle is located. + * + *---------------------------------------------------------------------- + */ + +int +TkBTreeNextTag(searchPtr) + register TkTextSearch *searchPtr; /* Information about search in + * progress; must have been set up by + * call to TkBTreeStartSearch. */ +{ + register TkTextSegment *segPtr; + register Node *nodePtr; + register Summary *summaryPtr; + + if (searchPtr->linesLeft <= 0) { + goto searchOver; + } + + /* + * The outermost loop iterates over lines that may potentially contain + * a relevant tag transition, starting from the current segment in + * the current line. + */ + + segPtr = searchPtr->nextPtr; + while (1) { + /* + * Check for more tags on the current line. + */ + + for ( ; segPtr != NULL; segPtr = segPtr->nextPtr) { + if (segPtr == searchPtr->lastPtr) { + goto searchOver; + } + if (((segPtr->typePtr == &tkTextToggleOnType) + || (segPtr->typePtr == &tkTextToggleOffType)) + && (searchPtr->allTags + || (segPtr->body.toggle.tagPtr == searchPtr->tagPtr))) { + searchPtr->segPtr = segPtr; + searchPtr->nextPtr = segPtr->nextPtr; + searchPtr->tagPtr = segPtr->body.toggle.tagPtr; + return 1; + } + searchPtr->curIndex.charIndex += segPtr->size; + } + + /* + * See if there are more lines associated with the current parent + * node. If so, go back to the top of the loop to search the next + * one. + */ + + nodePtr = searchPtr->curIndex.linePtr->parentPtr; + searchPtr->curIndex.linePtr = searchPtr->curIndex.linePtr->nextPtr; + searchPtr->linesLeft--; + if (searchPtr->linesLeft <= 0) { + goto searchOver; + } + if (searchPtr->curIndex.linePtr != NULL) { + segPtr = searchPtr->curIndex.linePtr->segPtr; + searchPtr->curIndex.charIndex = 0; + continue; + } + if (nodePtr == searchPtr->tagPtr->tagRootPtr) { + goto searchOver; + } + + /* + * Search across and up through the B-tree's node hierarchy looking + * for the next node that has a relevant tag transition somewhere in + * its subtree. Be sure to update linesLeft as we skip over large + * chunks of lines. + */ + + while (1) { + while (nodePtr->nextPtr == NULL) { + if (nodePtr->parentPtr == NULL || + nodePtr->parentPtr == searchPtr->tagPtr->tagRootPtr) { + goto searchOver; + } + nodePtr = nodePtr->parentPtr; + } + nodePtr = nodePtr->nextPtr; + for (summaryPtr = nodePtr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if ((searchPtr->allTags) || + (summaryPtr->tagPtr == searchPtr->tagPtr)) { + goto gotNodeWithTag; + } + } + searchPtr->linesLeft -= nodePtr->numLines; + } + + /* + * At this point we've found a subtree that has a relevant tag + * transition. Now search down (and across) through that subtree + * to find the first level-0 node that has a relevant tag transition. + */ + + gotNodeWithTag: + while (nodePtr->level > 0) { + for (nodePtr = nodePtr->children.nodePtr; ; + nodePtr = nodePtr->nextPtr) { + for (summaryPtr = nodePtr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if ((searchPtr->allTags) + || (summaryPtr->tagPtr == searchPtr->tagPtr)) { + goto nextChild; + } + } + searchPtr->linesLeft -= nodePtr->numLines; + if (nodePtr->nextPtr == NULL) { + panic("TkBTreeNextTag found incorrect tag summary info."); + } + } + nextChild: + continue; + } + + /* + * Now we're down to a level-0 node that contains a line that contains + * a relevant tag transition. Set up line information and go back to + * the beginning of the loop to search through lines. + */ + + searchPtr->curIndex.linePtr = nodePtr->children.linePtr; + searchPtr->curIndex.charIndex = 0; + segPtr = searchPtr->curIndex.linePtr->segPtr; + if (searchPtr->linesLeft <= 0) { + goto searchOver; + } + continue; + } + + searchOver: + searchPtr->linesLeft = 0; + searchPtr->segPtr = NULL; + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreePrevTag -- + * + * Once a tag search has begun, successive calls to this procedure + * return successive tag toggles in the reverse direction. + * Note: it is NOT SAFE to call this + * procedure if characters have been inserted into or deleted from + * the B-tree since the call to TkBTreeStartSearch. + * + * Results: + * The return value is 1 if another toggle was found that met the + * criteria specified in the call to TkBTreeStartSearch; in this + * case searchPtr->curIndex gives the toggle's position and + * searchPtr->curTagPtr points to its segment. 0 is returned if + * no more matching tag transitions were found; in this case + * searchPtr->curIndex is the same as searchPtr->stopIndex. + * + * Side effects: + * Information in *searchPtr is modified to update the state of the + * search and indicate where the next tag toggle is located. + * + *---------------------------------------------------------------------- + */ + +int +TkBTreePrevTag(searchPtr) + register TkTextSearch *searchPtr; /* Information about search in + * progress; must have been set up by + * call to TkBTreeStartSearch. */ +{ + register TkTextSegment *segPtr, *prevPtr; + register TkTextLine *linePtr, *prevLinePtr; + register Node *nodePtr, *node2Ptr, *prevNodePtr; + register Summary *summaryPtr; + int charIndex; + int pastLast; /* Saw last marker during scan */ + int linesSkipped; + + if (searchPtr->linesLeft <= 0) { + goto searchOver; + } + + /* + * The outermost loop iterates over lines that may potentially contain + * a relevant tag transition, starting from the current segment in + * the current line. "nextPtr" is maintained as the last segment in + * a line that we can look at. + */ + + while (1) { + /* + * Check for the last toggle before the current segment on this line. + */ + charIndex = 0; + if (searchPtr->lastPtr == NULL) { + /* + * Search back to the very beginning, so pastLast is irrelevent. + */ + pastLast = 1; + } else { + pastLast = 0; + } + for (prevPtr = NULL, segPtr = searchPtr->curIndex.linePtr->segPtr ; + segPtr != NULL && segPtr != searchPtr->nextPtr; + segPtr = segPtr->nextPtr) { + if (((segPtr->typePtr == &tkTextToggleOnType) + || (segPtr->typePtr == &tkTextToggleOffType)) + && (searchPtr->allTags + || (segPtr->body.toggle.tagPtr == searchPtr->tagPtr))) { + prevPtr = segPtr; + searchPtr->curIndex.charIndex = charIndex; + } + if (segPtr == searchPtr->lastPtr) { + prevPtr = NULL; /* Segments earlier than last don't count */ + pastLast = 1; + } + charIndex += segPtr->size; + } + if (prevPtr != NULL) { + if (searchPtr->linesLeft == 1 && !pastLast) { + /* + * We found a segment that is before the stopping index. + * Note that it is OK if prevPtr == lastPtr. + */ + goto searchOver; + } + searchPtr->segPtr = prevPtr; + searchPtr->nextPtr = prevPtr; + searchPtr->tagPtr = prevPtr->body.toggle.tagPtr; + return 1; + } + + searchPtr->linesLeft--; + if (searchPtr->linesLeft <= 0) { + goto searchOver; + } + + /* + * See if there are more lines associated with the current parent + * node. If so, go back to the top of the loop to search the previous + * one. + */ + + nodePtr = searchPtr->curIndex.linePtr->parentPtr; + for (prevLinePtr = NULL, linePtr = nodePtr->children.linePtr; + linePtr != NULL && linePtr != searchPtr->curIndex.linePtr; + prevLinePtr = linePtr, linePtr = linePtr->nextPtr) { + /* empty loop body */ ; + } + if (prevLinePtr != NULL) { + searchPtr->curIndex.linePtr = prevLinePtr; + searchPtr->nextPtr = NULL; + continue; + } + if (nodePtr == searchPtr->tagPtr->tagRootPtr) { + goto searchOver; + } + + /* + * Search across and up through the B-tree's node hierarchy looking + * for the previous node that has a relevant tag transition somewhere in + * its subtree. The search and line counting is trickier with/out + * back pointers. We'll scan all the nodes under a parent up to + * the current node, searching all of them for tag state. The last + * one we find, if any, is recorded in prevNodePtr, and any nodes + * past prevNodePtr that don't have tag state increment linesSkipped. + */ + + while (1) { + for (prevNodePtr = NULL, linesSkipped = 0, + node2Ptr = nodePtr->parentPtr->children.nodePtr ; + node2Ptr != nodePtr; node2Ptr = node2Ptr->nextPtr) { + for (summaryPtr = node2Ptr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if ((searchPtr->allTags) || + (summaryPtr->tagPtr == searchPtr->tagPtr)) { + prevNodePtr = node2Ptr; + linesSkipped = 0; + goto keepLooking; + } + } + linesSkipped += node2Ptr->numLines; + + keepLooking: + continue; + } + if (prevNodePtr != NULL) { + nodePtr = prevNodePtr; + searchPtr->linesLeft -= linesSkipped; + goto gotNodeWithTag; + } + nodePtr = nodePtr->parentPtr; + if (nodePtr->parentPtr == NULL || + nodePtr == searchPtr->tagPtr->tagRootPtr) { + goto searchOver; + } + } + + /* + * At this point we've found a subtree that has a relevant tag + * transition. Now search down (and across) through that subtree + * to find the last level-0 node that has a relevant tag transition. + */ + + gotNodeWithTag: + while (nodePtr->level > 0) { + for (linesSkipped = 0, prevNodePtr = NULL, + nodePtr = nodePtr->children.nodePtr; nodePtr != NULL ; + nodePtr = nodePtr->nextPtr) { + for (summaryPtr = nodePtr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if ((searchPtr->allTags) + || (summaryPtr->tagPtr == searchPtr->tagPtr)) { + prevNodePtr = nodePtr; + linesSkipped = 0; + goto keepLooking2; + } + } + linesSkipped += nodePtr->numLines; + + keepLooking2: + continue; + } + if (prevNodePtr == NULL) { + panic("TkBTreePrevTag found incorrect tag summary info."); + } + searchPtr->linesLeft -= linesSkipped; + nodePtr = prevNodePtr; + } + + /* + * Now we're down to a level-0 node that contains a line that contains + * a relevant tag transition. Set up line information and go back to + * the beginning of the loop to search through lines. We start with + * the last line below the node. + */ + + for (prevLinePtr = NULL, linePtr = nodePtr->children.linePtr; + linePtr != NULL ; + prevLinePtr = linePtr, linePtr = linePtr->nextPtr) { + /* empty loop body */ ; + } + searchPtr->curIndex.linePtr = prevLinePtr; + searchPtr->curIndex.charIndex = 0; + if (searchPtr->linesLeft <= 0) { + goto searchOver; + } + continue; + } + + searchOver: + searchPtr->linesLeft = 0; + searchPtr->segPtr = NULL; + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeCharTagged -- + * + * Determine whether a particular character has a particular tag. + * + * Results: + * The return value is 1 if the given tag is in effect at the + * character given by linePtr and ch, and 0 otherwise. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkBTreeCharTagged(indexPtr, tagPtr) + TkTextIndex *indexPtr; /* Indicates a character position at + * which to check for a tag. */ + TkTextTag *tagPtr; /* Tag of interest. */ +{ + register Node *nodePtr; + register TkTextLine *siblingLinePtr; + register TkTextSegment *segPtr; + TkTextSegment *toggleSegPtr; + int toggles, index; + + /* + * Check for toggles for the tag in indexPtr's line but before + * indexPtr. If there is one, its type indicates whether or + * not the character is tagged. + */ + + toggleSegPtr = NULL; + for (index = 0, segPtr = indexPtr->linePtr->segPtr; + (index + segPtr->size) <= indexPtr->charIndex; + index += segPtr->size, segPtr = segPtr->nextPtr) { + if (((segPtr->typePtr == &tkTextToggleOnType) + || (segPtr->typePtr == &tkTextToggleOffType)) + && (segPtr->body.toggle.tagPtr == tagPtr)) { + toggleSegPtr = segPtr; + } + } + if (toggleSegPtr != NULL) { + return (toggleSegPtr->typePtr == &tkTextToggleOnType); + } + + /* + * No toggle in this line. Look for toggles for the tag in lines + * that are predecessors of indexPtr->linePtr but under the same + * level-0 node. + */ + + for (siblingLinePtr = indexPtr->linePtr->parentPtr->children.linePtr; + siblingLinePtr != indexPtr->linePtr; + siblingLinePtr = siblingLinePtr->nextPtr) { + for (segPtr = siblingLinePtr->segPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + if (((segPtr->typePtr == &tkTextToggleOnType) + || (segPtr->typePtr == &tkTextToggleOffType)) + && (segPtr->body.toggle.tagPtr == tagPtr)) { + toggleSegPtr = segPtr; + } + } + } + if (toggleSegPtr != NULL) { + return (toggleSegPtr->typePtr == &tkTextToggleOnType); + } + + /* + * No toggle in this node. Scan upwards through the ancestors of + * this node, counting the number of toggles of the given tag in + * siblings that precede that node. + */ + + toggles = 0; + for (nodePtr = indexPtr->linePtr->parentPtr; nodePtr->parentPtr != NULL; + nodePtr = nodePtr->parentPtr) { + register Node *siblingPtr; + register Summary *summaryPtr; + + for (siblingPtr = nodePtr->parentPtr->children.nodePtr; + siblingPtr != nodePtr; siblingPtr = siblingPtr->nextPtr) { + for (summaryPtr = siblingPtr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr->tagPtr == tagPtr) { + toggles += summaryPtr->toggleCount; + } + } + } + if (nodePtr == tagPtr->tagRootPtr) { + break; + } + } + + /* + * An odd number of toggles means that the tag is present at the + * given point. + */ + + return toggles & 1; +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeGetTags -- + * + * Return information about all of the tags that are associated + * with a particular character in a B-tree of text. + * + * Results: + * The return value is a malloc-ed array containing pointers to + * information for each of the tags that is associated with + * the character at the position given by linePtr and ch. The + * word at *numTagsPtr is filled in with the number of pointers + * in the array. It is up to the caller to free the array by + * passing it to free. If there are no tags at the given character + * then a NULL pointer is returned and *numTagsPtr will be set to 0. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +TkTextTag ** +TkBTreeGetTags(indexPtr, numTagsPtr) + TkTextIndex *indexPtr; /* Indicates a particular position in + * the B-tree. */ + int *numTagsPtr; /* Store number of tags found at this + * location. */ +{ + register Node *nodePtr; + register TkTextLine *siblingLinePtr; + register TkTextSegment *segPtr; + int src, dst, index; + TagInfo tagInfo; +#define NUM_TAG_INFOS 10 + + tagInfo.numTags = 0; + tagInfo.arraySize = NUM_TAG_INFOS; + tagInfo.tagPtrs = (TkTextTag **) ckalloc((unsigned) + NUM_TAG_INFOS*sizeof(TkTextTag *)); + tagInfo.counts = (int *) ckalloc((unsigned) + NUM_TAG_INFOS*sizeof(int)); + + /* + * Record tag toggles within the line of indexPtr but preceding + * indexPtr. + */ + + for (index = 0, segPtr = indexPtr->linePtr->segPtr; + (index + segPtr->size) <= indexPtr->charIndex; + index += segPtr->size, segPtr = segPtr->nextPtr) { + if ((segPtr->typePtr == &tkTextToggleOnType) + || (segPtr->typePtr == &tkTextToggleOffType)) { + IncCount(segPtr->body.toggle.tagPtr, 1, &tagInfo); + } + } + + /* + * Record toggles for tags in lines that are predecessors of + * indexPtr->linePtr but under the same level-0 node. + */ + + for (siblingLinePtr = indexPtr->linePtr->parentPtr->children.linePtr; + siblingLinePtr != indexPtr->linePtr; + siblingLinePtr = siblingLinePtr->nextPtr) { + for (segPtr = siblingLinePtr->segPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + if ((segPtr->typePtr == &tkTextToggleOnType) + || (segPtr->typePtr == &tkTextToggleOffType)) { + IncCount(segPtr->body.toggle.tagPtr, 1, &tagInfo); + } + } + } + + /* + * For each node in the ancestry of this line, record tag toggles + * for all siblings that precede that node. + */ + + for (nodePtr = indexPtr->linePtr->parentPtr; nodePtr->parentPtr != NULL; + nodePtr = nodePtr->parentPtr) { + register Node *siblingPtr; + register Summary *summaryPtr; + + for (siblingPtr = nodePtr->parentPtr->children.nodePtr; + siblingPtr != nodePtr; siblingPtr = siblingPtr->nextPtr) { + for (summaryPtr = siblingPtr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr->toggleCount & 1) { + IncCount(summaryPtr->tagPtr, summaryPtr->toggleCount, + &tagInfo); + } + } + } + } + + /* + * Go through the tag information and squash out all of the tags + * that have even toggle counts (these tags exist before the point + * of interest, but not at the desired character itself). + */ + + for (src = 0, dst = 0; src < tagInfo.numTags; src++) { + if (tagInfo.counts[src] & 1) { + tagInfo.tagPtrs[dst] = tagInfo.tagPtrs[src]; + dst++; + } + } + *numTagsPtr = dst; + ckfree((char *) tagInfo.counts); + if (dst == 0) { + ckfree((char *) tagInfo.tagPtrs); + return NULL; + } + return tagInfo.tagPtrs; +} + +/* + *---------------------------------------------------------------------- + * + * IncCount -- + * + * This is a utility procedure used by TkBTreeGetTags. It + * increments the count for a particular tag, adding a new + * entry for that tag if there wasn't one previously. + * + * Results: + * None. + * + * Side effects: + * The information at *tagInfoPtr may be modified, and the arrays + * may be reallocated to make them larger. + * + *---------------------------------------------------------------------- + */ + +static void +IncCount(tagPtr, inc, tagInfoPtr) + TkTextTag *tagPtr; /* Handle for tag. */ + int inc; /* Amount by which to increment tag count. */ + TagInfo *tagInfoPtr; /* Holds cumulative information about tags; + * increment count here. */ +{ + register TkTextTag **tagPtrPtr; + int count; + + for (tagPtrPtr = tagInfoPtr->tagPtrs, count = tagInfoPtr->numTags; + count > 0; tagPtrPtr++, count--) { + if (*tagPtrPtr == tagPtr) { + tagInfoPtr->counts[tagInfoPtr->numTags-count] += inc; + return; + } + } + + /* + * There isn't currently an entry for this tag, so we have to + * make a new one. If the arrays are full, then enlarge the + * arrays first. + */ + + if (tagInfoPtr->numTags == tagInfoPtr->arraySize) { + TkTextTag **newTags; + int *newCounts, newSize; + + newSize = 2*tagInfoPtr->arraySize; + newTags = (TkTextTag **) ckalloc((unsigned) + (newSize*sizeof(TkTextTag *))); + memcpy((VOID *) newTags, (VOID *) tagInfoPtr->tagPtrs, + tagInfoPtr->arraySize * sizeof(TkTextTag *)); + ckfree((char *) tagInfoPtr->tagPtrs); + tagInfoPtr->tagPtrs = newTags; + newCounts = (int *) ckalloc((unsigned) (newSize*sizeof(int))); + memcpy((VOID *) newCounts, (VOID *) tagInfoPtr->counts, + tagInfoPtr->arraySize * sizeof(int)); + ckfree((char *) tagInfoPtr->counts); + tagInfoPtr->counts = newCounts; + tagInfoPtr->arraySize = newSize; + } + + tagInfoPtr->tagPtrs[tagInfoPtr->numTags] = tagPtr; + tagInfoPtr->counts[tagInfoPtr->numTags] = inc; + tagInfoPtr->numTags++; +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeCheck -- + * + * This procedure runs a set of consistency checks over a B-tree + * and panics if any inconsistencies are found. + * + * Results: + * None. + * + * Side effects: + * If a structural defect is found, the procedure panics with an + * error message. + * + *---------------------------------------------------------------------- + */ + +void +TkBTreeCheck(tree) + TkTextBTree tree; /* Tree to check. */ +{ + BTree *treePtr = (BTree *) tree; + register Summary *summaryPtr; + register Node *nodePtr; + register TkTextLine *linePtr; + register TkTextSegment *segPtr; + register TkTextTag *tagPtr; + Tcl_HashEntry *entryPtr; + Tcl_HashSearch search; + int count; + + /* + * Make sure that the tag toggle counts and the tag root pointers are OK. + */ + for (entryPtr = Tcl_FirstHashEntry(&treePtr->textPtr->tagTable, &search); + entryPtr != NULL ; entryPtr = Tcl_NextHashEntry(&search)) { + tagPtr = (TkTextTag *) Tcl_GetHashValue(entryPtr); + nodePtr = tagPtr->tagRootPtr; + if (nodePtr == (Node *) NULL) { + if (tagPtr->toggleCount != 0) { + panic("TkBTreeCheck found \"%s\" with toggles (%d) but no root", + tagPtr->name, tagPtr->toggleCount); + } + continue; /* no ranges for the tag */ + } else if (tagPtr->toggleCount == 0) { + panic("TkBTreeCheck found root for \"%s\" with no toggles", + tagPtr->name); + } else if (tagPtr->toggleCount & 1) { + panic("TkBTreeCheck found odd toggle count for \"%s\" (%d)", + tagPtr->name, tagPtr->toggleCount); + } + for (summaryPtr = nodePtr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr->tagPtr == tagPtr) { + panic("TkBTreeCheck found root node with summary info"); + } + } + count = 0; + if (nodePtr->level > 0) { + for (nodePtr = nodePtr->children.nodePtr ; nodePtr != NULL ; + nodePtr = nodePtr->nextPtr) { + for (summaryPtr = nodePtr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr->tagPtr == tagPtr) { + count += summaryPtr->toggleCount; + } + } + } + } else { + for (linePtr = nodePtr->children.linePtr ; linePtr != NULL ; + linePtr = linePtr->nextPtr) { + for (segPtr = linePtr->segPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + if ((segPtr->typePtr == &tkTextToggleOnType || + segPtr->typePtr == &tkTextToggleOffType) && + segPtr->body.toggle.tagPtr == tagPtr) { + count++; + } + } + } + } + if (count != tagPtr->toggleCount) { + panic("TkBTreeCheck toggleCount (%d) wrong for \"%s\" should be (%d)", + tagPtr->toggleCount, tagPtr->name, count); + } + } + + /* + * Call a recursive procedure to do the main body of checks. + */ + + nodePtr = treePtr->rootPtr; + CheckNodeConsistency(treePtr->rootPtr); + + /* + * Make sure that there are at least two lines in the text and + * that the last line has no characters except a newline. + */ + + if (nodePtr->numLines < 2) { + panic("TkBTreeCheck: less than 2 lines in tree"); + } + while (nodePtr->level > 0) { + nodePtr = nodePtr->children.nodePtr; + while (nodePtr->nextPtr != NULL) { + nodePtr = nodePtr->nextPtr; + } + } + linePtr = nodePtr->children.linePtr; + while (linePtr->nextPtr != NULL) { + linePtr = linePtr->nextPtr; + } + segPtr = linePtr->segPtr; + while ((segPtr->typePtr == &tkTextToggleOffType) + || (segPtr->typePtr == &tkTextRightMarkType) + || (segPtr->typePtr == &tkTextLeftMarkType)) { + /* + * It's OK to toggle a tag off in the last line, but + * not to start a new range. It's also OK to have marks + * in the last line. + */ + + segPtr = segPtr->nextPtr; + } + if (segPtr->typePtr != &tkTextCharType) { + panic("TkBTreeCheck: last line has bogus segment type"); + } + if (segPtr->nextPtr != NULL) { + panic("TkBTreeCheck: last line has too many segments"); + } + if (segPtr->size != 1) { + panic("TkBTreeCheck: last line has wrong # characters: %d", + segPtr->size); + } + if ((segPtr->body.chars[0] != '\n') || (segPtr->body.chars[1] != 0)) { + panic("TkBTreeCheck: last line had bad value: %s", + segPtr->body.chars); + } +} + +/* + *---------------------------------------------------------------------- + * + * CheckNodeConsistency -- + * + * This procedure is called as part of consistency checking for + * B-trees: it checks several aspects of a node and also runs + * checks recursively on the node's children. + * + * Results: + * None. + * + * Side effects: + * If anything suspicious is found in the tree structure, the + * procedure panics. + * + *---------------------------------------------------------------------- + */ + +static void +CheckNodeConsistency(nodePtr) + register Node *nodePtr; /* Node whose subtree should be + * checked. */ +{ + register Node *childNodePtr; + register Summary *summaryPtr, *summaryPtr2; + register TkTextLine *linePtr; + register TkTextSegment *segPtr; + int numChildren, numLines, toggleCount, minChildren; + + if (nodePtr->parentPtr != NULL) { + minChildren = MIN_CHILDREN; + } else if (nodePtr->level > 0) { + minChildren = 2; + } else { + minChildren = 1; + } + if ((nodePtr->numChildren < minChildren) + || (nodePtr->numChildren > MAX_CHILDREN)) { + panic("CheckNodeConsistency: bad child count (%d)", + nodePtr->numChildren); + } + + numChildren = 0; + numLines = 0; + if (nodePtr->level == 0) { + for (linePtr = nodePtr->children.linePtr; linePtr != NULL; + linePtr = linePtr->nextPtr) { + if (linePtr->parentPtr != nodePtr) { + panic("CheckNodeConsistency: line doesn't point to parent"); + } + if (linePtr->segPtr == NULL) { + panic("CheckNodeConsistency: line has no segments"); + } + for (segPtr = linePtr->segPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + if (segPtr->typePtr->checkProc != NULL) { + (*segPtr->typePtr->checkProc)(segPtr, linePtr); + } + if ((segPtr->size == 0) && (!segPtr->typePtr->leftGravity) + && (segPtr->nextPtr != NULL) + && (segPtr->nextPtr->size == 0) + && (segPtr->nextPtr->typePtr->leftGravity)) { + panic("CheckNodeConsistency: wrong segment order for gravity"); + } + if ((segPtr->nextPtr == NULL) + && (segPtr->typePtr != &tkTextCharType)) { + panic("CheckNodeConsistency: line ended with wrong type"); + } + } + numChildren++; + numLines++; + } + } else { + for (childNodePtr = nodePtr->children.nodePtr; childNodePtr != NULL; + childNodePtr = childNodePtr->nextPtr) { + if (childNodePtr->parentPtr != nodePtr) { + panic("CheckNodeConsistency: node doesn't point to parent"); + } + if (childNodePtr->level != (nodePtr->level-1)) { + panic("CheckNodeConsistency: level mismatch (%d %d)", + nodePtr->level, childNodePtr->level); + } + CheckNodeConsistency(childNodePtr); + for (summaryPtr = childNodePtr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + for (summaryPtr2 = nodePtr->summaryPtr; ; + summaryPtr2 = summaryPtr2->nextPtr) { + if (summaryPtr2 == NULL) { + if (summaryPtr->tagPtr->tagRootPtr == nodePtr) { + break; + } + panic("CheckNodeConsistency: node tag \"%s\" not %s", + summaryPtr->tagPtr->name, + "present in parent summaries"); + } + if (summaryPtr->tagPtr == summaryPtr2->tagPtr) { + break; + } + } + } + numChildren++; + numLines += childNodePtr->numLines; + } + } + if (numChildren != nodePtr->numChildren) { + panic("CheckNodeConsistency: mismatch in numChildren (%d %d)", + numChildren, nodePtr->numChildren); + } + if (numLines != nodePtr->numLines) { + panic("CheckNodeConsistency: mismatch in numLines (%d %d)", + numLines, nodePtr->numLines); + } + + for (summaryPtr = nodePtr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr->tagPtr->toggleCount == summaryPtr->toggleCount) { + panic("CheckNodeConsistency: found unpruned root for \"%s\"", + summaryPtr->tagPtr->name); + } + toggleCount = 0; + if (nodePtr->level == 0) { + for (linePtr = nodePtr->children.linePtr; linePtr != NULL; + linePtr = linePtr->nextPtr) { + for (segPtr = linePtr->segPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + if ((segPtr->typePtr != &tkTextToggleOnType) + && (segPtr->typePtr != &tkTextToggleOffType)) { + continue; + } + if (segPtr->body.toggle.tagPtr == summaryPtr->tagPtr) { + toggleCount ++; + } + } + } + } else { + for (childNodePtr = nodePtr->children.nodePtr; + childNodePtr != NULL; + childNodePtr = childNodePtr->nextPtr) { + for (summaryPtr2 = childNodePtr->summaryPtr; + summaryPtr2 != NULL; + summaryPtr2 = summaryPtr2->nextPtr) { + if (summaryPtr2->tagPtr == summaryPtr->tagPtr) { + toggleCount += summaryPtr2->toggleCount; + } + } + } + } + if (toggleCount != summaryPtr->toggleCount) { + panic("CheckNodeConsistency: mismatch in toggleCount (%d %d)", + toggleCount, summaryPtr->toggleCount); + } + for (summaryPtr2 = summaryPtr->nextPtr; summaryPtr2 != NULL; + summaryPtr2 = summaryPtr2->nextPtr) { + if (summaryPtr2->tagPtr == summaryPtr->tagPtr) { + panic("CheckNodeConsistency: duplicated node tag: %s", + summaryPtr->tagPtr->name); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * Rebalance -- + * + * This procedure is called when a node of a B-tree appears to be + * out of balance (too many children, or too few). It rebalances + * that node and all of its ancestors in the tree. + * + * Results: + * None. + * + * Side effects: + * The internal structure of treePtr may change. + * + *---------------------------------------------------------------------- + */ + +static void +Rebalance(treePtr, nodePtr) + BTree *treePtr; /* Tree that is being rebalanced. */ + register Node *nodePtr; /* Node that may be out of balance. */ +{ + /* + * Loop over the entire ancestral chain of the node, working up + * through the tree one node at a time until the root node has + * been processed. + */ + + for ( ; nodePtr != NULL; nodePtr = nodePtr->parentPtr) { + register Node *newPtr, *childPtr; + register TkTextLine *linePtr; + int i; + + /* + * Check to see if the node has too many children. If it does, + * then split off all but the first MIN_CHILDREN into a separate + * node following the original one. Then repeat until the + * node has a decent size. + */ + + if (nodePtr->numChildren > MAX_CHILDREN) { + while (1) { + /* + * If the node being split is the root node, then make a + * new root node above it first. + */ + + if (nodePtr->parentPtr == NULL) { + newPtr = (Node *) ckalloc(sizeof(Node)); + newPtr->parentPtr = NULL; + newPtr->nextPtr = NULL; + newPtr->summaryPtr = NULL; + newPtr->level = nodePtr->level + 1; + newPtr->children.nodePtr = nodePtr; + newPtr->numChildren = 1; + newPtr->numLines = nodePtr->numLines; + RecomputeNodeCounts(newPtr); + treePtr->rootPtr = newPtr; + } + newPtr = (Node *) ckalloc(sizeof(Node)); + newPtr->parentPtr = nodePtr->parentPtr; + newPtr->nextPtr = nodePtr->nextPtr; + nodePtr->nextPtr = newPtr; + newPtr->summaryPtr = NULL; + newPtr->level = nodePtr->level; + newPtr->numChildren = nodePtr->numChildren - MIN_CHILDREN; + if (nodePtr->level == 0) { + for (i = MIN_CHILDREN-1, + linePtr = nodePtr->children.linePtr; + i > 0; i--, linePtr = linePtr->nextPtr) { + /* Empty loop body. */ + } + newPtr->children.linePtr = linePtr->nextPtr; + linePtr->nextPtr = NULL; + } else { + for (i = MIN_CHILDREN-1, + childPtr = nodePtr->children.nodePtr; + i > 0; i--, childPtr = childPtr->nextPtr) { + /* Empty loop body. */ + } + newPtr->children.nodePtr = childPtr->nextPtr; + childPtr->nextPtr = NULL; + } + RecomputeNodeCounts(nodePtr); + nodePtr->parentPtr->numChildren++; + nodePtr = newPtr; + if (nodePtr->numChildren <= MAX_CHILDREN) { + RecomputeNodeCounts(nodePtr); + break; + } + } + } + + while (nodePtr->numChildren < MIN_CHILDREN) { + register Node *otherPtr; + Node *halfwayNodePtr = NULL; /* Initialization needed only */ + TkTextLine *halfwayLinePtr = NULL; /* to prevent cc warnings. */ + int totalChildren, firstChildren, i; + + /* + * Too few children for this node. If this is the root then, + * it's OK for it to have less than MIN_CHILDREN children + * as long as it's got at least two. If it has only one + * (and isn't at level 0), then chop the root node out of + * the tree and use its child as the new root. + */ + + if (nodePtr->parentPtr == NULL) { + if ((nodePtr->numChildren == 1) && (nodePtr->level > 0)) { + treePtr->rootPtr = nodePtr->children.nodePtr; + treePtr->rootPtr->parentPtr = NULL; + DeleteSummaries(nodePtr->summaryPtr); + ckfree((char *) nodePtr); + } + return; + } + + /* + * Not the root. Make sure that there are siblings to + * balance with. + */ + + if (nodePtr->parentPtr->numChildren < 2) { + Rebalance(treePtr, nodePtr->parentPtr); + continue; + } + + /* + * Find a sibling neighbor to borrow from, and arrange for + * nodePtr to be the earlier of the pair. + */ + + if (nodePtr->nextPtr == NULL) { + for (otherPtr = nodePtr->parentPtr->children.nodePtr; + otherPtr->nextPtr != nodePtr; + otherPtr = otherPtr->nextPtr) { + /* Empty loop body. */ + } + nodePtr = otherPtr; + } + otherPtr = nodePtr->nextPtr; + + /* + * We're going to either merge the two siblings together + * into one node or redivide the children among them to + * balance their loads. As preparation, join their two + * child lists into a single list and remember the half-way + * point in the list. + */ + + totalChildren = nodePtr->numChildren + otherPtr->numChildren; + firstChildren = totalChildren/2; + if (nodePtr->children.nodePtr == NULL) { + nodePtr->children = otherPtr->children; + otherPtr->children.nodePtr = NULL; + otherPtr->children.linePtr = NULL; + } + if (nodePtr->level == 0) { + register TkTextLine *linePtr; + + for (linePtr = nodePtr->children.linePtr, i = 1; + linePtr->nextPtr != NULL; + linePtr = linePtr->nextPtr, i++) { + if (i == firstChildren) { + halfwayLinePtr = linePtr; + } + } + linePtr->nextPtr = otherPtr->children.linePtr; + while (i <= firstChildren) { + halfwayLinePtr = linePtr; + linePtr = linePtr->nextPtr; + i++; + } + } else { + register Node *childPtr; + + for (childPtr = nodePtr->children.nodePtr, i = 1; + childPtr->nextPtr != NULL; + childPtr = childPtr->nextPtr, i++) { + if (i <= firstChildren) { + if (i == firstChildren) { + halfwayNodePtr = childPtr; + } + } + } + childPtr->nextPtr = otherPtr->children.nodePtr; + while (i <= firstChildren) { + halfwayNodePtr = childPtr; + childPtr = childPtr->nextPtr; + i++; + } + } + + /* + * If the two siblings can simply be merged together, do it. + */ + + if (totalChildren <= MAX_CHILDREN) { + RecomputeNodeCounts(nodePtr); + nodePtr->nextPtr = otherPtr->nextPtr; + nodePtr->parentPtr->numChildren--; + DeleteSummaries(otherPtr->summaryPtr); + ckfree((char *) otherPtr); + continue; + } + + /* + * The siblings can't be merged, so just divide their + * children evenly between them. + */ + + if (nodePtr->level == 0) { + otherPtr->children.linePtr = halfwayLinePtr->nextPtr; + halfwayLinePtr->nextPtr = NULL; + } else { + otherPtr->children.nodePtr = halfwayNodePtr->nextPtr; + halfwayNodePtr->nextPtr = NULL; + } + RecomputeNodeCounts(nodePtr); + RecomputeNodeCounts(otherPtr); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * RecomputeNodeCounts -- + * + * This procedure is called to recompute all the counts in a node + * (tags, child information, etc.) by scanning the information in + * its descendants. This procedure is called during rebalancing + * when a node's child structure has changed. + * + * Results: + * None. + * + * Side effects: + * The tag counts for nodePtr are modified to reflect its current + * child structure, as are its numChildren and numLines fields. + * Also, all of the childrens' parentPtr fields are made to point + * to nodePtr. + * + *---------------------------------------------------------------------- + */ + +static void +RecomputeNodeCounts(nodePtr) + register Node *nodePtr; /* Node whose tag summary information + * must be recomputed. */ +{ + register Summary *summaryPtr, *summaryPtr2; + register Node *childPtr; + register TkTextLine *linePtr; + register TkTextSegment *segPtr; + TkTextTag *tagPtr; + + /* + * Zero out all the existing counts for the node, but don't delete + * the existing Summary records (most of them will probably be reused). + */ + + for (summaryPtr = nodePtr->summaryPtr; summaryPtr != NULL; + summaryPtr = summaryPtr->nextPtr) { + summaryPtr->toggleCount = 0; + } + nodePtr->numChildren = 0; + nodePtr->numLines = 0; + + /* + * Scan through the children, adding the childrens' tag counts into + * the node's tag counts and adding new Summary structures if + * necessary. + */ + + if (nodePtr->level == 0) { + for (linePtr = nodePtr->children.linePtr; linePtr != NULL; + linePtr = linePtr->nextPtr) { + nodePtr->numChildren++; + nodePtr->numLines++; + linePtr->parentPtr = nodePtr; + for (segPtr = linePtr->segPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + if (((segPtr->typePtr != &tkTextToggleOnType) + && (segPtr->typePtr != &tkTextToggleOffType)) + || !(segPtr->body.toggle.inNodeCounts)) { + continue; + } + tagPtr = segPtr->body.toggle.tagPtr; + for (summaryPtr = nodePtr->summaryPtr; ; + summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr == NULL) { + summaryPtr = (Summary *) ckalloc(sizeof(Summary)); + summaryPtr->tagPtr = tagPtr; + summaryPtr->toggleCount = 1; + summaryPtr->nextPtr = nodePtr->summaryPtr; + nodePtr->summaryPtr = summaryPtr; + break; + } + if (summaryPtr->tagPtr == tagPtr) { + summaryPtr->toggleCount++; + break; + } + } + } + } + } else { + for (childPtr = nodePtr->children.nodePtr; childPtr != NULL; + childPtr = childPtr->nextPtr) { + nodePtr->numChildren++; + nodePtr->numLines += childPtr->numLines; + childPtr->parentPtr = nodePtr; + for (summaryPtr2 = childPtr->summaryPtr; summaryPtr2 != NULL; + summaryPtr2 = summaryPtr2->nextPtr) { + for (summaryPtr = nodePtr->summaryPtr; ; + summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr == NULL) { + summaryPtr = (Summary *) ckalloc(sizeof(Summary)); + summaryPtr->tagPtr = summaryPtr2->tagPtr; + summaryPtr->toggleCount = summaryPtr2->toggleCount; + summaryPtr->nextPtr = nodePtr->summaryPtr; + nodePtr->summaryPtr = summaryPtr; + break; + } + if (summaryPtr->tagPtr == summaryPtr2->tagPtr) { + summaryPtr->toggleCount += summaryPtr2->toggleCount; + break; + } + } + } + } + } + + /* + * Scan through the node's tag records again and delete any Summary + * records that still have a zero count, or that have all the toggles. + * The node with the children that account for all the tags toggles + * have no summary information, and they become the tagRootPtr for the tag. + */ + + summaryPtr2 = NULL; + for (summaryPtr = nodePtr->summaryPtr; summaryPtr != NULL; ) { + if (summaryPtr->toggleCount > 0 && + summaryPtr->toggleCount < summaryPtr->tagPtr->toggleCount) { + if (nodePtr->level == summaryPtr->tagPtr->tagRootPtr->level) { + /* + * The tag's root node split and some toggles left. + * The tag root must move up a level. + */ + summaryPtr->tagPtr->tagRootPtr = nodePtr->parentPtr; + } + summaryPtr2 = summaryPtr; + summaryPtr = summaryPtr->nextPtr; + continue; + } + if (summaryPtr->toggleCount == summaryPtr->tagPtr->toggleCount) { + /* + * A node merge has collected all the toggles under one node. + * Push the root down to this level. + */ + summaryPtr->tagPtr->tagRootPtr = nodePtr; + } + if (summaryPtr2 != NULL) { + summaryPtr2->nextPtr = summaryPtr->nextPtr; + ckfree((char *) summaryPtr); + summaryPtr = summaryPtr2->nextPtr; + } else { + nodePtr->summaryPtr = summaryPtr->nextPtr; + ckfree((char *) summaryPtr); + summaryPtr = nodePtr->summaryPtr; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeNumLines -- + * + * This procedure returns a count of the number of lines of + * text present in a given B-tree. + * + * Results: + * The return value is a count of the number of usable lines + * in tree (i.e. it doesn't include the dummy line that is just + * used to mark the end of the tree). + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkBTreeNumLines(tree) + TkTextBTree tree; /* Information about tree. */ +{ + BTree *treePtr = (BTree *) tree; + return treePtr->rootPtr->numLines - 1; +} + +/* + *-------------------------------------------------------------- + * + * CharSplitProc -- + * + * This procedure implements splitting for character segments. + * + * Results: + * The return value is a pointer to a chain of two segments + * that have the same characters as segPtr except split + * among the two segments. + * + * Side effects: + * Storage for segPtr is freed. + * + *-------------------------------------------------------------- + */ + +static TkTextSegment * +CharSplitProc(segPtr, index) + TkTextSegment *segPtr; /* Pointer to segment to split. */ + int index; /* Position within segment at which + * to split. */ +{ + TkTextSegment *newPtr1, *newPtr2; + + newPtr1 = (TkTextSegment *) ckalloc(CSEG_SIZE(index)); + newPtr2 = (TkTextSegment *) ckalloc( + CSEG_SIZE(segPtr->size - index)); + newPtr1->typePtr = &tkTextCharType; + newPtr1->nextPtr = newPtr2; + newPtr1->size = index; + strncpy(newPtr1->body.chars, segPtr->body.chars, (size_t) index); + newPtr1->body.chars[index] = 0; + newPtr2->typePtr = &tkTextCharType; + newPtr2->nextPtr = segPtr->nextPtr; + newPtr2->size = segPtr->size - index; + strcpy(newPtr2->body.chars, segPtr->body.chars + index); + ckfree((char*) segPtr); + return newPtr1; +} + +/* + *-------------------------------------------------------------- + * + * CharCleanupProc -- + * + * This procedure merges adjacent character segments into + * a single character segment, if possible. + * + * Results: + * The return value is a pointer to the first segment in + * the (new) list of segments that used to start with segPtr. + * + * Side effects: + * Storage for the segments may be allocated and freed. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static TkTextSegment * +CharCleanupProc(segPtr, linePtr) + TkTextSegment *segPtr; /* Pointer to first of two adjacent + * segments to join. */ + TkTextLine *linePtr; /* Line containing segments (not + * used). */ +{ + TkTextSegment *segPtr2, *newPtr; + + segPtr2 = segPtr->nextPtr; + if ((segPtr2 == NULL) || (segPtr2->typePtr != &tkTextCharType)) { + return segPtr; + } + newPtr = (TkTextSegment *) ckalloc(CSEG_SIZE( + segPtr->size + segPtr2->size)); + newPtr->typePtr = &tkTextCharType; + newPtr->nextPtr = segPtr2->nextPtr; + newPtr->size = segPtr->size + segPtr2->size; + strcpy(newPtr->body.chars, segPtr->body.chars); + strcpy(newPtr->body.chars + segPtr->size, segPtr2->body.chars); + ckfree((char*) segPtr); + ckfree((char*) segPtr2); + return newPtr; +} + +/* + *-------------------------------------------------------------- + * + * CharDeleteProc -- + * + * This procedure is invoked to delete a character segment. + * + * Results: + * Always returns 0 to indicate that the segment was deleted. + * + * Side effects: + * Storage for the segment is freed. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +CharDeleteProc(segPtr, linePtr, treeGone) + TkTextSegment *segPtr; /* Segment to delete. */ + TkTextLine *linePtr; /* Line containing segment. */ + int treeGone; /* Non-zero means the entire tree is + * being deleted, so everything must + * get cleaned up. */ +{ + ckfree((char*) segPtr); + return 0; +} + +/* + *-------------------------------------------------------------- + * + * CharCheckProc -- + * + * This procedure is invoked to perform consistency checks + * on character segments. + * + * Results: + * None. + * + * Side effects: + * If the segment isn't inconsistent then the procedure + * panics. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +CharCheckProc(segPtr, linePtr) + TkTextSegment *segPtr; /* Segment to check. */ + TkTextLine *linePtr; /* Line containing segment. */ +{ + /* + * Make sure that the segment contains the number of + * characters indicated by its header, and that the last + * segment in a line ends in a newline. Also make sure + * that there aren't ever two character segments adjacent + * to each other: they should be merged together. + */ + + if (segPtr->size <= 0) { + panic("CharCheckProc: segment has size <= 0"); + } + if (strlen(segPtr->body.chars) != (size_t) segPtr->size) { + panic("CharCheckProc: segment has wrong size"); + } + if (segPtr->nextPtr == NULL) { + if (segPtr->body.chars[segPtr->size-1] != '\n') { + panic("CharCheckProc: line doesn't end with newline"); + } + } else { + if (segPtr->nextPtr->typePtr == &tkTextCharType) { + panic("CharCheckProc: adjacent character segments weren't merged"); + } + } +} + +/* + *-------------------------------------------------------------- + * + * ToggleDeleteProc -- + * + * This procedure is invoked to delete toggle segments. + * + * Results: + * Returns 1 to indicate that the segment may not be deleted, + * unless the entire B-tree is going away. + * + * Side effects: + * If the tree is going away then the toggle's memory is + * freed; otherwise the toggle counts in nodes above the + * segment get updated. + * + *-------------------------------------------------------------- + */ + +static int +ToggleDeleteProc(segPtr, linePtr, treeGone) + TkTextSegment *segPtr; /* Segment to check. */ + TkTextLine *linePtr; /* Line containing segment. */ + int treeGone; /* Non-zero means the entire tree is + * being deleted, so everything must + * get cleaned up. */ +{ + if (treeGone) { + ckfree((char *) segPtr); + return 0; + } + + /* + * This toggle is in the middle of a range of characters that's + * being deleted. Refuse to die. We'll be moved to the end of + * the deleted range and our cleanup procedure will be called + * later. Decrement node toggle counts here, and set a flag + * so we'll re-increment them in the cleanup procedure. + */ + + if (segPtr->body.toggle.inNodeCounts) { + ChangeNodeToggleCount(linePtr->parentPtr, + segPtr->body.toggle.tagPtr, -1); + segPtr->body.toggle.inNodeCounts = 0; + } + return 1; +} + +/* + *-------------------------------------------------------------- + * + * ToggleCleanupProc -- + * + * This procedure is called when a toggle is part of a line that's + * been modified in some way. It's invoked after the + * modifications are complete. + * + * Results: + * The return value is the head segment in a new list + * that is to replace the tail of the line that used to + * start at segPtr. This allows the procedure to delete + * or modify segPtr. + * + * Side effects: + * Toggle counts in the nodes above the new line will be + * updated if they're not already. Toggles may be collapsed + * if there are duplicate toggles at the same position. + * + *-------------------------------------------------------------- + */ + +static TkTextSegment * +ToggleCleanupProc(segPtr, linePtr) + TkTextSegment *segPtr; /* Segment to check. */ + TkTextLine *linePtr; /* Line that now contains segment. */ +{ + TkTextSegment *segPtr2, *prevPtr; + int counts; + + /* + * If this is a toggle-off segment, look ahead through the next + * segments to see if there's a toggle-on segment for the same tag + * before any segments with non-zero size. If so then the two + * toggles cancel each other; remove them both. + */ + + if (segPtr->typePtr == &tkTextToggleOffType) { + for (prevPtr = segPtr, segPtr2 = prevPtr->nextPtr; + (segPtr2 != NULL) && (segPtr2->size == 0); + prevPtr = segPtr2, segPtr2 = prevPtr->nextPtr) { + if (segPtr2->typePtr != &tkTextToggleOnType) { + continue; + } + if (segPtr2->body.toggle.tagPtr != segPtr->body.toggle.tagPtr) { + continue; + } + counts = segPtr->body.toggle.inNodeCounts + + segPtr2->body.toggle.inNodeCounts; + if (counts != 0) { + ChangeNodeToggleCount(linePtr->parentPtr, + segPtr->body.toggle.tagPtr, -counts); + } + prevPtr->nextPtr = segPtr2->nextPtr; + ckfree((char *) segPtr2); + segPtr2 = segPtr->nextPtr; + ckfree((char *) segPtr); + return segPtr2; + } + } + + if (!segPtr->body.toggle.inNodeCounts) { + ChangeNodeToggleCount(linePtr->parentPtr, + segPtr->body.toggle.tagPtr, 1); + segPtr->body.toggle.inNodeCounts = 1; + } + return segPtr; +} + +/* + *-------------------------------------------------------------- + * + * ToggleLineChangeProc -- + * + * This procedure is invoked when a toggle segment is about + * to move from one line to another. + * + * Results: + * None. + * + * Side effects: + * Toggle counts are decremented in the nodes above the line. + * + *-------------------------------------------------------------- + */ + +static void +ToggleLineChangeProc(segPtr, linePtr) + TkTextSegment *segPtr; /* Segment to check. */ + TkTextLine *linePtr; /* Line that used to contain segment. */ +{ + if (segPtr->body.toggle.inNodeCounts) { + ChangeNodeToggleCount(linePtr->parentPtr, + segPtr->body.toggle.tagPtr, -1); + segPtr->body.toggle.inNodeCounts = 0; + } +} + +/* + *-------------------------------------------------------------- + * + * ToggleCheckProc -- + * + * This procedure is invoked to perform consistency checks + * on toggle segments. + * + * Results: + * None. + * + * Side effects: + * If a consistency problem is found the procedure panics. + * + *-------------------------------------------------------------- + */ + +static void +ToggleCheckProc(segPtr, linePtr) + TkTextSegment *segPtr; /* Segment to check. */ + TkTextLine *linePtr; /* Line containing segment. */ +{ + register Summary *summaryPtr; + int needSummary; + + if (segPtr->size != 0) { + panic("ToggleCheckProc: segment had non-zero size"); + } + if (!segPtr->body.toggle.inNodeCounts) { + panic("ToggleCheckProc: toggle counts not updated in nodes"); + } + needSummary = (segPtr->body.toggle.tagPtr->tagRootPtr != linePtr->parentPtr); + for (summaryPtr = linePtr->parentPtr->summaryPtr; ; + summaryPtr = summaryPtr->nextPtr) { + if (summaryPtr == NULL) { + if (needSummary) { + panic("ToggleCheckProc: tag not present in node"); + } else { + break; + } + } + if (summaryPtr->tagPtr == segPtr->body.toggle.tagPtr) { + if (!needSummary) { + panic("ToggleCheckProc: tag present in root node summary"); + } + break; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkBTreeCharsInLine -- + * + * This procedure returns a count of the number of characters + * in a given line. + * + * Results: + * The return value is the character count for linePtr. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkBTreeCharsInLine(linePtr) + TkTextLine *linePtr; /* Line whose characters should be + * counted. */ +{ + TkTextSegment *segPtr; + int count; + + count = 0; + for (segPtr = linePtr->segPtr; segPtr != NULL; segPtr = segPtr->nextPtr) { + count += segPtr->size; + } + return count; +} diff --git a/generic/tkTextDisp.c b/generic/tkTextDisp.c new file mode 100644 index 0000000..8d9c022 --- /dev/null +++ b/generic/tkTextDisp.c @@ -0,0 +1,5015 @@ +/* + * tkTextDisp.c -- + * + * This module provides facilities to display text widgets. It is + * the only place where information is kept about the screen layout + * of text widgets. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkTextDisp.c 1.124 97/07/11 18:01:03 + */ + +#include "tkPort.h" +#include "tkInt.h" +#include "tkText.h" + +/* + * The following structure describes how to display a range of characters. + * The information is generated by scanning all of the tags associated + * with the characters and combining that with default information for + * the overall widget. These structures form the hash keys for + * dInfoPtr->styleTable. + */ + +typedef struct StyleValues { + Tk_3DBorder border; /* Used for drawing background under text. + * NULL means use widget background. */ + int borderWidth; /* Width of 3-D border for background. */ + int relief; /* 3-D relief for background. */ + Pixmap bgStipple; /* Stipple bitmap for background. None + * means draw solid. */ + XColor *fgColor; /* Foreground color for text. */ + Tk_Font tkfont; /* Font for displaying text. */ + Pixmap fgStipple; /* Stipple bitmap for text and other + * foreground stuff. None means draw + * solid.*/ + int justify; /* Justification style for text. */ + int lMargin1; /* Left margin, in pixels, for first display + * line of each text line. */ + int lMargin2; /* Left margin, in pixels, for second and + * later display lines of each text line. */ + int offset; /* Offset in pixels of baseline, relative to + * baseline of line. */ + int overstrike; /* Non-zero means draw overstrike through + * text. */ + int rMargin; /* Right margin, in pixels. */ + int spacing1; /* Spacing above first dline in text line. */ + int spacing2; /* Spacing between lines of dline. */ + int spacing3; /* Spacing below last dline in text line. */ + TkTextTabArray *tabArrayPtr;/* Locations and types of tab stops (may + * be NULL). */ + int underline; /* Non-zero means draw underline underneath + * text. */ + Tk_Uid wrapMode; /* How to handle wrap-around for this tag. + * One of tkTextCharUid, tkTextNoneUid, + * or tkTextWordUid. */ +} StyleValues; + +/* + * The following structure extends the StyleValues structure above with + * graphics contexts used to actually draw the characters. The entries + * in dInfoPtr->styleTable point to structures of this type. + */ + +typedef struct TextStyle { + int refCount; /* Number of times this structure is + * referenced in Chunks. */ + GC bgGC; /* Graphics context for background. None + * means use widget background. */ + GC fgGC; /* Graphics context for foreground. */ + StyleValues *sValuePtr; /* Raw information from which GCs were + * derived. */ + Tcl_HashEntry *hPtr; /* Pointer to entry in styleTable. Used + * to delete entry. */ +} TextStyle; + +/* + * The following macro determines whether two styles have the same + * background so that, for example, no beveled border should be drawn + * between them. + */ + +#define SAME_BACKGROUND(s1, s2) \ + (((s1)->sValuePtr->border == (s2)->sValuePtr->border) \ + && ((s1)->sValuePtr->borderWidth == (s2)->sValuePtr->borderWidth) \ + && ((s1)->sValuePtr->relief == (s2)->sValuePtr->relief) \ + && ((s1)->sValuePtr->bgStipple == (s2)->sValuePtr->bgStipple)) + +/* + * The following structure describes one line of the display, which may + * be either part or all of one line of the text. + */ + +typedef struct DLine { + TkTextIndex index; /* Identifies first character in text + * that is displayed on this line. */ + int count; /* Number of characters accounted for by this + * display line, including a trailing space + * or newline that isn't actually displayed. */ + int y; /* Y-position at which line is supposed to + * be drawn (topmost pixel of rectangular + * area occupied by line). */ + int oldY; /* Y-position at which line currently + * appears on display. -1 means line isn't + * currently visible on display and must be + * redrawn. This is used to move lines by + * scrolling rather than re-drawing. */ + int height; /* Height of line, in pixels. */ + int baseline; /* Offset of text baseline from y, in + * pixels. */ + int spaceAbove; /* How much extra space was added to the + * top of the line because of spacing + * options. This is included in height + * and baseline. */ + int spaceBelow; /* How much extra space was added to the + * bottom of the line because of spacing + * options. This is included in height. */ + int length; /* Total length of line, in pixels. */ + TkTextDispChunk *chunkPtr; /* Pointer to first chunk in list of all + * of those that are displayed on this + * line of the screen. */ + struct DLine *nextPtr; /* Next in list of all display lines for + * this window. The list is sorted in + * order from top to bottom. Note: the + * next DLine doesn't always correspond + * to the next line of text: (a) can have + * multiple DLines for one text line, and + * (b) can have gaps where DLine's have been + * deleted because they're out of date. */ + int flags; /* Various flag bits: see below for values. */ +} DLine; + +/* + * Flag bits for DLine structures: + * + * HAS_3D_BORDER - Non-zero means that at least one of the + * chunks in this line has a 3D border, so + * it potentially interacts with 3D borders + * in neighboring lines (see + * DisplayLineBackground). + * NEW_LAYOUT - Non-zero means that the line has been + * re-layed out since the last time the + * display was updated. + * TOP_LINE - Non-zero means that this was the top line + * in the window the last time that the window + * was laid out. This is important because + * a line may be displayed differently if its + * at the top or bottom than if it's in the + * middle (e.g. beveled edges aren't displayed + * for middle lines if the adjacent line has + * a similar background). + * BOTTOM_LINE - Non-zero means that this was the bottom line + * in the window the last time that the window + * was laid out. + */ + +#define HAS_3D_BORDER 1 +#define NEW_LAYOUT 2 +#define TOP_LINE 4 +#define BOTTOM_LINE 8 + +/* + * Overall display information for a text widget: + */ + +typedef struct TextDInfo { + Tcl_HashTable styleTable; /* Hash table that maps from StyleValues + * to TextStyles for this widget. */ + DLine *dLinePtr; /* First in list of all display lines for + * this widget, in order from top to bottom. */ + GC copyGC; /* Graphics context for copying from off- + * screen pixmaps onto screen. */ + GC scrollGC; /* Graphics context for copying from one place + * in the window to another (scrolling): + * differs from copyGC in that we need to get + * GraphicsExpose events. */ + int x; /* First x-coordinate that may be used for + * actually displaying line information. + * Leaves space for border, etc. */ + int y; /* First y-coordinate that may be used for + * actually displaying line information. + * Leaves space for border, etc. */ + int maxX; /* First x-coordinate to right of available + * space for displaying lines. */ + int maxY; /* First y-coordinate below available + * space for displaying lines. */ + int topOfEof; /* Top-most pixel (lowest y-value) that has + * been drawn in the appropriate fashion for + * the portion of the window after the last + * line of the text. This field is used to + * figure out when to redraw part or all of + * the eof field. */ + + /* + * Information used for scrolling: + */ + + int newCharOffset; /* Desired x scroll position, measured as the + * number of average-size characters off-screen + * to the left for a line with no left + * margin. */ + int curPixelOffset; /* Actual x scroll position, measured as the + * number of pixels off-screen to the left. */ + int maxLength; /* Length in pixels of longest line that's + * visible in window (length may exceed window + * size). If there's no wrapping, this will + * be zero. */ + double xScrollFirst, xScrollLast; + /* Most recent values reported to horizontal + * scrollbar; used to eliminate unnecessary + * reports. */ + double yScrollFirst, yScrollLast; + /* Most recent values reported to vertical + * scrollbar; used to eliminate unnecessary + * reports. */ + + /* + * The following information is used to implement scanning: + */ + + int scanMarkChar; /* Character that was at the left edge of + * the window when the scan started. */ + int scanMarkX; /* X-position of mouse at time scan started. */ + int scanTotalScroll; /* Total scrolling (in screen lines) that has + * occurred since scanMarkY was set. */ + int scanMarkY; /* Y-position of mouse at time scan started. */ + + /* + * Miscellaneous information: + */ + + int dLinesInvalidated; /* This value is set to 1 whenever something + * happens that invalidates information in + * DLine structures; if a redisplay + * is in progress, it will see this and + * abort the redisplay. This is needed + * because, for example, an embedded window + * could change its size when it is first + * displayed, invalidating the DLine that + * is currently being displayed. If redisplay + * continues, it will use freed memory and + * could dump core. */ + int flags; /* Various flag values: see below for + * definitions. */ +} TextDInfo; + +/* + * In TkTextDispChunk structures for character segments, the clientData + * field points to one of the following structures: + */ + +typedef struct CharInfo { + int numChars; /* Number of characters to display. */ + char chars[4]; /* Characters to display. Actual size + * will be numChars, not 4. THIS MUST BE + * THE LAST FIELD IN THE STRUCTURE. */ +} CharInfo; + +/* + * Flag values for TextDInfo structures: + * + * DINFO_OUT_OF_DATE: Non-zero means that the DLine structures + * for this window are partially or completely + * out of date and need to be recomputed. + * REDRAW_PENDING: Means that a when-idle handler has been + * scheduled to update the display. + * REDRAW_BORDERS: Means window border or pad area has + * potentially been damaged and must be redrawn. + * REPICK_NEEDED: 1 means that the widget has been modified + * in a way that could change the current + * character (a different character might be + * under the mouse cursor now). Need to + * recompute the current character before + * the next redisplay. + */ + +#define DINFO_OUT_OF_DATE 1 +#define REDRAW_PENDING 2 +#define REDRAW_BORDERS 4 +#define REPICK_NEEDED 8 + +/* + * The following counters keep statistics about redisplay that can be + * checked to see how clever this code is at reducing redisplays. + */ + +static int numRedisplays; /* Number of calls to DisplayText. */ +static int linesRedrawn; /* Number of calls to DisplayDLine. */ +static int numCopies; /* Number of calls to XCopyArea to copy part + * of the screen. */ + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void AdjustForTab _ANSI_ARGS_((TkText *textPtr, + TkTextTabArray *tabArrayPtr, int index, + TkTextDispChunk *chunkPtr)); +static void CharBboxProc _ANSI_ARGS_((TkTextDispChunk *chunkPtr, + int index, int y, int lineHeight, int baseline, + int *xPtr, int *yPtr, int *widthPtr, + int *heightPtr)); +static void CharDisplayProc _ANSI_ARGS_((TkTextDispChunk *chunkPtr, + int x, int y, int height, int baseline, + Display *display, Drawable dst, int screenY)); +static int CharMeasureProc _ANSI_ARGS_((TkTextDispChunk *chunkPtr, + int x)); +static void CharUndisplayProc _ANSI_ARGS_((TkText *textPtr, + TkTextDispChunk *chunkPtr)); +static void DisplayDLine _ANSI_ARGS_((TkText *textPtr, + DLine *dlPtr, DLine *prevPtr, Pixmap pixmap)); +static void DisplayLineBackground _ANSI_ARGS_((TkText *textPtr, + DLine *dlPtr, DLine *prevPtr, Pixmap pixmap)); +static void DisplayText _ANSI_ARGS_((ClientData clientData)); +static DLine * FindDLine _ANSI_ARGS_((DLine *dlPtr, + TkTextIndex *indexPtr)); +static void FreeDLines _ANSI_ARGS_((TkText *textPtr, + DLine *firstPtr, DLine *lastPtr, int unlink)); +static void FreeStyle _ANSI_ARGS_((TkText *textPtr, + TextStyle *stylePtr)); +static TextStyle * GetStyle _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *indexPtr)); +static void GetXView _ANSI_ARGS_((Tcl_Interp *interp, + TkText *textPtr, int report)); +static void GetYView _ANSI_ARGS_((Tcl_Interp *interp, + TkText *textPtr, int report)); +static DLine * LayoutDLine _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *indexPtr)); +static int MeasureChars _ANSI_ARGS_((Tk_Font tkfont, + CONST char *source, int maxChars, int startX, + int maxX, int tabOrigin, int *nextXPtr)); +static void MeasureUp _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *srcPtr, int distance, + TkTextIndex *dstPtr)); +static int NextTabStop _ANSI_ARGS_((Tk_Font tkfont, int x, + int tabOrigin)); +static void UpdateDisplayInfo _ANSI_ARGS_((TkText *textPtr)); +static void ScrollByLines _ANSI_ARGS_((TkText *textPtr, + int offset)); +static int SizeOfTab _ANSI_ARGS_((TkText *textPtr, + TkTextTabArray *tabArrayPtr, int index, int x, + int maxX)); +static void TextInvalidateRegion _ANSI_ARGS_((TkText *textPtr, + TkRegion region)); + + +/* + *---------------------------------------------------------------------- + * + * TkTextCreateDInfo -- + * + * This procedure is called when a new text widget is created. + * Its job is to set up display-related information for the widget. + * + * Results: + * None. + * + * Side effects: + * A TextDInfo data structure is allocated and initialized and attached + * to textPtr. + * + *---------------------------------------------------------------------- + */ + +void +TkTextCreateDInfo(textPtr) + TkText *textPtr; /* Overall information for text widget. */ +{ + register TextDInfo *dInfoPtr; + XGCValues gcValues; + + dInfoPtr = (TextDInfo *) ckalloc(sizeof(TextDInfo)); + Tcl_InitHashTable(&dInfoPtr->styleTable, sizeof(StyleValues)/sizeof(int)); + dInfoPtr->dLinePtr = NULL; + dInfoPtr->copyGC = None; + gcValues.graphics_exposures = True; + dInfoPtr->scrollGC = Tk_GetGC(textPtr->tkwin, GCGraphicsExposures, + &gcValues); + dInfoPtr->topOfEof = 0; + dInfoPtr->newCharOffset = 0; + dInfoPtr->curPixelOffset = 0; + dInfoPtr->maxLength = 0; + dInfoPtr->xScrollFirst = -1; + dInfoPtr->xScrollLast = -1; + dInfoPtr->yScrollFirst = -1; + dInfoPtr->yScrollLast = -1; + dInfoPtr->scanMarkChar = 0; + dInfoPtr->scanMarkX = 0; + dInfoPtr->scanTotalScroll = 0; + dInfoPtr->scanMarkY = 0; + dInfoPtr->dLinesInvalidated = 0; + dInfoPtr->flags = DINFO_OUT_OF_DATE; + textPtr->dInfoPtr = dInfoPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextFreeDInfo -- + * + * This procedure is called to free up all of the private display + * information kept by this file for a text widget. + * + * Results: + * None. + * + * Side effects: + * Lots of resources get freed. + * + *---------------------------------------------------------------------- + */ + +void +TkTextFreeDInfo(textPtr) + TkText *textPtr; /* Overall information for text widget. */ +{ + register TextDInfo *dInfoPtr = textPtr->dInfoPtr; + + /* + * Be careful to free up styleTable *after* freeing up all the + * DLines, so that the hash table is still intact to free up the + * style-related information from the lines. Once the lines are + * all free then styleTable will be empty. + */ + + FreeDLines(textPtr, dInfoPtr->dLinePtr, (DLine *) NULL, 1); + Tcl_DeleteHashTable(&dInfoPtr->styleTable); + if (dInfoPtr->copyGC != None) { + Tk_FreeGC(textPtr->display, dInfoPtr->copyGC); + } + Tk_FreeGC(textPtr->display, dInfoPtr->scrollGC); + if (dInfoPtr->flags & REDRAW_PENDING) { + Tcl_CancelIdleCall(DisplayText, (ClientData) textPtr); + } + ckfree((char *) dInfoPtr); +} + +/* + *---------------------------------------------------------------------- + * + * GetStyle -- + * + * This procedure creates all the information needed to display + * text at a particular location. + * + * Results: + * The return value is a pointer to a TextStyle structure that + * corresponds to *sValuePtr. + * + * Side effects: + * A new entry may be created in the style table for the widget. + * + *---------------------------------------------------------------------- + */ + +static TextStyle * +GetStyle(textPtr, indexPtr) + TkText *textPtr; /* Overall information about text widget. */ + TkTextIndex *indexPtr; /* The character in the text for which + * display information is wanted. */ +{ + TkTextTag **tagPtrs; + register TkTextTag *tagPtr; + StyleValues styleValues; + TextStyle *stylePtr; + Tcl_HashEntry *hPtr; + int numTags, new, i; + XGCValues gcValues; + unsigned long mask; + + /* + * The variables below keep track of the highest-priority specification + * that has occurred for each of the various fields of the StyleValues. + */ + + int borderPrio, borderWidthPrio, reliefPrio, bgStipplePrio; + int fgPrio, fontPrio, fgStipplePrio; + int underlinePrio, justifyPrio, offsetPrio; + int lMargin1Prio, lMargin2Prio, rMarginPrio; + int spacing1Prio, spacing2Prio, spacing3Prio; + int overstrikePrio, tabPrio, wrapPrio; + + /* + * Find out what tags are present for the character, then compute + * a StyleValues structure corresponding to those tags (scan + * through all of the tags, saving information for the highest- + * priority tag). + */ + + tagPtrs = TkBTreeGetTags(indexPtr, &numTags); + borderPrio = borderWidthPrio = reliefPrio = bgStipplePrio = -1; + fgPrio = fontPrio = fgStipplePrio = -1; + underlinePrio = justifyPrio = offsetPrio = -1; + lMargin1Prio = lMargin2Prio = rMarginPrio = -1; + spacing1Prio = spacing2Prio = spacing3Prio = -1; + overstrikePrio = tabPrio = wrapPrio = -1; + memset((VOID *) &styleValues, 0, sizeof(StyleValues)); + styleValues.relief = TK_RELIEF_FLAT; + styleValues.fgColor = textPtr->fgColor; + styleValues.tkfont = textPtr->tkfont; + styleValues.justify = TK_JUSTIFY_LEFT; + styleValues.spacing1 = textPtr->spacing1; + styleValues.spacing2 = textPtr->spacing2; + styleValues.spacing3 = textPtr->spacing3; + styleValues.tabArrayPtr = textPtr->tabArrayPtr; + styleValues.wrapMode = textPtr->wrapMode; + for (i = 0 ; i < numTags; i++) { + tagPtr = tagPtrs[i]; + + /* + * On Windows and Mac, we need to skip the selection tag if + * we don't have focus. + */ + +#ifndef ALWAYS_SHOW_SELECTION + if ((tagPtr == textPtr->selTagPtr) && !(textPtr->flags & GOT_FOCUS)) { + continue; + } +#endif + + if ((tagPtr->border != NULL) && (tagPtr->priority > borderPrio)) { + styleValues.border = tagPtr->border; + borderPrio = tagPtr->priority; + } + if ((tagPtr->bdString != NULL) + && (tagPtr->priority > borderWidthPrio)) { + styleValues.borderWidth = tagPtr->borderWidth; + borderWidthPrio = tagPtr->priority; + } + if ((tagPtr->reliefString != NULL) + && (tagPtr->priority > reliefPrio)) { + if (styleValues.border == NULL) { + styleValues.border = textPtr->border; + } + styleValues.relief = tagPtr->relief; + reliefPrio = tagPtr->priority; + } + if ((tagPtr->bgStipple != None) + && (tagPtr->priority > bgStipplePrio)) { + styleValues.bgStipple = tagPtr->bgStipple; + bgStipplePrio = tagPtr->priority; + } + if ((tagPtr->fgColor != None) && (tagPtr->priority > fgPrio)) { + styleValues.fgColor = tagPtr->fgColor; + fgPrio = tagPtr->priority; + } + if ((tagPtr->tkfont != None) && (tagPtr->priority > fontPrio)) { + styleValues.tkfont = tagPtr->tkfont; + fontPrio = tagPtr->priority; + } + if ((tagPtr->fgStipple != None) + && (tagPtr->priority > fgStipplePrio)) { + styleValues.fgStipple = tagPtr->fgStipple; + fgStipplePrio = tagPtr->priority; + } + if ((tagPtr->justifyString != NULL) + && (tagPtr->priority > justifyPrio)) { + styleValues.justify = tagPtr->justify; + justifyPrio = tagPtr->priority; + } + if ((tagPtr->lMargin1String != NULL) + && (tagPtr->priority > lMargin1Prio)) { + styleValues.lMargin1 = tagPtr->lMargin1; + lMargin1Prio = tagPtr->priority; + } + if ((tagPtr->lMargin2String != NULL) + && (tagPtr->priority > lMargin2Prio)) { + styleValues.lMargin2 = tagPtr->lMargin2; + lMargin2Prio = tagPtr->priority; + } + if ((tagPtr->offsetString != NULL) + && (tagPtr->priority > offsetPrio)) { + styleValues.offset = tagPtr->offset; + offsetPrio = tagPtr->priority; + } + if ((tagPtr->overstrikeString != NULL) + && (tagPtr->priority > overstrikePrio)) { + styleValues.overstrike = tagPtr->overstrike; + overstrikePrio = tagPtr->priority; + } + if ((tagPtr->rMarginString != NULL) + && (tagPtr->priority > rMarginPrio)) { + styleValues.rMargin = tagPtr->rMargin; + rMarginPrio = tagPtr->priority; + } + if ((tagPtr->spacing1String != NULL) + && (tagPtr->priority > spacing1Prio)) { + styleValues.spacing1 = tagPtr->spacing1; + spacing1Prio = tagPtr->priority; + } + if ((tagPtr->spacing2String != NULL) + && (tagPtr->priority > spacing2Prio)) { + styleValues.spacing2 = tagPtr->spacing2; + spacing2Prio = tagPtr->priority; + } + if ((tagPtr->spacing3String != NULL) + && (tagPtr->priority > spacing3Prio)) { + styleValues.spacing3 = tagPtr->spacing3; + spacing3Prio = tagPtr->priority; + } + if ((tagPtr->tabString != NULL) + && (tagPtr->priority > tabPrio)) { + styleValues.tabArrayPtr = tagPtr->tabArrayPtr; + tabPrio = tagPtr->priority; + } + if ((tagPtr->underlineString != NULL) + && (tagPtr->priority > underlinePrio)) { + styleValues.underline = tagPtr->underline; + underlinePrio = tagPtr->priority; + } + if ((tagPtr->wrapMode != NULL) + && (tagPtr->priority > wrapPrio)) { + styleValues.wrapMode = tagPtr->wrapMode; + wrapPrio = tagPtr->priority; + } + } + if (tagPtrs != NULL) { + ckfree((char *) tagPtrs); + } + + /* + * Use an existing style if there's one around that matches. + */ + + hPtr = Tcl_CreateHashEntry(&textPtr->dInfoPtr->styleTable, + (char *) &styleValues, &new); + if (!new) { + stylePtr = (TextStyle *) Tcl_GetHashValue(hPtr); + stylePtr->refCount++; + return stylePtr; + } + + /* + * No existing style matched. Make a new one. + */ + + stylePtr = (TextStyle *) ckalloc(sizeof(TextStyle)); + stylePtr->refCount = 1; + if (styleValues.border != NULL) { + gcValues.foreground = Tk_3DBorderColor(styleValues.border)->pixel; + mask = GCForeground; + if (styleValues.bgStipple != None) { + gcValues.stipple = styleValues.bgStipple; + gcValues.fill_style = FillStippled; + mask |= GCStipple|GCFillStyle; + } + stylePtr->bgGC = Tk_GetGC(textPtr->tkwin, mask, &gcValues); + } else { + stylePtr->bgGC = None; + } + mask = GCForeground|GCFont; + gcValues.foreground = styleValues.fgColor->pixel; + gcValues.font = Tk_FontId(styleValues.tkfont); + if (styleValues.fgStipple != None) { + gcValues.stipple = styleValues.fgStipple; + gcValues.fill_style = FillStippled; + mask |= GCStipple|GCFillStyle; + } + stylePtr->fgGC = Tk_GetGC(textPtr->tkwin, mask, &gcValues); + stylePtr->sValuePtr = (StyleValues *) + Tcl_GetHashKey(&textPtr->dInfoPtr->styleTable, hPtr); + stylePtr->hPtr = hPtr; + Tcl_SetHashValue(hPtr, stylePtr); + return stylePtr; +} + +/* + *---------------------------------------------------------------------- + * + * FreeStyle -- + * + * This procedure is called when a TextStyle structure is no longer + * needed. It decrements the reference count and frees up the + * space for the style structure if the reference count is 0. + * + * Results: + * None. + * + * Side effects: + * The storage and other resources associated with the style + * are freed up if no-one's still using it. + * + *---------------------------------------------------------------------- + */ + +static void +FreeStyle(textPtr, stylePtr) + TkText *textPtr; /* Information about overall widget. */ + register TextStyle *stylePtr; /* Information about style to free. */ + +{ + stylePtr->refCount--; + if (stylePtr->refCount == 0) { + if (stylePtr->bgGC != None) { + Tk_FreeGC(textPtr->display, stylePtr->bgGC); + } + Tk_FreeGC(textPtr->display, stylePtr->fgGC); + Tcl_DeleteHashEntry(stylePtr->hPtr); + ckfree((char *) stylePtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * LayoutDLine -- + * + * This procedure generates a single DLine structure for a display + * line whose leftmost character is given by indexPtr. + * + * Results: + * The return value is a pointer to a DLine structure desribing the + * display line. All fields are filled in and correct except for + * y and nextPtr. + * + * Side effects: + * Storage is allocated for the new DLine. + * + *---------------------------------------------------------------------- + */ + +static DLine * +LayoutDLine(textPtr, indexPtr) + TkText *textPtr; /* Overall information about text widget. */ + TkTextIndex *indexPtr; /* Beginning of display line. May not + * necessarily point to a character segment. */ +{ + register DLine *dlPtr; /* New display line. */ + TkTextSegment *segPtr; /* Current segment in text. */ + TkTextDispChunk *lastChunkPtr; /* Last chunk allocated so far + * for line. */ + TkTextDispChunk *chunkPtr; /* Current chunk. */ + TkTextIndex curIndex; + TkTextDispChunk *breakChunkPtr; /* Chunk containing best word break + * point, if any. */ + TkTextIndex breakIndex; /* Index of first character in + * breakChunkPtr. */ + int breakCharOffset; /* Character within breakChunkPtr just + * to right of best break point. */ + int noCharsYet; /* Non-zero means that no characters + * have been placed on the line yet. */ + int justify; /* How to justify line: taken from + * style for first character in line. */ + int jIndent; /* Additional indentation (beyond + * margins) due to justification. */ + int rMargin; /* Right margin width for line. */ + Tk_Uid wrapMode; /* Wrap mode to use for this line. */ + int x = 0, maxX = 0; /* Initializations needed only to + * stop compiler warnings. */ + int wholeLine; /* Non-zero means this display line + * runs to the end of the text line. */ + int tabIndex; /* Index of the current tab stop. */ + int gotTab; /* Non-zero means the current chunk + * contains a tab. */ + TkTextDispChunk *tabChunkPtr; /* Pointer to the chunk containing + * the previous tab stop. */ + int maxChars; /* Maximum number of characters to + * include in this chunk. */ + TkTextTabArray *tabArrayPtr; /* Tab stops for line; taken from + * style for first character on line. */ + int tabSize; /* Number of pixels consumed by current + * tab stop. */ + TkTextDispChunk *lastCharChunkPtr; /* Pointer to last chunk in display + * lines with numChars > 0. Used to + * drop 0-sized chunks from the end + * of the line. */ + int offset, ascent, descent, code; + StyleValues *sValuePtr; + + /* + * Create and initialize a new DLine structure. + */ + + dlPtr = (DLine *) ckalloc(sizeof(DLine)); + dlPtr->index = *indexPtr; + dlPtr->count = 0; + dlPtr->y = 0; + dlPtr->oldY = -1; + dlPtr->height = 0; + dlPtr->baseline = 0; + dlPtr->chunkPtr = NULL; + dlPtr->nextPtr = NULL; + dlPtr->flags = NEW_LAYOUT; + + /* + * Each iteration of the loop below creates one TkTextDispChunk for + * the new display line. The line will always have at least one + * chunk (for the newline character at the end, if there's nothing + * else available). + */ + + curIndex = *indexPtr; + lastChunkPtr = NULL; + chunkPtr = NULL; + noCharsYet = 1; + breakChunkPtr = NULL; + breakCharOffset = 0; + justify = TK_JUSTIFY_LEFT; + tabIndex = -1; + tabChunkPtr = NULL; + tabArrayPtr = NULL; + rMargin = 0; + wrapMode = tkTextCharUid; + tabSize = 0; + lastCharChunkPtr = NULL; + + /* + * Find the first segment to consider for the line. Can't call + * TkTextIndexToSeg for this because it won't return a segment + * with zero size (such as the insertion cursor's mark). + */ + + for (offset = curIndex.charIndex, segPtr = curIndex.linePtr->segPtr; + (offset > 0) && (offset >= segPtr->size); + offset -= segPtr->size, segPtr = segPtr->nextPtr) { + /* Empty loop body. */ + } + + while (segPtr != NULL) { + if (segPtr->typePtr->layoutProc == NULL) { + segPtr = segPtr->nextPtr; + offset = 0; + continue; + } + if (chunkPtr == NULL) { + chunkPtr = (TkTextDispChunk *) ckalloc(sizeof(TkTextDispChunk)); + chunkPtr->nextPtr = NULL; + } + chunkPtr->stylePtr = GetStyle(textPtr, &curIndex); + + /* + * Save style information such as justification and indentation, + * up until the first character is encountered, then retain that + * information for the rest of the line. + */ + + if (noCharsYet) { + tabArrayPtr = chunkPtr->stylePtr->sValuePtr->tabArrayPtr; + justify = chunkPtr->stylePtr->sValuePtr->justify; + rMargin = chunkPtr->stylePtr->sValuePtr->rMargin; + wrapMode = chunkPtr->stylePtr->sValuePtr->wrapMode; + x = ((curIndex.charIndex == 0) + ? chunkPtr->stylePtr->sValuePtr->lMargin1 + : chunkPtr->stylePtr->sValuePtr->lMargin2); + if (wrapMode == tkTextNoneUid) { + maxX = INT_MAX; + } else { + maxX = textPtr->dInfoPtr->maxX - textPtr->dInfoPtr->x + - rMargin; + if (maxX < x) { + maxX = x; + } + } + } + + /* + * See if there is a tab in the current chunk; if so, only + * layout characters up to (and including) the tab. + */ + + gotTab = 0; + maxChars = segPtr->size - offset; + if (justify == TK_JUSTIFY_LEFT) { + if (segPtr->typePtr == &tkTextCharType) { + char *p; + + for (p = segPtr->body.chars + offset; *p != 0; p++) { + if (*p == '\t') { + maxChars = (p + 1 - segPtr->body.chars) - offset; + gotTab = 1; + break; + } + } + } + } + + chunkPtr->x = x; + code = (*segPtr->typePtr->layoutProc)(textPtr, &curIndex, segPtr, + offset, maxX-tabSize, maxChars, noCharsYet, wrapMode, + chunkPtr); + if (code <= 0) { + FreeStyle(textPtr, chunkPtr->stylePtr); + if (code < 0) { + /* + * This segment doesn't wish to display itself (e.g. most + * marks). + */ + + segPtr = segPtr->nextPtr; + offset = 0; + continue; + } + + /* + * No characters from this segment fit in the window: this + * means we're at the end of the display line. + */ + + if (chunkPtr != NULL) { + ckfree((char *) chunkPtr); + } + break; + } + if (chunkPtr->numChars > 0) { + noCharsYet = 0; + lastCharChunkPtr = chunkPtr; + } + if (lastChunkPtr == NULL) { + dlPtr->chunkPtr = chunkPtr; + } else { + lastChunkPtr->nextPtr = chunkPtr; + } + lastChunkPtr = chunkPtr; + x += chunkPtr->width; + if (chunkPtr->breakIndex > 0) { + breakCharOffset = chunkPtr->breakIndex; + breakIndex = curIndex; + breakChunkPtr = chunkPtr; + } + if (chunkPtr->numChars != maxChars) { + break; + } + + /* + * If we're at a new tab, adjust the layout for all the chunks + * pertaining to the previous tab. Also adjust the amount of + * space left in the line to account for space that will be eaten + * up by the tab. + */ + + if (gotTab) { + if (tabIndex >= 0) { + AdjustForTab(textPtr, tabArrayPtr, tabIndex, tabChunkPtr); + x = chunkPtr->x + chunkPtr->width; + } + tabIndex++; + tabChunkPtr = chunkPtr; + tabSize = SizeOfTab(textPtr, tabArrayPtr, tabIndex, x, maxX); + if (tabSize >= (maxX - x)) { + break; + } + } + curIndex.charIndex += chunkPtr->numChars; + offset += chunkPtr->numChars; + if (offset >= segPtr->size) { + offset = 0; + segPtr = segPtr->nextPtr; + } + chunkPtr = NULL; + } + if (noCharsYet) { + panic("LayoutDLine couldn't place any characters on a line"); + } + wholeLine = (segPtr == NULL); + + /* + * We're at the end of the display line. Throw away everything + * after the most recent word break, if there is one; this may + * potentially require the last chunk to be layed out again. + */ + + if (breakChunkPtr == NULL) { + /* + * This code makes sure that we don't accidentally display + * chunks with no characters at the end of the line (such as + * the insertion cursor). These chunks belong on the next + * line. So, throw away everything after the last chunk that + * has characters in it. + */ + + breakChunkPtr = lastCharChunkPtr; + breakCharOffset = breakChunkPtr->numChars; + } + if ((breakChunkPtr != NULL) && ((lastChunkPtr != breakChunkPtr) + || (breakCharOffset != lastChunkPtr->numChars))) { + while (1) { + chunkPtr = breakChunkPtr->nextPtr; + if (chunkPtr == NULL) { + break; + } + FreeStyle(textPtr, chunkPtr->stylePtr); + breakChunkPtr->nextPtr = chunkPtr->nextPtr; + (*chunkPtr->undisplayProc)(textPtr, chunkPtr); + ckfree((char *) chunkPtr); + } + if (breakCharOffset != breakChunkPtr->numChars) { + (*breakChunkPtr->undisplayProc)(textPtr, breakChunkPtr); + segPtr = TkTextIndexToSeg(&breakIndex, &offset); + (*segPtr->typePtr->layoutProc)(textPtr, &breakIndex, + segPtr, offset, maxX, breakCharOffset, 0, + wrapMode, breakChunkPtr); + } + lastChunkPtr = breakChunkPtr; + wholeLine = 0; + } + + /* + * Make tab adjustments for the last tab stop, if there is one. + */ + + if ((tabIndex >= 0) && (tabChunkPtr != NULL)) { + AdjustForTab(textPtr, tabArrayPtr, tabIndex, tabChunkPtr); + } + + /* + * Make one more pass over the line to recompute various things + * like its height, length, and total number of characters. Also + * modify the x-locations of chunks to reflect justification. + * If we're not wrapping, I'm not sure what is the best way to + * handle left and center justification: should the total length, + * for purposes of justification, be (a) the window width, (b) + * the length of the longest line in the window, or (c) the length + * of the longest line in the text? (c) isn't available, (b) seems + * weird, since it can change with vertical scrolling, so (a) is + * what is implemented below. + */ + + if (wrapMode == tkTextNoneUid) { + maxX = textPtr->dInfoPtr->maxX - textPtr->dInfoPtr->x - rMargin; + } + dlPtr->length = lastChunkPtr->x + lastChunkPtr->width; + if (justify == TK_JUSTIFY_LEFT) { + jIndent = 0; + } else if (justify == TK_JUSTIFY_RIGHT) { + jIndent = maxX - dlPtr->length; + } else { + jIndent = (maxX - dlPtr->length)/2; + } + ascent = descent = 0; + for (chunkPtr = dlPtr->chunkPtr; chunkPtr != NULL; + chunkPtr = chunkPtr->nextPtr) { + chunkPtr->x += jIndent; + dlPtr->count += chunkPtr->numChars; + if (chunkPtr->minAscent > ascent) { + ascent = chunkPtr->minAscent; + } + if (chunkPtr->minDescent > descent) { + descent = chunkPtr->minDescent; + } + if (chunkPtr->minHeight > dlPtr->height) { + dlPtr->height = chunkPtr->minHeight; + } + sValuePtr = chunkPtr->stylePtr->sValuePtr; + if ((sValuePtr->borderWidth > 0) + && (sValuePtr->relief != TK_RELIEF_FLAT)) { + dlPtr->flags |= HAS_3D_BORDER; + } + } + if (dlPtr->height < (ascent + descent)) { + dlPtr->height = ascent + descent; + dlPtr->baseline = ascent; + } else { + dlPtr->baseline = ascent + (dlPtr->height - ascent - descent)/2; + } + sValuePtr = dlPtr->chunkPtr->stylePtr->sValuePtr; + if (dlPtr->index.charIndex == 0) { + dlPtr->spaceAbove = sValuePtr->spacing1; + } else { + dlPtr->spaceAbove = sValuePtr->spacing2 - sValuePtr->spacing2/2; + } + if (wholeLine) { + dlPtr->spaceBelow = sValuePtr->spacing3; + } else { + dlPtr->spaceBelow = sValuePtr->spacing2/2; + } + dlPtr->height += dlPtr->spaceAbove + dlPtr->spaceBelow; + dlPtr->baseline += dlPtr->spaceAbove; + + /* + * Recompute line length: may have changed because of justification. + */ + + dlPtr->length = lastChunkPtr->x + lastChunkPtr->width; + return dlPtr; +} + +/* + *---------------------------------------------------------------------- + * + * UpdateDisplayInfo -- + * + * This procedure is invoked to recompute some or all of the + * DLine structures for a text widget. At the time it is called + * the DLine structures still left in the widget are guaranteed + * to be correct except that (a) the y-coordinates aren't + * necessarily correct, (b) there may be missing structures + * (the DLine structures get removed as soon as they are potentially + * out-of-date), and (c) DLine structures that don't start at the + * beginning of a line may be incorrect if previous information in + * the same line changed size in a way that moved a line boundary + * (DLines for any info that changed will have been deleted, but + * not DLines for unchanged info in the same text line). + * + * Results: + * None. + * + * Side effects: + * Upon return, the DLine information for textPtr correctly reflects + * the positions where characters will be displayed. However, this + * procedure doesn't actually bring the display up-to-date. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateDisplayInfo(textPtr) + TkText *textPtr; /* Text widget to update. */ +{ + register TextDInfo *dInfoPtr = textPtr->dInfoPtr; + register DLine *dlPtr, *prevPtr; + TkTextIndex index; + TkTextLine *lastLinePtr; + int y, maxY, pixelOffset, maxOffset; + + if (!(dInfoPtr->flags & DINFO_OUT_OF_DATE)) { + return; + } + dInfoPtr->flags &= ~DINFO_OUT_OF_DATE; + + /* + * Delete any DLines that are now above the top of the window. + */ + + index = textPtr->topIndex; + dlPtr = FindDLine(dInfoPtr->dLinePtr, &index); + if ((dlPtr != NULL) && (dlPtr != dInfoPtr->dLinePtr)) { + FreeDLines(textPtr, dInfoPtr->dLinePtr, dlPtr, 1); + } + + /* + *-------------------------------------------------------------- + * Scan through the contents of the window from top to bottom, + * recomputing information for lines that are missing. + *-------------------------------------------------------------- + */ + + lastLinePtr = TkBTreeFindLine(textPtr->tree, + TkBTreeNumLines(textPtr->tree)); + dlPtr = dInfoPtr->dLinePtr; + prevPtr = NULL; + y = dInfoPtr->y; + maxY = dInfoPtr->maxY; + while (1) { + register DLine *newPtr; + + if (index.linePtr == lastLinePtr) { + break; + } + + /* + * There are three possibilities right now: + * (a) the next DLine (dlPtr) corresponds exactly to the next + * information we want to display: just use it as-is. + * (b) the next DLine corresponds to a different line, or to + * a segment that will be coming later in the same line: + * leave this DLine alone in the hopes that we'll be able + * to use it later, then create a new DLine in front of + * it. + * (c) the next DLine corresponds to a segment in the line we + * want, but it's a segment that has already been processed + * or will never be processed. Delete the DLine and try + * again. + * + * One other twist on all this. It's possible for 3D borders + * to interact between lines (see DisplayLineBackground) so if + * a line is relayed out and has styles with 3D borders, its + * neighbors have to be redrawn if they have 3D borders too, + * since the interactions could have changed (the neighbors + * don't have to be relayed out, just redrawn). + */ + + if ((dlPtr == NULL) || (dlPtr->index.linePtr != index.linePtr)) { + /* + * Case (b) -- must make new DLine. + */ + + makeNewDLine: + if (tkTextDebug) { + char string[TK_POS_CHARS]; + + /* + * Debugging is enabled, so keep a log of all the lines + * that were re-layed out. The test suite uses this + * information. + */ + + TkTextPrintIndex(&index, string); + Tcl_SetVar2(textPtr->interp, "tk_textRelayout", (char *) NULL, + string, + TCL_GLOBAL_ONLY|TCL_APPEND_VALUE|TCL_LIST_ELEMENT); + } + newPtr = LayoutDLine(textPtr, &index); + if (prevPtr == NULL) { + dInfoPtr->dLinePtr = newPtr; + } else { + prevPtr->nextPtr = newPtr; + if (prevPtr->flags & HAS_3D_BORDER) { + prevPtr->oldY = -1; + } + } + newPtr->nextPtr = dlPtr; + dlPtr = newPtr; + } else { + /* + * DlPtr refers to the line we want. Next check the + * index within the line. + */ + + if (index.charIndex == dlPtr->index.charIndex) { + /* + * Case (a) -- can use existing display line as-is. + */ + + if ((dlPtr->flags & HAS_3D_BORDER) && (prevPtr != NULL) + && (prevPtr->flags & (NEW_LAYOUT))) { + dlPtr->oldY = -1; + } + goto lineOK; + } + if (index.charIndex < dlPtr->index.charIndex) { + goto makeNewDLine; + } + + /* + * Case (c) -- dlPtr is useless. Discard it and start + * again with the next display line. + */ + + newPtr = dlPtr->nextPtr; + FreeDLines(textPtr, dlPtr, newPtr, 0); + dlPtr = newPtr; + if (prevPtr != NULL) { + prevPtr->nextPtr = newPtr; + } else { + dInfoPtr->dLinePtr = newPtr; + } + continue; + } + + /* + * Advance to the start of the next line. + */ + + lineOK: + dlPtr->y = y; + y += dlPtr->height; + TkTextIndexForwChars(&index, dlPtr->count, &index); + prevPtr = dlPtr; + dlPtr = dlPtr->nextPtr; + + /* + * If we switched text lines, delete any DLines left for the + * old text line. + */ + + if (index.linePtr != prevPtr->index.linePtr) { + register DLine *nextPtr; + + nextPtr = dlPtr; + while ((nextPtr != NULL) + && (nextPtr->index.linePtr == prevPtr->index.linePtr)) { + nextPtr = nextPtr->nextPtr; + } + if (nextPtr != dlPtr) { + FreeDLines(textPtr, dlPtr, nextPtr, 0); + prevPtr->nextPtr = nextPtr; + dlPtr = nextPtr; + } + } + + /* + * It's important to have the following check here rather than in + * the while statement for the loop, so that there's always at least + * one DLine generated, regardless of how small the window is. This + * keeps a lot of other code from breaking. + */ + + if (y >= maxY) { + break; + } + } + + /* + * Delete any DLine structures that don't fit on the screen. + */ + + FreeDLines(textPtr, dlPtr, (DLine *) NULL, 1); + + /* + *-------------------------------------------------------------- + * If there is extra space at the bottom of the window (because + * we've hit the end of the text), then bring in more lines at + * the top of the window, if there are any, to fill in the view. + *-------------------------------------------------------------- + */ + + if (y < maxY) { + int lineNum, spaceLeft, charsToCount; + DLine *lowestPtr; + + /* + * Layout an entire text line (potentially > 1 display line), + * then link in as many display lines as fit without moving + * the bottom line out of the window. Repeat this until + * all the extra space has been used up or we've reached the + * beginning of the text. + */ + + spaceLeft = maxY - y; + lineNum = TkBTreeLineIndex(dInfoPtr->dLinePtr->index.linePtr); + charsToCount = dInfoPtr->dLinePtr->index.charIndex; + if (charsToCount == 0) { + charsToCount = INT_MAX; + lineNum--; + } + for ( ; (lineNum >= 0) && (spaceLeft > 0); lineNum--) { + index.linePtr = TkBTreeFindLine(textPtr->tree, lineNum); + index.charIndex = 0; + lowestPtr = NULL; + do { + dlPtr = LayoutDLine(textPtr, &index); + dlPtr->nextPtr = lowestPtr; + lowestPtr = dlPtr; + TkTextIndexForwChars(&index, dlPtr->count, &index); + charsToCount -= dlPtr->count; + } while ((charsToCount > 0) + && (index.linePtr == lowestPtr->index.linePtr)); + + /* + * Scan through the display lines from the bottom one up to + * the top one. + */ + + while (lowestPtr != NULL) { + dlPtr = lowestPtr; + spaceLeft -= dlPtr->height; + if (spaceLeft < 0) { + break; + } + lowestPtr = dlPtr->nextPtr; + dlPtr->nextPtr = dInfoPtr->dLinePtr; + dInfoPtr->dLinePtr = dlPtr; + if (tkTextDebug) { + char string[TK_POS_CHARS]; + + TkTextPrintIndex(&dlPtr->index, string); + Tcl_SetVar2(textPtr->interp, "tk_textRelayout", + (char *) NULL, string, + TCL_GLOBAL_ONLY|TCL_APPEND_VALUE|TCL_LIST_ELEMENT); + } + } + FreeDLines(textPtr, lowestPtr, (DLine *) NULL, 0); + charsToCount = INT_MAX; + } + + /* + * Now we're all done except that the y-coordinates in all the + * DLines are wrong and the top index for the text is wrong. + * Update them. + */ + + textPtr->topIndex = dInfoPtr->dLinePtr->index; + y = dInfoPtr->y; + for (dlPtr = dInfoPtr->dLinePtr; dlPtr != NULL; + dlPtr = dlPtr->nextPtr) { + if (y > dInfoPtr->maxY) { + panic("Added too many new lines in UpdateDisplayInfo"); + } + dlPtr->y = y; + y += dlPtr->height; + } + } + + /* + *-------------------------------------------------------------- + * If the old top or bottom line has scrolled elsewhere on the + * screen, we may not be able to re-use its old contents by + * copying bits (e.g., a beveled edge that was drawn when it was + * at the top or bottom won't be drawn when the line is in the + * middle and its neighbor has a matching background). Similarly, + * if the new top or bottom line came from somewhere else on the + * screen, we may not be able to copy the old bits. + *-------------------------------------------------------------- + */ + + dlPtr = dInfoPtr->dLinePtr; + if ((dlPtr->flags & HAS_3D_BORDER) && !(dlPtr->flags & TOP_LINE)) { + dlPtr->oldY = -1; + } + while (1) { + if ((dlPtr->flags & TOP_LINE) && (dlPtr != dInfoPtr->dLinePtr) + && (dlPtr->flags & HAS_3D_BORDER)) { + dlPtr->oldY = -1; + } + if ((dlPtr->flags & BOTTOM_LINE) && (dlPtr->nextPtr != NULL) + && (dlPtr->flags & HAS_3D_BORDER)) { + dlPtr->oldY = -1; + } + if (dlPtr->nextPtr == NULL) { + if ((dlPtr->flags & HAS_3D_BORDER) + && !(dlPtr->flags & BOTTOM_LINE)) { + dlPtr->oldY = -1; + } + dlPtr->flags &= ~TOP_LINE; + dlPtr->flags |= BOTTOM_LINE; + break; + } + dlPtr->flags &= ~(TOP_LINE|BOTTOM_LINE); + dlPtr = dlPtr->nextPtr; + } + dInfoPtr->dLinePtr->flags |= TOP_LINE; + + /* + * Arrange for scrollbars to be updated. + */ + + textPtr->flags |= UPDATE_SCROLLBARS; + + /* + *-------------------------------------------------------------- + * Deal with horizontal scrolling: + * 1. If there's empty space to the right of the longest line, + * shift the screen to the right to fill in the empty space. + * 2. If the desired horizontal scroll position has changed, + * force a full redisplay of all the lines in the widget. + * 3. If the wrap mode isn't "none" then re-scroll to the base + * position. + *-------------------------------------------------------------- + */ + + dInfoPtr->maxLength = 0; + for (dlPtr = dInfoPtr->dLinePtr; dlPtr != NULL; + dlPtr = dlPtr->nextPtr) { + if (dlPtr->length > dInfoPtr->maxLength) { + dInfoPtr->maxLength = dlPtr->length; + } + } + maxOffset = (dInfoPtr->maxLength - (dInfoPtr->maxX - dInfoPtr->x) + + textPtr->charWidth - 1)/textPtr->charWidth; + if (dInfoPtr->newCharOffset > maxOffset) { + dInfoPtr->newCharOffset = maxOffset; + } + if (dInfoPtr->newCharOffset < 0) { + dInfoPtr->newCharOffset = 0; + } + pixelOffset = dInfoPtr->newCharOffset * textPtr->charWidth; + if (pixelOffset != dInfoPtr->curPixelOffset) { + dInfoPtr->curPixelOffset = pixelOffset; + for (dlPtr = dInfoPtr->dLinePtr; dlPtr != NULL; + dlPtr = dlPtr->nextPtr) { + dlPtr->oldY = -1; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * FreeDLines -- + * + * This procedure is called to free up all of the resources + * associated with one or more DLine structures. + * + * Results: + * None. + * + * Side effects: + * Memory gets freed and various other resources are released. + * + *---------------------------------------------------------------------- + */ + +static void +FreeDLines(textPtr, firstPtr, lastPtr, unlink) + TkText *textPtr; /* Information about overall text + * widget. */ + register DLine *firstPtr; /* Pointer to first DLine to free up. */ + DLine *lastPtr; /* Pointer to DLine just after last + * one to free (NULL means everything + * starting with firstPtr). */ + int unlink; /* 1 means DLines are currently linked + * into the list rooted at + * textPtr->dInfoPtr->dLinePtr and + * they have to be unlinked. 0 means + * just free without unlinking. */ +{ + register TkTextDispChunk *chunkPtr, *nextChunkPtr; + register DLine *nextDLinePtr; + + if (unlink) { + if (textPtr->dInfoPtr->dLinePtr == firstPtr) { + textPtr->dInfoPtr->dLinePtr = lastPtr; + } else { + register DLine *prevPtr; + for (prevPtr = textPtr->dInfoPtr->dLinePtr; + prevPtr->nextPtr != firstPtr; prevPtr = prevPtr->nextPtr) { + /* Empty loop body. */ + } + prevPtr->nextPtr = lastPtr; + } + } + while (firstPtr != lastPtr) { + nextDLinePtr = firstPtr->nextPtr; + for (chunkPtr = firstPtr->chunkPtr; chunkPtr != NULL; + chunkPtr = nextChunkPtr) { + if (chunkPtr->undisplayProc != NULL) { + (*chunkPtr->undisplayProc)(textPtr, chunkPtr); + } + FreeStyle(textPtr, chunkPtr->stylePtr); + nextChunkPtr = chunkPtr->nextPtr; + ckfree((char *) chunkPtr); + } + ckfree((char *) firstPtr); + firstPtr = nextDLinePtr; + } + textPtr->dInfoPtr->dLinesInvalidated = 1; +} + +/* + *---------------------------------------------------------------------- + * + * DisplayDLine -- + * + * This procedure is invoked to draw a single line on the + * screen. + * + * Results: + * None. + * + * Side effects: + * The line given by dlPtr is drawn at its correct position in + * textPtr's window. Note that this is one *display* line, not + * one *text* line. + * + *---------------------------------------------------------------------- + */ + +static void +DisplayDLine(textPtr, dlPtr, prevPtr, pixmap) + TkText *textPtr; /* Text widget in which to draw line. */ + register DLine *dlPtr; /* Information about line to draw. */ + DLine *prevPtr; /* Line just before one to draw, or NULL + * if dlPtr is the top line. */ + Pixmap pixmap; /* Pixmap to use for double-buffering. + * Caller must make sure it's large enough + * to hold line. */ +{ + register TkTextDispChunk *chunkPtr; + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + Display *display; + int height, x; + + /* + * First, clear the area of the line to the background color for the + * text widget. + */ + + display = Tk_Display(textPtr->tkwin); + Tk_Fill3DRectangle(textPtr->tkwin, pixmap, textPtr->border, 0, 0, + Tk_Width(textPtr->tkwin), dlPtr->height, 0, TK_RELIEF_FLAT); + + /* + * Next, draw background information for the whole line. + */ + + DisplayLineBackground(textPtr, dlPtr, prevPtr, pixmap); + + /* + * Make another pass through all of the chunks to redraw the + * insertion cursor, if it is visible on this line. Must do + * it here rather than in the foreground pass below because + * otherwise a wide insertion cursor will obscure the character + * to its left. + */ + + if (textPtr->state == tkNormalUid) { + for (chunkPtr = dlPtr->chunkPtr; (chunkPtr != NULL); + chunkPtr = chunkPtr->nextPtr) { + x = chunkPtr->x + dInfoPtr->x - dInfoPtr->curPixelOffset; + if (chunkPtr->displayProc == TkTextInsertDisplayProc) { + (*chunkPtr->displayProc)(chunkPtr, x, dlPtr->spaceAbove, + dlPtr->height - dlPtr->spaceAbove - dlPtr->spaceBelow, + dlPtr->baseline - dlPtr->spaceAbove, display, pixmap, + dlPtr->y + dlPtr->spaceAbove); + } + } + } + + /* + * Make yet another pass through all of the chunks to redraw all of + * foreground information. Note: we have to call the displayProc + * even for chunks that are off-screen. This is needed, for + * example, so that embedded windows can be unmapped in this case. + * Conve + */ + + for (chunkPtr = dlPtr->chunkPtr; (chunkPtr != NULL); + chunkPtr = chunkPtr->nextPtr) { + if (chunkPtr->displayProc == TkTextInsertDisplayProc) { + /* + * Already displayed the insertion cursor above. Don't + * do it again here. + */ + + continue; + } + x = chunkPtr->x + dInfoPtr->x - dInfoPtr->curPixelOffset; + if ((x + chunkPtr->width <= 0) || (x >= dInfoPtr->maxX)) { + /* + * Note: we have to call the displayProc even for chunks + * that are off-screen. This is needed, for example, so + * that embedded windows can be unmapped in this case. + * Display the chunk at a coordinate that can be clearly + * identified by the displayProc as being off-screen to + * the left (the displayProc may not be able to tell if + * something is off to the right). + */ + + (*chunkPtr->displayProc)(chunkPtr, -chunkPtr->width, + dlPtr->spaceAbove, + dlPtr->height - dlPtr->spaceAbove - dlPtr->spaceBelow, + dlPtr->baseline - dlPtr->spaceAbove, display, pixmap, + dlPtr->y + dlPtr->spaceAbove); + } else { + (*chunkPtr->displayProc)(chunkPtr, x, dlPtr->spaceAbove, + dlPtr->height - dlPtr->spaceAbove - dlPtr->spaceBelow, + dlPtr->baseline - dlPtr->spaceAbove, display, pixmap, + dlPtr->y + dlPtr->spaceAbove); + } + if (dInfoPtr->dLinesInvalidated) { + return; + } + } + + /* + * Copy the pixmap onto the screen. If this is the last line on + * the screen then copy a piece of the line, so that it doesn't + * overflow into the border area. Another special trick: copy the + * padding area to the left of the line; this is because the + * insertion cursor sometimes overflows onto that area and we want + * to get as much of the cursor as possible. + */ + + height = dlPtr->height; + if ((height + dlPtr->y) > dInfoPtr->maxY) { + height = dInfoPtr->maxY - dlPtr->y; + } + XCopyArea(display, pixmap, Tk_WindowId(textPtr->tkwin), dInfoPtr->copyGC, + dInfoPtr->x, 0, (unsigned) (dInfoPtr->maxX - dInfoPtr->x), + (unsigned) height, dInfoPtr->x, dlPtr->y); + linesRedrawn++; +} + +/* + *-------------------------------------------------------------- + * + * DisplayLineBackground -- + * + * This procedure is called to fill in the background for + * a display line. It draws 3D borders cleverly so that + * adjacent chunks with the same style (whether on the same + * line or different lines) have a single 3D border around + * the whole region. + * + * Results: + * There is no return value. Pixmap is filled in with background + * information for dlPtr. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static void +DisplayLineBackground(textPtr, dlPtr, prevPtr, pixmap) + TkText *textPtr; /* Text widget containing line. */ + register DLine *dlPtr; /* Information about line to draw. */ + DLine *prevPtr; /* Line just above dlPtr, or NULL if dlPtr + * is the top-most line in the window. */ + Pixmap pixmap; /* Pixmap to use for double-buffering. + * Caller must make sure it's large enough + * to hold line. Caller must also have + * filled it with the background color for + * the widget. */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + TkTextDispChunk *chunkPtr; /* Pointer to chunk in the current line. */ + TkTextDispChunk *chunkPtr2; /* Pointer to chunk in the line above or + * below the current one. NULL if we're to + * the left of or to the right of the chunks + * in the line. */ + TkTextDispChunk *nextPtr2; /* Next chunk after chunkPtr2 (it's not the + * same as chunkPtr2->nextPtr in the case + * where chunkPtr2 is NULL because the line + * is indented). */ + int leftX; /* The left edge of the region we're + * currently working on. */ + int leftXIn; /* 1 means beveled edge at leftX slopes right + * as it goes down, 0 means it slopes left + * as it goes down. */ + int rightX; /* Right edge of chunkPtr. */ + int rightX2; /* Right edge of chunkPtr2. */ + int matchLeft; /* Does the style of this line match that + * of its neighbor just to the left of + * the current x coordinate? */ + int matchRight; /* Does line's style match its neighbor + * just to the right of the current x-coord? */ + int minX, maxX, xOffset; + StyleValues *sValuePtr; + Display *display; + + /* + * Pass 1: scan through dlPtr from left to right. For each range of + * chunks with the same style, draw the main background for the style + * plus the vertical parts of the 3D borders (the left and right + * edges). + */ + + display = Tk_Display(textPtr->tkwin); + minX = dInfoPtr->curPixelOffset; + xOffset = dInfoPtr->x - minX; + maxX = minX + dInfoPtr->maxX - dInfoPtr->x; + chunkPtr = dlPtr->chunkPtr; + + /* + * Note A: in the following statement, and a few others later in + * this file marked with "See Note A above", the right side of the + * assignment was replaced with 0 on 6/18/97. This has the effect + * of highlighting the empty space to the left of a line whenever + * the leftmost character of the line is highlighted. This way, + * multi-line highlights always line up along their left edges. + * However, this may look funny in the case where a single word is + * highlighted. To undo the change, replace "leftX = 0" with "leftX + * = chunkPtr->x" and "rightX2 = 0" with "rightX2 = nextPtr2->x" + * here and at all the marked points below. This restores the old + * behavior where empty space to the left of a line is not + * highlighted, leaving a ragged left edge for multi-line + * highlights. + */ + + leftX = 0; + for (; leftX < maxX; chunkPtr = chunkPtr->nextPtr) { + if ((chunkPtr->nextPtr != NULL) + && SAME_BACKGROUND(chunkPtr->nextPtr->stylePtr, + chunkPtr->stylePtr)) { + continue; + } + sValuePtr = chunkPtr->stylePtr->sValuePtr; + rightX = chunkPtr->x + chunkPtr->width; + if ((chunkPtr->nextPtr == NULL) && (rightX < maxX)) { + rightX = maxX; + } + if (chunkPtr->stylePtr->bgGC != None) { + XFillRectangle(display, pixmap, chunkPtr->stylePtr->bgGC, + leftX + xOffset, 0, (unsigned int) (rightX - leftX), + (unsigned int) dlPtr->height); + if (sValuePtr->relief != TK_RELIEF_FLAT) { + Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border, + leftX + xOffset, 0, sValuePtr->borderWidth, + dlPtr->height, 1, sValuePtr->relief); + Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border, + rightX - sValuePtr->borderWidth + xOffset, + 0, sValuePtr->borderWidth, dlPtr->height, 0, + sValuePtr->relief); + } + } + leftX = rightX; + } + + /* + * Pass 2: draw the horizontal bevels along the top of the line. To + * do this, scan through dlPtr from left to right while simultaneously + * scanning through the line just above dlPtr. ChunkPtr2 and nextPtr2 + * refer to two adjacent chunks in the line above. + */ + + chunkPtr = dlPtr->chunkPtr; + leftX = 0; /* See Note A above. */ + leftXIn = 1; + rightX = chunkPtr->x + chunkPtr->width; + if ((chunkPtr->nextPtr == NULL) && (rightX < maxX)) { + rightX = maxX; + } + chunkPtr2 = NULL; + if (prevPtr != NULL) { + /* + * Find the chunk in the previous line that covers leftX. + */ + + nextPtr2 = prevPtr->chunkPtr; + rightX2 = 0; /* See Note A above. */ + while (rightX2 <= leftX) { + chunkPtr2 = nextPtr2; + if (chunkPtr2 == NULL) { + break; + } + nextPtr2 = chunkPtr2->nextPtr; + rightX2 = chunkPtr2->x + chunkPtr2->width; + if (nextPtr2 == NULL) { + rightX2 = INT_MAX; + } + } + } else { + nextPtr2 = NULL; + rightX2 = INT_MAX; + } + + while (leftX < maxX) { + matchLeft = (chunkPtr2 != NULL) + && SAME_BACKGROUND(chunkPtr2->stylePtr, chunkPtr->stylePtr); + sValuePtr = chunkPtr->stylePtr->sValuePtr; + if (rightX <= rightX2) { + /* + * The chunk in our line is about to end. If its style + * changes then draw the bevel for the current style. + */ + + if ((chunkPtr->nextPtr == NULL) + || !SAME_BACKGROUND(chunkPtr->stylePtr, + chunkPtr->nextPtr->stylePtr)) { + if (!matchLeft && (sValuePtr->relief != TK_RELIEF_FLAT)) { + Tk_3DHorizontalBevel(textPtr->tkwin, pixmap, + sValuePtr->border, leftX + xOffset, 0, + rightX - leftX, sValuePtr->borderWidth, leftXIn, + 1, 1, sValuePtr->relief); + } + leftX = rightX; + leftXIn = 1; + + /* + * If the chunk in the line above is also ending at + * the same point then advance to the next chunk in + * that line. + */ + + if ((rightX == rightX2) && (chunkPtr2 != NULL)) { + goto nextChunk2; + } + } + chunkPtr = chunkPtr->nextPtr; + if (chunkPtr == NULL) { + break; + } + rightX = chunkPtr->x + chunkPtr->width; + if ((chunkPtr->nextPtr == NULL) && (rightX < maxX)) { + rightX = maxX; + } + continue; + } + + /* + * The chunk in the line above is ending at an x-position where + * there is no change in the style of the current line. If the + * style above matches the current line on one side of the change + * but not on the other, we have to draw an L-shaped piece of + * bevel. + */ + + matchRight = (nextPtr2 != NULL) + && SAME_BACKGROUND(nextPtr2->stylePtr, chunkPtr->stylePtr); + if (matchLeft && !matchRight) { + if (sValuePtr->relief != TK_RELIEF_FLAT) { + Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border, + rightX2 - sValuePtr->borderWidth + xOffset, 0, + sValuePtr->borderWidth, sValuePtr->borderWidth, 0, + sValuePtr->relief); + } + leftX = rightX2 - sValuePtr->borderWidth; + leftXIn = 0; + } else if (!matchLeft && matchRight + && (sValuePtr->relief != TK_RELIEF_FLAT)) { + Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border, + rightX2 + xOffset, 0, sValuePtr->borderWidth, + sValuePtr->borderWidth, 1, sValuePtr->relief); + Tk_3DHorizontalBevel(textPtr->tkwin, pixmap, sValuePtr->border, + leftX + xOffset, 0, rightX2 + sValuePtr->borderWidth -leftX, + sValuePtr->borderWidth, leftXIn, 0, 1, + sValuePtr->relief); + } + + nextChunk2: + chunkPtr2 = nextPtr2; + if (chunkPtr2 == NULL) { + rightX2 = INT_MAX; + } else { + nextPtr2 = chunkPtr2->nextPtr; + rightX2 = chunkPtr2->x + chunkPtr2->width; + if (nextPtr2 == NULL) { + rightX2 = INT_MAX; + } + } + } + /* + * Pass 3: draw the horizontal bevels along the bottom of the line. + * This uses the same approach as pass 2. + */ + + chunkPtr = dlPtr->chunkPtr; + leftX = 0; /* See Note A above. */ + leftXIn = 0; + rightX = chunkPtr->x + chunkPtr->width; + if ((chunkPtr->nextPtr == NULL) && (rightX < maxX)) { + rightX = maxX; + } + chunkPtr2 = NULL; + if (dlPtr->nextPtr != NULL) { + /* + * Find the chunk in the previous line that covers leftX. + */ + + nextPtr2 = dlPtr->nextPtr->chunkPtr; + rightX2 = 0; /* See Note A above. */ + while (rightX2 <= leftX) { + chunkPtr2 = nextPtr2; + if (chunkPtr2 == NULL) { + break; + } + nextPtr2 = chunkPtr2->nextPtr; + rightX2 = chunkPtr2->x + chunkPtr2->width; + if (nextPtr2 == NULL) { + rightX2 = INT_MAX; + } + } + } else { + nextPtr2 = NULL; + rightX2 = INT_MAX; + } + + while (leftX < maxX) { + matchLeft = (chunkPtr2 != NULL) + && SAME_BACKGROUND(chunkPtr2->stylePtr, chunkPtr->stylePtr); + sValuePtr = chunkPtr->stylePtr->sValuePtr; + if (rightX <= rightX2) { + if ((chunkPtr->nextPtr == NULL) + || !SAME_BACKGROUND(chunkPtr->stylePtr, + chunkPtr->nextPtr->stylePtr)) { + if (!matchLeft && (sValuePtr->relief != TK_RELIEF_FLAT)) { + Tk_3DHorizontalBevel(textPtr->tkwin, pixmap, + sValuePtr->border, leftX + xOffset, + dlPtr->height - sValuePtr->borderWidth, + rightX - leftX, sValuePtr->borderWidth, leftXIn, + 0, 0, sValuePtr->relief); + } + leftX = rightX; + leftXIn = 0; + if ((rightX == rightX2) && (chunkPtr2 != NULL)) { + goto nextChunk2b; + } + } + chunkPtr = chunkPtr->nextPtr; + if (chunkPtr == NULL) { + break; + } + rightX = chunkPtr->x + chunkPtr->width; + if ((chunkPtr->nextPtr == NULL) && (rightX < maxX)) { + rightX = maxX; + } + continue; + } + + matchRight = (nextPtr2 != NULL) + && SAME_BACKGROUND(nextPtr2->stylePtr, chunkPtr->stylePtr); + if (matchLeft && !matchRight) { + if (sValuePtr->relief != TK_RELIEF_FLAT) { + Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border, + rightX2 - sValuePtr->borderWidth + xOffset, + dlPtr->height - sValuePtr->borderWidth, + sValuePtr->borderWidth, sValuePtr->borderWidth, 0, + sValuePtr->relief); + } + leftX = rightX2 - sValuePtr->borderWidth; + leftXIn = 1; + } else if (!matchLeft && matchRight + && (sValuePtr->relief != TK_RELIEF_FLAT)) { + Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border, + rightX2 + xOffset, dlPtr->height - sValuePtr->borderWidth, + sValuePtr->borderWidth, sValuePtr->borderWidth, + 1, sValuePtr->relief); + Tk_3DHorizontalBevel(textPtr->tkwin, pixmap, sValuePtr->border, + leftX + xOffset, dlPtr->height - sValuePtr->borderWidth, + rightX2 + sValuePtr->borderWidth - leftX, + sValuePtr->borderWidth, leftXIn, 1, 0, sValuePtr->relief); + } + + nextChunk2b: + chunkPtr2 = nextPtr2; + if (chunkPtr2 == NULL) { + rightX2 = INT_MAX; + } else { + nextPtr2 = chunkPtr2->nextPtr; + rightX2 = chunkPtr2->x + chunkPtr2->width; + if (nextPtr2 == NULL) { + rightX2 = INT_MAX; + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * DisplayText -- + * + * This procedure is invoked as a when-idle handler to update the + * display. It only redisplays the parts of the text widget that + * are out of date. + * + * Results: + * None. + * + * Side effects: + * Information is redrawn on the screen. + * + *---------------------------------------------------------------------- + */ + +static void +DisplayText(clientData) + ClientData clientData; /* Information about widget. */ +{ + register TkText *textPtr = (TkText *) clientData; + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + Tk_Window tkwin; + register DLine *dlPtr; + DLine *prevPtr; + Pixmap pixmap; + int maxHeight, borders; + int bottomY = 0; /* Initialization needed only to stop + * compiler warnings. */ + Tcl_Interp *interp; + + if (textPtr->tkwin == NULL) { + + /* + * The widget has been deleted. Don't do anything. + */ + + return; + } + + interp = textPtr->interp; + Tcl_Preserve((ClientData) interp); + + if (tkTextDebug) { + Tcl_SetVar2(interp, "tk_textRelayout", (char *) NULL, "", + TCL_GLOBAL_ONLY); + } + + if (textPtr->tkwin == NULL) { + + /* + * The widget has been deleted. Don't do anything. + */ + + goto end; + } + + if (!Tk_IsMapped(textPtr->tkwin) || (dInfoPtr->maxX <= dInfoPtr->x) + || (dInfoPtr->maxY <= dInfoPtr->y)) { + UpdateDisplayInfo(textPtr); + dInfoPtr->flags &= ~REDRAW_PENDING; + goto doScrollbars; + } + numRedisplays++; + if (tkTextDebug) { + Tcl_SetVar2(interp, "tk_textRedraw", (char *) NULL, "", + TCL_GLOBAL_ONLY); + } + + if (textPtr->tkwin == NULL) { + + /* + * The widget has been deleted. Don't do anything. + */ + + goto end; + } + + /* + * Choose a new current item if that is needed (this could cause + * event handlers to be invoked, hence the preserve/release calls + * and the loop, since the handlers could conceivably necessitate + * yet another current item calculation). The tkwin check is because + * the whole window could go away in the Tcl_Release call. + */ + + while (dInfoPtr->flags & REPICK_NEEDED) { + Tcl_Preserve((ClientData) textPtr); + dInfoPtr->flags &= ~REPICK_NEEDED; + TkTextPickCurrent(textPtr, &textPtr->pickEvent); + tkwin = textPtr->tkwin; + Tcl_Release((ClientData) textPtr); + if (tkwin == NULL) { + goto end; + } + } + + /* + * First recompute what's supposed to be displayed. + */ + + UpdateDisplayInfo(textPtr); + dInfoPtr->dLinesInvalidated = 0; + + /* + * See if it's possible to bring some parts of the screen up-to-date + * by scrolling (copying from other parts of the screen). + */ + + for (dlPtr = dInfoPtr->dLinePtr; dlPtr != NULL; dlPtr = dlPtr->nextPtr) { + register DLine *dlPtr2; + int offset, height, y, oldY; + TkRegion damageRgn; + + if ((dlPtr->oldY == -1) || (dlPtr->y == dlPtr->oldY) + || ((dlPtr->oldY + dlPtr->height) > dInfoPtr->maxY)) { + continue; + } + + /* + * This line is already drawn somewhere in the window so it only + * needs to be copied to its new location. See if there's a group + * of lines that can all be copied together. + */ + + offset = dlPtr->y - dlPtr->oldY; + height = dlPtr->height; + y = dlPtr->y; + for (dlPtr2 = dlPtr->nextPtr; dlPtr2 != NULL; + dlPtr2 = dlPtr2->nextPtr) { + if ((dlPtr2->oldY == -1) + || ((dlPtr2->oldY + offset) != dlPtr2->y) + || ((dlPtr2->oldY + dlPtr2->height) > dInfoPtr->maxY)) { + break; + } + height += dlPtr2->height; + } + + /* + * Reduce the height of the area being copied if necessary to + * avoid overwriting the border area. + */ + + if ((y + height) > dInfoPtr->maxY) { + height = dInfoPtr->maxY -y; + } + oldY = dlPtr->oldY; + + /* + * Update the lines we are going to scroll to show that they + * have been copied. + */ + + while (1) { + dlPtr->oldY = dlPtr->y; + if (dlPtr->nextPtr == dlPtr2) { + break; + } + dlPtr = dlPtr->nextPtr; + } + + /* + * Scan through the lines following the copied ones to see if + * we are going to overwrite them with the copy operation. + * If so, mark them for redisplay. + */ + + for ( ; dlPtr2 != NULL; dlPtr2 = dlPtr2->nextPtr) { + if ((dlPtr2->oldY != -1) + && ((dlPtr2->oldY + dlPtr2->height) > y) + && (dlPtr2->oldY < (y + height))) { + dlPtr2->oldY = -1; + } + } + + /* + * Now scroll the lines. This may generate damage which we + * handle by calling TextInvalidateRegion to mark the display + * blocks as stale. + */ + + damageRgn = TkCreateRegion(); + if (TkScrollWindow(textPtr->tkwin, dInfoPtr->scrollGC, + dInfoPtr->x, oldY, + (dInfoPtr->maxX - dInfoPtr->x), height, + 0, y - oldY, damageRgn)) { + TextInvalidateRegion(textPtr, damageRgn); + } + numCopies++; + TkDestroyRegion(damageRgn); + } + + /* + * Clear the REDRAW_PENDING flag here. This is actually pretty + * tricky. We want to wait until *after* doing the scrolling, + * since that could generate more areas to redraw and don't + * want to reschedule a redisplay for them. On the other hand, + * we can't wait until after all the redisplaying, because the + * act of redisplaying could actually generate more redisplays + * (e.g. in the case of a nested window with event bindings triggered + * by redisplay). + */ + + dInfoPtr->flags &= ~REDRAW_PENDING; + + /* + * Redraw the borders if that's needed. + */ + + if (dInfoPtr->flags & REDRAW_BORDERS) { + if (tkTextDebug) { + Tcl_SetVar2(interp, "tk_textRedraw", (char *) NULL, "borders", + TCL_GLOBAL_ONLY|TCL_APPEND_VALUE|TCL_LIST_ELEMENT); + } + + if (textPtr->tkwin == NULL) { + + /* + * The widget has been deleted. Don't do anything. + */ + + goto end; + } + + Tk_Draw3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin), + textPtr->border, textPtr->highlightWidth, + textPtr->highlightWidth, + Tk_Width(textPtr->tkwin) - 2*textPtr->highlightWidth, + Tk_Height(textPtr->tkwin) - 2*textPtr->highlightWidth, + textPtr->borderWidth, textPtr->relief); + if (textPtr->highlightWidth != 0) { + GC gc; + + if (textPtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(textPtr->highlightColorPtr, + Tk_WindowId(textPtr->tkwin)); + } else { + gc = Tk_GCForColor(textPtr->highlightBgColorPtr, + Tk_WindowId(textPtr->tkwin)); + } + Tk_DrawFocusHighlight(textPtr->tkwin, gc, textPtr->highlightWidth, + Tk_WindowId(textPtr->tkwin)); + } + borders = textPtr->borderWidth + textPtr->highlightWidth; + if (textPtr->padY > 0) { + Tk_Fill3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin), + textPtr->border, borders, borders, + Tk_Width(textPtr->tkwin) - 2*borders, textPtr->padY, + 0, TK_RELIEF_FLAT); + Tk_Fill3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin), + textPtr->border, borders, + Tk_Height(textPtr->tkwin) - borders - textPtr->padY, + Tk_Width(textPtr->tkwin) - 2*borders, + textPtr->padY, 0, TK_RELIEF_FLAT); + } + if (textPtr->padX > 0) { + Tk_Fill3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin), + textPtr->border, borders, borders + textPtr->padY, + textPtr->padX, + Tk_Height(textPtr->tkwin) - 2*borders -2*textPtr->padY, + 0, TK_RELIEF_FLAT); + Tk_Fill3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin), + textPtr->border, + Tk_Width(textPtr->tkwin) - borders - textPtr->padX, + borders + textPtr->padY, textPtr->padX, + Tk_Height(textPtr->tkwin) - 2*borders -2*textPtr->padY, + 0, TK_RELIEF_FLAT); + } + dInfoPtr->flags &= ~REDRAW_BORDERS; + } + + /* + * Now we have to redraw the lines that couldn't be updated by + * scrolling. First, compute the height of the largest line and + * allocate an off-screen pixmap to use for double-buffered + * displays. + */ + + maxHeight = -1; + for (dlPtr = dInfoPtr->dLinePtr; dlPtr != NULL; + dlPtr = dlPtr->nextPtr) { + if ((dlPtr->height > maxHeight) && (dlPtr->oldY != dlPtr->y)) { + maxHeight = dlPtr->height; + } + bottomY = dlPtr->y + dlPtr->height; + } + if (maxHeight > dInfoPtr->maxY) { + maxHeight = dInfoPtr->maxY; + } + if (maxHeight > 0) { + pixmap = Tk_GetPixmap(Tk_Display(textPtr->tkwin), + Tk_WindowId(textPtr->tkwin), Tk_Width(textPtr->tkwin), + maxHeight, Tk_Depth(textPtr->tkwin)); + for (prevPtr = NULL, dlPtr = textPtr->dInfoPtr->dLinePtr; + (dlPtr != NULL) && (dlPtr->y < dInfoPtr->maxY); + prevPtr = dlPtr, dlPtr = dlPtr->nextPtr) { + if (dlPtr->oldY != dlPtr->y) { + if (tkTextDebug) { + char string[TK_POS_CHARS]; + TkTextPrintIndex(&dlPtr->index, string); + Tcl_SetVar2(textPtr->interp, "tk_textRedraw", + (char *) NULL, string, + TCL_GLOBAL_ONLY|TCL_APPEND_VALUE|TCL_LIST_ELEMENT); + } + DisplayDLine(textPtr, dlPtr, prevPtr, pixmap); + if (dInfoPtr->dLinesInvalidated) { + Tk_FreePixmap(Tk_Display(textPtr->tkwin), pixmap); + return; + } + dlPtr->oldY = dlPtr->y; + dlPtr->flags &= ~NEW_LAYOUT; + } + } + Tk_FreePixmap(Tk_Display(textPtr->tkwin), pixmap); + } + + /* + * See if we need to refresh the part of the window below the + * last line of text (if there is any such area). Refresh the + * padding area on the left too, since the insertion cursor might + * have been displayed there previously). + */ + + if (dInfoPtr->topOfEof > dInfoPtr->maxY) { + dInfoPtr->topOfEof = dInfoPtr->maxY; + } + if (bottomY < dInfoPtr->topOfEof) { + if (tkTextDebug) { + Tcl_SetVar2(textPtr->interp, "tk_textRedraw", + (char *) NULL, "eof", + TCL_GLOBAL_ONLY|TCL_APPEND_VALUE|TCL_LIST_ELEMENT); + } + + if (textPtr->tkwin == NULL) { + + /* + * The widget has been deleted. Don't do anything. + */ + + goto end; + } + + Tk_Fill3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin), + textPtr->border, dInfoPtr->x - textPtr->padX, bottomY, + dInfoPtr->maxX - (dInfoPtr->x - textPtr->padX), + dInfoPtr->topOfEof-bottomY, 0, TK_RELIEF_FLAT); + } + dInfoPtr->topOfEof = bottomY; + + doScrollbars: + + /* + * Update the vertical scrollbar, if there is one. Note: it's + * important to clear REDRAW_PENDING here, just in case the + * scroll procedure does something that requires redisplay. + */ + + if (textPtr->flags & UPDATE_SCROLLBARS) { + textPtr->flags &= ~UPDATE_SCROLLBARS; + if (textPtr->yScrollCmd != NULL) { + GetYView(textPtr->interp, textPtr, 1); + } + + if (textPtr->tkwin == NULL) { + + /* + * The widget has been deleted. Don't do anything. + */ + + goto end; + } + + /* + * Update the horizontal scrollbar, if any. + */ + + if (textPtr->xScrollCmd != NULL) { + GetXView(textPtr->interp, textPtr, 1); + } + } + +end: + Tcl_Release((ClientData) interp); +} + +/* + *---------------------------------------------------------------------- + * + * TkTextEventuallyRepick -- + * + * This procedure is invoked whenever something happens that + * could change the current character or the tags associated + * with it. + * + * Results: + * None. + * + * Side effects: + * A repick is scheduled as an idle handler. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +void +TkTextEventuallyRepick(textPtr) + TkText *textPtr; /* Widget record for text widget. */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + + dInfoPtr->flags |= REPICK_NEEDED; + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + dInfoPtr->flags |= REDRAW_PENDING; + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkTextRedrawRegion -- + * + * This procedure is invoked to schedule a redisplay for a given + * region of a text widget. The redisplay itself may not occur + * immediately: it's scheduled as a when-idle handler. + * + * Results: + * None. + * + * Side effects: + * Information will eventually be redrawn on the screen. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +void +TkTextRedrawRegion(textPtr, x, y, width, height) + TkText *textPtr; /* Widget record for text widget. */ + int x, y; /* Coordinates of upper-left corner of area + * to be redrawn, in pixels relative to + * textPtr's window. */ + int width, height; /* Width and height of area to be redrawn. */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + TkRegion damageRgn = TkCreateRegion(); + XRectangle rect; + + rect.x = x; + rect.y = y; + rect.width = width; + rect.height = height; + TkUnionRectWithRegion(&rect, damageRgn, damageRgn); + + TextInvalidateRegion(textPtr, damageRgn); + + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + dInfoPtr->flags |= REDRAW_PENDING; + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } + TkDestroyRegion(damageRgn); +} + +/* + *---------------------------------------------------------------------- + * + * TextInvalidateRegion -- + * + * Mark a region of text as invalid. + * + * Results: + * None. + * + * Side effects: + * Updates the display information for the text widget. + * + *---------------------------------------------------------------------- + */ + +static void +TextInvalidateRegion(textPtr, region) + TkText *textPtr; /* Widget record for text widget. */ + TkRegion region; /* Region of area to redraw. */ +{ + register DLine *dlPtr; + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + int maxY, inset; + XRectangle rect; + + /* + * Find all lines that overlap the given region and mark them for + * redisplay. + */ + + TkClipBox(region, &rect); + maxY = rect.y + rect.height; + for (dlPtr = dInfoPtr->dLinePtr; dlPtr != NULL; + dlPtr = dlPtr->nextPtr) { + if ((dlPtr->oldY != -1) && (TkRectInRegion(region, rect.x, dlPtr->y, + rect.width, (unsigned int) dlPtr->height) != RectangleOut)) { + dlPtr->oldY = -1; + } + } + if (dInfoPtr->topOfEof < maxY) { + dInfoPtr->topOfEof = maxY; + } + + /* + * Schedule the redisplay operation if there isn't one already + * scheduled. + */ + + inset = textPtr->borderWidth + textPtr->highlightWidth; + if ((rect.x < (inset + textPtr->padX)) + || (rect.y < (inset + textPtr->padY)) + || ((int) (rect.x + rect.width) > (Tk_Width(textPtr->tkwin) + - inset - textPtr->padX)) + || (maxY > (Tk_Height(textPtr->tkwin) - inset - textPtr->padY))) { + dInfoPtr->flags |= REDRAW_BORDERS; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkTextChanged -- + * + * This procedure is invoked when info in a text widget is about + * to be modified in a way that changes how it is displayed (e.g. + * characters were inserted or deleted, or tag information was + * changed). This procedure must be called *before* a change is + * made, so that indexes in the display information are still + * valid. + * + * Results: + * None. + * + * Side effects: + * The range of character between index1Ptr (inclusive) and + * index2Ptr (exclusive) will be redisplayed at some point in the + * future (the actual redisplay is scheduled as a when-idle handler). + * + *---------------------------------------------------------------------- + */ + +void +TkTextChanged(textPtr, index1Ptr, index2Ptr) + TkText *textPtr; /* Widget record for text widget. */ + TkTextIndex *index1Ptr; /* Index of first character to redisplay. */ + TkTextIndex *index2Ptr; /* Index of character just after last one + * to redisplay. */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + DLine *firstPtr, *lastPtr; + TkTextIndex rounded; + + /* + * Schedule both a redisplay and a recomputation of display information. + * It's done here rather than the end of the procedure for two reasons: + * + * 1. If there are no display lines to update we'll want to return + * immediately, well before the end of the procedure. + * 2. It's important to arrange for the redisplay BEFORE calling + * FreeDLines. The reason for this is subtle and has to do with + * embedded windows. The chunk delete procedure for an embedded + * window will schedule an idle handler to unmap the window. + * However, we want the idle handler for redisplay to be called + * first, so that it can put the embedded window back on the screen + * again (if appropriate). This will prevent the window from ever + * being unmapped, and thereby avoid flashing. + */ + + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } + dInfoPtr->flags |= REDRAW_PENDING|DINFO_OUT_OF_DATE|REPICK_NEEDED; + + /* + * Find the DLines corresponding to index1Ptr and index2Ptr. There + * is one tricky thing here, which is that we have to relayout in + * units of whole text lines: round index1Ptr back to the beginning + * of its text line, and include all the display lines after index2, + * up to the end of its text line. This is necessary because the + * indices stored in the display lines will no longer be valid. It's + * also needed because any edit could change the way lines wrap. + */ + + rounded = *index1Ptr; + rounded.charIndex = 0; + firstPtr = FindDLine(dInfoPtr->dLinePtr, &rounded); + if (firstPtr == NULL) { + return; + } + lastPtr = FindDLine(dInfoPtr->dLinePtr, index2Ptr); + while ((lastPtr != NULL) + && (lastPtr->index.linePtr == index2Ptr->linePtr)) { + lastPtr = lastPtr->nextPtr; + } + + /* + * Delete all the DLines from firstPtr up to but not including lastPtr. + */ + + FreeDLines(textPtr, firstPtr, lastPtr, 1); +} + +/* + *---------------------------------------------------------------------- + * + * TkTextRedrawTag -- + * + * This procedure is invoked to request a redraw of all characters + * in a given range that have a particular tag on or off. It's + * called, for example, when tag options change. + * + * Results: + * None. + * + * Side effects: + * Information on the screen may be redrawn, and the layout of + * the screen may change. + * + *---------------------------------------------------------------------- + */ + +void +TkTextRedrawTag(textPtr, index1Ptr, index2Ptr, tagPtr, withTag) + TkText *textPtr; /* Widget record for text widget. */ + TkTextIndex *index1Ptr; /* First character in range to consider + * for redisplay. NULL means start at + * beginning of text. */ + TkTextIndex *index2Ptr; /* Character just after last one to consider + * for redisplay. NULL means process all + * the characters in the text. */ + TkTextTag *tagPtr; /* Information about tag. */ + int withTag; /* 1 means redraw characters that have the + * tag, 0 means redraw those without. */ +{ + register DLine *dlPtr; + DLine *endPtr; + int tagOn; + TkTextSearch search; + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + TkTextIndex *curIndexPtr; + TkTextIndex endOfText, *endIndexPtr; + + /* + * Round up the starting position if it's before the first line + * visible on the screen (we only care about what's on the screen). + */ + + dlPtr = dInfoPtr->dLinePtr; + if (dlPtr == NULL) { + return; + } + if ((index1Ptr == NULL) || (TkTextIndexCmp(&dlPtr->index, index1Ptr) > 0)) { + index1Ptr = &dlPtr->index; + } + + /* + * Set the stopping position if it wasn't specified. + */ + + if (index2Ptr == NULL) { + index2Ptr = TkTextMakeIndex(textPtr->tree, + TkBTreeNumLines(textPtr->tree), 0, &endOfText); + } + + /* + * Initialize a search through all transitions on the tag, starting + * with the first transition where the tag's current state is different + * from what it will eventually be. + */ + + TkBTreeStartSearch(index1Ptr, index2Ptr, tagPtr, &search); + /* + * Make our own curIndex because at this point search.curIndex + * may not equal index1Ptr->curIndex in the case the first tag toggle + * comes after index1Ptr (See the use of FindTagStart in TkBTreeStartSearch) + */ + curIndexPtr = index1Ptr; + tagOn = TkBTreeCharTagged(index1Ptr, tagPtr); + if (tagOn != withTag) { + if (!TkBTreeNextTag(&search)) { + return; + } + curIndexPtr = &search.curIndex; + } + + /* + * Schedule a redisplay and layout recalculation if they aren't + * already pending. This has to be done before calling FreeDLines, + * for the reason given in TkTextChanged. + */ + + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } + dInfoPtr->flags |= REDRAW_PENDING|DINFO_OUT_OF_DATE|REPICK_NEEDED; + + /* + * Each loop through the loop below is for one range of characters + * where the tag's current state is different than its eventual + * state. At the top of the loop, search contains information about + * the first character in the range. + */ + + while (1) { + /* + * Find the first DLine structure in the range. Note: if the + * desired character isn't the first in its text line, then look + * for the character just before it instead. This is needed to + * handle the case where the first character of a wrapped + * display line just got smaller, so that it now fits on the + * line before: need to relayout the line containing the + * previous character. + */ + + if (curIndexPtr->charIndex == 0) { + dlPtr = FindDLine(dlPtr, curIndexPtr); + } else { + TkTextIndex tmp; + + tmp = *curIndexPtr; + tmp.charIndex -= 1; + dlPtr = FindDLine(dlPtr, &tmp); + } + if (dlPtr == NULL) { + break; + } + + /* + * Find the first DLine structure that's past the end of the range. + */ + + if (!TkBTreeNextTag(&search)) { + endIndexPtr = index2Ptr; + } else { + curIndexPtr = &search.curIndex; + endIndexPtr = curIndexPtr; + } + endPtr = FindDLine(dlPtr, endIndexPtr); + if ((endPtr != NULL) && (endPtr->index.linePtr == endIndexPtr->linePtr) + && (endPtr->index.charIndex < endIndexPtr->charIndex)) { + endPtr = endPtr->nextPtr; + } + + /* + * Delete all of the display lines in the range, so that they'll + * be re-layed out and redrawn. + */ + + FreeDLines(textPtr, dlPtr, endPtr, 1); + dlPtr = endPtr; + + /* + * Find the first text line in the next range. + */ + + if (!TkBTreeNextTag(&search)) { + break; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkTextRelayoutWindow -- + * + * This procedure is called when something has happened that + * invalidates the whole layout of characters on the screen, such + * as a change in a configuration option for the overall text + * widget or a change in the window size. It causes all display + * information to be recomputed and the window to be redrawn. + * + * Results: + * None. + * + * Side effects: + * All the display information will be recomputed for the window + * and the window will be redrawn. + * + *---------------------------------------------------------------------- + */ + +void +TkTextRelayoutWindow(textPtr) + TkText *textPtr; /* Widget record for text widget. */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + GC new; + XGCValues gcValues; + + /* + * Schedule the window redisplay. See TkTextChanged for the + * reason why this has to be done before any calls to FreeDLines. + */ + + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } + dInfoPtr->flags |= REDRAW_PENDING|REDRAW_BORDERS|DINFO_OUT_OF_DATE + |REPICK_NEEDED; + + /* + * (Re-)create the graphics context for drawing the traversal + * highlight. + */ + + gcValues.graphics_exposures = False; + new = Tk_GetGC(textPtr->tkwin, GCGraphicsExposures, &gcValues); + if (dInfoPtr->copyGC != None) { + Tk_FreeGC(textPtr->display, dInfoPtr->copyGC); + } + dInfoPtr->copyGC = new; + + /* + * Throw away all the current layout information. + */ + + FreeDLines(textPtr, dInfoPtr->dLinePtr, (DLine *) NULL, 1); + dInfoPtr->dLinePtr = NULL; + + /* + * Recompute some overall things for the layout. Even if the + * window gets very small, pretend that there's at least one + * pixel of drawing space in it. + */ + + if (textPtr->highlightWidth < 0) { + textPtr->highlightWidth = 0; + } + dInfoPtr->x = textPtr->highlightWidth + textPtr->borderWidth + + textPtr->padX; + dInfoPtr->y = textPtr->highlightWidth + textPtr->borderWidth + + textPtr->padY; + dInfoPtr->maxX = Tk_Width(textPtr->tkwin) - textPtr->highlightWidth + - textPtr->borderWidth - textPtr->padX; + if (dInfoPtr->maxX <= dInfoPtr->x) { + dInfoPtr->maxX = dInfoPtr->x + 1; + } + dInfoPtr->maxY = Tk_Height(textPtr->tkwin) - textPtr->highlightWidth + - textPtr->borderWidth - textPtr->padY; + if (dInfoPtr->maxY <= dInfoPtr->y) { + dInfoPtr->maxY = dInfoPtr->y + 1; + } + dInfoPtr->topOfEof = dInfoPtr->maxY; + + /* + * If the upper-left character isn't the first in a line, recompute + * it. This is necessary because a change in the window's size + * or options could change the way lines wrap. + */ + + if (textPtr->topIndex.charIndex != 0) { + MeasureUp(textPtr, &textPtr->topIndex, 0, &textPtr->topIndex); + } + + /* + * Invalidate cached scrollbar positions, so that scrollbars + * sliders will be udpated. + */ + + dInfoPtr->xScrollFirst = dInfoPtr->xScrollLast = -1; + dInfoPtr->yScrollFirst = dInfoPtr->yScrollLast = -1; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextSetYView -- + * + * This procedure is called to specify what lines are to be + * displayed in a text widget. + * + * Results: + * None. + * + * Side effects: + * The display will (eventually) be updated so that the position + * given by "indexPtr" is visible on the screen at the position + * determined by "pickPlace". + * + *---------------------------------------------------------------------- + */ + +void +TkTextSetYView(textPtr, indexPtr, pickPlace) + TkText *textPtr; /* Widget record for text widget. */ + TkTextIndex *indexPtr; /* Position that is to appear somewhere + * in the view. */ + int pickPlace; /* 0 means topLine must appear at top of + * screen. 1 means we get to pick where it + * appears: minimize screen motion or else + * display line at center of screen. */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + register DLine *dlPtr; + int bottomY, close, lineIndex; + TkTextIndex tmpIndex, rounded; + Tk_FontMetrics fm; + + /* + * If the specified position is the extra line at the end of the + * text, round it back to the last real line. + */ + + lineIndex = TkBTreeLineIndex(indexPtr->linePtr); + if (lineIndex == TkBTreeNumLines(indexPtr->tree)) { + TkTextIndexBackChars(indexPtr, 1, &rounded); + indexPtr = &rounded; + } + + if (!pickPlace) { + /* + * The specified position must go at the top of the screen. + * Just leave all the DLine's alone: we may be able to reuse + * some of the information that's currently on the screen + * without redisplaying it all. + */ + + if (indexPtr->charIndex == 0) { + textPtr->topIndex = *indexPtr; + } else { + MeasureUp(textPtr, indexPtr, 0, &textPtr->topIndex); + } + goto scheduleUpdate; + } + + /* + * We have to pick where to display the index. First, bring + * the display information up to date and see if the index will be + * completely visible in the current screen configuration. If so + * then there's nothing to do. + */ + + if (dInfoPtr->flags & DINFO_OUT_OF_DATE) { + UpdateDisplayInfo(textPtr); + } + dlPtr = FindDLine(dInfoPtr->dLinePtr, indexPtr); + if (dlPtr != NULL) { + if ((dlPtr->y + dlPtr->height) > dInfoPtr->maxY) { + /* + * Part of the line hangs off the bottom of the screen; + * pretend the whole line is off-screen. + */ + + dlPtr = NULL; + } else if ((dlPtr->index.linePtr == indexPtr->linePtr) + && (dlPtr->index.charIndex <= indexPtr->charIndex)) { + return; + } + } + + /* + * The desired line isn't already on-screen. Figure out what + * it means to be "close" to the top or bottom of the screen. + * Close means within 1/3 of the screen height or within three + * lines, whichever is greater. Add one extra line also, to + * account for the way MeasureUp rounds. + */ + + Tk_GetFontMetrics(textPtr->tkfont, &fm); + bottomY = (dInfoPtr->y + dInfoPtr->maxY + fm.linespace)/2; + close = (dInfoPtr->maxY - dInfoPtr->y)/3; + if (close < 3*fm.linespace) { + close = 3*fm.linespace; + } + close += fm.linespace; + if (dlPtr != NULL) { + /* + * The desired line is above the top of screen. If it is + * "close" to the top of the window then make it the top + * line on the screen. + */ + + MeasureUp(textPtr, &textPtr->topIndex, close, &tmpIndex); + if (TkTextIndexCmp(&tmpIndex, indexPtr) <= 0) { + MeasureUp(textPtr, indexPtr, 0, &textPtr->topIndex); + goto scheduleUpdate; + } + } else { + /* + * The desired line is below the bottom of the screen. If it is + * "close" to the bottom of the screen then position it at the + * bottom of the screen. + */ + + MeasureUp(textPtr, indexPtr, close, &tmpIndex); + if (FindDLine(dInfoPtr->dLinePtr, &tmpIndex) != NULL) { + bottomY = dInfoPtr->maxY - dInfoPtr->y; + } + } + + /* + * Our job now is to arrange the display so that indexPtr appears + * as low on the screen as possible but with its bottom no lower + * than bottomY. BottomY is the bottom of the window if the + * desired line is just below the current screen, otherwise it + * is a half-line lower than the center of the window. + */ + + MeasureUp(textPtr, indexPtr, bottomY, &textPtr->topIndex); + + scheduleUpdate: + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } + dInfoPtr->flags |= REDRAW_PENDING|DINFO_OUT_OF_DATE|REPICK_NEEDED; +} + +/* + *-------------------------------------------------------------- + * + * MeasureUp -- + * + * Given one index, find the index of the first character + * on the highest display line that would be displayed no more + * than "distance" pixels above the given index. + * + * Results: + * *dstPtr is filled in with the index of the first character + * on a display line. The display line is found by measuring + * up "distance" pixels above the pixel just below an imaginary + * display line that contains srcPtr. If the display line + * that covers this coordinate actually extends above the + * coordinate, then return the index of the next lower line + * instead (i.e. the returned index will be completely visible + * at or below the given y-coordinate). + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static void +MeasureUp(textPtr, srcPtr, distance, dstPtr) + TkText *textPtr; /* Text widget in which to measure. */ + TkTextIndex *srcPtr; /* Index of character from which to start + * measuring. */ + int distance; /* Vertical distance in pixels measured + * from the pixel just below the lowest + * one in srcPtr's line. */ + TkTextIndex *dstPtr; /* Index to fill in with result. */ +{ + int lineNum; /* Number of current line. */ + int charsToCount; /* Maximum number of characters to measure + * in current line. */ + TkTextIndex bestIndex; /* Best candidate seen so far for result. */ + TkTextIndex index; + DLine *dlPtr, *lowestPtr; + int noBestYet; /* 1 means bestIndex hasn't been set. */ + + noBestYet = 1; + charsToCount = srcPtr->charIndex + 1; + index.tree = srcPtr->tree; + for (lineNum = TkBTreeLineIndex(srcPtr->linePtr); lineNum >= 0; + lineNum--) { + /* + * Layout an entire text line (potentially > 1 display line). + * For the first line, which contains srcPtr, only layout the + * part up through srcPtr (charsToCount is non-infinite to + * accomplish this). Make a list of all the display lines + * in backwards order (the lowest DLine on the screen is first + * in the list). + */ + + index.linePtr = TkBTreeFindLine(srcPtr->tree, lineNum); + index.charIndex = 0; + lowestPtr = NULL; + do { + dlPtr = LayoutDLine(textPtr, &index); + dlPtr->nextPtr = lowestPtr; + lowestPtr = dlPtr; + TkTextIndexForwChars(&index, dlPtr->count, &index); + charsToCount -= dlPtr->count; + } while ((charsToCount > 0) && (index.linePtr == dlPtr->index.linePtr)); + + /* + * Scan through the display lines to see if we've covered enough + * vertical distance. If so, save the starting index for the + * line at the desired location. + */ + + for (dlPtr = lowestPtr; dlPtr != NULL; dlPtr = dlPtr->nextPtr) { + distance -= dlPtr->height; + if (distance < 0) { + *dstPtr = (noBestYet) ? dlPtr->index : bestIndex; + break; + } + bestIndex = dlPtr->index; + noBestYet = 0; + } + + /* + * Discard the display lines, then either return or prepare + * for the next display line to lay out. + */ + + FreeDLines(textPtr, lowestPtr, (DLine *) NULL, 0); + if (distance < 0) { + return; + } + charsToCount = INT_MAX; /* Consider all chars. in next line. */ + } + + /* + * Ran off the beginning of the text. Return the first character + * in the text. + */ + + TkTextMakeIndex(textPtr->tree, 0, 0, dstPtr); +} + +/* + *-------------------------------------------------------------- + * + * TkTextSeeCmd -- + * + * This procedure is invoked to process the "see" option for + * the widget command for text widgets. See the user documentation + * for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +TkTextSeeCmd(textPtr, interp, argc, argv) + TkText *textPtr; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. Someone else has already + * parsed this command enough to know that + * argv[1] is "see". */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + TkTextIndex index; + int x, y, width, height, lineWidth, charCount, oneThird, delta; + DLine *dlPtr; + TkTextDispChunk *chunkPtr; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " see index\"", (char *) NULL); + return TCL_ERROR; + } + if (TkTextGetIndex(interp, textPtr, argv[2], &index) != TCL_OK) { + return TCL_ERROR; + } + + /* + * If the specified position is the extra line at the end of the + * text, round it back to the last real line. + */ + + if (TkBTreeLineIndex(index.linePtr) == TkBTreeNumLines(index.tree)) { + TkTextIndexBackChars(&index, 1, &index); + } + + /* + * First get the desired position into the vertical range of the window. + */ + + TkTextSetYView(textPtr, &index, 1); + + /* + * Now make sure that the character is in view horizontally. + */ + + if (dInfoPtr->flags & DINFO_OUT_OF_DATE) { + UpdateDisplayInfo(textPtr); + } + lineWidth = dInfoPtr->maxX - dInfoPtr->x; + if (dInfoPtr->maxLength < lineWidth) { + return TCL_OK; + } + + /* + * Find the chunk that contains the desired index. + */ + + dlPtr = FindDLine(dInfoPtr->dLinePtr, &index); + charCount = index.charIndex - dlPtr->index.charIndex; + for (chunkPtr = dlPtr->chunkPtr; ; chunkPtr = chunkPtr->nextPtr) { + if (charCount < chunkPtr->numChars) { + break; + } + charCount -= chunkPtr->numChars; + } + + /* + * Call a chunk-specific procedure to find the horizontal range of + * the character within the chunk. + */ + + (*chunkPtr->bboxProc)(chunkPtr, charCount, dlPtr->y + dlPtr->spaceAbove, + dlPtr->height - dlPtr->spaceAbove - dlPtr->spaceBelow, + dlPtr->baseline - dlPtr->spaceAbove, &x, &y, &width, + &height); + delta = x - dInfoPtr->curPixelOffset; + oneThird = lineWidth/3; + if (delta < 0) { + if (delta < -oneThird) { + dInfoPtr->newCharOffset = (x - lineWidth/2)/textPtr->charWidth; + } else { + dInfoPtr->newCharOffset -= ((-delta) + textPtr->charWidth - 1) + / textPtr->charWidth; + } + } else { + delta -= (lineWidth - width); + if (delta > 0) { + if (delta > oneThird) { + dInfoPtr->newCharOffset = (x - lineWidth/2)/textPtr->charWidth; + } else { + dInfoPtr->newCharOffset += (delta + textPtr->charWidth - 1) + / textPtr->charWidth; + } + } else { + return TCL_OK; + } + } + dInfoPtr->flags |= DINFO_OUT_OF_DATE; + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + dInfoPtr->flags |= REDRAW_PENDING; + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * TkTextXviewCmd -- + * + * This procedure is invoked to process the "xview" option for + * the widget command for text widgets. See the user documentation + * for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +TkTextXviewCmd(textPtr, interp, argc, argv) + TkText *textPtr; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. Someone else has already + * parsed this command enough to know that + * argv[1] is "xview". */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + int type, charsPerPage, count, newOffset; + double fraction; + + if (dInfoPtr->flags & DINFO_OUT_OF_DATE) { + UpdateDisplayInfo(textPtr); + } + + if (argc == 2) { + GetXView(interp, textPtr, 0); + return TCL_OK; + } + + newOffset = dInfoPtr->newCharOffset; + type = Tk_GetScrollInfo(interp, argc, argv, &fraction, &count); + switch (type) { + case TK_SCROLL_ERROR: + return TCL_ERROR; + case TK_SCROLL_MOVETO: + if (fraction > 1.0) { + fraction = 1.0; + } + if (fraction < 0) { + fraction = 0; + } + newOffset = (int) (((fraction * dInfoPtr->maxLength) / textPtr->charWidth) + + 0.5); + break; + case TK_SCROLL_PAGES: + charsPerPage = ((dInfoPtr->maxX - dInfoPtr->x) / textPtr->charWidth) + - 2; + if (charsPerPage < 1) { + charsPerPage = 1; + } + newOffset += charsPerPage*count; + break; + case TK_SCROLL_UNITS: + newOffset += count; + break; + } + + dInfoPtr->newCharOffset = newOffset; + dInfoPtr->flags |= DINFO_OUT_OF_DATE; + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + dInfoPtr->flags |= REDRAW_PENDING; + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ScrollByLines -- + * + * This procedure is called to scroll a text widget up or down + * by a given number of lines. + * + * Results: + * None. + * + * Side effects: + * The view in textPtr's window changes to reflect the value + * of "offset". + * + *---------------------------------------------------------------------- + */ + +static void +ScrollByLines(textPtr, offset) + TkText *textPtr; /* Widget to scroll. */ + int offset; /* Amount by which to scroll, in *screen* + * lines. Positive means that information + * later in text becomes visible, negative + * means that information earlier in the + * text becomes visible. */ +{ + int i, charsToCount, lineNum; + TkTextIndex new, index; + TkTextLine *lastLinePtr; + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + DLine *dlPtr, *lowestPtr; + + if (offset < 0) { + /* + * Must scroll up (to show earlier information in the text). + * The code below is similar to that in MeasureUp, except that + * it counts lines instead of pixels. + */ + + charsToCount = textPtr->topIndex.charIndex + 1; + index.tree = textPtr->tree; + offset--; /* Skip line containing topIndex. */ + for (lineNum = TkBTreeLineIndex(textPtr->topIndex.linePtr); + lineNum >= 0; lineNum--) { + index.linePtr = TkBTreeFindLine(textPtr->tree, lineNum); + index.charIndex = 0; + lowestPtr = NULL; + do { + dlPtr = LayoutDLine(textPtr, &index); + dlPtr->nextPtr = lowestPtr; + lowestPtr = dlPtr; + TkTextIndexForwChars(&index, dlPtr->count, &index); + charsToCount -= dlPtr->count; + } while ((charsToCount > 0) + && (index.linePtr == dlPtr->index.linePtr)); + + for (dlPtr = lowestPtr; dlPtr != NULL; dlPtr = dlPtr->nextPtr) { + offset++; + if (offset == 0) { + textPtr->topIndex = dlPtr->index; + break; + } + } + + /* + * Discard the display lines, then either return or prepare + * for the next display line to lay out. + */ + + FreeDLines(textPtr, lowestPtr, (DLine *) NULL, 0); + if (offset >= 0) { + goto scheduleUpdate; + } + charsToCount = INT_MAX; + } + + /* + * Ran off the beginning of the text. Return the first character + * in the text. + */ + + TkTextMakeIndex(textPtr->tree, 0, 0, &textPtr->topIndex); + } else { + /* + * Scrolling down, to show later information in the text. + * Just count lines from the current top of the window. + */ + + lastLinePtr = TkBTreeFindLine(textPtr->tree, + TkBTreeNumLines(textPtr->tree)); + for (i = 0; i < offset; i++) { + dlPtr = LayoutDLine(textPtr, &textPtr->topIndex); + dlPtr->nextPtr = NULL; + TkTextIndexForwChars(&textPtr->topIndex, dlPtr->count, &new); + FreeDLines(textPtr, dlPtr, (DLine *) NULL, 0); + if (new.linePtr == lastLinePtr) { + break; + } + textPtr->topIndex = new; + } + } + + scheduleUpdate: + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } + dInfoPtr->flags |= REDRAW_PENDING|DINFO_OUT_OF_DATE|REPICK_NEEDED; +} + +/* + *-------------------------------------------------------------- + * + * TkTextYviewCmd -- + * + * This procedure is invoked to process the "yview" option for + * the widget command for text widgets. See the user documentation + * for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +TkTextYviewCmd(textPtr, interp, argc, argv) + TkText *textPtr; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. Someone else has already + * parsed this command enough to know that + * argv[1] is "yview". */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + int pickPlace, lineNum, type, charsInLine; + Tk_FontMetrics fm; + int pixels, count; + size_t switchLength; + double fraction; + TkTextIndex index, new; + TkTextLine *lastLinePtr; + DLine *dlPtr; + + if (dInfoPtr->flags & DINFO_OUT_OF_DATE) { + UpdateDisplayInfo(textPtr); + } + + if (argc == 2) { + GetYView(interp, textPtr, 0); + return TCL_OK; + } + + /* + * Next, handle the old syntax: "pathName yview ?-pickplace? where" + */ + + pickPlace = 0; + if (argv[2][0] == '-') { + switchLength = strlen(argv[2]); + if ((switchLength >= 2) + && (strncmp(argv[2], "-pickplace", switchLength) == 0)) { + pickPlace = 1; + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " yview -pickplace lineNum|index\"", + (char *) NULL); + return TCL_ERROR; + } + } + } + if ((argc == 3) || pickPlace) { + if (Tcl_GetInt(interp, argv[2+pickPlace], &lineNum) == TCL_OK) { + TkTextMakeIndex(textPtr->tree, lineNum, 0, &index); + TkTextSetYView(textPtr, &index, 0); + return TCL_OK; + } + + /* + * The argument must be a regular text index. + */ + + Tcl_ResetResult(interp); + if (TkTextGetIndex(interp, textPtr, argv[2+pickPlace], + &index) != TCL_OK) { + return TCL_ERROR; + } + TkTextSetYView(textPtr, &index, pickPlace); + return TCL_OK; + } + + /* + * New syntax: dispatch based on argv[2]. + */ + + type = Tk_GetScrollInfo(interp, argc, argv, &fraction, &count); + switch (type) { + case TK_SCROLL_ERROR: + return TCL_ERROR; + case TK_SCROLL_MOVETO: + if (fraction > 1.0) { + fraction = 1.0; + } + if (fraction < 0) { + fraction = 0; + } + fraction *= TkBTreeNumLines(textPtr->tree); + lineNum = (int) fraction; + TkTextMakeIndex(textPtr->tree, lineNum, 0, &index); + charsInLine = TkBTreeCharsInLine(index.linePtr); + index.charIndex = (int)((charsInLine * (fraction-lineNum)) + 0.5); + if (index.charIndex >= charsInLine) { + TkTextMakeIndex(textPtr->tree, lineNum+1, 0, &index); + } + TkTextSetYView(textPtr, &index, 0); + break; + case TK_SCROLL_PAGES: + /* + * Scroll up or down by screenfuls. Actually, use the + * window height minus two lines, so that there's some + * overlap between adjacent pages. + */ + + Tk_GetFontMetrics(textPtr->tkfont, &fm); + if (count < 0) { + pixels = (dInfoPtr->maxY - 2*fm.linespace - dInfoPtr->y)*(-count) + + fm.linespace; + MeasureUp(textPtr, &textPtr->topIndex, pixels, &new); + if (TkTextIndexCmp(&textPtr->topIndex, &new) == 0) { + /* + * A page of scrolling ended up being less than one line. + * Scroll one line anyway. + */ + + count = -1; + goto scrollByLines; + } + textPtr->topIndex = new; + } else { + /* + * Scrolling down by pages. Layout lines starting at the + * top index and count through the desired vertical distance. + */ + + pixels = (dInfoPtr->maxY - 2*fm.linespace - dInfoPtr->y)*count; + lastLinePtr = TkBTreeFindLine(textPtr->tree, + TkBTreeNumLines(textPtr->tree)); + do { + dlPtr = LayoutDLine(textPtr, &textPtr->topIndex); + dlPtr->nextPtr = NULL; + TkTextIndexForwChars(&textPtr->topIndex, dlPtr->count, + &new); + pixels -= dlPtr->height; + FreeDLines(textPtr, dlPtr, (DLine *) NULL, 0); + if (new.linePtr == lastLinePtr) { + break; + } + textPtr->topIndex = new; + } while (pixels > 0); + } + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } + dInfoPtr->flags |= REDRAW_PENDING|DINFO_OUT_OF_DATE|REPICK_NEEDED; + break; + case TK_SCROLL_UNITS: + scrollByLines: + ScrollByLines(textPtr, count); + break; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * TkTextScanCmd -- + * + * This procedure is invoked to process the "scan" option for + * the widget command for text widgets. See the user documentation + * for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +TkTextScanCmd(textPtr, interp, argc, argv) + register TkText *textPtr; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. Someone else has already + * parsed this command enough to know that + * argv[1] is "scan". */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + TkTextIndex index; + int c, x, y, totalScroll, newChar, maxChar; + Tk_FontMetrics fm; + size_t length; + + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " scan mark|dragto x y\"", (char *) NULL); + return TCL_ERROR; + } + if (Tcl_GetInt(interp, argv[3], &x) != TCL_OK) { + return TCL_ERROR; + } + if (Tcl_GetInt(interp, argv[4], &y) != TCL_OK) { + return TCL_ERROR; + } + c = argv[2][0]; + length = strlen(argv[2]); + if ((c == 'd') && (strncmp(argv[2], "dragto", length) == 0)) { + /* + * Amplify the difference between the current position and the + * mark position to compute how much the view should shift, then + * update the mark position to correspond to the new view. If we + * run off the edge of the text, reset the mark point so that the + * current position continues to correspond to the edge of the + * window. This means that the picture will start dragging as + * soon as the mouse reverses direction (without this reset, might + * have to slide mouse a long ways back before the picture starts + * moving again). + */ + + newChar = dInfoPtr->scanMarkChar + (10*(dInfoPtr->scanMarkX - x)) + / (textPtr->charWidth); + maxChar = 1 + (dInfoPtr->maxLength - (dInfoPtr->maxX - dInfoPtr->x) + + textPtr->charWidth - 1)/textPtr->charWidth; + if (newChar < 0) { + dInfoPtr->scanMarkChar = newChar = 0; + dInfoPtr->scanMarkX = x; + } else if (newChar > maxChar) { + dInfoPtr->scanMarkChar = newChar = maxChar; + dInfoPtr->scanMarkX = x; + } + dInfoPtr->newCharOffset = newChar; + + Tk_GetFontMetrics(textPtr->tkfont, &fm); + totalScroll = (10*(dInfoPtr->scanMarkY - y)) / fm.linespace; + if (totalScroll != dInfoPtr->scanTotalScroll) { + index = textPtr->topIndex; + ScrollByLines(textPtr, totalScroll-dInfoPtr->scanTotalScroll); + dInfoPtr->scanTotalScroll = totalScroll; + if ((index.linePtr == textPtr->topIndex.linePtr) && + (index.charIndex == textPtr->topIndex.charIndex)) { + dInfoPtr->scanTotalScroll = 0; + dInfoPtr->scanMarkY = y; + } + } + } else if ((c == 'm') && (strncmp(argv[2], "mark", length) == 0)) { + dInfoPtr->scanMarkChar = dInfoPtr->newCharOffset; + dInfoPtr->scanMarkX = x; + dInfoPtr->scanTotalScroll = 0; + dInfoPtr->scanMarkY = y; + } else { + Tcl_AppendResult(interp, "bad scan option \"", argv[2], + "\": must be mark or dragto", (char *) NULL); + return TCL_ERROR; + } + dInfoPtr->flags |= DINFO_OUT_OF_DATE; + if (!(dInfoPtr->flags & REDRAW_PENDING)) { + dInfoPtr->flags |= REDRAW_PENDING; + Tcl_DoWhenIdle(DisplayText, (ClientData) textPtr); + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * GetXView -- + * + * This procedure computes the fractions that indicate what's + * visible in a text window and, optionally, evaluates a + * Tcl script to report them to the text's associated scrollbar. + * + * Results: + * If report is zero, then interp->result is filled in with + * two real numbers separated by a space, giving the position of + * the left and right edges of the window as fractions from 0 to + * 1, where 0 means the left edge of the text and 1 means the right + * edge. If report is non-zero, then interp->result isn't modified + * directly, but instead a script is evaluated in interp to report + * the new horizontal scroll position to the scrollbar (if the scroll + * position hasn't changed then no script is invoked). + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +GetXView(interp, textPtr, report) + Tcl_Interp *interp; /* If "report" is FALSE, string + * describing visible range gets + * stored in interp->result. */ + TkText *textPtr; /* Information about text widget. */ + int report; /* Non-zero means report info to + * scrollbar if it has changed. */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + char buffer[200]; + double first, last; + int code; + + if (dInfoPtr->maxLength > 0) { + first = ((double) dInfoPtr->curPixelOffset) + / dInfoPtr->maxLength; + last = first + ((double) (dInfoPtr->maxX - dInfoPtr->x)) + / dInfoPtr->maxLength; + if (last > 1.0) { + last = 1.0; + } + } else { + first = 0; + last = 1.0; + } + if (!report) { + sprintf(interp->result, "%g %g", first, last); + return; + } + if ((first == dInfoPtr->xScrollFirst) && (last == dInfoPtr->xScrollLast)) { + return; + } + dInfoPtr->xScrollFirst = first; + dInfoPtr->xScrollLast = last; + sprintf(buffer, " %g %g", first, last); + code = Tcl_VarEval(interp, textPtr->xScrollCmd, + buffer, (char *) NULL); + if (code != TCL_OK) { + Tcl_AddErrorInfo(interp, + "\n (horizontal scrolling command executed by text)"); + Tcl_BackgroundError(interp); + } +} + +/* + *---------------------------------------------------------------------- + * + * GetYView -- + * + * This procedure computes the fractions that indicate what's + * visible in a text window and, optionally, evaluates a + * Tcl script to report them to the text's associated scrollbar. + * + * Results: + * If report is zero, then interp->result is filled in with + * two real numbers separated by a space, giving the position of + * the top and bottom of the window as fractions from 0 to 1, where + * 0 means the beginning of the text and 1 means the end. If + * report is non-zero, then interp->result isn't modified directly, + * but a script is evaluated in interp to report the new scroll + * position to the scrollbar (if the scroll position hasn't changed + * then no script is invoked). + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +GetYView(interp, textPtr, report) + Tcl_Interp *interp; /* If "report" is FALSE, string + * describing visible range gets + * stored in interp->result. */ + TkText *textPtr; /* Information about text widget. */ + int report; /* Non-zero means report info to + * scrollbar if it has changed. */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + char buffer[200]; + double first, last; + DLine *dlPtr; + int totalLines, code, count; + + dlPtr = dInfoPtr->dLinePtr; + totalLines = TkBTreeNumLines(textPtr->tree); + first = ((double) TkBTreeLineIndex(dlPtr->index.linePtr)) + + ((double) dlPtr->index.charIndex) + / (TkBTreeCharsInLine(dlPtr->index.linePtr)); + first /= totalLines; + while (1) { + if ((dlPtr->y + dlPtr->height) > dInfoPtr->maxY) { + /* + * The last line is only partially visible, so don't + * count its characters in what's visible. + */ + count = 0; + break; + } + if (dlPtr->nextPtr == NULL) { + count = dlPtr->count; + break; + } + dlPtr = dlPtr->nextPtr; + } + last = ((double) TkBTreeLineIndex(dlPtr->index.linePtr)) + + ((double) (dlPtr->index.charIndex + count)) + / (TkBTreeCharsInLine(dlPtr->index.linePtr)); + last /= totalLines; + if (!report) { + sprintf(interp->result, "%g %g", first, last); + return; + } + if ((first == dInfoPtr->yScrollFirst) && (last == dInfoPtr->yScrollLast)) { + return; + } + dInfoPtr->yScrollFirst = first; + dInfoPtr->yScrollLast = last; + sprintf(buffer, " %g %g", first, last); + code = Tcl_VarEval(interp, textPtr->yScrollCmd, + buffer, (char *) NULL); + if (code != TCL_OK) { + Tcl_AddErrorInfo(interp, + "\n (vertical scrolling command executed by text)"); + Tcl_BackgroundError(interp); + } +} + +/* + *---------------------------------------------------------------------- + * + * FindDLine -- + * + * This procedure is called to find the DLine corresponding to a + * given text index. + * + * Results: + * The return value is a pointer to the first DLine found in the + * list headed by dlPtr that displays information at or after the + * specified position. If there is no such line in the list then + * NULL is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static DLine * +FindDLine(dlPtr, indexPtr) + register DLine *dlPtr; /* Pointer to first in list of DLines + * to search. */ + TkTextIndex *indexPtr; /* Index of desired character. */ +{ + TkTextLine *linePtr; + + if (dlPtr == NULL) { + return NULL; + } + if (TkBTreeLineIndex(indexPtr->linePtr) + < TkBTreeLineIndex(dlPtr->index.linePtr)) { + /* + * The first display line is already past the desired line. + */ + return dlPtr; + } + + /* + * Find the first display line that covers the desired text line. + */ + + linePtr = dlPtr->index.linePtr; + while (linePtr != indexPtr->linePtr) { + while (dlPtr->index.linePtr == linePtr) { + dlPtr = dlPtr->nextPtr; + if (dlPtr == NULL) { + return NULL; + } + } + linePtr = TkBTreeNextLine(linePtr); + if (linePtr == NULL) { + panic("FindDLine reached end of text"); + } + } + if (indexPtr->linePtr != dlPtr->index.linePtr) { + return dlPtr; + } + + /* + * Now get to the right position within the text line. + */ + + while (indexPtr->charIndex >= (dlPtr->index.charIndex + dlPtr->count)) { + dlPtr = dlPtr->nextPtr; + if ((dlPtr == NULL) || (dlPtr->index.linePtr != indexPtr->linePtr)) { + break; + } + } + return dlPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextPixelIndex -- + * + * Given an (x,y) coordinate on the screen, find the location of + * the character closest to that location. + * + * Results: + * The index at *indexPtr is modified to refer to the character + * on the display that is closest to (x,y). + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkTextPixelIndex(textPtr, x, y, indexPtr) + TkText *textPtr; /* Widget record for text widget. */ + int x, y; /* Pixel coordinates of point in widget's + * window. */ + TkTextIndex *indexPtr; /* This index gets filled in with the + * index of the character nearest to (x,y). */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + register DLine *dlPtr; + register TkTextDispChunk *chunkPtr; + + /* + * Make sure that all of the layout information about what's + * displayed where on the screen is up-to-date. + */ + + if (dInfoPtr->flags & DINFO_OUT_OF_DATE) { + UpdateDisplayInfo(textPtr); + } + + /* + * If the coordinates are above the top of the window, then adjust + * them to refer to the upper-right corner of the window. If they're + * off to one side or the other, then adjust to the closest side. + */ + + if (y < dInfoPtr->y) { + y = dInfoPtr->y; + x = dInfoPtr->x; + } + if (x >= dInfoPtr->maxX) { + x = dInfoPtr->maxX - 1; + } + if (x < dInfoPtr->x) { + x = dInfoPtr->x; + } + + /* + * Find the display line containing the desired y-coordinate. + */ + + for (dlPtr = dInfoPtr->dLinePtr; y >= (dlPtr->y + dlPtr->height); + dlPtr = dlPtr->nextPtr) { + if (dlPtr->nextPtr == NULL) { + /* + * Y-coordinate is off the bottom of the displayed text. + * Use the last character on the last line. + */ + + x = dInfoPtr->maxX - 1; + break; + } + } + + /* + * Scan through the line's chunks to find the one that contains + * the desired x-coordinate. Before doing this, translate the + * x-coordinate from the coordinate system of the window to the + * coordinate system of the line (to take account of x-scrolling). + */ + + *indexPtr = dlPtr->index; + x = x - dInfoPtr->x + dInfoPtr->curPixelOffset; + for (chunkPtr = dlPtr->chunkPtr; x >= (chunkPtr->x + chunkPtr->width); + indexPtr->charIndex += chunkPtr->numChars, + chunkPtr = chunkPtr->nextPtr) { + if (chunkPtr->nextPtr == NULL) { + indexPtr->charIndex += chunkPtr->numChars - 1; + return; + } + } + + /* + * If the chunk has more than one character in it, ask it which + * character is at the desired location. + */ + + if (chunkPtr->numChars > 1) { + indexPtr->charIndex += (*chunkPtr->measureProc)(chunkPtr, x); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkTextCharBbox -- + * + * Given an index, find the bounding box of the screen area + * occupied by that character. + * + * Results: + * Zero is returned if the character is on the screen. -1 + * means the character isn't on the screen. If the return value + * is 0, then the bounding box of the part of the character that's + * visible on the screen is returned to *xPtr, *yPtr, *widthPtr, + * and *heightPtr. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkTextCharBbox(textPtr, indexPtr, xPtr, yPtr, widthPtr, heightPtr) + TkText *textPtr; /* Widget record for text widget. */ + TkTextIndex *indexPtr; /* Index of character whose bounding + * box is desired. */ + int *xPtr, *yPtr; /* Filled with character's upper-left + * coordinate. */ + int *widthPtr, *heightPtr; /* Filled in with character's dimensions. */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + DLine *dlPtr; + register TkTextDispChunk *chunkPtr; + int index; + + /* + * Make sure that all of the screen layout information is up to date. + */ + + if (dInfoPtr->flags & DINFO_OUT_OF_DATE) { + UpdateDisplayInfo(textPtr); + } + + /* + * Find the display line containing the desired index. + */ + + dlPtr = FindDLine(dInfoPtr->dLinePtr, indexPtr); + if ((dlPtr == NULL) || (TkTextIndexCmp(&dlPtr->index, indexPtr) > 0)) { + return -1; + } + + /* + * Find the chunk within the line that contains the desired + * index. + */ + + index = indexPtr->charIndex - dlPtr->index.charIndex; + for (chunkPtr = dlPtr->chunkPtr; ; chunkPtr = chunkPtr->nextPtr) { + if (chunkPtr == NULL) { + return -1; + } + if (index < chunkPtr->numChars) { + break; + } + index -= chunkPtr->numChars; + } + + /* + * Call a chunk-specific procedure to find the horizontal range of + * the character within the chunk, then fill in the vertical range. + * The x-coordinate returned by bboxProc is a coordinate within a + * line, not a coordinate on the screen. Translate it to reflect + * horizontal scrolling. + */ + + (*chunkPtr->bboxProc)(chunkPtr, index, dlPtr->y + dlPtr->spaceAbove, + dlPtr->height - dlPtr->spaceAbove - dlPtr->spaceBelow, + dlPtr->baseline - dlPtr->spaceAbove, xPtr, yPtr, widthPtr, + heightPtr); + *xPtr = *xPtr + dInfoPtr->x - dInfoPtr->curPixelOffset; + if ((index == (chunkPtr->numChars-1)) && (chunkPtr->nextPtr == NULL)) { + /* + * Last character in display line. Give it all the space up to + * the line. + */ + + if (*xPtr > dInfoPtr->maxX) { + *xPtr = dInfoPtr->maxX; + } + *widthPtr = dInfoPtr->maxX - *xPtr; + } + if ((*xPtr + *widthPtr) <= dInfoPtr->x) { + return -1; + } + if ((*xPtr + *widthPtr) > dInfoPtr->maxX) { + *widthPtr = dInfoPtr->maxX - *xPtr; + if (*widthPtr <= 0) { + return -1; + } + } + if ((*yPtr + *heightPtr) > dInfoPtr->maxY) { + *heightPtr = dInfoPtr->maxY - *yPtr; + if (*heightPtr <= 0) { + return -1; + } + } + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextDLineInfo -- + * + * Given an index, return information about the display line + * containing that character. + * + * Results: + * Zero is returned if the character is on the screen. -1 + * means the character isn't on the screen. If the return value + * is 0, then information is returned in the variables pointed + * to by xPtr, yPtr, widthPtr, heightPtr, and basePtr. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkTextDLineInfo(textPtr, indexPtr, xPtr, yPtr, widthPtr, heightPtr, basePtr) + TkText *textPtr; /* Widget record for text widget. */ + TkTextIndex *indexPtr; /* Index of character whose bounding + * box is desired. */ + int *xPtr, *yPtr; /* Filled with line's upper-left + * coordinate. */ + int *widthPtr, *heightPtr; /* Filled in with line's dimensions. */ + int *basePtr; /* Filled in with the baseline position, + * measured as an offset down from *yPtr. */ +{ + TextDInfo *dInfoPtr = textPtr->dInfoPtr; + DLine *dlPtr; + + /* + * Make sure that all of the screen layout information is up to date. + */ + + if (dInfoPtr->flags & DINFO_OUT_OF_DATE) { + UpdateDisplayInfo(textPtr); + } + + /* + * Find the display line containing the desired index. + */ + + dlPtr = FindDLine(dInfoPtr->dLinePtr, indexPtr); + if ((dlPtr == NULL) || (TkTextIndexCmp(&dlPtr->index, indexPtr) > 0)) { + return -1; + } + + *xPtr = dInfoPtr->x - dInfoPtr->curPixelOffset + dlPtr->chunkPtr->x; + *widthPtr = dlPtr->length - dlPtr->chunkPtr->x; + *yPtr = dlPtr->y; + if ((dlPtr->y + dlPtr->height) > dInfoPtr->maxY) { + *heightPtr = dInfoPtr->maxY - dlPtr->y; + } else { + *heightPtr = dlPtr->height; + } + *basePtr = dlPtr->baseline; + return 0; +} + +/* + *-------------------------------------------------------------- + * + * TkTextCharLayoutProc -- + * + * This procedure is the "layoutProc" for character segments. + * + * Results: + * If there is something to display for the chunk then a + * non-zero value is returned and the fields of chunkPtr + * will be filled in (see the declaration of TkTextDispChunk + * in tkText.h for details). If zero is returned it means + * that no characters from this chunk fit in the window. + * If -1 is returned it means that this segment just doesn't + * need to be displayed (never happens for text). + * + * Side effects: + * Memory is allocated to hold additional information about + * the chunk. + * + *-------------------------------------------------------------- + */ + +int +TkTextCharLayoutProc(textPtr, indexPtr, segPtr, offset, maxX, maxChars, + noCharsYet, wrapMode, chunkPtr) + TkText *textPtr; /* Text widget being layed out. */ + TkTextIndex *indexPtr; /* Index of first character to lay out + * (corresponds to segPtr and offset). */ + TkTextSegment *segPtr; /* Segment being layed out. */ + int offset; /* Offset within segment of first character + * to consider. */ + int maxX; /* Chunk must not occupy pixels at this + * position or higher. */ + int maxChars; /* Chunk must not include more than this + * many characters. */ + int noCharsYet; /* Non-zero means no characters have been + * assigned to this display line yet. */ + Tk_Uid wrapMode; /* How to handle line wrapping: tkTextCharUid, + * tkTextNoneUid, or tkTextWordUid. */ + register TkTextDispChunk *chunkPtr; + /* Structure to fill in with information + * about this chunk. The x field has already + * been set by the caller. */ +{ + Tk_Font tkfont; + int nextX, charsThatFit, count; + CharInfo *ciPtr; + char *p; + TkTextSegment *nextPtr; + Tk_FontMetrics fm; + + /* + * Figure out how many characters will fit in the space we've got. + * Include the next character, even though it won't fit completely, + * if any of the following is true: + * (a) the chunk contains no characters and the display line contains + * no characters yet (i.e. the line isn't wide enough to hold + * even a single character). + * (b) at least one pixel of the character is visible, we haven't + * already exceeded the character limit, and the next character + * is a white space character. + */ + + p = segPtr->body.chars + offset; + tkfont = chunkPtr->stylePtr->sValuePtr->tkfont; + charsThatFit = MeasureChars(tkfont, p, maxChars, chunkPtr->x, maxX, 0, + &nextX); + if (charsThatFit < maxChars) { + if ((charsThatFit == 0) && noCharsYet) { + charsThatFit = 1; + MeasureChars(tkfont, p, 1, chunkPtr->x, INT_MAX, 0, &nextX); + } + if ((nextX < maxX) && ((p[charsThatFit] == ' ') + || (p[charsThatFit] == '\t'))) { + /* + * Space characters are funny, in that they are considered + * to fit if there is at least one pixel of space left on the + * line. Just give the space character whatever space is left. + */ + + nextX = maxX; + charsThatFit++; + } + if (p[charsThatFit] == '\n') { + /* + * A newline character takes up no space, so if the previous + * character fits then so does the newline. + */ + + charsThatFit++; + } + if (charsThatFit == 0) { + return 0; + } + } + + Tk_GetFontMetrics(tkfont, &fm); + + /* + * Fill in the chunk structure and allocate and initialize a + * CharInfo structure. If the last character is a newline + * then don't bother to display it. + */ + + chunkPtr->displayProc = CharDisplayProc; + chunkPtr->undisplayProc = CharUndisplayProc; + chunkPtr->measureProc = CharMeasureProc; + chunkPtr->bboxProc = CharBboxProc; + chunkPtr->numChars = charsThatFit; + chunkPtr->minAscent = fm.ascent + chunkPtr->stylePtr->sValuePtr->offset; + chunkPtr->minDescent = fm.descent - chunkPtr->stylePtr->sValuePtr->offset; + chunkPtr->minHeight = 0; + chunkPtr->width = nextX - chunkPtr->x; + chunkPtr->breakIndex = -1; + ciPtr = (CharInfo *) ckalloc((unsigned) + (sizeof(CharInfo) - 3 + charsThatFit)); + chunkPtr->clientData = (ClientData) ciPtr; + ciPtr->numChars = charsThatFit; + strncpy(ciPtr->chars, p, (size_t) charsThatFit); + if (p[charsThatFit-1] == '\n') { + ciPtr->numChars--; + } + + /* + * Compute a break location. If we're in word wrap mode, a + * break can occur after any space character, or at the end of + * the chunk if the next segment (ignoring those with zero size) + * is not a character segment. + */ + + if (wrapMode != tkTextWordUid) { + chunkPtr->breakIndex = chunkPtr->numChars; + } else { + for (count = charsThatFit, p += charsThatFit-1; count > 0; + count--, p--) { + if (isspace(UCHAR(*p))) { + chunkPtr->breakIndex = count; + break; + } + } + if ((charsThatFit+offset) == segPtr->size) { + for (nextPtr = segPtr->nextPtr; nextPtr != NULL; + nextPtr = nextPtr->nextPtr) { + if (nextPtr->size != 0) { + if (nextPtr->typePtr != &tkTextCharType) { + chunkPtr->breakIndex = chunkPtr->numChars; + } + break; + } + } + } + } + return 1; +} + +/* + *-------------------------------------------------------------- + * + * CharDisplayProc -- + * + * This procedure is called to display a character chunk on + * the screen or in an off-screen pixmap. + * + * Results: + * None. + * + * Side effects: + * Graphics are drawn. + * + *-------------------------------------------------------------- + */ + +static void +CharDisplayProc(chunkPtr, x, y, height, baseline, display, dst, screenY) + TkTextDispChunk *chunkPtr; /* Chunk that is to be drawn. */ + int x; /* X-position in dst at which to + * draw this chunk (may differ from + * the x-position in the chunk because + * of scrolling). */ + int y; /* Y-position at which to draw this + * chunk in dst. */ + int height; /* Total height of line. */ + int baseline; /* Offset of baseline from y. */ + Display *display; /* Display to use for drawing. */ + Drawable dst; /* Pixmap or window in which to draw + * chunk. */ + int screenY; /* Y-coordinate in text window that + * corresponds to y. */ +{ + CharInfo *ciPtr = (CharInfo *) chunkPtr->clientData; + TextStyle *stylePtr; + StyleValues *sValuePtr; + int offsetChars, offsetX; + + if ((x + chunkPtr->width) <= 0) { + /* + * The chunk is off-screen. + */ + + return; + } + + stylePtr = chunkPtr->stylePtr; + sValuePtr = stylePtr->sValuePtr; + + /* + * If the text sticks out way to the left of the window, skip + * over the characters that aren't in the visible part of the + * window. This is essential if x is very negative (such as + * less than 32K); otherwise overflow problems will occur + * in servers that use 16-bit arithmetic, like X. + */ + + offsetX = x; + offsetChars = 0; + if (x < 0) { + offsetChars = MeasureChars(sValuePtr->tkfont, ciPtr->chars, + ciPtr->numChars, x, 0, x - chunkPtr->x, &offsetX); + } + + /* + * Draw the text, underline, and overstrike for this chunk. + */ + + if (ciPtr->numChars > offsetChars) { + int numChars = ciPtr->numChars - offsetChars; + char *string = ciPtr->chars + offsetChars; + + if ((numChars > 0) && (string[numChars - 1] == '\t')) { + numChars--; + } + Tk_DrawChars(display, dst, stylePtr->fgGC, sValuePtr->tkfont, string, + numChars, offsetX, y + baseline - sValuePtr->offset); + if (sValuePtr->underline) { + Tk_UnderlineChars(display, dst, stylePtr->fgGC, sValuePtr->tkfont, + ciPtr->chars + offsetChars, offsetX, + y + baseline - sValuePtr->offset, + 0, numChars); + + } + if (sValuePtr->overstrike) { + Tk_FontMetrics fm; + + Tk_GetFontMetrics(sValuePtr->tkfont, &fm); + Tk_UnderlineChars(display, dst, stylePtr->fgGC, sValuePtr->tkfont, + ciPtr->chars + offsetChars, offsetX, + y + baseline - sValuePtr->offset + - fm.descent - (fm.ascent * 3) / 10, + 0, numChars); + } + } +} + +/* + *-------------------------------------------------------------- + * + * CharUndisplayProc -- + * + * This procedure is called when a character chunk is no + * longer going to be displayed. It frees up resources + * that were allocated to display the chunk. + * + * Results: + * None. + * + * Side effects: + * Memory and other resources get freed. + * + *-------------------------------------------------------------- + */ + +static void +CharUndisplayProc(textPtr, chunkPtr) + TkText *textPtr; /* Overall information about text + * widget. */ + TkTextDispChunk *chunkPtr; /* Chunk that is about to be freed. */ +{ + CharInfo *ciPtr = (CharInfo *) chunkPtr->clientData; + + ckfree((char *) ciPtr); +} + +/* + *-------------------------------------------------------------- + * + * CharMeasureProc -- + * + * This procedure is called to determine which character in + * a character chunk lies over a given x-coordinate. + * + * Results: + * The return value is the index *within the chunk* of the + * character that covers the position given by "x". + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +CharMeasureProc(chunkPtr, x) + TkTextDispChunk *chunkPtr; /* Chunk containing desired coord. */ + int x; /* X-coordinate, in same coordinate + * system as chunkPtr->x. */ +{ + CharInfo *ciPtr = (CharInfo *) chunkPtr->clientData; + int endX; + + return MeasureChars(chunkPtr->stylePtr->sValuePtr->tkfont, ciPtr->chars, + chunkPtr->numChars-1, chunkPtr->x, x, 0, &endX); +} + +/* + *-------------------------------------------------------------- + * + * CharBboxProc -- + * + * This procedure is called to compute the bounding box of + * the area occupied by a single character. + * + * Results: + * There is no return value. *xPtr and *yPtr are filled in + * with the coordinates of the upper left corner of the + * character, and *widthPtr and *heightPtr are filled in with + * the dimensions of the character in pixels. Note: not all + * of the returned bbox is necessarily visible on the screen + * (the rightmost part might be off-screen to the right, + * and the bottommost part might be off-screen to the bottom). + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static void +CharBboxProc(chunkPtr, index, y, lineHeight, baseline, xPtr, yPtr, + widthPtr, heightPtr) + TkTextDispChunk *chunkPtr; /* Chunk containing desired char. */ + int index; /* Index of desired character within + * the chunk. */ + int y; /* Topmost pixel in area allocated + * for this line. */ + int lineHeight; /* Height of line, in pixels. */ + int baseline; /* Location of line's baseline, in + * pixels measured down from y. */ + int *xPtr, *yPtr; /* Gets filled in with coords of + * character's upper-left pixel. + * X-coord is in same coordinate + * system as chunkPtr->x. */ + int *widthPtr; /* Gets filled in with width of + * character, in pixels. */ + int *heightPtr; /* Gets filled in with height of + * character, in pixels. */ +{ + CharInfo *ciPtr = (CharInfo *) chunkPtr->clientData; + int maxX; + + maxX = chunkPtr->width + chunkPtr->x; + MeasureChars(chunkPtr->stylePtr->sValuePtr->tkfont, ciPtr->chars, index, + chunkPtr->x, 1000000, 0, xPtr); + + if (index == ciPtr->numChars) { + /* + * This situation only happens if the last character in a line + * is a space character, in which case it absorbs all of the + * extra space in the line (see TkTextCharLayoutProc). + */ + + *widthPtr = maxX - *xPtr; + } else if ((ciPtr->chars[index] == '\t') + && (index == (ciPtr->numChars-1))) { + /* + * The desired character is a tab character that terminates a + * chunk; give it all the space left in the chunk. + */ + + *widthPtr = maxX - *xPtr; + } else { + MeasureChars(chunkPtr->stylePtr->sValuePtr->tkfont, + ciPtr->chars + index, 1, *xPtr, 1000000, 0, widthPtr); + if (*widthPtr > maxX) { + *widthPtr = maxX - *xPtr; + } else { + *widthPtr -= *xPtr; + } + } + *yPtr = y + baseline - chunkPtr->minAscent; + *heightPtr = chunkPtr->minAscent + chunkPtr->minDescent; +} + +/* + *---------------------------------------------------------------------- + * + * AdjustForTab -- + * + * This procedure is called to move a series of chunks right + * in order to align them with a tab stop. + * + * Results: + * None. + * + * Side effects: + * The width of chunkPtr gets adjusted so that it absorbs the + * extra space due to the tab. The x locations in all the chunks + * after chunkPtr are adjusted rightward to align with the tab + * stop given by tabArrayPtr and index. + * + *---------------------------------------------------------------------- + */ + +static void +AdjustForTab(textPtr, tabArrayPtr, index, chunkPtr) + TkText *textPtr; /* Information about the text widget as + * a whole. */ + TkTextTabArray *tabArrayPtr; /* Information about the tab stops + * that apply to this line. May be + * NULL to indicate default tabbing + * (every 8 chars). */ + int index; /* Index of current tab stop. */ + TkTextDispChunk *chunkPtr; /* Chunk whose last character is + * the tab; the following chunks + * contain information to be shifted + * right. */ + +{ + int x, desired, delta, width, decimal, i, gotDigit; + TkTextDispChunk *chunkPtr2, *decimalChunkPtr; + CharInfo *ciPtr; + int tabX, prev, spaceWidth; + char *p; + TkTextTabAlign alignment; + + if (chunkPtr->nextPtr == NULL) { + /* + * Nothing after the actual tab; just return. + */ + + return; + } + + /* + * If no tab information has been given, do the usual thing: + * round up to the next boundary of 8 average-sized characters. + */ + + x = chunkPtr->nextPtr->x; + if ((tabArrayPtr == NULL) || (tabArrayPtr->numTabs == 0)) { + /* + * No tab information has been given, so use the default + * interpretation of tabs. + */ + + desired = NextTabStop(textPtr->tkfont, x, 0); + goto update; + } + + if (index < tabArrayPtr->numTabs) { + alignment = tabArrayPtr->tabs[index].alignment; + tabX = tabArrayPtr->tabs[index].location; + } else { + /* + * Ran out of tab stops; compute a tab position by extrapolating + * from the last two tab positions. + */ + + if (tabArrayPtr->numTabs > 1) { + prev = tabArrayPtr->tabs[tabArrayPtr->numTabs-2].location; + } else { + prev = 0; + } + alignment = tabArrayPtr->tabs[tabArrayPtr->numTabs-1].alignment; + tabX = tabArrayPtr->tabs[tabArrayPtr->numTabs-1].location + + (index + 1 - tabArrayPtr->numTabs) + * (tabArrayPtr->tabs[tabArrayPtr->numTabs-1].location - prev); + } + + if (alignment == LEFT) { + desired = tabX; + goto update; + } + + if ((alignment == CENTER) || (alignment == RIGHT)) { + /* + * Compute the width of all the information in the tab group, + * then use it to pick a desired location. + */ + + width = 0; + for (chunkPtr2 = chunkPtr->nextPtr; chunkPtr2 != NULL; + chunkPtr2 = chunkPtr2->nextPtr) { + width += chunkPtr2->width; + } + if (alignment == CENTER) { + desired = tabX - width/2; + } else { + desired = tabX - width; + } + goto update; + } + + /* + * Must be numeric alignment. Search through the text to be + * tabbed, looking for the last , or . before the first character + * that isn't a number, comma, period, or sign. + */ + + decimalChunkPtr = NULL; + decimal = gotDigit = 0; + for (chunkPtr2 = chunkPtr->nextPtr; chunkPtr2 != NULL; + chunkPtr2 = chunkPtr2->nextPtr) { + if (chunkPtr2->displayProc != CharDisplayProc) { + continue; + } + ciPtr = (CharInfo *) chunkPtr2->clientData; + for (p = ciPtr->chars, i = 0; i < ciPtr->numChars; p++, i++) { + if (isdigit(UCHAR(*p))) { + gotDigit = 1; + } else if ((*p == '.') || (*p == ',')) { + decimal = p-ciPtr->chars; + decimalChunkPtr = chunkPtr2; + } else if (gotDigit) { + if (decimalChunkPtr == NULL) { + decimal = p-ciPtr->chars; + decimalChunkPtr = chunkPtr2; + } + goto endOfNumber; + } + } + } + endOfNumber: + if (decimalChunkPtr != NULL) { + int curX; + + ciPtr = (CharInfo *) decimalChunkPtr->clientData; + MeasureChars(decimalChunkPtr->stylePtr->sValuePtr->tkfont, + ciPtr->chars, decimal, decimalChunkPtr->x, 1000000, 0, &curX); + desired = tabX - (curX - x); + goto update; + } else { + /* + * There wasn't a decimal point. Right justify the text. + */ + + width = 0; + for (chunkPtr2 = chunkPtr->nextPtr; chunkPtr2 != NULL; + chunkPtr2 = chunkPtr2->nextPtr) { + width += chunkPtr2->width; + } + desired = tabX - width; + } + + /* + * Shift all of the chunks to the right so that the left edge is + * at the desired location, then expand the chunk containing the + * tab. Be sure that the tab occupies at least the width of a + * space character. + */ + + update: + delta = desired - x; + MeasureChars(textPtr->tkfont, " ", 1, 0, INT_MAX, 0, &spaceWidth); + if (delta < spaceWidth) { + delta = spaceWidth; + } + for (chunkPtr2 = chunkPtr->nextPtr; chunkPtr2 != NULL; + chunkPtr2 = chunkPtr2->nextPtr) { + chunkPtr2->x += delta; + } + chunkPtr->width += delta; +} + +/* + *---------------------------------------------------------------------- + * + * SizeOfTab -- + * + * This returns an estimate of the amount of white space that will + * be consumed by a tab. + * + * Results: + * The return value is the minimum number of pixels that will + * be occupied by the index'th tab of tabArrayPtr, assuming that + * the current position on the line is x and the end of the + * line is maxX. For numeric tabs, this is a conservative + * estimate. The return value is always >= 0. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +SizeOfTab(textPtr, tabArrayPtr, index, x, maxX) + TkText *textPtr; /* Information about the text widget as + * a whole. */ + TkTextTabArray *tabArrayPtr; /* Information about the tab stops + * that apply to this line. NULL + * means use default tabbing (every + * 8 chars.) */ + int index; /* Index of current tab stop. */ + int x; /* Current x-location in line. Only + * used if tabArrayPtr == NULL. */ + int maxX; /* X-location of pixel just past the + * right edge of the line. */ +{ + int tabX, prev, result, spaceWidth; + TkTextTabAlign alignment; + + if ((tabArrayPtr == NULL) || (tabArrayPtr->numTabs == 0)) { + tabX = NextTabStop(textPtr->tkfont, x, 0); + return tabX - x; + } + if (index < tabArrayPtr->numTabs) { + tabX = tabArrayPtr->tabs[index].location; + alignment = tabArrayPtr->tabs[index].alignment; + } else { + /* + * Ran out of tab stops; compute a tab position by extrapolating + * from the last two tab positions. + */ + + if (tabArrayPtr->numTabs > 1) { + prev = tabArrayPtr->tabs[tabArrayPtr->numTabs-2].location; + } else { + prev = 0; + } + tabX = tabArrayPtr->tabs[tabArrayPtr->numTabs-1].location + + (index + 1 - tabArrayPtr->numTabs) + * (tabArrayPtr->tabs[tabArrayPtr->numTabs-1].location - prev); + alignment = tabArrayPtr->tabs[tabArrayPtr->numTabs-1].alignment; + } + if (alignment == CENTER) { + /* + * Be very careful in the arithmetic below, because maxX may + * be the largest positive number: watch out for integer + * overflow. + */ + + if ((maxX-tabX) < (tabX - x)) { + result = (maxX - x) - 2*(maxX - tabX); + } else { + result = 0; + } + goto done; + } + if (alignment == RIGHT) { + result = 0; + goto done; + } + + /* + * Note: this treats NUMERIC alignment the same as LEFT + * alignment, which is somewhat conservative. However, it's + * pretty tricky at this point to figure out exactly where + * the damn decimal point will be. + */ + + if (tabX > x) { + result = tabX - x; + } else { + result = 0; + } + + done: + MeasureChars(textPtr->tkfont, " ", 1, 0, INT_MAX, 0, &spaceWidth); + if (result < spaceWidth) { + result = spaceWidth; + } + return result; +} + +/* + *--------------------------------------------------------------------------- + * + * NextTabStop -- + * + * Given the current position, determine where the next default + * tab stop would be located. This procedure is called when the + * current chunk in the text has no tabs defined and so the default + * tab spacing for the font should be used. + * + * Results: + * The location in pixels of the next tab stop. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +static int +NextTabStop(tkfont, x, tabOrigin) + Tk_Font tkfont; /* Font in which chunk that contains tab + * stop will be drawn. */ + int x; /* X-position in pixels where last + * character was drawn. The next tab stop + * occurs somewhere after this location. */ + int tabOrigin; /* The origin for tab stops. May be + * non-zero if text has been scrolled. */ +{ + int tabWidth, rem; + + tabWidth = Tk_TextWidth(tkfont, "0", 1) * 8; + if (tabWidth == 0) { + tabWidth = 1; + } + + x += tabWidth; + rem = (x - tabOrigin) % tabWidth; + if (rem < 0) { + rem += tabWidth; + } + x -= rem; + return x; +} + +/* + *--------------------------------------------------------------------------- + * + * MeasureChars -- + * + * Determine the number of characters from the string that will fit + * in the given horizontal span. The measurement is done under the + * assumption that Tk_DisplayChars will be used to actually display + * the characters. + * + * If tabs are encountered in the string, they will be expanded + * to the next tab stop, unless the TK_IGNORE_TABS flag is specified. + * + * If a newline is encountered in the string, the line will be + * broken at that point, unless the TK_NEWSLINES_NOT_SPECIAL flag + * is specified. + * + * Results: + * The return value is the number of characters from source + * that fit in the span given by startX and maxX. *nextXPtr + * is filled in with the x-coordinate at which the first + * character that didn't fit would be drawn, if it were to + * be drawn. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +MeasureChars(tkfont, source, maxChars, startX, maxX, tabOrigin, nextXPtr) + Tk_Font tkfont; /* Font in which to draw characters. */ + CONST char *source; /* Characters to be displayed. Need not + * be NULL-terminated. */ + int maxChars; /* Maximum # of characters to consider from + * source. */ + int startX; /* X-position at which first character will + * be drawn. */ + int maxX; /* Don't consider any character that would + * cross this x-position. */ + int tabOrigin; /* X-location that serves as "origin" for + * tab stops. */ + int *nextXPtr; /* Return x-position of terminating + * character here. */ +{ + int curX, width, ch; + CONST char *special, *end, *start; + + ch = 0; /* lint. */ + curX = startX; + special = source; + end = source + maxChars; + for (start = source; start < end; ) { + if (start >= special) { + /* + * Find the next special character in the string. + */ + + for (special = start; special < end; special++) { + ch = *special; + if ((ch == '\t') || (ch == '\n')) { + break; + } + } + } + + /* + * Special points at the next special character (or the end of the + * string). Process characters between start and special. + */ + + if (curX >= maxX) { + break; + } + start += Tk_MeasureChars(tkfont, start, special - start, maxX - curX, + 0, &width); + curX += width; + if (start < special) { + /* + * No more chars fit in line. + */ + + break; + } + if (special < end) { + if (ch == '\t') { + start++; + } else { + break; + } + } + } + + *nextXPtr = curX; + return start - source; +} diff --git a/generic/tkTextImage.c b/generic/tkTextImage.c new file mode 100644 index 0000000..b5e363f --- /dev/null +++ b/generic/tkTextImage.c @@ -0,0 +1,898 @@ +/* + * tkImage.c -- + * + * This file contains code that allows images to be + * nested inside text widgets. It also implements the "image" + * widget command for texts. + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkTextImage.c 1.7 97/08/25 15:47:27 + */ + +#include "tk.h" +#include "tkText.h" +#include "tkPort.h" + +/* + * Definitions for alignment values: + */ + +#define ALIGN_BOTTOM 0 +#define ALIGN_CENTER 1 +#define ALIGN_TOP 2 +#define ALIGN_BASELINE 3 + +/* + * Macro that determines the size of an embedded image segment: + */ + +#define EI_SEG_SIZE ((unsigned) (Tk_Offset(TkTextSegment, body) \ + + sizeof(TkTextEmbImage))) + +/* + * Prototypes for procedures defined in this file: + */ + +static int AlignParseProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, Tk_Window tkwin, char *value, + char *widgRec, int offset)); +static char * AlignPrintProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin, char *widgRec, int offset, + Tcl_FreeProc **freeProcPtr)); +static TkTextSegment * EmbImageCleanupProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static void EmbImageCheckProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static void EmbImageBboxProc _ANSI_ARGS_((TkTextDispChunk *chunkPtr, + int index, int y, int lineHeight, int baseline, + int *xPtr, int *yPtr, int *widthPtr, + int *heightPtr)); +static int EmbImageConfigure _ANSI_ARGS_((TkText *textPtr, + TkTextSegment *eiPtr, int argc, char **argv)); +static int EmbImageDeleteProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr, int treeGone)); +static void EmbImageDisplayProc _ANSI_ARGS_(( + TkTextDispChunk *chunkPtr, int x, int y, + int lineHeight, int baseline, Display *display, + Drawable dst, int screenY)); +static int EmbImageLayoutProc _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *indexPtr, TkTextSegment *segPtr, + int offset, int maxX, int maxChars, + int noCharsYet, Tk_Uid wrapMode, + TkTextDispChunk *chunkPtr)); +static void EmbImageProc _ANSI_ARGS_((ClientData clientData, + int x, int y, int width, int height, + int imageWidth, int imageHeight)); + +/* + * The following structure declares the "embedded image" segment type. + */ + +static Tk_SegType tkTextEmbImageType = { + "image", /* name */ + 0, /* leftGravity */ + (Tk_SegSplitProc *) NULL, /* splitProc */ + EmbImageDeleteProc, /* deleteProc */ + EmbImageCleanupProc, /* cleanupProc */ + (Tk_SegLineChangeProc *) NULL, /* lineChangeProc */ + EmbImageLayoutProc, /* layoutProc */ + EmbImageCheckProc /* checkProc */ +}; + +/* + * Information used for parsing image configuration options: + */ + +static Tk_CustomOption alignOption = {AlignParseProc, AlignPrintProc, + (ClientData) NULL}; + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_CUSTOM, "-align", (char *) NULL, (char *) NULL, + "center", 0, TK_CONFIG_DONT_SET_DEFAULT, &alignOption}, + {TK_CONFIG_PIXELS, "-padx", (char *) NULL, (char *) NULL, + "0", Tk_Offset(TkTextEmbImage, padX), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_PIXELS, "-pady", (char *) NULL, (char *) NULL, + "0", Tk_Offset(TkTextEmbImage, padY), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_STRING, "-image", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextEmbImage, imageString), + TK_CONFIG_DONT_SET_DEFAULT|TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-name", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextEmbImage, imageName), + TK_CONFIG_DONT_SET_DEFAULT|TK_CONFIG_NULL_OK}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + *-------------------------------------------------------------- + * + * TkTextImageCmd -- + * + * This procedure implements the "image" widget command + * for text widgets. See the user documentation for details + * on what it does. + * + * Results: + * A standard Tcl result or error. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +TkTextImageCmd(textPtr, interp, argc, argv) + register TkText *textPtr; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. Someone else has already + * parsed this command enough to know that + * argv[1] is "image". */ +{ + size_t length; + register TkTextSegment *eiPtr; + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " image option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + length = strlen(argv[2]); + if ((strncmp(argv[2], "cget", length) == 0) && (length >= 2)) { + TkTextIndex index; + TkTextSegment *eiPtr; + + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " image cget index option\"", + (char *) NULL); + return TCL_ERROR; + } + if (TkTextGetIndex(interp, textPtr, argv[3], &index) != TCL_OK) { + return TCL_ERROR; + } + eiPtr = TkTextIndexToSeg(&index, (int *) NULL); + if (eiPtr->typePtr != &tkTextEmbImageType) { + Tcl_AppendResult(interp, "no embedded image at index \"", + argv[3], "\"", (char *) NULL); + return TCL_ERROR; + } + return Tk_ConfigureValue(interp, textPtr->tkwin, configSpecs, + (char *) &eiPtr->body.ei, argv[4], 0); + } else if ((strncmp(argv[2], "configure", length) == 0) && (length >= 2)) { + TkTextIndex index; + TkTextSegment *eiPtr; + + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " image configure index ?option value ...?\"", + (char *) NULL); + return TCL_ERROR; + } + if (TkTextGetIndex(interp, textPtr, argv[3], &index) != TCL_OK) { + return TCL_ERROR; + } + eiPtr = TkTextIndexToSeg(&index, (int *) NULL); + if (eiPtr->typePtr != &tkTextEmbImageType) { + Tcl_AppendResult(interp, "no embedded image at index \"", + argv[3], "\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 4) { + return Tk_ConfigureInfo(interp, textPtr->tkwin, configSpecs, + (char *) &eiPtr->body.ei, (char *) NULL, 0); + } else if (argc == 5) { + return Tk_ConfigureInfo(interp, textPtr->tkwin, configSpecs, + (char *) &eiPtr->body.ei, argv[4], 0); + } else { + TkTextChanged(textPtr, &index, &index); + return EmbImageConfigure(textPtr, eiPtr, argc-4, argv+4); + } + } else if ((strncmp(argv[2], "create", length) == 0) && (length >= 2)) { + TkTextIndex index; + int lineIndex; + + /* + * Add a new image. Find where to put the new image, and + * mark that position for redisplay. + */ + + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " image create index ?option value ...?\"", + (char *) NULL); + return TCL_ERROR; + } + if (TkTextGetIndex(interp, textPtr, argv[3], &index) != TCL_OK) { + return TCL_ERROR; + } + + /* + * Don't allow insertions on the last (dummy) line of the text. + */ + + lineIndex = TkBTreeLineIndex(index.linePtr); + if (lineIndex == TkBTreeNumLines(textPtr->tree)) { + lineIndex--; + TkTextMakeIndex(textPtr->tree, lineIndex, 1000000, &index); + } + + /* + * Create the new image segment and initialize it. + */ + + eiPtr = (TkTextSegment *) ckalloc(EI_SEG_SIZE); + eiPtr->typePtr = &tkTextEmbImageType; + eiPtr->size = 1; + eiPtr->body.ei.textPtr = textPtr; + eiPtr->body.ei.linePtr = NULL; + eiPtr->body.ei.imageName = NULL; + eiPtr->body.ei.imageString = NULL; + eiPtr->body.ei.name = NULL; + eiPtr->body.ei.image = NULL; + eiPtr->body.ei.align = ALIGN_CENTER; + eiPtr->body.ei.padX = eiPtr->body.ei.padY = 0; + eiPtr->body.ei.chunkCount = 0; + + /* + * Link the segment into the text widget, then configure it (delete + * it again if the configuration fails). + */ + + TkTextChanged(textPtr, &index, &index); + TkBTreeLinkSegment(eiPtr, &index); + if (EmbImageConfigure(textPtr, eiPtr, argc-4, argv+4) != TCL_OK) { + TkTextIndex index2; + + TkTextIndexForwChars(&index, 1, &index2); + TkBTreeDeleteChars(&index, &index2); + return TCL_ERROR; + } + } else if (strncmp(argv[2], "names", length) == 0) { + Tcl_HashSearch search; + Tcl_HashEntry *hPtr; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " image names\"", (char *) NULL); + return TCL_ERROR; + } + for (hPtr = Tcl_FirstHashEntry(&textPtr->imageTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + Tcl_AppendElement(interp, + Tcl_GetHashKey(&textPtr->markTable, hPtr)); + } + } else { + Tcl_AppendResult(interp, "bad image option \"", argv[2], + "\": must be cget, configure, create, or names", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * EmbImageConfigure -- + * + * This procedure is called to handle configuration options + * for an embedded image, using an argc/argv list. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message.. + * + * Side effects: + * Configuration information for the embedded image changes, + * such as alignment, or name of the image. + * + *-------------------------------------------------------------- + */ + +static int +EmbImageConfigure(textPtr, eiPtr, argc, argv) + TkText *textPtr; /* Information about text widget that + * contains embedded image. */ + TkTextSegment *eiPtr; /* Embedded image to be configured. */ + int argc; /* Number of strings in argv. */ + char **argv; /* Array of strings describing configuration + * options. */ +{ + Tk_Image image; + Tcl_DString newName; + Tcl_HashEntry *hPtr; + Tcl_HashSearch search; + int new; + char *name; + int count = 0; /* The counter for picking a unique name */ + int conflict = 0; /* True if we have a name conflict */ + unsigned int len; /* length of image name */ + + if (Tk_ConfigureWidget(textPtr->interp, textPtr->tkwin, configSpecs, + argc, argv, (char *) &eiPtr->body.ei,TK_CONFIG_ARGV_ONLY) + != TCL_OK) { + return TCL_ERROR; + } + + /* + * Create the image. Save the old image around and don't free it + * until after the new one is allocated. This keeps the reference + * count from going to zero so the image doesn't have to be recreated + * if it hasn't changed. + */ + + if (eiPtr->body.ei.imageString != NULL) { + image = Tk_GetImage(textPtr->interp, textPtr->tkwin, eiPtr->body.ei.imageString, + EmbImageProc, (ClientData) eiPtr); + if (image == NULL) { + return TCL_ERROR; + } + } else { + image = NULL; + } + if (eiPtr->body.ei.image != NULL) { + Tk_FreeImage(eiPtr->body.ei.image); + } + eiPtr->body.ei.image = image; + + if (eiPtr->body.ei.name != NULL) { + return TCL_OK; + } + + /* + * Find a unique name for this image. Use imageName (or imageString) + * if available, otherwise tack on a #nn and use it. If a name is already + * associated with this image, delete the name. + */ + + name = eiPtr->body.ei.imageName; + if (name == NULL) { + name = eiPtr->body.ei.imageString; + } + if (name == NULL) { + Tcl_AppendResult(textPtr->interp,"Either a \"-name\" ", + "or a \"-image\" argument must be provided ", + "to the \"image create\" subcommand.", + (char *) NULL); + return TCL_ERROR; + } + len = strlen(name); + for (hPtr = Tcl_FirstHashEntry(&textPtr->imageTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + char *haveName = Tcl_GetHashKey(&textPtr->imageTable, hPtr); + if (strncmp(name, haveName, len) == 0) { + new = 0; + sscanf(haveName+len,"#%d",&new); + if (new > count) { + count = new; + } + if (len == (int) strlen(haveName)) { + conflict = 1; + } + } + } + + Tcl_DStringInit(&newName); + Tcl_DStringAppend(&newName,name, -1); + + if (conflict) { + char buf[10]; + sprintf(buf, "#%d",count+1); + Tcl_DStringAppend(&newName,buf, -1); + } + name = Tcl_DStringValue(&newName); + hPtr = Tcl_CreateHashEntry(&textPtr->imageTable, name, &new); + Tcl_SetHashValue(hPtr, eiPtr); + Tcl_AppendResult(textPtr->interp, name , (char *) NULL); + eiPtr->body.ei.name = ckalloc((unsigned) Tcl_DStringLength(&newName)+1); + strcpy(eiPtr->body.ei.name,name); + Tcl_DStringFree(&newName); + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * AlignParseProc -- + * + * This procedure is invoked by Tk_ConfigureWidget during + * option processing to handle "-align" options for embedded + * images. + * + * Results: + * A standard Tcl return value. + * + * Side effects: + * The alignment for the embedded image may change. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +AlignParseProc(clientData, interp, tkwin, value, widgRec, offset) + ClientData clientData; /* Not used.*/ + Tcl_Interp *interp; /* Used for reporting errors. */ + Tk_Window tkwin; /* Window for text widget. */ + char *value; /* Value of option. */ + char *widgRec; /* Pointer to TkTextEmbWindow + * structure. */ + int offset; /* Offset into item (ignored). */ +{ + register TkTextEmbImage *embPtr = (TkTextEmbImage *) widgRec; + + if (strcmp(value, "baseline") == 0) { + embPtr->align = ALIGN_BASELINE; + } else if (strcmp(value, "bottom") == 0) { + embPtr->align = ALIGN_BOTTOM; + } else if (strcmp(value, "center") == 0) { + embPtr->align = ALIGN_CENTER; + } else if (strcmp(value, "top") == 0) { + embPtr->align = ALIGN_TOP; + } else { + Tcl_AppendResult(interp, "bad alignment \"", value, + "\": must be baseline, bottom, center, or top", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * AlignPrintProc -- + * + * This procedure is invoked by the Tk configuration code + * to produce a printable string for the "-align" configuration + * option for embedded images. + * + * Results: + * The return value is a string describing the embedded + * images's current alignment. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static char * +AlignPrintProc(clientData, tkwin, widgRec, offset, freeProcPtr) + ClientData clientData; /* Ignored. */ + Tk_Window tkwin; /* Window for text widget. */ + char *widgRec; /* Pointer to TkTextEmbImage + * structure. */ + int offset; /* Ignored. */ + Tcl_FreeProc **freeProcPtr; /* Pointer to variable to fill in with + * information about how to reclaim + * storage for return string. */ +{ + switch (((TkTextEmbImage *) widgRec)->align) { + case ALIGN_BASELINE: + return "baseline"; + case ALIGN_BOTTOM: + return "bottom"; + case ALIGN_CENTER: + return "center"; + case ALIGN_TOP: + return "top"; + default: + return "??"; + } +} + +/* + *-------------------------------------------------------------- + * + * EmbImageDeleteProc -- + * + * This procedure is invoked by the text B-tree code whenever + * an embedded image lies in a range of characters being deleted. + * + * Results: + * Returns 0 to indicate that the deletion has been accepted. + * + * Side effects: + * The embedded image is deleted, if it exists, and any resources + * associated with it are released. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +EmbImageDeleteProc(eiPtr, linePtr, treeGone) + TkTextSegment *eiPtr; /* Segment being deleted. */ + TkTextLine *linePtr; /* Line containing segment. */ + int treeGone; /* Non-zero means the entire tree is + * being deleted, so everything must + * get cleaned up. */ +{ + Tcl_HashEntry *hPtr; + + if (eiPtr->body.ei.image != NULL) { + hPtr = Tcl_FindHashEntry(&eiPtr->body.ei.textPtr->imageTable, + eiPtr->body.ei.name); + if (hPtr != NULL) { + /* + * (It's possible for there to be no hash table entry for this + * image, if an error occurred while creating the image segment + * but before the image got added to the table) + */ + + Tcl_DeleteHashEntry(hPtr); + } + Tk_FreeImage(eiPtr->body.ei.image); + } + Tk_FreeOptions(configSpecs, (char *) &eiPtr->body.ei, + eiPtr->body.ei.textPtr->display, 0); + if (eiPtr->body.ei.name != NULL) { + ckfree(eiPtr->body.ei.name); + } + ckfree((char *) eiPtr); + return 0; +} + +/* + *-------------------------------------------------------------- + * + * EmbImageCleanupProc -- + * + * This procedure is invoked by the B-tree code whenever a + * segment containing an embedded image is moved from one + * line to another. + * + * Results: + * None. + * + * Side effects: + * The linePtr field of the segment gets updated. + * + *-------------------------------------------------------------- + */ + +static TkTextSegment * +EmbImageCleanupProc(eiPtr, linePtr) + TkTextSegment *eiPtr; /* Mark segment that's being moved. */ + TkTextLine *linePtr; /* Line that now contains segment. */ +{ + eiPtr->body.ei.linePtr = linePtr; + return eiPtr; +} + +/* + *-------------------------------------------------------------- + * + * EmbImageLayoutProc -- + * + * This procedure is the "layoutProc" for embedded image + * segments. + * + * Results: + * 1 is returned to indicate that the segment should be + * displayed. The chunkPtr structure is filled in. + * + * Side effects: + * None, except for filling in chunkPtr. + * + *-------------------------------------------------------------- + */ + + /*ARGSUSED*/ +static int +EmbImageLayoutProc(textPtr, indexPtr, eiPtr, offset, maxX, maxChars, + noCharsYet, wrapMode, chunkPtr) + TkText *textPtr; /* Text widget being layed out. */ + TkTextIndex *indexPtr; /* Identifies first character in chunk. */ + TkTextSegment *eiPtr; /* Segment corresponding to indexPtr. */ + int offset; /* Offset within segPtr corresponding to + * indexPtr (always 0). */ + int maxX; /* Chunk must not occupy pixels at this + * position or higher. */ + int maxChars; /* Chunk must not include more than this + * many characters. */ + int noCharsYet; /* Non-zero means no characters have been + * assigned to this line yet. */ + Tk_Uid wrapMode; /* Wrap mode to use for line: tkTextCharUid, + * tkTextNoneUid, or tkTextWordUid. */ + register TkTextDispChunk *chunkPtr; + /* Structure to fill in with information + * about this chunk. The x field has already + * been set by the caller. */ +{ + int width, height; + + if (offset != 0) { + panic("Non-zero offset in EmbImageLayoutProc"); + } + + /* + * See if there's room for this image on this line. + */ + + if (eiPtr->body.ei.image == NULL) { + width = 0; + height = 0; + } else { + Tk_SizeOfImage(eiPtr->body.ei.image, &width, &height); + width += 2*eiPtr->body.ei.padX; + height += 2*eiPtr->body.ei.padY; + } + if ((width > (maxX - chunkPtr->x)) + && !noCharsYet && (textPtr->wrapMode != tkTextNoneUid)) { + return 0; + } + + /* + * Fill in the chunk structure. + */ + + chunkPtr->displayProc = EmbImageDisplayProc; + chunkPtr->undisplayProc = (Tk_ChunkUndisplayProc *) NULL; + chunkPtr->measureProc = (Tk_ChunkMeasureProc *) NULL; + chunkPtr->bboxProc = EmbImageBboxProc; + chunkPtr->numChars = 1; + if (eiPtr->body.ei.align == ALIGN_BASELINE) { + chunkPtr->minAscent = height - eiPtr->body.ei.padY; + chunkPtr->minDescent = eiPtr->body.ei.padY; + chunkPtr->minHeight = 0; + } else { + chunkPtr->minAscent = 0; + chunkPtr->minDescent = 0; + chunkPtr->minHeight = height; + } + chunkPtr->width = width; + chunkPtr->breakIndex = -1; + chunkPtr->breakIndex = 1; + chunkPtr->clientData = (ClientData) eiPtr; + eiPtr->body.ei.chunkCount += 1; + return 1; +} + +/* + *-------------------------------------------------------------- + * + * EmbImageCheckProc -- + * + * This procedure is invoked by the B-tree code to perform + * consistency checks on embedded images. + * + * Results: + * None. + * + * Side effects: + * The procedure panics if it detects anything wrong with + * the embedded image. + * + *-------------------------------------------------------------- + */ + +static void +EmbImageCheckProc(eiPtr, linePtr) + TkTextSegment *eiPtr; /* Segment to check. */ + TkTextLine *linePtr; /* Line containing segment. */ +{ + if (eiPtr->nextPtr == NULL) { + panic("EmbImageCheckProc: embedded image is last segment in line"); + } + if (eiPtr->size != 1) { + panic("EmbImageCheckProc: embedded image has size %d", eiPtr->size); + } +} + +/* + *-------------------------------------------------------------- + * + * EmbImageDisplayProc -- + * + * This procedure is invoked by the text displaying code + * when it is time to actually draw an embedded image + * chunk on the screen. + * + * Results: + * None. + * + * Side effects: + * The embedded image gets moved to the correct location + * and drawn onto the display. + * + *-------------------------------------------------------------- + */ + +static void +EmbImageDisplayProc(chunkPtr, x, y, lineHeight, baseline, display, dst, screenY) + TkTextDispChunk *chunkPtr; /* Chunk that is to be drawn. */ + int x; /* X-position in dst at which to + * draw this chunk (differs from + * the x-position in the chunk because + * of scrolling). */ + int y; /* Top of rectangular bounding box + * for line: tells where to draw this + * chunk in dst (x-position is in + * the chunk itself). */ + int lineHeight; /* Total height of line. */ + int baseline; /* Offset of baseline from y. */ + Display *display; /* Display to use for drawing. */ + Drawable dst; /* Pixmap or window in which to draw */ + int screenY; /* Y-coordinate in text window that + * corresponds to y. */ +{ + TkTextSegment *eiPtr = (TkTextSegment *) chunkPtr->clientData; + int lineX, imageX, imageY, width, height; + Tk_Image image; + + image = eiPtr->body.ei.image; + if (image == NULL) { + return; + } + if ((x + chunkPtr->width) <= 0) { + return; + } + + /* + * Compute the image's location and size in the text widget, taking + * into account the align value for the image. + */ + + EmbImageBboxProc(chunkPtr, 0, y, lineHeight, baseline, &lineX, + &imageY, &width, &height); + imageX = lineX - chunkPtr->x + x; + + Tk_RedrawImage(image, 0, 0, width, height, dst, + imageX, imageY); +} + +/* + *-------------------------------------------------------------- + * + * EmbImageBboxProc -- + * + * This procedure is called to compute the bounding box of + * the area occupied by an embedded image. + * + * Results: + * There is no return value. *xPtr and *yPtr are filled in + * with the coordinates of the upper left corner of the + * image, and *widthPtr and *heightPtr are filled in with + * the dimensions of the image in pixels. Note: not all + * of the returned bbox is necessarily visible on the screen + * (the rightmost part might be off-screen to the right, + * and the bottommost part might be off-screen to the bottom). + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static void +EmbImageBboxProc(chunkPtr, index, y, lineHeight, baseline, xPtr, yPtr, + widthPtr, heightPtr) + TkTextDispChunk *chunkPtr; /* Chunk containing desired char. */ + int index; /* Index of desired character within + * the chunk. */ + int y; /* Topmost pixel in area allocated + * for this line. */ + int lineHeight; /* Total height of line. */ + int baseline; /* Location of line's baseline, in + * pixels measured down from y. */ + int *xPtr, *yPtr; /* Gets filled in with coords of + * character's upper-left pixel. */ + int *widthPtr; /* Gets filled in with width of + * character, in pixels. */ + int *heightPtr; /* Gets filled in with height of + * character, in pixels. */ +{ + TkTextSegment *eiPtr = (TkTextSegment *) chunkPtr->clientData; + Tk_Image image; + + image = eiPtr->body.ei.image; + if (image != NULL) { + Tk_SizeOfImage(image, widthPtr, heightPtr); + } else { + *widthPtr = 0; + *heightPtr = 0; + } + *xPtr = chunkPtr->x + eiPtr->body.ei.padX; + switch (eiPtr->body.ei.align) { + case ALIGN_BOTTOM: + *yPtr = y + (lineHeight - *heightPtr - eiPtr->body.ei.padY); + break; + case ALIGN_CENTER: + *yPtr = y + (lineHeight - *heightPtr)/2; + break; + case ALIGN_TOP: + *yPtr = y + eiPtr->body.ei.padY; + break; + case ALIGN_BASELINE: + *yPtr = y + (baseline - *heightPtr); + break; + } +} + +/* + *-------------------------------------------------------------- + * + * TkTextImageIndex -- + * + * Given the name of an embedded image within a text widget, + * returns an index corresponding to the image's position + * in the text. + * + * Results: + * The return value is 1 if there is an embedded image by + * the given name in the text widget, 0 otherwise. If the + * image exists, *indexPtr is filled in with its index. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkTextImageIndex(textPtr, name, indexPtr) + TkText *textPtr; /* Text widget containing image. */ + char *name; /* Name of image. */ + TkTextIndex *indexPtr; /* Index information gets stored here. */ +{ + Tcl_HashEntry *hPtr; + TkTextSegment *eiPtr; + + hPtr = Tcl_FindHashEntry(&textPtr->imageTable, name); + if (hPtr == NULL) { + return 0; + } + eiPtr = (TkTextSegment *) Tcl_GetHashValue(hPtr); + indexPtr->tree = textPtr->tree; + indexPtr->linePtr = eiPtr->body.ei.linePtr; + indexPtr->charIndex = TkTextSegToOffset(eiPtr, indexPtr->linePtr); + return 1; +} + +/* + *-------------------------------------------------------------- + * + * EmbImageProc -- + * + * This procedure is called by the image code whenever an + * image or its contents changes. + * + * Results: + * None. + * + * Side effects: + * The image will be redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +EmbImageProc(clientData, x, y, width, height, imgWidth, imgHeight) + ClientData clientData; /* Pointer to widget record. */ + int x, y; /* Upper left pixel (within image) + * that must be redisplayed. */ + int width, height; /* Dimensions of area to redisplay + * (may be <= 0). */ + int imgWidth, imgHeight; /* New dimensions of image. */ + +{ + TkTextSegment *eiPtr = (TkTextSegment *) clientData; + TkTextIndex index; + + index.tree = eiPtr->body.ei.textPtr->tree; + index.linePtr = eiPtr->body.ei.linePtr; + index.charIndex = TkTextSegToOffset(eiPtr, eiPtr->body.ei.linePtr); + TkTextChanged(eiPtr->body.ei.textPtr, &index, &index); +} diff --git a/generic/tkTextIndex.c b/generic/tkTextIndex.c new file mode 100644 index 0000000..d88d88a --- /dev/null +++ b/generic/tkTextIndex.c @@ -0,0 +1,840 @@ +/* + * tkTextIndex.c -- + * + * This module provides procedures that manipulate indices for + * text widgets. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkTextIndex.c 1.15 97/06/17 17:49:24 + */ + +#include "default.h" +#include "tkPort.h" +#include "tkInt.h" +#include "tkText.h" + +/* + * Index to use to select last character in line (very large integer): + */ + +#define LAST_CHAR 1000000 + +/* + * Forward declarations for procedures defined later in this file: + */ + +static char * ForwBack _ANSI_ARGS_((char *string, + TkTextIndex *indexPtr)); +static char * StartEnd _ANSI_ARGS_(( char *string, + TkTextIndex *indexPtr)); + +/* + *-------------------------------------------------------------- + * + * TkTextMakeIndex -- + * + * Given a line index and a character index, look things up + * in the B-tree and fill in a TkTextIndex structure. + * + * Results: + * The structure at *indexPtr is filled in with information + * about the character at lineIndex and charIndex (or the + * closest existing character, if the specified one doesn't + * exist), and indexPtr is returned as result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +TkTextIndex * +TkTextMakeIndex(tree, lineIndex, charIndex, indexPtr) + TkTextBTree tree; /* Tree that lineIndex and charIndex refer + * to. */ + int lineIndex; /* Index of desired line (0 means first + * line of text). */ + int charIndex; /* Index of desired character. */ + TkTextIndex *indexPtr; /* Structure to fill in. */ +{ + register TkTextSegment *segPtr; + int index; + + indexPtr->tree = tree; + if (lineIndex < 0) { + lineIndex = 0; + charIndex = 0; + } + if (charIndex < 0) { + charIndex = 0; + } + indexPtr->linePtr = TkBTreeFindLine(tree, lineIndex); + if (indexPtr->linePtr == NULL) { + indexPtr->linePtr = TkBTreeFindLine(tree, TkBTreeNumLines(tree)); + charIndex = 0; + } + + /* + * Verify that the index is within the range of the line. + * If not, just use the index of the last character in the line. + */ + + for (index = 0, segPtr = indexPtr->linePtr->segPtr; ; + segPtr = segPtr->nextPtr) { + if (segPtr == NULL) { + indexPtr->charIndex = index-1; + break; + } + index += segPtr->size; + if (index > charIndex) { + indexPtr->charIndex = charIndex; + break; + } + } + return indexPtr; +} + +/* + *-------------------------------------------------------------- + * + * TkTextIndexToSeg -- + * + * Given an index, this procedure returns the segment and + * offset within segment for the index. + * + * Results: + * The return value is a pointer to the segment referred to + * by indexPtr; this will always be a segment with non-zero + * size. The variable at *offsetPtr is set to hold the + * integer offset within the segment of the character + * given by indexPtr. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +TkTextSegment * +TkTextIndexToSeg(indexPtr, offsetPtr) + TkTextIndex *indexPtr; /* Text index. */ + int *offsetPtr; /* Where to store offset within + * segment, or NULL if offset isn't + * wanted. */ +{ + register TkTextSegment *segPtr; + int offset; + + for (offset = indexPtr->charIndex, segPtr = indexPtr->linePtr->segPtr; + offset >= segPtr->size; + offset -= segPtr->size, segPtr = segPtr->nextPtr) { + /* Empty loop body. */ + } + if (offsetPtr != NULL) { + *offsetPtr = offset; + } + return segPtr; +} + +/* + *-------------------------------------------------------------- + * + * TkTextSegToOffset -- + * + * Given a segment pointer and the line containing it, this + * procedure returns the offset of the segment within its + * line. + * + * Results: + * The return value is the offset (within its line) of the + * first character in segPtr. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkTextSegToOffset(segPtr, linePtr) + TkTextSegment *segPtr; /* Segment whose offset is desired. */ + TkTextLine *linePtr; /* Line containing segPtr. */ +{ + TkTextSegment *segPtr2; + int offset; + + offset = 0; + for (segPtr2 = linePtr->segPtr; segPtr2 != segPtr; + segPtr2 = segPtr2->nextPtr) { + offset += segPtr2->size; + } + return offset; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextGetIndex -- + * + * Given a string, return the line and character indices that + * it describes. + * + * Results: + * The return value is a standard Tcl return result. If + * TCL_OK is returned, then everything went well and the index + * at *indexPtr is filled in; otherwise TCL_ERROR is returned + * and an error message is left in interp->result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkTextGetIndex(interp, textPtr, string, indexPtr) + Tcl_Interp *interp; /* Use this for error reporting. */ + TkText *textPtr; /* Information about text widget. */ + char *string; /* Textual description of position. */ + TkTextIndex *indexPtr; /* Index structure to fill in. */ +{ + register char *p; + char *end, *endOfBase; + Tcl_HashEntry *hPtr; + TkTextTag *tagPtr; + TkTextSearch search; + TkTextIndex first, last; + int wantLast, result; + char c; + + /* + *--------------------------------------------------------------------- + * Stage 1: check to see if the index consists of nothing but a mark + * name. We do this check now even though it's also done later, in + * order to allow mark names that include funny characters such as + * spaces or "+1c". + *--------------------------------------------------------------------- + */ + + if (TkTextMarkNameToIndex(textPtr, string, indexPtr) == TCL_OK) { + return TCL_OK; + } + + /* + *------------------------------------------------ + * Stage 2: start again by parsing the base index. + *------------------------------------------------ + */ + + indexPtr->tree = textPtr->tree; + + /* + * First look for the form "tag.first" or "tag.last" where "tag" + * is the name of a valid tag. Try to use up as much as possible + * of the string in this check (strrchr instead of strchr below). + * Doing the check now, and in this way, allows tag names to include + * funny characters like "@" or "+1c". + */ + + p = strrchr(string, '.'); + if (p != NULL) { + if ((p[1] == 'f') && (strncmp(p+1, "first", 5) == 0)) { + wantLast = 0; + endOfBase = p+6; + } else if ((p[1] == 'l') && (strncmp(p+1, "last", 4) == 0)) { + wantLast = 1; + endOfBase = p+5; + } else { + goto tryxy; + } + *p = 0; + hPtr = Tcl_FindHashEntry(&textPtr->tagTable, string); + *p = '.'; + if (hPtr == NULL) { + goto tryxy; + } + tagPtr = (TkTextTag *) Tcl_GetHashValue(hPtr); + TkTextMakeIndex(textPtr->tree, 0, 0, &first); + TkTextMakeIndex(textPtr->tree, TkBTreeNumLines(textPtr->tree), 0, + &last); + TkBTreeStartSearch(&first, &last, tagPtr, &search); + if (!TkBTreeCharTagged(&first, tagPtr) && !TkBTreeNextTag(&search)) { + Tcl_AppendResult(interp, + "text doesn't contain any characters tagged with \"", + Tcl_GetHashKey(&textPtr->tagTable, hPtr), "\"", + (char *) NULL); + return TCL_ERROR; + } + *indexPtr = search.curIndex; + if (wantLast) { + while (TkBTreeNextTag(&search)) { + *indexPtr = search.curIndex; + } + } + goto gotBase; + } + + tryxy: + if (string[0] == '@') { + /* + * Find character at a given x,y location in the window. + */ + + int x, y; + + p = string+1; + x = strtol(p, &end, 0); + if ((end == p) || (*end != ',')) { + goto error; + } + p = end+1; + y = strtol(p, &end, 0); + if (end == p) { + goto error; + } + TkTextPixelIndex(textPtr, x, y, indexPtr); + endOfBase = end; + goto gotBase; + } + + if (isdigit(UCHAR(string[0])) || (string[0] == '-')) { + int lineIndex, charIndex; + + /* + * Base is identified with line and character indices. + */ + + lineIndex = strtol(string, &end, 0) - 1; + if ((end == string) || (*end != '.')) { + goto error; + } + p = end+1; + if ((*p == 'e') && (strncmp(p, "end", 3) == 0)) { + charIndex = LAST_CHAR; + endOfBase = p+3; + } else { + charIndex = strtol(p, &end, 0); + if (end == p) { + goto error; + } + endOfBase = end; + } + TkTextMakeIndex(textPtr->tree, lineIndex, charIndex, indexPtr); + goto gotBase; + } + + for (p = string; *p != 0; p++) { + if (isspace(UCHAR(*p)) || (*p == '+') || (*p == '-')) { + break; + } + } + endOfBase = p; + if (string[0] == '.') { + /* + * See if the base position is the name of an embedded window. + */ + + c = *endOfBase; + *endOfBase = 0; + result = TkTextWindowIndex(textPtr, string, indexPtr); + *endOfBase = c; + if (result != 0) { + goto gotBase; + } + } + if ((string[0] == 'e') + && (strncmp(string, "end", (size_t) (endOfBase-string)) == 0)) { + /* + * Base position is end of text. + */ + + TkTextMakeIndex(textPtr->tree, TkBTreeNumLines(textPtr->tree), + 0, indexPtr); + goto gotBase; + } else { + /* + * See if the base position is the name of a mark. + */ + + c = *endOfBase; + *endOfBase = 0; + result = TkTextMarkNameToIndex(textPtr, string, indexPtr); + *endOfBase = c; + if (result == TCL_OK) { + goto gotBase; + } + + /* + * See if the base position is the name of an embedded image + */ + + c = *endOfBase; + *endOfBase = 0; + result = TkTextImageIndex(textPtr, string, indexPtr); + *endOfBase = c; + if (result != 0) { + goto gotBase; + } + } + goto error; + + /* + *------------------------------------------------------------------- + * Stage 3: process zero or more modifiers. Each modifier is either + * a keyword like "wordend" or "linestart", or it has the form + * "op count units" where op is + or -, count is a number, and units + * is "chars" or "lines". + *------------------------------------------------------------------- + */ + + gotBase: + p = endOfBase; + while (1) { + while (isspace(UCHAR(*p))) { + p++; + } + if (*p == 0) { + break; + } + + if ((*p == '+') || (*p == '-')) { + p = ForwBack(p, indexPtr); + } else { + p = StartEnd(p, indexPtr); + } + if (p == NULL) { + goto error; + } + } + return TCL_OK; + + error: + Tcl_AppendResult(interp, "bad text index \"", string, "\"", + (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextPrintIndex -- + * + * + * This procedure generates a string description of an index, + * suitable for reading in again later. + * + * Results: + * The characters pointed to by string are modified. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkTextPrintIndex(indexPtr, string) + TkTextIndex *indexPtr; /* Pointer to index. */ + char *string; /* Place to store the position. Must have + * at least TK_POS_CHARS characters. */ +{ + sprintf(string, "%d.%d", TkBTreeLineIndex(indexPtr->linePtr) + 1, + indexPtr->charIndex); +} + +/* + *-------------------------------------------------------------- + * + * TkTextIndexCmp -- + * + * Compare two indices to see which one is earlier in + * the text. + * + * Results: + * The return value is 0 if index1Ptr and index2Ptr refer + * to the same position in the file, -1 if index1Ptr refers + * to an earlier position than index2Ptr, and 1 otherwise. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkTextIndexCmp(index1Ptr, index2Ptr) + TkTextIndex *index1Ptr; /* First index. */ + TkTextIndex *index2Ptr; /* Second index. */ +{ + int line1, line2; + + if (index1Ptr->linePtr == index2Ptr->linePtr) { + if (index1Ptr->charIndex < index2Ptr->charIndex) { + return -1; + } else if (index1Ptr->charIndex > index2Ptr->charIndex) { + return 1; + } else { + return 0; + } + } + line1 = TkBTreeLineIndex(index1Ptr->linePtr); + line2 = TkBTreeLineIndex(index2Ptr->linePtr); + if (line1 < line2) { + return -1; + } + if (line1 > line2) { + return 1; + } + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * ForwBack -- + * + * This procedure handles +/- modifiers for indices to adjust + * the index forwards or backwards. + * + * Results: + * If the modifier in string is successfully parsed then the + * return value is the address of the first character after the + * modifier, and *indexPtr is updated to reflect the modifier. + * If there is a syntax error in the modifier then NULL is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static char * +ForwBack(string, indexPtr) + char *string; /* String to parse for additional info + * about modifier (count and units). + * Points to "+" or "-" that starts + * modifier. */ + TkTextIndex *indexPtr; /* Index to update as specified in string. */ +{ + register char *p; + char *end, *units; + int count, lineIndex; + size_t length; + + /* + * Get the count (how many units forward or backward). + */ + + p = string+1; + while (isspace(UCHAR(*p))) { + p++; + } + count = strtol(p, &end, 0); + if (end == p) { + return NULL; + } + p = end; + while (isspace(UCHAR(*p))) { + p++; + } + + /* + * Find the end of this modifier (next space or + or - character), + * then parse the unit specifier and update the position + * accordingly. + */ + + units = p; + while ((*p != 0) && !isspace(UCHAR(*p)) && (*p != '+') && (*p != '-')) { + p++; + } + length = p - units; + if ((*units == 'c') && (strncmp(units, "chars", length) == 0)) { + if (*string == '+') { + TkTextIndexForwChars(indexPtr, count, indexPtr); + } else { + TkTextIndexBackChars(indexPtr, count, indexPtr); + } + } else if ((*units == 'l') && (strncmp(units, "lines", length) == 0)) { + lineIndex = TkBTreeLineIndex(indexPtr->linePtr); + if (*string == '+') { + lineIndex += count; + } else { + lineIndex -= count; + + /* + * The check below retains the character position, even + * if the line runs off the start of the file. Without + * it, the character position will get reset to 0 by + * TkTextMakeIndex. + */ + + if (lineIndex < 0) { + lineIndex = 0; + } + } + TkTextMakeIndex(indexPtr->tree, lineIndex, indexPtr->charIndex, + indexPtr); + } else { + return NULL; + } + return p; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextIndexForwChars -- + * + * Given an index for a text widget, this procedure creates a + * new index that points "count" characters ahead of the source + * index. + * + * Results: + * *dstPtr is modified to refer to the character "count" characters + * after srcPtr, or to the last character in the file if there aren't + * "count" characters left in the file. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +void +TkTextIndexForwChars(srcPtr, count, dstPtr) + TkTextIndex *srcPtr; /* Source index. */ + int count; /* How many characters forward to + * move. May be negative. */ + TkTextIndex *dstPtr; /* Destination index: gets modified. */ +{ + TkTextLine *linePtr; + TkTextSegment *segPtr; + int lineLength; + + if (count < 0) { + TkTextIndexBackChars(srcPtr, -count, dstPtr); + return; + } + + *dstPtr = *srcPtr; + dstPtr->charIndex += count; + while (1) { + /* + * Compute the length of the current line. + */ + + lineLength = 0; + for (segPtr = dstPtr->linePtr->segPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + lineLength += segPtr->size; + } + + /* + * If the new index is in the same line then we're done. + * Otherwise go on to the next line. + */ + + if (dstPtr->charIndex < lineLength) { + return; + } + dstPtr->charIndex -= lineLength; + linePtr = TkBTreeNextLine(dstPtr->linePtr); + if (linePtr == NULL) { + dstPtr->charIndex = lineLength - 1; + return; + } + dstPtr->linePtr = linePtr; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkTextIndexBackChars -- + * + * Given an index for a text widget, this procedure creates a + * new index that points "count" characters earlier than the + * source index. + * + * Results: + * *dstPtr is modified to refer to the character "count" characters + * before srcPtr, or to the first character in the file if there aren't + * "count" characters earlier than srcPtr. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkTextIndexBackChars(srcPtr, count, dstPtr) + TkTextIndex *srcPtr; /* Source index. */ + int count; /* How many characters backward to + * move. May be negative. */ + TkTextIndex *dstPtr; /* Destination index: gets modified. */ +{ + TkTextSegment *segPtr; + int lineIndex; + + if (count < 0) { + TkTextIndexForwChars(srcPtr, -count, dstPtr); + return; + } + + *dstPtr = *srcPtr; + dstPtr->charIndex -= count; + lineIndex = -1; + while (dstPtr->charIndex < 0) { + /* + * Move back one line in the text. If we run off the beginning + * of the file then just return the first character in the text. + */ + + if (lineIndex < 0) { + lineIndex = TkBTreeLineIndex(dstPtr->linePtr); + } + if (lineIndex == 0) { + dstPtr->charIndex = 0; + return; + } + lineIndex--; + dstPtr->linePtr = TkBTreeFindLine(dstPtr->tree, lineIndex); + + /* + * Compute the length of the line and add that to dstPtr->charIndex. + */ + + for (segPtr = dstPtr->linePtr->segPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + dstPtr->charIndex += segPtr->size; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * StartEnd -- + * + * This procedure handles modifiers like "wordstart" and "lineend" + * to adjust indices forwards or backwards. + * + * Results: + * If the modifier is successfully parsed then the return value + * is the address of the first character after the modifier, and + * *indexPtr is updated to reflect the modifier. If there is a + * syntax error in the modifier then NULL is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static char * +StartEnd(string, indexPtr) + char *string; /* String to parse for additional info + * about modifier (count and units). + * Points to first character of modifer + * word. */ + TkTextIndex *indexPtr; /* Index to mdoify based on string. */ +{ + char *p; + int c, offset; + size_t length; + register TkTextSegment *segPtr; + + /* + * Find the end of the modifier word. + */ + + for (p = string; isalnum(UCHAR(*p)); p++) { + /* Empty loop body. */ + } + length = p-string; + if ((*string == 'l') && (strncmp(string, "lineend", length) == 0) + && (length >= 5)) { + indexPtr->charIndex = 0; + for (segPtr = indexPtr->linePtr->segPtr; segPtr != NULL; + segPtr = segPtr->nextPtr) { + indexPtr->charIndex += segPtr->size; + } + indexPtr->charIndex -= 1; + } else if ((*string == 'l') && (strncmp(string, "linestart", length) == 0) + && (length >= 5)) { + indexPtr->charIndex = 0; + } else if ((*string == 'w') && (strncmp(string, "wordend", length) == 0) + && (length >= 5)) { + int firstChar = 1; + + /* + * If the current character isn't part of a word then just move + * forward one character. Otherwise move forward until finding + * a character that isn't part of a word and stop there. + */ + + segPtr = TkTextIndexToSeg(indexPtr, &offset); + while (1) { + if (segPtr->typePtr == &tkTextCharType) { + c = segPtr->body.chars[offset]; + if (!isalnum(UCHAR(c)) && (c != '_')) { + break; + } + firstChar = 0; + } + offset += 1; + indexPtr->charIndex += 1; + if (offset >= segPtr->size) { + segPtr = TkTextIndexToSeg(indexPtr, &offset); + } + } + if (firstChar) { + TkTextIndexForwChars(indexPtr, 1, indexPtr); + } + } else if ((*string == 'w') && (strncmp(string, "wordstart", length) == 0) + && (length >= 5)) { + int firstChar = 1; + + /* + * Starting with the current character, look for one that's not + * part of a word and keep moving backward until you find one. + * Then if the character found wasn't the first one, move forward + * again one position. + */ + + segPtr = TkTextIndexToSeg(indexPtr, &offset); + while (1) { + if (segPtr->typePtr == &tkTextCharType) { + c = segPtr->body.chars[offset]; + if (!isalnum(UCHAR(c)) && (c != '_')) { + break; + } + firstChar = 0; + } + offset -= 1; + indexPtr->charIndex -= 1; + if (offset < 0) { + if (indexPtr->charIndex < 0) { + indexPtr->charIndex = 0; + goto done; + } + segPtr = TkTextIndexToSeg(indexPtr, &offset); + } + } + if (!firstChar) { + TkTextIndexForwChars(indexPtr, 1, indexPtr); + } + } else { + return NULL; + } + done: + return p; +} diff --git a/generic/tkTextMark.c b/generic/tkTextMark.c new file mode 100644 index 0000000..0d12c98 --- /dev/null +++ b/generic/tkTextMark.c @@ -0,0 +1,775 @@ +/* + * tkTextMark.c -- + * + * This file contains the procedure that implement marks for + * text widgets. + * + * Copyright (c) 1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkTextMark.c 1.18 97/10/20 11:12:50 + */ + +#include "tkInt.h" +#include "tkText.h" +#include "tkPort.h" + +/* + * Macro that determines the size of a mark segment: + */ + +#define MSEG_SIZE ((unsigned) (Tk_Offset(TkTextSegment, body) \ + + sizeof(TkTextMark))) + +/* + * Forward references for procedures defined in this file: + */ + +static void InsertUndisplayProc _ANSI_ARGS_((TkText *textPtr, + TkTextDispChunk *chunkPtr)); +static int MarkDeleteProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr, int treeGone)); +static TkTextSegment * MarkCleanupProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static void MarkCheckProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static int MarkLayoutProc _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *indexPtr, TkTextSegment *segPtr, + int offset, int maxX, int maxChars, + int noCharsYet, Tk_Uid wrapMode, + TkTextDispChunk *chunkPtr)); +static int MarkFindNext _ANSI_ARGS_((Tcl_Interp *interp, + TkText *textPtr, char *markName)); +static int MarkFindPrev _ANSI_ARGS_((Tcl_Interp *interp, + TkText *textPtr, char *markName)); + + +/* + * The following structures declare the "mark" segment types. + * There are actually two types for marks, one with left gravity + * and one with right gravity. They are identical except for + * their gravity property. + */ + +Tk_SegType tkTextRightMarkType = { + "mark", /* name */ + 0, /* leftGravity */ + (Tk_SegSplitProc *) NULL, /* splitProc */ + MarkDeleteProc, /* deleteProc */ + MarkCleanupProc, /* cleanupProc */ + (Tk_SegLineChangeProc *) NULL, /* lineChangeProc */ + MarkLayoutProc, /* layoutProc */ + MarkCheckProc /* checkProc */ +}; + +Tk_SegType tkTextLeftMarkType = { + "mark", /* name */ + 1, /* leftGravity */ + (Tk_SegSplitProc *) NULL, /* splitProc */ + MarkDeleteProc, /* deleteProc */ + MarkCleanupProc, /* cleanupProc */ + (Tk_SegLineChangeProc *) NULL, /* lineChangeProc */ + MarkLayoutProc, /* layoutProc */ + MarkCheckProc /* checkProc */ +}; + +/* + *-------------------------------------------------------------- + * + * TkTextMarkCmd -- + * + * This procedure is invoked to process the "mark" options of + * the widget command for text widgets. See the user documentation + * for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +TkTextMarkCmd(textPtr, interp, argc, argv) + register TkText *textPtr; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. Someone else has already + * parsed this command enough to know that + * argv[1] is "mark". */ +{ + int c, i; + size_t length; + Tcl_HashEntry *hPtr; + TkTextSegment *markPtr; + Tcl_HashSearch search; + TkTextIndex index; + Tk_SegType *newTypePtr; + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " mark option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[2][0]; + length = strlen(argv[2]); + if ((c == 'g') && (strncmp(argv[2], "gravity", length) == 0)) { + if (argc < 4 || argc > 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " mark gravity markName ?gravity?\"", + (char *) NULL); + return TCL_ERROR; + } + hPtr = Tcl_FindHashEntry(&textPtr->markTable, argv[3]); + if (hPtr == NULL) { + Tcl_AppendResult(interp, "there is no mark named \"", + argv[3], "\"", (char *) NULL); + return TCL_ERROR; + } + markPtr = (TkTextSegment *) Tcl_GetHashValue(hPtr); + if (argc == 4) { + if (markPtr->typePtr == &tkTextRightMarkType) { + interp->result = "right"; + } else { + interp->result = "left"; + } + return TCL_OK; + } + length = strlen(argv[4]); + c = argv[4][0]; + if ((c == 'l') && (strncmp(argv[4], "left", length) == 0)) { + newTypePtr = &tkTextLeftMarkType; + } else if ((c == 'r') && (strncmp(argv[4], "right", length) == 0)) { + newTypePtr = &tkTextRightMarkType; + } else { + Tcl_AppendResult(interp, "bad mark gravity \"", + argv[4], "\": must be left or right", (char *) NULL); + return TCL_ERROR; + } + TkTextMarkSegToIndex(textPtr, markPtr, &index); + TkBTreeUnlinkSegment(textPtr->tree, markPtr, + markPtr->body.mark.linePtr); + markPtr->typePtr = newTypePtr; + TkBTreeLinkSegment(markPtr, &index); + } else if ((c == 'n') && (strncmp(argv[2], "names", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " mark names\"", (char *) NULL); + return TCL_ERROR; + } + for (hPtr = Tcl_FirstHashEntry(&textPtr->markTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + Tcl_AppendElement(interp, + Tcl_GetHashKey(&textPtr->markTable, hPtr)); + } + } else if ((c == 'n') && (strncmp(argv[2], "next", length) == 0)) { + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " mark next index\"", (char *) NULL); + return TCL_ERROR; + } + return MarkFindNext(interp, textPtr, argv[3]); + } else if ((c == 'p') && (strncmp(argv[2], "previous", length) == 0)) { + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " mark previous index\"", (char *) NULL); + return TCL_ERROR; + } + return MarkFindPrev(interp, textPtr, argv[3]); + } else if ((c == 's') && (strncmp(argv[2], "set", length) == 0)) { + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " mark set markName index\"", (char *) NULL); + return TCL_ERROR; + } + if (TkTextGetIndex(interp, textPtr, argv[4], &index) != TCL_OK) { + return TCL_ERROR; + } + TkTextSetMark(textPtr, argv[3], &index); + } else if ((c == 'u') && (strncmp(argv[2], "unset", length) == 0)) { + for (i = 3; i < argc; i++) { + hPtr = Tcl_FindHashEntry(&textPtr->markTable, argv[i]); + if (hPtr != NULL) { + markPtr = (TkTextSegment *) Tcl_GetHashValue(hPtr); + if ((markPtr == textPtr->insertMarkPtr) + || (markPtr == textPtr->currentMarkPtr)) { + continue; + } + TkBTreeUnlinkSegment(textPtr->tree, markPtr, + markPtr->body.mark.linePtr); + Tcl_DeleteHashEntry(hPtr); + ckfree((char *) markPtr); + } + } + } else { + Tcl_AppendResult(interp, "bad mark option \"", argv[2], + "\": must be gravity, names, next, previous, set, or unset", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextSetMark -- + * + * Set a mark to a particular position, creating a new mark if + * one doesn't already exist. + * + * Results: + * The return value is a pointer to the mark that was just set. + * + * Side effects: + * A new mark is created, or an existing mark is moved. + * + *---------------------------------------------------------------------- + */ + +TkTextSegment * +TkTextSetMark(textPtr, name, indexPtr) + TkText *textPtr; /* Text widget in which to create mark. */ + char *name; /* Name of mark to set. */ + TkTextIndex *indexPtr; /* Where to set mark. */ +{ + Tcl_HashEntry *hPtr; + TkTextSegment *markPtr; + TkTextIndex insertIndex; + int new; + + hPtr = Tcl_CreateHashEntry(&textPtr->markTable, name, &new); + markPtr = (TkTextSegment *) Tcl_GetHashValue(hPtr); + if (!new) { + /* + * If this is the insertion point that's being moved, be sure + * to force a display update at the old position. Also, don't + * let the insertion cursor be after the final newline of the + * file. + */ + + if (markPtr == textPtr->insertMarkPtr) { + TkTextIndex index, index2; + TkTextMarkSegToIndex(textPtr, textPtr->insertMarkPtr, &index); + TkTextIndexForwChars(&index, 1, &index2); + TkTextChanged(textPtr, &index, &index2); + if (TkBTreeLineIndex(indexPtr->linePtr) + == TkBTreeNumLines(textPtr->tree)) { + TkTextIndexBackChars(indexPtr, 1, &insertIndex); + indexPtr = &insertIndex; + } + } + TkBTreeUnlinkSegment(textPtr->tree, markPtr, + markPtr->body.mark.linePtr); + } else { + markPtr = (TkTextSegment *) ckalloc(MSEG_SIZE); + markPtr->typePtr = &tkTextRightMarkType; + markPtr->size = 0; + markPtr->body.mark.textPtr = textPtr; + markPtr->body.mark.linePtr = indexPtr->linePtr; + markPtr->body.mark.hPtr = hPtr; + Tcl_SetHashValue(hPtr, markPtr); + } + TkBTreeLinkSegment(markPtr, indexPtr); + + /* + * If the mark is the insertion cursor, then update the screen at the + * mark's new location. + */ + + if (markPtr == textPtr->insertMarkPtr) { + TkTextIndex index2; + + TkTextIndexForwChars(indexPtr, 1, &index2); + TkTextChanged(textPtr, indexPtr, &index2); + } + return markPtr; +} + +/* + *-------------------------------------------------------------- + * + * TkTextMarkSegToIndex -- + * + * Given a segment that is a mark, create an index that + * refers to the next text character (or other text segment + * with non-zero size) after the mark. + * + * Results: + * *IndexPtr is filled in with index information. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +TkTextMarkSegToIndex(textPtr, markPtr, indexPtr) + TkText *textPtr; /* Text widget containing mark. */ + TkTextSegment *markPtr; /* Mark segment. */ + TkTextIndex *indexPtr; /* Index information gets stored here. */ +{ + TkTextSegment *segPtr; + + indexPtr->tree = textPtr->tree; + indexPtr->linePtr = markPtr->body.mark.linePtr; + indexPtr->charIndex = 0; + for (segPtr = indexPtr->linePtr->segPtr; segPtr != markPtr; + segPtr = segPtr->nextPtr) { + indexPtr->charIndex += segPtr->size; + } +} + +/* + *-------------------------------------------------------------- + * + * TkTextMarkNameToIndex -- + * + * Given the name of a mark, return an index corresponding + * to the mark name. + * + * Results: + * The return value is TCL_OK if "name" exists as a mark in + * the text widget. In this case *indexPtr is filled in with + * the next segment whose after the mark whose size is + * non-zero. TCL_ERROR is returned if the mark doesn't exist + * in the text widget. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkTextMarkNameToIndex(textPtr, name, indexPtr) + TkText *textPtr; /* Text widget containing mark. */ + char *name; /* Name of mark. */ + TkTextIndex *indexPtr; /* Index information gets stored here. */ +{ + Tcl_HashEntry *hPtr; + + hPtr = Tcl_FindHashEntry(&textPtr->markTable, name); + if (hPtr == NULL) { + return TCL_ERROR; + } + TkTextMarkSegToIndex(textPtr, (TkTextSegment *) Tcl_GetHashValue(hPtr), + indexPtr); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * MarkDeleteProc -- + * + * This procedure is invoked by the text B-tree code whenever + * a mark lies in a range of characters being deleted. + * + * Results: + * Returns 1 to indicate that deletion has been rejected. + * + * Side effects: + * None (even if the whole tree is being deleted we don't + * free up the mark; it will be done elsewhere). + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +MarkDeleteProc(segPtr, linePtr, treeGone) + TkTextSegment *segPtr; /* Segment being deleted. */ + TkTextLine *linePtr; /* Line containing segment. */ + int treeGone; /* Non-zero means the entire tree is + * being deleted, so everything must + * get cleaned up. */ +{ + return 1; +} + +/* + *-------------------------------------------------------------- + * + * MarkCleanupProc -- + * + * This procedure is invoked by the B-tree code whenever a + * mark segment is moved from one line to another. + * + * Results: + * None. + * + * Side effects: + * The linePtr field of the segment gets updated. + * + *-------------------------------------------------------------- + */ + +static TkTextSegment * +MarkCleanupProc(markPtr, linePtr) + TkTextSegment *markPtr; /* Mark segment that's being moved. */ + TkTextLine *linePtr; /* Line that now contains segment. */ +{ + markPtr->body.mark.linePtr = linePtr; + return markPtr; +} + +/* + *-------------------------------------------------------------- + * + * MarkLayoutProc -- + * + * This procedure is the "layoutProc" for mark segments. + * + * Results: + * If the mark isn't the insertion cursor then the return + * value is -1 to indicate that this segment shouldn't be + * displayed. If the mark is the insertion character then + * 1 is returned and the chunkPtr structure is filled in. + * + * Side effects: + * None, except for filling in chunkPtr. + * + *-------------------------------------------------------------- + */ + + /*ARGSUSED*/ +static int +MarkLayoutProc(textPtr, indexPtr, segPtr, offset, maxX, maxChars, + noCharsYet, wrapMode, chunkPtr) + TkText *textPtr; /* Text widget being layed out. */ + TkTextIndex *indexPtr; /* Identifies first character in chunk. */ + TkTextSegment *segPtr; /* Segment corresponding to indexPtr. */ + int offset; /* Offset within segPtr corresponding to + * indexPtr (always 0). */ + int maxX; /* Chunk must not occupy pixels at this + * position or higher. */ + int maxChars; /* Chunk must not include more than this + * many characters. */ + int noCharsYet; /* Non-zero means no characters have been + * assigned to this line yet. */ + Tk_Uid wrapMode; /* Not used. */ + register TkTextDispChunk *chunkPtr; + /* Structure to fill in with information + * about this chunk. The x field has already + * been set by the caller. */ +{ + if (segPtr != textPtr->insertMarkPtr) { + return -1; + } + + chunkPtr->displayProc = TkTextInsertDisplayProc; + chunkPtr->undisplayProc = InsertUndisplayProc; + chunkPtr->measureProc = (Tk_ChunkMeasureProc *) NULL; + chunkPtr->bboxProc = (Tk_ChunkBboxProc *) NULL; + chunkPtr->numChars = 0; + chunkPtr->minAscent = 0; + chunkPtr->minDescent = 0; + chunkPtr->minHeight = 0; + chunkPtr->width = 0; + + /* + * Note: can't break a line after the insertion cursor: this + * prevents the insertion cursor from being stranded at the end + * of a line. + */ + + chunkPtr->breakIndex = -1; + chunkPtr->clientData = (ClientData) textPtr; + return 1; +} + +/* + *-------------------------------------------------------------- + * + * TkTextInsertDisplayProc -- + * + * This procedure is called to display the insertion + * cursor. + * + * Results: + * None. + * + * Side effects: + * Graphics are drawn. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +void +TkTextInsertDisplayProc(chunkPtr, x, y, height, baseline, display, dst, screenY) + TkTextDispChunk *chunkPtr; /* Chunk that is to be drawn. */ + int x; /* X-position in dst at which to + * draw this chunk (may differ from + * the x-position in the chunk because + * of scrolling). */ + int y; /* Y-position at which to draw this + * chunk in dst (x-position is in + * the chunk itself). */ + int height; /* Total height of line. */ + int baseline; /* Offset of baseline from y. */ + Display *display; /* Display to use for drawing. */ + Drawable dst; /* Pixmap or window in which to draw + * chunk. */ + int screenY; /* Y-coordinate in text window that + * corresponds to y. */ +{ + TkText *textPtr = (TkText *) chunkPtr->clientData; + int halfWidth = textPtr->insertWidth/2; + + if ((x + halfWidth) < 0) { + /* + * The insertion cursor is off-screen. Just return. + */ + + return; + } + + /* + * As a special hack to keep the cursor visible on mono displays + * (or anywhere else that the selection and insertion cursors + * have the same color) write the default background in the cursor + * area (instead of nothing) when the cursor isn't on. Otherwise + * the selection might hide the cursor. + */ + + if (textPtr->flags & INSERT_ON) { + Tk_Fill3DRectangle(textPtr->tkwin, dst, textPtr->insertBorder, + x - textPtr->insertWidth/2, y, textPtr->insertWidth, + height, textPtr->insertBorderWidth, TK_RELIEF_RAISED); + } else if (textPtr->selBorder == textPtr->insertBorder) { + Tk_Fill3DRectangle(textPtr->tkwin, dst, textPtr->border, + x - textPtr->insertWidth/2, y, textPtr->insertWidth, + height, 0, TK_RELIEF_FLAT); + } +} + +/* + *-------------------------------------------------------------- + * + * InsertUndisplayProc -- + * + * This procedure is called when the insertion cursor is no + * longer at a visible point on the display. It does nothing + * right now. + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +InsertUndisplayProc(textPtr, chunkPtr) + TkText *textPtr; /* Overall information about text + * widget. */ + TkTextDispChunk *chunkPtr; /* Chunk that is about to be freed. */ +{ + return; +} + +/* + *-------------------------------------------------------------- + * + * MarkCheckProc -- + * + * This procedure is invoked by the B-tree code to perform + * consistency checks on mark segments. + * + * Results: + * None. + * + * Side effects: + * The procedure panics if it detects anything wrong with + * the mark. + * + *-------------------------------------------------------------- + */ + +static void +MarkCheckProc(markPtr, linePtr) + TkTextSegment *markPtr; /* Segment to check. */ + TkTextLine *linePtr; /* Line containing segment. */ +{ + Tcl_HashSearch search; + Tcl_HashEntry *hPtr; + + if (markPtr->body.mark.linePtr != linePtr) { + panic("MarkCheckProc: markPtr->body.mark.linePtr bogus"); + } + + /* + * Make sure that the mark is still present in the text's mark + * hash table. + */ + + for (hPtr = Tcl_FirstHashEntry(&markPtr->body.mark.textPtr->markTable, + &search); hPtr != markPtr->body.mark.hPtr; + hPtr = Tcl_NextHashEntry(&search)) { + if (hPtr == NULL) { + panic("MarkCheckProc couldn't find hash table entry for mark"); + } + } +} + +/* + *-------------------------------------------------------------- + * + * MarkFindNext -- + * + * This procedure searches forward for the next mark. + * + * Results: + * A standard Tcl result, which is a mark name or an empty string. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +MarkFindNext(interp, textPtr, string) + Tcl_Interp *interp; /* For error reporting */ + TkText *textPtr; /* The widget */ + char *string; /* The starting index or mark name */ +{ + TkTextIndex index; + Tcl_HashEntry *hPtr; + register TkTextSegment *segPtr; + int offset; + + + hPtr = Tcl_FindHashEntry(&textPtr->markTable, string); + if (hPtr != NULL) { + /* + * If given a mark name, return the next mark in the list of + * segments, even if it happens to be at the same character position. + */ + segPtr = (TkTextSegment *) Tcl_GetHashValue(hPtr); + TkTextMarkSegToIndex(textPtr, segPtr, &index); + segPtr = segPtr->nextPtr; + } else { + /* + * For non-mark name indices we want to return any marks that + * are right at the index. + */ + if (TkTextGetIndex(interp, textPtr, string, &index) != TCL_OK) { + return TCL_ERROR; + } + for (offset = 0, segPtr = index.linePtr->segPtr; + segPtr != NULL && offset < index.charIndex; + offset += segPtr->size, segPtr = segPtr->nextPtr) { + /* Empty loop body */ ; + } + } + while (1) { + /* + * segPtr points at the first possible candidate, + * or NULL if we ran off the end of the line. + */ + for ( ; segPtr != NULL ; segPtr = segPtr->nextPtr) { + if (segPtr->typePtr == &tkTextRightMarkType || + segPtr->typePtr == &tkTextLeftMarkType) { + Tcl_SetResult(interp, + Tcl_GetHashKey(&textPtr->markTable, segPtr->body.mark.hPtr), + TCL_STATIC); + return TCL_OK; + } + } + index.linePtr = TkBTreeNextLine(index.linePtr); + if (index.linePtr == (TkTextLine *) NULL) { + return TCL_OK; + } + index.charIndex = 0; + segPtr = index.linePtr->segPtr; + } +} + +/* + *-------------------------------------------------------------- + * + * MarkFindPrev -- + * + * This procedure searches backwards for the previous mark. + * + * Results: + * A standard Tcl result, which is a mark name or an empty string. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static int +MarkFindPrev(interp, textPtr, string) + Tcl_Interp *interp; /* For error reporting */ + TkText *textPtr; /* The widget */ + char *string; /* The starting index or mark name */ +{ + TkTextIndex index; + Tcl_HashEntry *hPtr; + register TkTextSegment *segPtr, *seg2Ptr, *prevPtr; + int offset; + + + hPtr = Tcl_FindHashEntry(&textPtr->markTable, string); + if (hPtr != NULL) { + /* + * If given a mark name, return the previous mark in the list of + * segments, even if it happens to be at the same character position. + */ + segPtr = (TkTextSegment *) Tcl_GetHashValue(hPtr); + TkTextMarkSegToIndex(textPtr, segPtr, &index); + } else { + /* + * For non-mark name indices we do not return any marks that + * are right at the index. + */ + if (TkTextGetIndex(interp, textPtr, string, &index) != TCL_OK) { + return TCL_ERROR; + } + for (offset = 0, segPtr = index.linePtr->segPtr; + segPtr != NULL && offset < index.charIndex; + offset += segPtr->size, segPtr = segPtr->nextPtr) { + /* Empty loop body */ ; + } + } + while (1) { + /* + * segPtr points just past the first possible candidate, + * or at the begining of the line. + */ + for (prevPtr = NULL, seg2Ptr = index.linePtr->segPtr; + seg2Ptr != NULL && seg2Ptr != segPtr; + seg2Ptr = seg2Ptr->nextPtr) { + if (seg2Ptr->typePtr == &tkTextRightMarkType || + seg2Ptr->typePtr == &tkTextLeftMarkType) { + prevPtr = seg2Ptr; + } + } + if (prevPtr != NULL) { + Tcl_SetResult(interp, + Tcl_GetHashKey(&textPtr->markTable, prevPtr->body.mark.hPtr), + TCL_STATIC); + return TCL_OK; + } + index.linePtr = TkBTreePreviousLine(index.linePtr); + if (index.linePtr == (TkTextLine *) NULL) { + return TCL_OK; + } + segPtr = NULL; + } +} diff --git a/generic/tkTextTag.c b/generic/tkTextTag.c new file mode 100644 index 0000000..b5b04be --- /dev/null +++ b/generic/tkTextTag.c @@ -0,0 +1,1376 @@ +/* + * tkTextTag.c -- + * + * This module implements the "tag" subcommand of the widget command + * for text widgets, plus most of the other high-level functions + * related to tags. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkTextTag.c 1.39 97/02/07 13:51:52 + */ + +#include "default.h" +#include "tkPort.h" +#include "tk.h" +#include "tkText.h" + +/* + * Information used for parsing tag configuration information: + */ + +static Tk_ConfigSpec tagConfigSpecs[] = { + {TK_CONFIG_BORDER, "-background", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, border), TK_CONFIG_NULL_OK}, + {TK_CONFIG_BITMAP, "-bgstipple", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, bgStipple), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-borderwidth", (char *) NULL, (char *) NULL, + "0", Tk_Offset(TkTextTag, bdString), + TK_CONFIG_DONT_SET_DEFAULT|TK_CONFIG_NULL_OK}, + {TK_CONFIG_BITMAP, "-fgstipple", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, fgStipple), TK_CONFIG_NULL_OK}, + {TK_CONFIG_FONT, "-font", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, tkfont), TK_CONFIG_NULL_OK}, + {TK_CONFIG_COLOR, "-foreground", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, fgColor), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-justify", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, justifyString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-lmargin1", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, lMargin1String), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-lmargin2", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, lMargin2String), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-offset", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, offsetString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-overstrike", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, overstrikeString), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-relief", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, reliefString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-rmargin", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, rMarginString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-spacing1", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, spacing1String), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-spacing2", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, spacing2String), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-spacing3", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, spacing3String), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-tabs", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, tabString), TK_CONFIG_NULL_OK}, + {TK_CONFIG_STRING, "-underline", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, underlineString), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_UID, "-wrap", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextTag, wrapMode), + TK_CONFIG_NULL_OK}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void ChangeTagPriority _ANSI_ARGS_((TkText *textPtr, + TkTextTag *tagPtr, int prio)); +static TkTextTag * FindTag _ANSI_ARGS_((Tcl_Interp *interp, + TkText *textPtr, char *tagName)); +static void SortTags _ANSI_ARGS_((int numTags, + TkTextTag **tagArrayPtr)); +static int TagSortProc _ANSI_ARGS_((CONST VOID *first, + CONST VOID *second)); + +/* + *-------------------------------------------------------------- + * + * TkTextTagCmd -- + * + * This procedure is invoked to process the "tag" options of + * the widget command for text widgets. See the user documentation + * for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +TkTextTagCmd(textPtr, interp, argc, argv) + register TkText *textPtr; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. Someone else has already + * parsed this command enough to know that + * argv[1] is "tag". */ +{ + int c, i, addTag; + size_t length; + char *fullOption; + register TkTextTag *tagPtr; + TkTextIndex first, last, index1, index2; + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[2][0]; + length = strlen(argv[2]); + if ((c == 'a') && (strncmp(argv[2], "add", length) == 0)) { + fullOption = "add"; + addTag = 1; + + addAndRemove: + if (argc < 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag ", fullOption, + " tagName index1 ?index2 index1 index2 ...?\"", + (char *) NULL); + return TCL_ERROR; + } + tagPtr = TkTextCreateTag(textPtr, argv[3]); + for (i = 4; i < argc; i += 2) { + if (TkTextGetIndex(interp, textPtr, argv[i], &index1) != TCL_OK) { + return TCL_ERROR; + } + if (argc > (i+1)) { + if (TkTextGetIndex(interp, textPtr, argv[i+1], &index2) + != TCL_OK) { + return TCL_ERROR; + } + if (TkTextIndexCmp(&index1, &index2) >= 0) { + return TCL_OK; + } + } else { + index2 = index1; + TkTextIndexForwChars(&index2, 1, &index2); + } + + if (tagPtr->affectsDisplay) { + TkTextRedrawTag(textPtr, &index1, &index2, tagPtr, !addTag); + } else { + /* + * Still need to trigger enter/leave events on tags that + * have changed. + */ + + TkTextEventuallyRepick(textPtr); + } + TkBTreeTag(&index1, &index2, tagPtr, addTag); + + /* + * If the tag is "sel" then grab the selection if we're supposed + * to export it and don't already have it. Also, invalidate + * partially-completed selection retrievals. + */ + + if (tagPtr == textPtr->selTagPtr) { + if (addTag && textPtr->exportSelection + && !(textPtr->flags & GOT_SELECTION)) { + Tk_OwnSelection(textPtr->tkwin, XA_PRIMARY, + TkTextLostSelection, (ClientData) textPtr); + textPtr->flags |= GOT_SELECTION; + } + textPtr->abortSelections = 1; + } + } + } else if ((c == 'b') && (strncmp(argv[2], "bind", length) == 0)) { + if ((argc < 4) || (argc > 6)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag bind tagName ?sequence? ?command?\"", + (char *) NULL); + return TCL_ERROR; + } + tagPtr = TkTextCreateTag(textPtr, argv[3]); + + /* + * Make a binding table if the widget doesn't already have + * one. + */ + + if (textPtr->bindingTable == NULL) { + textPtr->bindingTable = Tk_CreateBindingTable(interp); + } + + if (argc == 6) { + int append = 0; + unsigned long mask; + + if (argv[5][0] == 0) { + return Tk_DeleteBinding(interp, textPtr->bindingTable, + (ClientData) tagPtr, argv[4]); + } + if (argv[5][0] == '+') { + argv[5]++; + append = 1; + } + mask = Tk_CreateBinding(interp, textPtr->bindingTable, + (ClientData) tagPtr, argv[4], argv[5], append); + if (mask == 0) { + return TCL_ERROR; + } + if (mask & (unsigned) ~(ButtonMotionMask|Button1MotionMask + |Button2MotionMask|Button3MotionMask|Button4MotionMask + |Button5MotionMask|ButtonPressMask|ButtonReleaseMask + |EnterWindowMask|LeaveWindowMask|KeyPressMask + |KeyReleaseMask|PointerMotionMask|VirtualEventMask)) { + Tk_DeleteBinding(interp, textPtr->bindingTable, + (ClientData) tagPtr, argv[4]); + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "requested illegal events; ", + "only key, button, motion, enter, leave, and virtual ", + "events may be used", (char *) NULL); + return TCL_ERROR; + } + } else if (argc == 5) { + char *command; + + command = Tk_GetBinding(interp, textPtr->bindingTable, + (ClientData) tagPtr, argv[4]); + if (command == NULL) { + return TCL_ERROR; + } + interp->result = command; + } else { + Tk_GetAllBindings(interp, textPtr->bindingTable, + (ClientData) tagPtr); + } + } else if ((c == 'c') && (strncmp(argv[2], "cget", length) == 0) + && (length >= 2)) { + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag cget tagName option\"", + (char *) NULL); + return TCL_ERROR; + } + tagPtr = FindTag(interp, textPtr, argv[3]); + if (tagPtr == NULL) { + return TCL_ERROR; + } + return Tk_ConfigureValue(interp, textPtr->tkwin, tagConfigSpecs, + (char *) tagPtr, argv[4], 0); + } else if ((c == 'c') && (strncmp(argv[2], "configure", length) == 0) + && (length >= 2)) { + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag configure tagName ?option? ?value? ", + "?option value ...?\"", (char *) NULL); + return TCL_ERROR; + } + tagPtr = TkTextCreateTag(textPtr, argv[3]); + if (argc == 4) { + return Tk_ConfigureInfo(interp, textPtr->tkwin, tagConfigSpecs, + (char *) tagPtr, (char *) NULL, 0); + } else if (argc == 5) { + return Tk_ConfigureInfo(interp, textPtr->tkwin, tagConfigSpecs, + (char *) tagPtr, argv[4], 0); + } else { + int result; + + result = Tk_ConfigureWidget(interp, textPtr->tkwin, tagConfigSpecs, + argc-4, argv+4, (char *) tagPtr, 0); + /* + * Some of the configuration options, like -underline + * and -justify, require additional translation (this is + * needed because we need to distinguish a particular value + * of an option from "unspecified"). + */ + + if (tagPtr->bdString != NULL) { + if (Tk_GetPixels(interp, textPtr->tkwin, tagPtr->bdString, + &tagPtr->borderWidth) != TCL_OK) { + return TCL_ERROR; + } + if (tagPtr->borderWidth < 0) { + tagPtr->borderWidth = 0; + } + } + if (tagPtr->reliefString != NULL) { + if (Tk_GetRelief(interp, tagPtr->reliefString, + &tagPtr->relief) != TCL_OK) { + return TCL_ERROR; + } + } + if (tagPtr->justifyString != NULL) { + if (Tk_GetJustify(interp, tagPtr->justifyString, + &tagPtr->justify) != TCL_OK) { + return TCL_ERROR; + } + } + if (tagPtr->lMargin1String != NULL) { + if (Tk_GetPixels(interp, textPtr->tkwin, + tagPtr->lMargin1String, &tagPtr->lMargin1) != TCL_OK) { + return TCL_ERROR; + } + } + if (tagPtr->lMargin2String != NULL) { + if (Tk_GetPixels(interp, textPtr->tkwin, + tagPtr->lMargin2String, &tagPtr->lMargin2) != TCL_OK) { + return TCL_ERROR; + } + } + if (tagPtr->offsetString != NULL) { + if (Tk_GetPixels(interp, textPtr->tkwin, tagPtr->offsetString, + &tagPtr->offset) != TCL_OK) { + return TCL_ERROR; + } + } + if (tagPtr->overstrikeString != NULL) { + if (Tcl_GetBoolean(interp, tagPtr->overstrikeString, + &tagPtr->overstrike) != TCL_OK) { + return TCL_ERROR; + } + } + if (tagPtr->rMarginString != NULL) { + if (Tk_GetPixels(interp, textPtr->tkwin, + tagPtr->rMarginString, &tagPtr->rMargin) != TCL_OK) { + return TCL_ERROR; + } + } + if (tagPtr->spacing1String != NULL) { + if (Tk_GetPixels(interp, textPtr->tkwin, + tagPtr->spacing1String, &tagPtr->spacing1) != TCL_OK) { + return TCL_ERROR; + } + if (tagPtr->spacing1 < 0) { + tagPtr->spacing1 = 0; + } + } + if (tagPtr->spacing2String != NULL) { + if (Tk_GetPixels(interp, textPtr->tkwin, + tagPtr->spacing2String, &tagPtr->spacing2) != TCL_OK) { + return TCL_ERROR; + } + if (tagPtr->spacing2 < 0) { + tagPtr->spacing2 = 0; + } + } + if (tagPtr->spacing3String != NULL) { + if (Tk_GetPixels(interp, textPtr->tkwin, + tagPtr->spacing3String, &tagPtr->spacing3) != TCL_OK) { + return TCL_ERROR; + } + if (tagPtr->spacing3 < 0) { + tagPtr->spacing3 = 0; + } + } + if (tagPtr->tabArrayPtr != NULL) { + ckfree((char *) tagPtr->tabArrayPtr); + tagPtr->tabArrayPtr = NULL; + } + if (tagPtr->tabString != NULL) { + tagPtr->tabArrayPtr = TkTextGetTabs(interp, textPtr->tkwin, + tagPtr->tabString); + if (tagPtr->tabArrayPtr == NULL) { + return TCL_ERROR; + } + } + if (tagPtr->underlineString != NULL) { + if (Tcl_GetBoolean(interp, tagPtr->underlineString, + &tagPtr->underline) != TCL_OK) { + return TCL_ERROR; + } + } + if ((tagPtr->wrapMode != NULL) + && (tagPtr->wrapMode != tkTextCharUid) + && (tagPtr->wrapMode != tkTextNoneUid) + && (tagPtr->wrapMode != tkTextWordUid)) { + Tcl_AppendResult(interp, "bad wrap mode \"", tagPtr->wrapMode, + "\": must be char, none, or word", (char *) NULL); + tagPtr->wrapMode = NULL; + return TCL_ERROR; + } + + /* + * If the "sel" tag was changed, be sure to mirror information + * from the tag back into the text widget record. NOTE: we + * don't have to free up information in the widget record + * before overwriting it, because it was mirrored in the tag + * and hence freed when the tag field was overwritten. + */ + + if (tagPtr == textPtr->selTagPtr) { + textPtr->selBorder = tagPtr->border; + textPtr->selBdString = tagPtr->bdString; + textPtr->selFgColorPtr = tagPtr->fgColor; + } + tagPtr->affectsDisplay = 0; + if ((tagPtr->border != NULL) + || (tagPtr->bdString != NULL) + || (tagPtr->reliefString != NULL) + || (tagPtr->bgStipple != None) + || (tagPtr->fgColor != NULL) || (tagPtr->tkfont != None) + || (tagPtr->fgStipple != None) + || (tagPtr->justifyString != NULL) + || (tagPtr->lMargin1String != NULL) + || (tagPtr->lMargin2String != NULL) + || (tagPtr->offsetString != NULL) + || (tagPtr->overstrikeString != NULL) + || (tagPtr->rMarginString != NULL) + || (tagPtr->spacing1String != NULL) + || (tagPtr->spacing2String != NULL) + || (tagPtr->spacing3String != NULL) + || (tagPtr->tabString != NULL) + || (tagPtr->underlineString != NULL) + || (tagPtr->wrapMode != NULL)) { + tagPtr->affectsDisplay = 1; + } + TkTextRedrawTag(textPtr, (TkTextIndex *) NULL, + (TkTextIndex *) NULL, tagPtr, 1); + return result; + } + } else if ((c == 'd') && (strncmp(argv[2], "delete", length) == 0)) { + Tcl_HashEntry *hPtr; + + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag delete tagName tagName ...\"", + (char *) NULL); + return TCL_ERROR; + } + for (i = 3; i < argc; i++) { + hPtr = Tcl_FindHashEntry(&textPtr->tagTable, argv[i]); + if (hPtr == NULL) { + continue; + } + tagPtr = (TkTextTag *) Tcl_GetHashValue(hPtr); + if (tagPtr == textPtr->selTagPtr) { + continue; + } + if (tagPtr->affectsDisplay) { + TkTextRedrawTag(textPtr, (TkTextIndex *) NULL, + (TkTextIndex *) NULL, tagPtr, 1); + } + TkBTreeTag(TkTextMakeIndex(textPtr->tree, 0, 0, &first), + TkTextMakeIndex(textPtr->tree, + TkBTreeNumLines(textPtr->tree), 0, &last), + tagPtr, 0); + Tcl_DeleteHashEntry(hPtr); + if (textPtr->bindingTable != NULL) { + Tk_DeleteAllBindings(textPtr->bindingTable, + (ClientData) tagPtr); + } + + /* + * Update the tag priorities to reflect the deletion of this tag. + */ + + ChangeTagPriority(textPtr, tagPtr, textPtr->numTags-1); + textPtr->numTags -= 1; + TkTextFreeTag(textPtr, tagPtr); + } + } else if ((c == 'l') && (strncmp(argv[2], "lower", length) == 0)) { + TkTextTag *tagPtr2; + int prio; + + if ((argc != 4) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag lower tagName ?belowThis?\"", + (char *) NULL); + return TCL_ERROR; + } + tagPtr = FindTag(interp, textPtr, argv[3]); + if (tagPtr == NULL) { + return TCL_ERROR; + } + if (argc == 5) { + tagPtr2 = FindTag(interp, textPtr, argv[4]); + if (tagPtr2 == NULL) { + return TCL_ERROR; + } + if (tagPtr->priority < tagPtr2->priority) { + prio = tagPtr2->priority - 1; + } else { + prio = tagPtr2->priority; + } + } else { + prio = 0; + } + ChangeTagPriority(textPtr, tagPtr, prio); + TkTextRedrawTag(textPtr, (TkTextIndex *) NULL, (TkTextIndex *) NULL, + tagPtr, 1); + } else if ((c == 'n') && (strncmp(argv[2], "names", length) == 0) + && (length >= 2)) { + TkTextTag **arrayPtr; + int arraySize; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag names ?index?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + Tcl_HashSearch search; + Tcl_HashEntry *hPtr; + + arrayPtr = (TkTextTag **) ckalloc((unsigned) + (textPtr->numTags * sizeof(TkTextTag *))); + for (i = 0, hPtr = Tcl_FirstHashEntry(&textPtr->tagTable, &search); + hPtr != NULL; i++, hPtr = Tcl_NextHashEntry(&search)) { + arrayPtr[i] = (TkTextTag *) Tcl_GetHashValue(hPtr); + } + arraySize = textPtr->numTags; + } else { + if (TkTextGetIndex(interp, textPtr, argv[3], &index1) + != TCL_OK) { + return TCL_ERROR; + } + arrayPtr = TkBTreeGetTags(&index1, &arraySize); + if (arrayPtr == NULL) { + return TCL_OK; + } + } + SortTags(arraySize, arrayPtr); + for (i = 0; i < arraySize; i++) { + tagPtr = arrayPtr[i]; + Tcl_AppendElement(interp, tagPtr->name); + } + ckfree((char *) arrayPtr); + } else if ((c == 'n') && (strncmp(argv[2], "nextrange", length) == 0) + && (length >= 2)) { + TkTextSearch tSearch; + char position[TK_POS_CHARS]; + + if ((argc != 5) && (argc != 6)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag nextrange tagName index1 ?index2?\"", + (char *) NULL); + return TCL_ERROR; + } + tagPtr = FindTag((Tcl_Interp *) NULL, textPtr, argv[3]); + if (tagPtr == NULL) { + return TCL_OK; + } + if (TkTextGetIndex(interp, textPtr, argv[4], &index1) != TCL_OK) { + return TCL_ERROR; + } + TkTextMakeIndex(textPtr->tree, TkBTreeNumLines(textPtr->tree), + 0, &last); + if (argc == 5) { + index2 = last; + } else if (TkTextGetIndex(interp, textPtr, argv[5], &index2) + != TCL_OK) { + return TCL_ERROR; + } + + /* + * The search below is a bit tricky. Rather than use the B-tree + * facilities to stop the search at index2, let it search up + * until the end of the file but check for a position past index2 + * ourselves. The reason for doing it this way is that we only + * care whether the *start* of the range is before index2; once + * we find the start, we don't want TkBTreeNextTag to abort the + * search because the end of the range is after index2. + */ + + TkBTreeStartSearch(&index1, &last, tagPtr, &tSearch); + if (TkBTreeCharTagged(&index1, tagPtr)) { + TkTextSegment *segPtr; + int offset; + + /* + * The first character is tagged. See if there is an + * on-toggle just before the character. If not, then + * skip to the end of this tagged range. + */ + + for (segPtr = index1.linePtr->segPtr, offset = index1.charIndex; + offset >= 0; + offset -= segPtr->size, segPtr = segPtr->nextPtr) { + if ((offset == 0) && (segPtr->typePtr == &tkTextToggleOnType) + && (segPtr->body.toggle.tagPtr == tagPtr)) { + goto gotStart; + } + } + if (!TkBTreeNextTag(&tSearch)) { + return TCL_OK; + } + } + + /* + * Find the start of the tagged range. + */ + + if (!TkBTreeNextTag(&tSearch)) { + return TCL_OK; + } + gotStart: + if (TkTextIndexCmp(&tSearch.curIndex, &index2) >= 0) { + return TCL_OK; + } + TkTextPrintIndex(&tSearch.curIndex, position); + Tcl_AppendElement(interp, position); + TkBTreeNextTag(&tSearch); + TkTextPrintIndex(&tSearch.curIndex, position); + Tcl_AppendElement(interp, position); + } else if ((c == 'p') && (strncmp(argv[2], "prevrange", length) == 0) + && (length >= 2)) { + TkTextSearch tSearch; + char position1[TK_POS_CHARS]; + char position2[TK_POS_CHARS]; + + if ((argc != 5) && (argc != 6)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag prevrange tagName index1 ?index2?\"", + (char *) NULL); + return TCL_ERROR; + } + tagPtr = FindTag((Tcl_Interp *) NULL, textPtr, argv[3]); + if (tagPtr == NULL) { + return TCL_OK; + } + if (TkTextGetIndex(interp, textPtr, argv[4], &index1) != TCL_OK) { + return TCL_ERROR; + } + if (argc == 5) { + TkTextMakeIndex(textPtr->tree, 0, 0, &index2); + } else if (TkTextGetIndex(interp, textPtr, argv[5], &index2) + != TCL_OK) { + return TCL_ERROR; + } + + /* + * The search below is a bit weird. The previous toggle can be + * either an on or off toggle. If it is an on toggle, then we + * need to turn around and search forward for the end toggle. + * Otherwise we keep searching backwards. + */ + + TkBTreeStartSearchBack(&index1, &index2, tagPtr, &tSearch); + + if (!TkBTreePrevTag(&tSearch)) { + return TCL_OK; + } + if (tSearch.segPtr->typePtr == &tkTextToggleOnType) { + TkTextPrintIndex(&tSearch.curIndex, position1); + TkTextMakeIndex(textPtr->tree, TkBTreeNumLines(textPtr->tree), + 0, &last); + TkBTreeStartSearch(&tSearch.curIndex, &last, tagPtr, &tSearch); + TkBTreeNextTag(&tSearch); + TkTextPrintIndex(&tSearch.curIndex, position2); + } else { + TkTextPrintIndex(&tSearch.curIndex, position2); + TkBTreePrevTag(&tSearch); + if (TkTextIndexCmp(&tSearch.curIndex, &index2) < 0) { + return TCL_OK; + } + TkTextPrintIndex(&tSearch.curIndex, position1); + } + Tcl_AppendElement(interp, position1); + Tcl_AppendElement(interp, position2); + } else if ((c == 'r') && (strncmp(argv[2], "raise", length) == 0) + && (length >= 3)) { + TkTextTag *tagPtr2; + int prio; + + if ((argc != 4) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag raise tagName ?aboveThis?\"", + (char *) NULL); + return TCL_ERROR; + } + tagPtr = FindTag(interp, textPtr, argv[3]); + if (tagPtr == NULL) { + return TCL_ERROR; + } + if (argc == 5) { + tagPtr2 = FindTag(interp, textPtr, argv[4]); + if (tagPtr2 == NULL) { + return TCL_ERROR; + } + if (tagPtr->priority <= tagPtr2->priority) { + prio = tagPtr2->priority; + } else { + prio = tagPtr2->priority + 1; + } + } else { + prio = textPtr->numTags-1; + } + ChangeTagPriority(textPtr, tagPtr, prio); + TkTextRedrawTag(textPtr, (TkTextIndex *) NULL, (TkTextIndex *) NULL, + tagPtr, 1); + } else if ((c == 'r') && (strncmp(argv[2], "ranges", length) == 0) + && (length >= 3)) { + TkTextSearch tSearch; + char position[TK_POS_CHARS]; + + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " tag ranges tagName\"", (char *) NULL); + return TCL_ERROR; + } + tagPtr = FindTag((Tcl_Interp *) NULL, textPtr, argv[3]); + if (tagPtr == NULL) { + return TCL_OK; + } + TkTextMakeIndex(textPtr->tree, 0, 0, &first); + TkTextMakeIndex(textPtr->tree, TkBTreeNumLines(textPtr->tree), + 0, &last); + TkBTreeStartSearch(&first, &last, tagPtr, &tSearch); + if (TkBTreeCharTagged(&first, tagPtr)) { + TkTextPrintIndex(&first, position); + Tcl_AppendElement(interp, position); + } + while (TkBTreeNextTag(&tSearch)) { + TkTextPrintIndex(&tSearch.curIndex, position); + Tcl_AppendElement(interp, position); + } + } else if ((c == 'r') && (strncmp(argv[2], "remove", length) == 0) + && (length >= 2)) { + fullOption = "remove"; + addTag = 0; + goto addAndRemove; + } else { + Tcl_AppendResult(interp, "bad tag option \"", argv[2], + "\": must be add, bind, cget, configure, delete, lower, ", + "names, nextrange, raise, ranges, or remove", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextCreateTag -- + * + * Find the record describing a tag within a given text widget, + * creating a new record if one doesn't already exist. + * + * Results: + * The return value is a pointer to the TkTextTag record for tagName. + * + * Side effects: + * A new tag record is created if there isn't one already defined + * for tagName. + * + *---------------------------------------------------------------------- + */ + +TkTextTag * +TkTextCreateTag(textPtr, tagName) + TkText *textPtr; /* Widget in which tag is being used. */ + char *tagName; /* Name of desired tag. */ +{ + register TkTextTag *tagPtr; + Tcl_HashEntry *hPtr; + int new; + + hPtr = Tcl_CreateHashEntry(&textPtr->tagTable, tagName, &new); + if (!new) { + return (TkTextTag *) Tcl_GetHashValue(hPtr); + } + + /* + * No existing entry. Create a new one, initialize it, and add a + * pointer to it to the hash table entry. + */ + + tagPtr = (TkTextTag *) ckalloc(sizeof(TkTextTag)); + tagPtr->name = Tcl_GetHashKey(&textPtr->tagTable, hPtr); + tagPtr->toggleCount = 0; + tagPtr->tagRootPtr = NULL; + tagPtr->priority = textPtr->numTags; + tagPtr->border = NULL; + tagPtr->bdString = NULL; + tagPtr->borderWidth = 0; + tagPtr->reliefString = NULL; + tagPtr->relief = TK_RELIEF_FLAT; + tagPtr->bgStipple = None; + tagPtr->fgColor = NULL; + tagPtr->tkfont = NULL; + tagPtr->fgStipple = None; + tagPtr->justifyString = NULL; + tagPtr->justify = TK_JUSTIFY_LEFT; + tagPtr->lMargin1String = NULL; + tagPtr->lMargin1 = 0; + tagPtr->lMargin2String = NULL; + tagPtr->lMargin2 = 0; + tagPtr->offsetString = NULL; + tagPtr->offset = 0; + tagPtr->overstrikeString = NULL; + tagPtr->overstrike = 0; + tagPtr->rMarginString = NULL; + tagPtr->rMargin = 0; + tagPtr->spacing1String = NULL; + tagPtr->spacing1 = 0; + tagPtr->spacing2String = NULL; + tagPtr->spacing2 = 0; + tagPtr->spacing3String = NULL; + tagPtr->spacing3 = 0; + tagPtr->tabString = NULL; + tagPtr->tabArrayPtr = NULL; + tagPtr->underlineString = NULL; + tagPtr->underline = 0; + tagPtr->wrapMode = NULL; + tagPtr->affectsDisplay = 0; + textPtr->numTags++; + Tcl_SetHashValue(hPtr, tagPtr); + return tagPtr; +} + +/* + *---------------------------------------------------------------------- + * + * FindTag -- + * + * See if tag is defined for a given widget. + * + * Results: + * If tagName is defined in textPtr, a pointer to its TkTextTag + * structure is returned. Otherwise NULL is returned and an + * error message is recorded in interp->result unless interp + * is NULL. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static TkTextTag * +FindTag(interp, textPtr, tagName) + Tcl_Interp *interp; /* Interpreter to use for error message; + * if NULL, then don't record an error + * message. */ + TkText *textPtr; /* Widget in which tag is being used. */ + char *tagName; /* Name of desired tag. */ +{ + Tcl_HashEntry *hPtr; + + hPtr = Tcl_FindHashEntry(&textPtr->tagTable, tagName); + if (hPtr != NULL) { + return (TkTextTag *) Tcl_GetHashValue(hPtr); + } + if (interp != NULL) { + Tcl_AppendResult(interp, "tag \"", tagName, + "\" isn't defined in text widget", (char *) NULL); + } + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TkTextFreeTag -- + * + * This procedure is called when a tag is deleted to free up the + * memory and other resources associated with the tag. + * + * Results: + * None. + * + * Side effects: + * Memory and other resources are freed. + * + *---------------------------------------------------------------------- + */ + +void +TkTextFreeTag(textPtr, tagPtr) + TkText *textPtr; /* Info about overall widget. */ + register TkTextTag *tagPtr; /* Tag being deleted. */ +{ + if (tagPtr->border != None) { + Tk_Free3DBorder(tagPtr->border); + } + if (tagPtr->bdString != NULL) { + ckfree(tagPtr->bdString); + } + if (tagPtr->reliefString != NULL) { + ckfree(tagPtr->reliefString); + } + if (tagPtr->bgStipple != None) { + Tk_FreeBitmap(textPtr->display, tagPtr->bgStipple); + } + if (tagPtr->fgColor != None) { + Tk_FreeColor(tagPtr->fgColor); + } + Tk_FreeFont(tagPtr->tkfont); + if (tagPtr->fgStipple != None) { + Tk_FreeBitmap(textPtr->display, tagPtr->fgStipple); + } + if (tagPtr->justifyString != NULL) { + ckfree(tagPtr->justifyString); + } + if (tagPtr->lMargin1String != NULL) { + ckfree(tagPtr->lMargin1String); + } + if (tagPtr->lMargin2String != NULL) { + ckfree(tagPtr->lMargin2String); + } + if (tagPtr->offsetString != NULL) { + ckfree(tagPtr->offsetString); + } + if (tagPtr->overstrikeString != NULL) { + ckfree(tagPtr->overstrikeString); + } + if (tagPtr->rMarginString != NULL) { + ckfree(tagPtr->rMarginString); + } + if (tagPtr->spacing1String != NULL) { + ckfree(tagPtr->spacing1String); + } + if (tagPtr->spacing2String != NULL) { + ckfree(tagPtr->spacing2String); + } + if (tagPtr->spacing3String != NULL) { + ckfree(tagPtr->spacing3String); + } + if (tagPtr->tabString != NULL) { + ckfree(tagPtr->tabString); + } + if (tagPtr->tabArrayPtr != NULL) { + ckfree((char *) tagPtr->tabArrayPtr); + } + if (tagPtr->underlineString != NULL) { + ckfree(tagPtr->underlineString); + } + ckfree((char *) tagPtr); +} + +/* + *---------------------------------------------------------------------- + * + * SortTags -- + * + * This procedure sorts an array of tag pointers in increasing + * order of priority, optimizing for the common case where the + * array is small. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +SortTags(numTags, tagArrayPtr) + int numTags; /* Number of tag pointers at *tagArrayPtr. */ + TkTextTag **tagArrayPtr; /* Pointer to array of pointers. */ +{ + int i, j, prio; + register TkTextTag **tagPtrPtr; + TkTextTag **maxPtrPtr, *tmp; + + if (numTags < 2) { + return; + } + if (numTags < 20) { + for (i = numTags-1; i > 0; i--, tagArrayPtr++) { + maxPtrPtr = tagPtrPtr = tagArrayPtr; + prio = tagPtrPtr[0]->priority; + for (j = i, tagPtrPtr++; j > 0; j--, tagPtrPtr++) { + if (tagPtrPtr[0]->priority < prio) { + prio = tagPtrPtr[0]->priority; + maxPtrPtr = tagPtrPtr; + } + } + tmp = *maxPtrPtr; + *maxPtrPtr = *tagArrayPtr; + *tagArrayPtr = tmp; + } + } else { + qsort((VOID *) tagArrayPtr, (unsigned) numTags, sizeof (TkTextTag *), + TagSortProc); + } +} + +/* + *---------------------------------------------------------------------- + * + * TagSortProc -- + * + * This procedure is called by qsort when sorting an array of + * tags in priority order. + * + * Results: + * The return value is -1 if the first argument should be before + * the second element (i.e. it has lower priority), 0 if it's + * equivalent (this should never happen!), and 1 if it should be + * after the second element. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +TagSortProc(first, second) + CONST VOID *first, *second; /* Elements to be compared. */ +{ + TkTextTag *tagPtr1, *tagPtr2; + + tagPtr1 = * (TkTextTag **) first; + tagPtr2 = * (TkTextTag **) second; + return tagPtr1->priority - tagPtr2->priority; +} + +/* + *---------------------------------------------------------------------- + * + * ChangeTagPriority -- + * + * This procedure changes the priority of a tag by modifying + * its priority and the priorities of other tags that are affected + * by the change. + * + * Results: + * None. + * + * Side effects: + * Priorities may be changed for some or all of the tags in + * textPtr. The tags will be arranged so that there is exactly + * one tag at each priority level between 0 and textPtr->numTags-1, + * with tagPtr at priority "prio". + * + *---------------------------------------------------------------------- + */ + +static void +ChangeTagPriority(textPtr, tagPtr, prio) + TkText *textPtr; /* Information about text widget. */ + TkTextTag *tagPtr; /* Tag whose priority is to be + * changed. */ + int prio; /* New priority for tag. */ +{ + int low, high, delta; + register TkTextTag *tagPtr2; + Tcl_HashEntry *hPtr; + Tcl_HashSearch search; + + if (prio < 0) { + prio = 0; + } + if (prio >= textPtr->numTags) { + prio = textPtr->numTags-1; + } + if (prio == tagPtr->priority) { + return; + } else if (prio < tagPtr->priority) { + low = prio; + high = tagPtr->priority-1; + delta = 1; + } else { + low = tagPtr->priority+1; + high = prio; + delta = -1; + } + for (hPtr = Tcl_FirstHashEntry(&textPtr->tagTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + tagPtr2 = (TkTextTag *) Tcl_GetHashValue(hPtr); + if ((tagPtr2->priority >= low) && (tagPtr2->priority <= high)) { + tagPtr2->priority += delta; + } + } + tagPtr->priority = prio; +} + +/* + *-------------------------------------------------------------- + * + * TkTextBindProc -- + * + * This procedure is invoked by the Tk dispatcher to handle + * events associated with bindings on items. + * + * Results: + * None. + * + * Side effects: + * Depends on the command invoked as part of the binding + * (if there was any). + * + *-------------------------------------------------------------- + */ + +void +TkTextBindProc(clientData, eventPtr) + ClientData clientData; /* Pointer to canvas structure. */ + XEvent *eventPtr; /* Pointer to X event that just + * happened. */ +{ + TkText *textPtr = (TkText *) clientData; + int repick = 0; + +# define AnyButtonMask (Button1Mask|Button2Mask|Button3Mask\ + |Button4Mask|Button5Mask) + + Tcl_Preserve((ClientData) textPtr); + + /* + * This code simulates grabs for mouse buttons by keeping track + * of whether a button is pressed and refusing to pick a new current + * character while a button is pressed. + */ + + if (eventPtr->type == ButtonPress) { + textPtr->flags |= BUTTON_DOWN; + } else if (eventPtr->type == ButtonRelease) { + int mask; + + switch (eventPtr->xbutton.button) { + case Button1: + mask = Button1Mask; + break; + case Button2: + mask = Button2Mask; + break; + case Button3: + mask = Button3Mask; + break; + case Button4: + mask = Button4Mask; + break; + case Button5: + mask = Button5Mask; + break; + default: + mask = 0; + break; + } + if ((eventPtr->xbutton.state & AnyButtonMask) == (unsigned) mask) { + textPtr->flags &= ~BUTTON_DOWN; + repick = 1; + } + } else if ((eventPtr->type == EnterNotify) + || (eventPtr->type == LeaveNotify)) { + if (eventPtr->xcrossing.state & AnyButtonMask) { + textPtr->flags |= BUTTON_DOWN; + } else { + textPtr->flags &= ~BUTTON_DOWN; + } + TkTextPickCurrent(textPtr, eventPtr); + goto done; + } else if (eventPtr->type == MotionNotify) { + if (eventPtr->xmotion.state & AnyButtonMask) { + textPtr->flags |= BUTTON_DOWN; + } else { + textPtr->flags &= ~BUTTON_DOWN; + } + TkTextPickCurrent(textPtr, eventPtr); + } + if ((textPtr->numCurTags > 0) && (textPtr->bindingTable != NULL) + && (textPtr->tkwin != NULL)) { + Tk_BindEvent(textPtr->bindingTable, eventPtr, textPtr->tkwin, + textPtr->numCurTags, (ClientData *) textPtr->curTagArrayPtr); + } + if (repick) { + unsigned int oldState; + + oldState = eventPtr->xbutton.state; + eventPtr->xbutton.state &= ~(Button1Mask|Button2Mask + |Button3Mask|Button4Mask|Button5Mask); + TkTextPickCurrent(textPtr, eventPtr); + eventPtr->xbutton.state = oldState; + } + + done: + Tcl_Release((ClientData) textPtr); +} + +/* + *-------------------------------------------------------------- + * + * TkTextPickCurrent -- + * + * Find the character containing the coordinates in an event + * and place the "current" mark on that character. If the + * "current" mark has moved then generate a fake leave event + * on the old current character and a fake enter event on the new + * current character. + * + * Results: + * None. + * + * Side effects: + * The current mark for textPtr may change. If it does, + * then the commands associated with character entry and leave + * could do just about anything. For example, the text widget + * might be deleted. It is up to the caller to protect itself + * with calls to Tcl_Preserve and Tcl_Release. + * + *-------------------------------------------------------------- + */ + +void +TkTextPickCurrent(textPtr, eventPtr) + register TkText *textPtr; /* Text widget in which to select + * current character. */ + XEvent *eventPtr; /* Event describing location of + * mouse cursor. Must be EnterWindow, + * LeaveWindow, ButtonRelease, or + * MotionNotify. */ +{ + TkTextIndex index; + TkTextTag **oldArrayPtr, **newArrayPtr; + TkTextTag **copyArrayPtr = NULL; /* Initialization needed to prevent + * compiler warning. */ + + int numOldTags, numNewTags, i, j, size; + XEvent event; + + /* + * If a button is down, then don't do anything at all; we'll be + * called again when all buttons are up, and we can repick then. + * This implements a form of mouse grabbing. + */ + + if (textPtr->flags & BUTTON_DOWN) { + if (((eventPtr->type == EnterNotify) || (eventPtr->type == LeaveNotify)) + && ((eventPtr->xcrossing.mode == NotifyGrab) + || (eventPtr->xcrossing.mode == NotifyUngrab))) { + /* + * Special case: the window is being entered or left because + * of a grab or ungrab. In this case, repick after all. + * Furthermore, clear BUTTON_DOWN to release the simulated + * grab. + */ + + textPtr->flags &= ~BUTTON_DOWN; + } else { + return; + } + } + + /* + * Save information about this event in the widget in case we have + * to synthesize more enter and leave events later (e.g. because a + * character was deleted, causing a new character to be underneath + * the mouse cursor). Also translate MotionNotify events into + * EnterNotify events, since that's what gets reported to event + * handlers when the current character changes. + */ + + if (eventPtr != &textPtr->pickEvent) { + if ((eventPtr->type == MotionNotify) + || (eventPtr->type == ButtonRelease)) { + textPtr->pickEvent.xcrossing.type = EnterNotify; + textPtr->pickEvent.xcrossing.serial = eventPtr->xmotion.serial; + textPtr->pickEvent.xcrossing.send_event + = eventPtr->xmotion.send_event; + textPtr->pickEvent.xcrossing.display = eventPtr->xmotion.display; + textPtr->pickEvent.xcrossing.window = eventPtr->xmotion.window; + textPtr->pickEvent.xcrossing.root = eventPtr->xmotion.root; + textPtr->pickEvent.xcrossing.subwindow = None; + textPtr->pickEvent.xcrossing.time = eventPtr->xmotion.time; + textPtr->pickEvent.xcrossing.x = eventPtr->xmotion.x; + textPtr->pickEvent.xcrossing.y = eventPtr->xmotion.y; + textPtr->pickEvent.xcrossing.x_root = eventPtr->xmotion.x_root; + textPtr->pickEvent.xcrossing.y_root = eventPtr->xmotion.y_root; + textPtr->pickEvent.xcrossing.mode = NotifyNormal; + textPtr->pickEvent.xcrossing.detail = NotifyNonlinear; + textPtr->pickEvent.xcrossing.same_screen + = eventPtr->xmotion.same_screen; + textPtr->pickEvent.xcrossing.focus = False; + textPtr->pickEvent.xcrossing.state = eventPtr->xmotion.state; + } else { + textPtr->pickEvent = *eventPtr; + } + } + + /* + * Find the new current character, then find and sort all of the + * tags associated with it. + */ + + if (textPtr->pickEvent.type != LeaveNotify) { + TkTextPixelIndex(textPtr, textPtr->pickEvent.xcrossing.x, + textPtr->pickEvent.xcrossing.y, &index); + newArrayPtr = TkBTreeGetTags(&index, &numNewTags); + SortTags(numNewTags, newArrayPtr); + } else { + newArrayPtr = NULL; + numNewTags = 0; + } + + /* + * Resort the tags associated with the previous marked character + * (the priorities might have changed), then make a copy of the + * new tags, and compare the old tags to the copy, nullifying + * any tags that are present in both groups (i.e. the tags that + * haven't changed). + */ + + SortTags(textPtr->numCurTags, textPtr->curTagArrayPtr); + if (numNewTags > 0) { + size = numNewTags * sizeof(TkTextTag *); + copyArrayPtr = (TkTextTag **) ckalloc((unsigned) size); + memcpy((VOID *) copyArrayPtr, (VOID *) newArrayPtr, (size_t) size); + for (i = 0; i < textPtr->numCurTags; i++) { + for (j = 0; j < numNewTags; j++) { + if (textPtr->curTagArrayPtr[i] == copyArrayPtr[j]) { + textPtr->curTagArrayPtr[i] = NULL; + copyArrayPtr[j] = NULL; + break; + } + } + } + } + + /* + * Invoke the binding system with a LeaveNotify event for all of + * the tags that have gone away. We have to be careful here, + * because it's possible that the binding could do something + * (like calling tkwait) that eventually modifies + * textPtr->curTagArrayPtr. To avoid problems in situations like + * this, update curTagArrayPtr to its new value before invoking + * any bindings, and don't use it any more here. + */ + + numOldTags = textPtr->numCurTags; + textPtr->numCurTags = numNewTags; + oldArrayPtr = textPtr->curTagArrayPtr; + textPtr->curTagArrayPtr = newArrayPtr; + if (numOldTags != 0) { + if ((textPtr->bindingTable != NULL) && (textPtr->tkwin != NULL)) { + event = textPtr->pickEvent; + event.type = LeaveNotify; + + /* + * Always use a detail of NotifyAncestor. Besides being + * consistent, this avoids problems where the binding code + * will discard NotifyInferior events. + */ + + event.xcrossing.detail = NotifyAncestor; + Tk_BindEvent(textPtr->bindingTable, &event, textPtr->tkwin, + numOldTags, (ClientData *) oldArrayPtr); + } + ckfree((char *) oldArrayPtr); + } + + /* + * Reset the "current" mark (be careful to recompute its location, + * since it might have changed during an event binding). Then + * invoke the binding system with an EnterNotify event for all of + * the tags that have just appeared. + */ + + TkTextPixelIndex(textPtr, textPtr->pickEvent.xcrossing.x, + textPtr->pickEvent.xcrossing.y, &index); + TkTextSetMark(textPtr, "current", &index); + if (numNewTags != 0) { + if ((textPtr->bindingTable != NULL) && (textPtr->tkwin != NULL)) { + event = textPtr->pickEvent; + event.type = EnterNotify; + event.xcrossing.detail = NotifyAncestor; + Tk_BindEvent(textPtr->bindingTable, &event, textPtr->tkwin, + numNewTags, (ClientData *) copyArrayPtr); + } + ckfree((char *) copyArrayPtr); + } +} diff --git a/generic/tkTextWind.c b/generic/tkTextWind.c new file mode 100644 index 0000000..6452d13 --- /dev/null +++ b/generic/tkTextWind.c @@ -0,0 +1,1176 @@ +/* + * tkTextWind.c -- + * + * This file contains code that allows arbitrary windows to be + * nested inside text widgets. It also implements the "window" + * widget command for texts. + * + * Copyright (c) 1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkTextWind.c 1.14 97/04/25 16:52:09 + */ + +#include "tk.h" +#include "tkText.h" +#include "tkPort.h" + +/* + * The following structure is the official type record for the + * embedded window geometry manager: + */ + +static void EmbWinRequestProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); +static void EmbWinLostSlaveProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); + +static Tk_GeomMgr textGeomType = { + "text", /* name */ + EmbWinRequestProc, /* requestProc */ + EmbWinLostSlaveProc, /* lostSlaveProc */ +}; + +/* + * Definitions for alignment values: + */ + +#define ALIGN_BOTTOM 0 +#define ALIGN_CENTER 1 +#define ALIGN_TOP 2 +#define ALIGN_BASELINE 3 + +/* + * Macro that determines the size of an embedded window segment: + */ + +#define EW_SEG_SIZE ((unsigned) (Tk_Offset(TkTextSegment, body) \ + + sizeof(TkTextEmbWindow))) + +/* + * Prototypes for procedures defined in this file: + */ + +static int AlignParseProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, Tk_Window tkwin, char *value, + char *widgRec, int offset)); +static char * AlignPrintProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin, char *widgRec, int offset, + Tcl_FreeProc **freeProcPtr)); +static TkTextSegment * EmbWinCleanupProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static void EmbWinCheckProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr)); +static void EmbWinBboxProc _ANSI_ARGS_((TkTextDispChunk *chunkPtr, + int index, int y, int lineHeight, int baseline, + int *xPtr, int *yPtr, int *widthPtr, + int *heightPtr)); +static int EmbWinConfigure _ANSI_ARGS_((TkText *textPtr, + TkTextSegment *ewPtr, int argc, char **argv)); +static void EmbWinDelayedUnmap _ANSI_ARGS_(( + ClientData clientData)); +static int EmbWinDeleteProc _ANSI_ARGS_((TkTextSegment *segPtr, + TkTextLine *linePtr, int treeGone)); +static void EmbWinDisplayProc _ANSI_ARGS_(( + TkTextDispChunk *chunkPtr, int x, int y, + int lineHeight, int baseline, Display *display, + Drawable dst, int screenY)); +static int EmbWinLayoutProc _ANSI_ARGS_((TkText *textPtr, + TkTextIndex *indexPtr, TkTextSegment *segPtr, + int offset, int maxX, int maxChars, + int noCharsYet, Tk_Uid wrapMode, + TkTextDispChunk *chunkPtr)); +static void EmbWinStructureProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void EmbWinUndisplayProc _ANSI_ARGS_((TkText *textPtr, + TkTextDispChunk *chunkPtr)); + +/* + * The following structure declares the "embedded window" segment type. + */ + +static Tk_SegType tkTextEmbWindowType = { + "window", /* name */ + 0, /* leftGravity */ + (Tk_SegSplitProc *) NULL, /* splitProc */ + EmbWinDeleteProc, /* deleteProc */ + EmbWinCleanupProc, /* cleanupProc */ + (Tk_SegLineChangeProc *) NULL, /* lineChangeProc */ + EmbWinLayoutProc, /* layoutProc */ + EmbWinCheckProc /* checkProc */ +}; + +/* + * Information used for parsing window configuration options: + */ + +static Tk_CustomOption alignOption = {AlignParseProc, AlignPrintProc, + (ClientData) NULL}; + +static Tk_ConfigSpec configSpecs[] = { + {TK_CONFIG_CUSTOM, "-align", (char *) NULL, (char *) NULL, + "center", 0, TK_CONFIG_DONT_SET_DEFAULT, &alignOption}, + {TK_CONFIG_STRING, "-create", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextEmbWindow, create), + TK_CONFIG_DONT_SET_DEFAULT|TK_CONFIG_NULL_OK}, + {TK_CONFIG_INT, "-padx", (char *) NULL, (char *) NULL, + "0", Tk_Offset(TkTextEmbWindow, padX), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_INT, "-pady", (char *) NULL, (char *) NULL, + "0", Tk_Offset(TkTextEmbWindow, padY), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_BOOLEAN, "-stretch", (char *) NULL, (char *) NULL, + "0", Tk_Offset(TkTextEmbWindow, stretch), + TK_CONFIG_DONT_SET_DEFAULT}, + {TK_CONFIG_WINDOW, "-window", (char *) NULL, (char *) NULL, + (char *) NULL, Tk_Offset(TkTextEmbWindow, tkwin), + TK_CONFIG_DONT_SET_DEFAULT|TK_CONFIG_NULL_OK}, + {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL, + (char *) NULL, 0, 0} +}; + +/* + *-------------------------------------------------------------- + * + * TkTextWindowCmd -- + * + * This procedure implements the "window" widget command + * for text widgets. See the user documentation for details + * on what it does. + * + * Results: + * A standard Tcl result or error. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +TkTextWindowCmd(textPtr, interp, argc, argv) + register TkText *textPtr; /* Information about text widget. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. Someone else has already + * parsed this command enough to know that + * argv[1] is "window". */ +{ + size_t length; + register TkTextSegment *ewPtr; + + if (argc < 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " window option ?arg arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + length = strlen(argv[2]); + if ((strncmp(argv[2], "cget", length) == 0) && (length >= 2)) { + TkTextIndex index; + TkTextSegment *ewPtr; + + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " window cget index option\"", + (char *) NULL); + return TCL_ERROR; + } + if (TkTextGetIndex(interp, textPtr, argv[3], &index) != TCL_OK) { + return TCL_ERROR; + } + ewPtr = TkTextIndexToSeg(&index, (int *) NULL); + if (ewPtr->typePtr != &tkTextEmbWindowType) { + Tcl_AppendResult(interp, "no embedded window at index \"", + argv[3], "\"", (char *) NULL); + return TCL_ERROR; + } + return Tk_ConfigureValue(interp, textPtr->tkwin, configSpecs, + (char *) &ewPtr->body.ew, argv[4], 0); + } else if ((strncmp(argv[2], "configure", length) == 0) && (length >= 2)) { + TkTextIndex index; + TkTextSegment *ewPtr; + + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " window configure index ?option value ...?\"", + (char *) NULL); + return TCL_ERROR; + } + if (TkTextGetIndex(interp, textPtr, argv[3], &index) != TCL_OK) { + return TCL_ERROR; + } + ewPtr = TkTextIndexToSeg(&index, (int *) NULL); + if (ewPtr->typePtr != &tkTextEmbWindowType) { + Tcl_AppendResult(interp, "no embedded window at index \"", + argv[3], "\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 4) { + return Tk_ConfigureInfo(interp, textPtr->tkwin, configSpecs, + (char *) &ewPtr->body.ew, (char *) NULL, 0); + } else if (argc == 5) { + return Tk_ConfigureInfo(interp, textPtr->tkwin, configSpecs, + (char *) &ewPtr->body.ew, argv[4], 0); + } else { + TkTextChanged(textPtr, &index, &index); + return EmbWinConfigure(textPtr, ewPtr, argc-4, argv+4); + } + } else if ((strncmp(argv[2], "create", length) == 0) && (length >= 2)) { + TkTextIndex index; + int lineIndex; + + /* + * Add a new window. Find where to put the new window, and + * mark that position for redisplay. + */ + + if (argc < 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " window create index ?option value ...?\"", + (char *) NULL); + return TCL_ERROR; + } + if (TkTextGetIndex(interp, textPtr, argv[3], &index) != TCL_OK) { + return TCL_ERROR; + } + + /* + * Don't allow insertions on the last (dummy) line of the text. + */ + + lineIndex = TkBTreeLineIndex(index.linePtr); + if (lineIndex == TkBTreeNumLines(textPtr->tree)) { + lineIndex--; + TkTextMakeIndex(textPtr->tree, lineIndex, 1000000, &index); + } + + /* + * Create the new window segment and initialize it. + */ + + ewPtr = (TkTextSegment *) ckalloc(EW_SEG_SIZE); + ewPtr->typePtr = &tkTextEmbWindowType; + ewPtr->size = 1; + ewPtr->body.ew.textPtr = textPtr; + ewPtr->body.ew.linePtr = NULL; + ewPtr->body.ew.tkwin = NULL; + ewPtr->body.ew.create = NULL; + ewPtr->body.ew.align = ALIGN_CENTER; + ewPtr->body.ew.padX = ewPtr->body.ew.padY = 0; + ewPtr->body.ew.stretch = 0; + ewPtr->body.ew.chunkCount = 0; + ewPtr->body.ew.displayed = 0; + + /* + * Link the segment into the text widget, then configure it (delete + * it again if the configuration fails). + */ + + TkTextChanged(textPtr, &index, &index); + TkBTreeLinkSegment(ewPtr, &index); + if (EmbWinConfigure(textPtr, ewPtr, argc-4, argv+4) != TCL_OK) { + TkTextIndex index2; + + TkTextIndexForwChars(&index, 1, &index2); + TkBTreeDeleteChars(&index, &index2); + return TCL_ERROR; + } + } else if (strncmp(argv[2], "names", length) == 0) { + Tcl_HashSearch search; + Tcl_HashEntry *hPtr; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " window names\"", (char *) NULL); + return TCL_ERROR; + } + for (hPtr = Tcl_FirstHashEntry(&textPtr->windowTable, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + Tcl_AppendElement(interp, + Tcl_GetHashKey(&textPtr->markTable, hPtr)); + } + } else { + Tcl_AppendResult(interp, "bad window option \"", argv[2], + "\": must be cget, configure, create, or names", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * EmbWinConfigure -- + * + * This procedure is called to handle configuration options + * for an embedded window, using an argc/argv list. + * + * Results: + * The return value is a standard Tcl result. If TCL_ERROR is + * returned, then interp->result contains an error message.. + * + * Side effects: + * Configuration information for the embedded window changes, + * such as alignment, stretching, or name of the embedded + * window. + * + *-------------------------------------------------------------- + */ + +static int +EmbWinConfigure(textPtr, ewPtr, argc, argv) + TkText *textPtr; /* Information about text widget that + * contains embedded window. */ + TkTextSegment *ewPtr; /* Embedded window to be configured. */ + int argc; /* Number of strings in argv. */ + char **argv; /* Array of strings describing configuration + * options. */ +{ + Tk_Window oldWindow; + Tcl_HashEntry *hPtr; + int new; + + oldWindow = ewPtr->body.ew.tkwin; + if (Tk_ConfigureWidget(textPtr->interp, textPtr->tkwin, configSpecs, + argc, argv, (char *) &ewPtr->body.ew, TK_CONFIG_ARGV_ONLY) + != TCL_OK) { + return TCL_ERROR; + } + if (oldWindow != ewPtr->body.ew.tkwin) { + if (oldWindow != NULL) { + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&textPtr->windowTable, + Tk_PathName(oldWindow))); + Tk_DeleteEventHandler(oldWindow, StructureNotifyMask, + EmbWinStructureProc, (ClientData) ewPtr); + Tk_ManageGeometry(oldWindow, (Tk_GeomMgr *) NULL, + (ClientData) NULL); + if (textPtr->tkwin != Tk_Parent(oldWindow)) { + Tk_UnmaintainGeometry(oldWindow, textPtr->tkwin); + } else { + Tk_UnmapWindow(oldWindow); + } + } + if (ewPtr->body.ew.tkwin != NULL) { + Tk_Window ancestor, parent; + + /* + * Make sure that the text is either the parent of the + * embedded window or a descendant of that parent. Also, + * don't allow a top-level window to be managed inside + * a text. + */ + + parent = Tk_Parent(ewPtr->body.ew.tkwin); + for (ancestor = textPtr->tkwin; ; + ancestor = Tk_Parent(ancestor)) { + if (ancestor == parent) { + break; + } + if (Tk_IsTopLevel(ancestor)) { + badMaster: + Tcl_AppendResult(textPtr->interp, "can't embed ", + Tk_PathName(ewPtr->body.ew.tkwin), " in ", + Tk_PathName(textPtr->tkwin), (char *) NULL); + ewPtr->body.ew.tkwin = NULL; + return TCL_ERROR; + } + } + if (Tk_IsTopLevel(ewPtr->body.ew.tkwin) + || (ewPtr->body.ew.tkwin == textPtr->tkwin)) { + goto badMaster; + } + + /* + * Take over geometry management for the window, plus create + * an event handler to find out when it is deleted. + */ + + Tk_ManageGeometry(ewPtr->body.ew.tkwin, &textGeomType, + (ClientData) ewPtr); + Tk_CreateEventHandler(ewPtr->body.ew.tkwin, StructureNotifyMask, + EmbWinStructureProc, (ClientData) ewPtr); + + /* + * Special trick! Must enter into the hash table *after* + * calling Tk_ManageGeometry: if the window was already managed + * elsewhere in this text, the Tk_ManageGeometry call will cause + * the entry to be removed, which could potentially lose the new + * entry. + */ + + hPtr = Tcl_CreateHashEntry(&textPtr->windowTable, + Tk_PathName(ewPtr->body.ew.tkwin), &new); + Tcl_SetHashValue(hPtr, ewPtr); + + } + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * AlignParseProc -- + * + * This procedure is invoked by Tk_ConfigureWidget during + * option processing to handle "-align" options for embedded + * windows. + * + * Results: + * A standard Tcl return value. + * + * Side effects: + * The alignment for the embedded window may change. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +AlignParseProc(clientData, interp, tkwin, value, widgRec, offset) + ClientData clientData; /* Not used.*/ + Tcl_Interp *interp; /* Used for reporting errors. */ + Tk_Window tkwin; /* Window for text widget. */ + char *value; /* Value of option. */ + char *widgRec; /* Pointer to TkTextEmbWindow + * structure. */ + int offset; /* Offset into item (ignored). */ +{ + register TkTextEmbWindow *embPtr = (TkTextEmbWindow *) widgRec; + + if (strcmp(value, "baseline") == 0) { + embPtr->align = ALIGN_BASELINE; + } else if (strcmp(value, "bottom") == 0) { + embPtr->align = ALIGN_BOTTOM; + } else if (strcmp(value, "center") == 0) { + embPtr->align = ALIGN_CENTER; + } else if (strcmp(value, "top") == 0) { + embPtr->align = ALIGN_TOP; + } else { + Tcl_AppendResult(interp, "bad alignment \"", value, + "\": must be baseline, bottom, center, or top", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * AlignPrintProc -- + * + * This procedure is invoked by the Tk configuration code + * to produce a printable string for the "-align" configuration + * option for embedded windows. + * + * Results: + * The return value is a string describing the embedded + * window's current alignment. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static char * +AlignPrintProc(clientData, tkwin, widgRec, offset, freeProcPtr) + ClientData clientData; /* Ignored. */ + Tk_Window tkwin; /* Window for text widget. */ + char *widgRec; /* Pointer to TkTextEmbWindow + * structure. */ + int offset; /* Ignored. */ + Tcl_FreeProc **freeProcPtr; /* Pointer to variable to fill in with + * information about how to reclaim + * storage for return string. */ +{ + switch (((TkTextEmbWindow *) widgRec)->align) { + case ALIGN_BASELINE: + return "baseline"; + case ALIGN_BOTTOM: + return "bottom"; + case ALIGN_CENTER: + return "center"; + case ALIGN_TOP: + return "top"; + default: + return "??"; + } +} + +/* + *-------------------------------------------------------------- + * + * EmbWinStructureProc -- + * + * This procedure is invoked by the Tk event loop whenever + * StructureNotify events occur for a window that's embedded + * in a text widget. This procedure's only purpose is to + * clean up when windows are deleted. + * + * Results: + * None. + * + * Side effects: + * The window is disassociated from the window segment, and + * the portion of the text is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +EmbWinStructureProc(clientData, eventPtr) + ClientData clientData; /* Pointer to record describing window item. */ + XEvent *eventPtr; /* Describes what just happened. */ +{ + register TkTextSegment *ewPtr = (TkTextSegment *) clientData; + TkTextIndex index; + + if (eventPtr->type != DestroyNotify) { + return; + } + + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&ewPtr->body.ew.textPtr->windowTable, + Tk_PathName(ewPtr->body.ew.tkwin))); + ewPtr->body.ew.tkwin = NULL; + index.tree = ewPtr->body.ew.textPtr->tree; + index.linePtr = ewPtr->body.ew.linePtr; + index.charIndex = TkTextSegToOffset(ewPtr, ewPtr->body.ew.linePtr); + TkTextChanged(ewPtr->body.ew.textPtr, &index, &index); +} + +/* + *-------------------------------------------------------------- + * + * EmbWinRequestProc -- + * + * This procedure is invoked whenever a window that's associated + * with a window canvas item changes its requested dimensions. + * + * Results: + * None. + * + * Side effects: + * The size and location on the screen of the window may change, + * depending on the options specified for the window item. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +EmbWinRequestProc(clientData, tkwin) + ClientData clientData; /* Pointer to record for window item. */ + Tk_Window tkwin; /* Window that changed its desired + * size. */ +{ + TkTextSegment *ewPtr = (TkTextSegment *) clientData; + TkTextIndex index; + + index.tree = ewPtr->body.ew.textPtr->tree; + index.linePtr = ewPtr->body.ew.linePtr; + index.charIndex = TkTextSegToOffset(ewPtr, ewPtr->body.ew.linePtr); + TkTextChanged(ewPtr->body.ew.textPtr, &index, &index); +} + +/* + *-------------------------------------------------------------- + * + * EmbWinLostSlaveProc -- + * + * This procedure is invoked by the Tk geometry manager when + * a slave window managed by a text widget is claimed away + * by another geometry manager. + * + * Results: + * None. + * + * Side effects: + * The window is disassociated from the window segment, and + * the portion of the text is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +EmbWinLostSlaveProc(clientData, tkwin) + ClientData clientData; /* Pointer to record describing window item. */ + Tk_Window tkwin; /* Window that was claimed away by another + * geometry manager. */ +{ + register TkTextSegment *ewPtr = (TkTextSegment *) clientData; + TkTextIndex index; + + Tk_DeleteEventHandler(ewPtr->body.ew.tkwin, StructureNotifyMask, + EmbWinStructureProc, (ClientData) ewPtr); + Tcl_CancelIdleCall(EmbWinDelayedUnmap, (ClientData) ewPtr); + if (ewPtr->body.ew.textPtr->tkwin != Tk_Parent(tkwin)) { + Tk_UnmaintainGeometry(tkwin, ewPtr->body.ew.textPtr->tkwin); + } else { + Tk_UnmapWindow(tkwin); + } + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&ewPtr->body.ew.textPtr->windowTable, + Tk_PathName(ewPtr->body.ew.tkwin))); + ewPtr->body.ew.tkwin = NULL; + index.tree = ewPtr->body.ew.textPtr->tree; + index.linePtr = ewPtr->body.ew.linePtr; + index.charIndex = TkTextSegToOffset(ewPtr, ewPtr->body.ew.linePtr); + TkTextChanged(ewPtr->body.ew.textPtr, &index, &index); +} + +/* + *-------------------------------------------------------------- + * + * EmbWinDeleteProc -- + * + * This procedure is invoked by the text B-tree code whenever + * an embedded window lies in a range of characters being deleted. + * + * Results: + * Returns 0 to indicate that the deletion has been accepted. + * + * Side effects: + * The embedded window is deleted, if it exists, and any resources + * associated with it are released. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +static int +EmbWinDeleteProc(ewPtr, linePtr, treeGone) + TkTextSegment *ewPtr; /* Segment being deleted. */ + TkTextLine *linePtr; /* Line containing segment. */ + int treeGone; /* Non-zero means the entire tree is + * being deleted, so everything must + * get cleaned up. */ +{ + Tcl_HashEntry *hPtr; + + if (ewPtr->body.ew.tkwin != NULL) { + hPtr = Tcl_FindHashEntry(&ewPtr->body.ew.textPtr->windowTable, + Tk_PathName(ewPtr->body.ew.tkwin)); + if (hPtr != NULL) { + /* + * (It's possible for there to be no hash table entry for this + * window, if an error occurred while creating the window segment + * but before the window got added to the table) + */ + + Tcl_DeleteHashEntry(hPtr); + } + + /* + * Delete the event handler for the window before destroying + * the window, so that EmbWinStructureProc doesn't get called + * (we'll already do everything that it would have done, and + * it will just get confused). + */ + + Tk_DeleteEventHandler(ewPtr->body.ew.tkwin, StructureNotifyMask, + EmbWinStructureProc, (ClientData) ewPtr); + Tk_DestroyWindow(ewPtr->body.ew.tkwin); + } + Tcl_CancelIdleCall(EmbWinDelayedUnmap, (ClientData) ewPtr); + Tk_FreeOptions(configSpecs, (char *) &ewPtr->body.ew, + ewPtr->body.ew.textPtr->display, 0); + ckfree((char *) ewPtr); + return 0; +} + +/* + *-------------------------------------------------------------- + * + * EmbWinCleanupProc -- + * + * This procedure is invoked by the B-tree code whenever a + * segment containing an embedded window is moved from one + * line to another. + * + * Results: + * None. + * + * Side effects: + * The linePtr field of the segment gets updated. + * + *-------------------------------------------------------------- + */ + +static TkTextSegment * +EmbWinCleanupProc(ewPtr, linePtr) + TkTextSegment *ewPtr; /* Mark segment that's being moved. */ + TkTextLine *linePtr; /* Line that now contains segment. */ +{ + ewPtr->body.ew.linePtr = linePtr; + return ewPtr; +} + +/* + *-------------------------------------------------------------- + * + * EmbWinLayoutProc -- + * + * This procedure is the "layoutProc" for embedded window + * segments. + * + * Results: + * 1 is returned to indicate that the segment should be + * displayed. The chunkPtr structure is filled in. + * + * Side effects: + * None, except for filling in chunkPtr. + * + *-------------------------------------------------------------- + */ + + /*ARGSUSED*/ +static int +EmbWinLayoutProc(textPtr, indexPtr, ewPtr, offset, maxX, maxChars, + noCharsYet, wrapMode, chunkPtr) + TkText *textPtr; /* Text widget being layed out. */ + TkTextIndex *indexPtr; /* Identifies first character in chunk. */ + TkTextSegment *ewPtr; /* Segment corresponding to indexPtr. */ + int offset; /* Offset within segPtr corresponding to + * indexPtr (always 0). */ + int maxX; /* Chunk must not occupy pixels at this + * position or higher. */ + int maxChars; /* Chunk must not include more than this + * many characters. */ + int noCharsYet; /* Non-zero means no characters have been + * assigned to this line yet. */ + Tk_Uid wrapMode; /* Wrap mode to use for line: tkTextCharUid, + * tkTextNoneUid, or tkTextWordUid. */ + register TkTextDispChunk *chunkPtr; + /* Structure to fill in with information + * about this chunk. The x field has already + * been set by the caller. */ +{ + int width, height; + + if (offset != 0) { + panic("Non-zero offset in EmbWinLayoutProc"); + } + + if ((ewPtr->body.ew.tkwin == NULL) && (ewPtr->body.ew.create != NULL)) { + int code, new; + Tcl_DString name; + Tk_Window ancestor; + Tcl_HashEntry *hPtr; + + /* + * The window doesn't currently exist. Create it by evaluating + * the creation script. The script must return the window's + * path name: look up that name to get back to the window + * token. Then register ourselves as the geometry manager for + * the window. + */ + + code = Tcl_GlobalEval(textPtr->interp, ewPtr->body.ew.create); + if (code != TCL_OK) { + createError: + Tcl_BackgroundError(textPtr->interp); + goto gotWindow; + } + Tcl_DStringInit(&name); + Tcl_DStringAppend(&name, textPtr->interp->result, -1); + Tcl_ResetResult(textPtr->interp); + ewPtr->body.ew.tkwin = Tk_NameToWindow(textPtr->interp, + Tcl_DStringValue(&name), textPtr->tkwin); + if (ewPtr->body.ew.tkwin == NULL) { + goto createError; + } + for (ancestor = textPtr->tkwin; ; + ancestor = Tk_Parent(ancestor)) { + if (ancestor == Tk_Parent(ewPtr->body.ew.tkwin)) { + break; + } + if (Tk_IsTopLevel(ancestor)) { + badMaster: + Tcl_AppendResult(textPtr->interp, "can't embed ", + Tk_PathName(ewPtr->body.ew.tkwin), " relative to ", + Tk_PathName(textPtr->tkwin), (char *) NULL); + Tcl_BackgroundError(textPtr->interp); + ewPtr->body.ew.tkwin = NULL; + goto gotWindow; + } + } + if (Tk_IsTopLevel(ewPtr->body.ew.tkwin) + || (textPtr->tkwin == ewPtr->body.ew.tkwin)) { + goto badMaster; + } + Tk_ManageGeometry(ewPtr->body.ew.tkwin, &textGeomType, + (ClientData) ewPtr); + Tk_CreateEventHandler(ewPtr->body.ew.tkwin, StructureNotifyMask, + EmbWinStructureProc, (ClientData) ewPtr); + + /* + * Special trick! Must enter into the hash table *after* + * calling Tk_ManageGeometry: if the window was already managed + * elsewhere in this text, the Tk_ManageGeometry call will cause + * the entry to be removed, which could potentially lose the new + * entry. + */ + + hPtr = Tcl_CreateHashEntry(&textPtr->windowTable, + Tk_PathName(ewPtr->body.ew.tkwin), &new); + Tcl_SetHashValue(hPtr, ewPtr); + } + + /* + * See if there's room for this window on this line. + */ + + gotWindow: + if (ewPtr->body.ew.tkwin == NULL) { + width = 0; + height = 0; + } else { + width = Tk_ReqWidth(ewPtr->body.ew.tkwin) + 2*ewPtr->body.ew.padX; + height = Tk_ReqHeight(ewPtr->body.ew.tkwin) + 2*ewPtr->body.ew.padY; + } + if ((width > (maxX - chunkPtr->x)) + && !noCharsYet && (textPtr->wrapMode != tkTextNoneUid)) { + return 0; + } + + /* + * Fill in the chunk structure. + */ + + chunkPtr->displayProc = EmbWinDisplayProc; + chunkPtr->undisplayProc = EmbWinUndisplayProc; + chunkPtr->measureProc = (Tk_ChunkMeasureProc *) NULL; + chunkPtr->bboxProc = EmbWinBboxProc; + chunkPtr->numChars = 1; + if (ewPtr->body.ew.align == ALIGN_BASELINE) { + chunkPtr->minAscent = height - ewPtr->body.ew.padY; + chunkPtr->minDescent = ewPtr->body.ew.padY; + chunkPtr->minHeight = 0; + } else { + chunkPtr->minAscent = 0; + chunkPtr->minDescent = 0; + chunkPtr->minHeight = height; + } + chunkPtr->width = width; + chunkPtr->breakIndex = -1; + chunkPtr->breakIndex = 1; + chunkPtr->clientData = (ClientData) ewPtr; + ewPtr->body.ew.chunkCount += 1; + return 1; +} + +/* + *-------------------------------------------------------------- + * + * EmbWinCheckProc -- + * + * This procedure is invoked by the B-tree code to perform + * consistency checks on embedded windows. + * + * Results: + * None. + * + * Side effects: + * The procedure panics if it detects anything wrong with + * the embedded window. + * + *-------------------------------------------------------------- + */ + +static void +EmbWinCheckProc(ewPtr, linePtr) + TkTextSegment *ewPtr; /* Segment to check. */ + TkTextLine *linePtr; /* Line containing segment. */ +{ + if (ewPtr->nextPtr == NULL) { + panic("EmbWinCheckProc: embedded window is last segment in line"); + } + if (ewPtr->size != 1) { + panic("EmbWinCheckProc: embedded window has size %d", ewPtr->size); + } +} + +/* + *-------------------------------------------------------------- + * + * EmbWinDisplayProc -- + * + * This procedure is invoked by the text displaying code + * when it is time to actually draw an embedded window + * chunk on the screen. + * + * Results: + * None. + * + * Side effects: + * The embedded window gets moved to the correct location + * and mapped onto the screen. + * + *-------------------------------------------------------------- + */ + +static void +EmbWinDisplayProc(chunkPtr, x, y, lineHeight, baseline, display, dst, screenY) + TkTextDispChunk *chunkPtr; /* Chunk that is to be drawn. */ + int x; /* X-position in dst at which to + * draw this chunk (differs from + * the x-position in the chunk because + * of scrolling). */ + int y; /* Top of rectangular bounding box + * for line: tells where to draw this + * chunk in dst (x-position is in + * the chunk itself). */ + int lineHeight; /* Total height of line. */ + int baseline; /* Offset of baseline from y. */ + Display *display; /* Display to use for drawing. */ + Drawable dst; /* Pixmap or window in which to draw */ + int screenY; /* Y-coordinate in text window that + * corresponds to y. */ +{ + TkTextSegment *ewPtr = (TkTextSegment *) chunkPtr->clientData; + int lineX, windowX, windowY, width, height; + Tk_Window tkwin; + + tkwin = ewPtr->body.ew.tkwin; + if (tkwin == NULL) { + return; + } + if ((x + chunkPtr->width) <= 0) { + /* + * The window is off-screen; just unmap it. + */ + + if (ewPtr->body.ew.textPtr->tkwin != Tk_Parent(tkwin)) { + Tk_UnmaintainGeometry(tkwin, ewPtr->body.ew.textPtr->tkwin); + } else { + Tk_UnmapWindow(tkwin); + } + return; + } + + /* + * Compute the window's location and size in the text widget, taking + * into account the align and stretch values for the window. + */ + + EmbWinBboxProc(chunkPtr, 0, screenY, lineHeight, baseline, &lineX, + &windowY, &width, &height); + windowX = lineX - chunkPtr->x + x; + + if (ewPtr->body.ew.textPtr->tkwin == Tk_Parent(tkwin)) { + if ((windowX != Tk_X(tkwin)) || (windowY != Tk_Y(tkwin)) + || (Tk_ReqWidth(tkwin) != Tk_Width(tkwin)) + || (height != Tk_Height(tkwin))) { + Tk_MoveResizeWindow(tkwin, windowX, windowY, width, height); + } + Tk_MapWindow(tkwin); + } else { + Tk_MaintainGeometry(tkwin, ewPtr->body.ew.textPtr->tkwin, + windowX, windowY, width, height); + } + + /* + * Mark the window as displayed so that it won't get unmapped. + */ + + ewPtr->body.ew.displayed = 1; +} + +/* + *-------------------------------------------------------------- + * + * EmbWinUndisplayProc -- + * + * This procedure is called when the chunk for an embedded + * window is no longer going to be displayed. It arranges + * for the window associated with the chunk to be unmapped. + * + * Results: + * None. + * + * Side effects: + * The window is scheduled for unmapping. + * + *-------------------------------------------------------------- + */ + +static void +EmbWinUndisplayProc(textPtr, chunkPtr) + TkText *textPtr; /* Overall information about text + * widget. */ + TkTextDispChunk *chunkPtr; /* Chunk that is about to be freed. */ +{ + TkTextSegment *ewPtr = (TkTextSegment *) chunkPtr->clientData; + + ewPtr->body.ew.chunkCount--; + if (ewPtr->body.ew.chunkCount == 0) { + /* + * Don't unmap the window immediately, since there's a good chance + * that it will immediately be redisplayed, perhaps even in the + * same place. Instead, schedule the window to be unmapped later; + * the call to EmbWinDelayedUnmap will be cancelled in the likely + * event that the unmap becomes unnecessary. + */ + + ewPtr->body.ew.displayed = 0; + Tcl_DoWhenIdle(EmbWinDelayedUnmap, (ClientData) ewPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * EmbWinBboxProc -- + * + * This procedure is called to compute the bounding box of + * the area occupied by an embedded window. + * + * Results: + * There is no return value. *xPtr and *yPtr are filled in + * with the coordinates of the upper left corner of the + * window, and *widthPtr and *heightPtr are filled in with + * the dimensions of the window in pixels. Note: not all + * of the returned bbox is necessarily visible on the screen + * (the rightmost part might be off-screen to the right, + * and the bottommost part might be off-screen to the bottom). + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +static void +EmbWinBboxProc(chunkPtr, index, y, lineHeight, baseline, xPtr, yPtr, + widthPtr, heightPtr) + TkTextDispChunk *chunkPtr; /* Chunk containing desired char. */ + int index; /* Index of desired character within + * the chunk. */ + int y; /* Topmost pixel in area allocated + * for this line. */ + int lineHeight; /* Total height of line. */ + int baseline; /* Location of line's baseline, in + * pixels measured down from y. */ + int *xPtr, *yPtr; /* Gets filled in with coords of + * character's upper-left pixel. */ + int *widthPtr; /* Gets filled in with width of + * character, in pixels. */ + int *heightPtr; /* Gets filled in with height of + * character, in pixels. */ +{ + TkTextSegment *ewPtr = (TkTextSegment *) chunkPtr->clientData; + Tk_Window tkwin; + + tkwin = ewPtr->body.ew.tkwin; + if (tkwin != NULL) { + *widthPtr = Tk_ReqWidth(tkwin); + *heightPtr = Tk_ReqHeight(tkwin); + } else { + *widthPtr = 0; + *heightPtr = 0; + } + *xPtr = chunkPtr->x + ewPtr->body.ew.padX; + if (ewPtr->body.ew.stretch) { + if (ewPtr->body.ew.align == ALIGN_BASELINE) { + *heightPtr = baseline - ewPtr->body.ew.padY; + } else { + *heightPtr = lineHeight - 2*ewPtr->body.ew.padY; + } + } + switch (ewPtr->body.ew.align) { + case ALIGN_BOTTOM: + *yPtr = y + (lineHeight - *heightPtr - ewPtr->body.ew.padY); + break; + case ALIGN_CENTER: + *yPtr = y + (lineHeight - *heightPtr)/2; + break; + case ALIGN_TOP: + *yPtr = y + ewPtr->body.ew.padY; + break; + case ALIGN_BASELINE: + *yPtr = y + (baseline - *heightPtr); + break; + } +} + +/* + *-------------------------------------------------------------- + * + * EmbWinDelayedUnmap -- + * + * This procedure is an idle handler that does the actual + * work of unmapping an embedded window. See the comment + * in EmbWinUndisplayProc for details. + * + * Results: + * None. + * + * Side effects: + * The window gets unmapped, unless its chunk reference count + * has become non-zero again. + * + *-------------------------------------------------------------- + */ + +static void +EmbWinDelayedUnmap(clientData) + ClientData clientData; /* Token for the window to + * be unmapped. */ +{ + TkTextSegment *ewPtr = (TkTextSegment *) clientData; + + if (!ewPtr->body.ew.displayed && (ewPtr->body.ew.tkwin != NULL)) { + if (ewPtr->body.ew.textPtr->tkwin != Tk_Parent(ewPtr->body.ew.tkwin)) { + Tk_UnmaintainGeometry(ewPtr->body.ew.tkwin, + ewPtr->body.ew.textPtr->tkwin); + } else { + Tk_UnmapWindow(ewPtr->body.ew.tkwin); + } + } +} + +/* + *-------------------------------------------------------------- + * + * TkTextWindowIndex -- + * + * Given the name of an embedded window within a text widget, + * returns an index corresponding to the window's position + * in the text. + * + * Results: + * The return value is 1 if there is an embedded window by + * the given name in the text widget, 0 otherwise. If the + * window exists, *indexPtr is filled in with its index. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkTextWindowIndex(textPtr, name, indexPtr) + TkText *textPtr; /* Text widget containing window. */ + char *name; /* Name of window. */ + TkTextIndex *indexPtr; /* Index information gets stored here. */ +{ + Tcl_HashEntry *hPtr; + TkTextSegment *ewPtr; + + hPtr = Tcl_FindHashEntry(&textPtr->windowTable, name); + if (hPtr == NULL) { + return 0; + } + ewPtr = (TkTextSegment *) Tcl_GetHashValue(hPtr); + indexPtr->tree = textPtr->tree; + indexPtr->linePtr = ewPtr->body.ew.linePtr; + indexPtr->charIndex = TkTextSegToOffset(ewPtr, indexPtr->linePtr); + return 1; +} diff --git a/generic/tkTrig.c b/generic/tkTrig.c new file mode 100644 index 0000000..52dd8ba --- /dev/null +++ b/generic/tkTrig.c @@ -0,0 +1,1467 @@ +/* + * tkTrig.c -- + * + * This file contains a collection of trigonometry utility + * routines that are used by Tk and in particular by the + * canvas code. It also has miscellaneous geometry functions + * used by canvases. + * + * Copyright (c) 1992-1994 The Regents of the University of California. + * Copyright (c) 1994 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkTrig.c 1.27 97/03/07 11:34:35 + */ + +#include <stdio.h> +#include "tkInt.h" +#include "tkPort.h" +#include "tkCanvas.h" + +#undef MIN +#define MIN(a,b) (((a) < (b)) ? (a) : (b)) +#undef MAX +#define MAX(a,b) (((a) > (b)) ? (a) : (b)) +#ifndef PI +# define PI 3.14159265358979323846 +#endif /* PI */ + +/* + *-------------------------------------------------------------- + * + * TkLineToPoint -- + * + * Compute the distance from a point to a finite line segment. + * + * Results: + * The return value is the distance from the line segment + * whose end-points are *end1Ptr and *end2Ptr to the point + * given by *pointPtr. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +double +TkLineToPoint(end1Ptr, end2Ptr, pointPtr) + double end1Ptr[2]; /* Coordinates of first end-point of line. */ + double end2Ptr[2]; /* Coordinates of second end-point of line. */ + double pointPtr[2]; /* Points to coords for point. */ +{ + double x, y; + + /* + * Compute the point on the line that is closest to the + * point. This must be done separately for vertical edges, + * horizontal edges, and other edges. + */ + + if (end1Ptr[0] == end2Ptr[0]) { + + /* + * Vertical edge. + */ + + x = end1Ptr[0]; + if (end1Ptr[1] >= end2Ptr[1]) { + y = MIN(end1Ptr[1], pointPtr[1]); + y = MAX(y, end2Ptr[1]); + } else { + y = MIN(end2Ptr[1], pointPtr[1]); + y = MAX(y, end1Ptr[1]); + } + } else if (end1Ptr[1] == end2Ptr[1]) { + + /* + * Horizontal edge. + */ + + y = end1Ptr[1]; + if (end1Ptr[0] >= end2Ptr[0]) { + x = MIN(end1Ptr[0], pointPtr[0]); + x = MAX(x, end2Ptr[0]); + } else { + x = MIN(end2Ptr[0], pointPtr[0]); + x = MAX(x, end1Ptr[0]); + } + } else { + double m1, b1, m2, b2; + + /* + * The edge is neither horizontal nor vertical. Convert the + * edge to a line equation of the form y = m1*x + b1. Then + * compute a line perpendicular to this edge but passing + * through the point, also in the form y = m2*x + b2. + */ + + m1 = (end2Ptr[1] - end1Ptr[1])/(end2Ptr[0] - end1Ptr[0]); + b1 = end1Ptr[1] - m1*end1Ptr[0]; + m2 = -1.0/m1; + b2 = pointPtr[1] - m2*pointPtr[0]; + x = (b2 - b1)/(m1 - m2); + y = m1*x + b1; + if (end1Ptr[0] > end2Ptr[0]) { + if (x > end1Ptr[0]) { + x = end1Ptr[0]; + y = end1Ptr[1]; + } else if (x < end2Ptr[0]) { + x = end2Ptr[0]; + y = end2Ptr[1]; + } + } else { + if (x > end2Ptr[0]) { + x = end2Ptr[0]; + y = end2Ptr[1]; + } else if (x < end1Ptr[0]) { + x = end1Ptr[0]; + y = end1Ptr[1]; + } + } + } + + /* + * Compute the distance to the closest point. + */ + + return hypot(pointPtr[0] - x, pointPtr[1] - y); +} + +/* + *-------------------------------------------------------------- + * + * TkLineToArea -- + * + * Determine whether a line lies entirely inside, entirely + * outside, or overlapping a given rectangular area. + * + * Results: + * -1 is returned if the line given by end1Ptr and end2Ptr + * is entirely outside the rectangle given by rectPtr. 0 is + * returned if the polygon overlaps the rectangle, and 1 is + * returned if the polygon is entirely inside the rectangle. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkLineToArea(end1Ptr, end2Ptr, rectPtr) + double end1Ptr[2]; /* X and y coordinates for one endpoint + * of line. */ + double end2Ptr[2]; /* X and y coordinates for other endpoint + * of line. */ + double rectPtr[4]; /* Points to coords for rectangle, in the + * order x1, y1, x2, y2. X1 must be no + * larger than x2, and y1 no larger than y2. */ +{ + int inside1, inside2; + + /* + * First check the two points individually to see whether they + * are inside the rectangle or not. + */ + + inside1 = (end1Ptr[0] >= rectPtr[0]) && (end1Ptr[0] <= rectPtr[2]) + && (end1Ptr[1] >= rectPtr[1]) && (end1Ptr[1] <= rectPtr[3]); + inside2 = (end2Ptr[0] >= rectPtr[0]) && (end2Ptr[0] <= rectPtr[2]) + && (end2Ptr[1] >= rectPtr[1]) && (end2Ptr[1] <= rectPtr[3]); + if (inside1 != inside2) { + return 0; + } + if (inside1 & inside2) { + return 1; + } + + /* + * Both points are outside the rectangle, but still need to check + * for intersections between the line and the rectangle. Horizontal + * and vertical lines are particularly easy, so handle them + * separately. + */ + + if (end1Ptr[0] == end2Ptr[0]) { + /* + * Vertical line. + */ + + if (((end1Ptr[1] >= rectPtr[1]) ^ (end2Ptr[1] >= rectPtr[1])) + && (end1Ptr[0] >= rectPtr[0]) + && (end1Ptr[0] <= rectPtr[2])) { + return 0; + } + } else if (end1Ptr[1] == end2Ptr[1]) { + /* + * Horizontal line. + */ + + if (((end1Ptr[0] >= rectPtr[0]) ^ (end2Ptr[0] >= rectPtr[0])) + && (end1Ptr[1] >= rectPtr[1]) + && (end1Ptr[1] <= rectPtr[3])) { + return 0; + } + } else { + double m, x, y, low, high; + + /* + * Diagonal line. Compute slope of line and use + * for intersection checks against each of the + * sides of the rectangle: left, right, bottom, top. + */ + + m = (end2Ptr[1] - end1Ptr[1])/(end2Ptr[0] - end1Ptr[0]); + if (end1Ptr[0] < end2Ptr[0]) { + low = end1Ptr[0]; high = end2Ptr[0]; + } else { + low = end2Ptr[0]; high = end1Ptr[0]; + } + + /* + * Left edge. + */ + + y = end1Ptr[1] + (rectPtr[0] - end1Ptr[0])*m; + if ((rectPtr[0] >= low) && (rectPtr[0] <= high) + && (y >= rectPtr[1]) && (y <= rectPtr[3])) { + return 0; + } + + /* + * Right edge. + */ + + y += (rectPtr[2] - rectPtr[0])*m; + if ((y >= rectPtr[1]) && (y <= rectPtr[3]) + && (rectPtr[2] >= low) && (rectPtr[2] <= high)) { + return 0; + } + + /* + * Bottom edge. + */ + + if (end1Ptr[1] < end2Ptr[1]) { + low = end1Ptr[1]; high = end2Ptr[1]; + } else { + low = end2Ptr[1]; high = end1Ptr[1]; + } + x = end1Ptr[0] + (rectPtr[1] - end1Ptr[1])/m; + if ((x >= rectPtr[0]) && (x <= rectPtr[2]) + && (rectPtr[1] >= low) && (rectPtr[1] <= high)) { + return 0; + } + + /* + * Top edge. + */ + + x += (rectPtr[3] - rectPtr[1])/m; + if ((x >= rectPtr[0]) && (x <= rectPtr[2]) + && (rectPtr[3] >= low) && (rectPtr[3] <= high)) { + return 0; + } + } + return -1; +} + +/* + *-------------------------------------------------------------- + * + * TkThickPolyLineToArea -- + * + * This procedure is called to determine whether a connected + * series of line segments lies entirely inside, entirely + * outside, or overlapping a given rectangular area. + * + * Results: + * -1 is returned if the lines are entirely outside the area, + * 0 if they overlap, and 1 if they are entirely inside the + * given area. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +TkThickPolyLineToArea(coordPtr, numPoints, width, capStyle, joinStyle, rectPtr) + double *coordPtr; /* Points to an array of coordinates for + * the polyline: x0, y0, x1, y1, ... */ + int numPoints; /* Total number of points at *coordPtr. */ + double width; /* Width of each line segment. */ + int capStyle; /* How are end-points of polyline drawn? + * CapRound, CapButt, or CapProjecting. */ + int joinStyle; /* How are joints in polyline drawn? + * JoinMiter, JoinRound, or JoinBevel. */ + double *rectPtr; /* Rectangular area to check against. */ +{ + double radius, poly[10]; + int count; + int changedMiterToBevel; /* Non-zero means that a mitered corner + * had to be treated as beveled after all + * because the angle was < 11 degrees. */ + int inside; /* Tentative guess about what to return, + * based on all points seen so far: one + * means everything seen so far was + * inside the area; -1 means everything + * was outside the area. 0 means overlap + * has been found. */ + + radius = width/2.0; + inside = -1; + + if ((coordPtr[0] >= rectPtr[0]) && (coordPtr[0] <= rectPtr[2]) + && (coordPtr[1] >= rectPtr[1]) && (coordPtr[1] <= rectPtr[3])) { + inside = 1; + } + + /* + * Iterate through all of the edges of the line, computing a polygon + * for each edge and testing the area against that polygon. In + * addition, there are additional tests to deal with rounded joints + * and caps. + */ + + changedMiterToBevel = 0; + for (count = numPoints; count >= 2; count--, coordPtr += 2) { + + /* + * If rounding is done around the first point of the edge + * then test a circular region around the point with the + * area. + */ + + if (((capStyle == CapRound) && (count == numPoints)) + || ((joinStyle == JoinRound) && (count != numPoints))) { + poly[0] = coordPtr[0] - radius; + poly[1] = coordPtr[1] - radius; + poly[2] = coordPtr[0] + radius; + poly[3] = coordPtr[1] + radius; + if (TkOvalToArea(poly, rectPtr) != inside) { + return 0; + } + } + + /* + * Compute the polygonal shape corresponding to this edge, + * consisting of two points for the first point of the edge + * and two points for the last point of the edge. + */ + + if (count == numPoints) { + TkGetButtPoints(coordPtr+2, coordPtr, width, + capStyle == CapProjecting, poly, poly+2); + } else if ((joinStyle == JoinMiter) && !changedMiterToBevel) { + poly[0] = poly[6]; + poly[1] = poly[7]; + poly[2] = poly[4]; + poly[3] = poly[5]; + } else { + TkGetButtPoints(coordPtr+2, coordPtr, width, 0, poly, poly+2); + + /* + * If the last joint was beveled, then also check a + * polygon comprising the last two points of the previous + * polygon and the first two from this polygon; this checks + * the wedges that fill the beveled joint. + */ + + if ((joinStyle == JoinBevel) || changedMiterToBevel) { + poly[8] = poly[0]; + poly[9] = poly[1]; + if (TkPolygonToArea(poly, 5, rectPtr) != inside) { + return 0; + } + changedMiterToBevel = 0; + } + } + if (count == 2) { + TkGetButtPoints(coordPtr, coordPtr+2, width, + capStyle == CapProjecting, poly+4, poly+6); + } else if (joinStyle == JoinMiter) { + if (TkGetMiterPoints(coordPtr, coordPtr+2, coordPtr+4, + (double) width, poly+4, poly+6) == 0) { + changedMiterToBevel = 1; + TkGetButtPoints(coordPtr, coordPtr+2, width, 0, poly+4, + poly+6); + } + } else { + TkGetButtPoints(coordPtr, coordPtr+2, width, 0, poly+4, poly+6); + } + poly[8] = poly[0]; + poly[9] = poly[1]; + if (TkPolygonToArea(poly, 5, rectPtr) != inside) { + return 0; + } + } + + /* + * If caps are rounded, check the cap around the final point + * of the line. + */ + + if (capStyle == CapRound) { + poly[0] = coordPtr[0] - radius; + poly[1] = coordPtr[1] - radius; + poly[2] = coordPtr[0] + radius; + poly[3] = coordPtr[1] + radius; + if (TkOvalToArea(poly, rectPtr) != inside) { + return 0; + } + } + + return inside; +} + +/* + *-------------------------------------------------------------- + * + * TkPolygonToPoint -- + * + * Compute the distance from a point to a polygon. + * + * Results: + * The return value is 0.0 if the point referred to by + * pointPtr is within the polygon referred to by polyPtr + * and numPoints. Otherwise the return value is the + * distance of the point from the polygon. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +double +TkPolygonToPoint(polyPtr, numPoints, pointPtr) + double *polyPtr; /* Points to an array coordinates for + * closed polygon: x0, y0, x1, y1, ... + * The polygon may be self-intersecting. */ + int numPoints; /* Total number of points at *polyPtr. */ + double *pointPtr; /* Points to coords for point. */ +{ + double bestDist; /* Closest distance between point and + * any edge in polygon. */ + int intersections; /* Number of edges in the polygon that + * intersect a ray extending vertically + * upwards from the point to infinity. */ + int count; + register double *pPtr; + + /* + * Iterate through all of the edges in the polygon, updating + * bestDist and intersections. + * + * TRICKY POINT: when computing intersections, include left + * x-coordinate of line within its range, but not y-coordinate. + * Otherwise if the point lies exactly below a vertex we'll + * count it as two intersections. + */ + + bestDist = 1.0e36; + intersections = 0; + + for (count = numPoints, pPtr = polyPtr; count > 1; count--, pPtr += 2) { + double x, y, dist; + + /* + * Compute the point on the current edge closest to the point + * and update the intersection count. This must be done + * separately for vertical edges, horizontal edges, and + * other edges. + */ + + if (pPtr[2] == pPtr[0]) { + + /* + * Vertical edge. + */ + + x = pPtr[0]; + if (pPtr[1] >= pPtr[3]) { + y = MIN(pPtr[1], pointPtr[1]); + y = MAX(y, pPtr[3]); + } else { + y = MIN(pPtr[3], pointPtr[1]); + y = MAX(y, pPtr[1]); + } + } else if (pPtr[3] == pPtr[1]) { + + /* + * Horizontal edge. + */ + + y = pPtr[1]; + if (pPtr[0] >= pPtr[2]) { + x = MIN(pPtr[0], pointPtr[0]); + x = MAX(x, pPtr[2]); + if ((pointPtr[1] < y) && (pointPtr[0] < pPtr[0]) + && (pointPtr[0] >= pPtr[2])) { + intersections++; + } + } else { + x = MIN(pPtr[2], pointPtr[0]); + x = MAX(x, pPtr[0]); + if ((pointPtr[1] < y) && (pointPtr[0] < pPtr[2]) + && (pointPtr[0] >= pPtr[0])) { + intersections++; + } + } + } else { + double m1, b1, m2, b2; + int lower; /* Non-zero means point below line. */ + + /* + * The edge is neither horizontal nor vertical. Convert the + * edge to a line equation of the form y = m1*x + b1. Then + * compute a line perpendicular to this edge but passing + * through the point, also in the form y = m2*x + b2. + */ + + m1 = (pPtr[3] - pPtr[1])/(pPtr[2] - pPtr[0]); + b1 = pPtr[1] - m1*pPtr[0]; + m2 = -1.0/m1; + b2 = pointPtr[1] - m2*pointPtr[0]; + x = (b2 - b1)/(m1 - m2); + y = m1*x + b1; + if (pPtr[0] > pPtr[2]) { + if (x > pPtr[0]) { + x = pPtr[0]; + y = pPtr[1]; + } else if (x < pPtr[2]) { + x = pPtr[2]; + y = pPtr[3]; + } + } else { + if (x > pPtr[2]) { + x = pPtr[2]; + y = pPtr[3]; + } else if (x < pPtr[0]) { + x = pPtr[0]; + y = pPtr[1]; + } + } + lower = (m1*pointPtr[0] + b1) > pointPtr[1]; + if (lower && (pointPtr[0] >= MIN(pPtr[0], pPtr[2])) + && (pointPtr[0] < MAX(pPtr[0], pPtr[2]))) { + intersections++; + } + } + + /* + * Compute the distance to the closest point, and see if that + * is the best distance seen so far. + */ + + dist = hypot(pointPtr[0] - x, pointPtr[1] - y); + if (dist < bestDist) { + bestDist = dist; + } + } + + /* + * We've processed all of the points. If the number of intersections + * is odd, the point is inside the polygon. + */ + + if (intersections & 0x1) { + return 0.0; + } + return bestDist; +} + +/* + *-------------------------------------------------------------- + * + * TkPolygonToArea -- + * + * Determine whether a polygon lies entirely inside, entirely + * outside, or overlapping a given rectangular area. + * + * Results: + * -1 is returned if the polygon given by polyPtr and numPoints + * is entirely outside the rectangle given by rectPtr. 0 is + * returned if the polygon overlaps the rectangle, and 1 is + * returned if the polygon is entirely inside the rectangle. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkPolygonToArea(polyPtr, numPoints, rectPtr) + double *polyPtr; /* Points to an array coordinates for + * closed polygon: x0, y0, x1, y1, ... + * The polygon may be self-intersecting. */ + int numPoints; /* Total number of points at *polyPtr. */ + register double *rectPtr; /* Points to coords for rectangle, in the + * order x1, y1, x2, y2. X1 and y1 must + * be lower-left corner. */ +{ + int state; /* State of all edges seen so far (-1 means + * outside, 1 means inside, won't ever be + * 0). */ + int count; + register double *pPtr; + + /* + * Iterate over all of the edges of the polygon and test them + * against the rectangle. Can quit as soon as the state becomes + * "intersecting". + */ + + state = TkLineToArea(polyPtr, polyPtr+2, rectPtr); + if (state == 0) { + return 0; + } + for (pPtr = polyPtr+2, count = numPoints-1; count >= 2; + pPtr += 2, count--) { + if (TkLineToArea(pPtr, pPtr+2, rectPtr) != state) { + return 0; + } + } + + /* + * If all of the edges were inside the rectangle we're done. + * If all of the edges were outside, then the rectangle could + * still intersect the polygon (if it's entirely enclosed). + * Call TkPolygonToPoint to figure this out. + */ + + if (state == 1) { + return 1; + } + if (TkPolygonToPoint(polyPtr, numPoints, rectPtr) == 0.0) { + return 0; + } + return -1; +} + +/* + *-------------------------------------------------------------- + * + * TkOvalToPoint -- + * + * Computes the distance from a given point to a given + * oval, in canvas units. + * + * Results: + * The return value is 0 if the point given by *pointPtr is + * inside the oval. If the point isn't inside the + * oval then the return value is approximately the distance + * from the point to the oval. If the oval is filled, then + * anywhere in the interior is considered "inside"; if + * the oval isn't filled, then "inside" means only the area + * occupied by the outline. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +double +TkOvalToPoint(ovalPtr, width, filled, pointPtr) + double ovalPtr[4]; /* Pointer to array of four coordinates + * (x1, y1, x2, y2) defining oval's bounding + * box. */ + double width; /* Width of outline for oval. */ + int filled; /* Non-zero means oval should be treated as + * filled; zero means only consider outline. */ + double pointPtr[2]; /* Coordinates of point. */ +{ + double xDelta, yDelta, scaledDistance, distToOutline, distToCenter; + double xDiam, yDiam; + + /* + * Compute the distance between the center of the oval and the + * point in question, using a coordinate system where the oval + * has been transformed to a circle with unit radius. + */ + + xDelta = (pointPtr[0] - (ovalPtr[0] + ovalPtr[2])/2.0); + yDelta = (pointPtr[1] - (ovalPtr[1] + ovalPtr[3])/2.0); + distToCenter = hypot(xDelta, yDelta); + scaledDistance = hypot(xDelta / ((ovalPtr[2] + width - ovalPtr[0])/2.0), + yDelta / ((ovalPtr[3] + width - ovalPtr[1])/2.0)); + + + /* + * If the scaled distance is greater than 1 then it means no + * hit. Compute the distance from the point to the edge of + * the circle, then scale this distance back to the original + * coordinate system. + * + * Note: this distance isn't completely accurate. It's only + * an approximation, and it can overestimate the correct + * distance when the oval is eccentric. + */ + + if (scaledDistance > 1.0) { + return (distToCenter/scaledDistance) * (scaledDistance - 1.0); + } + + /* + * Scaled distance less than 1 means the point is inside the + * outer edge of the oval. If this is a filled oval, then we + * have a hit. Otherwise, do the same computation as above + * (scale back to original coordinate system), but also check + * to see if the point is within the width of the outline. + */ + + if (filled) { + return 0.0; + } + if (scaledDistance > 1E-10) { + distToOutline = (distToCenter/scaledDistance) * (1.0 - scaledDistance) + - width; + } else { + /* + * Avoid dividing by a very small number (it could cause an + * arithmetic overflow). This problem occurs if the point is + * very close to the center of the oval. + */ + + xDiam = ovalPtr[2] - ovalPtr[0]; + yDiam = ovalPtr[3] - ovalPtr[1]; + if (xDiam < yDiam) { + distToOutline = (xDiam - width)/2; + } else { + distToOutline = (yDiam - width)/2; + } + } + + if (distToOutline < 0.0) { + return 0.0; + } + return distToOutline; +} + +/* + *-------------------------------------------------------------- + * + * TkOvalToArea -- + * + * Determine whether an oval lies entirely inside, entirely + * outside, or overlapping a given rectangular area. + * + * Results: + * -1 is returned if the oval described by ovalPtr is entirely + * outside the rectangle given by rectPtr. 0 is returned if the + * oval overlaps the rectangle, and 1 is returned if the oval + * is entirely inside the rectangle. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkOvalToArea(ovalPtr, rectPtr) + register double *ovalPtr; /* Points to coordinates definining the + * bounding rectangle for the oval: x1, y1, + * x2, y2. X1 must be less than x2 and y1 + * less than y2. */ + register double *rectPtr; /* Points to coords for rectangle, in the + * order x1, y1, x2, y2. X1 and y1 must + * be lower-left corner. */ +{ + double centerX, centerY, radX, radY, deltaX, deltaY; + + /* + * First, see if oval is entirely inside rectangle or entirely + * outside rectangle. + */ + + if ((rectPtr[0] <= ovalPtr[0]) && (rectPtr[2] >= ovalPtr[2]) + && (rectPtr[1] <= ovalPtr[1]) && (rectPtr[3] >= ovalPtr[3])) { + return 1; + } + if ((rectPtr[2] < ovalPtr[0]) || (rectPtr[0] > ovalPtr[2]) + || (rectPtr[3] < ovalPtr[1]) || (rectPtr[1] > ovalPtr[3])) { + return -1; + } + + /* + * Next, go through the rectangle side by side. For each side + * of the rectangle, find the point on the side that is closest + * to the oval's center, and see if that point is inside the + * oval. If at least one such point is inside the oval, then + * the rectangle intersects the oval. + */ + + centerX = (ovalPtr[0] + ovalPtr[2])/2; + centerY = (ovalPtr[1] + ovalPtr[3])/2; + radX = (ovalPtr[2] - ovalPtr[0])/2; + radY = (ovalPtr[3] - ovalPtr[1])/2; + + deltaY = rectPtr[1] - centerY; + if (deltaY < 0.0) { + deltaY = centerY - rectPtr[3]; + if (deltaY < 0.0) { + deltaY = 0; + } + } + deltaY /= radY; + deltaY *= deltaY; + + /* + * Left side: + */ + + deltaX = (rectPtr[0] - centerX)/radX; + deltaX *= deltaX; + if ((deltaX + deltaY) <= 1.0) { + return 0; + } + + /* + * Right side: + */ + + deltaX = (rectPtr[2] - centerX)/radX; + deltaX *= deltaX; + if ((deltaX + deltaY) <= 1.0) { + return 0; + } + + deltaX = rectPtr[0] - centerX; + if (deltaX < 0.0) { + deltaX = centerX - rectPtr[2]; + if (deltaX < 0.0) { + deltaX = 0; + } + } + deltaX /= radX; + deltaX *= deltaX; + + /* + * Bottom side: + */ + + deltaY = (rectPtr[1] - centerY)/radY; + deltaY *= deltaY; + if ((deltaX + deltaY) < 1.0) { + return 0; + } + + /* + * Top side: + */ + + deltaY = (rectPtr[3] - centerY)/radY; + deltaY *= deltaY; + if ((deltaX + deltaY) < 1.0) { + return 0; + } + + return -1; +} + +/* + *-------------------------------------------------------------- + * + * TkIncludePoint -- + * + * Given a point and a generic canvas item header, expand + * the item's bounding box if needed to include the point. + * + * Results: + * None. + * + * Side effects: + * The boudn. + * + *-------------------------------------------------------------- + */ + + /* ARGSUSED */ +void +TkIncludePoint(itemPtr, pointPtr) + register Tk_Item *itemPtr; /* Item whose bounding box is + * being calculated. */ + double *pointPtr; /* Address of two doubles giving + * x and y coordinates of point. */ +{ + int tmp; + + tmp = (int) (pointPtr[0] + 0.5); + if (tmp < itemPtr->x1) { + itemPtr->x1 = tmp; + } + if (tmp > itemPtr->x2) { + itemPtr->x2 = tmp; + } + tmp = (int) (pointPtr[1] + 0.5); + if (tmp < itemPtr->y1) { + itemPtr->y1 = tmp; + } + if (tmp > itemPtr->y2) { + itemPtr->y2 = tmp; + } +} + +/* + *-------------------------------------------------------------- + * + * TkBezierScreenPoints -- + * + * Given four control points, create a larger set of XPoints + * for a Bezier spline based on the points. + * + * Results: + * The array at *xPointPtr gets filled in with numSteps XPoints + * corresponding to the Bezier spline defined by the four + * control points. Note: no output point is generated for the + * first input point, but an output point *is* generated for + * the last input point. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +TkBezierScreenPoints(canvas, control, numSteps, xPointPtr) + Tk_Canvas canvas; /* Canvas in which curve is to be + * drawn. */ + double control[]; /* Array of coordinates for four + * control points: x0, y0, x1, y1, + * ... x3 y3. */ + int numSteps; /* Number of curve points to + * generate. */ + register XPoint *xPointPtr; /* Where to put new points. */ +{ + int i; + double u, u2, u3, t, t2, t3; + + for (i = 1; i <= numSteps; i++, xPointPtr++) { + t = ((double) i)/((double) numSteps); + t2 = t*t; + t3 = t2*t; + u = 1.0 - t; + u2 = u*u; + u3 = u2*u; + Tk_CanvasDrawableCoords(canvas, + (control[0]*u3 + 3.0 * (control[2]*t*u2 + control[4]*t2*u) + + control[6]*t3), + (control[1]*u3 + 3.0 * (control[3]*t*u2 + control[5]*t2*u) + + control[7]*t3), + &xPointPtr->x, &xPointPtr->y); + } +} + +/* + *-------------------------------------------------------------- + * + * TkBezierPoints -- + * + * Given four control points, create a larger set of points + * for a Bezier spline based on the points. + * + * Results: + * The array at *coordPtr gets filled in with 2*numSteps + * coordinates, which correspond to the Bezier spline defined + * by the four control points. Note: no output point is + * generated for the first input point, but an output point + * *is* generated for the last input point. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +TkBezierPoints(control, numSteps, coordPtr) + double control[]; /* Array of coordinates for four + * control points: x0, y0, x1, y1, + * ... x3 y3. */ + int numSteps; /* Number of curve points to + * generate. */ + register double *coordPtr; /* Where to put new points. */ +{ + int i; + double u, u2, u3, t, t2, t3; + + for (i = 1; i <= numSteps; i++, coordPtr += 2) { + t = ((double) i)/((double) numSteps); + t2 = t*t; + t3 = t2*t; + u = 1.0 - t; + u2 = u*u; + u3 = u2*u; + coordPtr[0] = control[0]*u3 + + 3.0 * (control[2]*t*u2 + control[4]*t2*u) + control[6]*t3; + coordPtr[1] = control[1]*u3 + + 3.0 * (control[3]*t*u2 + control[5]*t2*u) + control[7]*t3; + } +} + +/* + *-------------------------------------------------------------- + * + * TkMakeBezierCurve -- + * + * Given a set of points, create a new set of points that fit + * parabolic splines to the line segments connecting the original + * points. Produces output points in either of two forms. + * + * Note: in spite of this procedure's name, it does *not* generate + * Bezier curves. Since only three control points are used for + * each curve segment, not four, the curves are actually just + * parabolic. + * + * Results: + * Either or both of the xPoints or dblPoints arrays are filled + * in. The return value is the number of points placed in the + * arrays. Note: if the first and last points are the same, then + * a closed curve is generated. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkMakeBezierCurve(canvas, pointPtr, numPoints, numSteps, xPoints, dblPoints) + Tk_Canvas canvas; /* Canvas in which curve is to be + * drawn. */ + double *pointPtr; /* Array of input coordinates: x0, + * y0, x1, y1, etc.. */ + int numPoints; /* Number of points at pointPtr. */ + int numSteps; /* Number of steps to use for each + * spline segments (determines + * smoothness of curve). */ + XPoint xPoints[]; /* Array of XPoints to fill in (e.g. + * for display. NULL means don't + * fill in any XPoints. */ + double dblPoints[]; /* Array of points to fill in as + * doubles, in the form x0, y0, + * x1, y1, .... NULL means don't + * fill in anything in this form. + * Caller must make sure that this + * array has enough space. */ +{ + int closed, outputPoints, i; + int numCoords = numPoints*2; + double control[8]; + + /* + * If the curve is a closed one then generate a special spline + * that spans the last points and the first ones. Otherwise + * just put the first point into the output. + */ + + outputPoints = 0; + if ((pointPtr[0] == pointPtr[numCoords-2]) + && (pointPtr[1] == pointPtr[numCoords-1])) { + closed = 1; + control[0] = 0.5*pointPtr[numCoords-4] + 0.5*pointPtr[0]; + control[1] = 0.5*pointPtr[numCoords-3] + 0.5*pointPtr[1]; + control[2] = 0.167*pointPtr[numCoords-4] + 0.833*pointPtr[0]; + control[3] = 0.167*pointPtr[numCoords-3] + 0.833*pointPtr[1]; + control[4] = 0.833*pointPtr[0] + 0.167*pointPtr[2]; + control[5] = 0.833*pointPtr[1] + 0.167*pointPtr[3]; + control[6] = 0.5*pointPtr[0] + 0.5*pointPtr[2]; + control[7] = 0.5*pointPtr[1] + 0.5*pointPtr[3]; + if (xPoints != NULL) { + Tk_CanvasDrawableCoords(canvas, control[0], control[1], + &xPoints->x, &xPoints->y); + TkBezierScreenPoints(canvas, control, numSteps, xPoints+1); + xPoints += numSteps+1; + } + if (dblPoints != NULL) { + dblPoints[0] = control[0]; + dblPoints[1] = control[1]; + TkBezierPoints(control, numSteps, dblPoints+2); + dblPoints += 2*(numSteps+1); + } + outputPoints += numSteps+1; + } else { + closed = 0; + if (xPoints != NULL) { + Tk_CanvasDrawableCoords(canvas, pointPtr[0], pointPtr[1], + &xPoints->x, &xPoints->y); + xPoints += 1; + } + if (dblPoints != NULL) { + dblPoints[0] = pointPtr[0]; + dblPoints[1] = pointPtr[1]; + dblPoints += 2; + } + outputPoints += 1; + } + + for (i = 2; i < numPoints; i++, pointPtr += 2) { + /* + * Set up the first two control points. This is done + * differently for the first spline of an open curve + * than for other cases. + */ + + if ((i == 2) && !closed) { + control[0] = pointPtr[0]; + control[1] = pointPtr[1]; + control[2] = 0.333*pointPtr[0] + 0.667*pointPtr[2]; + control[3] = 0.333*pointPtr[1] + 0.667*pointPtr[3]; + } else { + control[0] = 0.5*pointPtr[0] + 0.5*pointPtr[2]; + control[1] = 0.5*pointPtr[1] + 0.5*pointPtr[3]; + control[2] = 0.167*pointPtr[0] + 0.833*pointPtr[2]; + control[3] = 0.167*pointPtr[1] + 0.833*pointPtr[3]; + } + + /* + * Set up the last two control points. This is done + * differently for the last spline of an open curve + * than for other cases. + */ + + if ((i == (numPoints-1)) && !closed) { + control[4] = .667*pointPtr[2] + .333*pointPtr[4]; + control[5] = .667*pointPtr[3] + .333*pointPtr[5]; + control[6] = pointPtr[4]; + control[7] = pointPtr[5]; + } else { + control[4] = .833*pointPtr[2] + .167*pointPtr[4]; + control[5] = .833*pointPtr[3] + .167*pointPtr[5]; + control[6] = 0.5*pointPtr[2] + 0.5*pointPtr[4]; + control[7] = 0.5*pointPtr[3] + 0.5*pointPtr[5]; + } + + /* + * If the first two points coincide, or if the last + * two points coincide, then generate a single + * straight-line segment by outputting the last control + * point. + */ + + if (((pointPtr[0] == pointPtr[2]) && (pointPtr[1] == pointPtr[3])) + || ((pointPtr[2] == pointPtr[4]) + && (pointPtr[3] == pointPtr[5]))) { + if (xPoints != NULL) { + Tk_CanvasDrawableCoords(canvas, control[6], control[7], + &xPoints[0].x, &xPoints[0].y); + xPoints++; + } + if (dblPoints != NULL) { + dblPoints[0] = control[6]; + dblPoints[1] = control[7]; + dblPoints += 2; + } + outputPoints += 1; + continue; + } + + /* + * Generate a Bezier spline using the control points. + */ + + + if (xPoints != NULL) { + TkBezierScreenPoints(canvas, control, numSteps, xPoints); + xPoints += numSteps; + } + if (dblPoints != NULL) { + TkBezierPoints(control, numSteps, dblPoints); + dblPoints += 2*numSteps; + } + outputPoints += numSteps; + } + return outputPoints; +} + +/* + *-------------------------------------------------------------- + * + * TkMakeBezierPostscript -- + * + * This procedure generates Postscript commands that create + * a path corresponding to a given Bezier curve. + * + * Results: + * None. Postscript commands to generate the path are appended + * to interp->result. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +TkMakeBezierPostscript(interp, canvas, pointPtr, numPoints) + Tcl_Interp *interp; /* Interpreter in whose result the + * Postscript is to be stored. */ + Tk_Canvas canvas; /* Canvas widget for which the + * Postscript is being generated. */ + double *pointPtr; /* Array of input coordinates: x0, + * y0, x1, y1, etc.. */ + int numPoints; /* Number of points at pointPtr. */ +{ + int closed, i; + int numCoords = numPoints*2; + double control[8]; + char buffer[200]; + + /* + * If the curve is a closed one then generate a special spline + * that spans the last points and the first ones. Otherwise + * just put the first point into the path. + */ + + if ((pointPtr[0] == pointPtr[numCoords-2]) + && (pointPtr[1] == pointPtr[numCoords-1])) { + closed = 1; + control[0] = 0.5*pointPtr[numCoords-4] + 0.5*pointPtr[0]; + control[1] = 0.5*pointPtr[numCoords-3] + 0.5*pointPtr[1]; + control[2] = 0.167*pointPtr[numCoords-4] + 0.833*pointPtr[0]; + control[3] = 0.167*pointPtr[numCoords-3] + 0.833*pointPtr[1]; + control[4] = 0.833*pointPtr[0] + 0.167*pointPtr[2]; + control[5] = 0.833*pointPtr[1] + 0.167*pointPtr[3]; + control[6] = 0.5*pointPtr[0] + 0.5*pointPtr[2]; + control[7] = 0.5*pointPtr[1] + 0.5*pointPtr[3]; + sprintf(buffer, "%.15g %.15g moveto\n%.15g %.15g %.15g %.15g %.15g %.15g curveto\n", + control[0], Tk_CanvasPsY(canvas, control[1]), + control[2], Tk_CanvasPsY(canvas, control[3]), + control[4], Tk_CanvasPsY(canvas, control[5]), + control[6], Tk_CanvasPsY(canvas, control[7])); + } else { + closed = 0; + control[6] = pointPtr[0]; + control[7] = pointPtr[1]; + sprintf(buffer, "%.15g %.15g moveto\n", + control[6], Tk_CanvasPsY(canvas, control[7])); + } + Tcl_AppendResult(interp, buffer, (char *) NULL); + + /* + * Cycle through all the remaining points in the curve, generating + * a curve section for each vertex in the linear path. + */ + + for (i = numPoints-2, pointPtr += 2; i > 0; i--, pointPtr += 2) { + control[2] = 0.333*control[6] + 0.667*pointPtr[0]; + control[3] = 0.333*control[7] + 0.667*pointPtr[1]; + + /* + * Set up the last two control points. This is done + * differently for the last spline of an open curve + * than for other cases. + */ + + if ((i == 1) && !closed) { + control[6] = pointPtr[2]; + control[7] = pointPtr[3]; + } else { + control[6] = 0.5*pointPtr[0] + 0.5*pointPtr[2]; + control[7] = 0.5*pointPtr[1] + 0.5*pointPtr[3]; + } + control[4] = 0.333*control[6] + 0.667*pointPtr[0]; + control[5] = 0.333*control[7] + 0.667*pointPtr[1]; + + sprintf(buffer, "%.15g %.15g %.15g %.15g %.15g %.15g curveto\n", + control[2], Tk_CanvasPsY(canvas, control[3]), + control[4], Tk_CanvasPsY(canvas, control[5]), + control[6], Tk_CanvasPsY(canvas, control[7])); + Tcl_AppendResult(interp, buffer, (char *) NULL); + } +} + +/* + *-------------------------------------------------------------- + * + * TkGetMiterPoints -- + * + * Given three points forming an angle, compute the + * coordinates of the inside and outside points of + * the mitered corner formed by a line of a given + * width at that angle. + * + * Results: + * If the angle formed by the three points is less than + * 11 degrees then 0 is returned and m1 and m2 aren't + * modified. Otherwise 1 is returned and the points at + * m1 and m2 are filled in with the positions of the points + * of the mitered corner. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkGetMiterPoints(p1, p2, p3, width, m1, m2) + double p1[]; /* Points to x- and y-coordinates of point + * before vertex. */ + double p2[]; /* Points to x- and y-coordinates of vertex + * for mitered joint. */ + double p3[]; /* Points to x- and y-coordinates of point + * after vertex. */ + double width; /* Width of line. */ + double m1[]; /* Points to place to put "left" vertex + * point (see as you face from p1 to p2). */ + double m2[]; /* Points to place to put "right" vertex + * point. */ +{ + double theta1; /* Angle of segment p2-p1. */ + double theta2; /* Angle of segment p2-p3. */ + double theta; /* Angle between line segments (angle + * of joint). */ + double theta3; /* Angle that bisects theta1 and + * theta2 and points to m1. */ + double dist; /* Distance of miter points from p2. */ + double deltaX, deltaY; /* X and y offsets cooresponding to + * dist (fudge factors for bounding + * box). */ + double p1x, p1y, p2x, p2y, p3x, p3y; + static double elevenDegrees = (11.0*2.0*PI)/360.0; + + /* + * Round the coordinates to integers to mimic what happens when the + * line segments are displayed; without this code, the bounding box + * of a mitered line can be miscomputed greatly. + */ + + p1x = floor(p1[0]+0.5); + p1y = floor(p1[1]+0.5); + p2x = floor(p2[0]+0.5); + p2y = floor(p2[1]+0.5); + p3x = floor(p3[0]+0.5); + p3y = floor(p3[1]+0.5); + + if (p2y == p1y) { + theta1 = (p2x < p1x) ? 0 : PI; + } else if (p2x == p1x) { + theta1 = (p2y < p1y) ? PI/2.0 : -PI/2.0; + } else { + theta1 = atan2(p1y - p2y, p1x - p2x); + } + if (p3y == p2y) { + theta2 = (p3x > p2x) ? 0 : PI; + } else if (p3x == p2x) { + theta2 = (p3y > p2y) ? PI/2.0 : -PI/2.0; + } else { + theta2 = atan2(p3y - p2y, p3x - p2x); + } + theta = theta1 - theta2; + if (theta > PI) { + theta -= 2*PI; + } else if (theta < -PI) { + theta += 2*PI; + } + if ((theta < elevenDegrees) && (theta > -elevenDegrees)) { + return 0; + } + dist = 0.5*width/sin(0.5*theta); + if (dist < 0.0) { + dist = -dist; + } + + /* + * Compute theta3 (make sure that it points to the left when + * looking from p1 to p2). + */ + + theta3 = (theta1 + theta2)/2.0; + if (sin(theta3 - (theta1 + PI)) < 0.0) { + theta3 += PI; + } + deltaX = dist*cos(theta3); + m1[0] = p2x + deltaX; + m2[0] = p2x - deltaX; + deltaY = dist*sin(theta3); + m1[1] = p2y + deltaY; + m2[1] = p2y - deltaY; + return 1; +} + +/* + *-------------------------------------------------------------- + * + * TkGetButtPoints -- + * + * Given two points forming a line segment, compute the + * coordinates of two endpoints of a rectangle formed by + * bloating the line segment until it is width units wide. + * + * Results: + * There is no return value. M1 and m2 are filled in to + * correspond to m1 and m2 in the diagram below: + * + * ----------------* m1 + * | + * p1 *---------------* p2 + * | + * ----------------* m2 + * + * M1 and m2 will be W units apart, with p2 centered between + * them and m1-m2 perpendicular to p1-p2. However, if + * "project" is true then m1 and m2 will be as follows: + * + * -------------------* m1 + * p2 | + * p1 *---------------* | + * | + * -------------------* m2 + * + * In this case p2 will be width/2 units from the segment m1-m2. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +TkGetButtPoints(p1, p2, width, project, m1, m2) + double p1[]; /* Points to x- and y-coordinates of point + * before vertex. */ + double p2[]; /* Points to x- and y-coordinates of vertex + * for mitered joint. */ + double width; /* Width of line. */ + int project; /* Non-zero means project p2 by an additional + * width/2 before computing m1 and m2. */ + double m1[]; /* Points to place to put "left" result + * point, as you face from p1 to p2. */ + double m2[]; /* Points to place to put "right" result + * point. */ +{ + double length; /* Length of p1-p2 segment. */ + double deltaX, deltaY; /* Increments in coords. */ + + width *= 0.5; + length = hypot(p2[0] - p1[0], p2[1] - p1[1]); + if (length == 0.0) { + m1[0] = m2[0] = p2[0]; + m1[1] = m2[1] = p2[1]; + } else { + deltaX = -width * (p2[1] - p1[1]) / length; + deltaY = width * (p2[0] - p1[0]) / length; + m1[0] = p2[0] + deltaX; + m2[0] = p2[0] - deltaX; + m1[1] = p2[1] + deltaY; + m2[1] = p2[1] - deltaY; + if (project) { + m1[0] += deltaY; + m2[0] += deltaY; + m1[1] -= deltaX; + m2[1] -= deltaX; + } + } +} diff --git a/generic/tkUtil.c b/generic/tkUtil.c new file mode 100644 index 0000000..ddb3db0 --- /dev/null +++ b/generic/tkUtil.c @@ -0,0 +1,348 @@ +/* + * tkUtil.c -- + * + * This file contains miscellaneous utility procedures that + * are used by the rest of Tk, such as a procedure for drawing + * a focus highlight. + * + * Copyright (c) 1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUtil.c 1.13 97/06/06 11:16:22 + */ + +#include "tkInt.h" +#include "tkPort.h" + +/* + *---------------------------------------------------------------------- + * + * TkDrawInsetFocusHighlight -- + * + * This procedure draws a rectangular ring around the outside of + * a widget to indicate that it has received the input focus. It + * takes an additional padding argument that specifies how much + * padding is present outside th widget. + * + * Results: + * None. + * + * Side effects: + * A rectangle "width" pixels wide is drawn in "drawable", + * corresponding to the outer area of "tkwin". + * + *---------------------------------------------------------------------- + */ + +void +TkDrawInsetFocusHighlight(tkwin, gc, width, drawable, padding) + Tk_Window tkwin; /* Window whose focus highlight ring is + * to be drawn. */ + GC gc; /* Graphics context to use for drawing + * the highlight ring. */ + int width; /* Width of the highlight ring, in pixels. */ + Drawable drawable; /* Where to draw the ring (typically a + * pixmap for double buffering). */ + int padding; /* Width of padding outside of widget. */ +{ + XRectangle rects[4]; + + /* + * On the Macintosh the highlight ring needs to be "padded" + * out by one pixel. Unfortunantly, none of the Tk widgets + * had a notion of padding between the focus ring and the + * widget. So we add this padding here. This introduces + * two things to worry about: + * + * 1) The widget must draw the background color covering + * the focus ring area before calling Tk_DrawFocus. + * 2) It is impossible to draw a focus ring of width 1. + * (For the Macintosh Look & Feel use width of 3) + */ +#ifdef MAC_TCL + width--; +#endif + + rects[0].x = padding; + rects[0].y = padding; + rects[0].width = Tk_Width(tkwin) - (2 * padding); + rects[0].height = width; + rects[1].x = padding; + rects[1].y = Tk_Height(tkwin) - width - padding; + rects[1].width = Tk_Width(tkwin) - (2 * padding); + rects[1].height = width; + rects[2].x = padding; + rects[2].y = width + padding; + rects[2].width = width; + rects[2].height = Tk_Height(tkwin) - 2*width - 2*padding; + rects[3].x = Tk_Width(tkwin) - width - padding; + rects[3].y = rects[2].y; + rects[3].width = width; + rects[3].height = rects[2].height; + XFillRectangles(Tk_Display(tkwin), drawable, gc, rects, 4); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_DrawFocusHighlight -- + * + * This procedure draws a rectangular ring around the outside of + * a widget to indicate that it has received the input focus. + * + * Results: + * None. + * + * Side effects: + * A rectangle "width" pixels wide is drawn in "drawable", + * corresponding to the outer area of "tkwin". + * + *---------------------------------------------------------------------- + */ + +void +Tk_DrawFocusHighlight(tkwin, gc, width, drawable) + Tk_Window tkwin; /* Window whose focus highlight ring is + * to be drawn. */ + GC gc; /* Graphics context to use for drawing + * the highlight ring. */ + int width; /* Width of the highlight ring, in pixels. */ + Drawable drawable; /* Where to draw the ring (typically a + * pixmap for double buffering). */ +{ + TkDrawInsetFocusHighlight(tkwin, gc, width, drawable, 0); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetScrollInfo -- + * + * This procedure is invoked to parse "xview" and "yview" + * scrolling commands for widgets using the new scrolling + * command syntax ("moveto" or "scroll" options). + * + * Results: + * The return value is either TK_SCROLL_MOVETO, TK_SCROLL_PAGES, + * TK_SCROLL_UNITS, or TK_SCROLL_ERROR. This indicates whether + * the command was successfully parsed and what form the command + * took. If TK_SCROLL_MOVETO, *dblPtr is filled in with the + * desired position; if TK_SCROLL_PAGES or TK_SCROLL_UNITS, + * *intPtr is filled in with the number of lines to move (may be + * negative); if TK_SCROLL_ERROR, interp->result contains an + * error message. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +Tk_GetScrollInfo(interp, argc, argv, dblPtr, intPtr) + Tcl_Interp *interp; /* Used for error reporting. */ + int argc; /* # arguments for command. */ + char **argv; /* Arguments for command. */ + double *dblPtr; /* Filled in with argument "moveto" + * option, if any. */ + int *intPtr; /* Filled in with number of pages + * or lines to scroll, if any. */ +{ + int c; + size_t length; + + length = strlen(argv[2]); + c = argv[2][0]; + if ((c == 'm') && (strncmp(argv[2], "moveto", length) == 0)) { + if (argc != 4) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " ", argv[1], " moveto fraction\"", + (char *) NULL); + return TK_SCROLL_ERROR; + } + if (Tcl_GetDouble(interp, argv[3], dblPtr) != TCL_OK) { + return TK_SCROLL_ERROR; + } + return TK_SCROLL_MOVETO; + } else if ((c == 's') + && (strncmp(argv[2], "scroll", length) == 0)) { + if (argc != 5) { + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " ", argv[1], " scroll number units|pages\"", + (char *) NULL); + return TK_SCROLL_ERROR; + } + if (Tcl_GetInt(interp, argv[3], intPtr) != TCL_OK) { + return TK_SCROLL_ERROR; + } + length = strlen(argv[4]); + c = argv[4][0]; + if ((c == 'p') && (strncmp(argv[4], "pages", length) == 0)) { + return TK_SCROLL_PAGES; + } else if ((c == 'u') + && (strncmp(argv[4], "units", length) == 0)) { + return TK_SCROLL_UNITS; + } else { + Tcl_AppendResult(interp, "bad argument \"", argv[4], + "\": must be units or pages", (char *) NULL); + return TK_SCROLL_ERROR; + } + } + Tcl_AppendResult(interp, "unknown option \"", argv[2], + "\": must be moveto or scroll", (char *) NULL); + return TK_SCROLL_ERROR; +} + +/* + *--------------------------------------------------------------------------- + * + * TkComputeAnchor -- + * + * Determine where to place a rectangle so that it will be properly + * anchored with respect to the given window. Used by widgets + * to align a box of text inside a window. When anchoring with + * respect to one of the sides, the rectangle be placed inside of + * the internal border of the window. + * + * Results: + * *xPtr and *yPtr set to the upper-left corner of the rectangle + * anchored in the window. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ +void +TkComputeAnchor(anchor, tkwin, padX, padY, innerWidth, innerHeight, xPtr, yPtr) + Tk_Anchor anchor; /* Desired anchor. */ + Tk_Window tkwin; /* Anchored with respect to this window. */ + int padX, padY; /* Use this extra padding inside window, in + * addition to the internal border. */ + int innerWidth, innerHeight;/* Size of rectangle to anchor in window. */ + int *xPtr, *yPtr; /* Returns upper-left corner of anchored + * rectangle. */ +{ + switch (anchor) { + case TK_ANCHOR_NW: + case TK_ANCHOR_W: + case TK_ANCHOR_SW: + *xPtr = Tk_InternalBorderWidth(tkwin) + padX; + break; + + case TK_ANCHOR_N: + case TK_ANCHOR_CENTER: + case TK_ANCHOR_S: + *xPtr = (Tk_Width(tkwin) - innerWidth) / 2; + break; + + default: + *xPtr = Tk_Width(tkwin) - (Tk_InternalBorderWidth(tkwin) + padX) + - innerWidth; + break; + } + + switch (anchor) { + case TK_ANCHOR_NW: + case TK_ANCHOR_N: + case TK_ANCHOR_NE: + *yPtr = Tk_InternalBorderWidth(tkwin) + padY; + break; + + case TK_ANCHOR_W: + case TK_ANCHOR_CENTER: + case TK_ANCHOR_E: + *yPtr = (Tk_Height(tkwin) - innerHeight) / 2; + break; + + default: + *yPtr = Tk_Height(tkwin) - Tk_InternalBorderWidth(tkwin) - padY + - innerHeight; + break; + } +} + +/* + *--------------------------------------------------------------------------- + * + * TkFindStateString -- + * + * Given a lookup table, map a number to a string in the table. + * + * Results: + * If numKey was equal to the numeric key of one of the elements + * in the table, returns the string key of that element. + * Returns NULL if numKey was not equal to any of the numeric keys + * in the table. + * + * Side effects. + * None. + * + *--------------------------------------------------------------------------- + */ + +char * +TkFindStateString(mapPtr, numKey) + CONST TkStateMap *mapPtr; /* The state table. */ + int numKey; /* The key to try to find in the table. */ +{ + for ( ; mapPtr->strKey != NULL; mapPtr++) { + if (numKey == mapPtr->numKey) { + return mapPtr->strKey; + } + } + return NULL; +} + +/* + *--------------------------------------------------------------------------- + * + * TkFindStateNum -- + * + * Given a lookup table, map a string to a number in the table. + * + * Results: + * If strKey was equal to the string keys of one of the elements + * in the table, returns the numeric key of that element. + * Returns the numKey associated with the last element (the NULL + * string one) in the table if strKey was not equal to any of the + * string keys in the table. In that case, an error message is + * also left in interp->result (if interp is not NULL). + * + * Side effects. + * None. + * + *--------------------------------------------------------------------------- + */ + +int +TkFindStateNum(interp, field, mapPtr, strKey) + Tcl_Interp *interp; /* Interp for error reporting. */ + CONST char *field; /* String to use when constructing error. */ + CONST TkStateMap *mapPtr; /* Lookup table. */ + CONST char *strKey; /* String to try to find in lookup table. */ +{ + CONST TkStateMap *mPtr; + + if (mapPtr->strKey == NULL) { + panic("TkFindStateNum: no choices in lookup table"); + } + + for (mPtr = mapPtr; mPtr->strKey != NULL; mPtr++) { + if (strcmp(strKey, mPtr->strKey) == 0) { + return mPtr->numKey; + } + } + if (interp != NULL) { + mPtr = mapPtr; + Tcl_AppendResult(interp, "bad ", field, " value \"", strKey, + "\": must be ", mPtr->strKey, (char *) NULL); + for (mPtr++; mPtr->strKey != NULL; mPtr++) { + Tcl_AppendResult(interp, ", ", mPtr->strKey, (char *) NULL); + } + } + return mPtr->numKey; +} diff --git a/generic/tkVisual.c b/generic/tkVisual.c new file mode 100644 index 0000000..207b905 --- /dev/null +++ b/generic/tkVisual.c @@ -0,0 +1,540 @@ +/* + * tkVisual.c -- + * + * This file contains library procedures for allocating and + * freeing visuals and colormaps. This code is based on a + * prototype implementation by Paul Mackerras. + * + * Copyright (c) 1994 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkVisual.c 1.19 97/04/25 16:52:17 + */ + +#include "tkInt.h" +#include "tkPort.h" + +/* + * The table below maps from symbolic names for visual classes + * to the associated X class symbols. + */ + +typedef struct VisualDictionary { + char *name; /* Textual name of class. */ + int minLength; /* Minimum # characters that must be + * specified for an unambiguous match. */ + int class; /* X symbol for class. */ +} VisualDictionary; +static VisualDictionary visualNames[] = { + {"best", 1, 0}, + {"directcolor", 2, DirectColor}, + {"grayscale", 1, GrayScale}, + {"greyscale", 1, GrayScale}, + {"pseudocolor", 1, PseudoColor}, + {"staticcolor", 7, StaticColor}, + {"staticgray", 7, StaticGray}, + {"staticgrey", 7, StaticGray}, + {"truecolor", 1, TrueColor}, + {NULL, 0, 0}, +}; + +/* + * One of the following structures exists for each distinct non-default + * colormap allocated for a display by Tk_GetColormap. + */ + +struct TkColormap { + Colormap colormap; /* X's identifier for the colormap. */ + Visual *visual; /* Visual for which colormap was + * allocated. */ + int refCount; /* How many uses of the colormap are still + * outstanding (calls to Tk_GetColormap + * minus calls to Tk_FreeColormap). */ + int shareable; /* 0 means this colormap was allocated by + * a call to Tk_GetColormap with "new", + * implying that the window wants it all + * for itself. 1 means that the colormap + * was allocated as a default for a particular + * visual, so it can be shared. */ + struct TkColormap *nextPtr; /* Next in list of colormaps for this display, + * or NULL for end of list. */ +}; + +/* + *---------------------------------------------------------------------- + * + * Tk_GetVisual -- + * + * Given a string identifying a particular kind of visual, this + * procedure returns a visual and depth that matches the specification. + * + * Results: + * The return value is normally a pointer to a visual. If an + * error occurred in looking up the visual, NULL is returned and + * an error message is left in interp->result. The depth of the + * visual is returned to *depthPtr under normal returns. If + * colormapPtr is non-NULL, then this procedure also finds a + * suitable colormap for use with the visual in tkwin, and it + * returns that colormap in *colormapPtr unless an error occurs. + * + * Side effects: + * A new colormap may be allocated. + * + *---------------------------------------------------------------------- + */ + +Visual * +Tk_GetVisual(interp, tkwin, string, depthPtr, colormapPtr) + Tcl_Interp *interp; /* Interpreter to use for error + * reporting. */ + Tk_Window tkwin; /* Window in which visual will be + * used. */ + char *string; /* String describing visual. See + * manual entry for details. */ + int *depthPtr; /* The depth of the returned visual + * is stored here. */ + Colormap *colormapPtr; /* If non-NULL, then a suitable + * colormap for visual is placed here. + * This colormap must eventually be + * freed by calling Tk_FreeColormap. */ +{ + Tk_Window tkwin2; + XVisualInfo template, *visInfoList, *bestPtr; + long mask; + Visual *visual; + int length, c, numVisuals, prio, bestPrio, i; + char *p; + VisualDictionary *dictPtr; + TkColormap *cmapPtr; + TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr; + + /* + * Parse string and set up a template for use in searching for + * an appropriate visual. + */ + + c = string[0]; + if (c == '.') { + /* + * The string must be a window name. If the window is on the + * same screen as tkwin, then just use its visual. Otherwise + * use the information about the visual as a template for the + * search. + */ + + tkwin2 = Tk_NameToWindow(interp, string, tkwin); + if (tkwin2 == NULL) { + return NULL; + } + visual = Tk_Visual(tkwin2); + if (Tk_Screen(tkwin) == Tk_Screen(tkwin2)) { + *depthPtr = Tk_Depth(tkwin2); + if (colormapPtr != NULL) { + /* + * Use the colormap from the other window too (but be sure + * to increment its reference count if it's one of the ones + * allocated here). + */ + + *colormapPtr = Tk_Colormap(tkwin2); + for (cmapPtr = dispPtr->cmapPtr; cmapPtr != NULL; + cmapPtr = cmapPtr->nextPtr) { + if (cmapPtr->colormap == *colormapPtr) { + cmapPtr->refCount += 1; + break; + } + } + } + return visual; + } + template.depth = Tk_Depth(tkwin2); + template.class = visual->class; + template.red_mask = visual->red_mask; + template.green_mask = visual->green_mask; + template.blue_mask = visual->blue_mask; + template.colormap_size = visual->map_entries; + template.bits_per_rgb = visual->bits_per_rgb; + mask = VisualDepthMask|VisualClassMask|VisualRedMaskMask + |VisualGreenMaskMask|VisualBlueMaskMask|VisualColormapSizeMask + |VisualBitsPerRGBMask; + } else if ((c == 0) || ((c == 'd') && (string[1] != 0) + && (strncmp(string, "default", strlen(string)) == 0))) { + /* + * Use the default visual for the window's screen. + */ + + if (colormapPtr != NULL) { + *colormapPtr = DefaultColormapOfScreen(Tk_Screen(tkwin)); + } + *depthPtr = DefaultDepthOfScreen(Tk_Screen(tkwin)); + return DefaultVisualOfScreen(Tk_Screen(tkwin)); + } else if (isdigit(UCHAR(c))) { + int visualId; + + /* + * This is a visual ID. + */ + + if (Tcl_GetInt(interp, string, &visualId) == TCL_ERROR) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "bad X identifier for visual: ", + string, "\"", (char *) NULL); + return NULL; + } + template.visualid = visualId; + mask = VisualIDMask; + } else { + /* + * Parse the string into a class name (or "best") optionally + * followed by whitespace and a depth. + */ + + for (p = string; *p != 0; p++) { + if (isspace(UCHAR(*p)) || isdigit(UCHAR(*p))) { + break; + } + } + length = p - string; + template.class = -1; + for (dictPtr = visualNames; dictPtr->name != NULL; dictPtr++) { + if ((dictPtr->name[0] == c) && (length >= dictPtr->minLength) + && (strncmp(string, dictPtr->name, + (size_t) length) == 0)) { + template.class = dictPtr->class; + break; + } + } + if (template.class == -1) { + Tcl_AppendResult(interp, "unknown or ambiguous visual name \"", + string, "\": class must be ", (char *) NULL); + for (dictPtr = visualNames; dictPtr->name != NULL; dictPtr++) { + Tcl_AppendResult(interp, dictPtr->name, ", ", (char *) NULL); + } + Tcl_AppendResult(interp, "or default", (char *) NULL); + return NULL; + } + while (isspace(UCHAR(*p))) { + p++; + } + if (*p == 0) { + template.depth = 10000; + } else { + if (Tcl_GetInt(interp, p, &template.depth) != TCL_OK) { + return NULL; + } + } + if (c == 'b') { + mask = 0; + } else { + mask = VisualClassMask; + } + } + + /* + * Find all visuals that match the template we've just created, + * and return an error if there are none that match. + */ + + template.screen = Tk_ScreenNumber(tkwin); + mask |= VisualScreenMask; + visInfoList = XGetVisualInfo(Tk_Display(tkwin), mask, &template, + &numVisuals); + if (visInfoList == NULL) { + interp->result = "couldn't find an appropriate visual"; + return NULL; + } + + /* + * Search through the visuals that were returned to find the best + * one. The choice is based on the following criteria, in decreasing + * order of importance: + * + * 1. Depth: choose a visual with exactly the desired depth, + * else one with more bits than requested but as few bits + * as possible, else one with fewer bits but as many as + * possible. + * 2. Class: some visual classes are more desirable than others; + * pick the visual with the most desirable class. + * 3. Default: the default visual for the screen gets preference + * over other visuals, all else being equal. + */ + + bestPrio = 0; + bestPtr = NULL; + for (i = 0; i < numVisuals; i++) { + switch (visInfoList[i].class) { + case DirectColor: prio = 5; break; + case GrayScale: prio = 1; break; + case PseudoColor: prio = 7; break; + case StaticColor: prio = 3; break; + case StaticGray: prio = 1; break; + case TrueColor: prio = 5; break; + default: prio = 0; break; + } + if (visInfoList[i].visual + == DefaultVisualOfScreen(Tk_Screen(tkwin))) { + prio++; + } + if (bestPtr == NULL) { + goto newBest; + } + if (visInfoList[i].depth < bestPtr->depth) { + if (visInfoList[i].depth >= template.depth) { + goto newBest; + } + } else if (visInfoList[i].depth > bestPtr->depth) { + if (bestPtr->depth < template.depth) { + goto newBest; + } + } else { + if (prio > bestPrio) { + goto newBest; + } + } + continue; + + newBest: + bestPtr = &visInfoList[i]; + bestPrio = prio; + } + *depthPtr = bestPtr->depth; + visual = bestPtr->visual; + XFree((char *) visInfoList); + + /* + * If we need to find a colormap for this visual, do it now. + * If the visual is the default visual for the screen, then + * use the default colormap. Otherwise search for an existing + * colormap that's shareable. If all else fails, create a new + * colormap. + */ + + if (colormapPtr != NULL) { + if (visual == DefaultVisualOfScreen(Tk_Screen(tkwin))) { + *colormapPtr = DefaultColormapOfScreen(Tk_Screen(tkwin)); + } else { + for (cmapPtr = dispPtr->cmapPtr; cmapPtr != NULL; + cmapPtr = cmapPtr->nextPtr) { + if (cmapPtr->shareable && (cmapPtr->visual == visual)) { + *colormapPtr = cmapPtr->colormap; + cmapPtr->refCount += 1; + goto done; + } + } + cmapPtr = (TkColormap *) ckalloc(sizeof(TkColormap)); + cmapPtr->colormap = XCreateColormap(Tk_Display(tkwin), + RootWindowOfScreen(Tk_Screen(tkwin)), visual, + AllocNone); + cmapPtr->visual = visual; + cmapPtr->refCount = 1; + cmapPtr->shareable = 1; + cmapPtr->nextPtr = dispPtr->cmapPtr; + dispPtr->cmapPtr = cmapPtr; + *colormapPtr = cmapPtr->colormap; + } + } + + done: + return visual; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetColormap -- + * + * Given a string identifying a colormap, this procedure finds + * an appropriate colormap. + * + * Results: + * The return value is normally the X resource identifier for the + * colormap. If an error occurs, None is returned and an error + * message is placed in interp->result. + * + * Side effects: + * A reference count is incremented for the colormap, so + * Tk_FreeColormap must eventually be called exactly once for + * each call to Tk_GetColormap. + * + *---------------------------------------------------------------------- + */ + +Colormap +Tk_GetColormap(interp, tkwin, string) + Tcl_Interp *interp; /* Interpreter to use for error + * reporting. */ + Tk_Window tkwin; /* Window where colormap will be + * used. */ + char *string; /* String that identifies colormap: + * either "new" or the name of + * another window. */ +{ + Colormap colormap; + TkColormap *cmapPtr; + TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr; + Tk_Window other; + + /* + * Allocate a new colormap, if that's what is wanted. + */ + + if (strcmp(string, "new") == 0) { + cmapPtr = (TkColormap *) ckalloc(sizeof(TkColormap)); + cmapPtr->colormap = XCreateColormap(Tk_Display(tkwin), + RootWindowOfScreen(Tk_Screen(tkwin)), Tk_Visual(tkwin), + AllocNone); + cmapPtr->visual = Tk_Visual(tkwin); + cmapPtr->refCount = 1; + cmapPtr->shareable = 0; + cmapPtr->nextPtr = dispPtr->cmapPtr; + dispPtr->cmapPtr = cmapPtr; + return cmapPtr->colormap; + } + + /* + * Use a colormap from an existing window. It must have the same + * visual as tkwin (which means, among other things, that the + * other window must be on the same screen). + */ + + other = Tk_NameToWindow(interp, string, tkwin); + if (other == NULL) { + return None; + } + if (Tk_Screen(other) != Tk_Screen(tkwin)) { + Tcl_AppendResult(interp, "can't use colormap for ", string, + ": not on same screen", (char *) NULL); + return None; + } + if (Tk_Visual(other) != Tk_Visual(tkwin)) { + Tcl_AppendResult(interp, "can't use colormap for ", string, + ": incompatible visuals", (char *) NULL); + return None; + } + colormap = Tk_Colormap(other); + + /* + * If the colormap was a special one allocated by code in this file, + * increment its reference count. + */ + + for (cmapPtr = dispPtr->cmapPtr; cmapPtr != NULL; + cmapPtr = cmapPtr->nextPtr) { + if (cmapPtr->colormap == colormap) { + cmapPtr->refCount += 1; + } + } + return colormap; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreeColormap -- + * + * This procedure is called to release a colormap that was + * previously allocated by Tk_GetColormap. + * + * Results: + * None. + * + * Side effects: + * The colormap's reference count is decremented. If this was the + * last reference to the colormap, then the colormap is freed. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreeColormap(display, colormap) + Display *display; /* Display for which colormap was + * allocated. */ + Colormap colormap; /* Colormap that is no longer needed. + * Must have been returned by previous + * call to Tk_GetColormap, or + * preserved by a previous call to + * Tk_PreserveColormap. */ +{ + TkDisplay *dispPtr; + TkColormap *cmapPtr, *prevPtr; + + /* + * Find Tk's information about the display, then see if this + * colormap is a non-default one (if it's a default one, there + * won't be an entry for it in the display's list). + */ + + dispPtr = TkGetDisplay(display); + if (dispPtr == NULL) { + panic("unknown display passed to Tk_FreeColormap"); + } + for (prevPtr = NULL, cmapPtr = dispPtr->cmapPtr; cmapPtr != NULL; + prevPtr = cmapPtr, cmapPtr = cmapPtr->nextPtr) { + if (cmapPtr->colormap == colormap) { + cmapPtr->refCount -= 1; + if (cmapPtr->refCount == 0) { + XFreeColormap(display, colormap); + if (prevPtr == NULL) { + dispPtr->cmapPtr = cmapPtr->nextPtr; + } else { + prevPtr->nextPtr = cmapPtr->nextPtr; + } + ckfree((char *) cmapPtr); + } + return; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_PreserveColormap -- + * + * This procedure is called to indicate to Tk that the specified + * colormap is being referenced from another location and should + * not be freed until all extra references are eliminated. The + * colormap must have been returned by Tk_GetColormap. + * + * Results: + * None. + * + * Side effects: + * The colormap's reference count is incremented, so + * Tk_FreeColormap must eventually be called exactly once for + * each call to Tk_PreserveColormap. + * + *---------------------------------------------------------------------- + */ + +void +Tk_PreserveColormap(display, colormap) + Display *display; /* Display for which colormap was + * allocated. */ + Colormap colormap; /* Colormap that should be + * preserved. */ +{ + TkDisplay *dispPtr; + TkColormap *cmapPtr; + + /* + * Find Tk's information about the display, then see if this + * colormap is a non-default one (if it's a default one, there + * won't be an entry for it in the display's list). + */ + + dispPtr = TkGetDisplay(display); + if (dispPtr == NULL) { + panic("unknown display passed to Tk_PreserveColormap"); + } + for (cmapPtr = dispPtr->cmapPtr; cmapPtr != NULL; + cmapPtr = cmapPtr->nextPtr) { + if (cmapPtr->colormap == colormap) { + cmapPtr->refCount += 1; + return; + } + } +} diff --git a/generic/tkWindow.c b/generic/tkWindow.c new file mode 100644 index 0000000..fc9060a --- /dev/null +++ b/generic/tkWindow.c @@ -0,0 +1,2763 @@ +/* + * tkWindow.c -- + * + * This file provides basic window-manipulation procedures, + * which are equivalent to procedures in Xlib (and even + * invoke them) but also maintain the local Tk_Window + * structure. + * + * Copyright (c) 1989-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWindow.c 1.233 97/10/31 09:55:23 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * Count of number of main windows currently open in this process. + */ + +static int numMainWindows; + +/* + * First in list of all main windows managed by this process. + */ + +TkMainInfo *tkMainWindowList = NULL; + +/* + * List of all displays currently in use. + */ + +TkDisplay *tkDisplayList = NULL; + +/* + * Have statics in this module been initialized? + */ + +static int initialized = 0; + +/* + * The variables below hold several uid's that are used in many places + * in the toolkit. + */ + +Tk_Uid tkDisabledUid = NULL; +Tk_Uid tkActiveUid = NULL; +Tk_Uid tkNormalUid = NULL; + +/* + * Default values for "changes" and "atts" fields of TkWindows. Note + * that Tk always requests all events for all windows, except StructureNotify + * events on internal windows: these events are generated internally. + */ + +static XWindowChanges defChanges = { + 0, 0, 1, 1, 0, 0, Above +}; +#define ALL_EVENTS_MASK \ + KeyPressMask|KeyReleaseMask|ButtonPressMask|ButtonReleaseMask| \ + EnterWindowMask|LeaveWindowMask|PointerMotionMask|ExposureMask| \ + VisibilityChangeMask|PropertyChangeMask|ColormapChangeMask +static XSetWindowAttributes defAtts= { + None, /* background_pixmap */ + 0, /* background_pixel */ + CopyFromParent, /* border_pixmap */ + 0, /* border_pixel */ + NorthWestGravity, /* bit_gravity */ + NorthWestGravity, /* win_gravity */ + NotUseful, /* backing_store */ + (unsigned) ~0, /* backing_planes */ + 0, /* backing_pixel */ + False, /* save_under */ + ALL_EVENTS_MASK, /* event_mask */ + 0, /* do_not_propagate_mask */ + False, /* override_redirect */ + CopyFromParent, /* colormap */ + None /* cursor */ +}; + +/* + * The following structure defines all of the commands supported by + * Tk, and the C procedures that execute them. + */ + +typedef struct { + char *name; /* Name of command. */ + Tcl_CmdProc *cmdProc; /* Command's string-based procedure. */ + Tcl_ObjCmdProc *objProc; /* Command's object-based procedure. */ + int isSafe; /* If !0, this command will be exposed in + * a safe interpreter. Otherwise it will be + * hidden in a safe interpreter. */ +} TkCmd; + +static TkCmd commands[] = { + /* + * Commands that are part of the intrinsics: + */ + + {"bell", Tk_BellCmd, NULL, 0}, + {"bind", Tk_BindCmd, NULL, 1}, + {"bindtags", Tk_BindtagsCmd, NULL, 1}, + {"clipboard", Tk_ClipboardCmd, NULL, 0}, + {"destroy", Tk_DestroyCmd, NULL, 1}, + {"event", Tk_EventCmd, NULL, 1}, + {"focus", Tk_FocusCmd, NULL, 1}, + {"font", NULL, Tk_FontObjCmd, 1}, + {"grab", Tk_GrabCmd, NULL, 0}, + {"grid", Tk_GridCmd, NULL, 1}, + {"image", Tk_ImageCmd, NULL, 1}, + {"lower", Tk_LowerCmd, NULL, 1}, + {"option", Tk_OptionCmd, NULL, 1}, + {"pack", Tk_PackCmd, NULL, 1}, + {"place", Tk_PlaceCmd, NULL, 1}, + {"raise", Tk_RaiseCmd, NULL, 1}, + {"selection", Tk_SelectionCmd, NULL, 0}, + {"tk", NULL, Tk_TkObjCmd, 0}, + {"tkwait", Tk_TkwaitCmd, NULL, 1}, + {"tk_chooseColor", Tk_ChooseColorCmd, NULL, 0}, + {"tk_getOpenFile", Tk_GetOpenFileCmd, NULL, 0}, + {"tk_getSaveFile", Tk_GetSaveFileCmd, NULL, 0}, + {"tk_messageBox", Tk_MessageBoxCmd, NULL, 0}, + {"update", Tk_UpdateCmd, NULL, 1}, + {"winfo", NULL, Tk_WinfoObjCmd, 1}, + {"wm", Tk_WmCmd, NULL, 0}, + + /* + * Widget class commands. + */ + {"button", Tk_ButtonCmd, NULL, 1}, + {"canvas", Tk_CanvasCmd, NULL, 1}, + {"checkbutton", Tk_CheckbuttonCmd, NULL, 1}, + {"entry", Tk_EntryCmd, NULL, 1}, + {"frame", Tk_FrameCmd, NULL, 1}, + {"label", Tk_LabelCmd, NULL, 1}, + {"listbox", Tk_ListboxCmd, NULL, 1}, + {"menu", Tk_MenuCmd, NULL, 0}, + {"menubutton", Tk_MenubuttonCmd, NULL, 1}, + {"message", Tk_MessageCmd, NULL, 1}, + {"radiobutton", Tk_RadiobuttonCmd, NULL, 1}, + {"scale", Tk_ScaleCmd, NULL, 1}, + {"scrollbar", Tk_ScrollbarCmd, NULL, 1}, + {"text", Tk_TextCmd, NULL, 1}, + {"toplevel", Tk_ToplevelCmd, NULL, 0}, + + /* + * Misc. + */ + +#ifdef MAC_TCL + {"unsupported1", TkUnsupported1Cmd, NULL, 1}, +#endif + {(char *) NULL, (int (*) _ANSI_ARGS_((ClientData, Tcl_Interp *, int, char **))) NULL, NULL, 0} +}; + +/* + * The variables and table below are used to parse arguments from + * the "argv" variable in Tk_Init. + */ + +static int synchronize = 0; +static char *name = NULL; +static char *display = NULL; +static char *geometry = NULL; +static char *colormap = NULL; +static char *use = NULL; +static char *visual = NULL; +static int rest = 0; + +static Tk_ArgvInfo argTable[] = { + {"-colormap", TK_ARGV_STRING, (char *) NULL, (char *) &colormap, + "Colormap for main window"}, + {"-display", TK_ARGV_STRING, (char *) NULL, (char *) &display, + "Display to use"}, + {"-geometry", TK_ARGV_STRING, (char *) NULL, (char *) &geometry, + "Initial geometry for window"}, + {"-name", TK_ARGV_STRING, (char *) NULL, (char *) &name, + "Name to use for application"}, + {"-sync", TK_ARGV_CONSTANT, (char *) 1, (char *) &synchronize, + "Use synchronous mode for display server"}, + {"-visual", TK_ARGV_STRING, (char *) NULL, (char *) &visual, + "Visual for main window"}, + {"-use", TK_ARGV_STRING, (char *) NULL, (char *) &use, + "Id of window in which to embed application"}, + {"--", TK_ARGV_REST, (char *) 1, (char *) &rest, + "Pass all remaining arguments through to script"}, + {(char *) NULL, TK_ARGV_END, (char *) NULL, (char *) NULL, + (char *) NULL} +}; + +/* + * Forward declarations to procedures defined later in this file: + */ + +static Tk_Window CreateTopLevelWindow _ANSI_ARGS_((Tcl_Interp *interp, + Tk_Window parent, char *name, char *screenName)); +static void DeleteWindowsExitProc _ANSI_ARGS_(( + ClientData clientData)); +static TkDisplay * GetScreen _ANSI_ARGS_((Tcl_Interp *interp, + char *screenName, int *screenPtr)); +static int Initialize _ANSI_ARGS_((Tcl_Interp *interp)); +static int NameWindow _ANSI_ARGS_((Tcl_Interp *interp, + TkWindow *winPtr, TkWindow *parentPtr, + char *name)); +static void OpenIM _ANSI_ARGS_((TkDisplay *dispPtr)); +static void UnlinkWindow _ANSI_ARGS_((TkWindow *winPtr)); + +/* + *---------------------------------------------------------------------- + * + * CreateTopLevelWindow -- + * + * Make a new window that will be at top-level (its parent will + * be the root window of a screen). + * + * Results: + * The return value is a token for the new window, or NULL if + * an error prevented the new window from being created. If + * NULL is returned, an error message will be left in + * interp->result. + * + * Side effects: + * A new window structure is allocated locally. An X + * window is NOT initially created, but will be created + * the first time the window is mapped. + * + *---------------------------------------------------------------------- + */ + +static Tk_Window +CreateTopLevelWindow(interp, parent, name, screenName) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + Tk_Window parent; /* Token for logical parent of new window + * (used for naming, options, etc.). May + * be NULL. */ + char *name; /* Name for new window; if parent is + * non-NULL, must be unique among parent's + * children. */ + char *screenName; /* Name of screen on which to create + * window. NULL means use DISPLAY environment + * variable to determine. Empty string means + * use parent's screen, or DISPLAY if no + * parent. */ +{ + register TkWindow *winPtr; + register TkDisplay *dispPtr; + int screenId; + + if (!initialized) { + initialized = 1; + tkActiveUid = Tk_GetUid("active"); + tkDisabledUid = Tk_GetUid("disabled"); + tkNormalUid = Tk_GetUid("normal"); + + /* + * Create built-in image types. + */ + + Tk_CreateImageType(&tkBitmapImageType); + Tk_CreateImageType(&tkPhotoImageType); + + /* + * Create built-in photo image formats. + */ + + Tk_CreatePhotoImageFormat(&tkImgFmtGIF); + Tk_CreatePhotoImageFormat(&tkImgFmtPPM); + + /* + * Create exit handler to delete all windows when the application + * exits. + */ + + Tcl_CreateExitHandler(DeleteWindowsExitProc, (ClientData) NULL); + } + + if ((parent != NULL) && (screenName != NULL) && (screenName[0] == '\0')) { + dispPtr = ((TkWindow *) parent)->dispPtr; + screenId = Tk_ScreenNumber(parent); + } else { + dispPtr = GetScreen(interp, screenName, &screenId); + if (dispPtr == NULL) { + return (Tk_Window) NULL; + } + } + + winPtr = TkAllocWindow(dispPtr, screenId, (TkWindow *) parent); + + /* + * Force the window to use a border pixel instead of border pixmap. + * This is needed for the case where the window doesn't use the + * default visual. In this case, the default border is a pixmap + * inherited from the root window, which won't work because it will + * have the wrong visual. + */ + + winPtr->dirtyAtts |= CWBorderPixel; + + /* + * (Need to set the TK_TOP_LEVEL flag immediately here; otherwise + * Tk_DestroyWindow will core dump if it is called before the flag + * has been set.) + */ + + winPtr->flags |= TK_TOP_LEVEL; + + if (parent != NULL) { + if (NameWindow(interp, winPtr, (TkWindow *) parent, name) != TCL_OK) { + Tk_DestroyWindow((Tk_Window) winPtr); + return (Tk_Window) NULL; + } + } + TkWmNewWindow(winPtr); + + return (Tk_Window) winPtr; +} + +/* + *---------------------------------------------------------------------- + * + * GetScreen -- + * + * Given a string name for a display-plus-screen, find the + * TkDisplay structure for the display and return the screen + * number too. + * + * Results: + * The return value is a pointer to information about the display, + * or NULL if the display couldn't be opened. In this case, an + * error message is left in interp->result. The location at + * *screenPtr is overwritten with the screen number parsed from + * screenName. + * + * Side effects: + * A new connection is opened to the display if there is no + * connection already. A new TkDisplay data structure is also + * setup, if necessary. + * + *---------------------------------------------------------------------- + */ + +static TkDisplay * +GetScreen(interp, screenName, screenPtr) + Tcl_Interp *interp; /* Place to leave error message. */ + char *screenName; /* Name for screen. NULL or empty means + * use DISPLAY envariable. */ + int *screenPtr; /* Where to store screen number. */ +{ + register TkDisplay *dispPtr; + char *p; + int screenId; + size_t length; + + /* + * Separate the screen number from the rest of the display + * name. ScreenName is assumed to have the syntax + * <display>.<screen> with the dot and the screen being + * optional. + */ + + screenName = TkGetDefaultScreenName(interp, screenName); + if (screenName == NULL) { + interp->result = + "no display name and no $DISPLAY environment variable"; + return (TkDisplay *) NULL; + } + length = strlen(screenName); + screenId = 0; + p = screenName+length-1; + while (isdigit(UCHAR(*p)) && (p != screenName)) { + p--; + } + if ((*p == '.') && (p[1] != '\0')) { + length = p - screenName; + screenId = strtoul(p+1, (char **) NULL, 10); + } + + /* + * See if we already have a connection to this display. If not, + * then open a new connection. + */ + + for (dispPtr = tkDisplayList; ; dispPtr = dispPtr->nextPtr) { + if (dispPtr == NULL) { + dispPtr = TkpOpenDisplay(screenName); + if (dispPtr == NULL) { + Tcl_AppendResult(interp, "couldn't connect to display \"", + screenName, "\"", (char *) NULL); + return (TkDisplay *) NULL; + } + dispPtr->nextPtr = tkDisplayList; + dispPtr->name = (char *) ckalloc((unsigned) (length+1)); + dispPtr->lastEventTime = CurrentTime; + strncpy(dispPtr->name, screenName, length); + dispPtr->name[length] = '\0'; + dispPtr->bindInfoStale = 1; + dispPtr->modeModMask = 0; + dispPtr->metaModMask = 0; + dispPtr->altModMask = 0; + dispPtr->numModKeyCodes = 0; + dispPtr->modKeyCodes = NULL; + OpenIM(dispPtr); + dispPtr->errorPtr = NULL; + dispPtr->deleteCount = 0; + dispPtr->commTkwin = NULL; + dispPtr->selectionInfoPtr = NULL; + dispPtr->multipleAtom = None; + dispPtr->clipWindow = NULL; + dispPtr->clipboardActive = 0; + dispPtr->clipboardAppPtr = NULL; + dispPtr->clipTargetPtr = NULL; + dispPtr->atomInit = 0; + dispPtr->cursorFont = None; + dispPtr->grabWinPtr = NULL; + dispPtr->eventualGrabWinPtr = NULL; + dispPtr->buttonWinPtr = NULL; + dispPtr->serverWinPtr = NULL; + dispPtr->firstGrabEventPtr = NULL; + dispPtr->lastGrabEventPtr = NULL; + dispPtr->grabFlags = 0; + TkInitXId(dispPtr); + dispPtr->destroyCount = 0; + dispPtr->lastDestroyRequest = 0; + dispPtr->cmapPtr = NULL; + dispPtr->implicitWinPtr = NULL; + dispPtr->focusPtr = NULL; + dispPtr->stressPtr = NULL; + dispPtr->delayedMotionPtr = NULL; + Tcl_InitHashTable(&dispPtr->winTable, TCL_ONE_WORD_KEYS); + dispPtr->refCount = 0; + + tkDisplayList = dispPtr; + break; + } + if ((strncmp(dispPtr->name, screenName, length) == 0) + && (dispPtr->name[length] == '\0')) { + break; + } + } + if (screenId >= ScreenCount(dispPtr->display)) { + sprintf(interp->result, "bad screen number \"%d\"", screenId); + return (TkDisplay *) NULL; + } + *screenPtr = screenId; + return dispPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkGetDisplay -- + * + * Given an X display, TkGetDisplay returns the TkDisplay + * structure for the display. + * + * Results: + * The return value is a pointer to information about the display, + * or NULL if the display did not have a TkDisplay structure. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkDisplay * +TkGetDisplay(display) + Display *display; /* X's display pointer */ +{ + TkDisplay *dispPtr; + + for (dispPtr = tkDisplayList; dispPtr != NULL; + dispPtr = dispPtr->nextPtr) { + if (dispPtr->display == display) { + break; + } + } + return dispPtr; +} + +/* + *-------------------------------------------------------------- + * + * TkAllocWindow -- + * + * This procedure creates and initializes a TkWindow structure. + * + * Results: + * The return value is a pointer to the new window. + * + * Side effects: + * A new window structure is allocated and all its fields are + * initialized. + * + *-------------------------------------------------------------- + */ + +TkWindow * +TkAllocWindow(dispPtr, screenNum, parentPtr) + TkDisplay *dispPtr; /* Display associated with new window. */ + int screenNum; /* Index of screen for new window. */ + TkWindow *parentPtr; /* Parent from which this window should + * inherit visual information. NULL means + * use screen defaults instead of + * inheriting. */ +{ + register TkWindow *winPtr; + + winPtr = (TkWindow *) ckalloc(sizeof(TkWindow)); + winPtr->display = dispPtr->display; + winPtr->dispPtr = dispPtr; + winPtr->screenNum = screenNum; + if ((parentPtr != NULL) && (parentPtr->display == winPtr->display) + && (parentPtr->screenNum == winPtr->screenNum)) { + winPtr->visual = parentPtr->visual; + winPtr->depth = parentPtr->depth; + } else { + winPtr->visual = DefaultVisual(dispPtr->display, screenNum); + winPtr->depth = DefaultDepth(dispPtr->display, screenNum); + } + winPtr->window = None; + winPtr->childList = NULL; + winPtr->lastChildPtr = NULL; + winPtr->parentPtr = NULL; + winPtr->nextPtr = NULL; + winPtr->mainPtr = NULL; + winPtr->pathName = NULL; + winPtr->nameUid = NULL; + winPtr->classUid = NULL; + winPtr->changes = defChanges; + winPtr->dirtyChanges = CWX|CWY|CWWidth|CWHeight|CWBorderWidth; + winPtr->atts = defAtts; + if ((parentPtr != NULL) && (parentPtr->display == winPtr->display) + && (parentPtr->screenNum == winPtr->screenNum)) { + winPtr->atts.colormap = parentPtr->atts.colormap; + } else { + winPtr->atts.colormap = DefaultColormap(dispPtr->display, screenNum); + } + winPtr->dirtyAtts = CWEventMask|CWColormap|CWBitGravity; + winPtr->flags = 0; + winPtr->handlerList = NULL; +#ifdef TK_USE_INPUT_METHODS + winPtr->inputContext = NULL; +#endif /* TK_USE_INPUT_METHODS */ + winPtr->tagPtr = NULL; + winPtr->numTags = 0; + winPtr->optionLevel = -1; + winPtr->selHandlerList = NULL; + winPtr->geomMgrPtr = NULL; + winPtr->geomData = NULL; + winPtr->reqWidth = winPtr->reqHeight = 1; + winPtr->internalBorderWidth = 0; + winPtr->wmInfoPtr = NULL; + winPtr->classProcsPtr = NULL; + winPtr->instanceData = NULL; + winPtr->privatePtr = NULL; + + return winPtr; +} + +/* + *---------------------------------------------------------------------- + * + * NameWindow -- + * + * This procedure is invoked to give a window a name and insert + * the window into the hierarchy associated with a particular + * application. + * + * Results: + * A standard Tcl return value. + * + * Side effects: + * See above. + * + *---------------------------------------------------------------------- + */ + +static int +NameWindow(interp, winPtr, parentPtr, name) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + register TkWindow *winPtr; /* Window that is to be named and inserted. */ + TkWindow *parentPtr; /* Pointer to logical parent for winPtr + * (used for naming, options, etc.). */ + char *name; /* Name for winPtr; must be unique among + * parentPtr's children. */ +{ +#define FIXED_SIZE 200 + char staticSpace[FIXED_SIZE]; + char *pathName; + int new; + Tcl_HashEntry *hPtr; + int length1, length2; + + /* + * Setup all the stuff except name right away, then do the name stuff + * last. This is so that if the name stuff fails, everything else + * will be properly initialized (needed to destroy the window cleanly + * after the naming failure). + */ + winPtr->parentPtr = parentPtr; + winPtr->nextPtr = NULL; + if (parentPtr->childList == NULL) { + parentPtr->childList = winPtr; + } else { + parentPtr->lastChildPtr->nextPtr = winPtr; + } + parentPtr->lastChildPtr = winPtr; + winPtr->mainPtr = parentPtr->mainPtr; + winPtr->mainPtr->refCount++; + winPtr->nameUid = Tk_GetUid(name); + + /* + * Don't permit names that start with an upper-case letter: this + * will just cause confusion with class names in the option database. + */ + + if (isupper(UCHAR(name[0]))) { + Tcl_AppendResult(interp, + "window name starts with an upper-case letter: \"", + name, "\"", (char *) NULL); + return TCL_ERROR; + } + + /* + * To permit names of arbitrary length, must be prepared to malloc + * a buffer to hold the new path name. To run fast in the common + * case where names are short, use a fixed-size buffer on the + * stack. + */ + + length1 = strlen(parentPtr->pathName); + length2 = strlen(name); + if ((length1+length2+2) <= FIXED_SIZE) { + pathName = staticSpace; + } else { + pathName = (char *) ckalloc((unsigned) (length1+length2+2)); + } + if (length1 == 1) { + pathName[0] = '.'; + strcpy(pathName+1, name); + } else { + strcpy(pathName, parentPtr->pathName); + pathName[length1] = '.'; + strcpy(pathName+length1+1, name); + } + hPtr = Tcl_CreateHashEntry(&parentPtr->mainPtr->nameTable, pathName, &new); + if (pathName != staticSpace) { + ckfree(pathName); + } + if (!new) { + Tcl_AppendResult(interp, "window name \"", name, + "\" already exists in parent", (char *) NULL); + return TCL_ERROR; + } + Tcl_SetHashValue(hPtr, winPtr); + winPtr->pathName = Tcl_GetHashKey(&parentPtr->mainPtr->nameTable, hPtr); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkCreateMainWindow -- + * + * Make a new main window. A main window is a special kind of + * top-level window used as the outermost window in an + * application. + * + * Results: + * The return value is a token for the new window, or NULL if + * an error prevented the new window from being created. If + * NULL is returned, an error message will be left in + * interp->result. + * + * Side effects: + * A new window structure is allocated locally; "interp" is + * associated with the window and registered for "send" commands + * under "baseName". BaseName may be extended with an instance + * number in the form "#2" if necessary to make it globally + * unique. Tk-related commands are bound into interp. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +TkCreateMainWindow(interp, screenName, baseName) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + char *screenName; /* Name of screen on which to create + * window. Empty or NULL string means + * use DISPLAY environment variable. */ + char *baseName; /* Base name for application; usually of the + * form "prog instance". */ +{ + Tk_Window tkwin; + int dummy; + int isSafe; + Tcl_HashEntry *hPtr; + register TkMainInfo *mainPtr; + register TkWindow *winPtr; + register TkCmd *cmdPtr; + + /* + * Panic if someone updated the TkWindow structure without + * also updating the Tk_FakeWin structure (or vice versa). + */ + + if (sizeof(TkWindow) != sizeof(Tk_FakeWin)) { + panic("TkWindow and Tk_FakeWin are not the same size"); + } + + /* + * Create the basic TkWindow structure. + */ + + tkwin = CreateTopLevelWindow(interp, (Tk_Window) NULL, baseName, + screenName); + if (tkwin == NULL) { + return NULL; + } + + /* + * Create the TkMainInfo structure for this application, and set + * up name-related information for the new window. + */ + + winPtr = (TkWindow *) tkwin; + mainPtr = (TkMainInfo *) ckalloc(sizeof(TkMainInfo)); + mainPtr->winPtr = winPtr; + mainPtr->refCount = 1; + mainPtr->interp = interp; + Tcl_InitHashTable(&mainPtr->nameTable, TCL_STRING_KEYS); + TkBindInit(mainPtr); + TkFontPkgInit(mainPtr); + mainPtr->tlFocusPtr = NULL; + mainPtr->displayFocusPtr = NULL; + mainPtr->optionRootPtr = NULL; + Tcl_InitHashTable(&mainPtr->imageTable, TCL_STRING_KEYS); + mainPtr->strictMotif = 0; + if (Tcl_LinkVar(interp, "tk_strictMotif", (char *) &mainPtr->strictMotif, + TCL_LINK_BOOLEAN) != TCL_OK) { + Tcl_ResetResult(interp); + } + mainPtr->nextPtr = tkMainWindowList; + tkMainWindowList = mainPtr; + winPtr->mainPtr = mainPtr; + hPtr = Tcl_CreateHashEntry(&mainPtr->nameTable, ".", &dummy); + Tcl_SetHashValue(hPtr, winPtr); + winPtr->pathName = Tcl_GetHashKey(&mainPtr->nameTable, hPtr); + + /* + * We have just created another Tk application; increment the refcount + * on the display pointer. + */ + + winPtr->dispPtr->refCount++; + + /* + * Register the interpreter for "send" purposes. + */ + + winPtr->nameUid = Tk_GetUid(Tk_SetAppName(tkwin, baseName)); + + /* + * Bind in Tk's commands. + */ + + isSafe = Tcl_IsSafe(interp); + for (cmdPtr = commands; cmdPtr->name != NULL; cmdPtr++) { + if ((cmdPtr->cmdProc == NULL) && (cmdPtr->objProc == NULL)) { + panic("TkCreateMainWindow: builtin command with NULL string and object procs"); + } + if (cmdPtr->cmdProc != NULL) { + Tcl_CreateCommand(interp, cmdPtr->name, cmdPtr->cmdProc, + (ClientData) tkwin, (void (*) _ANSI_ARGS_((ClientData))) NULL); + } else { + Tcl_CreateObjCommand(interp, cmdPtr->name, cmdPtr->objProc, + (ClientData) tkwin, NULL); + } + if (isSafe) { + if (!(cmdPtr->isSafe)) { + Tcl_HideCommand(interp, cmdPtr->name, cmdPtr->name); + } + } + } + + /* + * Set variables for the intepreter. + */ + + Tcl_SetVar(interp, "tk_patchLevel", TK_PATCH_LEVEL, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tk_version", TK_VERSION, TCL_GLOBAL_ONLY); + + numMainWindows++; + return tkwin; +} + +/* + *-------------------------------------------------------------- + * + * Tk_CreateWindow -- + * + * Create a new internal or top-level window as a child of an + * existing window. + * + * Results: + * The return value is a token for the new window. This + * is not the same as X's token for the window. If an error + * occurred in creating the window (e.g. no such display or + * screen), then an error message is left in interp->result and + * NULL is returned. + * + * Side effects: + * A new window structure is allocated locally. An X + * window is not initially created, but will be created + * the first time the window is mapped. + * + *-------------------------------------------------------------- + */ + +Tk_Window +Tk_CreateWindow(interp, parent, name, screenName) + Tcl_Interp *interp; /* Interpreter to use for error reporting. + * Interp->result is assumed to be + * initialized by the caller. */ + Tk_Window parent; /* Token for parent of new window. */ + char *name; /* Name for new window. Must be unique + * among parent's children. */ + char *screenName; /* If NULL, new window will be internal on + * same screen as its parent. If non-NULL, + * gives name of screen on which to create + * new window; window will be a top-level + * window. */ +{ + TkWindow *parentPtr = (TkWindow *) parent; + TkWindow *winPtr; + + if ((parentPtr != NULL) && (parentPtr->flags & TK_ALREADY_DEAD)) { + Tcl_AppendResult(interp, + "can't create window: parent has been destroyed", + (char *) NULL); + return NULL; + } else if ((parentPtr != NULL) && + (parentPtr->flags & TK_CONTAINER)) { + Tcl_AppendResult(interp, + "can't create window: its parent has -container = yes", + (char *) NULL); + return NULL; + } + if (screenName == NULL) { + winPtr = TkAllocWindow(parentPtr->dispPtr, parentPtr->screenNum, + parentPtr); + if (NameWindow(interp, winPtr, parentPtr, name) != TCL_OK) { + Tk_DestroyWindow((Tk_Window) winPtr); + return NULL; + } else { + return (Tk_Window) winPtr; + } + } else { + return CreateTopLevelWindow(interp, parent, name, screenName); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_CreateWindowFromPath -- + * + * This procedure is similar to Tk_CreateWindow except that + * it uses a path name to create the window, rather than a + * parent and a child name. + * + * Results: + * The return value is a token for the new window. This + * is not the same as X's token for the window. If an error + * occurred in creating the window (e.g. no such display or + * screen), then an error message is left in interp->result and + * NULL is returned. + * + * Side effects: + * A new window structure is allocated locally. An X + * window is not initially created, but will be created + * the first time the window is mapped. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +Tk_CreateWindowFromPath(interp, tkwin, pathName, screenName) + Tcl_Interp *interp; /* Interpreter to use for error reporting. + * Interp->result is assumed to be + * initialized by the caller. */ + Tk_Window tkwin; /* Token for any window in application + * that is to contain new window. */ + char *pathName; /* Path name for new window within the + * application of tkwin. The parent of + * this window must already exist, but + * the window itself must not exist. */ + char *screenName; /* If NULL, new window will be on same + * screen as its parent. If non-NULL, + * gives name of screen on which to create + * new window; window will be a top-level + * window. */ +{ +#define FIXED_SPACE 5 + char fixedSpace[FIXED_SPACE+1]; + char *p; + Tk_Window parent; + int numChars; + + /* + * Strip the parent's name out of pathName (it's everything up + * to the last dot). There are two tricky parts: (a) must + * copy the parent's name somewhere else to avoid modifying + * the pathName string (for large names, space for the copy + * will have to be malloc'ed); (b) must special-case the + * situation where the parent is ".". + */ + + p = strrchr(pathName, '.'); + if (p == NULL) { + Tcl_AppendResult(interp, "bad window path name \"", pathName, + "\"", (char *) NULL); + return NULL; + } + numChars = p-pathName; + if (numChars > FIXED_SPACE) { + p = (char *) ckalloc((unsigned) (numChars+1)); + } else { + p = fixedSpace; + } + if (numChars == 0) { + *p = '.'; + p[1] = '\0'; + } else { + strncpy(p, pathName, (size_t) numChars); + p[numChars] = '\0'; + } + + /* + * Find the parent window. + */ + + parent = Tk_NameToWindow(interp, p, tkwin); + if (p != fixedSpace) { + ckfree(p); + } + if (parent == NULL) { + return NULL; + } + if (((TkWindow *) parent)->flags & TK_ALREADY_DEAD) { + Tcl_AppendResult(interp, + "can't create window: parent has been destroyed", (char *) NULL); + return NULL; + } else if (((TkWindow *) parent)->flags & TK_CONTAINER) { + Tcl_AppendResult(interp, + "can't create window: its parent has -container = yes", + (char *) NULL); + return NULL; + } + + /* + * Create the window. + */ + + if (screenName == NULL) { + TkWindow *parentPtr = (TkWindow *) parent; + TkWindow *winPtr; + + winPtr = TkAllocWindow(parentPtr->dispPtr, parentPtr->screenNum, + parentPtr); + if (NameWindow(interp, winPtr, parentPtr, pathName+numChars+1) + != TCL_OK) { + Tk_DestroyWindow((Tk_Window) winPtr); + return NULL; + } else { + return (Tk_Window) winPtr; + } + } else { + return CreateTopLevelWindow(interp, parent, pathName+numChars+1, + screenName); + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_DestroyWindow -- + * + * Destroy an existing window. After this call, the caller + * should never again use the token. + * + * Results: + * None. + * + * Side effects: + * The window is deleted, along with all of its children. + * Relevant callback procedures are invoked. + * + *-------------------------------------------------------------- + */ + +void +Tk_DestroyWindow(tkwin) + Tk_Window tkwin; /* Window to destroy. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr = winPtr->dispPtr; + XEvent event; + + if (winPtr->flags & TK_ALREADY_DEAD) { + /* + * A destroy event binding caused the window to be destroyed + * again. Ignore the request. + */ + + return; + } + winPtr->flags |= TK_ALREADY_DEAD; + + /* + * Some cleanup needs to be done immediately, rather than later, + * because it needs information that will be destoyed before we + * get to the main cleanup point. For example, TkFocusDeadWindow + * needs to access the parentPtr field from a window, but if + * a Destroy event handler deletes the window's parent this + * field will be NULL before the main cleanup point is reached. + */ + + TkFocusDeadWindow(winPtr); + + /* + * If this is a main window, remove it from the list of main + * windows. This needs to be done now (rather than later with + * all the other main window cleanup) to handle situations where + * a destroy binding for a window calls "exit". In this case + * the child window cleanup isn't complete when exit is called, + * so the reference count of its application doesn't go to zero + * when exit calls Tk_DestroyWindow on ".", so the main window + * doesn't get removed from the list and exit loops infinitely. + * Even worse, if "destroy ." is called by the destroy binding + * before calling "exit", "exit" will attempt to destroy + * mainPtr->winPtr, which no longer exists, and there may be a + * core dump. + * + * Also decrement the display refcount so that if this is the + * last Tk application in this process on this display, the display + * can be closed and its data structures deleted. + */ + + if (winPtr->mainPtr->winPtr == winPtr) { + dispPtr->refCount--; + if (tkMainWindowList == winPtr->mainPtr) { + tkMainWindowList = winPtr->mainPtr->nextPtr; + } else { + TkMainInfo *prevPtr; + + for (prevPtr = tkMainWindowList; + prevPtr->nextPtr != winPtr->mainPtr; + prevPtr = prevPtr->nextPtr) { + /* Empty loop body. */ + } + prevPtr->nextPtr = winPtr->mainPtr->nextPtr; + } + numMainWindows--; + } + + /* + * Recursively destroy children. + */ + + dispPtr->destroyCount++; + while (winPtr->childList != NULL) { + TkWindow *childPtr; + childPtr = winPtr->childList; + childPtr->flags |= TK_DONT_DESTROY_WINDOW; + Tk_DestroyWindow((Tk_Window) childPtr); + if (winPtr->childList == childPtr) { + /* + * The child didn't remove itself from the child list, so + * let's remove it here. This can happen in some strange + * conditions, such as when a Delete event handler for a + * window deletes the window's parent. + */ + + winPtr->childList = childPtr->nextPtr; + childPtr->parentPtr = NULL; + } + } + if ((winPtr->flags & (TK_CONTAINER|TK_BOTH_HALVES)) + == (TK_CONTAINER|TK_BOTH_HALVES)) { + /* + * This is the container for an embedded application, and + * the embedded application is also in this process. Delete + * the embedded window in-line here, for the same reasons we + * delete children in-line (otherwise, for example, the Tk + * window may appear to exist even though its X window is + * gone; this could cause errors). Special note: it's possible + * that the embedded window has already been deleted, in which + * case TkpGetOtherWindow will return NULL. + */ + + TkWindow *childPtr; + childPtr = TkpGetOtherWindow(winPtr); + if (childPtr != NULL) { + childPtr->flags |= TK_DONT_DESTROY_WINDOW; + Tk_DestroyWindow((Tk_Window) childPtr); + } + } + + /* + * Generate a DestroyNotify event. In order for the DestroyNotify + * event to be processed correctly, need to make sure the window + * exists. This is a bit of a kludge, and may be unnecessarily + * expensive, but without it no event handlers will get called for + * windows that don't exist yet. + * + * Note: if the window's pathName is NULL it means that the window + * was not successfully initialized in the first place, so we should + * not make the window exist or generate the event. + */ + + if (winPtr->pathName != NULL) { + if (winPtr->window == None) { + Tk_MakeWindowExist(tkwin); + } + event.type = DestroyNotify; + event.xdestroywindow.serial = + LastKnownRequestProcessed(winPtr->display); + event.xdestroywindow.send_event = False; + event.xdestroywindow.display = winPtr->display; + event.xdestroywindow.event = winPtr->window; + event.xdestroywindow.window = winPtr->window; + Tk_HandleEvent(&event); + } + + /* + * Cleanup the data structures associated with this window. + */ + + if (winPtr->flags & TK_TOP_LEVEL) { + TkWmDeadWindow(winPtr); + } else if (winPtr->flags & TK_WM_COLORMAP_WINDOW) { + TkWmRemoveFromColormapWindows(winPtr); + } + if (winPtr->window != None) { +#if defined(MAC_TCL) || defined(__WIN32__) + XDestroyWindow(winPtr->display, winPtr->window); +#else + if ((winPtr->flags & TK_TOP_LEVEL) + || !(winPtr->flags & TK_DONT_DESTROY_WINDOW)) { + /* + * The parent has already been destroyed and this isn't + * a top-level window, so this window will be destroyed + * implicitly when the parent's X window is destroyed; + * it's much faster not to do an explicit destroy of this + * X window. + */ + + dispPtr->lastDestroyRequest = NextRequest(winPtr->display); + XDestroyWindow(winPtr->display, winPtr->window); + } +#endif + TkFreeWindowId(dispPtr, winPtr->window); + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&dispPtr->winTable, + (char *) winPtr->window)); + winPtr->window = None; + } + dispPtr->destroyCount--; + UnlinkWindow(winPtr); + TkEventDeadWindow(winPtr); + TkBindDeadWindow(winPtr); +#ifdef TK_USE_INPUT_METHODS + if (winPtr->inputContext != NULL) { + XDestroyIC(winPtr->inputContext); + } +#endif /* TK_USE_INPUT_METHODS */ + if (winPtr->tagPtr != NULL) { + TkFreeBindingTags(winPtr); + } + TkOptionDeadWindow(winPtr); + TkSelDeadWindow(winPtr); + TkGrabDeadWindow(winPtr); + if (winPtr->mainPtr != NULL) { + if (winPtr->pathName != NULL) { + Tk_DeleteAllBindings(winPtr->mainPtr->bindingTable, + (ClientData) winPtr->pathName); + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&winPtr->mainPtr->nameTable, + winPtr->pathName)); + } + winPtr->mainPtr->refCount--; + if (winPtr->mainPtr->refCount == 0) { + register TkCmd *cmdPtr; + + /* + * We just deleted the last window in the application. Delete + * the TkMainInfo structure too and replace all of Tk's commands + * with dummy commands that return errors. Also delete the + * "send" command to unregister the interpreter. + * + * NOTE: Only replace the commands it if the interpreter is + * not being deleted. If it *is*, the interpreter cleanup will + * do all the needed work. + */ + + if ((winPtr->mainPtr->interp != NULL) && + (!Tcl_InterpDeleted(winPtr->mainPtr->interp))) { + for (cmdPtr = commands; cmdPtr->name != NULL; cmdPtr++) { + Tcl_CreateCommand(winPtr->mainPtr->interp, cmdPtr->name, + TkDeadAppCmd, (ClientData) NULL, + (void (*) _ANSI_ARGS_((ClientData))) NULL); + } + Tcl_CreateCommand(winPtr->mainPtr->interp, "send", + TkDeadAppCmd, (ClientData) NULL, + (void (*) _ANSI_ARGS_((ClientData))) NULL); + Tcl_UnlinkVar(winPtr->mainPtr->interp, "tk_strictMotif"); + } + + Tcl_DeleteHashTable(&winPtr->mainPtr->nameTable); + TkBindFree(winPtr->mainPtr); + TkFontPkgFree(winPtr->mainPtr); + TkDeleteAllImages(winPtr->mainPtr); + + /* + * When embedding Tk into other applications, make sure + * that all destroy events reach the server. Otherwise + * the embedding application may also attempt to destroy + * the windows, resulting in an X error + */ + + if (winPtr->flags & TK_EMBEDDED) { + XSync(winPtr->display,False) ; + } + ckfree((char *) winPtr->mainPtr); + + /* + * If no other applications are using the display, close the + * display now and relinquish its data structures. + */ + + if (dispPtr->refCount <= 0) { +#ifdef NOT_YET + /* + * I have disabled this code because on Windows there are + * still order dependencies in close-down. All displays + * and resources will get closed down properly anyway at + * exit, through the exit handler. + */ + + TkDisplay *theDispPtr, *backDispPtr; + + /* + * Splice this display out of the list of displays. + */ + + for (theDispPtr = tkDisplayList, backDispPtr = NULL; + (theDispPtr != winPtr->dispPtr) && + (theDispPtr != NULL); + theDispPtr = theDispPtr->nextPtr) { + backDispPtr = theDispPtr; + } + if (theDispPtr == NULL) { + panic("could not find display to close!"); + } + if (backDispPtr == NULL) { + tkDisplayList = theDispPtr->nextPtr; + } else { + backDispPtr->nextPtr = theDispPtr->nextPtr; + } + + /* + * Found and spliced it out, now actually do the cleanup. + */ + + if (dispPtr->name != NULL) { + ckfree(dispPtr->name); + } + + Tcl_DeleteHashTable(&(dispPtr->winTable)); + + /* + * Cannot yet close the display because we still have + * order of deletion problems. Defer until exit handling + * instead. At that time, the display will cleanly shut + * down (hopefully..). (JYL) + */ + + TkpCloseDisplay(dispPtr); + + /* + * There is lots more to clean up, we leave it at this for + * the time being. + */ +#endif + } + } + } + ckfree((char *) winPtr); +} + +/* + *-------------------------------------------------------------- + * + * Tk_MapWindow -- + * + * Map a window within its parent. This may require the + * window and/or its parents to actually be created. + * + * Results: + * None. + * + * Side effects: + * The given window will be mapped. Windows may also + * be created. + * + *-------------------------------------------------------------- + */ + +void +Tk_MapWindow(tkwin) + Tk_Window tkwin; /* Token for window to map. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + XEvent event; + + if (winPtr->flags & TK_MAPPED) { + return; + } + if (winPtr->window == None) { + Tk_MakeWindowExist(tkwin); + } + if (winPtr->flags & TK_TOP_LEVEL) { + /* + * Lots of special processing has to be done for top-level + * windows. Let tkWm.c handle everything itself. + */ + + TkWmMapWindow(winPtr); + return; + } + winPtr->flags |= TK_MAPPED; + XMapWindow(winPtr->display, winPtr->window); + event.type = MapNotify; + event.xmap.serial = LastKnownRequestProcessed(winPtr->display); + event.xmap.send_event = False; + event.xmap.display = winPtr->display; + event.xmap.event = winPtr->window; + event.xmap.window = winPtr->window; + event.xmap.override_redirect = winPtr->atts.override_redirect; + Tk_HandleEvent(&event); +} + +/* + *-------------------------------------------------------------- + * + * Tk_MakeWindowExist -- + * + * Ensure that a particular window actually exists. This + * procedure shouldn't normally need to be invoked from + * outside the Tk package, but may be needed if someone + * wants to manipulate a window before mapping it. + * + * Results: + * None. + * + * Side effects: + * When the procedure returns, the X window associated with + * tkwin is guaranteed to exist. This may require the + * window's ancestors to be created also. + * + *-------------------------------------------------------------- + */ + +void +Tk_MakeWindowExist(tkwin) + Tk_Window tkwin; /* Token for window. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + TkWindow *winPtr2; + Window parent; + Tcl_HashEntry *hPtr; + int new; + + if (winPtr->window != None) { + return; + } + + if ((winPtr->parentPtr == NULL) || (winPtr->flags & TK_TOP_LEVEL)) { + parent = XRootWindow(winPtr->display, winPtr->screenNum); + } else { + if (winPtr->parentPtr->window == None) { + Tk_MakeWindowExist((Tk_Window) winPtr->parentPtr); + } + parent = winPtr->parentPtr->window; + } + + if (winPtr->classProcsPtr != NULL + && winPtr->classProcsPtr->createProc != NULL) { + winPtr->window = (*winPtr->classProcsPtr->createProc)(tkwin, parent, + winPtr->instanceData); + } else { + winPtr->window = TkpMakeWindow(winPtr, parent); + } + + hPtr = Tcl_CreateHashEntry(&winPtr->dispPtr->winTable, + (char *) winPtr->window, &new); + Tcl_SetHashValue(hPtr, winPtr); + winPtr->dirtyAtts = 0; + winPtr->dirtyChanges = 0; +#ifdef TK_USE_INPUT_METHODS + winPtr->inputContext = NULL; +#endif /* TK_USE_INPUT_METHODS */ + + if (!(winPtr->flags & TK_TOP_LEVEL)) { + /* + * If any siblings higher up in the stacking order have already + * been created then move this window to its rightful position + * in the stacking order. + * + * NOTE: this code ignores any changes anyone might have made + * to the sibling and stack_mode field of the window's attributes, + * so it really isn't safe for these to be manipulated except + * by calling Tk_RestackWindow. + */ + + for (winPtr2 = winPtr->nextPtr; winPtr2 != NULL; + winPtr2 = winPtr2->nextPtr) { + if ((winPtr2->window != None) + && !(winPtr2->flags & (TK_TOP_LEVEL|TK_REPARENTED))) { + XWindowChanges changes; + changes.sibling = winPtr2->window; + changes.stack_mode = Below; + XConfigureWindow(winPtr->display, winPtr->window, + CWSibling|CWStackMode, &changes); + break; + } + } + + /* + * If this window has a different colormap than its parent, add + * the window to the WM_COLORMAP_WINDOWS property for its top-level. + */ + + if ((winPtr->parentPtr != NULL) && + (winPtr->atts.colormap != winPtr->parentPtr->atts.colormap)) { + TkWmAddToColormapWindows(winPtr); + winPtr->flags |= TK_WM_COLORMAP_WINDOW; + } + } + + /* + * Issue a ConfigureNotify event if there were deferred configuration + * changes (but skip it if the window is being deleted; the + * ConfigureNotify event could cause problems if we're being called + * from Tk_DestroyWindow under some conditions). + */ + + if ((winPtr->flags & TK_NEED_CONFIG_NOTIFY) + && !(winPtr->flags & TK_ALREADY_DEAD)){ + winPtr->flags &= ~TK_NEED_CONFIG_NOTIFY; + TkDoConfigureNotify(winPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_UnmapWindow, etc. -- + * + * There are several procedures under here, each of which + * mirrors an existing X procedure. In addition to performing + * the functions of the corresponding procedure, each + * procedure also updates the local window structure and + * synthesizes an X event (if the window's structure is being + * managed internally). + * + * Results: + * See the manual entries. + * + * Side effects: + * See the manual entries. + * + *-------------------------------------------------------------- + */ + +void +Tk_UnmapWindow(tkwin) + Tk_Window tkwin; /* Token for window to unmap. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + if (!(winPtr->flags & TK_MAPPED) || (winPtr->flags & TK_ALREADY_DEAD)) { + return; + } + if (winPtr->flags & TK_TOP_LEVEL) { + /* + * Special processing has to be done for top-level windows. Let + * tkWm.c handle everything itself. + */ + + TkWmUnmapWindow(winPtr); + return; + } + winPtr->flags &= ~TK_MAPPED; + XUnmapWindow(winPtr->display, winPtr->window); + if (!(winPtr->flags & TK_TOP_LEVEL)) { + XEvent event; + + event.type = UnmapNotify; + event.xunmap.serial = LastKnownRequestProcessed(winPtr->display); + event.xunmap.send_event = False; + event.xunmap.display = winPtr->display; + event.xunmap.event = winPtr->window; + event.xunmap.window = winPtr->window; + event.xunmap.from_configure = False; + Tk_HandleEvent(&event); + } +} + +void +Tk_ConfigureWindow(tkwin, valueMask, valuePtr) + Tk_Window tkwin; /* Window to re-configure. */ + unsigned int valueMask; /* Mask indicating which parts of + * *valuePtr are to be used. */ + XWindowChanges *valuePtr; /* New values. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + if (valueMask & CWX) { + winPtr->changes.x = valuePtr->x; + } + if (valueMask & CWY) { + winPtr->changes.y = valuePtr->y; + } + if (valueMask & CWWidth) { + winPtr->changes.width = valuePtr->width; + } + if (valueMask & CWHeight) { + winPtr->changes.height = valuePtr->height; + } + if (valueMask & CWBorderWidth) { + winPtr->changes.border_width = valuePtr->border_width; + } + if (valueMask & (CWSibling|CWStackMode)) { + panic("Can't set sibling or stack mode from Tk_ConfigureWindow."); + } + + if (winPtr->window != None) { + XConfigureWindow(winPtr->display, winPtr->window, + valueMask, valuePtr); + TkDoConfigureNotify(winPtr); + } else { + winPtr->dirtyChanges |= valueMask; + winPtr->flags |= TK_NEED_CONFIG_NOTIFY; + } +} + +void +Tk_MoveWindow(tkwin, x, y) + Tk_Window tkwin; /* Window to move. */ + int x, y; /* New location for window (within + * parent). */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->changes.x = x; + winPtr->changes.y = y; + if (winPtr->window != None) { + XMoveWindow(winPtr->display, winPtr->window, x, y); + TkDoConfigureNotify(winPtr); + } else { + winPtr->dirtyChanges |= CWX|CWY; + winPtr->flags |= TK_NEED_CONFIG_NOTIFY; + } +} + +void +Tk_ResizeWindow(tkwin, width, height) + Tk_Window tkwin; /* Window to resize. */ + int width, height; /* New dimensions for window. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->changes.width = (unsigned) width; + winPtr->changes.height = (unsigned) height; + if (winPtr->window != None) { + XResizeWindow(winPtr->display, winPtr->window, (unsigned) width, + (unsigned) height); + TkDoConfigureNotify(winPtr); + } else { + winPtr->dirtyChanges |= CWWidth|CWHeight; + winPtr->flags |= TK_NEED_CONFIG_NOTIFY; + } +} + +void +Tk_MoveResizeWindow(tkwin, x, y, width, height) + Tk_Window tkwin; /* Window to move and resize. */ + int x, y; /* New location for window (within + * parent). */ + int width, height; /* New dimensions for window. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->changes.x = x; + winPtr->changes.y = y; + winPtr->changes.width = (unsigned) width; + winPtr->changes.height = (unsigned) height; + if (winPtr->window != None) { + XMoveResizeWindow(winPtr->display, winPtr->window, x, y, + (unsigned) width, (unsigned) height); + TkDoConfigureNotify(winPtr); + } else { + winPtr->dirtyChanges |= CWX|CWY|CWWidth|CWHeight; + winPtr->flags |= TK_NEED_CONFIG_NOTIFY; + } +} + +void +Tk_SetWindowBorderWidth(tkwin, width) + Tk_Window tkwin; /* Window to modify. */ + int width; /* New border width for window. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->changes.border_width = width; + if (winPtr->window != None) { + XSetWindowBorderWidth(winPtr->display, winPtr->window, + (unsigned) width); + TkDoConfigureNotify(winPtr); + } else { + winPtr->dirtyChanges |= CWBorderWidth; + winPtr->flags |= TK_NEED_CONFIG_NOTIFY; + } +} + +void +Tk_ChangeWindowAttributes(tkwin, valueMask, attsPtr) + Tk_Window tkwin; /* Window to manipulate. */ + unsigned long valueMask; /* OR'ed combination of bits, + * indicating which fields of + * *attsPtr are to be used. */ + register XSetWindowAttributes *attsPtr; + /* New values for some attributes. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + if (valueMask & CWBackPixmap) { + winPtr->atts.background_pixmap = attsPtr->background_pixmap; + } + if (valueMask & CWBackPixel) { + winPtr->atts.background_pixel = attsPtr->background_pixel; + } + if (valueMask & CWBorderPixmap) { + winPtr->atts.border_pixmap = attsPtr->border_pixmap; + } + if (valueMask & CWBorderPixel) { + winPtr->atts.border_pixel = attsPtr->border_pixel; + } + if (valueMask & CWBitGravity) { + winPtr->atts.bit_gravity = attsPtr->bit_gravity; + } + if (valueMask & CWWinGravity) { + winPtr->atts.win_gravity = attsPtr->win_gravity; + } + if (valueMask & CWBackingStore) { + winPtr->atts.backing_store = attsPtr->backing_store; + } + if (valueMask & CWBackingPlanes) { + winPtr->atts.backing_planes = attsPtr->backing_planes; + } + if (valueMask & CWBackingPixel) { + winPtr->atts.backing_pixel = attsPtr->backing_pixel; + } + if (valueMask & CWOverrideRedirect) { + winPtr->atts.override_redirect = attsPtr->override_redirect; + } + if (valueMask & CWSaveUnder) { + winPtr->atts.save_under = attsPtr->save_under; + } + if (valueMask & CWEventMask) { + winPtr->atts.event_mask = attsPtr->event_mask; + } + if (valueMask & CWDontPropagate) { + winPtr->atts.do_not_propagate_mask + = attsPtr->do_not_propagate_mask; + } + if (valueMask & CWColormap) { + winPtr->atts.colormap = attsPtr->colormap; + } + if (valueMask & CWCursor) { + winPtr->atts.cursor = attsPtr->cursor; + } + + if (winPtr->window != None) { + XChangeWindowAttributes(winPtr->display, winPtr->window, + valueMask, attsPtr); + } else { + winPtr->dirtyAtts |= valueMask; + } +} + +void +Tk_SetWindowBackground(tkwin, pixel) + Tk_Window tkwin; /* Window to manipulate. */ + unsigned long pixel; /* Pixel value to use for + * window's background. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->atts.background_pixel = pixel; + + if (winPtr->window != None) { + XSetWindowBackground(winPtr->display, winPtr->window, pixel); + } else { + winPtr->dirtyAtts = (winPtr->dirtyAtts & (unsigned) ~CWBackPixmap) + | CWBackPixel; + } +} + +void +Tk_SetWindowBackgroundPixmap(tkwin, pixmap) + Tk_Window tkwin; /* Window to manipulate. */ + Pixmap pixmap; /* Pixmap to use for window's + * background. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->atts.background_pixmap = pixmap; + + if (winPtr->window != None) { + XSetWindowBackgroundPixmap(winPtr->display, + winPtr->window, pixmap); + } else { + winPtr->dirtyAtts = (winPtr->dirtyAtts & (unsigned) ~CWBackPixel) + | CWBackPixmap; + } +} + +void +Tk_SetWindowBorder(tkwin, pixel) + Tk_Window tkwin; /* Window to manipulate. */ + unsigned long pixel; /* Pixel value to use for + * window's border. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->atts.border_pixel = pixel; + + if (winPtr->window != None) { + XSetWindowBorder(winPtr->display, winPtr->window, pixel); + } else { + winPtr->dirtyAtts = (winPtr->dirtyAtts & (unsigned) ~CWBorderPixmap) + | CWBorderPixel; + } +} + +void +Tk_SetWindowBorderPixmap(tkwin, pixmap) + Tk_Window tkwin; /* Window to manipulate. */ + Pixmap pixmap; /* Pixmap to use for window's + * border. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->atts.border_pixmap = pixmap; + + if (winPtr->window != None) { + XSetWindowBorderPixmap(winPtr->display, + winPtr->window, pixmap); + } else { + winPtr->dirtyAtts = (winPtr->dirtyAtts & (unsigned) ~CWBorderPixel) + | CWBorderPixmap; + } +} + +void +Tk_DefineCursor(tkwin, cursor) + Tk_Window tkwin; /* Window to manipulate. */ + Tk_Cursor cursor; /* Cursor to use for window (may be None). */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + +#ifdef MAC_TCL + winPtr->atts.cursor = (XCursor) cursor; +#else + winPtr->atts.cursor = (Cursor) cursor; +#endif + + if (winPtr->window != None) { + XDefineCursor(winPtr->display, winPtr->window, winPtr->atts.cursor); + } else { + winPtr->dirtyAtts = winPtr->dirtyAtts | CWCursor; + } +} + +void +Tk_UndefineCursor(tkwin) + Tk_Window tkwin; /* Window to manipulate. */ +{ + Tk_DefineCursor(tkwin, None); +} + +void +Tk_SetWindowColormap(tkwin, colormap) + Tk_Window tkwin; /* Window to manipulate. */ + Colormap colormap; /* Colormap to use for window. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->atts.colormap = colormap; + + if (winPtr->window != None) { + XSetWindowColormap(winPtr->display, winPtr->window, colormap); + if (!(winPtr->flags & TK_TOP_LEVEL)) { + TkWmAddToColormapWindows(winPtr); + winPtr->flags |= TK_WM_COLORMAP_WINDOW; + } + } else { + winPtr->dirtyAtts |= CWColormap; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_SetWindowVisual -- + * + * This procedure is called to specify a visual to be used + * for a Tk window when it is created. This procedure, if + * called at all, must be called before the X window is created + * (i.e. before Tk_MakeWindowExist is called). + * + * Results: + * The return value is 1 if successful, or 0 if the X window has + * been already created. + * + * Side effects: + * The information given is stored for when the window is created. + * + *---------------------------------------------------------------------- + */ + +int +Tk_SetWindowVisual(tkwin, visual, depth, colormap) + Tk_Window tkwin; /* Window to manipulate. */ + Visual *visual; /* New visual for window. */ + int depth; /* New depth for window. */ + Colormap colormap; /* An appropriate colormap for the visual. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + if( winPtr->window != None ){ + /* Too late! */ + return 0; + } + + winPtr->visual = visual; + winPtr->depth = depth; + winPtr->atts.colormap = colormap; + winPtr->dirtyAtts |= CWColormap; + + /* + * The following code is needed to make sure that the window doesn't + * inherit the parent's border pixmap, which would result in a BadMatch + * error. + */ + + if (!(winPtr->dirtyAtts & CWBorderPixmap)) { + winPtr->dirtyAtts |= CWBorderPixel; + } + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * TkDoConfigureNotify -- + * + * Generate a ConfigureNotify event describing the current + * configuration of a window. + * + * Results: + * None. + * + * Side effects: + * An event is generated and processed by Tk_HandleEvent. + * + *---------------------------------------------------------------------- + */ + +void +TkDoConfigureNotify(winPtr) + register TkWindow *winPtr; /* Window whose configuration + * was just changed. */ +{ + XEvent event; + + event.type = ConfigureNotify; + event.xconfigure.serial = LastKnownRequestProcessed(winPtr->display); + event.xconfigure.send_event = False; + event.xconfigure.display = winPtr->display; + event.xconfigure.event = winPtr->window; + event.xconfigure.window = winPtr->window; + event.xconfigure.x = winPtr->changes.x; + event.xconfigure.y = winPtr->changes.y; + event.xconfigure.width = winPtr->changes.width; + event.xconfigure.height = winPtr->changes.height; + event.xconfigure.border_width = winPtr->changes.border_width; + if (winPtr->changes.stack_mode == Above) { + event.xconfigure.above = winPtr->changes.sibling; + } else { + event.xconfigure.above = None; + } + event.xconfigure.override_redirect = winPtr->atts.override_redirect; + Tk_HandleEvent(&event); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_SetClass -- + * + * This procedure is used to give a window a class. + * + * Results: + * None. + * + * Side effects: + * A new class is stored for tkwin, replacing any existing + * class for it. + * + *---------------------------------------------------------------------- + */ + +void +Tk_SetClass(tkwin, className) + Tk_Window tkwin; /* Token for window to assign class. */ + char *className; /* New class for tkwin. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->classUid = Tk_GetUid(className); + if (winPtr->flags & TK_TOP_LEVEL) { + TkWmSetClass(winPtr); + } + TkOptionClassChanged(winPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TkSetClassProcs -- + * + * This procedure is used to set the class procedures and + * instance data for a window. + * + * Results: + * None. + * + * Side effects: + * A new set of class procedures and instance data is stored + * for tkwin, replacing any existing values. + * + *---------------------------------------------------------------------- + */ + +void +TkSetClassProcs(tkwin, procs, instanceData) + Tk_Window tkwin; /* Token for window to modify. */ + TkClassProcs *procs; /* Class procs structure. */ + ClientData instanceData; /* Data to be passed to class procedures. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + winPtr->classProcsPtr = procs; + winPtr->instanceData = instanceData; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_NameToWindow -- + * + * Given a string name for a window, this procedure + * returns the token for the window, if there exists a + * window corresponding to the given name. + * + * Results: + * The return result is either a token for the window corresponding + * to "name", or else NULL to indicate that there is no such + * window. In this case, an error message is left in interp->result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +Tk_NameToWindow(interp, pathName, tkwin) + Tcl_Interp *interp; /* Where to report errors. */ + char *pathName; /* Path name of window. */ + Tk_Window tkwin; /* Token for window: name is assumed to + * belong to the same main window as tkwin. */ +{ + Tcl_HashEntry *hPtr; + + hPtr = Tcl_FindHashEntry(&((TkWindow *) tkwin)->mainPtr->nameTable, + pathName); + if (hPtr == NULL) { + Tcl_AppendResult(interp, "bad window path name \"", + pathName, "\"", (char *) NULL); + return NULL; + } + return (Tk_Window) Tcl_GetHashValue(hPtr); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_IdToWindow -- + * + * Given an X display and window ID, this procedure returns the + * Tk token for the window, if there exists a Tk window corresponding + * to the given ID. + * + * Results: + * The return result is either a token for the window corresponding + * to the given X id, or else NULL to indicate that there is no such + * window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +Tk_IdToWindow(display, window) + Display *display; /* X display containing the window. */ + Window window; /* X window window id. */ +{ + TkDisplay *dispPtr; + Tcl_HashEntry *hPtr; + + for (dispPtr = tkDisplayList; ; dispPtr = dispPtr->nextPtr) { + if (dispPtr == NULL) { + return NULL; + } + if (dispPtr->display == display) { + break; + } + } + + hPtr = Tcl_FindHashEntry(&dispPtr->winTable, (char *) window); + if (hPtr == NULL) { + return NULL; + } + return (Tk_Window) Tcl_GetHashValue(hPtr); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_DisplayName -- + * + * Return the textual name of a window's display. + * + * Results: + * The return value is the string name of the display associated + * with tkwin. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +char * +Tk_DisplayName(tkwin) + Tk_Window tkwin; /* Window whose display name is desired. */ +{ + return ((TkWindow *) tkwin)->dispPtr->name; +} + +/* + *---------------------------------------------------------------------- + * + * UnlinkWindow -- + * + * This procedure removes a window from the childList of its + * parent. + * + * Results: + * None. + * + * Side effects: + * The window is unlinked from its childList. + * + *---------------------------------------------------------------------- + */ + +static void +UnlinkWindow(winPtr) + TkWindow *winPtr; /* Child window to be unlinked. */ +{ + TkWindow *prevPtr; + + if (winPtr->parentPtr == NULL) { + return; + } + prevPtr = winPtr->parentPtr->childList; + if (prevPtr == winPtr) { + winPtr->parentPtr->childList = winPtr->nextPtr; + if (winPtr->nextPtr == NULL) { + winPtr->parentPtr->lastChildPtr = NULL; + } + } else { + while (prevPtr->nextPtr != winPtr) { + prevPtr = prevPtr->nextPtr; + if (prevPtr == NULL) { + panic("UnlinkWindow couldn't find child in parent"); + } + } + prevPtr->nextPtr = winPtr->nextPtr; + if (winPtr->nextPtr == NULL) { + winPtr->parentPtr->lastChildPtr = prevPtr; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_RestackWindow -- + * + * Change a window's position in the stacking order. + * + * Results: + * TCL_OK is normally returned. If other is not a descendant + * of tkwin's parent then TCL_ERROR is returned and tkwin is + * not repositioned. + * + * Side effects: + * Tkwin is repositioned in the stacking order. + * + *---------------------------------------------------------------------- + */ + +int +Tk_RestackWindow(tkwin, aboveBelow, other) + Tk_Window tkwin; /* Token for window whose position in + * the stacking order is to change. */ + int aboveBelow; /* Indicates new position of tkwin relative + * to other; must be Above or Below. */ + Tk_Window other; /* Tkwin will be moved to a position that + * puts it just above or below this window. + * If NULL then tkwin goes above or below + * all windows in the same parent. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + TkWindow *otherPtr = (TkWindow *) other; + XWindowChanges changes; + unsigned int mask; + + + /* + * Special case: if winPtr is a top-level window then just find + * the top-level ancestor of otherPtr and restack winPtr above + * otherPtr without changing any of Tk's childLists. + */ + + changes.stack_mode = aboveBelow; + mask = CWStackMode; + if (winPtr->flags & TK_TOP_LEVEL) { + while ((otherPtr != NULL) && !(otherPtr->flags & TK_TOP_LEVEL)) { + otherPtr = otherPtr->parentPtr; + } + TkWmRestackToplevel(winPtr, aboveBelow, otherPtr); + return TCL_OK; + } + + /* + * Find an ancestor of otherPtr that is a sibling of winPtr. + */ + + if (winPtr->parentPtr == NULL) { + /* + * Window is going to be deleted shortly; don't do anything. + */ + + return TCL_OK; + } + if (otherPtr == NULL) { + if (aboveBelow == Above) { + otherPtr = winPtr->parentPtr->lastChildPtr; + } else { + otherPtr = winPtr->parentPtr->childList; + } + } else { + while (winPtr->parentPtr != otherPtr->parentPtr) { + if ((otherPtr == NULL) || (otherPtr->flags & TK_TOP_LEVEL)) { + return TCL_ERROR; + } + otherPtr = otherPtr->parentPtr; + } + } + if (otherPtr == winPtr) { + return TCL_OK; + } + + /* + * Reposition winPtr in the stacking order. + */ + + UnlinkWindow(winPtr); + if (aboveBelow == Above) { + winPtr->nextPtr = otherPtr->nextPtr; + if (winPtr->nextPtr == NULL) { + winPtr->parentPtr->lastChildPtr = winPtr; + } + otherPtr->nextPtr = winPtr; + } else { + TkWindow *prevPtr; + + prevPtr = winPtr->parentPtr->childList; + if (prevPtr == otherPtr) { + winPtr->parentPtr->childList = winPtr; + } else { + while (prevPtr->nextPtr != otherPtr) { + prevPtr = prevPtr->nextPtr; + } + prevPtr->nextPtr = winPtr; + } + winPtr->nextPtr = otherPtr; + } + + /* + * Notify the X server of the change. If winPtr hasn't yet been + * created then there's no need to tell the X server now, since + * the stacking order will be handled properly when the window + * is finally created. + */ + + if (winPtr->window != None) { + changes.stack_mode = Above; + for (otherPtr = winPtr->nextPtr; otherPtr != NULL; + otherPtr = otherPtr->nextPtr) { + if ((otherPtr->window != None) + && !(otherPtr->flags & (TK_TOP_LEVEL|TK_REPARENTED))){ + changes.sibling = otherPtr->window; + changes.stack_mode = Below; + mask = CWStackMode|CWSibling; + break; + } + } + XConfigureWindow(winPtr->display, winPtr->window, mask, &changes); + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_MainWindow -- + * + * Returns the main window for an application. + * + * Results: + * If interp has a Tk application associated with it, the main + * window for the application is returned. Otherwise NULL is + * returned and an error message is left in interp->result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +Tk_MainWindow(interp) + Tcl_Interp *interp; /* Interpreter that embodies the + * application. Used for error + * reporting also. */ +{ + TkMainInfo *mainPtr; + + for (mainPtr = tkMainWindowList; mainPtr != NULL; + mainPtr = mainPtr->nextPtr) { + if (mainPtr->interp == interp) { + return (Tk_Window) mainPtr->winPtr; + } + } + interp->result = "this isn't a Tk application"; + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_StrictMotif -- + * + * Indicates whether strict Motif compliance has been specified + * for the given window. + * + * Results: + * The return value is 1 if strict Motif compliance has been + * requested for tkwin's application by setting the tk_strictMotif + * variable in its interpreter to a true value. 0 is returned + * if tk_strictMotif has a false value. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +Tk_StrictMotif(tkwin) + Tk_Window tkwin; /* Window whose application is + * to be checked. */ +{ + return ((TkWindow *) tkwin)->mainPtr->strictMotif; +} + +/* + *-------------------------------------------------------------- + * + * OpenIM -- + * + * Tries to open an X input method, associated with the + * given display. Right now we can only deal with a bare-bones + * input style: no preedit, and no status. + * + * Results: + * Stores the input method in dispPtr->inputMethod; if there isn't + * a suitable input method, then NULL is stored in dispPtr->inputMethod. + * + * Side effects: + * An input method gets opened. + * + *-------------------------------------------------------------- + */ + +static void +OpenIM(dispPtr) + TkDisplay *dispPtr; /* Tk's structure for the display. */ +{ +#ifndef TK_USE_INPUT_METHODS + return; +#else + unsigned short i; + XIMStyles *stylePtr; + + dispPtr->inputMethod = XOpenIM(dispPtr->display, NULL, NULL, NULL); + if (dispPtr->inputMethod == NULL) { + return; + } + + if ((XGetIMValues(dispPtr->inputMethod, XNQueryInputStyle, &stylePtr, + NULL) != NULL) || (stylePtr == NULL)) { + goto error; + } + for (i = 0; i < stylePtr->count_styles; i++) { + if (stylePtr->supported_styles[i] + == (XIMPreeditNothing|XIMStatusNothing)) { + XFree(stylePtr); + return; + } + } + XFree(stylePtr); + + error: + + /* + * Should close the input method, but this causes core dumps on some + * systems (e.g. Solaris 2.3 as of 1/6/95). + * XCloseIM(dispPtr->inputMethod); + */ + dispPtr->inputMethod = NULL; + return; +#endif /* TK_USE_INPUT_METHODS */ +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetNumMainWindows -- + * + * This procedure returns the number of main windows currently + * open in this process. + * + * Results: + * The number of main windows open in this process. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +Tk_GetNumMainWindows() +{ + return numMainWindows; +} + +/* + *---------------------------------------------------------------------- + * + * DeleteWindowsExitProc -- + * + * This procedure is invoked as an exit handler. It deletes all + * of the main windows in the process. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +DeleteWindowsExitProc(clientData) + ClientData clientData; /* Not used. */ +{ + TkDisplay *displayPtr, *nextPtr; + Tcl_Interp *interp; + + while (tkMainWindowList != NULL) { + /* + * We must protect the interpreter while deleting the window, + * because of <Destroy> bindings which could destroy the interpreter + * while the window is being deleted. This would leave frames on + * the call stack pointing at deleted memory, causing core dumps. + */ + + interp = tkMainWindowList->winPtr->mainPtr->interp; + Tcl_Preserve((ClientData) interp); + Tk_DestroyWindow((Tk_Window) tkMainWindowList->winPtr); + Tcl_Release((ClientData) interp); + } + + displayPtr = tkDisplayList; + tkDisplayList = NULL; + + /* + * Iterate destroying the displays until no more displays remain. + * It is possible for displays to get recreated during exit by any + * code that calls GetScreen, so we must destroy these new displays + * as well as the old ones. + */ + + for (displayPtr = tkDisplayList; + displayPtr != NULL; + displayPtr = tkDisplayList) { + + /* + * Now iterate over the current list of open displays, and first + * set the global pointer to NULL so we will be able to notice if + * any new displays got created during deletion of the current set. + * We must also do this to ensure that Tk_IdToWindow does not find + * the old display as it is being destroyed, when it wants to see + * if it needs to dispatch a message. + */ + + for (tkDisplayList = NULL; displayPtr != NULL; displayPtr = nextPtr) { + nextPtr = displayPtr->nextPtr; + if (displayPtr->name != (char *) NULL) { + ckfree(displayPtr->name); + } + Tcl_DeleteHashTable(&(displayPtr->winTable)); + TkpCloseDisplay(displayPtr); + } + } + + numMainWindows = 0; + tkMainWindowList = NULL; + initialized = 0; + tkDisabledUid = NULL; + tkActiveUid = NULL; + tkNormalUid = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_Init -- + * + * This procedure is invoked to add Tk to an interpreter. It + * incorporates all of Tk's commands into the interpreter and + * creates the main window for a new Tk application. If the + * interpreter contains a variable "argv", this procedure + * extracts several arguments from that variable, uses them + * to configure the main window, and modifies argv to exclude + * the arguments (see the "wish" documentation for a list of + * the arguments that are extracted). + * + * Results: + * Returns a standard Tcl completion code and sets interp->result + * if there is an error. + * + * Side effects: + * Depends on various initialization scripts that get invoked. + * + *---------------------------------------------------------------------- + */ + +int +Tk_Init(interp) + Tcl_Interp *interp; /* Interpreter to initialize. */ +{ + return Initialize(interp); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_SafeInit -- + * + * This procedure is invoked to add Tk to a safe interpreter. It + * invokes the internal procedure that does the real work. + * + * Results: + * Returns a standard Tcl completion code and sets interp->result + * if there is an error. + * + * Side effects: + * Depends on various initialization scripts that are invoked. + * + *---------------------------------------------------------------------- + */ + +int +Tk_SafeInit(interp) + Tcl_Interp *interp; /* Interpreter to initialize. */ +{ + /* + * Initialize the interpreter with Tk, safely. This removes + * all the Tk commands that are unsafe. + * + * Rationale: + * + * - Toplevel and menu are unsafe because they can be used to cover + * the entire screen and to steal input from the user. + * - Continuous ringing of the bell is a nuisance. + * - Cannot allow access to the clipboard because a malicious script + * can replace the contents with the string "rm -r *" and lead to + * surprises when the contents of the clipboard are pasted. We do + * not currently hide the selection command.. Should we? + * - Cannot allow send because it can be used to cause unsafe + * interpreters to execute commands. The tk command recreates the + * send command, so that too must be hidden. + * - Focus can be used to grab the focus away from another window, + * in effect stealing user input. Cannot allow that. + * NOTE: We currently do *not* hide focus as it would make it + * impossible to provide keyboard input to Tk in a safe interpreter. + * - Grab can be used to block the user from using any other apps + * on the screen. + * - Tkwait can block the containing process forever. Use bindings, + * fileevents and split the protocol into before-the-wait and + * after-the-wait parts. More work but necessary. + * - Wm is unsafe because (if toplevels are allowed, in the future) + * it can be used to remove decorations, move windows around, cover + * the entire screen etc etc. + * + * Current risks: + * + * - No CPU time limit, no memory allocation limits, no color limits. + * + * The actual code called is the same as Tk_Init but Tcl_IsSafe() + * is checked at several places to differentiate the two initialisations. + */ + + return Initialize(interp); +} + +/* + *---------------------------------------------------------------------- + * + * Initialize -- + * + * + * Results: + * A standard Tcl result. Also leaves an error message in interp->result + * if there was an error. + * + * Side effects: + * Depends on the initialization scripts that are invoked. + * + *---------------------------------------------------------------------- + */ + +static int +Initialize(interp) + Tcl_Interp *interp; /* Interpreter to initialize. */ +{ + char *p; + int argc, code; + char **argv, *args[20]; + Tcl_DString class; + char buffer[30]; + + /* + * Start by initializing all the static variables to default acceptable + * values so that no information is leaked from a previous run of this + * code. + */ + + synchronize = 0; + name = NULL; + display = NULL; + geometry = NULL; + colormap = NULL; + use = NULL; + visual = NULL; + rest = 0; + + /* + * If there is an "argv" variable, get its value, extract out + * relevant arguments from it, and rewrite the variable without + * the arguments that we used. + */ + + p = Tcl_GetVar2(interp, "argv", (char *) NULL, TCL_GLOBAL_ONLY); + argv = NULL; + if (p != NULL) { + if (Tcl_SplitList(interp, p, &argc, &argv) != TCL_OK) { + argError: + Tcl_AddErrorInfo(interp, + "\n (processing arguments in argv variable)"); + return TCL_ERROR; + } + if (Tk_ParseArgv(interp, (Tk_Window) NULL, &argc, argv, + argTable, TK_ARGV_DONT_SKIP_FIRST_ARG|TK_ARGV_NO_DEFAULTS) + != TCL_OK) { + ckfree((char *) argv); + goto argError; + } + p = Tcl_Merge(argc, argv); + Tcl_SetVar2(interp, "argv", (char *) NULL, p, TCL_GLOBAL_ONLY); + sprintf(buffer, "%d", argc); + Tcl_SetVar2(interp, "argc", (char *) NULL, buffer, TCL_GLOBAL_ONLY); + ckfree(p); + } + + /* + * Figure out the application's name and class. + */ + + Tcl_DStringInit(&class); + if (name == NULL) { + int offset; + TkpGetAppName(interp, &class); + offset = Tcl_DStringLength(&class)+1; + Tcl_DStringSetLength(&class, offset); + Tcl_DStringAppend(&class, Tcl_DStringValue(&class), offset-1); + name = Tcl_DStringValue(&class) + offset; + } else { + Tcl_DStringAppend(&class, name, -1); + } + + p = Tcl_DStringValue(&class); + if (islower(UCHAR(*p))) { + *p = toupper(UCHAR(*p)); + } + + /* + * Create an argument list for creating the top-level window, + * using the information parsed from argv, if any. + */ + + args[0] = "toplevel"; + args[1] = "."; + args[2] = "-class"; + args[3] = Tcl_DStringValue(&class); + argc = 4; + if (display != NULL) { + args[argc] = "-screen"; + args[argc+1] = display; + argc += 2; + + /* + * If this is the first application for this process, save + * the display name in the DISPLAY environment variable so + * that it will be available to subprocesses created by us. + */ + + if (numMainWindows == 0) { + Tcl_SetVar2(interp, "env", "DISPLAY", display, TCL_GLOBAL_ONLY); + } + } + if (colormap != NULL) { + args[argc] = "-colormap"; + args[argc+1] = colormap; + argc += 2; + colormap = NULL; + } + if (use != NULL) { + args[argc] = "-use"; + args[argc+1] = use; + argc += 2; + use = NULL; + } + if (visual != NULL) { + args[argc] = "-visual"; + args[argc+1] = visual; + argc += 2; + visual = NULL; + } + args[argc] = NULL; + code = TkCreateFrame((ClientData) NULL, interp, argc, args, 1, name); + + Tcl_DStringFree(&class); + if (code != TCL_OK) { + goto done; + } + Tcl_ResetResult(interp); + if (synchronize) { + XSynchronize(Tk_Display(Tk_MainWindow(interp)), True); + } + + /* + * Set the geometry of the main window, if requested. Put the + * requested geometry into the "geometry" variable. + */ + + if (geometry != NULL) { + Tcl_SetVar(interp, "geometry", geometry, TCL_GLOBAL_ONLY); + code = Tcl_VarEval(interp, "wm geometry . ", geometry, (char *) NULL); + if (code != TCL_OK) { + goto done; + } + geometry = NULL; + } + if (Tcl_PkgRequire(interp, "Tcl", TCL_VERSION, 1) == NULL) { + code = TCL_ERROR; + goto done; + } + code = Tcl_PkgProvide(interp, "Tk", TK_VERSION); + if (code != TCL_OK) { + goto done; + } + + /* + * Invoke platform-specific initialization. + */ + + code = TkpInit(interp); + + done: + if (argv != NULL) { + ckfree((char *) argv); + } + return code; +} diff --git a/library/bgerror.tcl b/library/bgerror.tcl new file mode 100644 index 0000000..d2b1cdc --- /dev/null +++ b/library/bgerror.tcl @@ -0,0 +1,99 @@ +# bgerror.tcl -- +# +# This file contains a default version of the bgerror procedure. It +# posts a dialog box with the error message and gives the user a chance +# to see a more detailed stack trace. +# +# SCCS: @(#) bgerror.tcl 1.16 97/08/06 09:19:50 +# +# Copyright (c) 1992-1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. + + +# bgerror -- +# This is the default version of bgerror. +# It tries to execute tkerror, if that fails it posts a dialog box containing +# the error message and gives the user a chance to ask to see a stack +# trace. +# Arguments: +# err - The error message. + +proc bgerror err { + global errorInfo tcl_platform + + # save errorInfo which would be erased in the catch below otherwise. + set info $errorInfo ; + + # For backward compatibility : + # Let's try to execute "tkerror" (using catch {tkerror ...} + # instead of searching it with info procs so the application gets + # a chance to auto load it using its favorite "unknown" mecanism. + # (we do the default dialog only if we get a TCL_ERROR (=1) return + # code from the tkerror trial, other ret codes are passed back + # to our caller (tcl background error handler) so the called "tkerror" + # can still use return -code break, to skip remaining messages + # in the error queue for instance) -- dl + set ret [catch {tkerror $err} msg]; + if {$ret != 1} {return -code $ret $msg} + + # Ok the application's tkerror either failed or was not found + # we use the default dialog then : + if {$tcl_platform(platform) == "macintosh"} { + set ok Ok + } else { + set ok OK + } + set button [tk_dialog .bgerrorDialog "Error in Tcl Script" \ + "Error: $err" error 0 $ok "Skip Messages" "Stack Trace"] + if {$button == 0} { + return + } elseif {$button == 1} { + return -code break + } + + set w .bgerrorTrace + catch {destroy $w} + toplevel $w -class ErrorTrace + wm minsize $w 1 1 + wm title $w "Stack Trace for Error" + wm iconname $w "Stack Trace" + button $w.ok -text OK -command "destroy $w" -default active + if {$tcl_platform(platform) == "macintosh"} { + text $w.text -relief flat -bd 2 -highlightthickness 0 -setgrid true \ + -yscrollcommand "$w.scroll set" -width 60 -height 20 + } else { + text $w.text -relief sunken -bd 2 -yscrollcommand "$w.scroll set" \ + -setgrid true -width 60 -height 20 + } + scrollbar $w.scroll -relief sunken -command "$w.text yview" + pack $w.ok -side bottom -padx 3m -pady 2m + pack $w.scroll -side right -fill y + pack $w.text -side left -expand yes -fill both + $w.text insert 0.0 $info + $w.text mark set insert 0.0 + + bind $w <Return> "destroy $w" + bind $w.text <Return> "destroy $w; break" + + # Center the window on the screen. + + wm withdraw $w + update idletasks + set x [expr [winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \ + - [winfo vrootx [winfo parent $w]]] + set y [expr [winfo screenheight $w]/2 - [winfo reqheight $w]/2 \ + - [winfo vrooty [winfo parent $w]]] + wm geom $w +$x+$y + wm deiconify $w + + # Be sure to release any grabs that might be present on the + # screen, since they could make it impossible for the user + # to interact with the stack trace. + + if {[grab current .] != ""} { + grab release [grab current .] + } +} diff --git a/library/button.tcl b/library/button.tcl new file mode 100644 index 0000000..b017b80 --- /dev/null +++ b/library/button.tcl @@ -0,0 +1,456 @@ +# button.tcl -- +# +# This file defines the default bindings for Tk label, button, +# checkbutton, and radiobutton widgets and provides procedures +# that help in implementing those bindings. +# +# SCCS: @(#) button.tcl 1.22 96/11/14 14:49:11 +# +# Copyright (c) 1992-1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +#------------------------------------------------------------------------- +# The code below creates the default class bindings for buttons. +#------------------------------------------------------------------------- + +if {$tcl_platform(platform) == "macintosh"} { + bind Radiobutton <Enter> { + tkButtonEnter %W + } + bind Radiobutton <1> { + tkButtonDown %W + } + bind Radiobutton <ButtonRelease-1> { + tkButtonUp %W + } + bind Checkbutton <Enter> { + tkButtonEnter %W + } + bind Checkbutton <1> { + tkButtonDown %W + } + bind Checkbutton <ButtonRelease-1> { + tkButtonUp %W + } +} +if {$tcl_platform(platform) == "windows"} { + bind Checkbutton <equal> { + tkCheckRadioInvoke %W select + } + bind Checkbutton <plus> { + tkCheckRadioInvoke %W select + } + bind Checkbutton <minus> { + tkCheckRadioInvoke %W deselect + } + bind Checkbutton <1> { + tkCheckRadioDown %W + } + bind Checkbutton <ButtonRelease-1> { + tkButtonUp %W + } + bind Checkbutton <Enter> { + tkCheckRadioEnter %W + } + + bind Radiobutton <1> { + tkCheckRadioDown %W + } + bind Radiobutton <ButtonRelease-1> { + tkButtonUp %W + } + bind Radiobutton <Enter> { + tkCheckRadioEnter %W + } +} +if {$tcl_platform(platform) == "unix"} { + bind Checkbutton <Return> { + if !$tk_strictMotif { + tkCheckRadioInvoke %W + } + } + bind Radiobutton <Return> { + if !$tk_strictMotif { + tkCheckRadioInvoke %W + } + } + bind Checkbutton <1> { + tkCheckRadioInvoke %W + } + bind Radiobutton <1> { + tkCheckRadioInvoke %W + } + bind Checkbutton <Enter> { + tkButtonEnter %W + } + bind Radiobutton <Enter> { + tkButtonEnter %W + } +} + +bind Button <space> { + tkButtonInvoke %W +} +bind Checkbutton <space> { + tkCheckRadioInvoke %W +} +bind Radiobutton <space> { + tkCheckRadioInvoke %W +} + +bind Button <FocusIn> {} +bind Button <Enter> { + tkButtonEnter %W +} +bind Button <Leave> { + tkButtonLeave %W +} +bind Button <1> { + tkButtonDown %W +} +bind Button <ButtonRelease-1> { + tkButtonUp %W +} + +bind Checkbutton <FocusIn> {} +bind Checkbutton <Leave> { + tkButtonLeave %W +} + +bind Radiobutton <FocusIn> {} +bind Radiobutton <Leave> { + tkButtonLeave %W +} + +if {$tcl_platform(platform) == "windows"} { + +######################### +# Windows implementation +######################### + +# tkButtonEnter -- +# The procedure below is invoked when the mouse pointer enters a +# button widget. It records the button we're in and changes the +# state of the button to active unless the button is disabled. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonEnter w { + global tkPriv + if {[$w cget -state] != "disabled"} { + if {$tkPriv(buttonWindow) == $w} { + $w configure -state active -relief sunken + } + } + set tkPriv(window) $w +} + +# tkButtonLeave -- +# The procedure below is invoked when the mouse pointer leaves a +# button widget. It changes the state of the button back to +# inactive. If we're leaving the button window with a mouse button +# pressed (tkPriv(buttonWindow) == $w), restore the relief of the +# button too. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonLeave w { + global tkPriv + if {[$w cget -state] != "disabled"} { + $w config -state normal + } + if {$w == $tkPriv(buttonWindow)} { + $w configure -relief $tkPriv(relief) + } + set tkPriv(window) "" +} + +# tkCheckRadioEnter -- +# The procedure below is invoked when the mouse pointer enters a +# checkbutton or radiobutton widget. It records the button we're in +# and changes the state of the button to active unless the button is +# disabled. +# +# Arguments: +# w - The name of the widget. + +proc tkCheckRadioEnter w { + global tkPriv + if {[$w cget -state] != "disabled"} { + if {$tkPriv(buttonWindow) == $w} { + $w configure -state active + } + } + set tkPriv(window) $w +} + +# tkButtonDown -- +# The procedure below is invoked when the mouse button is pressed in +# a button widget. It records the fact that the mouse is in the button, +# saves the button's relief so it can be restored later, and changes +# the relief to sunken. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonDown w { + global tkPriv + set tkPriv(relief) [lindex [$w conf -relief] 4] + if {[$w cget -state] != "disabled"} { + set tkPriv(buttonWindow) $w + $w config -relief sunken -state active + } +} + +# tkCheckRadioDown -- +# The procedure below is invoked when the mouse button is pressed in +# a button widget. It records the fact that the mouse is in the button, +# saves the button's relief so it can be restored later, and changes +# the relief to sunken. +# +# Arguments: +# w - The name of the widget. + +proc tkCheckRadioDown w { + global tkPriv + set tkPriv(relief) [lindex [$w conf -relief] 4] + if {[$w cget -state] != "disabled"} { + set tkPriv(buttonWindow) $w + $w config -state active + } +} + +# tkButtonUp -- +# The procedure below is invoked when the mouse button is released +# in a button widget. It restores the button's relief and invokes +# the command as long as the mouse hasn't left the button. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonUp w { + global tkPriv + if {$w == $tkPriv(buttonWindow)} { + set tkPriv(buttonWindow) "" + if {($w == $tkPriv(window)) + && ([$w cget -state] != "disabled")} { + $w config -relief $tkPriv(relief) -state normal + uplevel #0 [list $w invoke] + } + } +} + +} + +if {$tcl_platform(platform) == "unix"} { + +##################### +# Unix implementation +##################### + +# tkButtonEnter -- +# The procedure below is invoked when the mouse pointer enters a +# button widget. It records the button we're in and changes the +# state of the button to active unless the button is disabled. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonEnter {w} { + global tkPriv + if {[$w cget -state] != "disabled"} { + $w config -state active + if {$tkPriv(buttonWindow) == $w} { + $w configure -state active -relief sunken + } + } + set tkPriv(window) $w +} + +# tkButtonLeave -- +# The procedure below is invoked when the mouse pointer leaves a +# button widget. It changes the state of the button back to +# inactive. If we're leaving the button window with a mouse button +# pressed (tkPriv(buttonWindow) == $w), restore the relief of the +# button too. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonLeave w { + global tkPriv + if {[$w cget -state] != "disabled"} { + $w config -state normal + } + if {$w == $tkPriv(buttonWindow)} { + $w configure -relief $tkPriv(relief) + } + set tkPriv(window) "" +} + +# tkButtonDown -- +# The procedure below is invoked when the mouse button is pressed in +# a button widget. It records the fact that the mouse is in the button, +# saves the button's relief so it can be restored later, and changes +# the relief to sunken. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonDown w { + global tkPriv + set tkPriv(relief) [lindex [$w config -relief] 4] + if {[$w cget -state] != "disabled"} { + set tkPriv(buttonWindow) $w + $w config -relief sunken + } +} + +# tkButtonUp -- +# The procedure below is invoked when the mouse button is released +# in a button widget. It restores the button's relief and invokes +# the command as long as the mouse hasn't left the button. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonUp w { + global tkPriv + if {$w == $tkPriv(buttonWindow)} { + set tkPriv(buttonWindow) "" + $w config -relief $tkPriv(relief) + if {($w == $tkPriv(window)) + && ([$w cget -state] != "disabled")} { + uplevel #0 [list $w invoke] + } + } +} + +} + +if {$tcl_platform(platform) == "macintosh"} { + +#################### +# Mac implementation +#################### + +# tkButtonEnter -- +# The procedure below is invoked when the mouse pointer enters a +# button widget. It records the button we're in and changes the +# state of the button to active unless the button is disabled. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonEnter {w} { + global tkPriv + if {[$w cget -state] != "disabled"} { + if {$tkPriv(buttonWindow) == $w} { + $w configure -state active + } + } + set tkPriv(window) $w +} + +# tkButtonLeave -- +# The procedure below is invoked when the mouse pointer leaves a +# button widget. It changes the state of the button back to +# inactive. If we're leaving the button window with a mouse button +# pressed (tkPriv(buttonWindow) == $w), restore the relief of the +# button too. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonLeave w { + global tkPriv + if {$w == $tkPriv(buttonWindow)} { + $w configure -state normal + } + set tkPriv(window) "" +} + +# tkButtonDown -- +# The procedure below is invoked when the mouse button is pressed in +# a button widget. It records the fact that the mouse is in the button, +# saves the button's relief so it can be restored later, and changes +# the relief to sunken. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonDown w { + global tkPriv + if {[$w cget -state] != "disabled"} { + set tkPriv(buttonWindow) $w + $w config -state active + } +} + +# tkButtonUp -- +# The procedure below is invoked when the mouse button is released +# in a button widget. It restores the button's relief and invokes +# the command as long as the mouse hasn't left the button. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonUp w { + global tkPriv + if {$w == $tkPriv(buttonWindow)} { + $w config -state normal + set tkPriv(buttonWindow) "" + if {($w == $tkPriv(window)) + && ([$w cget -state] != "disabled")} { + uplevel #0 [list $w invoke] + } + } +} + +} + +################## +# Shared routines +################## + +# tkButtonInvoke -- +# The procedure below is called when a button is invoked through +# the keyboard. It simulate a press of the button via the mouse. +# +# Arguments: +# w - The name of the widget. + +proc tkButtonInvoke w { + if {[$w cget -state] != "disabled"} { + set oldRelief [$w cget -relief] + set oldState [$w cget -state] + $w configure -state active -relief sunken + update idletasks + after 100 + $w configure -state $oldState -relief $oldRelief + uplevel #0 [list $w invoke] + } +} + +# tkCheckRadioInvoke -- +# The procedure below is invoked when the mouse button is pressed in +# a checkbutton or radiobutton widget, or when the widget is invoked +# through the keyboard. It invokes the widget if it +# isn't disabled. +# +# Arguments: +# w - The name of the widget. +# cmd - The subcommand to invoke (one of invoke, select, or deselect). + +proc tkCheckRadioInvoke {w {cmd invoke}} { + if {[$w cget -state] != "disabled"} { + uplevel #0 [list $w $cmd] + } +} + diff --git a/library/clrpick.tcl b/library/clrpick.tcl new file mode 100644 index 0000000..af5f980 --- /dev/null +++ b/library/clrpick.tcl @@ -0,0 +1,691 @@ +# clrpick.tcl -- +# +# Color selection dialog for platforms that do not support a +# standard color selection dialog. +# +# SCCS: @(#) clrpick.tcl 1.3 96/09/05 09:59:24 +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# ToDo: +# +# (1): Find out how many free colors are left in the colormap and +# don't allocate too many colors. +# (2): Implement HSV color selection. +# + +# tkColorDialog -- +# +# Create a color dialog and let the user choose a color. This function +# should not be called directly. It is called by the tk_chooseColor +# function when a native color selector widget does not exist +# +proc tkColorDialog {args} { + global tkPriv + set w .__tk__color + upvar #0 $w data + + # The lines variables track the start and end indices of the line + # elements in the colorbar canvases. + set data(lines,red,start) 0 + set data(lines,red,last) -1 + set data(lines,green,start) 0 + set data(lines,green,last) -1 + set data(lines,blue,start) 0 + set data(lines,blue,last) -1 + + # This is the actual number of lines that are drawn in each color strip. + # Note that the bars may be of any width. + # However, NUM_COLORBARS must be a number that evenly divides 256. + # Such as 256, 128, 64, etc. + set data(NUM_COLORBARS) 8 + + # BARS_WIDTH is the number of pixels wide the color bar portion of the + # canvas is. This number must be a multiple of NUM_COLORBARS + set data(BARS_WIDTH) 128 + + # PLGN_WIDTH is the number of pixels wide of the triangular selection + # polygon. This also results in the definition of the padding on the + # left and right sides which is half of PLGN_WIDTH. Make this number even. + set data(PLGN_HEIGHT) 10 + + # PLGN_HEIGHT is the height of the selection polygon and the height of the + # selection rectangle at the bottom of the color bar. No restrictions. + set data(PLGN_WIDTH) 10 + + tkColorDialog_Config $w $args + tkColorDialog_InitValues $w + + if ![winfo exists $w] { + toplevel $w -class tkColorDialog + tkColorDialog_BuildDialog $w + } + wm transient $w $data(-parent) + + + # 5. Withdraw the window, then update all the geometry information + # so we know how big it wants to be, then center the window in the + # display and de-iconify it. + + wm withdraw $w + update idletasks + set x [expr [winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \ + - [winfo vrootx [winfo parent $w]]] + set y [expr [winfo screenheight $w]/2 - [winfo reqheight $w]/2 \ + - [winfo vrooty [winfo parent $w]]] + wm geom $w +$x+$y + wm deiconify $w + wm title $w $data(-title) + + # 6. Set a grab and claim the focus too. + + set oldFocus [focus] + set oldGrab [grab current $w] + if {$oldGrab != ""} { + set grabStatus [grab status $oldGrab] + } + grab $w + focus $data(okBtn) + + # 7. Wait for the user to respond, then restore the focus and + # return the index of the selected button. Restore the focus + # before deleting the window, since otherwise the window manager + # may take the focus away so we can't redirect it. Finally, + # restore any grab that was in effect. + + tkwait variable tkPriv(selectColor) + catch {focus $oldFocus} + grab release $w + destroy $w + unset data + if {$oldGrab != ""} { + if {$grabStatus == "global"} { + grab -global $oldGrab + } else { + grab $oldGrab + } + } + return $tkPriv(selectColor) +} + +# tkColorDialog_InitValues -- +# +# Get called during initialization or when user resets NUM_COLORBARS +# +proc tkColorDialog_InitValues {w} { + upvar #0 $w data + + # IntensityIncr is the difference in color intensity between a colorbar + # and its neighbors. + set data(intensityIncr) [expr 256 / $data(NUM_COLORBARS)] + + # ColorbarWidth is the width of each colorbar + set data(colorbarWidth) \ + [expr $data(BARS_WIDTH) / $data(NUM_COLORBARS)] + + # Indent is the width of the space at the left and right side of the + # colorbar. It is always half the selector polygon width, because the + # polygon extends into the space. + set data(indent) [expr $data(PLGN_WIDTH) / 2] + + set data(colorPad) 2 + set data(selPad) [expr $data(PLGN_WIDTH) / 2] + + # + # minX is the x coordinate of the first colorbar + # + set data(minX) $data(indent) + + # + # maxX is the x coordinate of the last colorbar + # + set data(maxX) [expr $data(BARS_WIDTH) + $data(indent)-1] + + # + # canvasWidth is the width of the entire canvas, including the indents + # + set data(canvasWidth) [expr $data(BARS_WIDTH) + \ + $data(PLGN_WIDTH)] + + # Set the initial color, specified by -initialcolor, or the + # color chosen by the user the last time. + set data(selection) $data(-initialcolor) + set data(finalColor) $data(-initialcolor) + set rgb [winfo rgb . $data(selection)] + + set data(red,intensity) [expr [lindex $rgb 0]/0x100] + set data(green,intensity) [expr [lindex $rgb 1]/0x100] + set data(blue,intensity) [expr [lindex $rgb 2]/0x100] +} + +# tkColorDialog_Config -- +# +# Parses the command line arguments to tk_chooseColor +# +proc tkColorDialog_Config {w argList} { + global tkPriv + upvar #0 $w data + + # 1: the configuration specs + # + set specs { + {-initialcolor "" "" ""} + {-parent "" "" "."} + {-title "" "" "Color"} + } + + # 2: parse the arguments + # + tclParseConfigSpec $w $specs "" $argList + + if ![string compare $data(-title) ""] { + set data(-title) " " + } + if ![string compare $data(-initialcolor) ""] { + if {[info exists tkPriv(selectColor)] && \ + [string compare $tkPriv(selectColor) ""]} { + set data(-initialcolor) $tkPriv(selectColor) + } else { + set data(-initialcolor) [. cget -background] + } + } else { + if [catch {winfo rgb . $data(-initialcolor)} err] { + error $err + } + } + + if ![winfo exists $data(-parent)] { + error "bad window path name \"$data(-parent)\"" + } +} + +# tkColorDialog_BuildDialog -- +# +# Build the dialog. +# +proc tkColorDialog_BuildDialog {w} { + upvar #0 $w data + + # TopFrame contains the color strips and the color selection + # + set topFrame [frame $w.top -relief raised -bd 1] + + # StripsFrame contains the colorstrips and the individual RGB entries + set stripsFrame [frame $topFrame.colorStrip] + + foreach c { Red Green Blue } { + set color [string tolower $c] + + # each f frame contains an [R|G|B] entry and the equiv. color strip. + set f [frame $stripsFrame.$color] + + # The box frame contains the label and entry widget for an [R|G|B] + set box [frame $f.box] + + label $box.label -text $c: -width 6 -under 0 -anchor ne + entry $box.entry -textvariable [format %s $w]($color,intensity) \ + -width 4 + pack $box.label -side left -fill y -padx 2 -pady 3 + pack $box.entry -side left -anchor n -pady 0 + pack $box -side left -fill both + + set height [expr \ + [winfo reqheight $box.entry] - \ + 2*([$box.entry cget -highlightthickness] + [$box.entry cget -bd])] + + canvas $f.color -height $height\ + -width $data(BARS_WIDTH) -relief sunken -bd 2 + canvas $f.sel -height $data(PLGN_HEIGHT) \ + -width $data(canvasWidth) -highlightthickness 0 + pack $f.color -expand yes -fill both + pack $f.sel -expand yes -fill both + + pack $f -side top -fill x -padx 0 -pady 2 + + set data($color,entry) $box.entry + set data($color,col) $f.color + set data($color,sel) $f.sel + + bind $data($color,col) <Configure> \ + "tkColorDialog_DrawColorScale $w $color 1" + bind $data($color,col) <Enter> \ + "tkColorDialog_EnterColorBar $w $color" + bind $data($color,col) <Leave> \ + "tkColorDialog_LeaveColorBar $w $color" + + bind $data($color,sel) <Enter> \ + "tkColorDialog_EnterColorBar $w $color" + bind $data($color,sel) <Leave> \ + "tkColorDialog_LeaveColorBar $w $color" + + bind $box.entry <Return> "tkColorDialog_HandleRGBEntry $w" + } + + pack $stripsFrame -side left -fill both -padx 4 -pady 10 + + # The selFrame contains a frame that demonstrates the currently + # selected color + # + set selFrame [frame $topFrame.sel] + set lab [label $selFrame.lab -text "Selection:" -under 0 -anchor sw] + set ent [entry $selFrame.ent -textvariable [format %s $w](selection) \ + -width 16] + set f1 [frame $selFrame.f1 -relief sunken -bd 2] + set data(finalCanvas) [frame $f1.demo -bd 0 -width 100 -height 70] + + pack $lab $ent -side top -fill x -padx 4 -pady 2 + pack $f1 -expand yes -anchor nw -fill both -padx 6 -pady 10 + pack $data(finalCanvas) -expand yes -fill both + + bind $ent <Return> "tkColorDialog_HandleSelEntry $w" + + pack $selFrame -side left -fill none -anchor nw + pack $topFrame -side top -expand yes -fill both -anchor nw + + # the botFrame frame contains the buttons + # + set botFrame [frame $w.bot -relief raised -bd 1] + button $botFrame.ok -text OK -width 8 -under 0 \ + -command "tkColorDialog_OkCmd $w" + button $botFrame.cancel -text Cancel -width 8 -under 0 \ + -command "tkColorDialog_CancelCmd $w" + + set data(okBtn) $botFrame.ok + set data(cancelBtn) $botFrame.cancel + + pack $botFrame.ok $botFrame.cancel \ + -padx 10 -pady 10 -expand yes -side left + pack $botFrame -side bottom -fill x + + + # Accelerator bindings + + bind $w <Alt-r> "focus $data(red,entry)" + bind $w <Alt-g> "focus $data(green,entry)" + bind $w <Alt-b> "focus $data(blue,entry)" + bind $w <Alt-s> "focus $ent" + bind $w <KeyPress-Escape> "tkButtonInvoke $data(cancelBtn)" + bind $w <Alt-c> "tkButtonInvoke $data(cancelBtn)" + bind $w <Alt-o> "tkButtonInvoke $data(okBtn)" + + wm protocol $w WM_DELETE_WINDOW "tkColorDialog_CancelCmd $w" +} + +# tkColorDialog_SetRGBValue -- +# +# Sets the current selection of the dialog box +# +proc tkColorDialog_SetRGBValue {w color} { + upvar #0 $w data + + set data(red,intensity) [lindex $color 0] + set data(green,intensity) [lindex $color 1] + set data(blue,intensity) [lindex $color 2] + + tkColorDialog_RedrawColorBars $w all + + # Now compute the new x value of each colorbars pointer polygon + foreach color { red green blue } { + set x [tkColorDialog_RgbToX $w $data($color,intensity)] + tkColorDialog_MoveSelector $w $data($color,sel) $color $x 0 + } +} + +# tkColorDialog_XToRgb -- +# +# Converts a screen coordinate to intensity +# +proc tkColorDialog_XToRgb {w x} { + upvar #0 $w data + + return [expr ($x * $data(intensityIncr))/ $data(colorbarWidth)] +} + +# tkColorDialog_RgbToX +# +# Converts an intensity to screen coordinate. +# +proc tkColorDialog_RgbToX {w color} { + upvar #0 $w data + + return [expr ($color * $data(colorbarWidth)/ $data(intensityIncr))] +} + + +# tkColorDialog_DrawColorScale -- +# +# Draw color scale is called whenever the size of one of the color +# scale canvases is changed. +# +proc tkColorDialog_DrawColorScale {w c {create 0}} { + global lines + upvar #0 $w data + + # col: color bar canvas + # sel: selector canvas + set col $data($c,col) + set sel $data($c,sel) + + # First handle the case that we are creating everything for the first time. + if $create { + # First remove all the lines that already exist. + if { $data(lines,$c,last) > $data(lines,$c,start)} { + for {set i $data(lines,$c,start)} \ + {$i <= $data(lines,$c,last)} { incr i} { + $sel delete $i + } + } + # Delete the selector if it exists + if [info exists data($c,index)] { + $sel delete $data($c,index) + } + + # Draw the selection polygons + tkColorDialog_CreateSelector $w $sel $c + $sel bind $data($c,index) <ButtonPress-1> \ + "tkColorDialog_StartMove $w $sel $c %x $data(selPad) 1" + $sel bind $data($c,index) <B1-Motion> \ + "tkColorDialog_MoveSelector $w $sel $c %x $data(selPad)" + $sel bind $data($c,index) <ButtonRelease-1> \ + "tkColorDialog_ReleaseMouse $w $sel $c %x $data(selPad)" + + set height [winfo height $col] + # Create an invisible region under the colorstrip to catch mouse clicks + # that aren't on the selector. + set data($c,clickRegion) [$sel create rectangle 0 0 \ + $data(canvasWidth) $height -fill {} -outline {}] + + bind $col <ButtonPress-1> \ + "tkColorDialog_StartMove $w $sel $c %x $data(colorPad)" + bind $col <B1-Motion> \ + "tkColorDialog_MoveSelector $w $sel $c %x $data(colorPad)" + bind $col <ButtonRelease-1> \ + "tkColorDialog_ReleaseMouse $w $sel $c %x $data(colorPad)" + + $sel bind $data($c,clickRegion) <ButtonPress-1> \ + "tkColorDialog_StartMove $w $sel $c %x $data(selPad)" + $sel bind $data($c,clickRegion) <B1-Motion> \ + "tkColorDialog_MoveSelector $w $sel $c %x $data(selPad)" + $sel bind $data($c,clickRegion) <ButtonRelease-1> \ + "tkColorDialog_ReleaseMouse $w $sel $c %x $data(selPad)" + } else { + # l is the canvas index of the first colorbar. + set l $data(lines,$c,start) + } + + # Draw the color bars. + set highlightW [expr \ + [$col cget -highlightthickness] + [$col cget -bd]] + for {set i 0} { $i < $data(NUM_COLORBARS)} { incr i} { + set intensity [expr $i * $data(intensityIncr)] + set startx [expr $i * $data(colorbarWidth) + $highlightW] + if { $c == "red" } { + set color [format "#%02x%02x%02x" \ + $intensity \ + $data(green,intensity) \ + $data(blue,intensity)] + } elseif { $c == "green" } { + set color [format "#%02x%02x%02x" \ + $data(red,intensity) \ + $intensity \ + $data(blue,intensity)] + } else { + set color [format "#%02x%02x%02x" \ + $data(red,intensity) \ + $data(green,intensity) \ + $intensity] + } + + if $create { + set index [$col create rect $startx $highlightW \ + [expr $startx +$data(colorbarWidth)] \ + [expr [winfo height $col] + $highlightW]\ + -fill $color -outline $color] + } else { + $col itemconf $l -fill $color -outline $color + incr l + } + } + $sel raise $data($c,index) + + if $create { + set data(lines,$c,last) $index + set data(lines,$c,start) [expr $index - $data(NUM_COLORBARS) + 1 ] + } + + tkColorDialog_RedrawFinalColor $w +} + +# tkColorDialog_CreateSelector -- +# +# Creates and draws the selector polygon at the position +# $data($c,intensity). +# +proc tkColorDialog_CreateSelector {w sel c } { + upvar #0 $w data + set data($c,index) [$sel create polygon \ + 0 $data(PLGN_HEIGHT) \ + $data(PLGN_WIDTH) $data(PLGN_HEIGHT) \ + $data(indent) 0] + set data($c,x) [tkColorDialog_RgbToX $w $data($c,intensity)] + $sel move $data($c,index) $data($c,x) 0 +} + +# tkColorDialog_RedrawFinalColor +# +# Combines the intensities of the three colors into the final color +# +proc tkColorDialog_RedrawFinalColor {w} { + upvar #0 $w data + + set color [format "#%02x%02x%02x" $data(red,intensity) \ + $data(green,intensity) $data(blue,intensity)] + + $data(finalCanvas) conf -bg $color + set data(finalColor) $color + set data(selection) $color + set data(finalRGB) [list \ + $data(red,intensity) \ + $data(green,intensity) \ + $data(blue,intensity)] +} + +# tkColorDialog_RedrawColorBars -- +# +# Only redraws the colors on the color strips that were not manipulated. +# Params: color of colorstrip that changed. If color is not [red|green|blue] +# Then all colorstrips will be updated +# +proc tkColorDialog_RedrawColorBars {w colorChanged} { + upvar #0 $w data + + switch $colorChanged { + red { + tkColorDialog_DrawColorScale $w green + tkColorDialog_DrawColorScale $w blue + } + green { + tkColorDialog_DrawColorScale $w red + tkColorDialog_DrawColorScale $w blue + } + blue { + tkColorDialog_DrawColorScale $w red + tkColorDialog_DrawColorScale $w green + } + default { + tkColorDialog_DrawColorScale $w red + tkColorDialog_DrawColorScale $w green + tkColorDialog_DrawColorScale $w blue + } + } + tkColorDialog_RedrawFinalColor $w +} + +#---------------------------------------------------------------------- +# Event handlers +#---------------------------------------------------------------------- + +# tkColorDialog_StartMove -- +# +# Handles a mousedown button event over the selector polygon. +# Adds the bindings for moving the mouse while the button is +# pressed. Sets the binding for the button-release event. +# +# Params: sel is the selector canvas window, color is the color of the strip. +# +proc tkColorDialog_StartMove {w sel color x delta {dontMove 0}} { + upvar #0 $w data + + if !$dontMove { + tkColorDialog_MoveSelector $w $sel $color $x $delta + } +} + +# tkColorDialog_MoveSelector -- +# +# Moves the polygon selector so that its middle point has the same +# x value as the specified x. If x is outside the bounds [0,255], +# the selector is set to the closest endpoint. +# +# Params: sel is the selector canvas, c is [red|green|blue] +# x is a x-coordinate. +# +proc tkColorDialog_MoveSelector {w sel color x delta} { + upvar #0 $w data + + incr x -$delta + + if { $x < 0 } { + set x 0 + } elseif { $x >= $data(BARS_WIDTH)} { + set x [expr $data(BARS_WIDTH) - 1] + } + set diff [expr $x - $data($color,x)] + $sel move $data($color,index) $diff 0 + set data($color,x) [expr $data($color,x) + $diff] + + # Return the x value that it was actually set at + return $x +} + +# tkColorDialog_ReleaseMouse +# +# Removes mouse tracking bindings, updates the colorbars. +# +# Params: sel is the selector canvas, color is the color of the strip, +# x is the x-coord of the mouse. +# +proc tkColorDialog_ReleaseMouse {w sel color x delta} { + upvar #0 $w data + + set x [tkColorDialog_MoveSelector $w $sel $color $x $delta] + + # Determine exactly what color we are looking at. + set data($color,intensity) [tkColorDialog_XToRgb $w $x] + + tkColorDialog_RedrawColorBars $w $color +} + +# tkColorDialog_ResizeColorbars -- +# +# Completely redraws the colorbars, including resizing the +# colorstrips +# +proc tkColorDialog_ResizeColorBars {w} { + upvar #0 $w data + + if { ($data(BARS_WIDTH) < $data(NUM_COLORBARS)) || + (($data(BARS_WIDTH) % $data(NUM_COLORBARS)) != 0)} { + set data(BARS_WIDTH) $data(NUM_COLORBARS) + } + tkColorDialog_InitValues $w + foreach color { red green blue } { + $data($color,col) conf -width $data(canvasWidth) + tkColorDialog_DrawColorScale $w $color 1 + } +} + +# tkColorDialog_HandleSelEntry -- +# +# Handles the return keypress event in the "Selection:" entry +# +proc tkColorDialog_HandleSelEntry {w} { + upvar #0 $w data + + set text [string trim $data(selection)] + # Check to make sure that the color is valid + if [catch {set color [winfo rgb . $text]} ] { + set data(selection) $data(finalColor) + return + } + + set R [expr [lindex $color 0]/0x100] + set G [expr [lindex $color 1]/0x100] + set B [expr [lindex $color 2]/0x100] + + tkColorDialog_SetRGBValue $w "$R $G $B" + set data(selection) $text +} + +# tkColorDialog_HandleRGBEntry -- +# +# Handles the return keypress event in the R, G or B entry +# +proc tkColorDialog_HandleRGBEntry {w} { + upvar #0 $w data + + foreach c {red green blue} { + if [catch { + set data($c,intensity) [expr int($data($c,intensity))] + }] { + set data($c,intensity) 0 + } + + if {$data($c,intensity) < 0} { + set data($c,intensity) 0 + } + if {$data($c,intensity) > 255} { + set data($c,intensity) 255 + } + } + + tkColorDialog_SetRGBValue $w "$data(red,intensity) $data(green,intensity) \ + $data(blue,intensity)" +} + +# mouse cursor enters a color bar +# +proc tkColorDialog_EnterColorBar {w color} { + upvar #0 $w data + + $data($color,sel) itemconfig $data($color,index) -fill red +} + +# mouse leaves enters a color bar +# +proc tkColorDialog_LeaveColorBar {w color} { + upvar #0 $w data + + $data($color,sel) itemconfig $data($color,index) -fill black +} + +# user hits OK button +# +proc tkColorDialog_OkCmd {w} { + global tkPriv + upvar #0 $w data + + set tkPriv(selectColor) $data(finalColor) +} + +# user hits Cancel button +# +proc tkColorDialog_CancelCmd {w} { + global tkPriv + + set tkPriv(selectColor) "" +} + diff --git a/library/comdlg.tcl b/library/comdlg.tcl new file mode 100644 index 0000000..4f00217 --- /dev/null +++ b/library/comdlg.tcl @@ -0,0 +1,308 @@ +# comdlg.tcl -- +# +# Some functions needed for the common dialog boxes. Probably need to go +# in a different file. +# +# SCCS: @(#) comdlg.tcl 1.4 96/09/05 09:07:54 +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# tclParseConfigSpec -- +# +# Parses a list of "-option value" pairs. If all options and +# values are legal, the values are stored in +# $data($option). Otherwise an error message is returned. When +# an error happens, the data() array may have been partially +# modified, but all the modified members of the data(0 array are +# guaranteed to have valid values. This is different than +# Tk_ConfigureWidget() which does not modify the value of a +# widget record if any error occurs. +# +# Arguments: +# +# w = widget record to modify. Must be the pathname of a widget. +# +# specs = { +# {-commandlineswitch resourceName ResourceClass defaultValue verifier} +# {....} +# } +# +# flags = currently unused. +# +# argList = The list of "-option value" pairs. +# +proc tclParseConfigSpec {w specs flags argList} { + upvar #0 $w data + + # 1: Put the specs in associative arrays for faster access + # + foreach spec $specs { + if {[llength $spec] < 4} { + error "\"spec\" should contain 5 or 4 elements" + } + set cmdsw [lindex $spec 0] + set cmd($cmdsw) "" + set rname($cmdsw) [lindex $spec 1] + set rclass($cmdsw) [lindex $spec 2] + set def($cmdsw) [lindex $spec 3] + set verproc($cmdsw) [lindex $spec 4] + } + + if {[expr [llength $argList] %2] != 0} { + foreach {cmdsw value} $argList { + if ![info exists cmd($cmdsw)] { + error "unknown option \"$cmdsw\", must be [tclListValidFlags cmd]" + } + } + error "value for \"[lindex $argList end]\" missing" + } + + # 2: set the default values + # + foreach cmdsw [array names cmd] { + set data($cmdsw) $def($cmdsw) + } + + # 3: parse the argument list + # + foreach {cmdsw value} $argList { + if ![info exists cmd($cmdsw)] { + error "unknown option \"$cmdsw\", must be [tclListValidFlags cmd]" + } + set data($cmdsw) $value + } + + # Done! +} + +proc tclListValidFlags {v} { + upvar $v cmd + + set len [llength [array names cmd]] + set i 1 + set separator "" + set errormsg "" + foreach cmdsw [lsort [array names cmd]] { + append errormsg "$separator$cmdsw" + incr i + if {$i == $len} { + set separator " or " + } else { + set separator ", " + } + } + return $errormsg +} + +# This procedure is used to sort strings in a case-insenstive mode. +# +proc tclSortNoCase {str1 str2} { + return [string compare [string toupper $str1] [string toupper $str2]] +} + + +# Gives an error if the string does not contain a valid integer +# number +# +proc tclVerifyInteger {string} { + lindex {1 2 3} $string +} + + +#---------------------------------------------------------------------- +# +# Focus Group +# +# Focus groups are used to handle the user's focusing actions inside a +# toplevel. +# +# One example of using focus groups is: when the user focuses on an +# entry, the text in the entry is highlighted and the cursor is put to +# the end of the text. When the user changes focus to another widget, +# the text in the previously focused entry is validated. +# +#---------------------------------------------------------------------- + + +# tkFocusGroup_Create -- +# +# Create a focus group. All the widgets in a focus group must be +# within the same focus toplevel. Each toplevel can have only +# one focus group, which is identified by the name of the +# toplevel widget. +# +proc tkFocusGroup_Create {t} { + global tkPriv + if [string compare [winfo toplevel $t] $t] { + error "$t is not a toplevel window" + } + if ![info exists tkPriv(fg,$t)] { + set tkPriv(fg,$t) 1 + set tkPriv(focus,$t) "" + bind $t <FocusIn> "tkFocusGroup_In $t %W %d" + bind $t <FocusOut> "tkFocusGroup_Out $t %W %d" + bind $t <Destroy> "tkFocusGroup_Destroy $t %W" + } +} + +# tkFocusGroup_BindIn -- +# +# Add a widget into the "FocusIn" list of the focus group. The $cmd will be +# called when the widget is focused on by the user. +# +proc tkFocusGroup_BindIn {t w cmd} { + global tkFocusIn tkPriv + if ![info exists tkPriv(fg,$t)] { + error "focus group \"$t\" doesn't exist" + } + set tkFocusIn($t,$w) $cmd +} + + +# tkFocusGroup_BindOut -- +# +# Add a widget into the "FocusOut" list of the focus group. The +# $cmd will be called when the widget loses the focus (User +# types Tab or click on another widget). +# +proc tkFocusGroup_BindOut {t w cmd} { + global tkFocusOut tkPriv + if ![info exists tkPriv(fg,$t)] { + error "focus group \"$t\" doesn't exist" + } + set tkFocusOut($t,$w) $cmd +} + +# tkFocusGroup_Destroy -- +# +# Cleans up when members of the focus group is deleted, or when the +# toplevel itself gets deleted. +# +proc tkFocusGroup_Destroy {t w} { + global tkPriv tkFocusIn tkFocusOut + + if ![string compare $t $w] { + unset tkPriv(fg,$t) + unset tkPriv(focus,$t) + + foreach name [array names tkFocusIn $t,*] { + unset tkFocusIn($name) + } + foreach name [array names tkFocusOut $t,*] { + unset tkFocusOut($name) + } + } else { + if [info exists tkPriv(focus,$t)] { + if ![string compare $tkPriv(focus,$t) $w] { + set tkPriv(focus,$t) "" + } + } + catch { + unset tkFocusIn($t,$w) + } + catch { + unset tkFocusOut($t,$w) + } + } +} + +# tkFocusGroup_In -- +# +# Handles the <FocusIn> event. Calls the FocusIn command for the newly +# focused widget in the focus group. +# +proc tkFocusGroup_In {t w detail} { + global tkPriv tkFocusIn + + if ![info exists tkFocusIn($t,$w)] { + set tkFocusIn($t,$w) "" + return + } + if ![info exists tkPriv(focus,$t)] { + return + } + if ![string compare $tkPriv(focus,$t) $w] { + # This is already in focus + # + return + } else { + set tkPriv(focus,$t) $w + eval $tkFocusIn($t,$w) + } +} + +# tkFocusGroup_Out -- +# +# Handles the <FocusOut> event. Checks if this is really a lose +# focus event, not one generated by the mouse moving out of the +# toplevel window. Calls the FocusOut command for the widget +# who loses its focus. +# +proc tkFocusGroup_Out {t w detail} { + global tkPriv tkFocusOut + + if {[string compare $detail NotifyNonlinear] && + [string compare $detail NotifyNonlinearVirtual]} { + # This is caused by mouse moving out of the window + return + } + if ![info exists tkPriv(focus,$t)] { + return + } + if ![info exists tkFocusOut($t,$w)] { + return + } else { + eval $tkFocusOut($t,$w) + set tkPriv(focus,$t) "" + } +} + +# tkFDGetFileTypes -- +# +# Process the string given by the -filetypes option of the file +# dialogs. Similar to the C function TkGetFileFilters() on the Mac +# and Windows platform. +# +proc tkFDGetFileTypes {string} { + foreach t $string { + if {[llength $t] < 2 || [llength $t] > 3} { + error "bad file type \"$t\", should be \"typeName {extension ?extensions ...?} ?{macType ?macTypes ...?}?\"" + } + eval lappend [list fileTypes([lindex $t 0])] [lindex $t 1] + } + + set types {} + foreach t $string { + set label [lindex $t 0] + set exts {} + + if [info exists hasDoneType($label)] { + continue + } + + set name "$label (" + set sep "" + foreach ext $fileTypes($label) { + if ![string compare $ext ""] { + continue + } + regsub {^[.]} $ext "*." ext + if ![info exists hasGotExt($label,$ext)] { + append name $sep$ext + lappend exts $ext + set hasGotExt($label,$ext) 1 + } + set sep , + } + append name ")" + lappend types [list $name $exts] + + set hasDoneType($label) 1 + } + + return $types +} diff --git a/library/console.tcl b/library/console.tcl new file mode 100644 index 0000000..d2c28b2 --- /dev/null +++ b/library/console.tcl @@ -0,0 +1,481 @@ +# console.tcl -- +# +# This code constructs the console window for an application. It +# can be used by non-unix systems that do not have built-in support +# for shells. +# +# SCCS: @(#) console.tcl 1.45 97/09/17 16:52:40 +# +# Copyright (c) 1995-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# TODO: history - remember partially written command + +# tkConsoleInit -- +# This procedure constructs and configures the console windows. +# +# Arguments: +# None. + +proc tkConsoleInit {} { + global tcl_platform + + if {! [consoleinterp eval {set tcl_interactive}]} { + wm withdraw . + } + + if {"$tcl_platform(platform)" == "macintosh"} { + set mod "Cmd" + } else { + set mod "Ctrl" + } + + menu .menubar + .menubar add cascade -label File -menu .menubar.file -underline 0 + .menubar add cascade -label Edit -menu .menubar.edit -underline 0 + + menu .menubar.file -tearoff 0 + .menubar.file add command -label "Source..." -underline 0 \ + -command tkConsoleSource + .menubar.file add command -label "Hide Console" -underline 0 \ + -command {wm withdraw .} + if {"$tcl_platform(platform)" == "macintosh"} { + .menubar.file add command -label "Quit" -command exit -accel Cmd-Q + } else { + .menubar.file add command -label "Exit" -underline 1 -command exit + } + + menu .menubar.edit -tearoff 0 + .menubar.edit add command -label "Cut" -underline 2 \ + -command { event generate .console <<Cut>> } -accel "$mod+X" + .menubar.edit add command -label "Copy" -underline 0 \ + -command { event generate .console <<Copy>> } -accel "$mod+C" + .menubar.edit add command -label "Paste" -underline 1 \ + -command { event generate .console <<Paste>> } -accel "$mod+V" + + if {"$tcl_platform(platform)" == "windows"} { + .menubar.edit add command -label "Delete" -underline 0 \ + -command { event generate .console <<Clear>> } -accel "Del" + + .menubar add cascade -label Help -menu .menubar.help -underline 0 + menu .menubar.help -tearoff 0 + .menubar.help add command -label "About..." -underline 0 \ + -command tkConsoleAbout + } else { + .menubar.edit add command -label "Clear" -underline 2 \ + -command { event generate .console <<Clear>> } + } + + . conf -menu .menubar + + text .console -yscrollcommand ".sb set" -setgrid true + scrollbar .sb -command ".console yview" + pack .sb -side right -fill both + pack .console -fill both -expand 1 -side left + if {$tcl_platform(platform) == "macintosh"} { + .console configure -font {Monaco 9 normal} -highlightthickness 0 + } + + tkConsoleBind .console + + .console tag configure stderr -foreground red + .console tag configure stdin -foreground blue + + focus .console + + wm protocol . WM_DELETE_WINDOW { wm withdraw . } + wm title . "Console" + flush stdout + .console mark set output [.console index "end - 1 char"] + tkTextSetCursor .console end + .console mark set promptEnd insert + .console mark gravity promptEnd left +} + +# tkConsoleSource -- +# +# Prompts the user for a file to source in the main interpreter. +# +# Arguments: +# None. + +proc tkConsoleSource {} { + set filename [tk_getOpenFile -defaultextension .tcl -parent . \ + -title "Select a file to source" \ + -filetypes {{"Tcl Scripts" .tcl} {"All Files" *}}] + if {"$filename" != ""} { + set cmd [list source $filename] + if [catch {consoleinterp eval $cmd} result] { + tkConsoleOutput stderr "$result\n" + } + } +} + +# tkConsoleInvoke -- +# Processes the command line input. If the command is complete it +# is evaled in the main interpreter. Otherwise, the continuation +# prompt is added and more input may be added. +# +# Arguments: +# None. + +proc tkConsoleInvoke {args} { + set ranges [.console tag ranges input] + set cmd "" + if {$ranges != ""} { + set pos 0 + while {[lindex $ranges $pos] != ""} { + set start [lindex $ranges $pos] + set end [lindex $ranges [incr pos]] + append cmd [.console get $start $end] + incr pos + } + } + if {$cmd == ""} { + tkConsolePrompt + } elseif [info complete $cmd] { + .console mark set output end + .console tag delete input + set result [consoleinterp record $cmd] + if {$result != ""} { + .console insert insert "$result\n" + } + tkConsoleHistory reset + tkConsolePrompt + } else { + tkConsolePrompt partial + } + .console yview -pickplace insert +} + +# tkConsoleHistory -- +# This procedure implements command line history for the +# console. In general is evals the history command in the +# main interpreter to obtain the history. The global variable +# histNum is used to store the current location in the history. +# +# Arguments: +# cmd - Which action to take: prev, next, reset. + +set histNum 1 +proc tkConsoleHistory {cmd} { + global histNum + + switch $cmd { + prev { + incr histNum -1 + if {$histNum == 0} { + set cmd {history event [expr [history nextid] -1]} + } else { + set cmd "history event $histNum" + } + if {[catch {consoleinterp eval $cmd} cmd]} { + incr histNum + return + } + .console delete promptEnd end + .console insert promptEnd $cmd {input stdin} + } + next { + incr histNum + if {$histNum == 0} { + set cmd {history event [expr [history nextid] -1]} + } elseif {$histNum > 0} { + set cmd "" + set histNum 1 + } else { + set cmd "history event $histNum" + } + if {$cmd != ""} { + catch {consoleinterp eval $cmd} cmd + } + .console delete promptEnd end + .console insert promptEnd $cmd {input stdin} + } + reset { + set histNum 1 + } + } +} + +# tkConsolePrompt -- +# This procedure draws the prompt. If tcl_prompt1 or tcl_prompt2 +# exists in the main interpreter it will be called to generate the +# prompt. Otherwise, a hard coded default prompt is printed. +# +# Arguments: +# partial - Flag to specify which prompt to print. + +proc tkConsolePrompt {{partial normal}} { + if {$partial == "normal"} { + set temp [.console index "end - 1 char"] + .console mark set output end + if [consoleinterp eval "info exists tcl_prompt1"] { + consoleinterp eval "eval \[set tcl_prompt1\]" + } else { + puts -nonewline "% " + } + } else { + set temp [.console index output] + .console mark set output end + if [consoleinterp eval "info exists tcl_prompt2"] { + consoleinterp eval "eval \[set tcl_prompt2\]" + } else { + puts -nonewline "> " + } + } + flush stdout + .console mark set output $temp + tkTextSetCursor .console end + .console mark set promptEnd insert + .console mark gravity promptEnd left +} + +# tkConsoleBind -- +# This procedure first ensures that the default bindings for the Text +# class have been defined. Then certain bindings are overridden for +# the class. +# +# Arguments: +# None. + +proc tkConsoleBind {win} { + bindtags $win "$win Text . all" + + # Ignore all Alt, Meta, and Control keypresses unless explicitly bound. + # Otherwise, if a widget binding for one of these is defined, the + # <KeyPress> class binding will also fire and insert the character, + # which is wrong. Ditto for <Escape>. + + bind $win <Alt-KeyPress> {# nothing } + bind $win <Meta-KeyPress> {# nothing} + bind $win <Control-KeyPress> {# nothing} + bind $win <Escape> {# nothing} + bind $win <KP_Enter> {# nothing} + + bind $win <Tab> { + tkConsoleInsert %W \t + focus %W + break + } + bind $win <Return> { + %W mark set insert {end - 1c} + tkConsoleInsert %W "\n" + tkConsoleInvoke + break + } + bind $win <Delete> { + if {[%W tag nextrange sel 1.0 end] != ""} { + %W tag remove sel sel.first promptEnd + } else { + if [%W compare insert < promptEnd] { + break + } + } + } + bind $win <BackSpace> { + if {[%W tag nextrange sel 1.0 end] != ""} { + %W tag remove sel sel.first promptEnd + } else { + if [%W compare insert <= promptEnd] { + break + } + } + } + foreach left {Control-a Home} { + bind $win <$left> { + if [%W compare insert < promptEnd] { + tkTextSetCursor %W {insert linestart} + } else { + tkTextSetCursor %W promptEnd + } + break + } + } + foreach right {Control-e End} { + bind $win <$right> { + tkTextSetCursor %W {insert lineend} + break + } + } + bind $win <Control-d> { + if [%W compare insert < promptEnd] { + break + } + } + bind $win <Control-k> { + if [%W compare insert < promptEnd] { + %W mark set insert promptEnd + } + } + bind $win <Control-t> { + if [%W compare insert < promptEnd] { + break + } + } + bind $win <Meta-d> { + if [%W compare insert < promptEnd] { + break + } + } + bind $win <Meta-BackSpace> { + if [%W compare insert <= promptEnd] { + break + } + } + bind $win <Control-h> { + if [%W compare insert <= promptEnd] { + break + } + } + foreach prev {Control-p Up} { + bind $win <$prev> { + tkConsoleHistory prev + break + } + } + foreach prev {Control-n Down} { + bind $win <$prev> { + tkConsoleHistory next + break + } + } + bind $win <Insert> { + catch {tkConsoleInsert %W [selection get -displayof %W]} + break + } + bind $win <KeyPress> { + tkConsoleInsert %W %A + break + } + foreach left {Control-b Left} { + bind $win <$left> { + if [%W compare insert == promptEnd] { + break + } + tkTextSetCursor %W insert-1c + break + } + } + foreach right {Control-f Right} { + bind $win <$right> { + tkTextSetCursor %W insert+1c + break + } + } + bind $win <F9> { + eval destroy [winfo child .] + if {$tcl_platform(platform) == "macintosh"} { + source -rsrc Console + } else { + source [file join $tk_library console.tcl] + } + } + bind $win <<Cut>> { + # Same as the copy event + if {![catch {set data [%W get sel.first sel.last]}]} { + clipboard clear -displayof %W + clipboard append -displayof %W $data + } + break + } + bind $win <<Copy>> { + if {![catch {set data [%W get sel.first sel.last]}]} { + clipboard clear -displayof %W + clipboard append -displayof %W $data + } + break + } + bind $win <<Paste>> { + catch { + set clip [selection get -displayof %W -selection CLIPBOARD] + set list [split $clip \n\r] + tkConsoleInsert %W [lindex $list 0] + foreach x [lrange $list 1 end] { + %W mark set insert {end - 1c} + tkConsoleInsert %W "\n" + tkConsoleInvoke + tkConsoleInsert %W $x + } + } + break + } +} + +# tkConsoleInsert -- +# Insert a string into a text at the point of the insertion cursor. +# If there is a selection in the text, and it covers the point of the +# insertion cursor, then delete the selection before inserting. Insertion +# is restricted to the prompt area. +# +# Arguments: +# w - The text window in which to insert the string +# s - The string to insert (usually just a single character) + +proc tkConsoleInsert {w s} { + if {$s == ""} { + return + } + catch { + if {[$w compare sel.first <= insert] + && [$w compare sel.last >= insert]} { + $w tag remove sel sel.first promptEnd + $w delete sel.first sel.last + } + } + if {[$w compare insert < promptEnd]} { + $w mark set insert end + } + $w insert insert $s {input stdin} + $w see insert +} + +# tkConsoleOutput -- +# +# This routine is called directly by ConsolePutsCmd to cause a string +# to be displayed in the console. +# +# Arguments: +# dest - The output tag to be used: either "stderr" or "stdout". +# string - The string to be displayed. + +proc tkConsoleOutput {dest string} { + .console insert output $string $dest + .console see insert +} + +# tkConsoleExit -- +# +# This routine is called by ConsoleEventProc when the main window of +# the application is destroyed. Don't call exit - that probably already +# happened. Just delete our window. +# +# Arguments: +# None. + +proc tkConsoleExit {} { + destroy . +} + +# tkConsoleAbout -- +# +# This routine displays an About box to show Tcl/Tk version info. +# +# Arguments: +# None. + +proc tkConsoleAbout {} { + global tk_patchLevel + tk_messageBox -type ok -message "Tcl for Windows +Copyright \251 1996 Sun Microsystems, Inc. + +Tcl [info patchlevel] +Tk $tk_patchLevel" +} + +# now initialize the console + +tkConsoleInit diff --git a/library/demos/README b/library/demos/README new file mode 100644 index 0000000..c71f977 --- /dev/null +++ b/library/demos/README @@ -0,0 +1,46 @@ +This directory contains a collection of programs to demonstrate +the features of the Tk toolkit. The programs are all scripts for +"wish", a windowing shell. If wish has been installed in /usr/local +then you can invoke any of the programs in this directory just +by typing its file name to your command shell. Otherwise invoke +wish with the file as its first argument, e.g., "wish hello". +The rest of this file contains a brief description of each program. +Files with names ending in ".tcl" are procedure packages used by one +or more of the demo programs; they can't be used as programs by +themselves so they aren't described below. + +hello - Creates a single button; if you click on it, a message + is typed and the application terminates. + +widget - Contains a collection of demonstrations of the widgets + currently available in the Tk library. Most of the .tcl + files are scripts for individual demos available through + the "widget" program. + +ixset - A simple Tk-based wrapper for the "xset" program, which + allows you to interactively query and set various X options + such as mouse acceleration and bell volume. Thanks to + Pierre David for contributing this example. + +rolodex - A mock-up of a simple rolodex application. It has much of + the user interface for such an application but no back-end + database. This program was written in response to Tom + LaStrange's toolkit benchmark challenge. + +tcolor - A color editor. Allows you to edit colors in several + different ways, and will also perform automatic updates + using "send". + +rmt - Allows you to "hook-up" remotely to any Tk application + on the display. Select an application with the menu, + then just type commands: they'll go to that application. + +timer - Displays a seconds timer with start and stop buttons. + Control-c and control-q cause it to exit. + +browse - A simple directory browser. Invoke it with and argument + giving the name of the directory you'd like to browse. + Double-click on files or subdirectories to browse them. + Control-c and control-q cause the program to exit. + +sccs id = SCCS: @(#) README 1.3 96/02/16 10:49:14 diff --git a/library/demos/arrow.tcl b/library/demos/arrow.tcl new file mode 100644 index 0000000..126c179 --- /dev/null +++ b/library/demos/arrow.tcl @@ -0,0 +1,238 @@ +# arrow.tcl -- +# +# This demonstration script creates a canvas widget that displays a +# large line with an arrowhead whose shape can be edited interactively. +# +# SCCS: @(#) arrow.tcl 1.8 97/03/02 16:18:20 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +# arrowSetup -- +# This procedure regenerates all the text and graphics in the canvas +# window. It's called when the canvas is initially created, and also +# whenever any of the parameters of the arrow head are changed +# interactively. +# +# Arguments: +# c - Name of the canvas widget. + +proc arrowSetup c { + upvar #0 demo_arrowInfo v + + # Remember the current box, if there is one. + + set tags [$c gettags current] + if {$tags != ""} { + set cur [lindex $tags [lsearch -glob $tags box?]] + } else { + set cur "" + } + + # Create the arrow and outline. + + $c delete all + eval "$c create line $v(x1) $v(y) $v(x2) $v(y) -width [expr 10*$v(width)] \ + -arrowshape {[expr 10*$v(a)] [expr 10*$v(b)] [expr 10*$v(c)]} \ + -arrow last $v(bigLineStyle)" + set xtip [expr $v(x2)-10*$v(b)] + set deltaY [expr 10*$v(c)+5*$v(width)] + $c create line $v(x2) $v(y) $xtip [expr $v(y)+$deltaY] \ + [expr $v(x2)-10*$v(a)] $v(y) $xtip [expr $v(y)-$deltaY] \ + $v(x2) $v(y) -width 2 -capstyle round -joinstyle round + + # Create the boxes for reshaping the line and arrowhead. + + eval "$c create rect [expr $v(x2)-10*$v(a)-5] [expr $v(y)-5] \ + [expr $v(x2)-10*$v(a)+5] [expr $v(y)+5] $v(boxStyle) \ + -tags {box1 box}" + eval "$c create rect [expr $xtip-5] [expr $v(y)-$deltaY-5] \ + [expr $xtip+5] [expr $v(y)-$deltaY+5] $v(boxStyle) \ + -tags {box2 box}" + eval "$c create rect [expr $v(x1)-5] [expr $v(y)-5*$v(width)-5] \ + [expr $v(x1)+5] [expr $v(y)-5*$v(width)+5] $v(boxStyle) \ + -tags {box3 box}" + if {$cur != ""} { + eval $c itemconfigure $cur $v(activeStyle) + } + + # Create three arrows in actual size with the same parameters + + $c create line [expr $v(x2)+50] 0 [expr $v(x2)+50] 1000 \ + -width 2 + set tmp [expr $v(x2)+100] + $c create line $tmp [expr $v(y)-125] $tmp [expr $v(y)-75] \ + -width $v(width) \ + -arrow both -arrowshape "$v(a) $v(b) $v(c)" + $c create line [expr $tmp-25] $v(y) [expr $tmp+25] $v(y) \ + -width $v(width) \ + -arrow both -arrowshape "$v(a) $v(b) $v(c)" + $c create line [expr $tmp-25] [expr $v(y)+75] [expr $tmp+25] \ + [expr $v(y)+125] -width $v(width) \ + -arrow both -arrowshape "$v(a) $v(b) $v(c)" + + # Create a bunch of other arrows and text items showing the + # current dimensions. + + set tmp [expr $v(x2)+10] + $c create line $tmp [expr $v(y)-5*$v(width)] \ + $tmp [expr $v(y)-$deltaY] \ + -arrow both -arrowshape $v(smallTips) + $c create text [expr $v(x2)+15] [expr $v(y)-$deltaY+5*$v(c)] \ + -text $v(c) -anchor w + set tmp [expr $v(x1)-10] + $c create line $tmp [expr $v(y)-5*$v(width)] \ + $tmp [expr $v(y)+5*$v(width)] \ + -arrow both -arrowshape $v(smallTips) + $c create text [expr $v(x1)-15] $v(y) -text $v(width) -anchor e + set tmp [expr $v(y)+5*$v(width)+10*$v(c)+10] + $c create line [expr $v(x2)-10*$v(a)] $tmp $v(x2) $tmp \ + -arrow both -arrowshape $v(smallTips) + $c create text [expr $v(x2)-5*$v(a)] [expr $tmp+5] \ + -text $v(a) -anchor n + set tmp [expr $tmp+25] + $c create line [expr $v(x2)-10*$v(b)] $tmp $v(x2) $tmp \ + -arrow both -arrowshape $v(smallTips) + $c create text [expr $v(x2)-5*$v(b)] [expr $tmp+5] \ + -text $v(b) -anchor n + + $c create text $v(x1) 310 -text "-width $v(width)" \ + -anchor w -font {Helvetica 18} + $c create text $v(x1) 330 -text "-arrowshape {$v(a) $v(b) $v(c)}" \ + -anchor w -font {Helvetica 18} + + incr v(count) +} + +set w .arrow +global tk_library +catch {destroy $w} +toplevel $w +wm title $w "Arrowhead Editor Demonstration" +wm iconname $w "arrow" +positionWindow $w +set c $w.c + +label $w.msg -font $font -wraplength 5i -justify left -text "This widget allows you to experiment with different widths and arrowhead shapes for lines in canvases. To change the line width or the shape of the arrowhead, drag any of the three boxes attached to the oversized arrow. The arrows on the right give examples at normal scale. The text at the bottom shows the configuration options as you'd enter them for a canvas line item." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +canvas $c -width 500 -height 350 -relief sunken -borderwidth 2 +pack $c -expand yes -fill both + +set demo_arrowInfo(a) 8 +set demo_arrowInfo(b) 10 +set demo_arrowInfo(c) 3 +set demo_arrowInfo(width) 2 +set demo_arrowInfo(motionProc) arrowMoveNull +set demo_arrowInfo(x1) 40 +set demo_arrowInfo(x2) 350 +set demo_arrowInfo(y) 150 +set demo_arrowInfo(smallTips) {5 5 2} +set demo_arrowInfo(count) 0 +if {[winfo depth $c] > 1} { + set demo_arrowInfo(bigLineStyle) "-fill SkyBlue1" + set demo_arrowInfo(boxStyle) "-fill {} -outline black -width 1" + set demo_arrowInfo(activeStyle) "-fill red -outline black -width 1" +} else { + set demo_arrowInfo(bigLineStyle) "-fill black \ + -stipple @[file join $tk_library demos images grey.25]" + set demo_arrowInfo(boxStyle) "-fill {} -outline black -width 1" + set demo_arrowInfo(activeStyle) "-fill black -outline black -width 1" +} +arrowSetup $c +$c bind box <Enter> "$c itemconfigure current $demo_arrowInfo(activeStyle)" +$c bind box <Leave> "$c itemconfigure current $demo_arrowInfo(boxStyle)" +$c bind box <B1-Enter> " " +$c bind box <B1-Leave> " " +$c bind box1 <1> {set demo_arrowInfo(motionProc) arrowMove1} +$c bind box2 <1> {set demo_arrowInfo(motionProc) arrowMove2} +$c bind box3 <1> {set demo_arrowInfo(motionProc) arrowMove3} +$c bind box <B1-Motion> "\$demo_arrowInfo(motionProc) $c %x %y" +bind $c <Any-ButtonRelease-1> "arrowSetup $c" + +# arrowMove1 -- +# This procedure is called for each mouse motion event on box1 (the +# one at the vertex of the arrow). It updates the controlling parameters +# for the line and arrowhead. +# +# Arguments: +# c - The name of the canvas window. +# x, y - The coordinates of the mouse. + +proc arrowMove1 {c x y} { + upvar #0 demo_arrowInfo v + set newA [expr ($v(x2)+5-round([$c canvasx $x]))/10] + if {$newA < 0} { + set newA 0 + } + if {$newA > 25} { + set newA 25 + } + if {$newA != $v(a)} { + $c move box1 [expr 10*($v(a)-$newA)] 0 + set v(a) $newA + } +} + +# arrowMove2 -- +# This procedure is called for each mouse motion event on box2 (the +# one at the trailing tip of the arrowhead). It updates the controlling +# parameters for the line and arrowhead. +# +# Arguments: +# c - The name of the canvas window. +# x, y - The coordinates of the mouse. + +proc arrowMove2 {c x y} { + upvar #0 demo_arrowInfo v + set newB [expr ($v(x2)+5-round([$c canvasx $x]))/10] + if {$newB < 0} { + set newB 0 + } + if {$newB > 25} { + set newB 25 + } + set newC [expr ($v(y)+5-round([$c canvasy $y])-5*$v(width))/10] + if {$newC < 0} { + set newC 0 + } + if {$newC > 20} { + set newC 20 + } + if {($newB != $v(b)) || ($newC != $v(c))} { + $c move box2 [expr 10*($v(b)-$newB)] [expr 10*($v(c)-$newC)] + set v(b) $newB + set v(c) $newC + } +} + +# arrowMove3 -- +# This procedure is called for each mouse motion event on box3 (the +# one that controls the thickness of the line). It updates the +# controlling parameters for the line and arrowhead. +# +# Arguments: +# c - The name of the canvas window. +# x, y - The coordinates of the mouse. + +proc arrowMove3 {c x y} { + upvar #0 demo_arrowInfo v + set newWidth [expr ($v(y)+2-round([$c canvasy $y]))/5] + if {$newWidth < 0} { + set newWidth 0 + } + if {$newWidth > 20} { + set newWidth 20 + } + if {$newWidth != $v(width)} { + $c move box3 0 [expr 5*($v(width)-$newWidth)] + set v(width) $newWidth + } +} diff --git a/library/demos/bind.tcl b/library/demos/bind.tcl new file mode 100644 index 0000000..175be10 --- /dev/null +++ b/library/demos/bind.tcl @@ -0,0 +1,79 @@ +# bind.tcl -- +# +# This demonstration script creates a text widget with bindings set +# up for hypertext-like effects. +# +# SCCS: @(#) bind.tcl 1.6 97/03/02 16:19:01 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .bind +catch {destroy $w} +toplevel $w +wm title $w "Text Demonstration - Tag Bindings" +wm iconname $w "bind" +positionWindow $w + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +text $w.text -yscrollcommand "$w.scroll set" -setgrid true \ + -width 60 -height 24 -font $font -wrap word +scrollbar $w.scroll -command "$w.text yview" +pack $w.scroll -side right -fill y +pack $w.text -expand yes -fill both + +# Set up display styles. + +if {[winfo depth $w] > 1} { + set bold "-background #43ce80 -relief raised -borderwidth 1" + set normal "-background {} -relief flat" +} else { + set bold "-foreground white -background black" + set normal "-foreground {} -background {}" +} + +# Add text to widget. + +$w.text insert 0.0 {\ +The same tag mechanism that controls display styles in text widgets can also be used to associate Tcl commands with regions of text, so that mouse or keyboard actions on the text cause particular Tcl commands to be invoked. For example, in the text below the descriptions of the canvas demonstrations have been tagged. When you move the mouse over a demo description the description lights up, and when you press button 1 over a description then that particular demonstration is invoked. + +} +$w.text insert end \ +{1. Samples of all the different types of items that can be created in canvas widgets.} d1 +$w.text insert end \n\n +$w.text insert end \ +{2. A simple two-dimensional plot that allows you to adjust the positions of the data points.} d2 +$w.text insert end \n\n +$w.text insert end \ +{3. Anchoring and justification modes for text items.} d3 +$w.text insert end \n\n +$w.text insert end \ +{4. An editor for arrow-head shapes for line items.} d4 +$w.text insert end \n\n +$w.text insert end \ +{5. A ruler with facilities for editing tab stops.} d5 +$w.text insert end \n\n +$w.text insert end \ +{6. A grid that demonstrates how canvases can be scrolled.} d6 + +# Create bindings for tags. + +foreach tag {d1 d2 d3 d4 d5 d6} { + $w.text tag bind $tag <Any-Enter> "$w.text tag configure $tag $bold" + $w.text tag bind $tag <Any-Leave> "$w.text tag configure $tag $normal" +} +$w.text tag bind d1 <1> {source [file join $tk_library demos items.tcl]} +$w.text tag bind d2 <1> {source [file join $tk_library demos plot.tcl]} +$w.text tag bind d3 <1> {source [file join $tk_library demos ctext.tcl]} +$w.text tag bind d4 <1> {source [file join $tk_library demos arrow.tcl]} +$w.text tag bind d5 <1> {source [file join $tk_library demos ruler.tcl]} +$w.text tag bind d6 <1> {source [file join $tk_library demos cscroll.tcl]} + +$w.text mark set insert 0.0 +$w.text configure -state disabled diff --git a/library/demos/bitmap.tcl b/library/demos/bitmap.tcl new file mode 100644 index 0000000..55f9e73 --- /dev/null +++ b/library/demos/bitmap.tcl @@ -0,0 +1,55 @@ +# bitmap.tcl -- +# +# This demonstration script creates a toplevel window that displays +# all of Tk's built-in bitmaps. +# +# SCCS: @(#) bitmap.tcl 1.6 97/03/02 16:19:20 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +# bitmapRow -- +# Create a row of bitmap items in a window. +# +# Arguments: +# w - The window that is to contain the row. +# args - The names of one or more bitmaps, which will be displayed +# in a new row across the bottom of w along with their +# names. + +proc bitmapRow {w args} { + frame $w + pack $w -side top -fill both + set i 0 + foreach bitmap $args { + frame $w.$i + pack $w.$i -side left -fill both -pady .25c -padx .25c + label $w.$i.bitmap -bitmap $bitmap + label $w.$i.label -text $bitmap -width 9 + pack $w.$i.label $w.$i.bitmap -side bottom + incr i + } +} + +set w .bitmap +global tk_library +catch {destroy $w} +toplevel $w +wm title $w "Bitmap Demonstration" +wm iconname $w "bitmap" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "This window displays all of Tk's built-in bitmaps, along with the names you can use for them in Tcl scripts." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.frame +bitmapRow $w.frame.0 error gray12 gray25 gray50 gray75 +bitmapRow $w.frame.1 hourglass info question questhead warning +pack $w.frame -side top -expand yes -fill both diff --git a/library/demos/browse b/library/demos/browse new file mode 100644 index 0000000..46f6532 --- /dev/null +++ b/library/demos/browse @@ -0,0 +1,56 @@ +#!/bin/sh +# the next line restarts using wish \ +exec wish "$0" "$@" + +# browse -- +# This script generates a directory browser, which lists the working +# directory and allows you to open files or subdirectories by +# double-clicking. +# +# SCCS: @(#) browse 1.8 96/02/16 10:49:18 + +# Create a scrollbar on the right side of the main window and a listbox +# on the left side. + +scrollbar .scroll -command ".list yview" +pack .scroll -side right -fill y +listbox .list -yscroll ".scroll set" -relief sunken -width 20 -height 20 \ + -setgrid yes +pack .list -side left -fill both -expand yes +wm minsize . 1 1 + +# The procedure below is invoked to open a browser on a given file; if the +# file is a directory then another instance of this program is invoked; if +# the file is a regular file then the Mx editor is invoked to display +# the file. + +proc browse {dir file} { + global env + if {[string compare $dir "."] != 0} {set file $dir/$file} + if [file isdirectory $file] { + exec browse $file & + } else { + if [file isfile $file] { + if [info exists env(EDITOR)] { + eval exec $env(EDITOR) $file & + } else { + exec xedit $file & + } + } else { + puts stdout "\"$file\" isn't a directory or regular file" + } + } +} + +# Fill the listbox with a list of all the files in the directory (run +# the "ls" command to get that information). + +if $argc>0 {set dir [lindex $argv 0]} else {set dir "."} +foreach i [exec ls -a $dir] { + .list insert end $i +} + +# Set up bindings for the browser. + +bind all <Control-c> {destroy .} +bind .list <Double-Button-1> {foreach i [selection get] {browse $dir $i}} diff --git a/library/demos/button.tcl b/library/demos/button.tcl new file mode 100644 index 0000000..8569b1d --- /dev/null +++ b/library/demos/button.tcl @@ -0,0 +1,36 @@ +# button.tcl -- +# +# This demonstration script creates a toplevel window containing +# several button widgets. +# +# SCCS: @(#) button.tcl 1.5 97/03/02 16:19:39 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .button +catch {destroy $w} +toplevel $w +wm title $w "Button Demonstration" +wm iconname $w "button" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "If you click on any of the four buttons below, the background of the button area will change to the color indicated in the button. You can press Tab to move among the buttons, then press Space to invoke the current button." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +button $w.b1 -text "Peach Puff" -width 10 \ + -command "$w config -bg PeachPuff1; $w.buttons config -bg PeachPuff1" +button $w.b2 -text "Light Blue" -width 10 \ + -command "$w config -bg LightBlue1; $w.buttons config -bg LightBlue1" +button $w.b3 -text "Sea Green" -width 10 \ + -command "$w config -bg SeaGreen2; $w.buttons config -bg SeaGreen2" +button $w.b4 -text "Yellow" -width 10 \ + -command "$w config -bg Yellow1; $w.buttons config -bg Yellow1" +pack $w.b1 $w.b2 $w.b3 $w.b4 -side top -expand yes -pady 2 diff --git a/library/demos/check.tcl b/library/demos/check.tcl new file mode 100644 index 0000000..46e21b3 --- /dev/null +++ b/library/demos/check.tcl @@ -0,0 +1,33 @@ +# check.tcl -- +# +# This demonstration script creates a toplevel window containing +# several checkbuttons. +# +# SCCS: @(#) check.tcl 1.4 97/03/02 16:19:57 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .check +catch {destroy $w} +toplevel $w +wm title $w "Checkbutton Demonstration" +wm iconname $w "check" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "Three checkbuttons are displayed below. If you click on a button, it will toggle the button's selection state and set a Tcl variable to a value indicating the state of the checkbutton. Click the \"See Variables\" button to see the current values of the variables." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +button $w.buttons.vars -text "See Variables" \ + -command "showVars $w.dialog wipers brakes sober" +pack $w.buttons.dismiss $w.buttons.code $w.buttons.vars -side left -expand 1 + +checkbutton $w.b1 -text "Wipers OK" -variable wipers -relief flat +checkbutton $w.b2 -text "Brakes OK" -variable brakes -relief flat +checkbutton $w.b3 -text "Driver Sober" -variable sober -relief flat +pack $w.b1 $w.b2 $w.b3 -side top -pady 2 -anchor w diff --git a/library/demos/clrpick.tcl b/library/demos/clrpick.tcl new file mode 100644 index 0000000..757e0b8 --- /dev/null +++ b/library/demos/clrpick.tcl @@ -0,0 +1,56 @@ +# clrpick.tcl -- +# +# This demonstration script prompts the user to select a color. +# +# SCCS: @(#) clrpick.tcl 1.3 97/03/02 16:20:12 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .clrpick +catch {destroy $w} +toplevel $w +wm title $w "Color Selection Dialog" +wm iconname $w "colors" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "Press the buttons below to choose the foreground and background colors for the widgets in this window." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +button $w.back -text "Set background color ..." \ + -command \ + "setColor $w $w.back background {-background -highlightbackground}" +button $w.fore -text "Set foreground color ..." \ + -command \ + "setColor $w $w.back foreground -foreground" + +pack $w.back $w.fore -side top -anchor c -pady 2m + +proc setColor {w button name options} { + grab $w + set initialColor [$button cget -$name] + set color [tk_chooseColor -title "Choose a $name color" -parent $w \ + -initialcolor $initialColor] + if [string compare $color ""] { + setColor_helper $w $options $color + } + grab release $w +} + +proc setColor_helper {w options color} { + foreach option $options { + catch { + $w config $option $color + } + } + foreach child [winfo children $w] { + setColor_helper $child $options $color + } +} diff --git a/library/demos/colors.tcl b/library/demos/colors.tcl new file mode 100644 index 0000000..e95c21c --- /dev/null +++ b/library/demos/colors.tcl @@ -0,0 +1,101 @@ +# colors.tcl -- +# +# This demonstration script creates a listbox widget that displays +# many of the colors from the X color database. You can click on +# a color to change the application's palette. +# +# SCCS: @(#) colors.tcl 1.4 97/03/02 16:20:29 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .colors +catch {destroy $w} +toplevel $w +wm title $w "Listbox Demonstration (colors)" +wm iconname $w "Listbox" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "A listbox containing several color names is displayed below, along with a scrollbar. You can scan the list either using the scrollbar or by dragging in the listbox window with button 2 pressed. If you double-click button 1 on a color, then the application's color palette will be set to match that color" +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.frame -borderwidth 10 +pack $w.frame -side top -expand yes -fill y + +scrollbar $w.frame.scroll -command "$w.frame.list yview" +listbox $w.frame.list -yscroll "$w.frame.scroll set" \ + -width 20 -height 16 -setgrid 1 +pack $w.frame.list $w.frame.scroll -side left -fill y -expand 1 + +bind $w.frame.list <Double-1> { + tk_setPalette [selection get] +} +$w.frame.list insert 0 gray60 gray70 gray80 gray85 gray90 gray95 \ + snow1 snow2 snow3 snow4 seashell1 seashell2 \ + seashell3 seashell4 AntiqueWhite1 AntiqueWhite2 AntiqueWhite3 \ + AntiqueWhite4 bisque1 bisque2 bisque3 bisque4 PeachPuff1 \ + PeachPuff2 PeachPuff3 PeachPuff4 NavajoWhite1 NavajoWhite2 \ + NavajoWhite3 NavajoWhite4 LemonChiffon1 LemonChiffon2 \ + LemonChiffon3 LemonChiffon4 cornsilk1 cornsilk2 cornsilk3 \ + cornsilk4 ivory1 ivory2 ivory3 ivory4 honeydew1 honeydew2 \ + honeydew3 honeydew4 LavenderBlush1 LavenderBlush2 \ + LavenderBlush3 LavenderBlush4 MistyRose1 MistyRose2 \ + MistyRose3 MistyRose4 azure1 azure2 azure3 azure4 \ + SlateBlue1 SlateBlue2 SlateBlue3 SlateBlue4 RoyalBlue1 \ + RoyalBlue2 RoyalBlue3 RoyalBlue4 blue1 blue2 blue3 blue4 \ + DodgerBlue1 DodgerBlue2 DodgerBlue3 DodgerBlue4 SteelBlue1 \ + SteelBlue2 SteelBlue3 SteelBlue4 DeepSkyBlue1 DeepSkyBlue2 \ + DeepSkyBlue3 DeepSkyBlue4 SkyBlue1 SkyBlue2 SkyBlue3 \ + SkyBlue4 LightSkyBlue1 LightSkyBlue2 LightSkyBlue3 \ + LightSkyBlue4 SlateGray1 SlateGray2 SlateGray3 SlateGray4 \ + LightSteelBlue1 LightSteelBlue2 LightSteelBlue3 \ + LightSteelBlue4 LightBlue1 LightBlue2 LightBlue3 \ + LightBlue4 LightCyan1 LightCyan2 LightCyan3 LightCyan4 \ + PaleTurquoise1 PaleTurquoise2 PaleTurquoise3 PaleTurquoise4 \ + CadetBlue1 CadetBlue2 CadetBlue3 CadetBlue4 turquoise1 \ + turquoise2 turquoise3 turquoise4 cyan1 cyan2 cyan3 cyan4 \ + DarkSlateGray1 DarkSlateGray2 DarkSlateGray3 \ + DarkSlateGray4 aquamarine1 aquamarine2 aquamarine3 \ + aquamarine4 DarkSeaGreen1 DarkSeaGreen2 DarkSeaGreen3 \ + DarkSeaGreen4 SeaGreen1 SeaGreen2 SeaGreen3 SeaGreen4 \ + PaleGreen1 PaleGreen2 PaleGreen3 PaleGreen4 SpringGreen1 \ + SpringGreen2 SpringGreen3 SpringGreen4 green1 green2 \ + green3 green4 chartreuse1 chartreuse2 chartreuse3 \ + chartreuse4 OliveDrab1 OliveDrab2 OliveDrab3 OliveDrab4 \ + DarkOliveGreen1 DarkOliveGreen2 DarkOliveGreen3 \ + DarkOliveGreen4 khaki1 khaki2 khaki3 khaki4 \ + LightGoldenrod1 LightGoldenrod2 LightGoldenrod3 \ + LightGoldenrod4 LightYellow1 LightYellow2 LightYellow3 \ + LightYellow4 yellow1 yellow2 yellow3 yellow4 gold1 gold2 \ + gold3 gold4 goldenrod1 goldenrod2 goldenrod3 goldenrod4 \ + DarkGoldenrod1 DarkGoldenrod2 DarkGoldenrod3 DarkGoldenrod4 \ + RosyBrown1 RosyBrown2 RosyBrown3 RosyBrown4 IndianRed1 \ + IndianRed2 IndianRed3 IndianRed4 sienna1 sienna2 sienna3 \ + sienna4 burlywood1 burlywood2 burlywood3 burlywood4 wheat1 \ + wheat2 wheat3 wheat4 tan1 tan2 tan3 tan4 chocolate1 \ + chocolate2 chocolate3 chocolate4 firebrick1 firebrick2 \ + firebrick3 firebrick4 brown1 brown2 brown3 brown4 salmon1 \ + salmon2 salmon3 salmon4 LightSalmon1 LightSalmon2 \ + LightSalmon3 LightSalmon4 orange1 orange2 orange3 orange4 \ + DarkOrange1 DarkOrange2 DarkOrange3 DarkOrange4 coral1 \ + coral2 coral3 coral4 tomato1 tomato2 tomato3 tomato4 \ + OrangeRed1 OrangeRed2 OrangeRed3 OrangeRed4 red1 red2 red3 \ + red4 DeepPink1 DeepPink2 DeepPink3 DeepPink4 HotPink1 \ + HotPink2 HotPink3 HotPink4 pink1 pink2 pink3 pink4 \ + LightPink1 LightPink2 LightPink3 LightPink4 PaleVioletRed1 \ + PaleVioletRed2 PaleVioletRed3 PaleVioletRed4 maroon1 \ + maroon2 maroon3 maroon4 VioletRed1 VioletRed2 VioletRed3 \ + VioletRed4 magenta1 magenta2 magenta3 magenta4 orchid1 \ + orchid2 orchid3 orchid4 plum1 plum2 plum3 plum4 \ + MediumOrchid1 MediumOrchid2 MediumOrchid3 MediumOrchid4 \ + DarkOrchid1 DarkOrchid2 DarkOrchid3 DarkOrchid4 purple1 \ + purple2 purple3 purple4 MediumPurple1 MediumPurple2 \ + MediumPurple3 MediumPurple4 thistle1 thistle2 thistle3 \ + thistle4 diff --git a/library/demos/cscroll.tcl b/library/demos/cscroll.tcl new file mode 100644 index 0000000..78f99fa --- /dev/null +++ b/library/demos/cscroll.tcl @@ -0,0 +1,96 @@ +# cscroll.tcl -- +# +# This demonstration script creates a simple canvas that can be +# scrolled in two dimensions. +# +# SCCS: @(#) cscroll.tcl 1.6 97/03/02 16:20:45 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .cscroll +catch {destroy $w} +toplevel $w +wm title $w "Scrollable Canvas Demonstration" +wm iconname $w "cscroll" +positionWindow $w +set c $w.c + +label $w.msg -font $font -wraplength 4i -justify left -text "This window displays a canvas widget that can be scrolled either using the scrollbars or by dragging with button 2 in the canvas. If you click button 1 on one of the rectangles, its indices will be printed on stdout." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.grid +scrollbar $w.hscroll -orient horiz -command "$c xview" +scrollbar $w.vscroll -command "$c yview" +canvas $c -relief sunken -borderwidth 2 -scrollregion {-11c -11c 50c 20c} \ + -xscrollcommand "$w.hscroll set" \ + -yscrollcommand "$w.vscroll set" +pack $w.grid -expand yes -fill both -padx 1 -pady 1 +grid rowconfig $w.grid 0 -weight 1 -minsize 0 +grid columnconfig $w.grid 0 -weight 1 -minsize 0 + +grid $c -padx 1 -in $w.grid -pady 1 \ + -row 0 -column 0 -rowspan 1 -columnspan 1 -sticky news +grid $w.vscroll -in $w.grid -padx 1 -pady 1 \ + -row 0 -column 1 -rowspan 1 -columnspan 1 -sticky news +grid $w.hscroll -in $w.grid -padx 1 -pady 1 \ + -row 1 -column 0 -rowspan 1 -columnspan 1 -sticky news + + +set bg [lindex [$c config -bg] 4] +for {set i 0} {$i < 20} {incr i} { + set x [expr {-10 + 3*$i}] + for {set j 0; set y -10} {$j < 10} {incr j; incr y 3} { + $c create rect ${x}c ${y}c [expr $x+2]c [expr $y+2]c \ + -outline black -fill $bg -tags rect + $c create text [expr $x+1]c [expr $y+1]c -text "$i,$j" \ + -anchor center -tags text + } +} + +$c bind all <Any-Enter> "scrollEnter $c" +$c bind all <Any-Leave> "scrollLeave $c" +$c bind all <1> "scrollButton $c" +bind $c <2> "$c scan mark %x %y" +bind $c <B2-Motion> "$c scan dragto %x %y" + +proc scrollEnter canvas { + global oldFill + set id [$canvas find withtag current] + if {[lsearch [$canvas gettags current] text] >= 0} { + set id [expr $id-1] + } + set oldFill [lindex [$canvas itemconfig $id -fill] 4] + if {[winfo depth $canvas] > 1} { + $canvas itemconfigure $id -fill SeaGreen1 + } else { + $canvas itemconfigure $id -fill black + $canvas itemconfigure [expr $id+1] -fill white + } +} + +proc scrollLeave canvas { + global oldFill + set id [$canvas find withtag current] + if {[lsearch [$canvas gettags current] text] >= 0} { + set id [expr $id-1] + } + $canvas itemconfigure $id -fill $oldFill + $canvas itemconfigure [expr $id+1] -fill black +} + +proc scrollButton canvas { + global oldFill + set id [$canvas find withtag current] + if {[lsearch [$canvas gettags current] text] < 0} { + set id [expr $id+1] + } + puts stdout "You buttoned at [lindex [$canvas itemconf $id -text] 4]" +} diff --git a/library/demos/ctext.tcl b/library/demos/ctext.tcl new file mode 100644 index 0000000..fdd3f79 --- /dev/null +++ b/library/demos/ctext.tcl @@ -0,0 +1,146 @@ +# ctext.tcl -- +# +# This demonstration script creates a canvas widget with a text +# item that can be edited and reconfigured in various ways. +# +# SCCS: @(#) ctext.tcl 1.6 97/03/02 16:21:02 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .ctext +catch {destroy $w} +toplevel $w +wm title $w "Canvas Text Demonstration" +wm iconname $w "Text" +positionWindow $w +set c $w.c + +label $w.msg -font $font -wraplength 5i -justify left -text "This window displays a string of text to demonstrate the text facilities of canvas widgets. You can click in the boxes to adjust the position of the text relative to its positioning point or change its justification. The text also supports the following simple bindings for editing: + 1. You can point, click, and type. + 2. You can also select with button 1. + 3. You can copy the selection to the mouse position with button 2. + 4. Backspace and Control+h delete the selection if there is one; + otherwise they delete the character just before the insertion cursor. + 5. Delete deletes the selection if there is one; otherwise it deletes + the character just after the insertion cursor." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +canvas $c -relief flat -borderwidth 0 -width 500 -height 350 +pack $w.c -side top -expand yes -fill both + +set textFont {Helvetica 24} + +$c create rectangle 245 195 255 205 -outline black -fill red + +# First, create the text item and give it bindings so it can be edited. + +$c addtag text withtag [$c create text 250 200 -text "This is just a string of text to demonstrate the text facilities of canvas widgets. Bindings have been been defined to support editing (see above)." -width 440 -anchor n -font {Helvetica 24} -justify left] +$c bind text <1> "textB1Press $c %x %y" +$c bind text <B1-Motion> "textB1Move $c %x %y" +$c bind text <Shift-1> "$c select adjust current @%x,%y" +$c bind text <Shift-B1-Motion> "textB1Move $c %x %y" +$c bind text <KeyPress> "textInsert $c %A" +$c bind text <Return> "textInsert $c \\n" +$c bind text <Control-h> "textBs $c" +$c bind text <BackSpace> "textBs $c" +$c bind text <Delete> "textDel $c" +$c bind text <2> "textPaste $c @%x,%y" + +# Next, create some items that allow the text's anchor position +# to be edited. + +proc mkTextConfig {w x y option value color} { + set item [$w create rect [expr $x] [expr $y] [expr $x+30] [expr $y+30] \ + -outline black -fill $color -width 1] + $w bind $item <1> "$w itemconf text $option $value" + $w addtag config withtag $item +} + +set x 50 +set y 50 +set color LightSkyBlue1 +mkTextConfig $c $x $y -anchor se $color +mkTextConfig $c [expr $x+30] [expr $y] -anchor s $color +mkTextConfig $c [expr $x+60] [expr $y] -anchor sw $color +mkTextConfig $c [expr $x] [expr $y+30] -anchor e $color +mkTextConfig $c [expr $x+30] [expr $y+30] -anchor center $color +mkTextConfig $c [expr $x+60] [expr $y+30] -anchor w $color +mkTextConfig $c [expr $x] [expr $y+60] -anchor ne $color +mkTextConfig $c [expr $x+30] [expr $y+60] -anchor n $color +mkTextConfig $c [expr $x+60] [expr $y+60] -anchor nw $color +set item [$c create rect [expr $x+40] [expr $y+40] [expr $x+50] [expr $y+50] \ + -outline black -fill red] +$c bind $item <1> "$c itemconf text -anchor center" +$c create text [expr $x+45] [expr $y-5] -text {Text Position} -anchor s \ + -font {Times 24} -fill brown + +# Lastly, create some items that allow the text's justification to be +# changed. + +set x 350 +set y 50 +set color SeaGreen2 +mkTextConfig $c $x $y -justify left $color +mkTextConfig $c [expr $x+30] [expr $y] -justify center $color +mkTextConfig $c [expr $x+60] [expr $y] -justify right $color +$c create text [expr $x+45] [expr $y-5] -text {Justification} -anchor s \ + -font {Times 24} -fill brown + +$c bind config <Enter> "textEnter $c" +$c bind config <Leave> "$c itemconf current -fill \$textConfigFill" + +set textConfigFill {} + +proc textEnter {w} { + global textConfigFill + set textConfigFill [lindex [$w itemconfig current -fill] 4] + $w itemconfig current -fill black +} + +proc textInsert {w string} { + if {$string == ""} { + return + } + catch {$w dchars text sel.first sel.last} + $w insert text insert $string +} + +proc textPaste {w pos} { + catch { + $w insert text $pos [selection get] + } +} + +proc textB1Press {w x y} { + $w icursor current @$x,$y + $w focus current + focus $w + $w select from current @$x,$y +} + +proc textB1Move {w x y} { + $w select to current @$x,$y +} + +proc textBs {w} { + if ![catch {$w dchars text sel.first sel.last}] { + return + } + set char [expr {[$w index text insert] - 1}] + if {$char >= 0} {$w dchar text $char} +} + +proc textDel {w} { + if ![catch {$w dchars text sel.first sel.last}] { + return + } + $w dchars text insert +} diff --git a/library/demos/dialog1.tcl b/library/demos/dialog1.tcl new file mode 100644 index 0000000..e221beb --- /dev/null +++ b/library/demos/dialog1.tcl @@ -0,0 +1,15 @@ +# dialog1.tcl -- +# +# This demonstration script creates a dialog box with a local grab. +# +# SCCS: @(#) dialog1.tcl 1.2 96/02/16 10:49:52 + +after idle {.dialog1.msg configure -wraplength 4i} +set i [tk_dialog .dialog1 "Dialog with local grab" {This is a modal dialog box. It uses Tk's "grab" command to create a "local grab" on the dialog box. The grab prevents any pointer-related events from getting to any other windows in the application until you have answered the dialog by invoking one of the buttons below. However, you can still interact with other applications.} \ +info 0 OK Cancel {Show Code}] + +switch $i { + 0 {puts "You pressed OK"} + 1 {puts "You pressed Cancel"} + 2 {showCode .dialog1} +} diff --git a/library/demos/dialog2.tcl b/library/demos/dialog2.tcl new file mode 100644 index 0000000..0cc3bb6 --- /dev/null +++ b/library/demos/dialog2.tcl @@ -0,0 +1,19 @@ +# dialog2.tcl -- +# +# This demonstration script creates a dialog box with a global grab. +# +# SCCS: @(#) dialog2.tcl 1.2 96/02/16 10:49:53 + +after idle { + .dialog2.msg configure -wraplength 4i +} +after 100 { + grab -global .dialog2 +} +set i [tk_dialog .dialog2 "Dialog with local grab" {This dialog box uses a global grab, so it prevents you from interacting with anything on your display until you invoke one of the buttons below. Global grabs are almost always a bad idea; don't use them unless you're truly desperate.} warning 0 OK Cancel {Show Code}] + +switch $i { + 0 {puts "You pressed OK"} + 1 {puts "You pressed Cancel"} + 2 {showCode .dialog2} +} diff --git a/library/demos/entry1.tcl b/library/demos/entry1.tcl new file mode 100644 index 0000000..0b68b68 --- /dev/null +++ b/library/demos/entry1.tcl @@ -0,0 +1,36 @@ +# entry1.tcl -- +# +# This demonstration script creates several entry widgets without +# scrollbars. +# +# SCCS: @(#) entry1.tcl 1.5 97/03/02 16:22:10 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .entry1 +catch {destroy $w} +toplevel $w +wm title $w "Entry Demonstration (no scrollbars)" +wm iconname $w "entry1" +positionWindow $w + +label $w.msg -font $font -wraplength 5i -justify left -text "Three different entries are displayed below. You can add characters by pointing, clicking and typing. The normal Motif editing characters are supported, along with many Emacs bindings. For example, Backspace and Control-h delete the character to the left of the insertion cursor and Delete and Control-d delete the chararacter to the right of the insertion cursor. For entries that are too large to fit in the window all at once, you can scan through the entries by dragging with mouse button2 pressed." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +entry $w.e1 +entry $w.e2 +entry $w.e3 +pack $w.e1 $w.e2 $w.e3 -side top -pady 5 -padx 10 -fill x + +$w.e1 insert 0 "Initial value" +$w.e2 insert end "This entry contains a long value, much too long " +$w.e2 insert end "to fit in the window at one time, so long in fact " +$w.e2 insert end "that you'll have to scan or scroll to see the end." diff --git a/library/demos/entry2.tcl b/library/demos/entry2.tcl new file mode 100644 index 0000000..d9b67cd --- /dev/null +++ b/library/demos/entry2.tcl @@ -0,0 +1,48 @@ +# entry2.tcl -- +# +# This demonstration script is the same as the entry1.tcl script +# except that it creates scrollbars for the entries. +# +# SCCS: @(#) entry2.tcl 1.5 97/03/02 16:22:24 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .entry2 +catch {destroy $w} +toplevel $w +wm title $w "Entry Demonstration (with scrollbars)" +wm iconname $w "entry2" +positionWindow $w + +label $w.msg -font $font -wraplength 5i -justify left -text "Three different entries are displayed below, with a scrollbar for each entry. You can add characters by pointing, clicking and typing. The normal Motif editing characters are supported, along with many Emacs bindings. For example, Backspace and Control-h delete the character to the left of the insertion cursor and Delete and Control-d delete the chararacter to the right of the insertion cursor. For entries that are too large to fit in the window all at once, you can scan through the entries with the scrollbars, or by dragging with mouse button2 pressed." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.frame -borderwidth 10 +pack $w.frame -side top -fill x -expand 1 + +entry $w.frame.e1 -xscrollcommand "$w.frame.s1 set" +scrollbar $w.frame.s1 -relief sunken -orient horiz -command \ + "$w.frame.e1 xview" +frame $w.frame.spacer1 -width 20 -height 10 +entry $w.frame.e2 -xscrollcommand "$w.frame.s2 set" +scrollbar $w.frame.s2 -relief sunken -orient horiz -command \ + "$w.frame.e2 xview" +frame $w.frame.spacer2 -width 20 -height 10 +entry $w.frame.e3 -xscrollcommand "$w.frame.s3 set" +scrollbar $w.frame.s3 -relief sunken -orient horiz -command \ + "$w.frame.e3 xview" +pack $w.frame.e1 $w.frame.s1 $w.frame.spacer1 $w.frame.e2 $w.frame.s2 \ + $w.frame.spacer2 $w.frame.e3 $w.frame.s3 -side top -fill x + +$w.frame.e1 insert 0 "Initial value" +$w.frame.e2 insert end "This entry contains a long value, much too long " +$w.frame.e2 insert end "to fit in the window at one time, so long in fact " +$w.frame.e2 insert end "that you'll have to scan or scroll to see the end." diff --git a/library/demos/filebox.tcl b/library/demos/filebox.tcl new file mode 100644 index 0000000..83eeacc --- /dev/null +++ b/library/demos/filebox.tcl @@ -0,0 +1,70 @@ +# filebox.tcl -- +# +# This demonstration script prompts the user to select a file. +# +# SCCS: @(#) filebox.tcl 1.3 97/03/02 16:22:36 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .filebox +catch {destroy $w} +toplevel $w +wm title $w "File Selection Dialogs" +wm iconname $w "filebox" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "Enter a file name in the entry box or click on the \"Browse\" buttons to select a file name using the file selection dialog." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +foreach i {open save} { + set f [frame $w.$i] + label $f.lab -text "Select a file to $i: " -anchor e + entry $f.ent -width 20 + button $f.but -text "Browse ..." -command "fileDialog $w $f.ent $i" + pack $f.lab -side left + pack $f.ent -side left -expand yes -fill x + pack $f.but -side left + pack $f -fill x -padx 1c -pady 3 +} + +if ![string compare $tcl_platform(platform) unix] { + checkbutton $w.strict -text "Use Motif Style Dialog" \ + -variable tk_strictMotif -onvalue 1 -offvalue 0 + pack $w.strict -anchor c +} + +proc fileDialog {w ent operation} { + # Type names Extension(s) Mac File Type(s) + # + #--------------------------------------------------------- + set types { + {"Text files" {.txt .doc} } + {"Text files" {} TEXT} + {"Tcl Scripts" {.tcl} TEXT} + {"C Source Files" {.c .h} } + {"All Source Files" {.tcl .c .h} } + {"Image Files" {.gif} } + {"Image Files" {.jpeg .jpg} } + {"Image Files" "" {GIFF JPEG}} + {"All files" *} + } + if {$operation == "open"} { + set file [tk_getOpenFile -filetypes $types -parent $w] + } else { + set file [tk_getSaveFile -filetypes $types -parent $w \ + -initialfile Untitled -defaultextension .txt] + } + if [string compare $file ""] { + $ent delete 0 end + $ent insert 0 $file + $ent xview end + } +} diff --git a/library/demos/floor.tcl b/library/demos/floor.tcl new file mode 100644 index 0000000..30b62da --- /dev/null +++ b/library/demos/floor.tcl @@ -0,0 +1,1370 @@ +# floor.tcl -- +# +# This demonstration script creates a canvas widet that displays the +# floorplan for DEC's Western Research Laboratory. +# +# SCCS: @(#) floor.tcl 1.6 97/03/02 16:23:32 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +# floorDisplay -- +# Recreate the floorplan display in the canvas given by "w". The +# floor given by "active" is displayed on top with its office structure +# visible. +# +# Arguments: +# w - Name of the canvas window. +# active - Number of active floor (1, 2, or 3). + +proc floorDisplay {w active} { + global floorLabels floorItems colors activeFloor + + if {$activeFloor == $active} { + return + } + + $w delete all + set activeFloor $active + + # First go through the three floors, displaying the backgrounds for + # each floor. + + bg1 $w $colors(bg1) $colors(outline1) + bg2 $w $colors(bg2) $colors(outline2) + bg3 $w $colors(bg3) $colors(outline3) + + # Raise the background for the active floor so that it's on top. + + $w raise floor$active + + # Create a dummy item just to mark this point in the display list, + # so we can insert highlights here. + + $w create rect 0 100 1 101 -fill {} -outline {} -tags marker + + # Add the walls and labels for the active floor, along with + # transparent polygons that define the rooms on the floor. + # Make sure that the room polygons are on top. + + catch {unset floorLabels} + catch {unset floorItems} + fg$active $w $colors(offices) + $w raise room + + # Offset the floors diagonally from each other. + + $w move floor1 2c 2c + $w move floor2 1c 1c + + # Create items for the room entry and its label. + + $w create window 600 100 -anchor w -window $w.entry + $w create text 600 100 -anchor e -text "Room: " + $w config -scrollregion [$w bbox all] +} + +# newRoom -- +# This procedure is invoked whenever the mouse enters a room +# in the floorplan. It changes tags so that the current room is +# highlighted. +# +# Arguments: +# w - The name of the canvas window. + +proc newRoom w { + global currentRoom floorLabels + + set id [$w find withtag current] + if {$id != ""} { + set currentRoom $floorLabels($id) + } + update idletasks +} + +# roomChanged -- +# This procedure is invoked whenever the currentRoom variable changes. +# It highlights the current room and unhighlights any previous room. +# +# Arguments: +# w - The canvas window displaying the floorplan. +# args - Not used. + +proc roomChanged {w args} { + global currentRoom floorItems colors + $w delete highlight + if [catch {set item $floorItems($currentRoom)}] { + return + } + set new [eval \ + "$w create polygon [$w coords $item] -fill $colors(active) \ + -tags highlight"] + $w raise $new marker +} + +# bg1 -- +# This procedure represents part of the floorplan database. When +# invoked, it instantiates the background information for the first +# floor. +# +# Arguments: +# w - The canvas window. +# fill - Fill color to use for the floor's background. +# outline - Color to use for the floor's outline. + +proc bg1 {w fill outline} { + $w create poly 347 80 349 82 351 84 353 85 363 92 375 99 386 104 \ + 386 129 398 129 398 162 484 162 484 129 559 129 559 133 725 \ + 133 725 129 802 129 802 389 644 389 644 391 559 391 559 327 \ + 508 327 508 311 484 311 484 278 395 278 395 288 400 288 404 \ + 288 409 290 413 292 418 297 421 302 422 309 421 318 417 325 \ + 411 330 405 332 397 333 344 333 340 334 336 336 335 338 332 \ + 342 331 347 332 351 334 354 336 357 341 359 340 360 335 363 \ + 331 365 326 366 304 366 304 355 258 355 258 387 60 387 60 391 \ + 0 391 0 337 3 337 3 114 8 114 8 25 30 25 30 5 93 5 98 5 104 7 \ + 110 10 116 16 119 20 122 28 123 32 123 68 220 68 220 34 221 \ + 22 223 17 227 13 231 8 236 4 242 2 246 0 260 0 283 1 300 5 \ + 321 14 335 22 348 25 365 29 363 39 358 48 352 56 337 70 \ + 344 76 347 80 \ + -tags {floor1 bg} -fill $fill + $w create line 386 129 398 129 -fill $outline -tags {floor1 bg} + $w create line 258 355 258 387 -fill $outline -tags {floor1 bg} + $w create line 60 387 60 391 -fill $outline -tags {floor1 bg} + $w create line 0 337 0 391 -fill $outline -tags {floor1 bg} + $w create line 60 391 0 391 -fill $outline -tags {floor1 bg} + $w create line 3 114 3 337 -fill $outline -tags {floor1 bg} + $w create line 258 387 60 387 -fill $outline -tags {floor1 bg} + $w create line 484 162 398 162 -fill $outline -tags {floor1 bg} + $w create line 398 162 398 129 -fill $outline -tags {floor1 bg} + $w create line 484 278 484 311 -fill $outline -tags {floor1 bg} + $w create line 484 311 508 311 -fill $outline -tags {floor1 bg} + $w create line 508 327 508 311 -fill $outline -tags {floor1 bg} + $w create line 559 327 508 327 -fill $outline -tags {floor1 bg} + $w create line 644 391 559 391 -fill $outline -tags {floor1 bg} + $w create line 644 389 644 391 -fill $outline -tags {floor1 bg} + $w create line 559 129 484 129 -fill $outline -tags {floor1 bg} + $w create line 484 162 484 129 -fill $outline -tags {floor1 bg} + $w create line 725 133 559 133 -fill $outline -tags {floor1 bg} + $w create line 559 129 559 133 -fill $outline -tags {floor1 bg} + $w create line 725 129 802 129 -fill $outline -tags {floor1 bg} + $w create line 802 389 802 129 -fill $outline -tags {floor1 bg} + $w create line 3 337 0 337 -fill $outline -tags {floor1 bg} + $w create line 559 391 559 327 -fill $outline -tags {floor1 bg} + $w create line 802 389 644 389 -fill $outline -tags {floor1 bg} + $w create line 725 133 725 129 -fill $outline -tags {floor1 bg} + $w create line 8 25 8 114 -fill $outline -tags {floor1 bg} + $w create line 8 114 3 114 -fill $outline -tags {floor1 bg} + $w create line 30 25 8 25 -fill $outline -tags {floor1 bg} + $w create line 484 278 395 278 -fill $outline -tags {floor1 bg} + $w create line 30 25 30 5 -fill $outline -tags {floor1 bg} + $w create line 93 5 30 5 -fill $outline -tags {floor1 bg} + $w create line 98 5 93 5 -fill $outline -tags {floor1 bg} + $w create line 104 7 98 5 -fill $outline -tags {floor1 bg} + $w create line 110 10 104 7 -fill $outline -tags {floor1 bg} + $w create line 116 16 110 10 -fill $outline -tags {floor1 bg} + $w create line 119 20 116 16 -fill $outline -tags {floor1 bg} + $w create line 122 28 119 20 -fill $outline -tags {floor1 bg} + $w create line 123 32 122 28 -fill $outline -tags {floor1 bg} + $w create line 123 68 123 32 -fill $outline -tags {floor1 bg} + $w create line 220 68 123 68 -fill $outline -tags {floor1 bg} + $w create line 386 129 386 104 -fill $outline -tags {floor1 bg} + $w create line 386 104 375 99 -fill $outline -tags {floor1 bg} + $w create line 375 99 363 92 -fill $outline -tags {floor1 bg} + $w create line 353 85 363 92 -fill $outline -tags {floor1 bg} + $w create line 220 68 220 34 -fill $outline -tags {floor1 bg} + $w create line 337 70 352 56 -fill $outline -tags {floor1 bg} + $w create line 352 56 358 48 -fill $outline -tags {floor1 bg} + $w create line 358 48 363 39 -fill $outline -tags {floor1 bg} + $w create line 363 39 365 29 -fill $outline -tags {floor1 bg} + $w create line 365 29 348 25 -fill $outline -tags {floor1 bg} + $w create line 348 25 335 22 -fill $outline -tags {floor1 bg} + $w create line 335 22 321 14 -fill $outline -tags {floor1 bg} + $w create line 321 14 300 5 -fill $outline -tags {floor1 bg} + $w create line 300 5 283 1 -fill $outline -tags {floor1 bg} + $w create line 283 1 260 0 -fill $outline -tags {floor1 bg} + $w create line 260 0 246 0 -fill $outline -tags {floor1 bg} + $w create line 246 0 242 2 -fill $outline -tags {floor1 bg} + $w create line 242 2 236 4 -fill $outline -tags {floor1 bg} + $w create line 236 4 231 8 -fill $outline -tags {floor1 bg} + $w create line 231 8 227 13 -fill $outline -tags {floor1 bg} + $w create line 223 17 227 13 -fill $outline -tags {floor1 bg} + $w create line 221 22 223 17 -fill $outline -tags {floor1 bg} + $w create line 220 34 221 22 -fill $outline -tags {floor1 bg} + $w create line 340 360 335 363 -fill $outline -tags {floor1 bg} + $w create line 335 363 331 365 -fill $outline -tags {floor1 bg} + $w create line 331 365 326 366 -fill $outline -tags {floor1 bg} + $w create line 326 366 304 366 -fill $outline -tags {floor1 bg} + $w create line 304 355 304 366 -fill $outline -tags {floor1 bg} + $w create line 395 288 400 288 -fill $outline -tags {floor1 bg} + $w create line 404 288 400 288 -fill $outline -tags {floor1 bg} + $w create line 409 290 404 288 -fill $outline -tags {floor1 bg} + $w create line 413 292 409 290 -fill $outline -tags {floor1 bg} + $w create line 418 297 413 292 -fill $outline -tags {floor1 bg} + $w create line 421 302 418 297 -fill $outline -tags {floor1 bg} + $w create line 422 309 421 302 -fill $outline -tags {floor1 bg} + $w create line 421 318 422 309 -fill $outline -tags {floor1 bg} + $w create line 421 318 417 325 -fill $outline -tags {floor1 bg} + $w create line 417 325 411 330 -fill $outline -tags {floor1 bg} + $w create line 411 330 405 332 -fill $outline -tags {floor1 bg} + $w create line 405 332 397 333 -fill $outline -tags {floor1 bg} + $w create line 397 333 344 333 -fill $outline -tags {floor1 bg} + $w create line 344 333 340 334 -fill $outline -tags {floor1 bg} + $w create line 340 334 336 336 -fill $outline -tags {floor1 bg} + $w create line 336 336 335 338 -fill $outline -tags {floor1 bg} + $w create line 335 338 332 342 -fill $outline -tags {floor1 bg} + $w create line 331 347 332 342 -fill $outline -tags {floor1 bg} + $w create line 332 351 331 347 -fill $outline -tags {floor1 bg} + $w create line 334 354 332 351 -fill $outline -tags {floor1 bg} + $w create line 336 357 334 354 -fill $outline -tags {floor1 bg} + $w create line 341 359 336 357 -fill $outline -tags {floor1 bg} + $w create line 341 359 340 360 -fill $outline -tags {floor1 bg} + $w create line 395 288 395 278 -fill $outline -tags {floor1 bg} + $w create line 304 355 258 355 -fill $outline -tags {floor1 bg} + $w create line 347 80 344 76 -fill $outline -tags {floor1 bg} + $w create line 344 76 337 70 -fill $outline -tags {floor1 bg} + $w create line 349 82 347 80 -fill $outline -tags {floor1 bg} + $w create line 351 84 349 82 -fill $outline -tags {floor1 bg} + $w create line 353 85 351 84 -fill $outline -tags {floor1 bg} +} + +# bg2 -- +# This procedure represents part of the floorplan database. When +# invoked, it instantiates the background information for the second +# floor. +# +# Arguments: +# w - The canvas window. +# fill - Fill color to use for the floor's background. +# outline - Color to use for the floor's outline. + +proc bg2 {w fill outline} { + $w create poly 559 129 484 129 484 162 398 162 398 129 315 129 \ + 315 133 176 133 176 129 96 129 96 133 3 133 3 339 0 339 0 391 \ + 60 391 60 387 258 387 258 329 350 329 350 311 395 311 395 280 \ + 484 280 484 311 508 311 508 327 558 327 558 391 644 391 644 \ + 367 802 367 802 129 725 129 725 133 559 133 559 129 \ + -tags {floor2 bg} -fill $fill + $w create line 350 311 350 329 -fill $outline -tags {floor2 bg} + $w create line 398 129 398 162 -fill $outline -tags {floor2 bg} + $w create line 802 367 802 129 -fill $outline -tags {floor2 bg} + $w create line 802 129 725 129 -fill $outline -tags {floor2 bg} + $w create line 725 133 725 129 -fill $outline -tags {floor2 bg} + $w create line 559 129 559 133 -fill $outline -tags {floor2 bg} + $w create line 559 133 725 133 -fill $outline -tags {floor2 bg} + $w create line 484 162 484 129 -fill $outline -tags {floor2 bg} + $w create line 559 129 484 129 -fill $outline -tags {floor2 bg} + $w create line 802 367 644 367 -fill $outline -tags {floor2 bg} + $w create line 644 367 644 391 -fill $outline -tags {floor2 bg} + $w create line 644 391 558 391 -fill $outline -tags {floor2 bg} + $w create line 558 327 558 391 -fill $outline -tags {floor2 bg} + $w create line 558 327 508 327 -fill $outline -tags {floor2 bg} + $w create line 508 327 508 311 -fill $outline -tags {floor2 bg} + $w create line 484 311 508 311 -fill $outline -tags {floor2 bg} + $w create line 484 280 484 311 -fill $outline -tags {floor2 bg} + $w create line 398 162 484 162 -fill $outline -tags {floor2 bg} + $w create line 484 280 395 280 -fill $outline -tags {floor2 bg} + $w create line 395 280 395 311 -fill $outline -tags {floor2 bg} + $w create line 258 387 60 387 -fill $outline -tags {floor2 bg} + $w create line 3 133 3 339 -fill $outline -tags {floor2 bg} + $w create line 3 339 0 339 -fill $outline -tags {floor2 bg} + $w create line 60 391 0 391 -fill $outline -tags {floor2 bg} + $w create line 0 339 0 391 -fill $outline -tags {floor2 bg} + $w create line 60 387 60 391 -fill $outline -tags {floor2 bg} + $w create line 258 329 258 387 -fill $outline -tags {floor2 bg} + $w create line 350 329 258 329 -fill $outline -tags {floor2 bg} + $w create line 395 311 350 311 -fill $outline -tags {floor2 bg} + $w create line 398 129 315 129 -fill $outline -tags {floor2 bg} + $w create line 176 133 315 133 -fill $outline -tags {floor2 bg} + $w create line 176 129 96 129 -fill $outline -tags {floor2 bg} + $w create line 3 133 96 133 -fill $outline -tags {floor2 bg} + $w create line 315 133 315 129 -fill $outline -tags {floor2 bg} + $w create line 176 133 176 129 -fill $outline -tags {floor2 bg} + $w create line 96 133 96 129 -fill $outline -tags {floor2 bg} +} + +# bg3 -- +# This procedure represents part of the floorplan database. When +# invoked, it instantiates the background information for the third +# floor. +# +# Arguments: +# w - The canvas window. +# fill - Fill color to use for the floor's background. +# outline - Color to use for the floor's outline. + +proc bg3 {w fill outline} { + $w create poly 159 300 107 300 107 248 159 248 159 129 96 129 96 \ + 133 21 133 21 331 0 331 0 391 60 391 60 370 159 370 159 300 \ + -tags {floor3 bg} -fill $fill + $w create poly 258 370 258 329 350 329 350 311 399 311 399 129 \ + 315 129 315 133 176 133 176 129 159 129 159 370 258 370 \ + -tags {floor3 bg} -fill $fill + $w create line 96 133 96 129 -fill $outline -tags {floor3 bg} + $w create line 176 129 96 129 -fill $outline -tags {floor3 bg} + $w create line 176 129 176 133 -fill $outline -tags {floor3 bg} + $w create line 315 133 176 133 -fill $outline -tags {floor3 bg} + $w create line 315 133 315 129 -fill $outline -tags {floor3 bg} + $w create line 399 129 315 129 -fill $outline -tags {floor3 bg} + $w create line 399 311 399 129 -fill $outline -tags {floor3 bg} + $w create line 399 311 350 311 -fill $outline -tags {floor3 bg} + $w create line 350 329 350 311 -fill $outline -tags {floor3 bg} + $w create line 350 329 258 329 -fill $outline -tags {floor3 bg} + $w create line 258 370 258 329 -fill $outline -tags {floor3 bg} + $w create line 60 370 258 370 -fill $outline -tags {floor3 bg} + $w create line 60 370 60 391 -fill $outline -tags {floor3 bg} + $w create line 60 391 0 391 -fill $outline -tags {floor3 bg} + $w create line 0 391 0 331 -fill $outline -tags {floor3 bg} + $w create line 21 331 0 331 -fill $outline -tags {floor3 bg} + $w create line 21 331 21 133 -fill $outline -tags {floor3 bg} + $w create line 96 133 21 133 -fill $outline -tags {floor3 bg} + $w create line 107 300 159 300 159 248 107 248 107 300 \ + -fill $outline -tags {floor3 bg} +} + +# fg1 -- +# This procedure represents part of the floorplan database. When +# invoked, it instantiates the foreground information for the first +# floor (office outlines and numbers). +# +# Arguments: +# w - The canvas window. +# color - Color to use for drawing foreground information. + +proc fg1 {w color} { + global floorLabels floorItems + set i [$w create polygon 375 246 375 172 341 172 341 246 -fill {} -tags {floor1 room}] + set floorLabels($i) 101 + set {floorItems(101)} $i + $w create text 358 209 -text 101 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 307 240 339 240 339 206 307 206 -fill {} -tags {floor1 room}] + set floorLabels($i) {Pub Lift1} + set {floorItems(Pub Lift1)} $i + $w create text 323 223 -text {Pub Lift1} -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 339 205 307 205 307 171 339 171 -fill {} -tags {floor1 room}] + set floorLabels($i) {Priv Lift1} + set {floorItems(Priv Lift1)} $i + $w create text 323 188 -text {Priv Lift1} -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 42 389 42 337 1 337 1 389 -fill {} -tags {floor1 room}] + set floorLabels($i) 110 + set {floorItems(110)} $i + $w create text 21.5 363 -text 110 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 59 389 59 385 90 385 90 337 44 337 44 389 -fill {} -tags {floor1 room}] + set floorLabels($i) 109 + set {floorItems(109)} $i + $w create text 67 363 -text 109 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 51 300 51 253 6 253 6 300 -fill {} -tags {floor1 room}] + set floorLabels($i) 111 + set {floorItems(111)} $i + $w create text 28.5 276.5 -text 111 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 98 248 98 309 79 309 79 248 -fill {} -tags {floor1 room}] + set floorLabels($i) 117B + set {floorItems(117B)} $i + $w create text 88.5 278.5 -text 117B -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 51 251 51 204 6 204 6 251 -fill {} -tags {floor1 room}] + set floorLabels($i) 112 + set {floorItems(112)} $i + $w create text 28.5 227.5 -text 112 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 6 156 51 156 51 203 6 203 -fill {} -tags {floor1 room}] + set floorLabels($i) 113 + set {floorItems(113)} $i + $w create text 28.5 179.5 -text 113 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 85 169 79 169 79 192 85 192 -fill {} -tags {floor1 room}] + set floorLabels($i) 117A + set {floorItems(117A)} $i + $w create text 82 180.5 -text 117A -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 77 302 77 168 53 168 53 302 -fill {} -tags {floor1 room}] + set floorLabels($i) 117 + set {floorItems(117)} $i + $w create text 65 235 -text 117 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 51 155 51 115 6 115 6 155 -fill {} -tags {floor1 room}] + set floorLabels($i) 114 + set {floorItems(114)} $i + $w create text 28.5 135 -text 114 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 95 115 53 115 53 168 95 168 -fill {} -tags {floor1 room}] + set floorLabels($i) 115 + set {floorItems(115)} $i + $w create text 74 141.5 -text 115 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 87 113 87 27 10 27 10 113 -fill {} -tags {floor1 room}] + set floorLabels($i) 116 + set {floorItems(116)} $i + $w create text 48.5 70 -text 116 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 89 91 128 91 128 113 89 113 -fill {} -tags {floor1 room}] + set floorLabels($i) 118 + set {floorItems(118)} $i + $w create text 108.5 102 -text 118 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 178 128 178 132 216 132 216 91 163 91 163 112 149 112 149 128 -fill {} -tags {floor1 room}] + set floorLabels($i) 120 + set {floorItems(120)} $i + $w create text 189.5 111.5 -text 120 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 79 193 87 193 87 169 136 169 136 192 156 192 156 169 175 169 175 246 79 246 -fill {} -tags {floor1 room}] + set floorLabels($i) 122 + set {floorItems(122)} $i + $w create text 131 207.5 -text 122 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 138 169 154 169 154 191 138 191 -fill {} -tags {floor1 room}] + set floorLabels($i) 121 + set {floorItems(121)} $i + $w create text 146 180 -text 121 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 99 300 126 300 126 309 99 309 -fill {} -tags {floor1 room}] + set floorLabels($i) 106A + set {floorItems(106A)} $i + $w create text 112.5 304.5 -text 106A -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 128 299 128 309 150 309 150 248 99 248 99 299 -fill {} -tags {floor1 room}] + set floorLabels($i) 105 + set {floorItems(105)} $i + $w create text 124.5 278.5 -text 105 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 174 309 174 300 152 300 152 309 -fill {} -tags {floor1 room}] + set floorLabels($i) 106B + set {floorItems(106B)} $i + $w create text 163 304.5 -text 106B -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 176 299 176 309 216 309 216 248 152 248 152 299 -fill {} -tags {floor1 room}] + set floorLabels($i) 104 + set {floorItems(104)} $i + $w create text 184 278.5 -text 104 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 138 385 138 337 91 337 91 385 -fill {} -tags {floor1 room}] + set floorLabels($i) 108 + set {floorItems(108)} $i + $w create text 114.5 361 -text 108 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 256 337 140 337 140 385 256 385 -fill {} -tags {floor1 room}] + set floorLabels($i) 107 + set {floorItems(107)} $i + $w create text 198 361 -text 107 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 300 353 300 329 260 329 260 353 -fill {} -tags {floor1 room}] + set floorLabels($i) Smoking + set {floorItems(Smoking)} $i + $w create text 280 341 -text Smoking -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 314 135 314 170 306 170 306 246 177 246 177 135 -fill {} -tags {floor1 room}] + set floorLabels($i) 123 + set {floorItems(123)} $i + $w create text 245.5 190.5 -text 123 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 217 248 301 248 301 326 257 326 257 310 217 310 -fill {} -tags {floor1 room}] + set floorLabels($i) 103 + set {floorItems(103)} $i + $w create text 259 287 -text 103 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 396 188 377 188 377 169 316 169 316 131 396 131 -fill {} -tags {floor1 room}] + set floorLabels($i) 124 + set {floorItems(124)} $i + $w create text 356 150 -text 124 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 397 226 407 226 407 189 377 189 377 246 397 246 -fill {} -tags {floor1 room}] + set floorLabels($i) 125 + set {floorItems(125)} $i + $w create text 392 217.5 -text 125 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 399 187 409 187 409 207 474 207 474 164 399 164 -fill {} -tags {floor1 room}] + set floorLabels($i) 126 + set {floorItems(126)} $i + $w create text 436.5 185.5 -text 126 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 409 209 409 229 399 229 399 253 486 253 486 239 474 239 474 209 -fill {} -tags {floor1 room}] + set floorLabels($i) 127 + set {floorItems(127)} $i + $w create text 436.5 231 -text 127 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 501 164 501 174 495 174 495 188 490 188 490 204 476 204 476 164 -fill {} -tags {floor1 room}] + set floorLabels($i) MShower + set {floorItems(MShower)} $i + $w create text 488.5 184 -text MShower -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 497 176 513 176 513 204 492 204 492 190 497 190 -fill {} -tags {floor1 room}] + set floorLabels($i) Closet + set {floorItems(Closet)} $i + $w create text 502.5 190 -text Closet -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 476 237 476 206 513 206 513 254 488 254 488 237 -fill {} -tags {floor1 room}] + set floorLabels($i) WShower + set {floorItems(WShower)} $i + $w create text 494.5 230 -text WShower -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 486 131 558 131 558 135 724 135 724 166 697 166 697 275 553 275 531 254 515 254 515 174 503 174 503 161 486 161 -fill {} -tags {floor1 room}] + set floorLabels($i) 130 + set {floorItems(130)} $i + $w create text 638.5 205 -text 130 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 308 242 339 242 339 248 342 248 342 246 397 246 397 276 393 276 393 309 300 309 300 248 308 248 -fill {} -tags {floor1 room}] + set floorLabels($i) 102 + set {floorItems(102)} $i + $w create text 367.5 278.5 -text 102 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 397 255 486 255 486 276 397 276 -fill {} -tags {floor1 room}] + set floorLabels($i) 128 + set {floorItems(128)} $i + $w create text 441.5 265.5 -text 128 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 510 309 486 309 486 255 530 255 552 277 561 277 561 325 510 325 -fill {} -tags {floor1 room}] + set floorLabels($i) 129 + set {floorItems(129)} $i + $w create text 535.5 293 -text 129 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 696 281 740 281 740 387 642 387 642 389 561 389 561 277 696 277 -fill {} -tags {floor1 room}] + set floorLabels($i) 133 + set {floorItems(133)} $i + $w create text 628.5 335 -text 133 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 742 387 742 281 800 281 800 387 -fill {} -tags {floor1 room}] + set floorLabels($i) 132 + set {floorItems(132)} $i + $w create text 771 334 -text 132 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 800 168 800 280 699 280 699 168 -fill {} -tags {floor1 room}] + set floorLabels($i) 134 + set {floorItems(134)} $i + $w create text 749.5 224 -text 134 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 726 131 726 166 800 166 800 131 -fill {} -tags {floor1 room}] + set floorLabels($i) 135 + set {floorItems(135)} $i + $w create text 763 148.5 -text 135 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 340 360 335 363 331 365 326 366 304 366 304 312 396 312 396 288 400 288 404 288 409 290 413 292 418 297 421 302 422 309 421 318 417 325 411 330 405 332 397 333 344 333 340 334 336 336 335 338 332 342 331 347 332 351 334 354 336 357 341 359 -fill {} -tags {floor1 room}] + set floorLabels($i) {Ramona Stair} + set {floorItems(Ramona Stair)} $i + $w create text 368 323 -text {Ramona Stair} -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 30 23 30 5 93 5 98 5 104 7 110 10 116 16 119 20 122 28 123 32 123 68 220 68 220 87 90 87 90 23 -fill {} -tags {floor1 room}] + set floorLabels($i) {University Stair} + set {floorItems(University Stair)} $i + $w create text 155 77.5 -text {University Stair} -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 282 37 295 40 312 49 323 56 337 70 352 56 358 48 363 39 365 29 348 25 335 22 321 14 300 5 283 1 260 0 246 0 242 2 236 4 231 8 227 13 223 17 221 22 220 34 260 34 -fill {} -tags {floor1 room}] + set floorLabels($i) {Plaza Stair} + set {floorItems(Plaza Stair)} $i + $w create text 317.5 28.5 -text {Plaza Stair} -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 220 34 260 34 282 37 295 40 312 49 323 56 337 70 350 83 365 94 377 100 386 104 386 128 220 128 -fill {} -tags {floor1 room}] + set floorLabels($i) {Plaza Deck} + set {floorItems(Plaza Deck)} $i + $w create text 303 81 -text {Plaza Deck} -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 257 336 77 336 6 336 6 301 77 301 77 310 257 310 -fill {} -tags {floor1 room}] + set floorLabels($i) 106 + set {floorItems(106)} $i + $w create text 131.5 318.5 -text 106 -fill $color -anchor c -tags {floor1 label} + set i [$w create polygon 146 110 162 110 162 91 130 91 130 115 95 115 95 128 114 128 114 151 157 151 157 153 112 153 112 130 97 130 97 168 175 168 175 131 146 131 -fill {} -tags {floor1 room}] + set floorLabels($i) 119 + set {floorItems(119)} $i + $w create text 143.5 133 -text 119 -fill $color -anchor c -tags {floor1 label} + $w create line 155 191 155 189 -fill $color -tags {floor1 wall} + $w create line 155 177 155 169 -fill $color -tags {floor1 wall} + $w create line 96 129 96 169 -fill $color -tags {floor1 wall} + $w create line 78 169 176 169 -fill $color -tags {floor1 wall} + $w create line 176 247 176 129 -fill $color -tags {floor1 wall} + $w create line 340 206 307 206 -fill $color -tags {floor1 wall} + $w create line 340 187 340 170 -fill $color -tags {floor1 wall} + $w create line 340 210 340 201 -fill $color -tags {floor1 wall} + $w create line 340 247 340 224 -fill $color -tags {floor1 wall} + $w create line 340 241 307 241 -fill $color -tags {floor1 wall} + $w create line 376 246 376 170 -fill $color -tags {floor1 wall} + $w create line 307 247 307 170 -fill $color -tags {floor1 wall} + $w create line 376 170 307 170 -fill $color -tags {floor1 wall} + $w create line 315 129 315 170 -fill $color -tags {floor1 wall} + $w create line 147 129 176 129 -fill $color -tags {floor1 wall} + $w create line 202 133 176 133 -fill $color -tags {floor1 wall} + $w create line 398 129 315 129 -fill $color -tags {floor1 wall} + $w create line 258 352 258 387 -fill $color -tags {floor1 wall} + $w create line 60 387 60 391 -fill $color -tags {floor1 wall} + $w create line 0 337 0 391 -fill $color -tags {floor1 wall} + $w create line 60 391 0 391 -fill $color -tags {floor1 wall} + $w create line 3 114 3 337 -fill $color -tags {floor1 wall} + $w create line 258 387 60 387 -fill $color -tags {floor1 wall} + $w create line 52 237 52 273 -fill $color -tags {floor1 wall} + $w create line 52 189 52 225 -fill $color -tags {floor1 wall} + $w create line 52 140 52 177 -fill $color -tags {floor1 wall} + $w create line 395 306 395 311 -fill $color -tags {floor1 wall} + $w create line 531 254 398 254 -fill $color -tags {floor1 wall} + $w create line 475 178 475 238 -fill $color -tags {floor1 wall} + $w create line 502 162 398 162 -fill $color -tags {floor1 wall} + $w create line 398 129 398 188 -fill $color -tags {floor1 wall} + $w create line 383 188 376 188 -fill $color -tags {floor1 wall} + $w create line 408 188 408 194 -fill $color -tags {floor1 wall} + $w create line 398 227 398 254 -fill $color -tags {floor1 wall} + $w create line 408 227 398 227 -fill $color -tags {floor1 wall} + $w create line 408 222 408 227 -fill $color -tags {floor1 wall} + $w create line 408 206 408 210 -fill $color -tags {floor1 wall} + $w create line 408 208 475 208 -fill $color -tags {floor1 wall} + $w create line 484 278 484 311 -fill $color -tags {floor1 wall} + $w create line 484 311 508 311 -fill $color -tags {floor1 wall} + $w create line 508 327 508 311 -fill $color -tags {floor1 wall} + $w create line 559 327 508 327 -fill $color -tags {floor1 wall} + $w create line 644 391 559 391 -fill $color -tags {floor1 wall} + $w create line 644 389 644 391 -fill $color -tags {floor1 wall} + $w create line 514 205 475 205 -fill $color -tags {floor1 wall} + $w create line 496 189 496 187 -fill $color -tags {floor1 wall} + $w create line 559 129 484 129 -fill $color -tags {floor1 wall} + $w create line 484 162 484 129 -fill $color -tags {floor1 wall} + $w create line 725 133 559 133 -fill $color -tags {floor1 wall} + $w create line 559 129 559 133 -fill $color -tags {floor1 wall} + $w create line 725 149 725 167 -fill $color -tags {floor1 wall} + $w create line 725 129 802 129 -fill $color -tags {floor1 wall} + $w create line 802 389 802 129 -fill $color -tags {floor1 wall} + $w create line 739 167 802 167 -fill $color -tags {floor1 wall} + $w create line 396 188 408 188 -fill $color -tags {floor1 wall} + $w create line 0 337 9 337 -fill $color -tags {floor1 wall} + $w create line 58 337 21 337 -fill $color -tags {floor1 wall} + $w create line 43 391 43 337 -fill $color -tags {floor1 wall} + $w create line 105 337 75 337 -fill $color -tags {floor1 wall} + $w create line 91 387 91 337 -fill $color -tags {floor1 wall} + $w create line 154 337 117 337 -fill $color -tags {floor1 wall} + $w create line 139 387 139 337 -fill $color -tags {floor1 wall} + $w create line 227 337 166 337 -fill $color -tags {floor1 wall} + $w create line 258 337 251 337 -fill $color -tags {floor1 wall} + $w create line 258 328 302 328 -fill $color -tags {floor1 wall} + $w create line 302 355 302 311 -fill $color -tags {floor1 wall} + $w create line 395 311 302 311 -fill $color -tags {floor1 wall} + $w create line 484 278 395 278 -fill $color -tags {floor1 wall} + $w create line 395 294 395 278 -fill $color -tags {floor1 wall} + $w create line 473 278 473 275 -fill $color -tags {floor1 wall} + $w create line 473 256 473 254 -fill $color -tags {floor1 wall} + $w create line 533 257 531 254 -fill $color -tags {floor1 wall} + $w create line 553 276 551 274 -fill $color -tags {floor1 wall} + $w create line 698 276 553 276 -fill $color -tags {floor1 wall} + $w create line 559 391 559 327 -fill $color -tags {floor1 wall} + $w create line 802 389 644 389 -fill $color -tags {floor1 wall} + $w create line 741 314 741 389 -fill $color -tags {floor1 wall} + $w create line 698 280 698 167 -fill $color -tags {floor1 wall} + $w create line 707 280 698 280 -fill $color -tags {floor1 wall} + $w create line 802 280 731 280 -fill $color -tags {floor1 wall} + $w create line 741 280 741 302 -fill $color -tags {floor1 wall} + $w create line 698 167 727 167 -fill $color -tags {floor1 wall} + $w create line 725 137 725 129 -fill $color -tags {floor1 wall} + $w create line 514 254 514 175 -fill $color -tags {floor1 wall} + $w create line 496 175 514 175 -fill $color -tags {floor1 wall} + $w create line 502 175 502 162 -fill $color -tags {floor1 wall} + $w create line 475 166 475 162 -fill $color -tags {floor1 wall} + $w create line 496 176 496 175 -fill $color -tags {floor1 wall} + $w create line 491 189 496 189 -fill $color -tags {floor1 wall} + $w create line 491 205 491 189 -fill $color -tags {floor1 wall} + $w create line 487 238 475 238 -fill $color -tags {floor1 wall} + $w create line 487 240 487 238 -fill $color -tags {floor1 wall} + $w create line 487 252 487 254 -fill $color -tags {floor1 wall} + $w create line 315 133 304 133 -fill $color -tags {floor1 wall} + $w create line 256 133 280 133 -fill $color -tags {floor1 wall} + $w create line 78 247 270 247 -fill $color -tags {floor1 wall} + $w create line 307 247 294 247 -fill $color -tags {floor1 wall} + $w create line 214 133 232 133 -fill $color -tags {floor1 wall} + $w create line 217 247 217 266 -fill $color -tags {floor1 wall} + $w create line 217 309 217 291 -fill $color -tags {floor1 wall} + $w create line 217 309 172 309 -fill $color -tags {floor1 wall} + $w create line 154 309 148 309 -fill $color -tags {floor1 wall} + $w create line 175 300 175 309 -fill $color -tags {floor1 wall} + $w create line 151 300 175 300 -fill $color -tags {floor1 wall} + $w create line 151 247 151 309 -fill $color -tags {floor1 wall} + $w create line 78 237 78 265 -fill $color -tags {floor1 wall} + $w create line 78 286 78 309 -fill $color -tags {floor1 wall} + $w create line 106 309 78 309 -fill $color -tags {floor1 wall} + $w create line 130 309 125 309 -fill $color -tags {floor1 wall} + $w create line 99 309 99 247 -fill $color -tags {floor1 wall} + $w create line 127 299 99 299 -fill $color -tags {floor1 wall} + $w create line 127 309 127 299 -fill $color -tags {floor1 wall} + $w create line 155 191 137 191 -fill $color -tags {floor1 wall} + $w create line 137 169 137 191 -fill $color -tags {floor1 wall} + $w create line 78 171 78 169 -fill $color -tags {floor1 wall} + $w create line 78 190 78 218 -fill $color -tags {floor1 wall} + $w create line 86 192 86 169 -fill $color -tags {floor1 wall} + $w create line 86 192 78 192 -fill $color -tags {floor1 wall} + $w create line 52 301 3 301 -fill $color -tags {floor1 wall} + $w create line 52 286 52 301 -fill $color -tags {floor1 wall} + $w create line 52 252 3 252 -fill $color -tags {floor1 wall} + $w create line 52 203 3 203 -fill $color -tags {floor1 wall} + $w create line 3 156 52 156 -fill $color -tags {floor1 wall} + $w create line 8 25 8 114 -fill $color -tags {floor1 wall} + $w create line 63 114 3 114 -fill $color -tags {floor1 wall} + $w create line 75 114 97 114 -fill $color -tags {floor1 wall} + $w create line 108 114 129 114 -fill $color -tags {floor1 wall} + $w create line 129 114 129 89 -fill $color -tags {floor1 wall} + $w create line 52 114 52 128 -fill $color -tags {floor1 wall} + $w create line 132 89 88 89 -fill $color -tags {floor1 wall} + $w create line 88 25 88 89 -fill $color -tags {floor1 wall} + $w create line 88 114 88 89 -fill $color -tags {floor1 wall} + $w create line 218 89 144 89 -fill $color -tags {floor1 wall} + $w create line 147 111 147 129 -fill $color -tags {floor1 wall} + $w create line 162 111 147 111 -fill $color -tags {floor1 wall} + $w create line 162 109 162 111 -fill $color -tags {floor1 wall} + $w create line 162 96 162 89 -fill $color -tags {floor1 wall} + $w create line 218 89 218 94 -fill $color -tags {floor1 wall} + $w create line 218 89 218 119 -fill $color -tags {floor1 wall} + $w create line 8 25 88 25 -fill $color -tags {floor1 wall} + $w create line 258 337 258 328 -fill $color -tags {floor1 wall} + $w create line 113 129 96 129 -fill $color -tags {floor1 wall} + $w create line 302 355 258 355 -fill $color -tags {floor1 wall} + $w create line 386 104 386 129 -fill $color -tags {floor1 wall} + $w create line 377 100 386 104 -fill $color -tags {floor1 wall} + $w create line 365 94 377 100 -fill $color -tags {floor1 wall} + $w create line 350 83 365 94 -fill $color -tags {floor1 wall} + $w create line 337 70 350 83 -fill $color -tags {floor1 wall} + $w create line 337 70 323 56 -fill $color -tags {floor1 wall} + $w create line 312 49 323 56 -fill $color -tags {floor1 wall} + $w create line 295 40 312 49 -fill $color -tags {floor1 wall} + $w create line 282 37 295 40 -fill $color -tags {floor1 wall} + $w create line 260 34 282 37 -fill $color -tags {floor1 wall} + $w create line 253 34 260 34 -fill $color -tags {floor1 wall} + $w create line 386 128 386 104 -fill $color -tags {floor1 wall} + $w create line 113 152 156 152 -fill $color -tags {floor1 wall} + $w create line 113 152 156 152 -fill $color -tags {floor1 wall} + $w create line 113 152 113 129 -fill $color -tags {floor1 wall} +} + +# fg2 -- +# This procedure represents part of the floorplan database. When +# invoked, it instantiates the foreground information for the second +# floor (office outlines and numbers). +# +# Arguments: +# w - The canvas window. +# color - Color to use for drawing foreground information. + +proc fg2 {w color} { + global floorLabels floorItems + set i [$w create polygon 748 188 755 188 755 205 758 205 758 222 800 222 800 168 748 168 -fill {} -tags {floor2 room}] + set floorLabels($i) 238 + set {floorItems(238)} $i + $w create text 774 195 -text 238 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 726 188 746 188 746 166 800 166 800 131 726 131 -fill {} -tags {floor2 room}] + set floorLabels($i) 237 + set {floorItems(237)} $i + $w create text 763 148.5 -text 237 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 497 187 497 204 559 204 559 324 641 324 643 324 643 291 641 291 641 205 696 205 696 291 694 291 694 314 715 314 715 291 715 205 755 205 755 190 724 190 724 187 -fill {} -tags {floor2 room}] + set floorLabels($i) 246 + set {floorItems(246)} $i + $w create text 600 264 -text 246 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 694 279 643 279 643 314 694 314 -fill {} -tags {floor2 room}] + set floorLabels($i) 247 + set {floorItems(247)} $i + $w create text 668.5 296.5 -text 247 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 232 250 308 250 308 242 339 242 339 246 397 246 397 255 476 255 476 250 482 250 559 250 559 274 482 274 482 278 396 278 396 274 232 274 -fill {} -tags {floor2 room}] + set floorLabels($i) 202 + set {floorItems(202)} $i + $w create text 285.5 260 -text 202 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 53 228 53 338 176 338 233 338 233 196 306 196 306 180 175 180 175 169 156 169 156 196 176 196 176 228 -fill {} -tags {floor2 room}] + set floorLabels($i) 206 + set {floorItems(206)} $i + $w create text 143 267 -text 206 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 51 277 6 277 6 338 51 338 -fill {} -tags {floor2 room}] + set floorLabels($i) 212 + set {floorItems(212)} $i + $w create text 28.5 307.5 -text 212 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 557 276 486 276 486 309 510 309 510 325 557 325 -fill {} -tags {floor2 room}] + set floorLabels($i) 245 + set {floorItems(245)} $i + $w create text 521.5 300.5 -text 245 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 560 389 599 389 599 326 560 326 -fill {} -tags {floor2 room}] + set floorLabels($i) 244 + set {floorItems(244)} $i + $w create text 579.5 357.5 -text 244 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 601 389 601 326 643 326 643 389 -fill {} -tags {floor2 room}] + set floorLabels($i) 243 + set {floorItems(243)} $i + $w create text 622 357.5 -text 243 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 688 316 645 316 645 365 688 365 -fill {} -tags {floor2 room}] + set floorLabels($i) 242 + set {floorItems(242)} $i + $w create text 666.5 340.5 -text 242 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 802 367 759 367 759 226 802 226 -fill {} -tags {floor2 room}] + set floorLabels($i) {Barbecue Deck} + set {floorItems(Barbecue Deck)} $i + $w create text 780.5 296.5 -text {Barbecue Deck} -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 755 262 755 314 717 314 717 262 -fill {} -tags {floor2 room}] + set floorLabels($i) 240 + set {floorItems(240)} $i + $w create text 736 288 -text 240 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 755 316 689 316 689 365 755 365 -fill {} -tags {floor2 room}] + set floorLabels($i) 241 + set {floorItems(241)} $i + $w create text 722 340.5 -text 241 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 755 206 717 206 717 261 755 261 -fill {} -tags {floor2 room}] + set floorLabels($i) 239 + set {floorItems(239)} $i + $w create text 736 233.5 -text 239 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 695 277 643 277 643 206 695 206 -fill {} -tags {floor2 room}] + set floorLabels($i) 248 + set {floorItems(248)} $i + $w create text 669 241.5 -text 248 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 676 135 676 185 724 185 724 135 -fill {} -tags {floor2 room}] + set floorLabels($i) 236 + set {floorItems(236)} $i + $w create text 700 160 -text 236 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 675 135 635 135 635 145 628 145 628 185 675 185 -fill {} -tags {floor2 room}] + set floorLabels($i) 235 + set {floorItems(235)} $i + $w create text 651.5 160 -text 235 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 626 143 633 143 633 135 572 135 572 143 579 143 579 185 626 185 -fill {} -tags {floor2 room}] + set floorLabels($i) 234 + set {floorItems(234)} $i + $w create text 606 160 -text 234 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 557 135 571 135 571 145 578 145 578 185 527 185 527 131 557 131 -fill {} -tags {floor2 room}] + set floorLabels($i) 233 + set {floorItems(233)} $i + $w create text 552.5 158 -text 233 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 476 249 557 249 557 205 476 205 -fill {} -tags {floor2 room}] + set floorLabels($i) 230 + set {floorItems(230)} $i + $w create text 516.5 227 -text 230 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 476 164 486 164 486 131 525 131 525 185 476 185 -fill {} -tags {floor2 room}] + set floorLabels($i) 232 + set {floorItems(232)} $i + $w create text 500.5 158 -text 232 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 476 186 495 186 495 204 476 204 -fill {} -tags {floor2 room}] + set floorLabels($i) 229 + set {floorItems(229)} $i + $w create text 485.5 195 -text 229 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 474 207 409 207 409 187 399 187 399 164 474 164 -fill {} -tags {floor2 room}] + set floorLabels($i) 227 + set {floorItems(227)} $i + $w create text 436.5 185.5 -text 227 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 399 228 399 253 474 253 474 209 409 209 409 228 -fill {} -tags {floor2 room}] + set floorLabels($i) 228 + set {floorItems(228)} $i + $w create text 436.5 231 -text 228 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 397 246 397 226 407 226 407 189 377 189 377 246 -fill {} -tags {floor2 room}] + set floorLabels($i) 226 + set {floorItems(226)} $i + $w create text 392 217.5 -text 226 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 377 169 316 169 316 131 397 131 397 188 377 188 -fill {} -tags {floor2 room}] + set floorLabels($i) 225 + set {floorItems(225)} $i + $w create text 356.5 150 -text 225 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 234 198 306 198 306 249 234 249 -fill {} -tags {floor2 room}] + set floorLabels($i) 224 + set {floorItems(224)} $i + $w create text 270 223.5 -text 224 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 270 179 306 179 306 170 314 170 314 135 270 135 -fill {} -tags {floor2 room}] + set floorLabels($i) 223 + set {floorItems(223)} $i + $w create text 292 157 -text 223 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 268 179 221 179 221 135 268 135 -fill {} -tags {floor2 room}] + set floorLabels($i) 222 + set {floorItems(222)} $i + $w create text 244.5 157 -text 222 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 177 179 219 179 219 135 177 135 -fill {} -tags {floor2 room}] + set floorLabels($i) 221 + set {floorItems(221)} $i + $w create text 198 157 -text 221 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 299 327 349 327 349 284 341 284 341 276 299 276 -fill {} -tags {floor2 room}] + set floorLabels($i) 204 + set {floorItems(204)} $i + $w create text 324 301.5 -text 204 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 234 276 297 276 297 327 257 327 257 338 234 338 -fill {} -tags {floor2 room}] + set floorLabels($i) 205 + set {floorItems(205)} $i + $w create text 265.5 307 -text 205 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 256 385 256 340 212 340 212 385 -fill {} -tags {floor2 room}] + set floorLabels($i) 207 + set {floorItems(207)} $i + $w create text 234 362.5 -text 207 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 210 340 164 340 164 385 210 385 -fill {} -tags {floor2 room}] + set floorLabels($i) 208 + set {floorItems(208)} $i + $w create text 187 362.5 -text 208 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 115 340 162 340 162 385 115 385 -fill {} -tags {floor2 room}] + set floorLabels($i) 209 + set {floorItems(209)} $i + $w create text 138.5 362.5 -text 209 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 89 228 89 156 53 156 53 228 -fill {} -tags {floor2 room}] + set floorLabels($i) 217 + set {floorItems(217)} $i + $w create text 71 192 -text 217 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 89 169 97 169 97 190 89 190 -fill {} -tags {floor2 room}] + set floorLabels($i) 217A + set {floorItems(217A)} $i + $w create text 93 179.5 -text 217A -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 89 156 89 168 95 168 95 135 53 135 53 156 -fill {} -tags {floor2 room}] + set floorLabels($i) 216 + set {floorItems(216)} $i + $w create text 71 145.5 -text 216 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 51 179 51 135 6 135 6 179 -fill {} -tags {floor2 room}] + set floorLabels($i) 215 + set {floorItems(215)} $i + $w create text 28.5 157 -text 215 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 51 227 6 227 6 180 51 180 -fill {} -tags {floor2 room}] + set floorLabels($i) 214 + set {floorItems(214)} $i + $w create text 28.5 203.5 -text 214 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 51 275 6 275 6 229 51 229 -fill {} -tags {floor2 room}] + set floorLabels($i) 213 + set {floorItems(213)} $i + $w create text 28.5 252 -text 213 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 114 340 67 340 67 385 114 385 -fill {} -tags {floor2 room}] + set floorLabels($i) 210 + set {floorItems(210)} $i + $w create text 90.5 362.5 -text 210 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 59 389 59 385 65 385 65 340 1 340 1 389 -fill {} -tags {floor2 room}] + set floorLabels($i) 211 + set {floorItems(211)} $i + $w create text 33 364.5 -text 211 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 393 309 350 309 350 282 342 282 342 276 393 276 -fill {} -tags {floor2 room}] + set floorLabels($i) 203 + set {floorItems(203)} $i + $w create text 367.5 292.5 -text 203 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 99 191 91 191 91 226 174 226 174 198 154 198 154 192 109 192 109 169 99 169 -fill {} -tags {floor2 room}] + set floorLabels($i) 220 + set {floorItems(220)} $i + $w create text 132.5 208.5 -text 220 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 339 205 307 205 307 171 339 171 -fill {} -tags {floor2 room}] + set floorLabels($i) {Priv Lift2} + set {floorItems(Priv Lift2)} $i + $w create text 323 188 -text {Priv Lift2} -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 307 240 339 240 339 206 307 206 -fill {} -tags {floor2 room}] + set floorLabels($i) {Pub Lift 2} + set {floorItems(Pub Lift 2)} $i + $w create text 323 223 -text {Pub Lift 2} -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 175 168 97 168 97 131 175 131 -fill {} -tags {floor2 room}] + set floorLabels($i) 218 + set {floorItems(218)} $i + $w create text 136 149.5 -text 218 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 154 191 111 191 111 169 154 169 -fill {} -tags {floor2 room}] + set floorLabels($i) 219 + set {floorItems(219)} $i + $w create text 132.5 180 -text 219 -fill $color -anchor c -tags {floor2 label} + set i [$w create polygon 375 246 375 172 341 172 341 246 -fill {} -tags {floor2 room}] + set floorLabels($i) 201 + set {floorItems(201)} $i + $w create text 358 209 -text 201 -fill $color -anchor c -tags {floor2 label} + $w create line 641 186 678 186 -fill $color -tags {floor2 wall} + $w create line 757 350 757 367 -fill $color -tags {floor2 wall} + $w create line 634 133 634 144 -fill $color -tags {floor2 wall} + $w create line 634 144 627 144 -fill $color -tags {floor2 wall} + $w create line 572 133 572 144 -fill $color -tags {floor2 wall} + $w create line 572 144 579 144 -fill $color -tags {floor2 wall} + $w create line 398 129 398 162 -fill $color -tags {floor2 wall} + $w create line 174 197 175 197 -fill $color -tags {floor2 wall} + $w create line 175 197 175 227 -fill $color -tags {floor2 wall} + $w create line 757 206 757 221 -fill $color -tags {floor2 wall} + $w create line 396 188 408 188 -fill $color -tags {floor2 wall} + $w create line 727 189 725 189 -fill $color -tags {floor2 wall} + $w create line 747 167 802 167 -fill $color -tags {floor2 wall} + $w create line 747 167 747 189 -fill $color -tags {floor2 wall} + $w create line 755 189 739 189 -fill $color -tags {floor2 wall} + $w create line 769 224 757 224 -fill $color -tags {floor2 wall} + $w create line 802 224 802 129 -fill $color -tags {floor2 wall} + $w create line 802 129 725 129 -fill $color -tags {floor2 wall} + $w create line 725 189 725 129 -fill $color -tags {floor2 wall} + $w create line 725 186 690 186 -fill $color -tags {floor2 wall} + $w create line 676 133 676 186 -fill $color -tags {floor2 wall} + $w create line 627 144 627 186 -fill $color -tags {floor2 wall} + $w create line 629 186 593 186 -fill $color -tags {floor2 wall} + $w create line 579 144 579 186 -fill $color -tags {floor2 wall} + $w create line 559 129 559 133 -fill $color -tags {floor2 wall} + $w create line 725 133 559 133 -fill $color -tags {floor2 wall} + $w create line 484 162 484 129 -fill $color -tags {floor2 wall} + $w create line 559 129 484 129 -fill $color -tags {floor2 wall} + $w create line 526 129 526 186 -fill $color -tags {floor2 wall} + $w create line 540 186 581 186 -fill $color -tags {floor2 wall} + $w create line 528 186 523 186 -fill $color -tags {floor2 wall} + $w create line 511 186 475 186 -fill $color -tags {floor2 wall} + $w create line 496 190 496 186 -fill $color -tags {floor2 wall} + $w create line 496 205 496 202 -fill $color -tags {floor2 wall} + $w create line 475 205 527 205 -fill $color -tags {floor2 wall} + $w create line 558 205 539 205 -fill $color -tags {floor2 wall} + $w create line 558 205 558 249 -fill $color -tags {floor2 wall} + $w create line 558 249 475 249 -fill $color -tags {floor2 wall} + $w create line 662 206 642 206 -fill $color -tags {floor2 wall} + $w create line 695 206 675 206 -fill $color -tags {floor2 wall} + $w create line 695 278 642 278 -fill $color -tags {floor2 wall} + $w create line 642 291 642 206 -fill $color -tags {floor2 wall} + $w create line 695 291 695 206 -fill $color -tags {floor2 wall} + $w create line 716 208 716 206 -fill $color -tags {floor2 wall} + $w create line 757 206 716 206 -fill $color -tags {floor2 wall} + $w create line 757 221 757 224 -fill $color -tags {floor2 wall} + $w create line 793 224 802 224 -fill $color -tags {floor2 wall} + $w create line 757 262 716 262 -fill $color -tags {floor2 wall} + $w create line 716 220 716 264 -fill $color -tags {floor2 wall} + $w create line 716 315 716 276 -fill $color -tags {floor2 wall} + $w create line 757 315 703 315 -fill $color -tags {floor2 wall} + $w create line 757 325 757 224 -fill $color -tags {floor2 wall} + $w create line 757 367 644 367 -fill $color -tags {floor2 wall} + $w create line 689 367 689 315 -fill $color -tags {floor2 wall} + $w create line 647 315 644 315 -fill $color -tags {floor2 wall} + $w create line 659 315 691 315 -fill $color -tags {floor2 wall} + $w create line 600 325 600 391 -fill $color -tags {floor2 wall} + $w create line 627 325 644 325 -fill $color -tags {floor2 wall} + $w create line 644 391 644 315 -fill $color -tags {floor2 wall} + $w create line 615 325 575 325 -fill $color -tags {floor2 wall} + $w create line 644 391 558 391 -fill $color -tags {floor2 wall} + $w create line 563 325 558 325 -fill $color -tags {floor2 wall} + $w create line 558 391 558 314 -fill $color -tags {floor2 wall} + $w create line 558 327 508 327 -fill $color -tags {floor2 wall} + $w create line 558 275 484 275 -fill $color -tags {floor2 wall} + $w create line 558 302 558 275 -fill $color -tags {floor2 wall} + $w create line 508 327 508 311 -fill $color -tags {floor2 wall} + $w create line 484 311 508 311 -fill $color -tags {floor2 wall} + $w create line 484 275 484 311 -fill $color -tags {floor2 wall} + $w create line 475 208 408 208 -fill $color -tags {floor2 wall} + $w create line 408 206 408 210 -fill $color -tags {floor2 wall} + $w create line 408 222 408 227 -fill $color -tags {floor2 wall} + $w create line 408 227 398 227 -fill $color -tags {floor2 wall} + $w create line 398 227 398 254 -fill $color -tags {floor2 wall} + $w create line 408 188 408 194 -fill $color -tags {floor2 wall} + $w create line 383 188 376 188 -fill $color -tags {floor2 wall} + $w create line 398 188 398 162 -fill $color -tags {floor2 wall} + $w create line 398 162 484 162 -fill $color -tags {floor2 wall} + $w create line 475 162 475 254 -fill $color -tags {floor2 wall} + $w create line 398 254 475 254 -fill $color -tags {floor2 wall} + $w create line 484 280 395 280 -fill $color -tags {floor2 wall} + $w create line 395 311 395 275 -fill $color -tags {floor2 wall} + $w create line 307 197 293 197 -fill $color -tags {floor2 wall} + $w create line 278 197 233 197 -fill $color -tags {floor2 wall} + $w create line 233 197 233 249 -fill $color -tags {floor2 wall} + $w create line 307 179 284 179 -fill $color -tags {floor2 wall} + $w create line 233 249 278 249 -fill $color -tags {floor2 wall} + $w create line 269 179 269 133 -fill $color -tags {floor2 wall} + $w create line 220 179 220 133 -fill $color -tags {floor2 wall} + $w create line 155 191 110 191 -fill $color -tags {floor2 wall} + $w create line 90 190 98 190 -fill $color -tags {floor2 wall} + $w create line 98 169 98 190 -fill $color -tags {floor2 wall} + $w create line 52 133 52 165 -fill $color -tags {floor2 wall} + $w create line 52 214 52 177 -fill $color -tags {floor2 wall} + $w create line 52 226 52 262 -fill $color -tags {floor2 wall} + $w create line 52 274 52 276 -fill $color -tags {floor2 wall} + $w create line 234 275 234 339 -fill $color -tags {floor2 wall} + $w create line 226 339 258 339 -fill $color -tags {floor2 wall} + $w create line 211 387 211 339 -fill $color -tags {floor2 wall} + $w create line 214 339 177 339 -fill $color -tags {floor2 wall} + $w create line 258 387 60 387 -fill $color -tags {floor2 wall} + $w create line 3 133 3 339 -fill $color -tags {floor2 wall} + $w create line 165 339 129 339 -fill $color -tags {floor2 wall} + $w create line 117 339 80 339 -fill $color -tags {floor2 wall} + $w create line 68 339 59 339 -fill $color -tags {floor2 wall} + $w create line 0 339 46 339 -fill $color -tags {floor2 wall} + $w create line 60 391 0 391 -fill $color -tags {floor2 wall} + $w create line 0 339 0 391 -fill $color -tags {floor2 wall} + $w create line 60 387 60 391 -fill $color -tags {floor2 wall} + $w create line 258 329 258 387 -fill $color -tags {floor2 wall} + $w create line 350 329 258 329 -fill $color -tags {floor2 wall} + $w create line 395 311 350 311 -fill $color -tags {floor2 wall} + $w create line 398 129 315 129 -fill $color -tags {floor2 wall} + $w create line 176 133 315 133 -fill $color -tags {floor2 wall} + $w create line 176 129 96 129 -fill $color -tags {floor2 wall} + $w create line 3 133 96 133 -fill $color -tags {floor2 wall} + $w create line 66 387 66 339 -fill $color -tags {floor2 wall} + $w create line 115 387 115 339 -fill $color -tags {floor2 wall} + $w create line 163 387 163 339 -fill $color -tags {floor2 wall} + $w create line 234 275 276 275 -fill $color -tags {floor2 wall} + $w create line 288 275 309 275 -fill $color -tags {floor2 wall} + $w create line 298 275 298 329 -fill $color -tags {floor2 wall} + $w create line 341 283 350 283 -fill $color -tags {floor2 wall} + $w create line 321 275 341 275 -fill $color -tags {floor2 wall} + $w create line 375 275 395 275 -fill $color -tags {floor2 wall} + $w create line 315 129 315 170 -fill $color -tags {floor2 wall} + $w create line 376 170 307 170 -fill $color -tags {floor2 wall} + $w create line 307 250 307 170 -fill $color -tags {floor2 wall} + $w create line 376 245 376 170 -fill $color -tags {floor2 wall} + $w create line 340 241 307 241 -fill $color -tags {floor2 wall} + $w create line 340 245 340 224 -fill $color -tags {floor2 wall} + $w create line 340 210 340 201 -fill $color -tags {floor2 wall} + $w create line 340 187 340 170 -fill $color -tags {floor2 wall} + $w create line 340 206 307 206 -fill $color -tags {floor2 wall} + $w create line 293 250 307 250 -fill $color -tags {floor2 wall} + $w create line 271 179 238 179 -fill $color -tags {floor2 wall} + $w create line 226 179 195 179 -fill $color -tags {floor2 wall} + $w create line 176 129 176 179 -fill $color -tags {floor2 wall} + $w create line 182 179 176 179 -fill $color -tags {floor2 wall} + $w create line 174 169 176 169 -fill $color -tags {floor2 wall} + $w create line 162 169 90 169 -fill $color -tags {floor2 wall} + $w create line 96 169 96 129 -fill $color -tags {floor2 wall} + $w create line 175 227 90 227 -fill $color -tags {floor2 wall} + $w create line 90 190 90 227 -fill $color -tags {floor2 wall} + $w create line 52 179 3 179 -fill $color -tags {floor2 wall} + $w create line 52 228 3 228 -fill $color -tags {floor2 wall} + $w create line 52 276 3 276 -fill $color -tags {floor2 wall} + $w create line 155 177 155 169 -fill $color -tags {floor2 wall} + $w create line 110 191 110 169 -fill $color -tags {floor2 wall} + $w create line 155 189 155 197 -fill $color -tags {floor2 wall} + $w create line 350 283 350 329 -fill $color -tags {floor2 wall} + $w create line 162 197 155 197 -fill $color -tags {floor2 wall} + $w create line 341 275 341 283 -fill $color -tags {floor2 wall} +} + +# fg3 -- +# This procedure represents part of the floorplan database. When +# invoked, it instantiates the foreground information for the third +# floor (office outlines and numbers). +# +# Arguments: +# w - The canvas window. +# color - Color to use for drawing foreground information. + +proc fg3 {w color} { + global floorLabels floorItems + set i [$w create polygon 89 228 89 180 70 180 70 228 -fill {} -tags {floor3 room}] + set floorLabels($i) 316 + set {floorItems(316)} $i + $w create text 79.5 204 -text 316 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 115 368 162 368 162 323 115 323 -fill {} -tags {floor3 room}] + set floorLabels($i) 309 + set {floorItems(309)} $i + $w create text 138.5 345.5 -text 309 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 164 323 164 368 211 368 211 323 -fill {} -tags {floor3 room}] + set floorLabels($i) 308 + set {floorItems(308)} $i + $w create text 187.5 345.5 -text 308 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 256 368 212 368 212 323 256 323 -fill {} -tags {floor3 room}] + set floorLabels($i) 307 + set {floorItems(307)} $i + $w create text 234 345.5 -text 307 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 244 276 297 276 297 327 260 327 260 321 244 321 -fill {} -tags {floor3 room}] + set floorLabels($i) 305 + set {floorItems(305)} $i + $w create text 270.5 301.5 -text 305 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 251 219 251 203 244 203 244 219 -fill {} -tags {floor3 room}] + set floorLabels($i) 324B + set {floorItems(324B)} $i + $w create text 247.5 211 -text 324B -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 251 249 244 249 244 232 251 232 -fill {} -tags {floor3 room}] + set floorLabels($i) 324A + set {floorItems(324A)} $i + $w create text 247.5 240.5 -text 324A -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 223 135 223 179 177 179 177 135 -fill {} -tags {floor3 room}] + set floorLabels($i) 320 + set {floorItems(320)} $i + $w create text 200 157 -text 320 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 114 368 114 323 67 323 67 368 -fill {} -tags {floor3 room}] + set floorLabels($i) 310 + set {floorItems(310)} $i + $w create text 90.5 345.5 -text 310 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 23 277 23 321 68 321 68 277 -fill {} -tags {floor3 room}] + set floorLabels($i) 312 + set {floorItems(312)} $i + $w create text 45.5 299 -text 312 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 23 229 68 229 68 275 23 275 -fill {} -tags {floor3 room}] + set floorLabels($i) 313 + set {floorItems(313)} $i + $w create text 45.5 252 -text 313 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 68 227 23 227 23 180 68 180 -fill {} -tags {floor3 room}] + set floorLabels($i) 314 + set {floorItems(314)} $i + $w create text 45.5 203.5 -text 314 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 95 179 95 135 23 135 23 179 -fill {} -tags {floor3 room}] + set floorLabels($i) 315 + set {floorItems(315)} $i + $w create text 59 157 -text 315 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 99 226 99 204 91 204 91 226 -fill {} -tags {floor3 room}] + set floorLabels($i) 316B + set {floorItems(316B)} $i + $w create text 95 215 -text 316B -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 91 202 99 202 99 180 91 180 -fill {} -tags {floor3 room}] + set floorLabels($i) 316A + set {floorItems(316A)} $i + $w create text 95 191 -text 316A -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 97 169 109 169 109 192 154 192 154 198 174 198 174 226 101 226 101 179 97 179 -fill {} -tags {floor3 room}] + set floorLabels($i) 319 + set {floorItems(319)} $i + $w create text 141.5 209 -text 319 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 65 368 58 368 58 389 1 389 1 333 23 333 23 323 65 323 -fill {} -tags {floor3 room}] + set floorLabels($i) 311 + set {floorItems(311)} $i + $w create text 29.5 361 -text 311 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 154 191 111 191 111 169 154 169 -fill {} -tags {floor3 room}] + set floorLabels($i) 318 + set {floorItems(318)} $i + $w create text 132.5 180 -text 318 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 175 168 97 168 97 131 175 131 -fill {} -tags {floor3 room}] + set floorLabels($i) 317 + set {floorItems(317)} $i + $w create text 136 149.5 -text 317 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 274 194 274 221 306 221 306 194 -fill {} -tags {floor3 room}] + set floorLabels($i) 323 + set {floorItems(323)} $i + $w create text 290 207.5 -text 323 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 306 222 274 222 274 249 306 249 -fill {} -tags {floor3 room}] + set floorLabels($i) 325 + set {floorItems(325)} $i + $w create text 290 235.5 -text 325 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 263 179 224 179 224 135 263 135 -fill {} -tags {floor3 room}] + set floorLabels($i) 321 + set {floorItems(321)} $i + $w create text 243.5 157 -text 321 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 314 169 306 169 306 192 273 192 264 181 264 135 314 135 -fill {} -tags {floor3 room}] + set floorLabels($i) 322 + set {floorItems(322)} $i + $w create text 293.5 163.5 -text 322 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 307 240 339 240 339 206 307 206 -fill {} -tags {floor3 room}] + set floorLabels($i) {Pub Lift3} + set {floorItems(Pub Lift3)} $i + $w create text 323 223 -text {Pub Lift3} -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 339 205 307 205 307 171 339 171 -fill {} -tags {floor3 room}] + set floorLabels($i) {Priv Lift3} + set {floorItems(Priv Lift3)} $i + $w create text 323 188 -text {Priv Lift3} -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 350 284 376 284 376 276 397 276 397 309 350 309 -fill {} -tags {floor3 room}] + set floorLabels($i) 303 + set {floorItems(303)} $i + $w create text 373.5 292.5 -text 303 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 272 203 272 249 252 249 252 230 244 230 244 221 252 221 252 203 -fill {} -tags {floor3 room}] + set floorLabels($i) 324 + set {floorItems(324)} $i + $w create text 262 226 -text 324 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 299 276 299 327 349 327 349 284 341 284 341 276 -fill {} -tags {floor3 room}] + set floorLabels($i) 304 + set {floorItems(304)} $i + $w create text 324 301.5 -text 304 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 375 246 375 172 341 172 341 246 -fill {} -tags {floor3 room}] + set floorLabels($i) 301 + set {floorItems(301)} $i + $w create text 358 209 -text 301 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 397 246 377 246 377 185 397 185 -fill {} -tags {floor3 room}] + set floorLabels($i) 327 + set {floorItems(327)} $i + $w create text 387 215.5 -text 327 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 316 131 316 169 377 169 377 185 397 185 397 131 -fill {} -tags {floor3 room}] + set floorLabels($i) 326 + set {floorItems(326)} $i + $w create text 356.5 150 -text 326 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 308 251 242 251 242 274 342 274 342 282 375 282 375 274 397 274 397 248 339 248 339 242 308 242 -fill {} -tags {floor3 room}] + set floorLabels($i) 302 + set {floorItems(302)} $i + $w create text 319.5 261 -text 302 -fill $color -anchor c -tags {floor3 label} + set i [$w create polygon 70 321 242 321 242 200 259 200 259 203 272 203 272 193 263 180 242 180 175 180 175 169 156 169 156 196 177 196 177 228 107 228 70 228 70 275 107 275 107 248 160 248 160 301 107 301 107 275 70 275 -fill {} -tags {floor3 room}] + set floorLabels($i) 306 + set {floorItems(306)} $i + $w create text 200.5 284.5 -text 306 -fill $color -anchor c -tags {floor3 label} + $w create line 341 275 341 283 -fill $color -tags {floor3 wall} + $w create line 162 197 155 197 -fill $color -tags {floor3 wall} + $w create line 396 247 399 247 -fill $color -tags {floor3 wall} + $w create line 399 129 399 311 -fill $color -tags {floor3 wall} + $w create line 258 202 243 202 -fill $color -tags {floor3 wall} + $w create line 350 283 350 329 -fill $color -tags {floor3 wall} + $w create line 251 231 243 231 -fill $color -tags {floor3 wall} + $w create line 243 220 251 220 -fill $color -tags {floor3 wall} + $w create line 243 250 243 202 -fill $color -tags {floor3 wall} + $w create line 155 197 155 190 -fill $color -tags {floor3 wall} + $w create line 110 192 110 169 -fill $color -tags {floor3 wall} + $w create line 155 192 110 192 -fill $color -tags {floor3 wall} + $w create line 155 177 155 169 -fill $color -tags {floor3 wall} + $w create line 176 197 176 227 -fill $color -tags {floor3 wall} + $w create line 69 280 69 274 -fill $color -tags {floor3 wall} + $w create line 21 276 69 276 -fill $color -tags {floor3 wall} + $w create line 69 262 69 226 -fill $color -tags {floor3 wall} + $w create line 21 228 69 228 -fill $color -tags {floor3 wall} + $w create line 21 179 75 179 -fill $color -tags {floor3 wall} + $w create line 69 179 69 214 -fill $color -tags {floor3 wall} + $w create line 90 220 90 227 -fill $color -tags {floor3 wall} + $w create line 90 204 90 202 -fill $color -tags {floor3 wall} + $w create line 90 203 100 203 -fill $color -tags {floor3 wall} + $w create line 90 187 90 179 -fill $color -tags {floor3 wall} + $w create line 90 227 176 227 -fill $color -tags {floor3 wall} + $w create line 100 179 100 227 -fill $color -tags {floor3 wall} + $w create line 100 179 87 179 -fill $color -tags {floor3 wall} + $w create line 96 179 96 129 -fill $color -tags {floor3 wall} + $w create line 162 169 96 169 -fill $color -tags {floor3 wall} + $w create line 173 169 176 169 -fill $color -tags {floor3 wall} + $w create line 182 179 176 179 -fill $color -tags {floor3 wall} + $w create line 176 129 176 179 -fill $color -tags {floor3 wall} + $w create line 195 179 226 179 -fill $color -tags {floor3 wall} + $w create line 224 133 224 179 -fill $color -tags {floor3 wall} + $w create line 264 179 264 133 -fill $color -tags {floor3 wall} + $w create line 238 179 264 179 -fill $color -tags {floor3 wall} + $w create line 273 207 273 193 -fill $color -tags {floor3 wall} + $w create line 273 235 273 250 -fill $color -tags {floor3 wall} + $w create line 273 224 273 219 -fill $color -tags {floor3 wall} + $w create line 273 193 307 193 -fill $color -tags {floor3 wall} + $w create line 273 222 307 222 -fill $color -tags {floor3 wall} + $w create line 273 250 307 250 -fill $color -tags {floor3 wall} + $w create line 384 247 376 247 -fill $color -tags {floor3 wall} + $w create line 340 206 307 206 -fill $color -tags {floor3 wall} + $w create line 340 187 340 170 -fill $color -tags {floor3 wall} + $w create line 340 210 340 201 -fill $color -tags {floor3 wall} + $w create line 340 247 340 224 -fill $color -tags {floor3 wall} + $w create line 340 241 307 241 -fill $color -tags {floor3 wall} + $w create line 376 247 376 170 -fill $color -tags {floor3 wall} + $w create line 307 250 307 170 -fill $color -tags {floor3 wall} + $w create line 376 170 307 170 -fill $color -tags {floor3 wall} + $w create line 315 129 315 170 -fill $color -tags {floor3 wall} + $w create line 376 283 366 283 -fill $color -tags {floor3 wall} + $w create line 376 283 376 275 -fill $color -tags {floor3 wall} + $w create line 399 275 376 275 -fill $color -tags {floor3 wall} + $w create line 341 275 320 275 -fill $color -tags {floor3 wall} + $w create line 341 283 350 283 -fill $color -tags {floor3 wall} + $w create line 298 275 298 329 -fill $color -tags {floor3 wall} + $w create line 308 275 298 275 -fill $color -tags {floor3 wall} + $w create line 243 322 243 275 -fill $color -tags {floor3 wall} + $w create line 243 275 284 275 -fill $color -tags {floor3 wall} + $w create line 258 322 226 322 -fill $color -tags {floor3 wall} + $w create line 212 370 212 322 -fill $color -tags {floor3 wall} + $w create line 214 322 177 322 -fill $color -tags {floor3 wall} + $w create line 163 370 163 322 -fill $color -tags {floor3 wall} + $w create line 165 322 129 322 -fill $color -tags {floor3 wall} + $w create line 84 322 117 322 -fill $color -tags {floor3 wall} + $w create line 71 322 64 322 -fill $color -tags {floor3 wall} + $w create line 115 322 115 370 -fill $color -tags {floor3 wall} + $w create line 66 322 66 370 -fill $color -tags {floor3 wall} + $w create line 52 322 21 322 -fill $color -tags {floor3 wall} + $w create line 21 331 0 331 -fill $color -tags {floor3 wall} + $w create line 21 331 21 133 -fill $color -tags {floor3 wall} + $w create line 96 133 21 133 -fill $color -tags {floor3 wall} + $w create line 176 129 96 129 -fill $color -tags {floor3 wall} + $w create line 315 133 176 133 -fill $color -tags {floor3 wall} + $w create line 315 129 399 129 -fill $color -tags {floor3 wall} + $w create line 399 311 350 311 -fill $color -tags {floor3 wall} + $w create line 350 329 258 329 -fill $color -tags {floor3 wall} + $w create line 258 322 258 370 -fill $color -tags {floor3 wall} + $w create line 60 370 258 370 -fill $color -tags {floor3 wall} + $w create line 60 370 60 391 -fill $color -tags {floor3 wall} + $w create line 0 391 0 331 -fill $color -tags {floor3 wall} + $w create line 60 391 0 391 -fill $color -tags {floor3 wall} + $w create line 307 250 307 242 -fill $color -tags {floor3 wall} + $w create line 273 250 307 250 -fill $color -tags {floor3 wall} + $w create line 258 250 243 250 -fill $color -tags {floor3 wall} +} + +# Below is the "main program" that creates the floorplan demonstration. + +set w .floor +global c tk_library currentRoom colors activeFloor +catch {destroy $w} +toplevel $w +wm title $w "Floorplan Canvas Demonstration" +wm iconname $w "Floorplan" +wm geometry $w +20+20 +wm minsize $w 100 100 + +label $w.msg -font $font -wraplength 8i -justify left -text "This window contains a canvas widget showing the floorplan of Digital Equipment Corporation's Western Research Laboratory. It has three levels. At any given time one of the levels is active, meaning that you can see its room structure. To activate a level, click the left mouse button anywhere on it. As the mouse moves over the active level, the room under the mouse lights up and its room number appears in the \"Room:\" entry. You can also type a room number in the entry and the room will light up." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +set f [frame $w.frame] +pack $f -side top -fill both -expand yes +set h [scrollbar $f.hscroll -highlightthickness 0 -orient horizontal] +set v [scrollbar $f.vscroll -highlightthickness 0 -orient vertical] +set f1 [frame $f.f1 -bd 2 -relief sunken] +set c [canvas $f1.c -width 900 -height 500 -borderwidth 0 \ + -highlightthickness 0 -xscrollcommand "$h set" -yscrollcommand "$v set"] +pack $c -expand yes -fill both +grid $f1 -padx 1 -pady 1 \ + -row 0 -column 0 -rowspan 1 -columnspan 1 -sticky news +grid $v -padx 1 -pady 1 \ + -row 0 -column 1 -rowspan 1 -columnspan 1 -sticky news +grid $h -padx 1 -pady 1 \ + -row 1 -column 0 -rowspan 1 -columnspan 1 -sticky news +grid rowconfig $f 0 -weight 1 -minsize 0 +grid columnconfig $f 0 -weight 1 -minsize 0 +pack $f -expand yes -fill both -padx 1 -pady 1 + +$v config -command "$c yview" +$h config -command "$c xview" + +# Create an entry for displaying and typing in current room. + +entry $c.entry -width 10 -relief sunken -bd 2 -textvariable currentRoom + +# Choose colors, then fill in the floorplan. + +if {[winfo depth $c] > 1} { + set colors(bg1) #a9c1da + set colors(outline1) #77889a + set colors(bg2) #9ab0c6 + set colors(outline2) #687786 + set colors(bg3) #8ba0b3 + set colors(outline3) #596673 + set colors(offices) Black + set colors(active) #c4d1df +} else { + set colors(bg1) white + set colors(outline1) black + set colors(bg2) white + set colors(outline2) black + set colors(bg3) white + set colors(outline3) black + set colors(offices) Black + set colors(active) black +} +set activeFloor "" +floorDisplay $c 3 + +# Set up event bindings for canvas: + +$c bind floor1 <1> "floorDisplay $c 1" +$c bind floor2 <1> "floorDisplay $c 2" +$c bind floor3 <1> "floorDisplay $c 3" +$c bind room <Enter> "newRoom $c" +$c bind room <Leave> {set currentRoom ""} +bind $c <2> "$c scan mark %x %y" +bind $c <B2-Motion> "$c scan dragto %x %y" +bind $c <Destroy> "unset currentRoom" +set currentRoom "" +trace variable currentRoom w "roomChanged $c" diff --git a/library/demos/form.tcl b/library/demos/form.tcl new file mode 100644 index 0000000..3c43497 --- /dev/null +++ b/library/demos/form.tcl @@ -0,0 +1,40 @@ +# form.tcl -- +# +# This demonstration script creates a simple form with a bunch +# of entry widgets. +# +# SCCS: @(#) form.tcl 1.5 97/03/02 16:23:48 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .form +catch {destroy $w} +toplevel $w +wm title $w "Form Demonstration" +wm iconname $w "form" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "This window contains a simple form where you can type in the various entries and use tabs to move circularly between the entries." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +foreach i {f1 f2 f3 f4 f5} { + frame $w.$i -bd 2 + entry $w.$i.entry -relief sunken -width 40 + label $w.$i.label + pack $w.$i.entry -side right + pack $w.$i.label -side left +} +$w.f1.label config -text Name: +$w.f2.label config -text Address: +$w.f5.label config -text Phone: +pack $w.msg $w.f1 $w.f2 $w.f3 $w.f4 $w.f5 -side top -fill x +bind $w <Return> "destroy $w" +focus $w.f1.entry diff --git a/library/demos/hello b/library/demos/hello new file mode 100644 index 0000000..0fa5d05 --- /dev/null +++ b/library/demos/hello @@ -0,0 +1,18 @@ +#!/bin/sh +# the next line restarts using wish \ +exec wish "$0" "$@" + +# hello -- +# Simple Tk script to create a button that prints "Hello, world". +# Click on the button to terminate the program. +# +# SCCS: @(#) hello 1.6 96/02/16 10:49:18 +# +# The first line below creates the button, and the second line +# asks the packer to shrink-wrap the application's main window +# around the button. + +button .hello -text "Hello, world" -command { + puts stdout "Hello, world"; destroy . +} +pack .hello diff --git a/library/demos/hscale.tcl b/library/demos/hscale.tcl new file mode 100644 index 0000000..a760586 --- /dev/null +++ b/library/demos/hscale.tcl @@ -0,0 +1,47 @@ +# hscale.tcl -- +# +# This demonstration script shows an example with a horizontal scale. +# +# SCCS: @(#) hscale.tcl 1.4 97/03/02 16:24:01 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .hscale +catch {destroy $w} +toplevel $w +wm title $w "Horizontal Scale Demonstration" +wm iconname $w "hscale" +positionWindow $w + +label $w.msg -font $font -wraplength 3.5i -justify left -text "An arrow and a horizontal scale are displayed below. If you click or drag mouse button 1 in the scale, you can change the length of the arrow." +pack $w.msg -side top -padx .5c + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.frame -borderwidth 10 +pack $w.frame -side top -fill x + +canvas $w.frame.canvas -width 50 -height 50 -bd 0 -highlightthickness 0 +$w.frame.canvas create polygon 0 0 1 1 2 2 -fill DeepSkyBlue3 -tags poly +$w.frame.canvas create line 0 0 1 1 2 2 0 0 -fill black -tags line +scale $w.frame.scale -orient horizontal -length 284 -from 0 -to 250 \ + -command "setWidth $w.frame.canvas" -tickinterval 50 +pack $w.frame.canvas -side top -expand yes -anchor s -fill x -padx 15 +pack $w.frame.scale -side bottom -expand yes -anchor n +$w.frame.scale set 75 + +proc setWidth {w width} { + incr width 21 + set x2 [expr $width - 30] + if {$x2 < 21} { + set x2 21 + } + $w coords poly 20 15 20 35 $x2 35 $x2 45 $width 25 $x2 5 $x2 15 20 15 + $w coords line 20 15 20 35 $x2 35 $x2 45 $width 25 $x2 5 $x2 15 20 15 +} diff --git a/library/demos/icon.tcl b/library/demos/icon.tcl new file mode 100644 index 0000000..1c98fd4 --- /dev/null +++ b/library/demos/icon.tcl @@ -0,0 +1,52 @@ +# icon.tcl -- +# +# This demonstration script creates a toplevel window containing +# buttons that display bitmaps instead of text. +# +# SCCS: @(#) icon.tcl 1.8 97/03/02 16:24:19 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .icon +catch {destroy $w} +toplevel $w +wm title $w "Iconic Button Demonstration" +wm iconname $w "icon" +positionWindow $w + +label $w.msg -font $font -wraplength 5i -justify left -text "This window shows three ways of using bitmaps or images in radiobuttons and checkbuttons. On the left are two radiobuttons, each of which displays a bitmap and an indicator. In the middle is a checkbutton that displays a different image depending on whether it is selected or not. On the right is a checkbutton that displays a single bitmap but changes its background color to indicate whether or not it is selected." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +image create bitmap flagup \ + -file [file join $tk_library demos images flagup.bmp] \ + -maskfile [file join $tk_library demos images flagup.bmp] +image create bitmap flagdown \ + -file [file join $tk_library demos images flagdown.bmp] \ + -maskfile [file join $tk_library demos images flagdown.bmp] +frame $w.frame -borderwidth 10 +pack $w.frame -side top + +checkbutton $w.frame.b1 -image flagdown -selectimage flagup \ + -indicatoron 0 +$w.frame.b1 configure -selectcolor [$w.frame.b1 cget -background] +checkbutton $w.frame.b2 \ + -bitmap @[file join $tk_library demos images letters.bmp] \ + -indicatoron 0 -selectcolor SeaGreen1 +frame $w.frame.left +pack $w.frame.left $w.frame.b1 $w.frame.b2 -side left -expand yes -padx 5m + +radiobutton $w.frame.left.b3 \ + -bitmap @[file join $tk_library demos images letters.bmp] \ + -variable letters -value full +radiobutton $w.frame.left.b4 \ + -bitmap @[file join $tk_library demos images noletter.bmp] \ + -variable letters -value empty +pack $w.frame.left.b3 $w.frame.left.b4 -side top -expand yes diff --git a/library/demos/image1.tcl b/library/demos/image1.tcl new file mode 100644 index 0000000..a3b78db --- /dev/null +++ b/library/demos/image1.tcl @@ -0,0 +1,36 @@ +# image1.tcl -- +# +# This demonstration script displays two image widgets. +# +# SCCS: @(#) image1.tcl 1.6 97/03/02 16:24:35 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .image1 +catch {destroy $w} +toplevel $w +wm title $w "Image Demonstration #1" +wm iconname $w "Image1" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "This demonstration displays two images, each in a separate label widget." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +catch {image delete image1a} +image create photo image1a -file [file join $tk_library demos images earth.gif] +label $w.l1 -image image1a -bd 1 -relief sunken + +catch {image delete image1b} +image create photo image1b \ + -file [file join $tk_library demos images earthris.gif] +label $w.l2 -image image1b -bd 1 -relief sunken + +pack $w.l1 $w.l2 -side top -padx .5m -pady .5m diff --git a/library/demos/image2.tcl b/library/demos/image2.tcl new file mode 100644 index 0000000..badea14 --- /dev/null +++ b/library/demos/image2.tcl @@ -0,0 +1,80 @@ +# image2.tcl -- +# +# This demonstration script creates a simple collection of widgets +# that allow you to select and view images in a Tk label. +# +# SCCS: @(#) image2.tcl 1.9 97/03/02 16:24:48 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +# loadDir -- +# This procedure reloads the directory listbox from the directory +# named in the demo's entry. +# +# Arguments: +# w - Name of the toplevel window of the demo. + +proc loadDir w { + global dirName + + $w.f.list delete 0 end + foreach i [lsort [glob [file join $dirName *]]] { + $w.f.list insert end [file tail $i] + } +} + +# loadImage -- +# Given the name of the toplevel window of the demo and the mouse +# position, extracts the directory entry under the mouse and loads +# that file into a photo image for display. +# +# Arguments: +# w - Name of the toplevel window of the demo. +# x, y- Mouse position within the listbox. + +proc loadImage {w x y} { + global dirName + + set file [file join $dirName [$w.f.list get @$x,$y]] + image2a configure -file $file +} + +set w .image2 +catch {destroy $w} +toplevel $w +wm title $w "Image Demonstration #2" +wm iconname $w "Image2" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "This demonstration allows you to view images using a Tk \"photo\" image. First type a directory name in the listbox, then type Return to load the directory into the listbox. Then double-click on a file name in the listbox to see that image." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +label $w.dirLabel -text "Directory:" +set dirName [file join $tk_library demos images] +entry $w.dirName -width 30 -textvariable dirName +bind $w.dirName <Return> "loadDir $w" +frame $w.spacer1 -height 3m -width 20 +label $w.fileLabel -text "File:" +frame $w.f +pack $w.dirLabel $w.dirName $w.spacer1 $w.fileLabel $w.f -side top -anchor w + +listbox $w.f.list -width 20 -height 10 -yscrollcommand "$w.f.scroll set" +scrollbar $w.f.scroll -command "$w.f.list yview" +pack $w.f.list $w.f.scroll -side left -fill y -expand 1 +$w.f.list insert 0 earth.gif earthris.gif teapot.ppm +bind $w.f.list <Double-1> "loadImage $w %x %y" + +catch {image delete image2a} +image create photo image2a +frame $w.spacer2 -height 3m -width 20 +label $w.imageLabel -text "Image:" +label $w.image -image image2a +pack $w.spacer2 $w.imageLabel $w.image -side top -anchor w diff --git a/library/demos/images/earth.gif b/library/demos/images/earth.gif new file mode 100644 index 0000000..32d1328 --- /dev/null +++ b/library/demos/images/earth.gif @@ -0,0 +1,350 @@ +GIF87a@È÷ØÐÀ ( (( 00(88(88(@80@@0@H0@H8@80H@0HH0H88H@8HH8HP8HX8HH@HP@HX@H`@H80P@0P88P@8PH8PP8P@@PH@PP@PX@P`@PPHPXHP`HPhHP88X@8XH8XP8X@@XH@XP@XX@XHHXPHXXHX`HXhHXXPX`PXhPXpPXhXX@@`H@`P@`HH`PH`XH``H`PP`XP``P`hP`pP``X`hX`pX`xX`p``x``H@hHHhPHhXHh`HhPPhXPh`PhhPhpPhXXh`XhhXhpXhxXhh`hp`hx`h€`hxhh€hhˆhhPPpXPp`PpXXp`XphXppXph`pp`px`p€`pphpxhp€hpˆhphp€ppˆpppp˜ppxp˜xpPPxXXx`XxhXxh`xp`xx`xphxxhx€hxˆhxxpx€pxˆpxpx˜pxˆxxxx˜xx xx˜€x €x¨€xÀ€xh`€ph€xh€xp€€p€ˆp€€x€ˆx€x€˜x€ x€ˆ€€€€˜€€ €€¨€€˜ˆ€ ˆ€¨ˆ€°ˆ€€xˆˆxˆxˆˆ€ˆ€ˆ˜€ˆ €ˆ˜ˆˆ ˆˆ¨ˆˆ°ˆˆ ˆ¨ˆ°ˆ¸ˆ°˜ˆ˜ˆ ˆ¨ˆ ¨°¸¨˜°˜¸˜À˜ ˜¨˜°˜¨˜˜°˜˜¸˜˜À˜˜° ˜¸ ˜À ˜¸¨˜À¨˜°˜ ° ¸ À °¨ ¸¨ À¨ Ȩ È° ¸¨¨À¨¨È¨¨À°¨È°¨Ð°¨Ð¸¨È°°È¸°Ð¸°ÐÀ°ÐÀ¸ÐȸØȸØиØÈÀ,@Èþ0X@Áƒ
4@À B„:<¨ â
D|HACŒ+~l8`cÅ„D"GˆZœ óX€áÂ/¢ŒsÔ+Z̘ŒÙ¯_Àxñö«S`Uy¹ê´©0H|èÐ3ƒ +Òæ´ð€‚ηP¨à6gNâ.¨0¡‚ƒ&œµû€ï]›vžûÀ]t:FË6måÈoÙ +&lA‚e0\HÁÂhËi1DÀÀCÖb³Þðš5‡4`àÀAïßÀ9< 3áJ‹N¾,X¡ÌãC" ’€HŠ'À$Ðòù‚4þ|>¼À›9c‹xñ# +PÁš1Ö«×/¥IIíµJ/UøU}À,Õ”|ùñÒ‹+›Pâ„$xÐÁªEševYN, fqµµøESc$*†Wc˜¦!v—tÙ…VaT°–]T€ZeýÚµµfäl±m@›k¹epÛÁE)œ‡Æ5g%q9°\K©TÐDx9\•Ids$0ž•é%“vY +$'‡¦i@y„BË0Î0#ß5×8•+ªX¢J%†ªâ ,±0ƒÍ3Í#Œ€}2ÅÌ5Ø\CŸ}X5õ+œˆá‚d‰všigݨÓ`n)¶_þl±¨ã‰éè@¬.ºªZ·âEcZ¶òˆ4Ö•“lùXZh +dZÙÚkÄöšµ$Ù¤oRþ›. $Ñx5äDqyQṯTfC+UWæºûÐMäÉ$Ó¹kÒ„/h‰Ã ÐÒ4€6“é5¿´B¨%š´²¨'šdB!Ÿdœq,ÂÄŒ-Âtì 0ÆDÃÍ6Î`ãL0̼bU~¾øR/†¼ñ©±aX™Z8ù•“[;KXdgÅÊ@‹kqX†±KÁu|lŽ€1ít´®ÆZh§Z–óµ±U‹A¶ÖÒ–m¶äÖíoòûåq +µ´¸ed/™¹íQþÜo/@ÜMÊôJø"¤æxçæ$Paxà‚›ðâ3ÚTîLÅL3M4Ð3i+°ÔL+ª\‚q#§¤~Ê(¦|2Š,×RL5æ´“8åh³Í8¹góè3Î830¾€îp!^@…:Q€ÐI4oU_«MHÛ”V^Õæª]öEïLÁÖ¸R–V¬Ö,jÈ)lòÓ†-Jr+e¼ÑÍÞ0ÑÈKbÁÍë€l‚×rg¼°‹_Ï9@–ÊSž§Ià.ø%PŠU¤¢ÚðF9ÐAŽq„ðì@Ç5žAŒX ‚‚` +a F Nu8LÝ'шD|BþÛ0G9Úa;qpƒw&Ô3 ‘l<£¶ð,zñ +^PÂ<ð@OºÖÅÄ +/°Ê ‡–íh½úU¬œ§ª©5-G +Ð +ƒ •%ZðK͘•3×XlD[Úx¥Þè7tLÔä9çJŽ•Â7î`„Œœ¸Ä$§5ä9±Np’~!¨ä U¡ +XP£°‡0¨^°ò’XƒÔÀ†AxbHÄ#RwÃ~¢È…,„‘
n1ÜÇ7À[€ÜÈæ8²áŒf¬õYZ°¼fM3uq^õÐ(¾
ÆF‚1Zó3‰O}áþƒÀªt‚ϤÈÊI³.À“!ÑO6ÔªMÙ’„ü¥R‚‰"ÑUœ¹AD<-Žà¢ “àÜšÊãœòè- 6˜JUbâÁPÅ0_Ä¢–ðC üÀ>°a
m°2?ñˆQ5y@f—z +d&"¥HF:Òqi˜ÃÝè8ÀQ
n|–åØƵ¡²f,¥¨Ð‚8pÊ F-mi•Ž““áJ|M{Ë~¦W´FŸD«ht×ö™¦k;–AU£5±™F4YƒMl4?üQ¢QÂK›:¹Î&"uÉ-¢H-Ñ‹] +ÏÿœÃÚ9e„‚çrþ@ ð"\+ôÃAOè¾€1h OX¢™`ƒì ÔG³»8EtOqÌ<Œay`ªvW'h8C·Å.ŒÑj€ãªÐìF9ØÑŽrŒãˆÛÈÆ5º‰WZÍv„×tžhgliã;çê¢}ö…0ã›gÓ¸†šH`U¥qßgXƒµÈF“}oÔ†ÙßÄ…_Š‰wÂEQvAD‘úú,¹<ëÉtè ^êйʓÀÁ"'xÑŸT°¢¬ Ô+šQŒlHüÆ&S§+Õ…÷OmDäÝíj׬øØ-Fqc¤NÒè†;ÜQŽfš#æø†þ9xWŽlbì@¾´h™ÓTM0nQ±*ó½PÚ¥%Ú 44WÅÐ…°º‘i" Oµ4Z:‰@i²f®mHôc¶üh?Êzº7ÀÉÛ¼¸´œçÌ’±ßª„$Ä€në¨DA»¸)D5fma° Wð"¿¸†UV1 LÌB×€†5²**ƒ©Ê†2`‡Ì<<5©ÅT]R¬CcH#±à¡êd!òZ£ÎšÇ!fw´Cˆå¸2†·ŠJ,‡UUeš×¢[-¸®„©Ëöˆ[‰(3:©@× ´4€±N¢egfÆÂÓúcl™6µR8\ñjþÛRNàâˆÛ@@˜Œø’áÒWáÎ#—:áþ r*´1fhº F1˜á‹eK[ÏÆaÒUg
k ]·&!QO¸®Î}D†ÉíÔ=;xPê(TgÔ]p£Ë8/4Íáîw´Ãéð²ƒÁcTT!Àã~gd#»ôL3¯Ê‰ÐøÌ¢½kUp4LfîšòÉÑá«Ù£A_Ã,Éf€6Ûå›Ô›AgEšSs,Ÿ‡¤œ…Ž•8I¦Œ®v”èÁ×£° Üú¸@†š·:æ«6ÝÒpúÒ—ªŒ¦‹cÙIÇöêˆ'Û0E×U—ô¦û¥xÄ1GþðOYý®‘»Ávx´ãˆØxʧP‘äÝBä[Z@9ר1D)‘Žjô³Á>Ñq´lŽ>CÂOC2i‹5-–Hº½á$lS®çzä!Æb,gá.ÜA@©æZ„/Š¡0€ «àAŸp·°êànçñàWµUâ
ÆàeK‡t§P|âÐ
Àf^Fv£q`b`ØÆCÂÄuÜölÏfšYõ
±°Ö ° +®3 +¢0 +`˜º êcFØ@YÁ¨ dQij´#>â*Op+¢BãE*`„¡x7,•!ˆo¡Os…>þŠÕ,G"?˜ÖiI‚?PÂ-¾Â"ˆ£I +%T,WQncj\rIæq©÷Hãa7‘/@Ä +¶`·p +âó0î ghàð{À·]¼¸ƒ^7|ÄDT`Fpav¨“m¾ˆCÑ|»â0
„` <ô ž +·PÉ gàP‹ãð<¦ ¿& 7еOýgXñ‡‘ñ=§
Ç_mÑ`Œf=o¡h‹Ç,-
˜y™¾¡$ Ö?q0¡Z§µH¡jŸ´çÂz´FbŸ¸ÀZ)¦j‘‘RcÀ « ¶ðt§°ô@ñ€†êUß(þ|Og
ÄW„ˆC7”TcG0G`CBÕTUfeNG}K·ƒÆpTy€‚0ð +à°ê`õ@Ò@ó`×0þÁ¬°« 3ÀV£¡gƒ–S#;Ógvv¸3òt1Gi!—£±,ÐB!"?òwHüóy5¡8©·.Q¢Å1c‘r™›E/vrqA[b° «ð +¾`Hçeâõ•XåƒÖ æàƒ?¨tÓ‡“7Ä„m@EZ‡]v0Ù†tMçšÔ·]¦ å0
Ãà
ãHéÐD²À
°¤
¿3½à•?ö)« _–Qúþ4—r¡#Ûù"JsptdˆÛ¹*À§ñg¿bžù„{y¥ápi-Ó"6ÖrGHˆ´"
É&Ž¤b›E7²¶jõ"''e7Gs/Ð +¾æ·Àš²8fÝàu?X|[e
Eøš¯Ier€g0LLˆTÅ”šÖ°ë@“ζ]Rh
Wå
ÁPÝ@D¿ð– ä
Íà&™±03¬3VTÐO•Q5KWF,Dz}ÖhwÕ7äG=UŸ«‚ø$-‡a÷¹6.fT aŠ¹&b[mÂàz𲇣/ ÐrÅÑ!Ä! ®ðc@úƒþÚ¡©ó{â à`¨:}cð»ÀŽF0EX§uÖf
ö»¨¢E £Å÷{àÐ
Ø€1 +’Ъ™`SµP¶27å +¸Õ +3ÓZôW§!•¡Oñ§O$b#é„`ƒ1È#v±€Œa=;aXr‰*‚I#õs?j#%^”¦’Ù2çý)Rür™‹#'sj š8qã3wÀ +°ð‚Ó¥]<h|àÐlº¯MmÉ€GP8P}§`]§`öp|âÀ¢Ry“‡Ê‹I÷ `z °| |Ъ¸• ¡P²«±ð +ª°‚« 3®@ ÷6þö´ohqRF4}†*üÕh˜QXû„!h‘¥à¥§ˆK*yJZgYQ‚¢kl‚zÁzþã7ɦ¢GR +1cè¡.° ^±¸TJu¨§àmÀW„ÎȯÛe]Rm„0Qp9ª‰p +ê`õª¥ªKÅ‹©“z`ip±«‘Ъ¨ +¬j Ÿ0«Á0œÀ +š +'[¬Ð(pGøž""`}XtÕhñXXäƒhÂJƒWg@I?uy—G VH0t…¦tC‘¥Çºciš‰0QX§ÎQc3?ö‚^Öd«Ór@L‡z“Lˆ¶ûºu9þØ š09`` +4™]bæ{ć¡9Ô£Àj`ê+¸} S“@ * ‘ ‘€ +– ‹Â ™¹Š‹J«ðœ” IqáƒxÈÆÒ³spŽ†`wpû€bÑ2,Zc$‡²‹ –ùWä´e%"¥$œIô?ør™Ã« —P¤Æ°Ó&ÒרÙ5”ÔËTØ5”H¥Ý`ŒpÆhŒÐtuû›Ü†Tm`€WÀjPê«‘ “€ +’Ð\ }pÅók • \Á $‰JŠ» +Ñy e€opeJÃpÜ_„A>ásx0,úöŽí“`Îò>þÏB-ÕŠ5eƒ6¼±a‡ŒŸ¡T®ç&L%9zÞŠ%¸/Šµãã)ëÄ°¼6…;Ê©s]¹‰]×%a· ¨‘úBðÞÛTÎØ›å‹FPŒTPePg`Tl±z𬀠+PÌż‡[ÌXœ ™` ˜À '«¸„[+Xîq8aßSž†æŽÅLÁ¯"qƺúd€uÇX[ãGœ±;‰N‘¸‹,Üb"b¬gøÂIa‚Š™j3w4£dÐ)4<±¢ÜЧÊ; ÑcÐPa`Ѧ ƒ»P +y€x°lÓ‹ÑØlrÐ]€CpþËd R0UePS°¾ò¹‘`¸^L¸Æ\̒𾨀 '» • J¶— +n¹iAå¹ÀbT¥u•Çlq–}œ!L*Pva—„u!ÇòO’fiYS-°;YŒÈˆQc™% ꘉéI–ÜI!÷˜Äk7A" ^P¤Â Þ–dg;¾O±¢Ñ©|ÑýLðm›«ó »P»Ð
3L]>¤ m`XPFPT`V@S0e@Uà˾,fð’¯ +}°• +¨°»ÓôK¿¨P ˜€½˜ J¨€ÆªàcÍ“NÚl5ïÔ‡WÇü¨X;[GÆž þ!ösÁ ¡qöã$¾á +hÔbõ’®Ø!z:'˜TR1Q*™#™Í0ªÐ3LÓ]ú{I'…=ʃ݇ýŽØ]ÑÇ:¦p¦–p1X W K`ŒS ¡}P¬¾žm±f¾d€Wð~€Ì@ ¸´ ¾ ÅókÛÆŒÅÏü +™€ ½íÛ¨D H0!jÎrq6bŽáÔl!GO•A/kžÏ½G”Ö`a¹‘y %ˆZßJbÜšr8 Ü: ¹ÂèA[8Å°ƒŠßϦßûÍß9¤ÃaÀÃ=Øÿ]Ø> à;ðpŽu¬³:¥°eþLBÐF •ZEÒ~Žy€ppT`Òkð˽|@ ªðª° ’ð´à +œ Å}ÀâÆ< Ûˆ ƒP•°ADÅÖL¥yõgR³nhœÑêk±Ü„±,‚g˦̂—Ó"˜~ô·Ÿ²Á hz]ÞÿÞ
©YyAÉY~zJ.Úã©ÀÂà9º€”]7ª´Œ’Úu]×uÑcp +åþЂ]ÑêžÊLPØî©œ]0LxÃÓµl§P +¥ˆžŒX‡¢7‚pS0K`g@~gà‚P ð|p[Åp×° ¿ +‘°,> ˜`4Ä +«ðþB©®ì¸o“ögYm¬sE'AÆÜȲ`¡¡>•‡ÁF¦¸dÃ^ôaq +Aar/f4!Q‘ôÞÊÖä½ÖÜó0Ì +Ä ×.Xæ`+¶.ê¨a°“‰-î]oÑPàí.àêÎuNç0€ØvÌØÊð ¹ßÀØu'ËS`WfPYÐÙo i0© p ·Àä +‚JWlÛ“ +®` ³À ¿ªê¨Ple|W–KÍ>г#Ô3€Ù™`8ËB@û¥fP«Q“Ç€`sÈ`hyÁÞ—Èb(çôú‰Q sizRŸ +®½ÑþU¯åë›Köa`ÒÝõØö‡]ö~Ñ^ç>ðPp]R†: šÏö|ÊŸH …Poonj°jоjÀ–žˆñš” +U¤Hî‰H•*OÍ´‘;wתU¼x¡2ˆJ‹ D^xáA…"M–´€òÁ(¼L™ÒBÊ™%D ™ófM‘xÚT‰¡&†"1ˆ´€ÁiÓN3pÀ!ÃLxÀÀ…a„]0–lXÎ.(°ÖíY³eÏ:V-Ûè2`PRÄ%V½”ÛuëÔaĉ/nÔq£<vÆ„ ÓÊe(L~@éfÌä.þ?4ÿ ½¹”);]º0YM:Ìå<?2eÍš1c¦v% +³Ø÷ajÖŠCéÒ$AÁ¹DéO L©¬”I³¦Ð&K•öHš„PB…•(Qòl[9sÚ®©¿ö‹—*TÓx°¡>S›5_BÈ)“æÿÿDzé'†²`&—XЂFÊ€©¦0¨ ©œªJªª¬ÒPƒ¨ºª€.ºÊ+D²¸+¯°X‹D¸0k,¾ &´ddÀ€½âË‚.éÅÜ;̘ßSFß>#ÈÆèÌ2̘`ŠÒ2ÛìJÍ4ÛaŒuæ‰æµ×˜x +GJa¤Úä0%‘FF‘å´Ã"+R1&Šþ8ƒ?Ø(ä’+´ˆ£?8y¥NÙÃ7Ô€ƒKÔÐC4Òèã;…bH@„á¦r´Ù†›s°¹†÷RÏäÏ¿™n¢à§®`u ¦•^š©UN°‚Wa5©¾¥ Xʦ§dЩ/TVÃ4Ð`‚˜F|˸J,‘Åá*‹Z²¨EÀ,jGŒQ¬hðà`’‘†H#ç<åÈßšœ,J)E´v¨²4&ò…á‡R̉ÇsÚhä“-M©FYn1å“0a³SLIì‘ñƒ²1ë¢*¨¸â5ÀdŽ7¦Ø"
9Taã
?²¨">°°ÂŠ4Ü@¥ê¾‹D„þøDM ÉF›q¶ÆlžõSS1úê˯&ŸX…6À–dâ ÖQºil[ÿ›`lŒ…0Â¥,lC£²j˜¼’KÄ·NŒëEß²±Ä ´½»Úp_ꀒ^œÁmelCÒ7Ç“±D"{mµzKûÁ}óÕa`ЗóÒ|xŠR²1¦v‘#´<ˆéÆM>y¸LSdi¤YÚÍø;VLª(c +)¬XãŠ6@É„+F>cú5ÒPC5õÃ?þ°ÂŒ4ÌØã = გIa¦—lÒç›aœÑ†R7â(>=Bh$•V¢€‚ô'&1‰ØªŸøÏ?þ Ö¨Ÿ Y`KÖR¢!EÈ*pËÀ¬hÔ-ùM- +°–\ª%–½ ®.|1ËKdD¯x@¿pF6ÖÕ8kH£HyHŒl*—ˆÉØAa–`¯|åë¢sAaàƒ~…t:]4ц0Ä¢SzÄ2¬¡Œ6œB¦ Í"ìЈG”b£ØÅbLјÃØƲðÁ¬@…F˜Â/h! Z¨ô¬À7„o
|ðá …(=˜A¨˜D&A‰= ×0Æ<æáx¤ÃÌxF0˜a¿Žì>)‰€}¬6 šð +@ J¸B6šœMW2éOJÄf^á‡AÇþzJTÜv¡¨hÊ\À‡úÂB¼äíny!a]Hô¢jÁ(. +€QYHÈB¯<`nèE3Öõ®ÆÁë7Ž‘Í'"#‡1Ñ3•¡Ò–º%,`Á +Và‚°à/ð×tðÎ-q=Ø\t!BPfÒÆ#”!‹49¼Í-0†˜ÆâF’£1®À2a +U˜Bª°…&haoÎÜ)ê”jØöàJô Dô°J Bh}ð!‚!
u¸#ôÇ;Èñ_¨DEQ9À”k]“ W5 ôe—‚åN~…ŸµVè‚L¡`nR¶)ECâþ¨À•åƒã"üö"´@óZ]QW¶…X½$YHE3Œq$~±‡ø¨l˜Ä$;lŒ2P’ÒŒ¨ÑA6x +N °@t¢»ç>C'а 0`ÂF¡±<Xl¶SFÅ +cŠ[€£âèÆ'0&$#=.ŸÀAhP´´¥E(Âøp…5ø
oÄ%ü@²FÂá~0Cx÷@TIDÒ|“ì 0ñ‹W$£RG=à1pýè/:‚ +IÌ@™kNî:äDl¶ÛÿÀö5™¼2?kS+wR +T¨*ls›†þ–ÂÀ°v9Ë7E"n“n|¡‹þöÒ͹ô…-HÅSo(Ç6öh…yR&3\ø¾šìƒ¼@KðÁÀ°Ø² +aØÌ|ÐÏÜöÿÔWì@ˆàÞ¢àáE'j]˜B·FïŒT˜[4ŽHš½¢§#d¡Y ¦„›©Áz¨ ø`álÏ}à©$†JHè’¸‚#A`4ìGíAw #XE*V©¡Â(Ø€B² °±µ+P, k
hl#±«Q +$l%«–ÅŒ›Ü¢’¢º¬¥›=a·²ÙÂåEû–\^òTʹËf!=¢EŽŒþå¹eÕT¦OØéìù.0yËx`Ä#…%À€cLbi\àOÜêà¡ðÌ.¬Q]ãi£;ea
päFÔ`IGQ +Ã8¼ÎJàšp†7Àa
{PƒÈ`h•N¡VØCøÚ»‡3¬áã™Ã"f‘†A¨Bg(Ã’Š`îXBÒàoçuhÃ10*"57x`*v¯°VÖ Ðlÿá ì“ŸZ)(lk«®•A¸™eÒ +¡Š²5Í»£nÖTaa\€qɘ +œ!
ihö0²`ã.~›wdz
—‰weXSZ(C!xøLÀ0†:äa°†. þ†D”"¤(…-LQ +BˆÁ¡ƒnÞÄc0×É0Ò(FzŠ<ˆ"„YG<ä|Ù[@T7ä6†%‚p…#$a¦k„Ü CÃÜÐR ƒŽ§…7¤AjD Üð9 B
†ØÄ*$Q†3øa’‘Ú$*Ñ +nHõõ <à_hV°«‹µ,ð€¥Ø:É•—Ð%^ê a»š_Ѧ¸‰¯¦IŠ¤x”H +cI¸Ãpa!n !‘¶½«¶ÄŠË1¼‘hÑ‘¸€,XgPÄ;…5’…OX£[Èã.ƒ6è0P',ú‚#à}aBÐ…]X[(D@þÑKOÈ…b€DÐMH†d a`„áÓ„Cø0`0¾Xˆcx„OPs‡d°
:ÝX3eh.Ü ZÚ®!°AR#Ђ?À“L2)‚9P‚è©$ð)0òóJ„7À„J 4œ;Bà…KAÛ?àƒH`?„O†nè¯x€‡v0¥kX…¼ŽH…?@‚‰[±‰U—p•’H +»a›¥·Â5aÄ +JŠ¥1sŠ¹›»˜0A¹8‘kAÁi³‘¾È1‹I‰è1B¾S8˜DCÙH|0à‚/è:X’PH#H¢(ÀþãiPFp.0D„Xð9 „C…jàgQøO@Gƒ%x<x\†…©…[À¸nø"ÜÀ˜]8ÉÃ8Iä²ßc3jƒ#À"€9!ˆ¾‘Y30*È‚0?Pƒ-…oÐZ„5È‚ì *õâ„TH¤*-0òЃ>¨¾>*¡b4c€Exp‡o`a¸ÅŒÀšK€ƒ¨5•X¢‰¶ü0 ˜%—0Š²a@þa¥•X›h ›H–8¦¶‘˜°;2Ái¶Â&ºË‘óŠ\€¹“‹Yé°:s"Œ[¸JBp<x.Ø‚|SC6ƒ‚…RhþË°'<`’jP†b†dØY`<hDh…L8„C°G…[Èg¨Q…OÈOXFè‚Ú3†O(…hp†Px[Xq/š#:Æ9‰K>üF @ !hÏ* ‚#è8P”3pƒ—j@fÀ„ñ8ƒ+¸¾70ƒ>øƒŸí1P „4¨9„š>؃?˜M 3spu`Y ‡kHèÐø¨„5@‚T&]s€8;X9›i«ô‰·› ‰Ë@ƾ4 +Ê+¥1˜1º¡–YÁp,i;¡»¦À‚jy‰‘‘¯x
„TÅþOŠd†"1.pуCÈFÐ]…F)q„ePs0†n†h…\°O8„E@RB6hƒ6ðOÐg …O°[ Qˆ…PX<èCRh1]cÐR 7k˜Ãn¨œ2E§Á¨˜Q(ÈDÀH‚ ‚˜Õ ¹+˜#€Ï+Ø‚:°>848ƒèI™©,˜ƒHØ7¨ƒYZ`†œ2ƒï@Ÿêó@ „O`Óm†W˜«Ëˆ#ÅA€ƒ$H|‰V"ѬQ««ù³Ú‰ÿñ dTÆ\Û‰A +¦–¨À«’€cÚŠÈŒ0iqlþ,L·€¬"E‹4sq¼šgp[HÈâì„L`6 ƒ8˜zä‚8;0M] Œ}¬(ÀkèsXÓ[p†µ…`È„E0NQèÓ1°#øMOÈ„6h‚C€RhMdXyn‡pX‡äƒƒFˆ3çäÈeHISX¥mƒ¨I‚HOp*h* G$‚ ‚ À,p"¸D—zÕ&P38ƒð‘™+H8øbè„e°«b†K83(¥KàÏBЄWh…fÈÏk†]ÌX…F$à€ù° ô%}‰- Ó³ þp…K¶Â `Á«¤ +×Mã×É—sÀkÁh+RÄ‹±è;¢‘®ŽXa¸…X ”NøLÙ#ÔÓ8è‚6È>í„N …X †á»F`’NXsè†Rh†b€†dD†dHM(…tppèÇ%8‚!P0ÈM F|‡xk@‡rð…ƒ1hÍRX†‹3BhƒD(…upe‡u¸‡{à%ˆ‚/ð‚%$! 1È\03 ‚ë*)èZ#p„Ø‹C<À*D3¨’¹aìa9Іf°y؇{xmX…@Ø=(5àä„Ahþ…W†i؆qp†aØÅTÀUP…U(„8ˆ%Ñ»Y"ã^‚+RƲ¶bÄ X‰¶ÛÀ§°l™€¹ÓÂJlù×Ù›½HL‹‘;f€€ÒTȪV€…Zè„Câà‚.€Õ`. G¨…Zˆ\Èa°…8Q°ÜÐdˆ†h¸[pY¨ÈFp½1p4+9P[X#ƒ:`ƒG{Ȇ|°‡SËKØ=uÚäÁ]@&)kp‡]X‡|Ø?4X‚—:0:`ƒ+H‚$øKÈj…(ð*0A˜'Ègð-@:(_€Aø/þpƒ/(:xƒ7(@Ø/Єi‡}À|†_ëq”48µ„Mò…VPM`†
•.–©:ðè€Ö% ®ø™p%® r];2¾W26¥¢ À06¼ÊѸáײ°Ýà +RÆ,¡Àb,9!ÇÄã²è\¼NÐK@P/IƃCˆƒ8`E@†iðXÀ…XÐ…j0Ƴ…]xHiÐ…á#kMð„DÐD@†fÀiÀ{HdHÚfƒò´e€-„h à|Ø} [°Pe>kH„SàsÚQX‡nX{èKxƒ-й-p'àìþßÔ„E¸„PX‡z‡[8P˜b°ömJX f„AÀ…k†ixz …Yà'8„@H„jâƒÞ‡}("v5à?°ûUØÄIPahT€ŽèèTÀ„Aàæ$
ÀµZ9«^É5“Š8é±Ã0A‰a QiºŒWdi6ø¥± G¼œK,éHÁDÒ$€
ˆ5©©„Uj@ˆƒAˆ@hƒ—í6<È…v ZGàz˜Yh;è„jpuèb0b(ý]†p°‡{@îj¶‡aæ†ÍHPŽqp‡y¨‡Ãîþ†P€
+b„ÆɃ’=k(…6R†xèMÈ/€8ø“-D¨8È„L¸GèC(z ip,8U°9¸r`qÈOm‡t æwÈ}Phx ‡s@m(„D0†xÀ‡}¨‡FWh|¸†9ðNˆnIO‹K؈„ˆ„km5TÀC „7H_t¥ãŸ›X û µj°3.öŽ‰ +«bƒ¤1Y^Ø‹ºñïn©¦‰»œ½Þ4 ¡Á0ˆñ˜Ièž@ø÷[€…?ø1èoà†XEˆo˜‡lè‚%àG8Ùt€‡æ„O ,þè—Rh‡åš‡{؇y¨PzØ÷xˆ…LPx1 Gn‡ ¾‡\€‡rK<e8ÉÛÀ8Œ[c…’Õ„<0„E›O*xU#H‚Gà…L@††ïÊl‡IÀ,0„:j‡{à†lh,ßwåþyÃfô}°‡rà„OˆÅ}gtF¿vàZ ñÙ9¤?ú3•WSL8L¸ƒ&0‰¡®ˆ€[j0ý€¥ÿ ±Wa “¾¥]Y« »Õ@x% 3¦’–Áúod‹±l€i« ¡±¨ºTIØžîéž:cˆ†äµp@KhƒQþM°,Ø0xƒ¡5Yi…68ÖXÏ;†zz0xÈxÈqð¤{ ‡6`0Ð<9€SpwH}Ø|è¿nˆq0‡O°8B(ZÆ!~S˜` +ö¿y î#p‚+Ð_…?Êdˆ‡zx +fƒ!`‚CØ{ÀvoH_†rhgŸOh!ˆlĨý²vo_¾}ûêI£Ç.´MjÞø‘é¥T”6FŠ$©RªT¨Ra:”éÐ0<°à²åƒ˜1]Z)s4mVp0sç… Ø´€¦Î—G_Ö¼`4‚…20`à`‚Õ,`Àõ+þ®p%àµkÕ^½NP[umÕ®8xû ^¨PI’4‰O?àÀ„§V1Yž4Ñ#¦Ò:‚°\¡ÓfK(Z ÂÉ“V¬X+E°–ˆÁ¥‹3{÷ìYSÏš8YÕîÕ3ׄˆ,„êò£”<yëô؇Ï\¶GÆd-[¶n,yöäY‹Î˜¸{øôá›çP<°ˆ!…Ù'4Fzìⶮ=wŸÎ(Ê$†V¸zó²árV.-º„“Í4ÓˆSÏAô<£Š8ðÈCÏ +)4Ï5·tƒN0¬2Œ+«øe &ªtXIG’ì¥JH˜BÈ ^ ÀÁR5µÄ”L2ÖANDµTþALàÈcLÀDAM4Âd@UN¹„AQ…ÁT\µÖWhquÖY\ÖYd…éY\]¹V™U9@/«ìÅ—$|ÆxÄbL0žxò +'mÐBÇ Àá„u`-‰È2M:ÂÈò‰&X ñÇ#†.ðÌÓŽ9ÎDÃM:ÈÐsO7¹è¢Â'¼!rä±L<ñÈ@qûX³Œ0·"B÷ˆ\gÏI#7æÔh!„cÜ‘‡)òÔÃN8àa +3²øÒŠ%XàAŠ/hÀrË-¾l2!îäs=Ý¢m„|â7ÚcÎ<ñ$$á>÷ÜsαÈÒ%œÈþ²
9×ür &°/œLÉ^!…¤Ê uÐÑ„IäÓ(¤LÌ$äK1U@²M,%Ô‘0Å<£KQy3>=à]Y>°@_M`VUau•&—h¾eæÑj’uW!zÁÙ|H↴RK4²dB‡%’É׆òÅ!p.ÈØR!ŸÊ‚…#¹²L0ñ‰2â|ó )ºÜâi7ÂTC<Žà1Ævx’I8눳8Äí8ê8cŒ)ùä£ÚtÁu#O>Ý !‹&Œ„‚
5Ð(¥¼ç¯¿ŠäQŒ/„à±ÈgÔ2%NÁ1
¢ã̼å˜ãKEà€ƒ[þ¬QÅš³Ž<íC«Bÿº‚I'–„BL0Å´ã7×ò‹+Ÿ\ÃÌ*U¼J*×QÇ7t@ÓN1¥ã‚¢›D€H- Œ~ž$ðFˆ’–Ô¤%e€JÈÀ,°µlÐ+ìÒW´²€°€ð+à —¸‚B5ýì„xA›øÂøVó„0„Ñ B´á|ıBp"ÛÄ ¡vÑmX8Ju‹gŒ#ðDððeXC„xÄ-!Šj€câÈ=ŠñR”"xDp¤¡Žnä£Vö€‡,dñwt÷08J7œ}˜c]è#‰8! +þ*E7Ì‘Ž„ÇŽXÁMÔ"€(Å1ÚÀƒJcyw@‚Ö`"ðÀ +SHB*‹`8ìAõPqêÑ_´!½øÄ6Ðág´CÂè &a Y\ã©_%è—Š“bNX Ž.”¶È,€HšY’€²0',9RN^—@H œÉ"à”©D€Jj©ð3a)KþD–êâO1mI…hy€8ñ‹½H‚ðà b@Cža؇8,"¡øCˆAŒEÔጵ¢Ç"ÌY¤ƒÃ 1Ó:`ÃÖ°C¡OÈáÙ¨F<î1c$â?Àþƒ-v!jÈÁÒ NÚÑ7i`OâPÆ:â!
Òíò°Q‰+4á q°;œ¡'[ðjð°G Vº9$rx„/Î {àƒáG3ñ‡"8O E0Âΰ†"Há +p‡;ªáŽxtÏå¸F-BAŠN ô€G9bÁ‡?ø!•lPT9ÈÁ‰=Lªx%N/ˆ€ìL™ ²é„
Œ‰ÉZ6@”©›-ûÉø‡³ +f .j“UR˜¥}t„VñÒÒÞÝ®ü… Á/¤Ö—H@ô¢(†6°‘ 8¬AlXhñgãÞ G4‡wpG!îHGþ:²Ñt|í€2¡7M|J€ÅÞg$CæÅ¢bØb·ÐÄ¡¨*$òpÇ-¬aŽ9ZCæèÛ‰×áŽ6è Ùh"Q‡[Ãh8ÂÄ¡}Ùî°„ÆàsÀ#ÀÎÇéñY@ãÛÀ؆+L¡ WØB²`)Ø1@9ÜñYmPƒÓ(<àÃŽKü—èƒ þð +_tãç ĉ觊K QJÀfrkb@àWœ,A Nx\¢w&þKî—T32WÛY™èÂÂr $™ + кœ»jŠî 3p ½ôÅ"~.þÞ¡
[4#H%Øð†:âµx=Úá@p!ë UqæQx$"ÔHÇ=Ú‹åäaËPF3ºq‹O$ÂõpÇ2ôÁzäáZê(Ƹ!GÜb¯–£M6Œ±qHC¥PF<ÖsÐñ5ȃ0,1M°™©„ +l0ââ¹N°AJ¾îƒpT>ºÁQh8Cg€%¢p‡9¨á +T¨ÂºPˆXXÃõxÇùü5Ž^Ä‚²F;ÞaàâoÄ$‹açÌ Ä$Tñ‹U¨•ƒ àÛÖÈÒÀ†Ò2I? ¸6z§8e"Ŭ&J¢Ù“¤þ"–°Lºa1KY̲/eILn Z]¤=Àá•aG&!ªwŒƒ/$ÖÀ6„¢tè9Ê¡‰$ –òÀGº±«Ú#âxD)–ñoéXÇÊpÄ:àq®`‰Â¡œ<ºÁˆCà¿âê=ªQc4¢®—8ø-}îXõG:¼*Š:ÄM8‚)>†1,{ +yÆ"†GzÌ#!óxÐ 1牂1o¨Â*`*áU@°0‡DD£p„Æ5H’'`B‘0€Ã;1¼O Ђ+Bˆ¨‚…] YÂ/ôý\B%Â(Ad€øϹŒN°Ìqþ‘ŒSÛ…à ®p%TTÐS\Ð[ŒEt}ÉW”É–0€Ñp@1U°P@vu×D
Cñ%t‚g±ƒ6–ìEðìÁ"Ì%T¤xÁÐ.ÐÑ„@=|Žöàƒ:ˆ8€Ã=ÄŠT©ƒ:Ñ„BHÈ=˜Ãsœ["¤Þ-PÃpäÃ'àÁ2´˜;Ü‘5Ã:Ìž>ØÃ}ƒ;hB(Ðß`Á!äA8|‚5ìË>´ƒ<ÄÃ&œB5غHC7pƒ3PpÁTœALÁT\A4Áp Á<A"C6d'‚PÁÀ‚þ,8Ã5|J82d-l%D!/ôACeB›`B*T¬Á ’SɤణŽ°`”œ ×—Ž„S× EnES¸Dd€8¥E
+—ß•ßmYøÝÒ¬PKˆ/H
*PÂ,ƒ7 Ã9h ìÁ¯øAïìA'd \B ‚"x‚̃3@Ã:ЃKJ>¬C:t|Î.¬¡Š%‡<¼Õçƒ-DË=üÊuˆÃ>G5Ü‚³!„ç€ÃªÃ.Șº „(x6à€ôÀ8Ápe
ˆÂÏeC.hŠ”1# Ã<؃9X‚˜Á<þz$ALÁ˜üUà"¨B8AP $'¼B œ Ã5¨Â«xCö°Ã6àÂÓm‚*È7ö*LÂ+ð‚H@Ý9mÌÚˆZÐãÌœ`O ]<²ÝMLIV°š––Í?™ZAMÏ`—¨¹…\@¬jî.”C;°C9`ƒœøÅH^Üå¤Ò_N¨$&‚ d,ÄB,@ƒ/PÃOiGÒ†;ä^.èI$ƒ: ¢2„b7`[7ÈB2(¢90鬃1˜Q7àƒ;€Ã-|\=<ŸºÙs€~hæd,¬$ÁØÁ"´Á"`Aþ`O4LÂ1 Cî
AÐAÜB0´Á*Q ˜AAÜ_˜½’$6ãwZ|%¸˜APLA¬/ô‚˜=ЂÐÃ803°‚%¨B/%T!¼î%BJ„@—¢×lÒfËœ]> +=Îc‘ØLM8MWpÅÞuI™$ÓøLÚ¡šLœ¨Ún@DZ2”Ã7”Ã8hÂ$ø&°B%°HžÁI¦A!€B¤úe{ ÖHŠÈ!Ü7P§=,ùM›;`‡1ØAã8ƒ0 C5¼C<ŒB)x"ÜB.Ü¢9ø€1„ØA)hŽ)ìØþAÔƒ:È‚.tƒêC<h/+€Á`"ÈÁ.8Ã~ºƒ)x‚ì„Kˆ$Ë`ÁaUAèÁÜhdÁÑÁÌh/ž˜È¨‚Ü™Õ
hAJúÁ $Ã!âƒ~Ã5ôÂÈ%¸AL'l‚2‰it%Ap€ÉüV ¤‘]L¤Å +‰ ÊäVœ–ìæLP…ZÌEðÓŸ +'¥I[ «¹…[0VÐ…@¤4MƒC`C3hÂÕ@`&`‚`œ¿šT&P¡Œ^A!hÁà€ðÀ\
ÜÁ3üGbƒ4DÃ7œ.pÃ.4B)Ø$þÂ'8‚)Ü‚-C,è'Ü)<8àC>ÈBìAÍÝC6T$E‡<L<¨CªÚC5(ƒ1Hƒ1tb=.C-P”fÂÀ! Â'XÂ+¤g6X¼\àâýA4œà(¸ ôAÂÌÁ\¸ÁdlÁzA¾²ÁÀlA",â=¼C4d4Ì!ÀÂ+€£%XÂFhB/ðÂ%”æÌÁàÀJ¼© jLèLÊŽÎÐï¶ýÒŒ;‰NÌcL,V…˜ôA!@žšÐ©¡ª¤ñÌY¨ˆj¦Â+xV00C%|¤* Ý þH¿Ö¨îÁ&\Âü«Ð!¼Á('0AÔÀ‚0C- A(,BæJC2ÈÂ-< +7Л0Œ‚.C4àB2˜‚¨Ñ.à-étC¤ƒ;”ƒÊB"Â.ƒ2ì纜›4T‡‘é[)dΙ2´ƒ@˜6„˼Â&ä2TB!`Íh¼rÔ.ÁpáúQA|(Á%¸B5Ñ™ÀÁüÁ¨Â%d(”H²”<Vnƒ38C0l0¼+\BB%\hf‚VÂ$‘¤À.ۄʶéü¦,Ït“]‰¥éÈþZš,þS<É\¡šAa c ªåSvå/4€‹S´I*¨‚/80¨ÔI^Â$`B øøÁ]f*¡£zä@'-€˜+lØ€`Aè@ìÀbÎ- ƒ5tƒ4ÄÂ'<‚00#Ø‚.HÃ-ìÂy˜2tC2’;èptƒ8ÄC4tÁŒq)¤8ðU<(C6„CƒtíB7XÃK:C)Xƒ;dC:ÈŠ3PC4Ã"Ђ%B/`‚XÁøkó AÜb»æhA˜Á`ä€Â0 #‚$æ¤ùAhÁØ"HAl"p‚5|ƒ4þÃ2L3Ã4<ƒ—6¯†dì%\B!HÂL‚„€IÊÉ̉bïŒMPQs=–L£ 3ÿä–p×V„ÚJWY„‰–œ’¡U¤à°I*¬‚jckiNBýTB+BÕŒVîZÁÛPÁ˜ò6`ƒ/0Ãx™ +ø€`œ`QØBòE‘-Ü‚(tB#,B2$ƒ3Ü‚WC7C5XlØ”4ˆC‹•N#(U¹ËGg\e(ʃ2ìÂ{߈õ‹=”C5„4ˆC:Àƒ~;ƒ6lƒ/°ü.Ã×ÐðÚvœ¼ÁAlÂëVA% A
àþÌ)<+Ð.PÁÉuÙœã/P‚+chWA`q:ƒUY8:”Ã0l‚Ä&\‚&pB'HL!LÂ$ÀAtLTÀ&;ÞDý:—þÊïq‘ÉäÄqñ̉2§O¼ÅZl…WÍ?a?µýâoý^À æù3T]_@]‡P”8Ì.°HTÓ`hÁ Ã3ÄB+´B¾hè€,çA5¤8(ƒ-ŒÂ'ØÎ'à5ˆC#ÈÁŒB4Tƒ. B(šÂ:äƒ4”ÞqŽ,Ã2˜‚)x·jP[)ØCV(%¢1$Ä2¸ƒ0„ƒ¬@_<ÔCþ;ìtÂØAìȸÜÖ,½AÁL(+ÁGÂÙÌ‚%ÄضmOlÂ&`Âô¢8¸|Á€C;l8ÌQ:˜ƒv£9hÃ,숀M+¼‚%¸ÉlAxÀ-ëf +ž¬Mp>à/“ʺlË$¶pTŒ¶rç˜ô¬—xytu]0§89>‘Œ¤/üÂ/°90CiFÂüP‰³9B4Ø9ÄÂ`®ßü%é‚/Ђ(ƒ&‚×zînÁÀ\
(Â7d7ˆ:#$¬~›;<+!Œ2Ȇ)ÀCTC=XÃ-!Ä»ž5´:IþG=ÜB8”Ž8˜ƒ.è|cî^©Bä,_>¨T<¸C.8C3XBcÐÁܯ50 BìïÁ—™0i´—Áh,{-¸h@($d|J¾øA4ê4v¨!8 b±|0P‚ \ ˆ£!°&üZ|ÀþÈùD¤E¶O8vOÀÌqáÙUšL°ýZ€°Ó”gVœPÎry—ìÓqTUàQ80ŸÀ*ôB/\Ã8\C3¨‚‰ð¬äÔ'àuD¹`h¬X©BEŠ3F¨Ð¦mX+@žàl#ˆÍŸ8hšØèQþÌX±\»åq4Fœ1sÒl5*N¸[Ëàåû¤Ì8}ûòå×Óž¼D‰¬É«o8FÆníºuËÔ®Sʬ™gŒ,ËêÕs†FW¶X¥ˆ
ôhÝ:yö”•ccåŽ%3VˆäÀd +Ž3p”AbEÊ2IªT "$—9|z „鎡IqþXÉÈŽ–5a>sf+—5pݸ=“f.¹m®ôzÈ+L„ÁYB¢Cxófð€‚ïÞ¾8xÀà7oãÙó>°|÷p¼+çmá‚XX€œÁ„âÀ3Xp½ôàÏ#wà9 +€O~ýB^¿€1ëÕ˜þT6á…KešmzÉÅsÈI" +¦ðŽ©(â8‚f˜LYC- +„3Ðc‡¾ã–”ÄÇiF±Æ˜Dd©1™n¤9¥´ì)E™]zÚçž|äÉçw¤y¤yRGqdÉcS‰ +ḵF–e¢É#ÆÐ$qxÉÁKŠ&“<”±Ç|ð)‡X´X‚#Š ‚%‚â/3Þ@‰"æ8#ˆ=§Ø‡Œ8È4Ì`˜`y%/®8‹+’à¢JäÐä•LH‘%˜`|qFšvàqÇœköðCI@áe“AáŽ<È€·éºkîé~ûm·åšC®þ7a£ëí>b{³@;í0€ï=ñ*øŽ½Ôk>ôÀ5î<‚‹ÎÝÀ{`‚6áÏ?VXQe’Nz¡„`ùD˜aˆÑd5®0£ +)¢â
#hhgz Ċΰâ3Ž ¢#ŠX¤krúf{Ö9…qiä“ezTæ”]l¹%š]¬QÇž}ö‰'|nnª(câ Êe¹2*i¬ÑQ–RJÁJ #~ˆC™v®aC”ÔY'fsŽÌ§b eè*¢R¨Ú•MòäE,™â†¿¦(˜O²“€cÌŠyf4Øc“!¦€Ã‘X€y…
L9¤•P™†™dÖ™uÈáþE’IþdL©¤¢DØÀ:à¤]–9f³à½ã\?½·à’‹8k-¨ &PoåŠû.=äÄõv=ø¢½Ž8ø€áfœW•JhYE>*É¿¿§<@aåÂ)ȘBEz)"E†i@ŠÈÁ-®˜c‰-â↖`"(k22dõFÑ
cìB <à.x$‘é,û°ÆOìa}ô¤ó0Ç'Jñ S(CÉ(F)dñ O”‚6ðœ<£•X‘)Ä!xtCNò +"ñˆpXbbðCÙÂàKÌdhÂA…?ýE +Œú‚„<U +¡þ†”0°*Ð0Dа7ü¡…Ã3‚ʵƒÌ„Þ ¹Ïâ^XB +:Ð;ÙMÇ8»é{”Ã:äç7²{@ ¥»g.:ˆ¨E8 È™@ÔÓIó˜gxÞå·€Gð<@Y¥{@šAŽ_ôb¨˜D+z +>p‚´ F/„Á
j¼ã¿Âî`,â†@5Æ!ðáxÀÅ1^±:d‚
E‚ Ž€s€C]1Æä>ñ‰<”¢†&3š58ÁIgÝ0Ç:t¦{ìÄùˆ‡4La
eXi²…ñ]|"Fø¤….È(þèѺ±(ÕÃyØBä€qd¢pg(ìІ<Ì"Ipˆ0 A ‹Bß’ !à J¨‚ð€ˆ#Á/V…68±t`.BZÈ/ä‹[8CoüÆ7.! @‚”ÞÀ&¼ VïyÚ'Ð:Vì^ã1§¬Ï²%#pÉå¼Ç>àQðÎSä =Ÿü
#ã€øŽ €.p‡s\.±¬Ä%Zt¼ƒå G9lv´£•8à |Q„%p¯ÀD(¢‘`¬A x@:ÒQU¼E¸°„!8Qƒ¢¼(dîƒÇNöS¸ÃêHÄþŒ²äOæc'òXG7äaOyجHû¨™‹FŒ¢£À#‘ˆ¬›*Âj`ƒ¥)ãPh„hŒwdc\8C–‘MpÂEP‚¬ †8ä!5¥ÂC*œ¡ +SH‚´ÐE+h!ZÈú„p„/ì + 3hŒ?¬
t(2±_Äëˆ<ÚÑrüb†Ø&0ñ@Äa
>Ð6` +<²ÑYÀp÷0`7ä鎲 +;-Ó5'®ÀŽ LÀ:‰Å(ɼrqK°P>Î’‹£œëlàìÀƼRQ‰ITé Ç;ÌQŽÌfƒåþ¨0¢+øA
Ó¸+š ‰Z0£gÀC5î±çf´Â4 1Á8<B4«®>ÊñƒGÐh£x„Ñn19ßF£§Í {ÄãHû¸à+hŽn˜*¦x„-ja‹D Â]xÂ4V[.ø 1>†1œB-ò‡:tá >xa`94(á oÀPMÍà'$ªPV ‚BÕ0ï"DQjPƒ_¦†GôY 0|± ËÄArà á Îø›å€F.JñŠÍ"€|`YYʽÉÎëÖª¼·rX +Ö°Çåh9;ˆ@îÊ£;ãë<X`Åþ5Êu¹'±ÃyÏ‘I
r©@Eü`‡l´ÃÜȆ1ÈÑ@”ˆ›ÂÔ KX‚ +jh¶à©Eì™ähÅÈF,ìX†5FÑmèìLÃ'Œ6 +F(£Fh„Pf +](£õ؉v¯kØì(ÝP†à¯4Qœ*bà‚q#A;؆PƒeiJaâÕâeTCNÀÂàAmhcoð‚Ý„?˜!š.„°u*$¡1B…ƒ4ïƒÂ2¼Á<ã‡ÈÄÒð†@°a‹àD`¡u3à‡4¨
‰#lD|€þî½Xæ²ëÖÅëGy|#Ê$8T8Îå:dŽ;´ r‡<*`”#\†‡Ì„§[Ê£8ZG”Øå `ÜxPX!øœáØÁPPÎÀ¨€Æg +Ö @¡¨@BŒ` +l`‰¶`6äØd +4ÍÛ`dÖäÁ€¼Ê«¨G!ìàJ‚jÆftæñöáó¡JÕÆà†Mj!Ú€–`aÞOŒ@ jàˆŠ `JAÌA
Ä@èê!†&
Ö@Âʈ +ƒ¢/Ôàªà +ª ¨þ ¨ ‹î ¥Š ¾`¡ÎA
váØ ŒÁÂhÀᨡ´¡ÞÀà€
䙞à<`䎬c¢#Zžå>–‚ãºì‘T)X^(À+éZn'\”«=ˆ§=À¸E”ìC< •é.€ÈáRARÁj)sØá|ÌÀÊ@|Î`aPzÁ{@>qO”` aØ!hAÓn À¦` †$žÜÁPFõÆ úI¾Ë¬!òàJf¤Hêáºl‰äâ!%íàF!ò@rÌâÀ‎€hJþƒ`#èn! à h"$á¡VôlÏÞAjÐÀvJ +h€bJ
¼@¥¯à +‚ ¥t ²\á¼àAØZAöŒà@
¡Üd1G¸A,-áºÀ~ÅW§Y’çäœÑ‡…Ëv#;°±wº£ËºCË°ƒ’.)’k=ÜÍÊq‹ÿÚlX‹72 ÎzAéR€A^ØÎ fð +¬@ŽÁè°@0!tž™¨ +@a¢¶áÊ¡:¡
h | UtàdÆÚ tDdGä Fa>aþKa¸ÖÁJJÒŸ¨"&ïA&oF¨B¬MÎéFAð` è²g –¯Þ4fOd¤¢Âà¢Ò–¡Î@1¡þ ,áì‚
ÜòÞx ¢À˜Þ@!ÔÀSæfQ’ ®@@A÷€0&Æ $dëŒà +°`TBÁq¸AžPc€a +þ 6a° B€‚å°’ã7FS±øÏ\R§vŠ…åvƒv„‡#ÊÚô(é€ÊÚ<ËKC xÈQLEiLQ©Ë:`Êx!X¡RTá°!2
È@†Ðàœ¡´Œ!œþ@†á0AjÁÆÁhÀp@þ`°€d&º@*í@nu$á¦B*òàvd*R2%kèfòiî¡ÔŒ>ÇàÁF¡ŽÀ Â@Ö°` ´À¦µé| ƒ*” v`œaà +´`:D!lAèÐ`O¤ .q +ÞÊ}¨s +ä
ùÐÇ +à +Ô }Üù¦ çÆ v§(L8¸a2–ªA¹!Š0ÁüàF–ºŽ `4ÍôÊ´O{£uÖjZ>såèƒ:‰9¬1;()É.‰]ð®ö*“ þ‹[À¯ò4°Ìƒ7¬£?@®áTAh¡2Áª(ð Èá³æá¸a°aÐAl‚!¾µ!&á:¬àÝh „€!Œ€áò*wrw¬mWOÁŸnáo§ñd"%³DÌá(dL€µ=w@*«mÁ Ø`–À œ`Ø @êÍd@| \ÍBa¡Ð „ p€C!ˆþ` +¾`ÁŠªB®À L®„@y†ø¢O +¤`.¨€zØ•Š`§Ø2¬@
àÀÚµ
>aÔÁࡸª!Èh¡þ:Asú€dÏ:Àm6YT‡Xhó¬ÑL•(`É^g8fn’*É’’ã=:i€ç=Ö#”|ni? ZH“®VAé–îz$Á,~¢¡èaê衶2bÁì ¨aܸA†à +Þ 2h`–øÞÇÂàžPõ|uWW׈©"?yd”¸†þe´$K˜uWÛ *à ٖàV½¸€è ¡8Ìà8o@7Â*Ál!”×lðÀ¨Apa´€l4Æ ÞÀ¶
+Áœ!ˆ`³ ëˆ ®`‹ ¢ˆØÎ +†þ¯0ŽS
ÜÀ +ÐÜ`
Þà
äÀ¤!r¹A¾!ˆ¡ýŠ†Á{å÷ÄŒ€B ‡c¼‘º”<îãYJ³Ë¬‘“¬Œ€Í-@7pg‘Vvw–LÕ‘¯Ê‘˜åh™”ç–`PG"aS!X¡x‚á„3Öî¡ÒÈ!†ê°¡©
°€”W +¥>tàŽ8× {dW£8%[†NA1Ùqwõˆ +ºÀœ +TÏZ¿à¸ ÅÔ§¦Á8ÁàÀ¬ô~€£®°pÃAnà’ËŒ ÚÁ®¾ ¹áþìÀÀÈaúùOü" $ fà/”à¶@ + "äþ Jl”`÷Ò@߸€„Á3n!naMf’˜ÁRa2G
r J€¬#Y„.vV–9–˜{CË*¸9 £;0à4·,8)“Œ# {‚{¯ìc\zcDp# *A(²¡Rèá4ˆéÁÐÎA`áj ä`Hïwÿ„ÁúDh „ø®eÚ Û z¡©B|{Wp÷ + € ˜`$ó€sÛè b!šÁΪ’@| pIrpÃ`Ò¢ap Qãþ¿@X@!€jÐaÈÆ 8ÆÔ`/1ÆÇ´Ü tàøšà
n@ª@¶ 8aÎ |°à~Á
ªÀüja~a:¡ä Bᆡ*ú@Øàz@J@¬ˆúô7.3]Ø*:ð‘…vy¸ƒ°0Æã®O@çžù§ætÇ. ,»›32Çbamä€2ÈÐaØAÊ¡¦˜¦ QC +„ |Ô<·y@Óh@‚àX2†âo·¸‡Û !-ÄþVfwp›ÑU$*AÚ€
Nþ!DvÞ#7¼=d!b`€ Br›…@z –á&A
Æ Îã aæ 4F‘Ɇ‡i€UuT$¹ó¸ê"2<˜f
¶
<!€Áà ê ã.6!çœ@tŠ,å®ãXî#]Gåäjf=°tŽ¥uP ®*IŒƒ“xÿÆq= +@»8I±+Ê6 6Ø›!!je8°¡„A:«a±|A*!U,á +¶Žãƒ}ø®÷Þ#è P š@z€ tµ·{›$ó@*üœÏ_ÄhŒa¸í€%ŸÑ»ÀÚþáJ!*Ç Úà Ö3ª;®`oÿ¤¢y^£ùºÀ f`n€l©e1® ¸7 ¢Í¡‰¾e¤ +AÞÔ›@
¾ ü‚ +¦@‹ #ä¬;Ô`Å,¡y(á
@þ ØÀHÚZâ` D€„%ÝI8TÙj8*@å„Ef¸3»Ã’–cÈ…7”–x’ü;Âñ7¾£—Ùeõk|.{Ê3;áá<b¡:¡ªÁ2–,aÑ.$QÊà§:®—ø¦Àj@câ€H—@DœàÚNa$Oa@å@æÿ\X…»p›^õ=*KAþn£~À€°`t±à.A´þ¹d y¡»¥Ã ÆZ€:BJ D€h™Rf +5‚$yC¥J’$e´X!ƒäŠ#c á±iR7e„)2QM*e¬X1YeÊ3fªHiÊ•3göô´Š¯5~úÀ‰$É OÓÊù"ÆGŠªZ}ÀÀÂU(\ýú@«UUÉŠ½ª•+تZ#<¸pÁ‚ØeàànUðÚ]Ð7/_®\Tu Ø.âP9Ž RǨ0eêÅ +P'`Ùʵ{çÏ«JÖL™"å´–§¸¬"„H’+N , +U–¡8ŽvYKtþ*¸ðàc†?eÌš5áa 8gÂäÇçPò3v‹œuä´q‡
,Øä8‰£
PÂŒ Óüǘ<E¶,8c‘§Ðˆ‘_
EhAÅ{(AF%aÆlLQ„F1‡däP T ÄÆäT|1Ë/pìÁ“\RÉ$~âÇ’ìá‡%ŸH£M&vp¡‚ +|EØ^[
‰ÕZ`- äU†ù€[d \5%`8_€0X_VÚL`˜”0ŽI™dŽU²Ê¾øÂʃÀ²
9ï´ƒÊ! d‚ FLADC[¨¡Å„Z˜A…E~Ìqˆ0þÔØR7ÛØbG)ÖtcLÃÁ†Ç*]<Å?´çž,Ÿ|ÒÈPØ!_Àñ[8áDFLHC +4° +ŸsbtQÃ
4Ä4ÌpR˜AF44Ä@ qÆrPò†V$¡~ÜD
H¨q…STÁ¬gA“MV”Q…iXÓŽ0³Çe˜Á‡~DB£¨ÁL¢J0Ã`F¯>žeæÕZfY•ÖbŠY•ÉK>`X_©”^Y ¦}Ùe_ ¥•(/9¥`bŠðX$B#%É$l‚É/“°RI0Á”cN6,ñÆ”¨AÇ>D +þnÌdâ'™À ³°"1ÕPc
8æ”S.ÊX#ËqÅ‘Š÷)§BçÜtí½ç^"P01†^ Á\h¡[PDDêàPŒAËÞ E¶AÑlS¦g;ƒ[œG-¬Ì‘ÃDC„ÐZAÓÇ€$žAFµg¨aZe¡(¾ìAFO{D¢$,I”"‰%½ô²JJè ¨UYV‘_–’c…W^K– $ÊU©,ÿWOÖ…²™(ËUÀ]6ó5öy‰/‰©ÊúîrPFh”™ÂþÀ +f°"«è6ÀK‚ +lxÃÙàˆo¼ƒìþІ6†Xd"ÇpF3`Ak¤CÕG7Êá6qC§P†pÆðž¼*>?`ÂàŠ8†G<¢ïqNâ‡ð°AãQÂl\sfÑ€oaˆÎp0 ìGŒÎ]žõ9ÓáY78 B‹^H‚lx„&¬°FÐ`# b)b!„w•_;á—¦ð…Bpbz ƒÔ š4² +\%(Q Ò‚¯À„àx ñ‹ß”Ðr¾TîåL‡ÁKXv†$ôPËYüb3Á$Æf¼“^ÔÒ¶X ¼ *&aLÈôÁ̸+Ž!gŒã¿°ÂQ‰8,C„#¤þÇ;F8bÀ¢Íð…'`Œv¨Óßø8ª‘xÀ#ÊÇrNq7!2§Xƒks~ÐE;Tnx°Cê‡6(XÐÂ|…ž"¡9‚¡°è1?ÙêÁÞ„ÏÑ@ŒE˜GM·, à SD! +‘…&
gÀ#bB„)$Á +bp´ˆ`…7ZU¸—Á @Lo˜Ä Ÿº6X{@ü€ U`Bq¸B +Fi¤i}‡ÁÊŠ”$Ä€é|WÚ™’˜ôó¡1ZÁ’ÿh†¤À(æ—{]ë”À‹b™¨ˆŒ$ô` _X¢À€Å4Øq
#Ì€ˆçþ;æñt´Ã›Í˜Æ3q% +Ô€;ŒQ
sÀƒêXG<æa{ÈÇú"u.w +Á™â;(bÁFÈa¸¶À¸+\ÁWç±V
j =ª`=@Øè
œN„Bgh‚ „’âQŒDÈO~vš1pB
¸èÅà ®-@ e(´ÐIPÊ‚¤€¯§Æd
ƒLƒÒ†¥–!’k°Ä%þ†Qª Íp‚
ü$Ù^–D>»ºò;;YˆDÊŽqE¬†ÉK–fF/&Kjý* +8«0¦$$áH,2«`Ã$°Àt¼ƒd Iþr!wÀã›åp†02!ˆA|á +g ñrPãõ¸‡™çQzÈóð¨í¨”áÃ˽']ƒ1À +ˆ@!!‡:‚qè–`*LÄ‘+‚@ KƒdÝ !ÏŠ.…6`ÁÐD´p-œ(~×xÆ"Ôà ‡˜Ä¿xqH+4Á
dÀˆà6°¢¦ƒ”–ª`<„!
ÆØSÉ°àÑD
jxC ˜] ¤a‚U|Y?™qcw1¶SéJg{/ôãð[^ɯŒXĽôaî"˜¶îÌ–xƒ`Q± +^¤‚2B.à q‰Bìá +•(9|þ!"2`"éH‡6ØAŽgtÕ%gظЉR€£ÑàF;ê{¨Ùî¼#‚çS„ÁSB´†8^>·uXÃðùÄ|ôƒ0ԥà Í,\G°‚¨€ƒ, +A¹§pF×Lá"“¦º0„3šn u¨D€ñŒ_¸+¤80B¡’0KœA E؉J '¬!d@È ÿ‹ì„(ÈhX°Êà+8;\41ƒÁè-€Ãr€X H[Yë»]ÌV.¦òìËX’@†– +ò•sAL‹ï2˜.©UK©G}É®B:\C°¬ø…*ö™È˜“¨Ä"Rqþ@$¢Ì~W-²±
Lb4×ß/R%ä¡åÐ&Qn”ÃRÍЄ4A;4Â8aЧ8ò‘yÈ6ýâàFsñ‰U‘
qà¹1:(îqTätWF JP5‚R7`EFèr8…F×’-\@ÐÀÀÀ •ªö,?À–]HÀ/P—wà +g@JÀe† $QlïâÀÀU æ0è‘IrÐ +¨h€=g°[P(àôsyEB"özeåã¦'#$S‚><ó §äbíƒ.öb±”K`òzpÔD• +‘±`þI4Q ‘€lT !aRÀˆ€e1‘gÀ.QRB05°‡Ð N™mp9 ϵå'òp*‡7ë`ÁQñ~ëàîPÖàap*]°Lds·‘ˆlgPSò+ 8ë‘ÐVp’³GÖEEÀRHE%U@}qp |AÐ9?€Ø.bp¨15à JÐp¾Ð"Ävwÿ…;Ìöw^€ µ`B©@#z@4±}={ˆCw%Ðn‘neÅ>¨·axq%A¢«G@ö…Uñ?3.#?HB¦ÇK€!2þo oçbrt †”! ¹÷TW|@(20”ÀÊfÁe\vH¨1B@ˆ×&hЋ)P8iCð?p +•ÒÊq÷Ô£`
úêp +£`²ð9×Ò¡L°_ ‡±`cÀtЫ£\Œ’t;"8ÕUÏBEp§14áVào QŸSÕ¥ht@ë@¿àQ°’c:= +«`X› +›À %Qp÷_oÐgàf sà +Ó0Úsû²`£yX{°fWp(°Iâ?
.†3jÕy~Q&\þA…X²…!KZ¡2j‘gb\A†Xa‘9c%Ón}aT$rÑ ³÷¹žýÖ0M¶ØÓ’Á#"3Á.ÌVkfª19z”“Ì‚D`7€6 5à9àP`
ë`£èrÉ1*Ÿ`
Ê`Ýò àð 4w•ªò:Ž\‡`¤À
±tÐPW°o°Ip80.Ÿ¶gЋ¨/šZW—‹’ZðH€M~ 9Ò¢Gzt1ð¥ !w
›@Òˆ:cð¥0hÀ{ ÷b<D€ÎFNàsÀ À0
×à€_X³šfIÕÃopþËyÉ©b¥JÁ€2yõÅiz|!$ò¦JW(?°mt…cùƒK^‚_RbäSWZapp
½€ +Bž¹·oj°tà +ˆ`ïàBXkv/û²!%<S`“59mt-Е,@È:PÖõà âÐ
Ö
´åg
õ°Á!õ
y yЩOphKPIƒ +Ü
Ó [€‚âU`_³Tàû%J I ªz‹w‰7€G`4g€ü"RÀ,Ĉ.†9¤øp¾ÀH °Ü"À«@ +îånPgð.!Mu]†þÀ¦-ik –´~0 #Ú T0“WnäC&6¦À%–W_¢Mh^AÛF28vó3‡1‘uªW4#ônìÓ„0©BQ©mâ†B šÀg +±@–0Bî%@m@Uµ%•SÁó_Ž&99y-@,I°KÀJp5ðÎPOQñ ”
+¬‰öÐ
)yâpÍ+K°M°d3´
Ú \02BÐFZ0o@dGˆÖâ,2 FApèâ,3(0„H^©a3à$š-1` +ö`f瀅zà.ÀË°
Ûà“þPS6qƒTTÕâ~bð +[q&šoÝr5ÓT0p>jafc†Z§òóCò>`qJ‡ &…q@33@X²à>îƒzWB…I‚[XI«´’aX’P ¯
å€ÌЖð¼V XæZ°‡”Ò’“Ö2Q·])pG`FGÐy .ÊgËa
»¬êàJ9•3÷ œòx£À]Ð8Cø\ðsà •JF ZE0×’[opŽ`ô,¦£-§3) ÕuRÙ"-ÖB8@càI€0ôpï€ +ŠP +Á þ_d¡àÌh öwu—†@Žfà +× æoúb` og„}aj`)`½Jh†b?ge3J?»´¨_x%ds‘V‚*˜|½tc9ìËK«G´hò;– +©À&dà‰ +’ +¬À +¾@lÀ=‘hxp™À +ì‚"Fp¸@h0›'a—¿xH-gd&p>iJ„ ÊÂ=äC.ç‰æ(gOÁâ°£€gvà ‹¶ÐM°+l°`ð_ D—‡dŒA`"(Dl#%€“3Ð,Mœ-R€Äb4R¦ó9¢-CpMPþ,` +í@ÐpÏ
™ 3ptŠ ® +[“à¤c[À ¼0 fP +ÛÐ +iPwÅ»rp ¨ÀÀ{ ‰y“œ†Š$p%¹ä>Áänp‚qVwj@]AÔCÍsunôCbán**«ÿÓKBbÐ÷цƒ¤{€ +•ap j@¿Ð0t¸€ÏÀ {À € “`Ÿ©@¯`‚0½˜“Å2`!`)Ð#= GÐ]P”ö¤´e
è— Ã±Ê°òpgyðb0u¯ÐKà„ËrçÚš¶f¥Â’EEPØþR—R ¹…ŸH`¥A€«¦ƒ.å5R¢›9p «]u°Ô
$¤
¼ €'èÃÐ~ð}]z7Hjp —PX3 ;Q@.}°”ðwfà̦¢•·I2ØVÜ˧Þæ½é%¾¹„¯·Vªgå9KVðÓ¨®Ô%é&cQͽ‚q>àúdm¢’€Ö»·’ð—p‡¾pµƒ° €ÀÐ@ØœÀ †` %(ÀÀªðÀ¢¯Ì‘Ù2Ð;€<N»pH‰rëPfòI)y Ý`»pmðaq ( +°>°þ(¨X`U[9ˆ£³€8PALÒ¢Áo°Y ŒI°,^ À#Übàu§ó,%P9%…P@? é@ôp
”€×‚\_ +× +R|ÌÓÂ;H’¢V;±¦Ï3<[`%ÀÌÙ>øKÁÔ…ýCÔðo|ÁßPh•œ©Ô„ 2SÊ[8³VîÓy)œ†"`á…e©à f°zðÙ®•@ q@tÅà +‰
–0²¼š°†À +’9°[@•Ðl'ªF°B`ê!,+p/°:à *JÉ«ö°ù %lþ
»` +S™c@ +µò\ÀL`ÄðO¯J0S†@\(EÀH@o}^àMÀå:€°÷B@˜ÀE)à©°#….Ë"(УA`•9ô70ßàèäÒ¶ƒu œÀ +¸¦bx /ÀæfÐYð›°k²©n°ì²C·ùíV†A=ÛV§‡½YBÔ–72õ¾9[¨XA&êF†Y‘éœáføíûV©à¹Ðá3âÖ–À˜LsK`Z —0ÈpÓÂðºÇp¼ÒIÐV€: BPW€&Aˆ)þ @Yc°ás7Öìrâp +ë€~öÚò~ñ°ë„PaðP€ÏŠà
¥’ýîFÀ ° Ÿ9oé¹ +jðkŠ€‘¦-úA¡c^Ë)ð9·XIl:IA‚ƒð
ç@¡ÒW¬` +5Œ°3Rªd)3Åa•*R,R¬RFŠ?oö¨qóæÏ7gÐ$É"…\2`¦ËÌ„É`AËô<ð`g?LXà`gÑ +B{þ4úÓçR¥â,ºàfNEt…Ù3©Ë +>»öôI¡/^¨ÜFŠI.¥5{ⲉó†Ž*f½:îþQtY0KkÊÁ›WÎ[²wøè½ó”)´Ep`ÁŠ%H•!I„)R#E‰5šˆ EK (§N'oìuùòá“®ž¹ØîHåJ$§'bÐdi“MV:ŒäP’É—5¬'¡!„Æ*Vz4éAC +"Eˆ!„"Sf̈£È
3pA$È"ëÐ(¯ ^x#2àCá‘uìy‡f¦(¢1p¹†@¬@"‹4ôˆÈ +-Ô˜‚‡È¨bŠ*´Ø£Œ,Ìø£E8àXC‹+p!ƒ–ŠB릖¶2-Ÿnºé« +€i'³‚*ÀÇ™ž‚ŠÉ Š¥ž&I)®tþJ*'Øê%(˜À +¾ôé rÒ€¶VáE’T$уT&™„HüàÃEžÉd?®€ãfZ9$d 1gž{àÁç|ê¡r¡†˜aˆA&“<6‰ãŽ%tXâ0¶8‚98áDœtvbŒSÄul›u}öÉÇOùD–0è8¤OÚpF[‹&ž¸Ãçœx‚VàA%r¨A;¾£“Vê"ˆp‹@/=ÔoŒ $P(" "ˆø¼÷ìÃ…©¤Š÷h0å›tèa§’Ê{äšVÈ ‚Š@ÔÐH +,IÅ‹¤0£ŒŒ4.Ã#8þÔ¸âŠ"<¸ ')Íjé,ž(ÐJG—(€È€dÀ€¥|*ªÈ0[¢Àª¬‚Š‚ +(°ƒ–¨ª«¯’Ú +KtêK¤új¦ Ìœ W~i‹IÚÔ#’?(äƒ88$L¹„IøPc?,ƒš×©ÇžÛ½‡zࡧo{çxÞA™gq„mˆahjÁ&s¸‘Å5q¬¹E{ìÑGŸ|n•Ge’YÆ‘R1$‘PŠiE(BɃ‘E„ F(êÀcN(ˆçzH!’Àrx¯ì¡ó€ˆá†P˜… ¦@‚õhxã-æ½a»÷pà!þ18ÙD’údpÁµÑCD+¾øC"%èH‘¦@†B +)C‰*¤¡c TÃà0 Aøa
J˜ARÆ—=@zÀÔŠ¤ À%JÑ +Õp3¥ E,Vé™OšÒ”2= U±!`&¦ýH+Yƒš–®Ä€…GD´@RÁ–%ƒ¿pE%P±ŠXØ„0ˆ±ŠVô¢I¦@#t‹ô¸Ç=â±}¤QpŠ›:ÚÑgdó G9 ‹-СåÈÆ¡œAjP£ßP‡=ä±Hk(ãÒ¨Ùh{Äf‘õ‡5Ú@g0ÁK€Å1B‘Fx·PþD ‚,A wpDzP8á22ÂJP‚úl§A¨Aœ°Dá
8ÀÁ{Rp3h Búh@ M°‚|î`>DvP†à® HADù™—9E4JèA"YC*ø`…@PÂgpƒÝü@‡@üAFA”vĬ¥jf ÒS²æ§%€K9YÚS΂£&A%e¨Ê˜\2´°tÔKAK™H–ªìăoXEJ…k£ÚÆ/²1Žq°¢Ø`Æ$0ÁŠWPÁW¨Âšð…AX0èhÔ;ê‘Æ{´Ü(,ªÁd£æh)a„°
XÂþŽ°„6`†4ðQ:uÈ#pë¨$ïa+INrtö€#tñˆD¡„XF:ºA8x”B·àA(¢±OØ¢ÇØÁFqQÜá9( M¶‚ø2 U¸ƒ"¨PjV3B&2Uнj’F>äÃ&&Q†"ÌÀÕ§ÖCŠèbRX0 ñÛ,èjØÄ*Ôð¡5hæ•ÄjP‚ÀÌ)Q£IH!jÄ‚ž¥H:ÓQO¾B´…'P)SÊ*¦ }åi8éJ–r’¥ñöŒhczØÄg@C¾€Æ8®¡rÐ4͸+Þ‰=ô!#øñ+XŠ!Ð vHÔ;þØ1x,õâ@G,¾aDÐb¥Þ@†'Žƒ¨@4è¬V°¬à?8Å\ýv›z¨CŒEmêj:\5jðX‡ê”±‹Ñ‰ƒùˆÇ2âŽRPù°Ç<ÆaŒP £íHÇ0˜ ‚ˆ )HÂhЂ(8a&HZàƒôàQàAš@‡&(ás¸CxPu¥@]D°Aêˆ@Dh=ØÅ;èÁ‹÷”³>Hˆˆó0‹=\D€dB±Š3\á
}4&(¡†„ 9DK˜¬$ºð']zJº´Ðñ¢÷);¬èOlÄ´îhG\Ù +p=Dû–©* ›€þ!˜k¨¢Ä Ç8ØQr¦ª™¨@qAFK B¦„+„á‰û7ܱ8‚¹²ð„%¾`ˆLl"˜¨DDc‚œ@'0ÁGc¸Ctöè[=àp(öH£€ÒáÊt¦ÃÇé&¹|„Ëô°Ç>êÑdìBŒ(Å;¤á „ -Bžs‚$à‚:8Á¶ „Ehâ ´¨†!„>Ê! bÈ„!HAˆî¥ >Ú¡¥.±‡Ú¢ë¸Ç9¤0 Ô˜¾ØP%ñ[)h¤^ðƒ®Ïù!p +<°¨ø(+$Lᕲ;¥)…>2Êjøþ¤/íGÛáÖÊ‚l,‘)B ¼²¹ò’‚>€"`Ë5ŒI<£èøc9Ú¡
f°¢´àÅ T„<eá|ÿÙÏ4}ˆmÄ{ŽïHÇËA
fø"œ(B¡ 4(QpãѨÀ*XÂð ipCê€G<ÌÞ0Jã’@]p:”œ·ÚGúoó¨n´!Q 4Ñ…/,b[«€ƒiÚØ‚6h0ø<hƒ/ø4È\P(ˆ:à,إΟ Àu;$èž1‡ÇàÙ"h‚2ЋÀƒMpˆ‹á±‚*ˆ º>68þ‚ðX¨%Ñ#‰‰Š™‚+q€ 0)“²‰^Ú`ƒ’Ÿ¸Œ¯Ê3’:<³à ª9Šb€ð¼ŸXf¸r¸†^ „s`_ð†w0‡whf Lf8ƒ) $Ђ¸¡ƒ$‚u±&ˆ†t`‡q[؆qh†Aº"CÀ:X1%00$ @h¨ðÈX(H„D¸…j‡ÁÙK|ˆ¿Ž;ŽÓ‡ƒ¿K?\i#{è†1øˆ‚ƒCø+1 @Ȉ³]¢û¸%P@h”p‚-0X²øˆ÷@gþ, Ržé"erà²+$P‹˜‚,(Iµßš‚4H‡ˆ 4x„?À‚ð讖óX¢‹&ԑ̳ –ᙫ˜šó’¨x<ðȨ€"̳’ÀÓ(Ãí² +œ€’Y°kÀ†_@`†Tp†v˜‡©*Vˆ…`°!ØÃ7à‚X†4XE0<HatXÄZè„P`Z\à„иÏPΪ(8S1 …R8‡s Ch¥ƒFh–8¤nX”’Û±ºz¿¼Ä\ÙÅIJ¿{è1S@†R0…0ˆ‚<ЄCX/<p„%(þ
ëYF0èƒ/Ø‚6«ƒ(…?h‚(xo B“žèóQØ¥ƒu Yx$˜°˜rÒEP=@ ‹!ƒŒ©‚¸Fû‚@؃+¨@¯ør€øB¡Â’§é"y©*„!l’$b–€–X€3ɵª¹š"‰š–9“—(†ü ¸:`†nUˆL˜fàjÈÉwØt˜†fø*ȉH<x…*ƒL`O€o@` ði˜‡vØf˜…PÈ„1x†fЂ0‚!ÐÄÖô³5àDXY†m†Ap‚%Pþx0ƒ%ÈY°s@¹{€¸{E[¹•«Å$9^¼•À©‡x€x]°ƒE< …â (³m#ø'Gxm€…\@.¸L@ƒÑŒ¹qî¹"`ÆiŠÉDxvx‡s€„ —Ј²#¹«+0.)5ixƒä§3xµ"Z›¯+Ñ/]B-!/ˆ¢BúôH* +I´8!Su¯©P%"ûú €û‡_ÐOH …vœÁðr`4°˜(ð„^X%€‚NÈ…kè„Lp†:¨…+˜à‚0@jZþ_@m†ð ‚#°PÁ‚#P%й'ˆ‚-ØØ#ðÀh%P(È[`i¬xp«|@R’ƒ?¼ÌË[‘Å’CR|#•+Gà‚PxYˆðP&h€ƒ<0opEð@èO¤p„Gàg‚+ ééÓû]²¦0XIû…rD¦,q)§$è50Hˆ‹Ð‚7p5ˆ 8„@°‚W‹!÷š‰B¡2€› Õõ$Õ&¤šŠ¢¨óÚÕˆ‹Ê(–ˆO‰Âš$Œš†,é¼¢aû$‡`èT€\ІþL€I›o`t¸†?0‚3HC„K€.XNðbØl…c8†Uh‚ °…bð…V`XP…WðUø#(™#€3±Tp‚8¨ƒA `±à'H‚PÞ:û'ƒ¨ƒGH¼Z“»
Û ¤xˆ‡µê8I²
\aX#ÝËF¡‡\Àƒ\ðbè‚'hS¨˜³/BX<Ð.ˆ8ø‚!ÈÌï1ˆO`<‚@H‘ȼÆG@‡{Іxt‚BˆòÐ`1XHX‘"Ð) - ƒK¸ƒ9@ƒ 0è³x/öˆL!"Ùþ +Å[’ºš‡”(‹„ +6¢©€”ùH¦ñ¼//ñJÂö²u™ˆ¤¯ÑHd…¶È„aWà†Ç0r8‡c¸! Ÿ.Ø‚1àKpÄtX‡w(mã8Ð6Єs`M…8ƒP€JØ‚5À‚’1‚Y°€‚.à3:¨ƒ0Ð_(`„å[0Ðp‚°<0…ӱ
#µ‡GY$Ò±ÅÒIÒ‘sRJ +tè<(…7ÈG…0¨OCˆƒ%8'¨:°¥/As0 ƒ/°F@fƒB@ÀÌ*ù/€Mf„e€v`/ƒUþ@…p¡ ðM€„öˆ—1b4@5L˜ƒS[7ø€ø +)€H©0€¯ ¡r Éš|öŠ /`;)©()b¤Y¼)™H‡ÜÚŠƒ²`€úĆkœºf@×qhw˜vœk#+ ø‚gðMH†@J‡*}l8t°C,`‚x=WƒE„5¸‚i”BYøèÐ8`;<@F „ÜDȃjˆa` ¨R0m&YdØQ¾ÙðÓÙEî}?$Ekð°³c ‡6`Y0„:X`(YP‚&ø.Àƒþ;€ƒ8˜ƒÆ%8ÌpHr0:ˆøS +Ä¡4Ò Àv m`…3˜2 ¨ò˜"Ð3˜-XJøNèºÀ‚AžèÔ‘‚Š €‘z(°g¾-ð²á·-[k’¯ C*¤ŠòȦ!¢”ü!œ"³Èî¬ùBðgØ@Ògx…cȆrø9¤CÔ{#ø ƒAð<hjð7L½`ˆvhvøhÁ~†kp….@É,’M’õf–@$B„EX„N^I6.†að(€‚SìØC c¿'åzÀ¤ÙK[‘Åô“XPŽþñ|P•Dz‡Z°ƒh¥(Hž’ý€w‚<pXb„GxCˆ…3`YRpq`Vˆ!d’žp:˜ƒÈÜ<
k†MØ‚)Às*sqž‚ýé)ø‚B(HT©5P‚‘à»÷¢RÂd»¢¯=7è’L6ßvnñr’€€¢ŠŸPè"Ú‘÷ʼ[å +¡p/¯ +ü‚€¸Ï‡l`†s{év(l u^Hó)0‚:0 9ð„rŒÈ€†fÈlØrÍ®eKy†0eðˆL¤p×S„•eF8FøQ`u0‡[ QÀƒ.ð&þx'à ØFk82¿±‡uPwˆ¿é˵z¿¹n#5¨‡OÄ.ØÑ'p@è€/Ð1ÀdXa@dÀƒr`†P†tøºmF@ κ @0!¸@ˆ]Ð0†‡„ø-‚ ‚"Ð--‚$ð+x@„MÀA˜§“„¼ ‹³M¡àÖ +" àŽ¯Â™Šô ÅK€è°€Šx<#.C!².ÏC¡¢ï’ZËî/
pm°*lІmÈ·Š‡zpv`ûs„)p+¸;ƒEP!(êÐ-‚ÍDPXðP°„þ\èB€Rx:`p’ý€„ówø€8Kx„`€ƒG0]È…RX„C`‚G0,FhDÀð<%ülƒRˆ•dÙ˜
yˆ¿!ãEU¶wcÐ[p„\E˜†gàð(•è€ƒGèGPjXQ0Ž\ød wÐ…’f8x‚eZàPP' %ˆ<ørxȆ= — H–·+ ƒ2€:ø€„ S¥=U¤ÄÑaƒ6\``ÅŠTd qADŽ0xèÀ‡r\pàÁ‘<ˆyòA(Xx@A'Ì—#þ!RÄHâƒEy…©Ô¨ÌšcFX&fÞèÑ»wo^;sç´mÁâ§HžgÔž…J2£F +3hÈ(âCˆwð”òF, +RÈ iƒº&B´ÑÁÄB¸:‘Æ훬:\Æäy¤,š.]¢Ú@ÉÃÈŽDÀرK™¸oÖÔ©³w/ß>ûn×¾oßî|ùîÉS×í"D¹ŠÙúDË"T˜èð"ʘ(bbc*Y-XÄB=.«;ièØ¥kSãÃr?ä9¶©F .’ˆ¡Æ®º_4pHU!E€R¤AFUl¡Æ…2 EÜ`‚4ôRJRdþÀD90TF*5”GÐFœ´!‹/5cL8•S°HAOà¨ÑH"rÄPJ"Å´S=™4ÓˆÀ +3ì“É$œ£ÕVðt%Ìtì‘D'¸ôÂÆ%>àÁI%аbŒ!†t±0Æ-ÇhÃÄ#ÓPs(ƒV ‡ðAØÈ#ˆ.ÉsH'ºT“Í2¥£Ë2²àá"Žx"‡.¼ ÝËè"Î:âX³‹<´íƒ*où裪o¿ÁcM#c8‚Ì2ËPƒOô0‚}x,27çT“K„ˆaÊ6È|"Š(xÄRL5æ|òÈ2Þã‰+¬à…1¢&)¤ð Zˆþ±:üaC†~˜QDAhàSTa†f|AÉ$~œA
|pFA․âL4Jet°Ðh’QF½XT’M]°dN7½G–<bÂ@qdrËE)õ@=ePÈ“Ü\à +-ÌØó[=õ¨“^…°qè‚C¡H¥ä’L8é ‡Ž6yÐá]À‚(d³
;—tPv…uòGM5Áx†a„!Š3Ä”²Œ2·.ãË'yàQ‡§uúÁµè²N>öˆsª>½ÑfÛn¸Ý–<ðHS1ËlM1ËHS)\ü`x‚:é|ó
!Ž„2†.žþ‡ò)ºDzËyÔ)p8! +. @ä\£%¸€EÊìÇN3‘àPI”QDh¡‡Sa…jXñtœÄ%l ãÁ@GtD%QLø{ô°D? $C:QËB"£ŽA &9i@É4Ò¢€h#ÉO&裞´$&>zÉ| •q\뚇•êtX‚W8ÃáÜàmȃºàñŽw´£7ÄŠVÞA
<„AÇP#hQr´ O„!"¶àìâך „0äb¢(G:ºd,Cé¸rƒ1tj.x„#|c7â´™þ\ªXÕªTÝÃæ°F:¸‘ŒjPCµ E1ä°ˆ`CÐÆ d´†‰pD)Æ ŠRÄâ¥F#B±R,X¡€E¾pàà„Á2˜á¨€tÀE5Ðq(©
N8CªP„ ái¾Ìà=TA nàƒh\€Cʦ™€(ùH5+R” ¤h&XXH^t"É(&!³‰Ì`$@“(¬€ï»¦Å$XÁ‡ìäEà…6Æ!ŒL£óÈŠVêÑ_ÂZ‚¦`ƒ"ÔÀï€Ç<Ê1t`cÜ€‡:xG|Àƒž`B,€‘‡`l¢|*Ìþ¤Ð˜‚iè VÐG$#ë8D{ԉ𰄼@0‡8XŪ{¬ªg¼™jªR4p#§·øD,d‘;°à…ñÀKIðÔÀ`Øœ3€»Gè‚ËÆÆWb<¦R‹P”Pƒ- ¡Ã1|aƒ!Q 5ÊÁ
tËP†Ð7¡@*øÒ`†,\¡Ad +:`°†ÀÏbýQŠ:²!Œà› +ƒ_Q"ˆ0 %?Ñ SzÍ%= 0šÇP»1Ü +#"qàm)x1™8@«ÐÆ5P +hŒ£XùY=Þq
^Z¡—A(Âþ¨q¹r\ã†C'jasô¨Çlö{ƒ ˆ¸$.Æ %âà¿P †/< ‚”€0€2”ázˆCøx£=6aj‚?P†)âXßL5rTUïû3p(Cž€hFбö)œz¥V€d Ã¥ð‹2¤q0<â܈Æ#m +OÒ!/˜ÄðÀÐÅœ@‡9œ ÕøÆ4´Läad A¡`¡j¶B‚Ì -4s؀⠀»`E +@†„a À6àçø±ˆc>QÙm]‚À%IÀБ¦!w#1ù‰Å&þhÁ“8P2‰6®‘ŠU°ÍGAë1q˜›P›tLƒ½pÂxð,ìàXšˆ†9²‚ûÚMˆÂ1Б-¦l.X‚A Œ ö‚±i$Ê»¯:”{Ø¥U=ìñ8:âÆ©w|\éªãypD8ÌA
h¸ *eÏi\àôàc`D'ŽA
nì žÈ‡p°#ÉG9Âѹ\¬" +x„p`!<Í`uî „RP#ÐØÆ4^‰KLbAjP€Ð„=˜A +f°Â¬@5Œy¦˜ÉHâZvÓ~‘Ÿk5bþ?Œ°¬arz8ñjàF“ +TÊŽ"H±;&Ê}_Édr¢\£º’X zA
ûÞ+Ù"XQ +°áÂ@C³a½„+hJÈÂ"@ñ0!Ú=ömð¡'ÂÅxÆ >P6Ádû[`>àGäÁjÄ.P4w¸{Â÷h•)W¹Û×¾òõ(‡1ª!*p˜ÂZð0‡2`(ˆa.pÁTÓô@ Oè6(¼A
RB"ÇŽ»u¡cÔ F(V<‰—ŠÀŒÝ3ñ%Èá¹Æ0†±kî¨ÄªÐ„>ˆìœ˜AøTA˜ÁÌ€Ò…ÄþHD…ÈOŠô‡XÖ¥@ùˆˆHG¸ŒqÄJ8ÀN\€Mäļ;MÐ7µXŒ4UPO$ÅKI>€\/ $ðÂ/¸‚-œ›VÐC9ÈÂ"`C˜ +àÁ3`,l|̼AˆÁü^lÃ=[½-‚(|Ã;ÔAiˆ@¹€,!UìÛü-$C,$ªÜƒ:(Ϋ›ˆñFoèFÑm˜Ð:¬ƒ5èB.¨K;ØC:¬ƒ;¬KÃ"ƒ¼ÀhRñÀ&ê|A.|Ã6¼@<B,¬‹.@k´C98ƒ(¾
Á•!DÁþ#lƒ6øX‚ä*ÆB) Ã4<Ã0,X‚D‚ÈeõÁ Zû Œ†…F|ž…P LÂH„@ÊdE€Ð”£žElIœ ŒÐÈL4qM@s Ì8ÍDÚŽ<ð€uA‚$L‚$t‚1ÐW=Ѓ9HC,`38Â5`p ÁøØЀÐÁDu B1ˆCnìÃ;Dƒ#¼9,äŒ|Á8AÙ<Ï74‚8˜ƒ3\.°ÚoȃT¥ŠÛãØFUñá=КP#t:¼=Àƒ<ðG+ÊþøÀxAà@i@,A:uØ‚7”
±7Pƒ…9È‚#àA€sä°8C(0¬(XÂ%24C.è1@Ã50Ã,¸ÂÁX%@ˆÀHhœYÀÁ`6•cŠEÅÓÙYD<9LKÄFе֎¨£åÄ RÀoZÀ‹˜„!Ì–Smg9™LÅt@*X*H$2ÀƒCÒq98ƒ/ÂÈ@ +øÀŒ(‚!ÀÁŒÐ@ ¼Á°-XC=PHUƒÛÐC;䂘À€‚XÁlG6”BOþiC<üÌ7”CWÊÃ}Ø„RŽ>äž<ÐÃ@Í<tC4”ƒ4|B"‚´08C.D5 Ãdì,ø´„Àè€,Á¬@„Æ‘U‡ˆÇ;tC8ˆÃy”C'ÈèÀp_:Ð;xÙ4hÂ#ô/Ö +22<Ã3¨-¼‚!Á&H‚ôgHxI<SœæžÙYüØü€Eh €ü|Ä¥„DàÃDDI¨HˆÈj¹]Œ=jKh£¥
…qiPõ„OäSÛWXW*¤$°Á4¼Ã@eè<¸C9C+üA˜€Å!ÌA&‚€AþhÁ׈¼ C:´C~º8È~ŽCØÀ€‚ˆÇ8ä‰CïņlpÃ%%}Ùå½JUYè„Õƒ<Ÿ8 ØVŒa.È#,#8‚.¬K(’耨 Ø€ð@l,„2tÁ¬À€5¼C9ˆÃVfh:D)ÆÝÐ;°C9l1èB3Ã"Â"ü….L4Ã140+ÜÁ*¨BAhAæA€@d€4)×RŒŸšHžêGÜ)7í)9m GtD‹ÐVLØ<iД`‘è„;mšÉEˆŒÄC4@Ë\-‘8þD¤ZjL|€uI*ì$ÃD9ä<lh;8C%A
DÁ <‚0Ã(È&‚ä&ÄA(£(k$'Ń=ÜÆVÔ<àÃ;ƒ˜€&B8ÔÃ94˜ƒ9è”·ÊF=„¬ƒ 9äµÆ‘V„¡VØWæPaÕ!DÐA2€Qˆ~(AÃ7Œƒ&$B´À +Ƽ ô€®Â(M,x-ŒÁ@Á¼€»vƒÂb8 ‡Ä®î
µ"6 ƒ7xƒ/äA'Ð)D®4ƒ.ã00Ã+pÂ&lB Át¤öÌ/YéÈPT(€ÏNàÿúOŠþL„üý¨7uÈû™Ú™Ë8r6ä„N” Õ2E@‰¤j펜D¢õã¦A@rf@$D'$D'DVÌÃ;¸ƒ;´C3 A#À'xç BÔA° d"d‚ÀÂ&hÜP2üA,¨màC=ƒ5¼ð40ä&Pƒ9\ƒ5€ƒ¸ÕC:¨ƒCÂÃXƒ1TkOUêþW¾ƒ9ôÑ68Ã-h‚(|BŒ¨€øÀˆD0tä)qŒ,_ˆ@|PÇ4C.L6Â,_sp_¯Ê—˱I,z@É#hC9x6°Âþ×8Â2Y1Öݶ'pB*H‚¸ÁÌï¼Aà@Ìo`ÈqA +ŘˆœúO(@üÚ)6ALKŒ“k‘ˆÂø™6ý„oV\ð¨`
qYP9Yí¦±H¨U*ÙQ + ‚*ð`*‚6Üпð8ÈB&x)”dÕÜÆ"B| (‚_à€Ô#üÅÀ' .mÐÃ.¨í6ÈÁ„A5hƒµˆJ:€ƒ:¸C„…ƒ#Xƒ8¼‘TÆ88)<|C5Tƒ4|ƒ9¸†2ÜB\â4àsôÀä"ÔA"0¨@84 ’ìÀä@”âþ0‚#Œ
0ô@ô€ÐÒ@C4lC;p%VHì;¤C98–7pC3̉6„"uá-žh2ÔÆ20Pæ* ÂDB¼…¨ÁA\Ì™ÁÜYŸVÄD0?h žå©ž>Fä™Ðv g3LF0LDhЇ, <•#‹X°på„Rì/èì£VÙõ#sUZJä#Í@©¡Â/T;¸ÃDqE6ÄB+´A.–ƒ'‚'°/‚"t‚-DÃ0¼Â„ÔÁpdÃé6ƒ|™C6°Tƒ7pKgœŠƒ4‡9Tƒ!¶[}σ:ˆ±5ØB"_"hÂ($‚]þ9‚8.Èu"DAZº@hB0Á‚GÁíÀˆ- ä@½:€4-8BX¹À)€ÂDèÂÝTÃDÉë”C3„B,äÂ'0"Љ7hƒ6äâ5<ƒ6¤(5410Ã0äÂ10Ã/ð+¬B!Â3hAA +”Àœ5ê7R6g§DmrùGÔ¦ÿT35ßF$ÀmAÌŠ8þlšD H¢ Ô£Ò:CH* ÚmˆÅD€û(‰ÅÀLÉ8=kª*‚7D,p³Ã8xgxB)Àõ6ø'(BFÖÁƆB+x0ÐBÜÁ"‚pØ@¸ ®}½Cþå 8A28Ã.ˆC1´ƒk¤ƒ9tƒk˜„΃<ÈC<È×åÜz„C:„Ã2 Ê$Ã(1‚7È(° àA.0BXR#°€Œ)‚×hÂœ€ +´€ +(¼@!²#Œ@Ùx€hƒ3‚!œQÃ6ì.tñ~”1ÈB(ÔÁüÀäx.î8o5xC5LC10ÔÉöÂ+¤‚!8yÐ@ÄË´éÅk‚àÃø¯.Xv$ÄxˆÉÿæ)Ö-ŒÊ«|ž§È«6p×i¾ž£ÕæùÆ…
ÆÌ‘8ê7É„¤*ðÂ5ø‚7w—ƒ9`”&¬ÁäþÂ8ŒCÅbÄ'´Â+C'„&t04Qô‰8Á,Á.PM—Ã7C'cÆ:ÐÃdÔ47Ø´2(C<ü:<¸ƒ:|Ã:¨®s8lèåÀÃ:dîfÄœ1À2Ø‚&()ƒ0ÄB(° øÀ (Ç(¼€ô@œø€ (!ˆB¼T¨€B¼ÀòáÁ^{9xÃ_TC8xƒ(<Â1€‚ˆU"Ã6èî8pÃ6lC9h7xC.bl×Ð--€Bûn‚!˜ÙÅ'A À`´OþD³ÿx£œÎ©Ïšø/6!;À8‰ù2ïé(ÀÚ¡DQDWÇÈL:þ+@<`À`AÁ‚T¸€@ 2˜P`CPºvíX»wîÚe+Çn3AFò +GN%K®ÔŠå 2N)Ò´ÅÈ;‹5‰£(Ͻ}ûî•«Æ-Z0,c–Õ£çl×·pÖ åQfí›;wéÀS§.;pÆŒ…
—n:qàªÅ-n´[r@åù’iQ±\´î,Ê¥V©0ÁlA³¢ÆQXxðQ«…à(‚" +-'‹žAóÆ®2dÔ¼]³§14!:üÈ +KrÞpËæmÛ´kÌZÝq„+X«Mœ6aº$HMŒ5J|èÐÁ‚ƒ\'P°‚íþÀo/À|ð ˜7o ö¶/ϯ d°àƒpà‚ +(xÀÀ ŠH †þÓÏ ýZÀë`o¿†\`‚†8ì0ƒ4xéålÊ)±g¸)gœfZy¢”oV"'j¨c_„A¦CŠ;lx¢“N¡‚‰:>Y§|ð'kªq†<¬áæ›vš‘&en!ÅzÔçdªÇkÆÚ<–‰ftÐ1ó-qª‘F™]œ‰%”GŠÁR¦1Æ–Z<q$—\œ!%‘œ ボØ!Š(<x&:X!XhÁƒ1Ba"ŠV^ÑD&ðˆµgLxáþ‰%ŽP¡H†™`ñæœmxƒF›_ŸñÅ.Æ ¤:ĨÃC0³"Lð`º
(è?Òƒ/>Æ3mú@,7<ó +R =óŠ/>ùÞóÏ:ë:à(€@ +8tÁýî+Ⱥ ÿkïÚ²nÿËP ÷³À@PI˜k¸áfœm°áœqŠ&jV‚‘•L袓hœÑÆ•:¶àÂŽCꀣ9ž°á]¨±žyð¹zÚ)‡Z8ÅšrÒ‰fhL¹%™eœ”æ‘j ì&s¸I†‘P:®æ_!…”\¢¥šmœiD—bŠ‰†˜ZÂÀƒgBÁþEd’±…[B1DŒ.¾@c\xB„†‘ÃDDhÁLz8æ™PTá‹<i&>Žph„RB¦”i~ÝF›hf‡†_&\À¡‡(¹£’"QPAÚ8¸€ ƒÆ“/=r( yu·³î»òØ+Oúç¿3Ÿv
x`<²c/?„¹å®á{%†XbŠ*2˜?…–w°½ù„˜!ÿªˆxŠUCã‡0Šá1v8ƒ±˜FŠ¨ +˜@µÈ5ØñZ‚ tà Q‡MÄ¡yØ5ìayØãï ‡“²aX˜¢JË(F-tac$CÛþE:Äas„EÕ(F)rQŒjP#žˆ!Q +S”¢Ôˆ2”opƒºÈI9¢á C„¢ˆáK"¸<â)ðA +Ñ…„"!ø€@Àø`XèÁŽ!bl!/ƒ– #àQ^¸Â@ RÐ"¾š4`
]c;ºCr ¤à1a¨™
R‚étà^y|œ÷-X@|ïOxp ~”‡yê‹Þ»Ëöâ#ˆÂþgeh8PüâW0uˆAÒC¤)üCé@Åx±q@cæ`6ˆ!hˆç B +J@ˆR Ãœì`›þ‰‡Zb±(5l¡¤zØC*/„G;„!‡e€#cÕè›(DA +A +ßbXÀaŽmd£¢°)dŠXBŽÏQ +OÜBåÐ7xÐXÀBQðBÆ@‡D´\x‚±ƒˆ +xh‚"þ( +<€À$ÀÁžp|átƒ+¸‚ä !ðÀW?àU¯¢€ªƒ¡
d„l“¾Ð À†-ô@S&@A–ð…œ‰@Z C¶Å€\ ]ázÎÅ]Âg<@€œgñÀËyçy—…ÎמüdÇúZ&Ä0"J˜D²¡…øçaÝ<Dþ Æ!A «H3°!»`£DÙ(Æ+ŒaŽrxC˜8 ê +¦½ðÈÆ-^ñ….b(¢(†0vzÜã¥sÁ!‹E$Ý@7xö
bÐ!w8Á¶b¦¸XCtF1rh +[|Í£h#~]@£¼K¬F3p¢‰:€P0"ò€@(¡ uX$ R,Á$¸(Ža‹!@´Ð%à@Žƒr€8;~õ«!ðª>°¸&„¡°È1hA‹Zwˆ¾ „,™9`”8,‚l`@lxp€sÉG²×ãÞ0»,ÙñXç–¼tåyîþc¡ûø‡°Õcˆ¾@ ¨"üAP5–°ÄâWBr!ý:AÈ€$RÎq`Ë&‡,á b”Hv̈œ€‡l¼ƒ¹ðà†íÆp:,BŒhF,’áŽÞC*ïHG;Ð1Dx‚æP7ŠÑ-΢‘‹M)N£eìps‰5Z#Œj,£xòÄ#J1µc [µhF.ZQWtƒÀ)¼Ñ&äÀ bÁ†QÕQŒa Ž˜:ÐñB¸ «<Pqþh„MÁA *¨Ê"GãÈ¥ xL!<,¯˜Å+0á„$8A šÂš)ŠŸ@:l^|²3þÙçr±ï*dIØñ•[á*sú–Ÿ1wKBûá_¾*à€÷¨:¥åO–§Z‰¬y"ý‹C „Ú…4$©HE/˜Á¶h°„C.V2m0C!P‹TÂéw”C¦#âÀˆ¦E*,üî<àQŽ`0"±0†3”ø
i40`”;ƒR(¿ºØEâ‚MèÂâ8¯2–Ѧ´va$˜Ã1rá
a´Wy`„æœÑ€! +wƒ#V…Y·E,´wœ#hÀD0„%_&V$ø#Þ‚€«,xxนHÅDt‚hpF‚þ"¡9°œ`¾RÙ?¶7ÁJÖy £A¼ƒòðÀÇ(÷ŽôØ3°ô ß Ö«Ï»â–üE,òå™è%Ð懾å|–§iAÄ_0$C&`a(pa æ.
œN´!´‚:æ霶؀JÀ¾!d¯2èDaÚ@ì ^M»ê¹Š¦DJrA<!ª$c òA:Ä ¨aŠa¤a‹¶ÁªAÖ¼¼ŒÁÂàšêÎ.¨´Á¼¡D!z Ô!†á¢@áÃha‰¡í +tþ†Á x +D€ÅR@è`P€Æ¤…ÆZ@qÀxxá@¡á¾ ‚` +fPÀ9žÃÞ”€T ã,`y„)˜äC[ÌC]@µÅË®‡<æo{‹yÔã:úýìÃ?šgàŒ(@bÞÇ:6$AÚÃAú¬ÿðÌ@0¶úcÐÄe€b*šaD„2!¹Ð¡X¢~
bRdÒAìÒA£Š!à€0ˆÁJÔ¡æîÚ¡i‚.ÊL!Ò,¢áA–Æ€v!¢A´h¨á^¤š+NÈ„¼@t÷ð †Hᘀþ`áÐ~À^àDÀš¡
á‚!Æ`À` ¶ ÄÀɘï¦Á†@:‡î¨àBÀ× +n:hÌ)_€¾`ˆÊ@!*A
®€ +f`€ h@k ÜR¼j$¦ýЖâo;¨'[°¬þ,«;Ì%[èåÐeþÚe;ø™€=Ì'Ë”é1IËšèç~úb<XK! (pÐÐg? "_R bT€Á„þàAà´áš!d`Ä€*éJ\¨Ì‰„z aÀÁèîàÐÁ¤¡Ú¡t!vÚ¡þŠ¡ À +§ÁtAÚp’á-ªèÖ–óŒ¡\Ètà^a2‰ ¡¼º +``vÀ<Áò@.hž!ð€ >šà¢ ¶áº€dÅ> R€Æ +îx +.¬|`¯ žÌ® +¸èà’Pà, P h€® bLk–øá[¾#0£gý^ <à[øò¥'˜ä—j?–1JñãZòÎ ó@àš^k;ò¬Aö£šæE§ia„^.¤"â´`x!(¡Z¡¾`,aØÈ!°a'}`2AÈþAöÞÁœ¤Ava`áÒa ÒIÌ¡@áè‚)ä¦Ä!ˆa/Œ¡L¡ÊÁî¶AL!¾a4¡ø¨&®àŽÁŽá´¡ð`ZÒá`ÀjA¾á*T D=@á®AXH æ`TÀ« é«>TùR šÀ8!Þ@ò +`@´ ¼à
Þãd4n LqZ@:¨ì!òÃH`y„”\æv‰ýȶ²Ü]Ð#å²å–à¥þf;ò/Ï‚}$fDK¢ü4ä˜F"´±`ºCfñ@þŠN4É”~@ú€xA0ázAÁð D´´cZ!¡2r!ˆ¸`!ôÉ<¡à¡»ÜAöÒAdµžj!¤ÚDˆá~ ÂánaŒl‹Al²Æ:áÂàóF!À ø3ð ˆ!´Aóvò€î <\*ÐÁ¾a«!ÆÀœ`ò†! Al•(®â@àŽÄÕ*·* \ – š Eáž ¶àH`
’ p Šà,ƒ`‚ ˆ@H@*1y +ëÊ,+\€‰! Ië˺l`»¬.³Eþ;º…K¹¥±J«?8Ö1%†8Sûì˜ê§eùçeíLÐÈô!`+Ðè‡>@hV-°à +„w6fÈ)¨á´Á¨á²SÏaZá
HÀJF¡Ô!ª³“†Áláf +UñË$‰nA¾Á¨a¬! ¡÷rÀpa5¡ +Æ`PB¦¶a'À òàE@Hð@WÎáw€u@@a|pv`â¼ É<€¤ÒZ rà ¾€øé48¼`Öõ +¼@
uyb`wÑ2¬ TÀHI•2À þë<ø/¿±,–—®g—ré>~ñ`ù–¼š‡«æêc 0ó> À1
ð@øeÏDaâ":“šª±è
è*›\KžŽVVá¦@ˆ€¡8±¡h3FãNaÉð4è >`p"Ò#ÒŒÄnŠðÓ”aFÁð  Já¥aiÂÁ.éÂà@…a!r!Þ
°!ošBá–ࢀ¶†Y9Æ'[á¨á¦¡@!˜`îÀꀔ€¶à–`-;ÀŽþCÁ†!@a^áŽã +Á þ’ p f@R`š’à +Œ`qXéÖËÊÌ/]βv–p©T°°Œ\"Y?Ô/zl1;lŽ¤}èl´B”ïG3ƒ‰›$‚^Ð}(‚_À¥é“ÿ' h–€á&‚€Öàh:ápš!®€!¶!cd'ß ˜ ¼`>AhŠ:»ÁDÆN“ö¢òàt<‹È*–áJÊA´¡X8¢à'BAsøðÎ4tኞa`áðàpFСŽaÁPE†a‡5Až€Ä`YÀáQGû-Œ?,¤gáB:1þf,{þ .€`hÀ»gàšÀ¦@»c‘ZsBÄC/¹'y¹#þ˨ïÒ²€T˜$‹ÊL°$äã‚ —Za¬ƒcÛgC@´Ô÷A¬Ec ¢ZÍþ¬e¶Ád”@fiö€ø@ +‚ Ä|ÁŒé8‰:OɈ7‚áVT@¸@p YÁ 1n¡:¹A%ÐaÄ¿l!–á +¿NÊa&Ó¢Ák;aRèà xfê”A)²ð.¢nÂò Ž¼¯#!ž ‡Ñ9ÎYÁzR’¬&ŒtÀ Ò8A@:þ¡††…I|\ÁDÚ.®¦s·P„`Š` +¬@Nº`Cy¿ËŒ> +`±${q0¹Ga
Öäpi0ýr²Ìl¿%dan‘}óF«}b‹š$¹|Õµ¨1d5V`¦Ï”L; í®¡ö@ +¤ š8¡0Á +xÄ!;ÙÀžÁ³‡¡J’Dàj@ Àj€¬3Çsá4¸á-ªÁ˜p‰ ¡<9-¸¶ìZ!aš|D !È‹ºW¨µa¡A¦5¦¡D.©Ä +Æ`ì@Eê@(à’Ì Ú þ”`®øá8hŽáž9©fAs™ÁÐÕ¾ ò•€jव;¬ è… B`°E’{>~ôyÁCbÛ›é»g0àþš\ìcyÑe`¸ãçÞ”)|
J#Äæ~®×¹qì
éÜ÷š†Ï> P˜T¼9ņ{Þàr'! +žØ4¡h!¤åŠ ÄZ øÆt!jTÅÐ!Ø¢`Ä=›ÖÐá¼á˜¢`~Ø A +£?ËF¶Á‡áh¡Š”u‹hß'Q¥~õ¦Á7bAÊHè ÚÀ¸þäÅ@.áΣk˜ÁiíÀÎIœaÍéÀ´ ’m:¦ ” j ¨€¦Ãn\þòÒsI[âO¨ËÌ“Þ§ + (Àƒ$8¸ aC:p€¢ƒ.XØá+<h°€Á”|XÒJ.Kš|PàäI“/M–<ÙR¦Ë“! @…Š×µk©Ò”™"ÄP¦B’l‰µrç¶Áòâh³D´ZñÐG&p”ŒÈC +5j¸t#f,]:uvÑ}Cg7:tìÐQ£uȆˆ?Mó¶
Z©hÛ¼q#÷-[dhмEÓ¦mµþpÔg«%GQ.rÛ:kƒFŠ£PšpK'Š¡BNêºmˆ,ZÀ½òt¨P¯|uš««B… +”VK"8dÑ“¥Ž$8@l°àpóÓ§_`ð óÀ'Àï|ýúF$Pàý{þÀ@€K8t@y +@ôÐi„ÁFAð€XèÀ79„R,Yt¡K0A„ÒE9-@J7½äaD + *¿ÅË%~Xá„+”XQ‚ M(±Â"Þ”ƒŽ6¡È3Ã,‹/„…,vÐÁŠ܆-´hb +8è”ÓM9~™Ž7ì´“Ž;é´ÓN9Ú„²È!þ`8Á„(Þ€†1ÔcÎ9èØ6ä sΡåTÍ2žÃ‰-º@sN3µ0ó"x ‚ +^ЂÌ4ž\ò +\Ò‰"œ€B-³ÈÙª‹¼r›o°¼Ê%†`2] o¸áM¸‘†uITƒ4„zû5ôzôñWÀy
©§žAMËPÚ$zïUë-ᚇÞ1©Q‚%A0aL@‡ôÒËÀ¼¨„"D"Á´ÒJ9}èÒÀñdâKù›â)D’ +3G]ÃÌ/«`ÒË/”àC %À7“aÓ ‹Ð +,ÀCGºä2jÅLƒœˆ"K5’mó
7vÓæþ;å¨ùf9Û3
4ÇK.Wiƒ`ï°X`‡¾s(;¨=Œ.Áà±H'¹
3¸~¡B=¬ð:€B
4΄R‹(Ç2-ÁàÊÝ¡„¢Èn¯Ì"Ȇ¤â ++œl²‰*”È~há†~kÆFÈÐå‰K-³¦×Þzëá·~õ%8í²Ô‡޳æ©nÞ€ ¸À‚ç]„‘IZð€ï¿ÿnÁ½$~èF ,bºêŽh‰ ÜSI/”$¨@|ÔÄÀÃ0¼`F5ˆòL4W‘ª‡ÔÊ0±¼R‡.Ç £MŸäÔ5‘i3M5oá†7¾Qsäé/å þ‡¥ši,æÕø‹_¤v5CIäH 64ñš;"a!På:b•ØB8Á‰i`ãÄ,rѽ`t/®øÍ0‚!«Kl"w C!Ç V\¢”ðƒãÞà8ø¡WzШ@d9Èuв–·Hð#vaÀ´ÌóŸ.‚ZìPzØu(&p€@`# ‡&”„턎؆6“Ø&ÅãI¾rr¡E¢D"¸öRñˆ1Ã’×F3šUøÀ|ú†™A‹N€Â°E,†!Œ\$#åHà6¦±
th&2‰2_Œ$µrðM‡²%þ¿ñ
v\͘T`Eoœƒ×1 AŒgƒ¨Å0šD‡P8â½Å"ˆQÍg£À8F0†a2ÄÙª h'è0:(…H+0Á«@ôá‰}p¢Ò+xYº;µFwÖ‘n@k$×|‚.ªDîáDlg.þ”‡ bü‰òuÌ+°P½6ä€y)’ ‘ 1Â.Dš$y2-ÑCtw!u€Ž¡ˆR‰J2ãb×hÆ0šñf¼¢¡€†[ˆ†
dÔ‚‡…Þ á4rœ£HçH;¼spdG9Âá
i)jåàF2¨á
b-PQ›Ú_þå
±232„ªª6¼áÎpCØg˜ô +NàbÈy-^щP£ÀØB÷\ +»Í¢™ÄVÚA"wÀÄ%0 Å]"”„$æ Ä&z!S(‚ +>0‹Œ¢´ÍSú0t¢Ð:]F…K%$¹ãçvB-€$xÞL6”/€ÁD%9ÑñR
ÒE"ý®¿\B%Ô%**(± +^ÌB^ †÷fÑAc5É€Æ6°lƒµx…,’Q׿œ+í@Ç8 +;
jJ€ÏpÆ4ì–oDÆÛG-LAÀ<3>Ô3{?g¶°{5Ô3‹þö +EÄžF+˜Y`4ƒ &ñ‹V‚üeÅR‹ˆE,Ît¸C¢SˆKP"¶hâæ7h¡ +R88À9ÒyŽ‹ Â`-Ï}±¢Ý"~ºÕ9o9 1AQCt7Ò:VÀË£yo:°ïÊ$A.ºIñX”µH&4Xx§ëÝø¦b”˜…9Œ_oÃ`2°‘RGÚ8G6–qÔHƒ€í(T ¾aa¾„i€ÐÈ…ÍL1×Q€DÛ;ÂáU©É8˜aJæ6ÆA`h\#ÕW#“ÔŒ‰Mf(B…(0xŒÙZ¶šE%ƒÁªYÌ,ä„+ÎþÚBÌa‚0%.ñÚ>¼o˜¼ †+àȯ¹Ê Üg¢o³Ez~T”]ÝúVDØ•nq‹ +@´Cd?bÄ]±(àRó6’E&b)#7SœœèD-:ÑEŠ'S‡\¸ˆL¤"œØ&0.æZ°‚ÓLFg¶A(rŒƒh!.R˜Ê‘Øff˜†Ç6‘‹bCÊ`L5¾1p0S—‡jfª½ÊÌÂ:ÍÌÐ2Š½ÌtœC¯iǦ6îfEã…À7(4±í£4•Ó6ô4-:ÝYÅm"‚À%æ@7xßøVBRàd]º]xz*j®þö ç‹j¼hrÇ…ðŽ®ë<btH„è‰7¥*ùïæ5íÔ‘êj9ðAJ"—üT¤ÿª9ìÅ›SØC ’HÅ+zÁ^|ú½ …§Ÿ±tÎxõÏ$ Ú¿!¥“u°÷ÃÆ4©ÏÈ2Å@Æ3çï`rpf× ,]1\ÊPÐ5S3m~‘wÏdÌàw1Ï «Ò ½ÏpJuIÌÁÑi®P1›°t@_€ok°^°g×à Õ²l¦Ú¢Yt€-æòEe: ·E³#\ "-Ó9
¡qå10rG¾ƒGbѳh·g<:SÇw!Œæ<þ9q|$Ò'1?!F %ƒÈÓ]ào° +¨ +¬à¯ÀižVÃP`Ú
Ú0á`$åà
æ€ï°W‡â
N·~˜±ÞPa:óšBÔÐhw(J7MŒÁtΤL€Âvwwl&¦b*æUØtÀp
ÀPupŠðÌ06Èúõi6Äi«À +›PŽã8psðZÐV-Pd±‚Õ’:ˆp•E¦CFÓR Ãí.pÖ-Ÿóƒ.Å-R{
á<%q„Jà;ßuH)aé%ðÈS"èè"…f0àH"(±i@” ¯à +ž¶TÔðcаþÚ€X‘‡â`kÇv‡ŠÕlŒá
Ô
Ü@Lƒh +ÿøcJgu‡ÒÛÚP
µTb–X‰Ó&i(˜ˆMöw
ùØŽà†—t
h +‹Çi°àŠ›ÀZ†»2‹o [`P5€3€*(pžãòÑE¤3zÅzÊ¥E-S™z8wF±-²çQˆ´ +’ð" r#Òh|4û’^…Æ"É£^@Á!ùB-¢; g0‚1å,±I@?‡ H
Ô€ÀÀ'Ø0LX1uè`ÍD~z‘œüã?Ä€›‘
ÇPÚ
ÄÇ0ØPb$)(•Hb€BmËþdL˜øUØ”wœ¡
.¹xÏðÎæ’/i´P+âæ +Svsð^ jàøÖ+Y S€H€¼Hbæñ‚KyÒÙp³Etƒ
ç‚ÈehÄf3¸Fª{ÜòGÒrpG"„ö‚–6þÒ<T|&si/·h‘—A-$’;$£O¿Õ„IÅ}©!O—Ké(„E@©tœAVÏP +‰°ß0ß·¨æLwglì VÆ(TšX±L{K”Q$šx’J1G›çó›äÄÖ÷ÓÇ «p o°JÐ= Âi½b¤V`U@D™âÒFþÅ-Yp¦”Ê…Ër¥aT•Â•:³3žÂ8-°
qÓb¶ƒuù%E!¸·!KH…=•"Æã„iY„e*Sðù"%S +‘PÌ’/ЗÆÞÓÐ0IŨ˜ÁtO&f—(Ôt…¥}RÓp9*ˆŠAІ‰Æf(¦jW¦*k|ˆ‰„•b#ùšÎ›×àlÐ0›Íp«Øilدð +¬@ X@4J$ ~Ð{ÐZW€DPðyÖòEàóáEQÉ 2£žêáp\êŒovÐQïA¦—•%±,:!F /pPRGx„3±„€ä„6÷þrqD…‚H:år4{1‘•x™ ^°8€ +ú“ÄP™à×ðB–
¢d$é‡ÉtšAJÎÀ£êUWSl—¨¢&clgª%yãpšfu’;£/d£0é=lÈiÆ£¼ð®°<àVào YöDk YE0âÑ1ƒ§Ãa- +÷¨‡ŒV™eÄpq:Ðùƒ+ñƒäUº³s0;w¢àRà—0êåh9a—4÷ž)ñ á5Ž3UqÃ.Þ5páu(Д <ë™0µðBŒÚØà÷3`ÎðK'‡«
Z·µÀUóþWº$iAv•˜1ÆLªÊL™ˆA2–Ùàl/™Ð°IÌ@¨XµÀ³<‹}æöÏá°`¬öÆDj`¹U&`Ec4Yzfç‘”¨£Œ4˜-ÖÉEØ’z7\[«-Y);ç¶ó±p{c9·à*uɣ°ëb/íÅHF"ÑåH&B-ŠÖ‚=q@.zöôX_Ž+¬ >VŠÓ”L§
æ
Ó ‡—™Çp¹ÓÛpw'ûL,{l&Z‰<’°4:X‘au„Å/äBÓ`«Èp?–Š7¾ð»¿ð³½à +?— +[½âjPUð´!°0ŒQƒþÅRÉ^äQTŠµÓÉs†Ï«EÒø”YÄ-A^ b†»gõyG"<Jøú2—1§/ré‡s]þê^,{·G¦ïa"ˆv9@_ài¬`kp°Të
¨ÆUGã@«ö¢ +
Â@ÁÅК¤z€‘ˆAĶlg$}ˆAúÁ/XÏv
„jêW±›ÔTÌ€ºú“¥«ÁðæV}¬ +— jàƪjfÀDzWÄU›µöÑf¨×p¤G¡×-_À ×WêŒÌÒì!;C8;°sÜ¢hÖ•ê«ï;sÊh8±hט0ê’^„&Ç b0#UþÆŸÓq»ózß\-’©ð³ +PW0}ûx«Ã0«
Õ0
›Xþ#Îðk’y‡M~ØL„å
ã@Lé ‰~™ª1Xj™.Y«Ï†³i)ß3²«ßãi¼Ú ¼|e²õO~¼G Ðä±ÅÉxÝ•Ó ÷¡W|Ô«gµckU:„l´ÇÔÓ:ê’ ±@/*gŸz)^{k{-ñŽÏ>a0Å5„x)„çù§4å/n° « +`f€©Ð +Ù·N>F›˜QØœA~³D¹ð_L7¡*ª¤¼„â±ÖL)Ì©
š}ÒA¡Ø0›êþ÷ÙÌ੬”7Ÿ¶xÄN—äi³à +‰³ V[’Ðk N{U”,S¶Q9ƒ^ꥢcҵpÆp ÕQ«³Fçª\…Š®°'d|§ly„¿ãö;x[…;HçµÏ2i*A0åeú!ñÍÆ3Fù" „Ê(Âgæ²°5©° ”ГWÀœÀiã=ŽüGãÈ–ÁtØ»¸p˜€õˆ¯©u$[XË
ûvêB³é?þ#ÉJ7
ý™È Múµx«ÂpàÝ +˜P ¯EýVBÀ‹Ñš•H½<ͬ§W:àyQϼµñ1ÜogþÄuŒÒÒ,ßÜË"=a;÷0!I8Ç6Ñž»c·31‹´„]ˆrnÄЄÈ'Fs”×8Aˆ¸üŸ“Rp”0_Y¦g` ¿àiÝC¯L›Èðl«ÃŠ ²“ÍÙI²L7™‘ˆ©1à…ʘX…mN´iM?FN6<¼Û»´Ì ½ÊB¯•eµ¸D[4K|ÔOm¨£Ô£Ü£ç¥I)•D.ëØ̵N̓ی¦ÒÅråi§uTRèÀGÃS"=e·øªÖcŸ/Ñ!1R5—–''†±#¨RBår&€¤W6P”ð³ÝƒŠLÅT–"˜Ò
ÉþaÏ œÁ©Aè˜m«éÔ@Ké‡è›$ð‚y4´ÙsANÒDNïéÁàµ0Õ·®ZK”¤ÍJÍ»`z®#®VÜÌ\:÷ÑÃÍP\ +QâŒ[¶A÷){Ô“|º30ò¦pK/0ùÒHKøóì<sôYí])Ró"žQÕˆí°s 0;fÚ9íºðT D}P G“›t«4L`ýŽ
Ju]ç¯Y³¨ölÿ>`©áB³ª~µ9›s_o÷vèÄ@ÚëT¸Àð€8½;ã«°ek°Q¹ýy?¨äT Õé1¨#ÅLiUép–þ/\ÇU•Ú"‡Œcôƒà[-5E¨K„rü`Î*Uç¨Î=Ÿ² ½0c¾GíšðÉŽ'òSâNÕ¥qt—ý,„q 0n ‘€ úè=0Éc—ÄTŸ£psÎÐl´zF`mŸ
oj^ØÔ`£Íð™±ð/M£²Ü=)³Cë”®pø®Ð œ˜ +‚ÓgOš4TTxàpÁƒ$Nœˆ@"?Š'b$À/"\Àñb\)1âH–1F´Øä‚&êY€ÁÃ…>Xà¢Q d¸`Á§8¨ÀÀê¬X>°:´þ+W¸úLÊ ëÕˆíÔ—¬p°ÀnQ»‹0° ¯Y»:ïÞêàˆ2júÂÔ+0f‘%3&Œ˜³fÆCöŒÚ4lØœ=ƒíÙ3m¤¡E‹6íZ4hØJ—–mšX³f̈+FLX®fÁ|k&>ì1-Z¯^±bʼnU§N›0UäÇ+fªÑëÄ»;ºüH`åÆžüPv䇱}Gå5RÔiÒ#Á13âŒ(ØäM¾$2à!«‹ˆ{`«˜²à‚( À©#4Š‚¤Œâ0³°BK¨®¾ +jAøP/@À§ª@«‚Ê)§¼ I(þª®ð ˆ4(IE•^~ìh †`ŒæÉaT{&·)™iæ4$MÓšffË’Kb"&˜a€ Fá(»í2k †XzqE•T¤Ãd“M8Ùä’Jâ@ãŠ$„¨!†8° ¤À$R@£õZ≢€‰#÷ì+©½Æ»ˆ‹<ZT£ûæˉ€š"¨ʼnÀÏQê²Ë(½\/2xƒr}À±:Üʬ«¬‚uWC,³’òÐÃd€U¯ˆòz5XÂh\€¨ºâÌ.¶ó ¢6(ÁŒ=&Éd^Ì<“É'Ç|–`pk†˜%$Æ´,O»2Ò¦<í˜ÍÆüeÌZþÌtS³Û†É¥`Z~Qn•Uè¼DL0¡Ø8Þ8# hèÂh証þ4e‰Ÿ’Ы”=•íÊ轚FþO<›0:`f%*'òµgÈúźb|ÀVlê 2Ë‚V=l Ù©¿l`6X¬‘Ên¥‹(c”qçu¼kg°j¼ö‚ÕðVZ™¥H_Œ|¬Xx™¥ÉzÕ¼’™g§·(wÓL·2k·–âè¥Ì^~anVRI¥’K.¡J(™ä6°0¢:Ø —ùÌFPaɽþkofMß»Häñ>/®˜M"¹'ÔÃogð- èœbd`çþ¹¸ÍK‚\›Š‚]ÅR +j•½¶¨[–´ÅšÛÛÚúy¼ŽBQ® ÍöÉ[ÓÒ0¯û¥¶LB
!¡‹«(R‘žô#ÁË8‘Y’ºžd¦'ùÂ]D ¼|A„eæIëÅ+xÁV`›“D*B7 ë¬!P3ø˜UZŸ*@>èÞy^6³G¹= ‚¥Z†»h åÉOP ¹Hï! òٷ懽¦Dñ)PyÀ²R!®\qY(Ë‚2Ô½°+F@QˆŠR´ÑˆFôÐC ç2¡l(Gi“ˆ@26@à°Â܆„.WôB¼è0xá` °]¼ þr€qÁv!ÐarJ-‚Q°aô‚½ø +VÁ Í¥â¨@…$Lù‡?øÁF86p%‘TOúRŸhéN#+IYG0©P™l‡¦š.i6žÿ &AsÚ\‚<¥íÎ{‘O¸b—¦X iÄâfÓ®x•a= YŒÚ²:DN}ÅYÂJø“¾ÆY\!£ƒ¢–h¾jfË‘ófå6»ðA¸ÂÜP1W|M(!Y@½Q&‘3’$9)È_¸‚´¨Ü,\¡ÑˆuÎs¦4H¬`„€à•fsÙ£ð)hÒ’A›áDÎc’”ñcQé”ÊtI)Líð¥.‹KHþd—¼¸ÐgF62ÀñÞXæZbJ®,L(+p’Õ¡õ}(‹ÌòÐÂ,¬uŒâcÀÒ&”[nB׺fÈTGýµo0ìÃ+ü®
€Àgˆ)1¡9ˆAŒ‰U,/ZáD +ò€O:äåþ¨ +²Bª %%Pˆ=ôAg(CÕTMG2Iñlò2aºh$¸SÔì`›»¤~„˜ÈŒI4_»ª–xD'ùÏΧªåDC@ßyΪF%*ØÃÊ[v³¤OXêÃBÅ®(+ôdÔ°<d©omê]…W–Þogu)ÚLõiF½@¯+
ÐãLþ 2ìÁ’ðì(G˜Š+–9¯˜…r>È“R« ¥ K)‰=èÁe B< :!h0 diff --git a/library/demos/images/earthris.gif b/library/demos/images/earthris.gif new file mode 100644 index 0000000..194ddb5 --- /dev/null +++ b/library/demos/images/earthris.gif @@ -0,0 +1,24 @@ +GIF87a@ȧ’I$¶’Iÿÿÿ¶mIÛ¶mÛ¶’m$ÿÛ’ÿÿÛÛ’m¶’mÿÛ¶IÛÿÿÿÿ¶’m$’¶ÛÛÛÿ¶ÛÛ$’mIIm’$m’ÛÛ’¶m$ÿ¶’¶¶mI$$mÛ’I$I¶¶ÛmI$ÿ¶mmI’II’$$ÛÛ¶ÛÛÛmm’¶Ûÿ¶I$’$$ÿÿ’’Im$$¶IIÿÛÛ’ÛÛ¶¶I’’IÛ¶I’’Û¶mmÿ’m¶’Û¶¶’Ûmm$$m’’¶’$ÛÿÛm’¶’’m’¶¶¶¶ÿ¶ÿÿÛ’’m$mmÛÛ’’¶II$ImI’’I’¶m’Û’’’¶$I¶’¶¶¶¶Û¶ÛÛ¶ÿÿ’$ÿ’IÿÛm$¶mII’I’Ûmm’mm’m’’¶ÿ¶$¶’’ÛI$ÿ’’ÿ¶¶III$$m$$’$I’m¶’m¶¶m¶Ûm¶ÿmÛÿ’Ûÿ¶m¶ÿ’¶ÿÛÛmIÛ’$ÛÛmÿ¶ÛImm’$$$I$$$$I$$m$II$mm$m¶$’m$’’I$I$II$’I$ÛIIIIIIm$ImII¶’I¶Ûmm$mmImmÛm’ImÛ¶’’Im’IÛ’m¶’mÛ’¶I¶¶mÛ¶Ûm¶Û¶Ûm’Û’ÛÛ’ÿÛ¶¶ÿ$IÿIÿI$ÿ’¶ÿ¶$ÿ¶IÿÛÿ,@È@þH° Áƒ*\È°¡Ã‡#JœH±¢Å‹3jÜȱ£Ç CŠI²¤É“(Sª\ɲ¥Ë—0cÊœI³¦Í›8sêÜɳ§ÏŸ@ƒ +J´¨Ñ£H“*]Ê´©Ì&H@µêW³J˜À©×¯1P•à`‚²PLøtÁËÖ \˜êÀA„"´Ñ;á®_*¨¨Kx€°ˆSlÑWGúÞ¸Ñ÷ìVEj7Ä
&t8Ü£‡…§o8±`³ ›/Èí;'ÂYŸs‡A …Ñ@\pPEªè2;,N<‚ŠÍTeëžN½¥Aˆþü®Î½»÷ïàÃþ‹O¾¼ùóèÓ«_Ͼ½û÷ðãkðAÀúô P°¿@¨€v€œà 0ø€P ß„8yðÂ&`x@$@/T@+à¡ Bàá +®ÀŒ(cÔ¨Ÿ6àøCŽþ`C 'œ€ ‰ ‚0` ÀÀSˆ”ü'äQ€Å2˜€UdZÅà” 64à&RHÔ›nÖi'àé›xp@þÉ ÊÁ†4@¢àh"´#ÜXi +È(cþ)i¥@@¦BFÙ$ÿ=逫¸€þ¨ +ùÀ,à_€°>«ô˜d”¹2 ªÄØä©N6™ 4Èì³Í.K¥²2,{ªTJI%ƒ0PmÕ~[æ¸äZ•¦9¤a`´çRpR@hÈë&nÖÛ€½Zh¢ýŠ°¡£
¤H
÷Õ(bŸ2LC¦f€Š‘6Ú¢‡d,14iàP) +À Új£}™¶lë}1lÚcÂ6.\#ĬÀ8¢}5ò,ôÎCò¼®Ý2È<*Ïxºå«ÿ
à‘G:yuª"¬®¶PªØÔºóÙdŸ-t§ Mcv‹ª¼b µe7é`þƒÒNÙ ˜D[U³$Ú€œˆ'®øâŒ7îøãG.ùä”Wnùå˜g®ùæœw®ùq_…dM °…ðš(PAX]Wa%;ìWuàyæP„*\öÚf¶þÚYg
A +)øDy5Add¡uV‘}amƒr{ä-\‚M@!…÷i½FDcÒÅ5jôÕ§À±]/ûò[Àºm´Û¾ýæ 8â¿ß P(p—!HÁ1ÿˆG–ÿYð‚Ì 7ÈÁzðƒ ¡GŸF½« q*˜ê`Rü‰„Û@‰.61¥(&@°€„¡þ÷¡Á¶Òô*f….MÌz™B7.iùÇCvÚ×a˜yY‘Oø@¿.V‚õë‹Ø¥&F!˜(B¨€^*¨ ˆB¬ü$t F90€ê3ª:¢êXÈêÒ5ð²²?hÒÚ«0ôÊ?¤± + ¬)!`ˆb2¢Uš8ªpr“K”›F‰tYÁ +Žz¡äÅ¡‹m¬€e¥Zt€jPŠ*Øõ(zù«_%He °±3ÌC/f,G€a€Cª4 дíìR£Ê&©¢5¨íHÖ´Õ~TfMÑl\@€°fv H;’Ùºy5T¥IþКÝòÉ«vjÀn 0Õ²¬e,œ`L 8Á¾•PpE«YaCÀ ”€~àh8ŠÐ2‹¡å +épä`QHižNBåi_û’.á¤KŠ"D¡~‘àP~ª%½€Aá²N6åP>t1FÓi?˘ˆ&…)nbj@gÀ.fC§ÆèøAPU‰ ”ªI5OÙ'˜M6" Zs™?ë#Ë4#Š@1úæF0XNÀF&"ÙÙ¢¦MKl…£:u% IVm@ª8ûÇ!Ö>vQÌDÄÙ—uM@¬²ê¨>€«Œ‰œdþ¢˜¢µ-*Úö¶¸ÍnwËÛÞúö·À
®p‡KÜâ÷¸ÈM®r—ËÜæ:÷¹Ð®t§KÝê‚0X¡ +ñÎw—''yÌÃËÆ»ººLàÖN´ë´R¹Ëš€šÈ8‚3uÍ&ð†,¯‹Ý$ Àô.¥ci¯‚'P„ÍH@8Ën :ªLÀ{>èËxQ
‡0 –YŠp•x(¸Êf(*øO )ïBpáë ¢éÀ]¶°ò
¯¼Ñ›ÀB0Ö\08qQ€ƒ—(aÂR©BdBà©ÀÆ)ˆÄ@:½ÃÈå49VBgî¢áLxÀÃÊþ”ŒåD&S¸€â¿í {ÂaÄ]:ЂX ¢ÑŸhÒѨ¿››"¡wõ 9„öžÜRc€ ŠX@ü×=ÂŒ—¼xñ¢uó¾-äz:Âo±´`4ÊqÎìbâQÛúָε®wÍë^ûú×À¶°‡MìbûØÈN¶²—}P^¥A +:^&Y)%Àd0…á˜M
¥èDÏÌÆÊXÐrHt @}öC,<4#¾ÞÄRn£$¬8¤}Òí!hÕb[•”¤FׂËR?”,R“DÒØJ¡ƒcø·U€1HŒÞÀ ü
E€aÈBQŒþLJÝe~t7G®‘n0—$ϬT«É“(@š²¦s$ͪIv3"´eDi]Ÿ5ׂžµ£OK“g€5F[±ÞÔxŸ¶>TG™€UÒ²ª¡@¥òO2AÁ˜©¢’7 +B5¢A~> #é¢z\šÔ0š«¾ˆ=ÐÕh7¸5+K€g\Pt¸À.¸’FÀH]éŠYObü²d€0 ò´zø»gõ$ºÁJYTy: õfÏЉôS߶{0¤õ7í)P€âסXKQàPÏ4Q¥j0Ì
Üc£‡.ÅØ8FÁ‡PQ> Vl›zË´þy4°ÉeSÕl òÛŠ?Ô&€ÙÖ¦€b+ŸÇjz³~•OÒ¨¢ÁrR>±õsdùÍY³òP-iR7ïÖQ‡G+wÓwAÇ-›¤Ž‚u<Su2of÷R†`S‹b1ýÖ"ŠâT‰BCŒ20ò(a|-².‡Â, K,à(({(4„CÇ|õ±ƒê†@„#@XàÄ3°ò<3} ÓC-'„â´*«òXýÁM.cPƒ)Ó'VØ*`}·zÈ’$¬G%Ý¢D©7ôGyj(6@y„pè#b#GùäZbSÓ%Œ8e7‚ãI‡ +X!¸÷'þ{b/¿§qn2S0ES‚F)1"5°1X€UrKEFP8@1´Ô"‘²!”2€$èXr6”‚°W#CZ"’)WNs)6C#"³)ó‰M3".“YŒEp5ŠÂ×VÛÇVÞ´„…rv6”7$ÞçFÃn-®²}åÄ%,Gm\%švVd¤Y>ÈM÷±G÷±ÞäF€„%Q"€€X.ÑrÓ6Y°h`ƒJÓ(}â&ø&_Ĉ(KÕ'ò5äEV´E0pˆ2‘5%p³1oD#°8¤2 ƒÈG‰ *—3MÅU5W‹%0"/9þ1’%‚M9S1 ÂVXU"#W)%"#M$2$1% ”ˆX$ó‘°¶X³ˆV™„‹…Mƒ…öÙWD4(Ç2uô) S–¶˜M#’1™y;NøQ)F˜„˜bZ;`;p5ÞÄ4ö¶—|Ù—~ù—€˜‚9˜„Y˜†y˜ˆ™˜Š¹˜ŒÙ˜Žù˜™’9™”Y™–y™˜™™š¹™œÙ™žù™ š¢9š¤Yš¦yš'ÑPà) ’P p‚šÑ] Ö;›1^30#;uADE›±Ub€:@;@‘w1daÙE`Ä©À^ +þö6Sp ׳œ…‘_„`ÙÕ×)b1`ž6cvePàgi`f= á¹46牞Táe§©c1`¤îeîõ;ùÙSñ;“Ð}Ñ<Ð9¡þù:…a¦iOÑ(fQþ dÃs<ÉBö}Ña»C<Ô9A0š-A6¢æj¶I@ÜEkìsNààËsd¯ƒIàIðIº£‰š-€DŸPR` ¿1c!ð¥›0a€vH@¦h!d?00ÀápàŸkö™õUc>°>ÄÓa~V>p>p1þß•q!Z gØcyñ°:ŠÖ™Ý3˜ðOð¨pewA[a $ }f?²Lª×ó<öCŸL<?†¢ùjH€¬ál0ÞÉAÐvc +?ya;Á±¨0Á¡?ð”@¯ñoðzš¯¦‡òf=Þã«Ïé£ê`<fñ:㺞„Z~@ p}¦[Ñð~vg[=Ä媡ê* +efÏ©@7:?ð“óÙ p‘@Ô¨PkÿJ@®6®£‘}±B•j„0cœ¡ž[0¨töÐÎq‡0þ².û²0³2;³4[³6{³8›³:»³<Û³>û³@´B;´D[´F{´H›´J»´LÛ´±I2ðX yèP‚PT׳¶¸2êF›µG +Pæ ³2[`"8²áv‹2‚ðÝ sUŒö±ìˆ; rP ÷¢¶,`Vàf%Ç|ÔäIòxÿsp$ó÷,z㇡ós.°.’¶”92$#CžëL2)15be)•]ðFЇÎJ(qžP09p³{W„c,°»»û·É\Сë4 +Ð1ž1³þ¶¼°U=Hw6Ifu#þHïþÖp¯k-øDy¨2©bDh²-HÂDäz„s¹£)[GF)‚"`1ÇU"BŽ#‹£4ÀYž2}tt+Ò+tƒ+HgyO—I¢5òh à½Ü¾–Ô½÷y臮8@â»ÂES]§uÐ!ßÂB)ªèŠf$X¡rwädyëÔNr+*g *;sßX+qär˜Ô$â$x÷$Tb7±ÂrÔ(·]SÂx°r%°‡PWÁžôžè%³9EÿãuCµ'5ˆ'þâLò¾©¿âL`l1%—MÁ(*úÁ3þ¡%pQ•+pÌrüñ$GR*\‚%á»t;—&Â,þPÀN—HM2JA(6Ètˆ4j¢&Tâpšô‡ÑµÆòÈŸDEG.G„ž€J+¥8‰ÂAeKAÕJB‰èE 0rvŽâ'öâ&YK+2ׄ–uN@HŸrn4À²Ëÿ1,QBÌ. . Ž?8,È%C2G¥‚*¯²H°rIHr,¦âÃHrÍOÇ7~cÉLäpeOE'€Î
WQ4X'”˜›[Ì'±œ{5H('X'à'w{e\‚#YCßÆ|(c+œp¶@IM6„īí4ÍPHCã4ê´%ê÷„.+üQ„Ô¦søÀ"I[‚+J\µó,Iìþ$€R¶P˜tx<,•ÌÒM‚zó$€ Õqˆ&äëÄ@S|-©»+ð’,R(}r{úìÁ/ø'¼”J ‰1ÃD:dV€RÊk÷‰c}©)ú6 °dÝClµei}å*B,·$³6^«No͆j3IrGCgÍ—”$m”+eÛòˆOr[Ǫ'%—”€fxÉUñÈJä,ƒ7-ÒmŸtÎSB¹|88~-b ɸçè/"P0„²|)800ÐLÆçq³tL0.µÊ0Kh9)©ì(˜¸ÚÿL(”5@–•²ƒ\»GŠ,·sèÑê¦ošþõ$åTü‘Zn¹G=¢*Ôf·F~x ê4Þ§•Äå}%ì$q¼t´R¶ÿ—&xX€YÇn5Ç[R6vsPVÒÞÂPèÄåò¥p +¢0 +Ž²uBó/G¥Å
0(}ò‚$ u3ØIåo’‹g„‹Íä!$ð‚ºKCB#Yµ) ë!·TK¥)Ÿ(ŒT2ÇÜNCweÖ< n,‡7›¥¹)c„ÜÄŽ¢Ò4f*kìÑ2J>˜—éHnGø*£´ÃÌ<ÓR$3WòOE’å
E8°BÍFðFu츼ÂMÖ}Üçç½ë´Q5$¦wP à@}x|“zæÜD J‘',þWÄ/‰h'ÎJò=…Þ45P‰îÕP”Ô$NãÇ$“ 2|ÔD2È4Š ì(Ò(•è4hW:4‹)—A‚ÖÒë‘Ù‘gÓêׂuNîˆ}<SC¤²¶L…—þMÜ4‡¼bZw86bz;Y0—ÑÅÜ5û‹„¡Ò~‹Ô·õµEþËþqåâÑWSÇ@ÄNz‰=Á2µ|ãz’\a/ûR/SÎÏí>á÷lT†RÕ9%-øE°SmGL1Љ„;12‘ãmûÞ"° ¼ËÇL«8¸ýîŠl×÷ñnh‹C©X‰)+^™M#ÓMkE"¬øþ!¼½ÆDcy%6*c`ãýMÖhWßÈ#k6+gÃF£`W§Nó÷}+ ÎL 3ãAZ˜5N +`ÖcY„üq%A7çMÔId"Õ«ÌϘõ„rÚú¾EòW‘²UeGÕ†øà¬Ô!ûÞ!F0o[Ë„7ÿF`$c3&¯Ø(/¹1Õ§Ð#rke0qµTSr°0Ó+|ͤ"ʤ¹y…‹R¹)öÁV³Ä÷S…{0¶2×ÀY)<Àr¢oäC|ú5ÂCÌòsÛF’…ô<yn/cn•rã*)Œ€ÇÌìFºnê÷¡Çü,xéƒÀh°@òâ(‰ÁPC”˜"«901ˆv|ïŠü^r2øà´E÷Â'3¨‰Er–ÆFŸ.32b’ˆ¥oo„Xžøï29r()£®á^
W%Ù}MòFw ÁÀ€¨@@€€ƒ,P@ ÀÂ**P‘@Ä |\¡ãÁ +%3@`(ÀãȈ,<sâK†ºÈ‘ÀŠ +€¸@@†'þTèS€‚‚%B¬¡²c6´ÚaÂKTXù±J”D diff --git a/library/demos/images/face.bmp b/library/demos/images/face.bmp new file mode 100644 index 0000000..03d829f --- /dev/null +++ b/library/demos/images/face.bmp @@ -0,0 +1,173 @@ +#define face_width 108 +#define face_height 144 +#define face_x_hot 48 +#define face_y_hot 80 +static char face_bits[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x09, + 0x20, 0x80, 0x24, 0x05, 0x00, 0x80, 0x08, 0x00, 0x00, 0x00, 0x00, 0x88, + 0x24, 0x20, 0x80, 0x24, 0x00, 0x00, 0x00, 0x10, 0x80, 0x04, 0x00, 0x01, + 0x00, 0x01, 0x40, 0x0a, 0x09, 0x00, 0x92, 0x04, 0x80, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x40, 0x12, 0x00, 0x00, 0x10, 0x40, 0x00, 0x00, 0x84, + 0x24, 0x40, 0x22, 0xa8, 0x02, 0x14, 0x84, 0x92, 0x40, 0x42, 0x12, 0x04, + 0x10, 0x00, 0x00, 0x00, 0x00, 0x52, 0x00, 0x52, 0x11, 0x00, 0x12, 0x00, + 0x40, 0x02, 0x00, 0x20, 0x00, 0x08, 0x00, 0xaa, 0x02, 0x54, 0x85, 0x24, + 0x00, 0x10, 0x12, 0x00, 0x00, 0x81, 0x44, 0x00, 0x90, 0x5a, 0x00, 0xea, + 0x1b, 0x00, 0x80, 0x40, 0x40, 0x02, 0x00, 0x08, 0x00, 0x20, 0xa2, 0x05, + 0x8a, 0xb4, 0x6e, 0x45, 0x12, 0x04, 0x08, 0x00, 0x00, 0x00, 0x10, 0x02, + 0xa8, 0x92, 0x00, 0xda, 0x5f, 0x10, 0x00, 0x10, 0xa1, 0x04, 0x20, 0x41, + 0x02, 0x00, 0x5a, 0x25, 0xa0, 0xff, 0xfb, 0x05, 0x41, 0x02, 0x04, 0x00, + 0x00, 0x08, 0x40, 0x80, 0xec, 0x9b, 0xec, 0xfe, 0x7f, 0x01, 0x04, 0x20, + 0x90, 0x02, 0x04, 0x00, 0x08, 0x20, 0xfb, 0x2e, 0xf5, 0xff, 0xff, 0x57, + 0x00, 0x04, 0x02, 0x00, 0x00, 0x20, 0x01, 0xc1, 0x6e, 0xab, 0xfa, 0xff, + 0xff, 0x05, 0x90, 0x20, 0x48, 0x02, 0x00, 0x04, 0x20, 0xa8, 0xdf, 0xb5, + 0xfe, 0xff, 0xff, 0x0b, 0x01, 0x00, 0x01, 0x00, 0x80, 0x80, 0x04, 0xe0, + 0xbb, 0xef, 0xff, 0xff, 0x7f, 0x01, 0x00, 0x04, 0x48, 0x02, 0x00, 0x20, + 0x80, 0xf4, 0x6f, 0xfb, 0xff, 0xff, 0xff, 0x20, 0x90, 0x40, 0x02, 0x00, + 0x00, 0x04, 0x08, 0xb8, 0xf6, 0xff, 0xff, 0xdf, 0xbe, 0x12, 0x45, 0x10, + 0x90, 0x04, 0x90, 0x00, 0x22, 0xfa, 0xff, 0xff, 0xff, 0xbb, 0xd7, 0xe9, + 0x3a, 0x02, 0x02, 0x00, 0x04, 0x90, 0x80, 0xfe, 0xdf, 0xf6, 0xb7, 0xef, + 0xbe, 0x56, 0x57, 0x40, 0x48, 0x09, 0x00, 0x04, 0x00, 0xfa, 0xf5, 0xdf, + 0xed, 0x5a, 0xd5, 0xea, 0xbd, 0x09, 0x00, 0x00, 0x40, 0x00, 0x92, 0xfe, + 0xbf, 0x7d, 0xb7, 0x6a, 0x55, 0xbf, 0xf7, 0x02, 0x11, 0x01, 0x00, 0x91, + 0x00, 0xff, 0xff, 0xaf, 0x55, 0x55, 0x5b, 0xeb, 0xef, 0x22, 0x04, 0x04, + 0x04, 0x00, 0xa4, 0xff, 0xf7, 0xad, 0xaa, 0xaa, 0xaa, 0xbe, 0xfe, 0x03, + 0x20, 0x00, 0x10, 0x44, 0x80, 0xff, 0x7f, 0x55, 0x12, 0x91, 0x2a, 0xeb, + 0xbf, 0x0b, 0x82, 0x02, 0x00, 0x00, 0xd1, 0x7f, 0xdf, 0xa2, 0xa4, 0x54, + 0x55, 0xfd, 0xfd, 0x47, 0x08, 0x08, 0x00, 0x21, 0xe4, 0xff, 0x37, 0x11, + 0x09, 0xa5, 0xaa, 0xb6, 0xff, 0x0d, 0x80, 0x00, 0x00, 0x04, 0xd0, 0xff, + 0x4f, 0x44, 0x20, 0x48, 0x55, 0xfb, 0xff, 0x27, 0x11, 0x02, 0x40, 0x40, + 0xe2, 0xfb, 0x15, 0x11, 0x4a, 0x55, 0x4a, 0x7d, 0xf7, 0x0f, 0x00, 0x00, + 0x04, 0x08, 0xf8, 0xdf, 0x52, 0x44, 0x01, 0x52, 0xb5, 0xfa, 0xff, 0x0f, + 0x49, 0x02, 0x00, 0x02, 0xe9, 0xf6, 0x0a, 0x11, 0xa4, 0x88, 0x4a, 0x6d, + 0xff, 0x5f, 0x00, 0x00, 0x10, 0x20, 0xf0, 0x2f, 0x21, 0x44, 0x10, 0x52, + 0xb5, 0xfa, 0xff, 0x0f, 0x44, 0x04, 0x80, 0x08, 0xf8, 0xab, 0x8a, 0x00, + 0x81, 0xa4, 0xd4, 0xd6, 0xfe, 0x2f, 0x00, 0x00, 0x04, 0x40, 0xb5, 0x2d, + 0x21, 0x08, 0x04, 0x90, 0xaa, 0xfa, 0xff, 0x1f, 0x11, 0x01, 0x00, 0x04, + 0xf0, 0x57, 0x0a, 0x22, 0x40, 0x4a, 0xda, 0x5e, 0xfb, 0x1f, 0x40, 0x00, + 0x40, 0x20, 0xba, 0x95, 0x90, 0x00, 0x01, 0xa0, 0xaa, 0xea, 0xff, 0x5f, + 0x02, 0x02, 0x00, 0x01, 0xe8, 0x57, 0x05, 0x00, 0x00, 0x12, 0xd5, 0xfe, + 0xfd, 0x1f, 0x48, 0x00, 0x04, 0x48, 0x7a, 0x95, 0x08, 0x02, 0x10, 0x40, + 0xaa, 0x55, 0xf7, 0x1f, 0x00, 0x09, 0x20, 0x00, 0xf8, 0x57, 0x22, 0x10, + 0x00, 0x28, 0xa9, 0xfa, 0xff, 0x5f, 0x02, 0x00, 0x00, 0x49, 0xdd, 0x29, + 0x01, 0x00, 0x80, 0x80, 0xaa, 0xd7, 0xff, 0x0f, 0x10, 0x00, 0x08, 0x00, + 0xf8, 0x96, 0x08, 0x00, 0x00, 0x20, 0x54, 0xfa, 0xee, 0x3f, 0x81, 0x04, + 0x40, 0x24, 0xfe, 0x55, 0x82, 0x00, 0x00, 0x82, 0xd2, 0xad, 0xff, 0x0f, + 0x08, 0x00, 0x04, 0x80, 0x6c, 0x97, 0x00, 0x00, 0x02, 0x20, 0xa9, 0xf6, + 0xdf, 0x5f, 0x00, 0x02, 0x20, 0x09, 0xfa, 0x49, 0x12, 0x00, 0x20, 0x84, + 0x54, 0xdb, 0xfe, 0x1f, 0x91, 0x00, 0x00, 0x00, 0xf8, 0x2b, 0x00, 0x20, + 0x00, 0x40, 0xa4, 0xf6, 0xbb, 0x1f, 0x04, 0x00, 0x44, 0x92, 0x7e, 0x95, + 0x02, 0x00, 0x00, 0x89, 0xaa, 0xdd, 0xff, 0x1f, 0x20, 0x09, 0x10, 0x00, + 0xf4, 0x57, 0x20, 0x01, 0x08, 0x20, 0xa9, 0x76, 0xff, 0x5f, 0x02, 0x00, + 0x00, 0x21, 0xfc, 0x4a, 0x05, 0x00, 0x01, 0x80, 0x54, 0xdb, 0xff, 0x1e, + 0x08, 0x02, 0x04, 0x08, 0xf9, 0x2b, 0x00, 0x00, 0x40, 0x28, 0xd2, 0xf6, + 0xff, 0xbf, 0x80, 0x00, 0x90, 0x00, 0xbc, 0x92, 0x08, 0x10, 0x00, 0x82, + 0x54, 0xdb, 0xff, 0x1f, 0x20, 0x00, 0x00, 0x44, 0xf9, 0x55, 0x02, 0x01, + 0x00, 0x20, 0xaa, 0xbd, 0xfd, 0x3f, 0x08, 0x04, 0x04, 0x10, 0xf4, 0x2a, + 0x01, 0x00, 0x22, 0x80, 0xd4, 0xf6, 0xff, 0x5f, 0x82, 0x00, 0x40, 0x02, + 0xf8, 0x55, 0x20, 0x00, 0x00, 0x50, 0x6a, 0xdf, 0xfe, 0x3f, 0x00, 0x00, + 0x00, 0x48, 0xe9, 0x4a, 0x05, 0x08, 0x00, 0xa5, 0xd5, 0xf5, 0xff, 0x3f, + 0x10, 0x01, 0x10, 0x01, 0xb0, 0xab, 0x92, 0x02, 0x40, 0xf8, 0xbf, 0xde, + 0xfe, 0x5f, 0x02, 0x04, 0x04, 0x48, 0xfa, 0xd4, 0x6f, 0x20, 0x84, 0xef, + 0xff, 0xfb, 0xff, 0x1f, 0x20, 0x00, 0x00, 0x00, 0xe0, 0xed, 0xbf, 0x0b, + 0xa1, 0x7e, 0xff, 0xbf, 0xfd, 0x5f, 0x04, 0x01, 0x20, 0x49, 0xd2, 0xfb, + 0xfe, 0x55, 0xd4, 0xff, 0xff, 0xf6, 0xff, 0x07, 0x00, 0x04, 0x00, 0x00, + 0xc0, 0xaa, 0xfb, 0x2b, 0xa2, 0xfe, 0xff, 0xdf, 0xee, 0x1f, 0x91, 0x00, + 0x82, 0xa4, 0xa4, 0xf5, 0xff, 0x57, 0xd5, 0xff, 0xbf, 0xfd, 0xff, 0x4d, + 0x00, 0x00, 0x20, 0x00, 0x88, 0x5b, 0xff, 0x2f, 0x69, 0xff, 0xff, 0xdb, + 0xfe, 0x1f, 0x24, 0x02, 0x00, 0x49, 0xa2, 0xd6, 0xff, 0x5f, 0xea, 0xff, + 0x7f, 0x7f, 0x7f, 0x0d, 0x00, 0x00, 0x10, 0x00, 0x40, 0xab, 0xf7, 0xbb, + 0xf0, 0xdf, 0xff, 0xd5, 0xff, 0xbf, 0x82, 0x04, 0x42, 0x24, 0x91, 0xd5, + 0xaa, 0xae, 0xd4, 0xaa, 0x52, 0x7b, 0xff, 0x15, 0x08, 0x00, 0x00, 0x01, + 0x04, 0x55, 0xd5, 0x55, 0x70, 0x5b, 0x75, 0xdd, 0xdf, 0x1f, 0x40, 0x00, + 0x08, 0x48, 0xa0, 0x4a, 0xa9, 0x56, 0xea, 0x56, 0xad, 0x6a, 0x7d, 0x9b, + 0x04, 0x01, 0x00, 0x02, 0x42, 0x2a, 0xd5, 0xaa, 0xa8, 0xaa, 0xaa, 0xfa, + 0xdf, 0x2f, 0x10, 0x04, 0x22, 0x48, 0x08, 0x45, 0x2a, 0x15, 0x68, 0x55, + 0x55, 0xd7, 0x76, 0x1b, 0x00, 0x00, 0x00, 0x01, 0x40, 0x2a, 0x80, 0xa0, + 0xb2, 0x09, 0x48, 0xb9, 0xdf, 0x17, 0x22, 0x01, 0x00, 0x24, 0x45, 0x8a, + 0x24, 0x4a, 0x54, 0x51, 0x91, 0xf6, 0x6e, 0x4b, 0x00, 0x04, 0x90, 0x00, + 0x80, 0x52, 0x00, 0x20, 0x69, 0x05, 0xa4, 0xaa, 0xff, 0x1e, 0x48, 0x00, + 0x02, 0x92, 0x08, 0x05, 0x81, 0x94, 0xd4, 0x92, 0x40, 0xfd, 0xb6, 0x8b, + 0x00, 0x01, 0x40, 0x00, 0x82, 0x54, 0x00, 0x48, 0x68, 0x05, 0x90, 0xa4, + 0xef, 0x06, 0x24, 0x00, 0x08, 0x12, 0x10, 0x05, 0x00, 0x10, 0xb5, 0x01, + 0x42, 0xfb, 0xbf, 0x43, 0x00, 0x09, 0x00, 0x40, 0x81, 0xa8, 0x08, 0x4a, + 0xaa, 0x96, 0x90, 0xac, 0x6d, 0x15, 0x22, 0x00, 0x20, 0x09, 0x04, 0x15, + 0x80, 0x28, 0xdc, 0x01, 0x24, 0xfb, 0xbf, 0x01, 0x80, 0x04, 0x09, 0x00, + 0x40, 0x48, 0x02, 0x45, 0xb2, 0x2e, 0x41, 0x6d, 0xef, 0x05, 0x11, 0x00, + 0x40, 0x52, 0x02, 0x15, 0x29, 0x2a, 0xac, 0x42, 0x54, 0xfb, 0x3b, 0x51, + 0x84, 0x00, 0x08, 0x00, 0x20, 0x54, 0x80, 0x05, 0xb5, 0x3d, 0xa2, 0xb6, + 0xdf, 0x00, 0x20, 0x04, 0x20, 0x49, 0x89, 0xa8, 0x6a, 0x29, 0xac, 0xd6, + 0x54, 0xff, 0x3f, 0x84, 0x00, 0x01, 0x04, 0x10, 0x00, 0x94, 0xa8, 0x56, + 0xda, 0x5f, 0xab, 0xd5, 0x1e, 0x10, 0x48, 0x00, 0x90, 0x82, 0x48, 0xa8, + 0xb2, 0xac, 0xfd, 0x55, 0xd5, 0xfe, 0x9f, 0x80, 0x00, 0x0a, 0x02, 0x08, + 0x02, 0x55, 0x5a, 0x75, 0xff, 0xaf, 0xb6, 0xf7, 0x2d, 0x12, 0x92, 0x00, + 0x10, 0x20, 0x10, 0xa8, 0x54, 0xd5, 0xbf, 0x5d, 0xad, 0xdd, 0x0f, 0x00, + 0x00, 0x04, 0x40, 0x09, 0x84, 0xa8, 0xaa, 0x5a, 0xed, 0xeb, 0x6a, 0xff, + 0x9f, 0xa4, 0x24, 0x01, 0x02, 0xa0, 0x20, 0x50, 0x55, 0xd5, 0xbe, 0xae, + 0xad, 0xfd, 0x16, 0x00, 0x10, 0x04, 0x20, 0x0a, 0x08, 0xb4, 0xaa, 0x95, + 0xaa, 0x7b, 0xb7, 0xdb, 0x5f, 0x92, 0x04, 0x01, 0x84, 0x20, 0x21, 0x51, + 0xd5, 0x2a, 0xa9, 0xee, 0xd5, 0xfe, 0x0d, 0x00, 0x20, 0x04, 0x10, 0x00, + 0x08, 0x50, 0xe9, 0xd7, 0xd4, 0xfb, 0xb5, 0xff, 0x9f, 0x24, 0x09, 0x01, + 0x42, 0x4a, 0xa2, 0x64, 0xd5, 0x55, 0x7b, 0x7f, 0xda, 0x7d, 0x4f, 0x00, + 0x20, 0x04, 0x00, 0x80, 0x00, 0xa0, 0x2a, 0x13, 0x84, 0x6a, 0x55, 0xff, + 0x1d, 0x48, 0x8a, 0x00, 0x94, 0x24, 0x8a, 0xc8, 0xaa, 0x42, 0x20, 0x5d, + 0xf5, 0xff, 0x5f, 0x01, 0x00, 0x02, 0x01, 0x00, 0x20, 0xa2, 0x4a, 0x1a, + 0x82, 0x56, 0xda, 0xbd, 0x3f, 0x92, 0x92, 0x00, 0x90, 0x92, 0x00, 0x40, + 0x95, 0x6a, 0xf4, 0x55, 0x6d, 0xff, 0xd6, 0x00, 0x00, 0x0a, 0x04, 0x20, + 0x14, 0x49, 0x4b, 0xaa, 0xaa, 0x56, 0xf5, 0xff, 0xbf, 0xab, 0xa4, 0x00, + 0x20, 0x89, 0x40, 0x80, 0xaa, 0xaa, 0xaa, 0xaa, 0xde, 0xbf, 0xeb, 0x03, + 0x00, 0x02, 0x04, 0x02, 0x0a, 0x10, 0x2b, 0x2a, 0x55, 0x5b, 0xf5, 0xff, + 0xd7, 0x2f, 0x92, 0x00, 0x10, 0x28, 0x21, 0x01, 0x56, 0x95, 0xa0, 0x56, + 0xdf, 0xef, 0xea, 0x87, 0x40, 0x0a, 0x42, 0x41, 0x00, 0x90, 0xaa, 0x52, + 0xb6, 0xad, 0xfa, 0xff, 0xd5, 0x2f, 0x14, 0x00, 0x00, 0x04, 0x95, 0x04, + 0xaa, 0xac, 0x55, 0x6b, 0xff, 0xb7, 0xea, 0x9f, 0x40, 0x02, 0x28, 0x51, + 0x00, 0x40, 0x58, 0xd5, 0xda, 0xd6, 0x6e, 0x7f, 0xf9, 0x3f, 0x12, 0x04, + 0x02, 0x04, 0x49, 0x25, 0x55, 0xaa, 0x77, 0xab, 0xff, 0x2b, 0xfd, 0x3f, + 0x48, 0x01, 0x20, 0x41, 0x00, 0x00, 0x58, 0xa9, 0xda, 0xea, 0xfd, 0xaf, + 0xfa, 0xff, 0x02, 0x04, 0x08, 0x14, 0x29, 0x49, 0x52, 0x55, 0x55, 0x55, + 0xff, 0x8d, 0xfe, 0x3f, 0xa8, 0x00, 0x02, 0x41, 0x00, 0x02, 0xa0, 0xa2, + 0xaa, 0xea, 0xff, 0x53, 0xfd, 0xff, 0x02, 0x04, 0x50, 0x04, 0x25, 0xa8, + 0x54, 0x49, 0x52, 0xb5, 0xbf, 0x8a, 0xfe, 0xff, 0xa9, 0x08, 0x04, 0x50, + 0x80, 0x02, 0xa1, 0x2a, 0x95, 0xea, 0xff, 0xa1, 0xff, 0xff, 0x03, 0x02, + 0x90, 0x02, 0x09, 0x08, 0x44, 0x49, 0x52, 0xbd, 0x7f, 0xca, 0xff, 0xff, + 0x2b, 0x09, 0x04, 0x48, 0x40, 0x82, 0x90, 0x56, 0xa9, 0xf6, 0xbf, 0xd0, + 0xff, 0xff, 0x47, 0x00, 0x50, 0x02, 0x15, 0x11, 0x40, 0x95, 0xaa, 0xfd, + 0x2f, 0xe9, 0xff, 0xff, 0x8f, 0x0a, 0x84, 0x50, 0x40, 0x84, 0x14, 0xaa, + 0x6a, 0xff, 0x5f, 0xf2, 0xff, 0xff, 0x7f, 0x00, 0x10, 0x02, 0x09, 0x10, + 0x40, 0x7d, 0xf7, 0xff, 0x0b, 0xfc, 0xff, 0xff, 0xaf, 0x02, 0x84, 0x50, + 0x42, 0x85, 0x12, 0xd0, 0xdd, 0xff, 0xa7, 0xf2, 0xff, 0xff, 0xff, 0x04, + 0x00, 0x0a, 0x08, 0x10, 0x48, 0xf8, 0xff, 0xff, 0x0a, 0xfe, 0xff, 0xff, + 0x7f, 0x03, 0xa4, 0x80, 0xa2, 0x8a, 0x02, 0x68, 0xff, 0xff, 0x52, 0xfd, + 0xff, 0xff, 0xff, 0x07, 0x00, 0x2a, 0x08, 0x20, 0x28, 0xdc, 0xff, 0x5f, + 0x05, 0xff, 0xff, 0xff, 0xff, 0x0d, 0x92, 0x40, 0x22, 0x09, 0x02, 0xea, + 0xfb, 0xaf, 0x48, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x12, 0x81, 0xa0, + 0x48, 0x9c, 0x6e, 0x93, 0xa2, 0xff, 0xff, 0xff, 0xff, 0x07, 0xa8, 0x40, + 0x28, 0x0a, 0x02, 0x74, 0xb5, 0x45, 0x81, 0xff, 0xff, 0xff, 0xff, 0x0f, + 0x02, 0x0a, 0x81, 0x20, 0x08, 0xae, 0xaa, 0x90, 0xe8, 0xff, 0xff, 0xff, + 0xff, 0x0f, 0x90, 0x40, 0x28, 0x88, 0x12, 0x58, 0x15, 0x50, 0xd0, 0xff, + 0xff, 0xff, 0xff, 0x0f, 0x44, 0x0a, 0x41, 0x21, 0x08, 0xae, 0x04, 0x14, + 0xf0, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x10, 0x40, 0x14, 0x88, 0x04, 0xba, + 0x02, 0x28, 0xe8, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x42, 0x15, 0x41, 0x21, + 0x05, 0xad, 0x00, 0x05, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x10, 0x40, + 0x24, 0x8a, 0x0e, 0x36, 0x00, 0x0a, 0xf4, 0xff, 0xff, 0xff, 0xff, 0x0f, + 0x42, 0x25, 0x90, 0xd0, 0x8b, 0xc2, 0x41, 0x05, 0xfc, 0xff, 0xff, 0xff, + 0xff, 0x0f, 0x10, 0x08, 0x05, 0xe8, 0x8e, 0x58, 0x80, 0x02, 0xfa, 0xff, + 0xff, 0xff, 0xff, 0x0f, 0x4a, 0x20, 0xa8, 0xba, 0x0b, 0x2b, 0x51, 0x01, + 0xfe, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x8a, 0x02, 0xe8, 0xaf, 0x84, + 0x90, 0x04, 0xfd, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x52, 0x21, 0x54, 0xbf, + 0x1f, 0x15, 0xa5, 0x02, 0xfe, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x08, + 0x01, 0xfa, 0xb6, 0xa4, 0x52, 0x40, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, + 0x4a, 0xa2, 0x54, 0xef, 0x5f, 0x4b, 0xa4, 0x80, 0xff, 0xff, 0xff, 0xff, + 0xff, 0x0f, 0x80, 0x10, 0x82, 0xfe, 0xbf, 0x92, 0x52, 0x42, 0xff, 0xff, + 0xff, 0xff, 0xff, 0x0f, 0x12, 0x42, 0xa8, 0xbf, 0x1f, 0x24, 0x80, 0xa0, + 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x84, 0x28, 0x8a, 0xf7, 0x37, 0x80, + 0x52, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x10, 0x82, 0xe0, 0xff, + 0x1f, 0x00, 0x20, 0xe1, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x84, 0x28, + 0xca, 0xff, 0x1f, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, + 0x10, 0x42, 0xf0, 0xfd, 0x1b, 0x00, 0x50, 0xf0, 0xff, 0xff, 0xff, 0xff, + 0xff, 0x0f, 0xa4, 0x10, 0xc5, 0xff, 0x1f, 0x00, 0x00, 0xe0, 0xff, 0xff, + 0xff, 0xff, 0xff, 0x0f, 0x00, 0x22, 0xf8, 0xff, 0x0e, 0x00, 0x00, 0xf0, + 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0xaa, 0x88, 0xe2, 0xff, 0x0f, 0x10, + 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x25, 0xfa, 0xff, + 0x0f, 0x01, 0x11, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0xff, 0xfb, + 0xfb, 0xff, 0x7f, 0x5d, 0xd5, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f}; diff --git a/library/demos/images/flagdown.bmp b/library/demos/images/flagdown.bmp new file mode 100644 index 0000000..55abc51 --- /dev/null +++ b/library/demos/images/flagdown.bmp @@ -0,0 +1,27 @@ +#define flagdown_width 48 +#define flagdown_height 48 +static char flagdown_bits[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, + 0x00, 0x00, 0x80, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xe1, 0x00, 0x00, + 0x00, 0x00, 0x70, 0x80, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x03, 0x00, + 0x00, 0x00, 0x0c, 0x00, 0x03, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x04, + 0x00, 0x00, 0x03, 0x00, 0x06, 0x06, 0x00, 0x80, 0x01, 0x00, 0x06, 0x07, + 0x00, 0xc0, 0x1f, 0x00, 0x87, 0x07, 0x00, 0xe0, 0x7f, 0x80, 0xc7, 0x07, + 0x00, 0x70, 0xe0, 0xc0, 0xe5, 0x07, 0x00, 0x38, 0x80, 0xe1, 0x74, 0x07, + 0x00, 0x18, 0x80, 0x71, 0x3c, 0x07, 0x00, 0x0c, 0x00, 0x3b, 0x1e, 0x03, + 0x00, 0x0c, 0x00, 0x1f, 0x0f, 0x00, 0x00, 0x86, 0x1f, 0x8e, 0x07, 0x00, + 0x00, 0x06, 0x06, 0xc6, 0x05, 0x00, 0x00, 0x06, 0x00, 0xc6, 0x05, 0x00, + 0x00, 0x06, 0x00, 0xc6, 0x04, 0x00, 0x00, 0x06, 0x00, 0x06, 0x04, 0x00, + 0x7f, 0x06, 0x00, 0x06, 0xe4, 0xff, 0x00, 0x06, 0x00, 0x06, 0x04, 0x00, + 0x00, 0x06, 0x00, 0x06, 0x04, 0x00, 0x00, 0x06, 0x00, 0x06, 0x06, 0x00, + 0x00, 0x06, 0x00, 0x06, 0x03, 0x00, 0x00, 0x06, 0x00, 0x86, 0x01, 0x00, + 0x00, 0x06, 0x00, 0xc6, 0x00, 0x00, 0x00, 0x06, 0x00, 0x66, 0x00, 0x00, + 0x00, 0x06, 0x00, 0x36, 0x00, 0x00, 0x00, 0x06, 0x00, 0x3e, 0x00, 0x00, + 0x00, 0xfe, 0xff, 0x2f, 0x00, 0x00, 0x00, 0xfc, 0xff, 0x27, 0x00, 0x00, + 0x00, 0x00, 0x88, 0x20, 0x00, 0x00, 0x00, 0x00, 0x88, 0x20, 0x00, 0x00, + 0x00, 0x00, 0x88, 0x20, 0x00, 0x00, 0x00, 0x00, 0x88, 0x20, 0x00, 0x00, + 0x00, 0x00, 0x88, 0x20, 0x00, 0x00, 0x00, 0x00, 0x88, 0x20, 0x00, 0x00, + 0x00, 0x00, 0x88, 0x20, 0x00, 0x00, 0x00, 0x00, 0x88, 0x20, 0x00, 0x00, + 0xf7, 0xbf, 0x8e, 0xfc, 0xdf, 0xf8, 0x9d, 0xeb, 0x9b, 0x76, 0xd2, 0x7a, + 0x46, 0x30, 0xe2, 0x0f, 0xe1, 0x47, 0x55, 0x84, 0x48, 0x11, 0x84, 0x19}; diff --git a/library/demos/images/flagup.bmp b/library/demos/images/flagup.bmp new file mode 100644 index 0000000..6eb0d84 --- /dev/null +++ b/library/demos/images/flagup.bmp @@ -0,0 +1,27 @@ +#define flagup_width 48 +#define flagup_height 48 +static char flagup_bits[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x7f, 0x00, + 0x00, 0x00, 0x00, 0xe0, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xef, 0x6a, 0x00, + 0x00, 0x00, 0xc0, 0x7b, 0x75, 0x00, 0x00, 0x00, 0xe0, 0xe0, 0x6a, 0x00, + 0x00, 0x00, 0x30, 0x60, 0x75, 0x00, 0x00, 0x00, 0x18, 0xe0, 0x7f, 0x00, + 0x00, 0x00, 0x0c, 0xe0, 0x7f, 0x00, 0x00, 0x00, 0x06, 0xe0, 0x04, 0x00, + 0x00, 0x00, 0x03, 0xe0, 0x04, 0x00, 0x00, 0x80, 0x01, 0xe0, 0x06, 0x00, + 0x00, 0xc0, 0x1f, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x7f, 0xe0, 0x07, 0x00, + 0x00, 0x70, 0xe0, 0xe0, 0x05, 0x00, 0x00, 0x38, 0x80, 0xe1, 0x04, 0x00, + 0x00, 0x18, 0x80, 0xf1, 0x04, 0x00, 0x00, 0x0c, 0x00, 0xfb, 0x04, 0x00, + 0x00, 0x0c, 0x00, 0xff, 0x04, 0x00, 0x00, 0x86, 0x1f, 0xee, 0x04, 0x00, + 0x00, 0x06, 0x06, 0xe6, 0x04, 0x00, 0x00, 0x06, 0x00, 0xe6, 0x04, 0x00, + 0x00, 0x06, 0x00, 0xe6, 0x04, 0x00, 0x00, 0x06, 0x00, 0x66, 0x04, 0x00, + 0x7f, 0x56, 0x52, 0x06, 0xe4, 0xff, 0x00, 0x76, 0x55, 0x06, 0x04, 0x00, + 0x00, 0x56, 0x57, 0x06, 0x04, 0x00, 0x00, 0x56, 0x55, 0x06, 0x06, 0x00, + 0x00, 0x56, 0xd5, 0x06, 0x03, 0x00, 0x00, 0x06, 0x00, 0x86, 0x01, 0x00, + 0x54, 0x06, 0x00, 0xc6, 0x54, 0x55, 0xaa, 0x06, 0x00, 0x66, 0xaa, 0x2a, + 0x54, 0x06, 0x00, 0x36, 0x55, 0x55, 0xaa, 0x06, 0x00, 0xbe, 0xaa, 0x2a, + 0x54, 0xfe, 0xff, 0x6f, 0x55, 0x55, 0xaa, 0xfc, 0xff, 0xa7, 0xaa, 0x2a, + 0x54, 0x01, 0x88, 0x60, 0x55, 0x55, 0xaa, 0xaa, 0x8a, 0xa0, 0xaa, 0x2a, + 0x54, 0x55, 0x8d, 0x60, 0x55, 0x55, 0xaa, 0xaa, 0x8a, 0xa0, 0xaa, 0x2a, + 0x54, 0x55, 0x8d, 0x60, 0x55, 0x55, 0xaa, 0xaa, 0x8a, 0xa0, 0xaa, 0x2a, + 0x54, 0x55, 0x8d, 0x50, 0x55, 0x55, 0xaa, 0xaa, 0x8a, 0xa8, 0xaa, 0x2a, + 0x54, 0x55, 0x95, 0x54, 0x55, 0x55, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x2a, + 0x54, 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; diff --git a/library/demos/images/gray25.bmp b/library/demos/images/gray25.bmp new file mode 100644 index 0000000..b234b3c --- /dev/null +++ b/library/demos/images/gray25.bmp @@ -0,0 +1,6 @@ +#define grey_width 16 +#define grey_height 16 +static char grey_bits[] = { + 0x11, 0x11, 0x44, 0x44, 0x11, 0x11, 0x44, 0x44, 0x11, 0x11, 0x44, 0x44, + 0x11, 0x11, 0x44, 0x44, 0x11, 0x11, 0x44, 0x44, 0x11, 0x11, 0x44, 0x44, + 0x11, 0x11, 0x44, 0x44, 0x11, 0x11, 0x44, 0x44}; diff --git a/library/demos/images/letters.bmp b/library/demos/images/letters.bmp new file mode 100644 index 0000000..0f12568 --- /dev/null +++ b/library/demos/images/letters.bmp @@ -0,0 +1,27 @@ +#define letters_width 48 +#define letters_height 48 +static char letters_bits[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xfe, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, + 0x00, 0xfa, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2a, + 0x00, 0x3a, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2e, + 0xe0, 0xff, 0xff, 0xff, 0xff, 0x21, 0x20, 0x00, 0x00, 0x00, 0x00, 0x21, + 0xa0, 0x03, 0x00, 0x00, 0x70, 0x21, 0x20, 0x00, 0x00, 0x00, 0x50, 0x21, + 0xa0, 0x1f, 0x00, 0x00, 0x50, 0x21, 0x20, 0x00, 0x00, 0x00, 0x70, 0x21, + 0xfe, 0xff, 0xff, 0xff, 0x0f, 0x21, 0x02, 0x00, 0x00, 0x00, 0x08, 0x21, + 0xfa, 0x01, 0x00, 0x80, 0x0b, 0x21, 0x02, 0x00, 0x00, 0x80, 0x0a, 0x21, + 0xba, 0x01, 0x00, 0x80, 0x0a, 0x21, 0x02, 0x00, 0x00, 0x80, 0x0b, 0x21, + 0x3a, 0x00, 0x00, 0x00, 0x08, 0x21, 0x02, 0x00, 0x00, 0x00, 0x08, 0x21, + 0x02, 0xc0, 0xfb, 0x03, 0x08, 0x21, 0x02, 0x00, 0x00, 0x00, 0x08, 0x3f, + 0x02, 0xc0, 0xbd, 0x0f, 0x08, 0x01, 0x02, 0x00, 0x00, 0x00, 0x08, 0x01, + 0x02, 0xc0, 0x7f, 0x7b, 0x08, 0x01, 0x02, 0x00, 0x00, 0x00, 0x08, 0x01, + 0x02, 0x00, 0x00, 0x00, 0xf8, 0x01, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, + 0xfe, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; diff --git a/library/demos/images/noletter.bmp b/library/demos/images/noletter.bmp new file mode 100644 index 0000000..5774124 --- /dev/null +++ b/library/demos/images/noletter.bmp @@ -0,0 +1,27 @@ +#define noletters_width 48 +#define noletters_height 48 +static char noletters_bits[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x1f, 0x00, 0x00, + 0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0xc0, 0xff, 0xff, 0x07, 0x00, + 0x00, 0xf0, 0x0f, 0xe0, 0x1f, 0x00, 0x00, 0xfc, 0x01, 0x00, 0x7f, 0x00, + 0x00, 0x3e, 0x00, 0x00, 0xf8, 0x00, 0x00, 0x1f, 0x00, 0x00, 0xf0, 0x01, + 0x80, 0x07, 0x00, 0x00, 0xc0, 0x03, 0xc0, 0x03, 0x00, 0x00, 0xe0, 0x07, + 0xe0, 0x01, 0x00, 0x00, 0xf0, 0x0f, 0xe0, 0x00, 0x00, 0x00, 0x78, 0x0e, + 0xf0, 0x00, 0x00, 0x00, 0x3c, 0x1e, 0x70, 0x00, 0x00, 0x00, 0x1e, 0x1c, + 0x38, 0x00, 0x00, 0x00, 0x0f, 0x38, 0x38, 0x00, 0x00, 0x80, 0x07, 0x38, + 0x3c, 0xfc, 0xff, 0xff, 0x7f, 0x78, 0x1c, 0x04, 0x00, 0xe0, 0x41, 0x70, + 0x1c, 0x04, 0x00, 0xf0, 0x40, 0x70, 0x1c, 0x74, 0x00, 0x78, 0x4e, 0x70, + 0x0e, 0x04, 0x00, 0x3c, 0x4a, 0xe0, 0x0e, 0x74, 0x03, 0x1e, 0x4a, 0xe0, + 0x0e, 0x04, 0x00, 0x0f, 0x4e, 0xe0, 0x0e, 0x04, 0x80, 0x07, 0x40, 0xe0, + 0x0e, 0x04, 0xf8, 0x0f, 0x40, 0xe0, 0x0e, 0x04, 0xe0, 0x01, 0x40, 0xe0, + 0x0e, 0x04, 0xf8, 0x00, 0x40, 0xe0, 0x0e, 0x04, 0x78, 0x00, 0x40, 0xe0, + 0x0e, 0x04, 0xfc, 0xf3, 0x40, 0xe0, 0x1c, 0x04, 0x1e, 0x00, 0x40, 0x70, + 0x1c, 0x04, 0x0f, 0x00, 0x40, 0x70, 0x1c, 0x84, 0x07, 0x00, 0x40, 0x70, + 0x3c, 0xfc, 0xff, 0xff, 0x7f, 0x78, 0x38, 0xe0, 0x01, 0x00, 0x00, 0x38, + 0x38, 0xf0, 0x00, 0x00, 0x00, 0x38, 0x70, 0x78, 0x00, 0x00, 0x00, 0x1c, + 0xf0, 0x3c, 0x00, 0x00, 0x00, 0x1e, 0xe0, 0x1e, 0x00, 0x00, 0x00, 0x0e, + 0xe0, 0x0f, 0x00, 0x00, 0x00, 0x0f, 0xc0, 0x07, 0x00, 0x00, 0x80, 0x07, + 0x80, 0x07, 0x00, 0x00, 0xc0, 0x03, 0x00, 0x1f, 0x00, 0x00, 0xf0, 0x01, + 0x00, 0x3e, 0x00, 0x00, 0xf8, 0x00, 0x00, 0xfc, 0x01, 0x00, 0x7f, 0x00, + 0x00, 0xf0, 0x0f, 0xe0, 0x1f, 0x00, 0x00, 0xc0, 0xff, 0xff, 0x07, 0x00, + 0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0xf0, 0x1f, 0x00, 0x00}; diff --git a/library/demos/images/pattern.bmp b/library/demos/images/pattern.bmp new file mode 100644 index 0000000..df31baf --- /dev/null +++ b/library/demos/images/pattern.bmp @@ -0,0 +1,6 @@ +#define foo_width 16 +#define foo_height 16 +static char foo_bits[] = { + 0x60, 0x06, 0x90, 0x09, 0x90, 0x09, 0xb0, 0x0d, 0x4e, 0x72, 0x49, 0x92, + 0x71, 0x8e, 0x8e, 0x71, 0x8e, 0x71, 0x71, 0x8e, 0x49, 0x92, 0x4e, 0x72, + 0xb0, 0x0d, 0x90, 0x09, 0x90, 0x09, 0x60, 0x06}; diff --git a/library/demos/images/tcllogo.gif b/library/demos/images/tcllogo.gif new file mode 100644 index 0000000..fcdfd36 --- /dev/null +++ b/library/demos/images/tcllogo.gif @@ -0,0 +1,8 @@ +GIF89aDd÷ÿÿÿÿÿÿÌÿÿ™ÿÿfÿÿ3ÿÿÿÌÿÿÌÌÿÌ™ÿÌfÿÌ3ÿÌÿ™ÿÿ™Ìÿ™™ÿ™fÿ™3ÿ™ÿfÿÿfÌÿf™ÿffÿf3ÿfÿ3ÿÿ3Ìÿ3™ÿ3fÿ33ÿ3ÿÿÿÌÿ™ÿfÿ3ÿÌÿÿÌÿÌÌÿ™ÌÿfÌÿ3ÌÿÌÌÿÌÌÌÌÌ™ÌÌfÌÌ3ÌÌÌ™ÿÌ™ÌÌ™™Ì™fÌ™3Ì™ÌfÿÌfÌÌf™ÌffÌf3ÌfÌ3ÿÌ3ÌÌ3™Ì3fÌ33Ì3ÌÿÌÌÌ™ÌfÌ3Ì™ÿÿ™ÿÌ™ÿ™™ÿf™ÿ3™ÿ™Ìÿ™Ì̙̙™Ìf™Ì3™Ì™™ÿ™™Ì™™™™™f™™3™™™fÿ™fÌ™f™™ff™f3™f™3ÿ™3Ì™3™™3f™33™3™ÿ™Ì™™™f™3™fÿÿfÿÌfÿ™fÿffÿ3fÿfÌÿfÌÌfÌ™fÌffÌ3fÌf™ÿf™Ìf™™f™ff™3f™ffÿffÌff™fffff3fff3ÿf3Ìf3™f3ff33f3fÿfÌf™fff3f3ÿÿ3ÿÌ3ÿ™3ÿf3ÿ33ÿ3Ìÿ3ÌÌ3Ì™3Ìf3Ì33Ì3™ÿ3™Ì3™™3™f3™33™3fÿ3fÌ3f™3ff3f33f33ÿ33Ì33™33f333333ÿ3Ì3™3f333ÿÿÿÌÿ™ÿfÿ3ÿÌÿÌÌÌ™ÌfÌ3Ì™ÿ™Ì™™™f™3™fÿfÌf™fff3f3ÿ3Ì3™3f333ÿÌ™f3îÝ»ªˆwUD"îÝ»ªˆwUD"îÝ»ªˆwUD"îîîÝÝÝ»»»ªªªˆˆˆwwwUUUDDD""",DdÿH° Áƒ*\È°¡ÀzöHt@Q†Œ92æpà°ãÀzõ$@@ÑEŒuY¹2ˆË—0c™qÀcB,[ÆÜɳ§Ï ë1qbM2~*]ªÈÆ‹s¨ÌS†@L³jݺ“#¬\Êõ‰àêسhƒ›¶Ö£ÜÊ] +D(€¸m™ëÈ@¼Z÷îܱƒoO¿3=²cÁÁG"(ðØpLíq]°à%ãÉ +[†™ã#¬Ÿ+ïåüXðh—¥ž^¡³ËÈ‚¸~írÁÙK#Gp] Æîzõ¶µ:øÒÐ{Ô°ÝsïFœÇÃzè\)t—ŒWÿr€= Ù·nÐݧôÛ;r§?¢Ã€zOªÔsþ-A¨‰gÕé TÈ8£ ímU9pµeÙQW=¤(¨!2] eß@nõ™n1Yx€= j¨!gÕEPˆÕÆÓ¨¢ŠÎM‹Á¨•cÇñ†8:ƒÌ!;”\‰=aöbX@*YZ†E®ÂÓ¡ÁåN±
4ƒˆòt@E*ÈâN5@Ý€k’VPR5Vbö”é’È¡¦g2òÔ¥@pÁNY¤*³)w›žÃÝVC£;17[‹aéš…(–©cNÁ˜šk5ØUA”GØ¥Šã!œÊ`—ÑÅÿ§Õz_‰x*LP‰ã*ª ãkFW[;=X+Z@¬p£ÎÀ‚m¹”± E_̪ØE°«mõá_Öæ j¶¥å ×£ÄÊd¸g‘ƒ®Ì®ÂzAš.Lˆ¤XXîÂkç!‘)Sù²;–»ËÚ9F=2èukVNt^»9$\fõÐ+`Vʆì²Èø» +I÷úÔ1wÈâHJÂú@¯X’þ––*’OÂV<P²O17—Ö*+Zr cÑŠ²XØ¢!ت¨Oƒ[•e€bIÄ> +®"®ŠV¶e¬@T‡U“=T2øºíüÓ׎u€ +++ˆˆ¬ÈAFÈ®ûdÕO¨ÿHÆ=º®HDÈ"äcÔª®’¬¿÷ðÇãA‡kU¨†Šgª¢=¨ÍSÁÿ‰u„‰×µ,)õÀúøÔž;`…†ûÔ·, ç}ÔJ ¹º‘ˆÐ¹¬ÐN°Þ>ó›ƒ +"“»*Z±¯XßÊ̯ÄIF*à(ÃòbÏ>298£ØsõuìbáÐ9> >å@ à;SçÏÿÓ˜9ÃûY«ß–Ñš9Xô¡?þÝéŽC‹ÑÊ·äCzûSÑ䧹ž,Yü^øT”ƒ—¡¥gwIKäF'ÊÁÆ~J!£ƒåÎrÓ³úÎ⛂¬`:Dg% à#€h9Y©ÿ$„U c ZÐHqC¦ñ`9Â!¡¸zŒnˆay¢ç0s@8£ŠËªBÏ¢E·å!E@ ›ŠV`®´DlRS +&¢°)!̨„ˆÉ)(:kçb- Ü#A‡†dpG<äK…ÄÐ4@dÎ-ƒ„d!óAŠôÍ’‹‹ö––#a9PV×æÒ¼¶Í%‡8Ó\Œ¹è€"0qÙ½€ð´qZ=BŽæÊ_é8åÚ-wâÔ8}ŸƒVL¤"¥`1Ej ÛmæŤî|š3£…¾r©rqJ',ˆ6Mô•—¹ËÎ7µ‘˜<à.ž*WüPÿ˗Ъ=ܼ_"„È<8ñ»Ì±nS®hÒ'ÿ,Q@uc•ÓtÐ3…‰ü<ãq–æ»Wϼ9/ƒ²GQÛœáç~9N~%„é©DPMX53¥Jš4uÓÑrB¨4X„I
=¦$«ÀW8™é‚@¾zxê–ø +Éf£¾vÖ'&#ÈI9¨_,ÁV_âçä$¬YÍLu*ÄV.9¥ž‰ëOþÔÄíæuå-õ¥W¾,¯}%_‹I‚•°\åBë!826-å9ìc³Ùíd*gm¤ƒ¢G²®D#2 ˆDd˜¢ˆD$%)ÉIP¯f6² F<› diff --git a/library/demos/images/teapot.ppm b/library/demos/images/teapot.ppm new file mode 100644 index 0000000..5a7a48c --- /dev/null +++ b/library/demos/images/teapot.ppm @@ -0,0 +1,30 @@ +P6 +256 256 +255 +\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À +j5 +h4 +g3 +5$D,K/b; h>"wM1tK.e="a<#cA,U8&E-<(9&.!a0 b1 c1 + ++3#@)46G<:HMCIXHK\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀU*´vT¿~X¸{YÃk+›W&‰N$|>u:p8k5 +f3 +a0 _/ ]. [- I¡\*ª_(‘LkRMmSMmSMnSMnSMD,R3W5mA"|O0|P1j?"c<!a=%Y7"N1F,;'NCJNCJNDJODJODJODJh>!a: X/K%&4$+2F=;HPEJL&\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀŸlR¶xTsTµd)ŠO$w;m6 +g3 +a0 Z- \/T*Q(ŠHµm8kRMmSMnTMoTMpTMpUM15G15G05G04G04GpUMpTM5^9 d<!yF#O+€N,rC#qB"pB#k?"a: Z7 6ODJPDJPEJQEJQEJREJREJREJRFJSFJSFJSFJSFJe<!X/- '0FªqS–gQ\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À“fP¯tS mRR%Bf3 +^/ V+Q(L&I$r9 TlRMnSM46G47G47G46G46G46G46G46G36G36G25G25G15G04G/4F.3FoA"ˆN$‹O%S)ŒR)”T&”T%‘R%ŠO$€J#xE#PDJQEJREJRFJSFJTFJTFJTGJUGJUGJUGJUGJVGJVGJVGJVGJVGJVGJY6N't;‹O$dP¥oRdP\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À¨pSkQ“S%x=[- R)I$E"@ ”M¦]'pTM68G78G78G78G78G78G78G78G78G68G67G67G57G57G47G36G36G25Gp98eOLpUMtVMn7·f+½i,¾i*¿i*¾h*…B
ˆ`O~[NqUM[- ‰HUGJUGJVGJVGJVHJWHJWHJWHKWHKXHKXHKXHKXHKXHKXIKXIKXIKXIKXIKh>!Y0W+]. s=‡M$dPŸlR\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀoTM¥oRdPvE"V+K%A 99†F¤['qUMtVM99H:9H:9H:9H:9H:9H:9H:9H:9H:9H99H99H99H99H99H99H:9H;:H>;HB=HPDJ\JKmSMwXN|ZN°y[ᦆ֘uº{W¹yU¿€]Á„btU£nR—hQˆaO{ZNvWNtVMvXNwXNyYNzYN{ZN|ZN}[N}[N~[N~[N~[N~[N~[N~[N~[N}[N}[N{ZNzYNxXN…L$f3 +I$L&P(U*\. €J#\O›jQ\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀžkR‰aOo9
L&C!:4f3 +X&pUMuWMwXNxXN<:H<:H<:H<:H<;H<;H<;H<;H=;H=;H=;H=;H>;H>;H?<H@<HA=HC>HG@ILBIREJ[JKcNLjQL§pR±uTºzUÃ~VÈWË‚XÖŽcäsÒŽe¼{V²vT¨pSžkR•gQŒbP†_O‚^O]O€\O€\O€\O€\O€]O]O]O]O]O]O]O]O]O]O]O€\O€\O~\N}[N|ZNxXN•T%H$G#K%Q(W+zG#nTM˜iQ\À\À\À\À\À\À\À\À\À\À\À\ÀdOLrUMuWNwXNyYN{ZN}[N{ZNwXNsVM\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\Àˆ`OcPnA"M&@ 8F#m6 +›W&rVMvWNyYNzYN|ZN}[N}[N><H?<H?<H?<H?<H?<H@<H@<H@<HA=HA=HB=HC>HE?IG@IIAIKBIODJSFJWHK—hQŸlR§pR°b(¾i*Én+Ù|7Û|6Ïr,Íq+Êp-Ãl+»g)±b(®sS§pS lRšiQ•gQePcPŠaPˆaO‡`O‡`O†_O†_O…_O…_O…_O…_O…_O…_O…_O„_O„^O„^Oƒ^Oƒ^O‚]O]O€\O~[N{ZN•T%F#B!Y,L&U*~I#„^O†`O\À\À\À\ÀcNLrUMzYN\O„^Oˆ`OŠbPŒcPdPeP’fP“fP“fQ“fQ”fQ‘ePcP‰aP~[N\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À’fPsVM^/ C!7
ŽQ%tVMwXNzYN|ZN}[N\N\O€\O]O]O‚]O‚]OA=HB=HB=HB>HC>HC>ID?IE?IF@IG@IIAIKBIŒcPdP’eP–gQšiQŸlR£nR¤\'´d)¿i*Æm+Îs/Ïs/Êo+Én+Ål*¾i*ºg)³c(ª_(ªqS¦oR¡mRkQ™iQ•gQ“fP‘ePŽdPcPŒbP‹bPŠbPŠaP‰aP‰aO‰aOˆaOˆ`Oˆ`O‡`O‡`O‡`O†`O†_O…_O„^Oƒ^O‚]O\O}[N›QD"?D"K%_/ kRL’fPODJSFJ†_OŠbPŽcP‘eP“fQ–gQ™iQœjQžkR lR¡mR£nR¤nR¥oR¥oR¥oR¤nR¢mRŸlRšiQ‘eP…_O\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀB+‘ePI#L&90y<šPxXN{ZN}[N\N€\O]O‚]Oƒ^Oƒ^O„^O„_O…_O…_O†_O†`O‡`O‡`Oˆ`O‰aOŠaP‹bPŒbPcPŽdP‘eP“fP•gQ˜hQšiQžkR¢mR¡Z'«_(¶e)½h)Âk*Çn,Çn,Æm*Æl*Áj*ºf)¶e)²c(«_(¦]'§pR¤nR¡mRžkR›jQ™iQ–gQ”gQ“fP‘ePdPdPŽdPŽcPcPŒcPŒbP‹bP‹bP‹bPŠbPŠaP‰aP‰aO‰aOˆ`O‡`O†_O…_Oƒ^O]Oª_(@B!I$B!N'w=‘eP`LKbNLeOLkR mR£nR¥oR§pSªqS¬rS®sS¯tS°tS°tS±uS±uS°tS¯tSsSªrS§pS¢mRšjQŒbPjQL\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À‹bPpTME"5‡M$tVM{ZN}[N\O]O‚^Oƒ^O„_O…_O†_O†`O‡`Oˆ`Oˆ`O‰aO‰aPŠaPŠbP‹bPŒbPcPŽcPdPdP’eP“fP•gQ—hQ™iQ›jQkR lR¢mR¡Z'¬`(µd)ºg)ÇgÀj*Àj*¾i*¿i*»g)µd)²c(¯a(ª_(¤\'§pR¥oR¢nR mRžkRœjQšiQ˜iQ—hQ•gQ”gQ“fP’eP‘eP‘ePdPdPdPŽcPŽcPcPcPŒcPŒbP‹bP‹bPŠbPŠaP‰aOˆ`O†_O„^O\NœQ@ <G#_LKŽcPlSMnTMpUMsVM°tS²uT³vTµwT¶wT¶xT¶xT¶wTµwT´vT²uT¯tS¬sSªqS§pS¤oR¢nRžkR˜hQ‹bPeOL\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀwXN\NJ%01ŽJvWN}[N\O]Oƒ^O…_O†_O†`O‡`Oˆ`O‰aO‰aPŠaPŠbP‹bPŒbPŒbPcPŽcPŽdPdPdP‘eP’eP”fQ•gQ–gQ˜hQ™iQ›jQkQŸlR¡mRžY&¦]'`(³c(·e)Àc¸\¸\¹\º]»]¶^®a(¬`(©^'£['¢['¥oR£nR¡mR lRžkRœkQ›jQšiQ˜iQ—hQ–gQ•gQ”gQ”fQ“fP’eP’eP‘eP‘ePdPdPdPdPŽdPŽcPcPcPŒbP‹bPŠaPˆaO†`O]O˜OG#7F#uWMƒ^OwXNxXNzYN{ZN|ZN¹yT¸yT·xT´wT±uTsS¨pS¡mRœjQ•gQdPŒbP‰aP‰aPŒbPŽcP‘ePcP|ZN\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À[JKŠbP^/ 101|>wXN}[N]Oƒ^O…_O‡`O‡`OˆaO‰aPŠaP‹bP‹bPŒbPŒcPcPŽcPŽcPdPdPdP‘eP’eP“fP”fQ•gQ–gQ—hQ˜hQ™iQ›jQœkQžkRŸlR mRžY&¦]'`(±b(·[ÇgÉiÉhÅfÂdÃe¿c«Uª_(§]'£[' Z'¤nR£nR¡mR mRŸlRžkRkQœjQšjQšiQ™iQ˜hQ—hQ–gQ•gQ•gQ”fQ”fQ“fP“fP’eP’eP‘e + + +@%<-$G?@…pfdNLuWM\NdNL\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀTFJvWN‰aP./01„E}[N]O…_Oˆ`O‰aP‹bPŒbPcPcPŽcPdPdPdPeP‘eP’eP’eP“fP“fQ”fQ•gQ•gQ–gQ–hQ—hQ˜hQ™iQšiQ›jQœjQkQkRžlRŸlRžY&¤\'¨^'µ^½bÀcÃeÇi ÄgÀc½b¼a¹`µ^´]¯X¢[' Z'žY&¢mR¡mR¡mR lRŸlRŸlRžkRkQœkQœjQ›jQšjQšiQ™iQ™iQ˜iQ˜hQ—hQ—hQ—hQ–gQ–gQ•gQ•gQ•gQ”fQ”fQ“fQ“fP’eP‘ePdPcP‰aP—O‡`O‡`OoTMQEJC>IeZY638* B\À\À\À\À\À,4 .G1!\TU¡ƒrsVM{ZN`MK\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À[JKyYNŒbP/0ˆN$]O…_Oˆ`O‹bPŒbPcPŽcPdPdPdP‘eP‘eP’eP’fP“fP“fQ”fQ”gQ•gQ–gQ–gQ—hQ—hQ˜hQ™iQ™iQšiQ›jQœjQœkQkRžkRŸlRœO¡Z'¥\'©^'V¼a¾bÁeÆi!Ãf¾b»a¹`·_³]²\µZ¢[' Z'ŸY&œQ¡mR¡mR mR lRŸlRŸlRžkRkRkQœkQœjQ›jQ›jQšjQšiQšiQ™iQ™iQ˜iQ˜hQ˜hQ—hQ—hQ—hQ–hQ–gQ–gQ•gQ•gQ”fQ’fPdPcPšW&dPŠaPrUM + B\À\À\À\À\À\À\À\À\À\À%7!!C*F#P){dYœze»p€\OgPL\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀSFJ`LKvWNŠaPm6 +X,uWM‚]O‡`OŠbPcPŽdPdPdP‘eP’eP’fP“fP“fQ”fQ”gQ•gQ•gQ–gQ–gQ—hQ—hQ˜hQ˜iQ™iQ™iQšiQ›jQ›jQœjQœkQkQžkRžlRŸlR¢Z'¤\'§]'·_¹`¼a½bÁeÅi"Áe¼aº`·_¶_²]²\±\«Y¡Z' Z'¡Z'¡mR¡mR mR lR lRŸlRŸlRžlRžkRžkRkRkQœkQœjQœjQ›jQ›jQ›jQšjQšiQšiQšiQ™iQ™iQ™iQ˜iQ˜hQ˜hQ—hQ–gQ•gQ“fQdP†_Oq8–gQˆ`OuWM”T%\À\À\À\À\À\À\À\À\À\À B B!!T,c5ƒF‚T3È›~Æ“qƒ^OfOL\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀXHK_LKsVM‡`OcP ’S%]OŠbPcPdP‘eP’eP“fP“fQ”fQ”gQ•gQ•gQ–gQ–gQ—hQ—hQ—hQ˜hQ˜iQ™iQ™iQšiQšiQ›jQ›jQœjQœjQkQkRžkRžlRŸlRŸlR¥\'¦]'¨^'Vº`»a½bÁfÄi"Àe»a¹`·_¶_³]±\±\¤R¢Z'¢Z'£['¡mR¡mR¡mR¡mR mR lR lRŸlRŸlRŸlRžlRžkRžkRkRkRkQkQœjQœjQœjQœjQœjQ›jQ›jQ›jQ›jQšjQšiQ™iQ™iQ˜hQ–gQ‘eP§Sq8‰aO•gQ‡`OtVMœX&\À\À\À\À\À\À\À\À\À\À B B Bl@!{A…L$›Y'½†a“fPˆaO]KK\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀODJ[JKaMKqUM\OcPƒ^OvE"‚]OŠaPdP‘eP“fP”fQ•gQ•gQ–gQ–hQ—hQ—hQ˜hQ˜hQ˜iQ™iQ™iQ™iQšiQšjQ›jQ›jQœjQœjQœkQkQkRžkRžkRŸlRŸlRŸlR lR©^'©^'ª_(®W»a¼a¾cÂg Äi"¿e»a¹`·_¶_³^±\±\¤R£['£['§]'¢mR¢mR¡mR¡mR¡mR¡mR mR lR lR lR lRŸlRŸlRŸlRŸlRžlRžlRžkRžkRžkRžkRkRkRkRkRkQkQkQœjQœjQšiQ˜hQ’ePšW&M&oTMšiQ‘eP…_OtVMmSMdOL\À\À\À\À\À\À\À\À\À B B B‘J Z'ª_(œkQ™iQ‡`OSFJ\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀTFJ\JKcNLlRMzYN‡`O’ePzZN \Nˆ`OdP“fQ•gQ–gQ—hQ˜hQ˜hQ™iQ™iQ™iQšiQšiQšiQ›jQ›jQ›jQœjQœjQœjQœkQkQkRžkRžkRžlRŸlRŸlRŸlR lR lR mR®a(`(¬`(¶[½a½b¿dÃh!Äi"¿d»a¹`¸_¶_µ^²]³]¦S¤\'§]'«_(¢nR¢mR¢mR¢mR¢mR¢mR¢mR¡mR¡mR¡mR¡mR¡mR mR mR mR mR lR lR lR lR lR lR lR lR lRŸlRŸlR lRŸlRžkRœkQ™iQePt:kQ˜hQcP€]OtVMlSMa2
\À\À\À\À\À\À\À\À\À B B +$5 ¬`(¶e)£nRœjQƒ^OJAI\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀXIK^KKdNLhPLuWM‚]OŒbP”fQeP
m6 +†`OŽcP“fQ—hQ˜hQ™iQšiQšjQ›jQ›jQ›jQœjQœjQœjQœkQkQkQkRžkRžkRžkRžlRŸlRŸlRŸlR lR lR lR¡mR¡mR¡mR¡mRºg)³c(²c(±b(V¿cÂeÅi!Åi!Àd¼bº`¹`·_·_¶^¢Q§]'ª_(`(¹f)£nR£nR£nR£nR£nR£nR£nR¢nR¢nR¢nR¢nR¢nR¢nR¢mR¢mR¢mR¢mR¢mR¢mR¢mR¢mR¢mR¢nR¢mR¢mR£nR¢mR¢mR¡mR mRkR—hQˆGa0 ŠbP mRœjQ“fQ‰aP}[NrUMmSM…L$\À\À\À\À\À\À\À\À B B
#C, 8&H.Z7 §pR›jQ{ZN\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀQEJ[JK`LKdNLhQLqUM{ZN…_OŽcP–gQ—hQ +‹bP‘eP–hQšiQ›jQœjQkQkQkRžkRžkRžlRžlRŸlRŸlRŸlRŸlRŸlR lR lR lR mR¡mR¡mR¡mR¡mR¡mR¢mR¢mR¢mR¢nR£nRÀj*ºg)·e)¶d)Âd°XÅgÅhÂe¿c½b½b¾bªU`(®a(¯a(³c(¾i*¤oR¤oR¤nR¤nR¤nR¤nR¤nR¤nR¤nR¤nR¤nR¤nR¤nR¤nR¤nR¤nR¤nR¤oR¤oR¥oR¥oR¥oR¥oR¥oR¥oR¦oR¦oR¥oR¥oR¤nR¡mR›jQŽQ%Z- œjQ£nRŸlR—hQŽdP…_OuWMpTMnSMkRLa: \À\À\À\À\À\À\À B B&D2
@*S6#G@IPDJ˜hQmSM\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀVGJ]KKbMLeOLiQLlRMvWN\OˆaO‘eP—hQœjQ•gQoTM•gQ™iQkQŸlRŸlR lR mR¡mR¡mR¡mR¡mR¡mR¡mR¡mR¢mR¢mR¢mR¢mR¢mR¢mR¢nR£nR£nR£nR£nR£nR¤nR¤nR¤nR¤nR¤nR¤nRÆl*Ãl+¾j+¹g)¸f)¶e)µd)¶e)¶e)·e)·e)¸f)¾i*Ìs0Ðs.¦oR¦oR¦oR¦oR¦oR¦oR¦oR¦oR¦oR¦oR¦oR¦oR¦oR¦oR¦oR¦oR¦pR§pR§pR§pR§pR§pS§pS¨pS¨qS©qS©qS©qS¨pS©qS§pS¤nRŸlR‘I˜hQ§pR¥oR¡mRšiQ’ePŠaP€\OsVMpTMnTMlRM–X)\À\À\À\À\À\À\À B%C)D$;J/[8"LBITGJYIKWHK\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀNCJYIK_LKcNLgPLjQLlRMpUMzYNƒ^O‹bP‘eP˜hQkQŸlR”fQ- —hQ›jQŸlR¢mR£nR£nR£nR¤nR¤nR¤nR¤nR¤nR¤nR¤nR¤oR¤oR¥oR¥oR¥oR¥oR¥oR¥oR¥oR¥oR¥oR¥oR¥oR¦oR¦oR¦oR¦oR¦oR¦pR¦pR§pRàpßy-Ûw-Ûw-Þy.â{-ãu§pS§pS§pS§pS§pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨qS©qS©qS©qS©qS©qS©qS©qSªqSªrS«rS«rS¬rS¬rS¬rS¬rS¬sS«rSªqS¦oRšiQ™iQ©qSªqS§pR¡mRœjQ•gQcP„_O{ZNtVMpUMoTMmSMjQL_9 \À\À\À\À\À B"C(D#*A$[<)d<!QEJWHKXHKD>I\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀSFJ[JKaMKeOLhPLkRLmSMoTMuWM}[N…_O‹bP’eP˜hQžkR¢mR£nRžkR!-EkR¡mR¤nR¥oR¦pR§pR§pS§pS§pS§pS§pS§pS§pS§pR§pS§pS§pS§pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨pS¨qS¨qS¨qS©qS©qS©qS©qS©qS©qS©qS©qS©qS©qS©qSªqSªqSªqSªqSªrS«rS«rS«rS«rS«rS«rS¬rS¬rS¬rS¬sSsS®sS®sS¯tS¯tS¯tS¯tS°tS°uS°tS®sS«rS£nR¦oR®sSsS«rS§pR¢mRœjQ–gQdPˆaO\OyYNuWMqUMoTMnSMkRLo8
\À\À\À\À\À B'D+E$(1J/jH1NCJUGJYIKUGJ\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀXHK]KKbNLfOLiQLkRMmSMoTMqUMxXN\N†_OŒbP’fP˜hQkQ¡mR¥oR§pS¦pR˜hQ¢mR¥oR¨pSªqS«rS«rS«rS«rS«rS«rS«rS«rS«rS«rS«rSªrSªrSªrS«rS«rS«rS«rS«rS«rS«rS«rS«rS«rS«rS«rS«rS«rS«rS«rS¬rS¬rS¬rS¬rS¬rS¬rS¬rS¬sS¬sSsSsSsSsSsSsS®sS®sS®sS®sS®tS¯tS°tS°uS±uS±uT±uT²uT²uT²uT´vTµwT´vT³vT²uT¯tS¢mR¯tS±uT±uS®tS«rS§pR¢mRkQ—hQ‘ePŠaPƒ^O\N{ZNvXNqUMpTMnSMlRMP%\À\À\À\À B#C*E$.E- .!G$Y:%d<"SFJYIKZIKNCJ\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀPDJZIK_LKdNLgPLjQLlRMnSMpTMqUMuWMyYN€\O†`OcP’fP—hQœjQ¡mR¥oR¨qS«rS«rSªrS mR«rSsS¯tS°tS°tS°tS¯tS¯tS¯tS¯tS¯tS¯tS¯tS¯tS¯tS¯tS®tS®sS®sS®sS®sS®sS®sS®sS®sS®sS®tS®tS®tS¯tS¯tS¯tS¯tS¯tS¯tS¯tS¯tS¯tS¯tS°tS°tS°tS±uS +!C+E'0F.4F7%8%U/lG.SFJZIK]KKZIKB=H\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀREJZJK`LKdNLgPLjQLlRMnSMpTMqUMtWMxXN{ZN~[N]O„^O†`O‰aO‹bPdP•gQ™iQœkQ lR¤nR§pSªrSsS¯tT²uT´vT¶wT·xT¹yT¹yTºyTºyT¹yT¶xT´vT¬rS¢nR—hQ¿|U¿|UÀ|UÀ|UÀ|UÀ|UÀ|UÀ|UÀ|UÀ|UÀ|UÀ|UÀ|UÀ|UÀ}UÀ}UÁ}UÁ}UÁ}UÁ}UÂ}UÂ~UÃ~UÃ~VÃ~VÄVÅ€WÆX®a(ŸlRªrS´vT¸yT¼zU¾|UÁ~VÃXÆ‚[Ɇ_΋dÓ‘jÔ“mÔ“nБlÊŒhĆd½_¶{[°vWªsU¦pS¢nRžkRšiQ˜hQ•gQ“fQ‘ePdPŒbP‰aO†_Oƒ^O€\O|ZNxXNsVMpTMnTMmSMjQL€C B)D&/F-3F47G6%>"Y7 kA$YIK]KK^KKSFJ\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀVGJ\KKbMLeOLhPLkRLmSMnTMpTMrUMuWNyYN|ZN\N‚]O„_O‡`OŠaPŒbPŽcPeP“fP—hQ›jQžlR¢nR¥oS©qT¬sT¯uU²vU´wV¶xV¸yV¹yUºzU»zU¼{U½{U¾{U¾|U¿|U¿|U¿|U¿|U¾{U½{U¼{U¼zU»zTºyT¹yT¸xTµwT³vT´vT´vT´vT´wT´wTµwT·xT¹yTºzT¼zU½{U¾{U¿|UÀ|UÂ}UÄVÅ€WÇ‚YÉ„\͈_ÑŒdÙ”láuç£|쩂ſtî‡ëª…æ¦ÞŸ{Õ—sËŽl†d¹^³yZuW¨qU¤oSŸlRžkRœjQšiQ˜hQ–gQ”fQ‘ePdPcPŠaP‡`O„^O]O}[NyYNuWMpTMoTMmSMkRLgPL&D#.E,3F46G;'<(D"iB(VGJ]KK`LK[JKB>H\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀNCJYIK^LKcNLfOLiQLkRMmSMoTMqUMsVMvXNzYN}[N€\O‚^O…_Oˆ`OŠaPŒcPdP‘eP“fQ•gQ—hQ™iQkR mS¤oT¨rU¬tW°wY´zZ¸}\»]¾€^À^Á‚^‚^Â\Á€ZÁYÁXÁ~WÁ~WÂ~VÂ~VÂ~VÃ~VÃ~UÃ~UÄ~UÄ~UÄUÄUÅVÅVÅVÅVÆVÆ€VÆ€VÇ€WÇWÈ‚XɃZË…[͇^ЊaÓdØ’iÜ—nâtè£zî©ó¯‡ø´û¸‘üº“û¹“÷¶ñ±Œé©…à¡~Ö˜vËmÇf»€`´z[®vX©rU¥pT£oS¢nS lRžkRœkRšjQ˜iQ–hQ”fQ’ePdPcP‹bPˆ`O…_O‚]O~[NzYNvWNpTMoTMnSMkRMhQLo7,2F36G99HC+@ ]8 nA"\JK`ML_LKSFJ\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀSFJ[JK`LKdNLgPLjQLlRMnSMpTMqUMtVMwXNzZN}[N€]Oƒ^O†_OˆaO‹bPcPdP‘eP“fQ•gQ—hQ™iQ›jRžlR mS£oU§rW¬vZ²{]¹€a¿…fÅŠjËnГqÓ•sÕ–sÕ–rÕ–qÕ”oÓ’mÑjÏgÍŠcˈaɆ^È„\Ç‚[ÆYÅ€XÅ€WÅWÅWÅVÅVÅWÅ€WÆ€WÇXÈ‚YɃ[Ê…\͇_ÏŠaÒeÕ‘hÙ•mÝ™qávä¡zç¤}ê§€ë©ƒëª„é¨ƒå¥€ß |Ù›wÓ•rÌmƉh¿„c¸~^²yZ®vX¬tWªsV¨qU¦pT¤oS¢nS mRžlRœkR›jQ™iQ—hQ•gQ“fPePŽcP‹bPˆaO…_O‚^O\N{ZNwXNsVMoTMnSMlRMiQL~I#26G99G?<HA*E$ i@$ZIKaMLbML[JK;:H\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀWHJ]KKbMLeOLhPLjRLlSMnTMpTMrUMuWMxXN{ZN~\N]O„^O†`O‰aO‹bPŽcPdP’eP”fQ–gQ˜hQšiQœkRžlS mT£oU¦rWªuZ¯y]´~aºƒfŠlË’sÔšzÜ¡€ã§†è«‰ë®‹í¯Œí®‹ë¬ˆè¨„ã£~ßžyÚ™tÖ•oÒjÎŒfˈbÈ…_ƃ\ÅZÄ€YÃXÂWÂ~WÂ~WÂ~WÃXÀXÄ€YÅZƃ\Ç…^Ɇ`ˈbÌŠdÍ‹fÎgÎŽiÎŽjÎŽjÍŽjËŒiljgÆd¿ƒaº^¸}]¶|\´{[²yZ°xY®vX¬tWªsV¨qU¦pT¤oS¢nS mRžlRkR›jQ™iQ—hQ•gQ“fP‘ePŽdPŒbP‰aO†_Oƒ^O€\O|ZNxXNtVMpTMnSMmSMjQLgPL99G?<HG-E&b;!YIK`MLdOM`LKNCJ\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ +S)?*%.—hQ—hQ‘eP‡`OuWM\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀSFJ[JK`LKdNLgPLjQLlRMnSMoTMqUMsVMwXNzYN}[N€\O‚^O…_O‡`OŠaPŒbPŽdP‘eP“fP•gQ—hQ˜iQšjRœkRŸlS¡nT¤pV§sX«vZ°z^¶b¼…gËmÊ’sјzØŸ€Þ¤…ã©Šèê¯ë°ê¯Žè¬‹å¨‡à¤‚Ûž|Ö™wÑ“qÌŽlljgÃ…bÀ‚_½\»}Zº{X¹zW¸yV·yU·xU·xU·xT·xT·xU·xU·xU·yV·yV·yW¸zW¸{X¹{Y¹|Zº}[º}[º}\º~\¹~]¹~]¸}]·|\µ{\´z[²yZ°wY®vX¬tWªsV¨rU¦pT¤oS¢nS¡mRŸlRkRœjQšiQ˜hQ–gQ”fQ’ePdPcPŠbP‡`O…_O‚]O~[NzZNvWNrUMoTMmSMlRMiQLeOLJAIJ(h>!]KKfQOgQN_LKD>I\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À™iQ°tS¸yT¼{UÂYÎŒeïˆô´Õ—u¶|\ Z'™LˆD
|>’eP¦oR¨qS¦oR¡mRšjQ‘eP„^OhPL\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀWHJ\KKaMLeOLhPLjQLlRMnSMpTMqUMtVMwXNzZN}[N€]Oƒ^O†_Oˆ`OŠbPcPdP‘eP“fQ•gQ—hQ™iQ›jRkRŸmS¢nT¤qV¨sX¬w[±{_¶€c½†hÄŒnË’tÒ™zØŸ€Þ¥…㩉çꯎꯎê®ç«Šä§†ß£Ûž|Õ˜vГpËŽkljfÃ…bÀ‚_½\»}Yº{X¸zW¸yV·xU·xU·xT¶xT¶xT¶xU¶xU·xU·xU·yV·yV·zW¸zX¸{Y¹|Y¹|Z¹}[¹}[¹}\¹}\¸}\·}\¶|\µ{[³zZ²yZ°wY®vX¬tWªsV¨rU¦pT¤oS£nS¡mRŸlRžkRœjQšiQ˜hQ–gQ”fQ’ePdPŽcP‹bPˆ`O…_O‚^O\N{ZNwXNsVMoTMnSMlRMiQLfOLJ(V.]KKePNkUQcNLQEJ\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À‚]O¡mR©qS¬rS°tS³vTµwT·xUº{WĆbÒ“qךxÊo +K«rS´vT¶wT´vT²uT®sSªqS¤nRkQ•gQˆ`OuWNY,\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀNCJYIK^KKbNLfOLhQLkRLmSMoTMpUMrUMuWMxXN{ZN~[N]O„^O†_O‰aO‹bPcPdP‘eP“fQ•gQ—hQ™iQ›jRkRŸmS¢oT¥qV¨tXw[±|_·d½†iÄŒnË“tÒ™zØŸ€Þ¥…㩉笌鮎ꮎéŒæª‰ã§…ߢ€Ú{Õ—uÏ’pËjƈfÂ…b¿^½\»|Y¹{X¸zV·yV·xU·xU¶xT¶xT¶xT¶xU¶xU¶xU¶xU·yV·yV·yW¸zW¸{X¸{Y¸|Z¹|Z¹|[¹}[¸}\¸}\·|\¶|[µ{[³zZ±xY°wX®vX¬tWªsV¨rU¦pT¥oS£nS¡mRŸlRžkRœjQšjQ˜iQ—hQ”gQ’fPdPŽcP‹bP‰aO†_Oƒ^O€\O|ZNxXNtVMoTMnSMlRMjQLgPLzG#\JKcOMoXUgPMZIK\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À’fP”gQ•gQ—hQ™iQkQ lR¤nR§pRªqS¬sS¯tS:"r<zYNsS¹yT¾|UÁ~WÆ„^ËŠeË‹gƈe¾‚aµz[tV¦pS¢mRkQ–gQŠbPzYNkRL\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀRFJZJK`LKcNLfPLiQLkRMmSMoTMqUMrVMvWNyYN|ZN\N]O„^O‡`O‰aO‹bPcPdP’eP”fQ–gQ—hQ™iQ›jRlR mS¢oU¥qV©tYx\²|`¸d¾‡iÅoË“uÒ™{ÙŸ€Þ¥…㩉笌é®é®è¬‹å©ˆâ¦„Þ¡ÙœzÔ—tÏ‘oÊŒjƈe„a¿^½~[»|Y¹{X¸zV·yV·xU¶xU¶xT¶xT¶xT¶xT¶xU¶xU¶xU¶xV·yV·yW·zW·zX¸{Y¸{Y¸|Z¸|Z¸|[¸|[·|[·|[¶{[´z[³yZ±xY°wX®vW¬tWªsV¨rU¦pT¥oS£nS¡mRŸlRžkRœkRšjQ™iQ—hQ•gQ“fP‘ePŽdPŒbP‰aP†`Oƒ^O€]O}[NyYNuWNqUMnSMlSMkRLhPLcNLbNLpYVlUP`LK>;H\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À›jQ‡`O{ZN©^'¨^'`(·e)½h)Ãk*Êo+±b(£nRºyTÃ~UÇXÒdãŸwò°‰ñ°‹è©…ÝŸ}Ô˜vÈm¾„eµ}_®x[°y\®x[«tW§qT¡mRœjQ–gQ‹bP}[NlRM\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀVGJ\JKaMKdNLgPLjQLlRMnSMpTMqUMsVMvXNzYN|[N\O‚]O…_O‡`O‰aPŒbPŽcPdP’eP”fQ–gQ˜hQšiQœjRžlS mS£oU¦rW©uY®x\³|`¸d¾‡jÅoÌ“uÒš{Ù €Þ¥…㩉欋èèŒç«Šå©‡á¥ƒÝ ~Ø›yÓ–tΑoÊŒjňe„a¿^¼~[º|Y¹{W¸zV·yV·xU¶xU¶xT¶xT¶xT¶xT¶xU¶xU¶xU¶xU¶xV·yV·yW·zX·zX¸{Y¸{Z¸{Z·|Z·|[·|[¶{[µ{[´zZ³yZ±xY¯wX®uW¬tVªsV¨rU¦pT¥oS£nS¡mR lRžkRœkR›jQ™iQ—hQ•gQ“fQ‘ePdPŒcPŠaP‡`O„^O]O~[NzYNvWNrUMnSMmSMkRLiQLeOLoXUu]XdOLKBI\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À:9H\N–hQ¸}\¯uUsT¯tT¯tS¨qS¤nR£nR¢nRŸlR›jQšiQ˜hQ—hQ–gQ”fQ’eP‘eP—hQœkR mS¥pUªtX«uY¨sW¦qU mS›jQ•gQƒB’S%jQL\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀLBIXHK^KKbMLeOLhPLjRLlSMnSMpTMqUMtVMwXNzYN}[N€\O‚^O…_O‡`OŠaPŒbPŽcPeP’fP”fQ–gQ˜hQšiRœkRžlS nT£pU¦rWªuY®y]³}`¹‚e¿ˆjÅŽpÌ”vÓš{Ù Þ¤…⨉櫋笌笋櫊䨆ंܟ~ךxÒ•sÎnÉŒiŇeÁ„a¾€^¼~[º|Y¹{W¸yV·yV·xU¶xU¶xT¶wT¶wT¶wT¶xT¶xU¶xU¶xU¶xV¶yV¶yW·zW·zX·zY·{Y·{Z·{Z·{Z¶{Z¶{ZµzZ³yZ²yY±xY¯vXuW¬tVªsU¨rU¦pT¥oS£nS¡mR lRžlRkR›jQ™iQ—hQ•gQ“fQ‘ePdPcPŠaP‡`O…_O‚]O\N{ZNwXNsVMnSMmSMkRMiQLfOL_LKhQMUGJ\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À (6BFP>=DKHMqjk€trwf`~kc„ndŠqesete¯Ž{w`¡v[\N†_OcP“fP˜iQœjRŸlS£oT¦qV¥qV£oTžlR™iQº^‡`OQ%hPL\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀQEJZIK_LKcNLfOLiQLkRLmSMoTMpUMrUMuWMxXN{ZN~[N€]Oƒ^O…_Oˆ`OŠaPŒcPŽdP‘eP“fP”gQ–hQ˜iQšjRœkRžlS¡nT£pU¦rWªuZ®y]³}a¹‚e¿ˆkÆŽpÌ”vÓš{ÙŸ€Þ¤…⨈媊櫋櫊婈⦅ߣ۞}ÖšxÑ•rÍmÈ‹ićdÁƒa¾€]¼~[º|Y¹zW¸yV·yU¶xU¶xU¶wT¶wT¶wT¶wT¶wT¶xU¶xU¶xU¶xU¶xV¶yV¶yW¶zX·zX·zY¶zY¶{Y¶{Z¶{ZµzZ´zZ³yY²xY°wX¯vXuW«tVªsU¨rU¦pT¥oS£nS¡mS mRžlRkR›jQ™iQ˜hQ–gQ”fQ‘ePdPcP‹bPˆ`O…_O‚]O\O|ZNxXNtVMoTMmSMlRMjQLgPLbML[JK\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À%5 (6$/79CEEKjgkrc_›…{‘uf±{Ÿw_ºq]Oˆ`OŽcP”fQ˜hQ›jRžlR¡nT¢oT¡nTkR˜hQŽdP¦]'ŽQ%\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\À\ÀUGJ[JK`MKdNLgPLiQLkRMmSMoTMqUMrUMuWNxXN{ZN~[N]O +
&3#.$-% .% .& /&!,#,#@70A71XNHXNHWNHWNHZRLYQLYQLXQLWQLWPLUOLSNLQMKOLJMJJ0//.-.,,-&(+"(!' 15;6CT37=MMMKMP^ad_enY`hNZlNZlU\dV\eŠ‘™Š™Š™–Ÿ–Ÿ–ž•ž“œ—¦Œ’›ƒ¡DQbDQbDQbDQbDQbMUc¤ƒ‘ylŸ‡|€oiKo¡Š¯áŠ¯áŠ¯áŠ¯áŠ¯áŠ¯áŠ¯á‹¯á‹¯á‹¯á‹¯á‹¯á‹¯á‹¯á‹¯á‹¯áKo¢Ko¢Ko¢Ko¢Ko¢Ko¢Ko¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢Kp¢‹¯â‹¯â‹¯â‹¯âLp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢Lp¢„¨Ú„¨Ú„¨Ú„¨Ú„¨Ú„¨Û„¨Û„¨Û„¨Û„©Û„©Û„©Û„©Û„©Û„©Û…©Û…©Û…©Û…©Û…©Û…©ÛGkžGkžGkžGkžGkžGkžGkžGkžGkž…©Û…©Ü…©Ü…©Ü…©Ü…©Ü…©Ü…ªÜ…ªÜ…ªÜ…ªÜ…ªÜ…ªÜ†ªÜ†ªÜ†ªÜ†ªÜ†ªÜHlžHlžHlžHlžHlžHlžHlžHlžHlžHlžHlžHlžHlž'K}'K}'K}'K}'K}'K}'K}'K}'K}HO\=J[=J[=J[ -> ,> ,>(.7#)2#)2(.7(.7(.7#)2(.7(.7(/7(/7)/8/28114H7,99@.05&,5$&)$$$######"""(((8888888888888884"nO9„gXˆjZE/ (-"
diff --git a/library/demos/items.tcl b/library/demos/items.tcl new file mode 100644 index 0000000..83e6033 --- /dev/null +++ b/library/demos/items.tcl @@ -0,0 +1,285 @@ +# items.tcl -- +# +# This demonstration script creates a canvas that displays the +# canvas item types. +# +# SCCS: @(#) items.tcl 1.16 97/03/02 16:25:05 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .items +catch {destroy $w} +toplevel $w +wm title $w "Canvas Item Demonstration" +wm iconname $w "Items" +positionWindow $w +set c $w.frame.c + +label $w.msg -font $font -wraplength 5i -justify left -text "This window contains a canvas widget with examples of the various kinds of items supported by canvases. The following operations are supported:\n Button-1 drag:\tmoves item under pointer.\n Button-2 drag:\trepositions view.\n Button-3 drag:\tstrokes out area.\n Ctrl+f:\t\tprints items under area." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.frame +pack $w.frame -side top -fill both -expand yes + +canvas $c -scrollregion {0c 0c 30c 24c} -width 15c -height 10c \ + -relief sunken -borderwidth 2 \ + -xscrollcommand "$w.frame.hscroll set" \ + -yscrollcommand "$w.frame.vscroll set" +scrollbar $w.frame.vscroll -command "$c yview" +scrollbar $w.frame.hscroll -orient horiz -command "$c xview" + +grid $c -in $w.frame \ + -row 0 -column 0 -rowspan 1 -columnspan 1 -sticky news +grid $w.frame.vscroll \ + -row 0 -column 1 -rowspan 1 -columnspan 1 -sticky news +grid $w.frame.hscroll \ + -row 1 -column 0 -rowspan 1 -columnspan 1 -sticky news +grid rowconfig $w.frame 0 -weight 1 -minsize 0 +grid columnconfig $w.frame 0 -weight 1 -minsize 0 + +# Display a 3x3 rectangular grid. + +$c create rect 0c 0c 30c 24c -width 2 +$c create line 0c 8c 30c 8c -width 2 +$c create line 0c 16c 30c 16c -width 2 +$c create line 10c 0c 10c 24c -width 2 +$c create line 20c 0c 20c 24c -width 2 + +set font1 {Helvetica 12} +set font2 {Helvetica 24 bold} +if {[winfo depth $c] > 1} { + set blue DeepSkyBlue3 + set red red + set bisque bisque3 + set green SeaGreen3 +} else { + set blue black + set red black + set bisque black + set green black +} + +# Set up demos within each of the areas of the grid. + +$c create text 5c .2c -text Lines -anchor n +$c create line 1c 1c 3c 1c 1c 4c 3c 4c -width 2m -fill $blue \ + -cap butt -join miter -tags item +$c create line 4.67c 1c 4.67c 4c -arrow last -tags item +$c create line 6.33c 1c 6.33c 4c -arrow both -tags item +$c create line 5c 6c 9c 6c 9c 1c 8c 1c 8c 4.8c 8.8c 4.8c 8.8c 1.2c \ + 8.2c 1.2c 8.2c 4.6c 8.6c 4.6c 8.6c 1.4c 8.4c 1.4c 8.4c 4.4c \ + -width 3 -fill $red -tags item +$c create line 1c 5c 7c 5c 7c 7c 9c 7c -width .5c \ + -stipple @[file join $tk_library demos images gray25.bmp] \ + -arrow both -arrowshape {15 15 7} -tags item +$c create line 1c 7c 1.75c 5.8c 2.5c 7c 3.25c 5.8c 4c 7c -width .5c \ + -cap round -join round -tags item + +$c create text 15c .2c -text "Curves (smoothed lines)" -anchor n +$c create line 11c 4c 11.5c 1c 13.5c 1c 14c 4c -smooth on \ + -fill $blue -tags item +$c create line 15.5c 1c 19.5c 1.5c 15.5c 4.5c 19.5c 4c -smooth on \ + -arrow both -width 3 -tags item +$c create line 12c 6c 13.5c 4.5c 16.5c 7.5c 18c 6c \ + 16.5c 4.5c 13.5c 7.5c 12c 6c -smooth on -width 3m -cap round \ + -stipple @[file join $tk_library demos images gray25.bmp] \ + -fill $red -tags item + +$c create text 25c .2c -text Polygons -anchor n +$c create polygon 21c 1.0c 22.5c 1.75c 24c 1.0c 23.25c 2.5c \ + 24c 4.0c 22.5c 3.25c 21c 4.0c 21.75c 2.5c -fill $green \ + -outline black -width 4 -tags item +$c create polygon 25c 4c 25c 4c 25c 1c 26c 1c 27c 4c 28c 1c \ + 29c 1c 29c 4c 29c 4c -fill $red -smooth on -tags item +$c create polygon 22c 4.5c 25c 4.5c 25c 6.75c 28c 6.75c \ + 28c 5.25c 24c 5.25c 24c 6.0c 26c 6c 26c 7.5c 22c 7.5c \ + -stipple @[file join $tk_library demos images gray25.bmp] \ + -outline black -tags item + +$c create text 5c 8.2c -text Rectangles -anchor n +$c create rectangle 1c 9.5c 4c 12.5c -outline $red -width 3m -tags item +$c create rectangle 0.5c 13.5c 4.5c 15.5c -fill $green -tags item +$c create rectangle 6c 10c 9c 15c -outline {} \ + -stipple @[file join $tk_library demos images gray25.bmp] \ + -fill $blue -tags item + +$c create text 15c 8.2c -text Ovals -anchor n +$c create oval 11c 9.5c 14c 12.5c -outline $red -width 3m -tags item +$c create oval 10.5c 13.5c 14.5c 15.5c -fill $green -tags item +$c create oval 16c 10c 19c 15c -outline {} \ + -stipple @[file join $tk_library demos images gray25.bmp] \ + -fill $blue -tags item + +$c create text 25c 8.2c -text Text -anchor n +$c create rectangle 22.4c 8.9c 22.6c 9.1c +$c create text 22.5c 9c -anchor n -font $font1 -width 4c \ + -text "A short string of text, word-wrapped, justified left, and anchored north (at the top). The rectangles show the anchor points for each piece of text." -tags item +$c create rectangle 25.4c 10.9c 25.6c 11.1c +$c create text 25.5c 11c -anchor w -font $font1 -fill $blue \ + -text "Several lines,\n each centered\nindividually,\nand all anchored\nat the left edge." \ + -justify center -tags item +$c create rectangle 24.9c 13.9c 25.1c 14.1c +$c create text 25c 14c -font $font2 -anchor c -fill $red -stipple gray50 \ + -text "Stippled characters" -tags item + +$c create text 5c 16.2c -text Arcs -anchor n +$c create arc 0.5c 17c 7c 20c -fill $green -outline black \ + -start 45 -extent 270 -style pieslice -tags item +$c create arc 6.5c 17c 9.5c 20c -width 4m -style arc \ + -outline $blue -start -135 -extent 270 -tags item \ + -outlinestipple @[file join $tk_library demos images gray25.bmp] +$c create arc 0.5c 20c 9.5c 24c -width 4m -style pieslice \ + -fill {} -outline $red -start 225 -extent -90 -tags item +$c create arc 5.5c 20.5c 9.5c 23.5c -width 4m -style chord \ + -fill $blue -outline {} -start 45 -extent 270 -tags item + +$c create text 15c 16.2c -text Bitmaps -anchor n +$c create bitmap 13c 20c -tags item \ + -bitmap @[file join $tk_library demos images face.bmp] +$c create bitmap 17c 18.5c -tags item \ + -bitmap @[file join $tk_library demos images noletter.bmp] +$c create bitmap 17c 21.5c -tags item \ + -bitmap @[file join $tk_library demos images letters.bmp] + +$c create text 25c 16.2c -text Windows -anchor n +button $c.button -text "Press Me" -command "butPress $c $red" +$c create window 21c 18c -window $c.button -anchor nw -tags item +entry $c.entry -width 20 -relief sunken +$c.entry insert end "Edit this text" +$c create window 21c 21c -window $c.entry -anchor nw -tags item +scale $c.scale -from 0 -to 100 -length 6c -sliderlength .4c \ + -width .5c -tickinterval 0 +$c create window 28.5c 17.5c -window $c.scale -anchor n -tags item +$c create text 21c 17.9c -text Button: -anchor sw +$c create text 21c 20.9c -text Entry: -anchor sw +$c create text 28.5c 17.4c -text Scale: -anchor s + +# Set up event bindings for canvas: + +$c bind item <Any-Enter> "itemEnter $c" +$c bind item <Any-Leave> "itemLeave $c" +bind $c <2> "$c scan mark %x %y" +bind $c <B2-Motion> "$c scan dragto %x %y" +bind $c <3> "itemMark $c %x %y" +bind $c <B3-Motion> "itemStroke $c %x %y" +bind $c <Control-f> "itemsUnderArea $c" +bind $c <1> "itemStartDrag $c %x %y" +bind $c <B1-Motion> "itemDrag $c %x %y" + +# Utility procedures for highlighting the item under the pointer: + +proc itemEnter {c} { + global restoreCmd + + if {[winfo depth $c] == 1} { + set restoreCmd {} + return + } + set type [$c type current] + if {$type == "window"} { + set restoreCmd {} + return + } + if {$type == "bitmap"} { + set bg [lindex [$c itemconf current -background] 4] + set restoreCmd [list $c itemconfig current -background $bg] + $c itemconfig current -background SteelBlue2 + return + } + set fill [lindex [$c itemconfig current -fill] 4] + if {(($type == "rectangle") || ($type == "oval") || ($type == "arc")) + && ($fill == "")} { + set outline [lindex [$c itemconfig current -outline] 4] + set restoreCmd "$c itemconfig current -outline $outline" + $c itemconfig current -outline SteelBlue2 + } else { + set restoreCmd "$c itemconfig current -fill $fill" + $c itemconfig current -fill SteelBlue2 + } +} + +proc itemLeave {c} { + global restoreCmd + + eval $restoreCmd +} + +# Utility procedures for stroking out a rectangle and printing what's +# underneath the rectangle's area. + +proc itemMark {c x y} { + global areaX1 areaY1 + set areaX1 [$c canvasx $x] + set areaY1 [$c canvasy $y] + $c delete area +} + +proc itemStroke {c x y} { + global areaX1 areaY1 areaX2 areaY2 + set x [$c canvasx $x] + set y [$c canvasy $y] + if {($areaX1 != $x) && ($areaY1 != $y)} { + $c delete area + $c addtag area withtag [$c create rect $areaX1 $areaY1 $x $y \ + -outline black] + set areaX2 $x + set areaY2 $y + } +} + +proc itemsUnderArea {c} { + global areaX1 areaY1 areaX2 areaY2 + set area [$c find withtag area] + set items "" + foreach i [$c find enclosed $areaX1 $areaY1 $areaX2 $areaY2] { + if {[lsearch [$c gettags $i] item] != -1} { + lappend items $i + } + } + puts stdout "Items enclosed by area: $items" + set items "" + foreach i [$c find overlapping $areaX1 $areaY1 $areaX2 $areaY2] { + if {[lsearch [$c gettags $i] item] != -1} { + lappend items $i + } + } + puts stdout "Items overlapping area: $items" +} + +set areaX1 0 +set areaY1 0 +set areaX2 0 +set areaY2 0 + +# Utility procedures to support dragging of items. + +proc itemStartDrag {c x y} { + global lastX lastY + set lastX [$c canvasx $x] + set lastY [$c canvasy $y] +} + +proc itemDrag {c x y} { + global lastX lastY + set x [$c canvasx $x] + set y [$c canvasy $y] + $c move current [expr $x-$lastX] [expr $y-$lastY] + set lastX $x + set lastY $y +} + +# Procedure that's invoked when the button embedded in the canvas +# is invoked. + +proc butPress {w color} { + set i [$w create text 25c 18.1c -text "Ouch!!" -fill $color -anchor n] + after 500 "$w delete $i" +} diff --git a/library/demos/ixset b/library/demos/ixset new file mode 100644 index 0000000..dcde75d --- /dev/null +++ b/library/demos/ixset @@ -0,0 +1,312 @@ +#!/bin/sh +# the next line restarts using wish \ +exec wish "$0" "$@" + +# ixset -- +# A nice interface to "xset" to change X server settings +# +# History : +# 91/11/23 : pda@masi.ibp.fr, jt@ratp.fr : design +# 92/08/01 : pda@masi.ibp.fr : cleaning +# +# SCCS: @(#) ixset 1.7 96/02/16 10:49:19 + +# +# Button actions +# + +proc quit {} { + destroy . +} + +proc ok {} { + writesettings + quit +} + +proc cancel {} { + readsettings + dispsettings +} + +# apply is just "writesettings" + + +# +# Read current settings +# + +proc readsettings {} { + global kbdrep ; set kbdrep "on" + global kbdcli ; set kbdcli 0 + global bellvol ; set bellvol 100 + global bellpit ; set bellpit 440 + global belldur ; set belldur 100 + global mouseacc ; set mouseacc "3/1" + global mousethr ; set mousethr 4 + global screenbla ; set screenbla "blank" + global screentim ; set screentim 600 + global screencyc ; set screencyc 600 + + set xfd [open "|xset q" r] + while {[gets $xfd line] > -1} { + set kw [lindex $line 0] + + case $kw in { + {auto} + { + set rpt [lindex $line 1] + if {[expr "{$rpt} == {repeat:}"]} then { + set kbdrep [lindex $line 2] + set kbdcli [lindex $line 6] + } + } + {bell} + { + set bellvol [lindex $line 2] + set bellpit [lindex $line 5] + set belldur [lindex $line 8] + } + {acceleration:} + { + set mouseacc [lindex $line 1] + set mousethr [lindex $line 3] + } + {prefer} + { + set bla [lindex $line 2] + set screenbla [expr "{$bla} == {yes} ? {blank} : {noblank}"] + } + {timeout:} + { + set screentim [lindex $line 1] + set screencyc [lindex $line 3] + } + } + } + close $xfd + + # puts stdout [format "Key REPEAT = %s\n" $kbdrep] + # puts stdout [format "Key CLICK = %s\n" $kbdcli] + # puts stdout [format "Bell VOLUME = %s\n" $bellvol] + # puts stdout [format "Bell PITCH = %s\n" $bellpit] + # puts stdout [format "Bell DURATION = %s\n" $belldur] + # puts stdout [format "Mouse ACCELERATION = %s\n" $mouseacc] + # puts stdout [format "Mouse THRESHOLD = %s\n" $mousethr] + # puts stdout [format "Screen BLANCK = %s\n" $screenbla] + # puts stdout [format "Screen TIMEOUT = %s\n" $screentim] + # puts stdout [format "Screen CYCLE = %s\n" $screencyc] +} + + +# +# Write settings into the X server +# + +proc writesettings {} { + global kbdrep kbdcli bellvol bellpit belldur + global mouseacc mousethr screenbla screentim screencyc + + set bellvol [.bell.vol get] + set bellpit [.bell.val.pit.entry get] + set belldur [.bell.val.dur.entry get] + + if {[expr "{$kbdrep} == {on}"]} then { + set kbdcli [.kbd.val.cli get] + } else { + set kbdcli "off" + } + + set mouseacc [.mouse.hor.acc.entry get] + set mousethr [.mouse.hor.thr.entry get] + + set screentim [.screen.val.le.tim.entry get] + set screencyc [.screen.val.le.cyc.entry get] + + exec xset \ + b $bellvol $bellpit $belldur \ + c $kbdcli \ + r $kbdrep \ + m $mouseacc $mousethr \ + s $screentim $screencyc \ + s $screenbla +} + + +# +# Sends all settings to the window +# + +proc dispsettings {} { + global kbdrep kbdcli bellvol bellpit belldur + global mouseacc mousethr screenbla screentim screencyc + + .bell.vol set $bellvol + .bell.val.pit.entry delete 0 end + .bell.val.pit.entry insert 0 $bellpit + .bell.val.dur.entry delete 0 end + .bell.val.dur.entry insert 0 $belldur + + .kbd.val.onoff [expr "{$kbdrep} == {on} ? {select} : {deselect}"] + .kbd.val.cli set $kbdcli + + .mouse.hor.acc.entry delete 0 end + .mouse.hor.acc.entry insert 0 $mouseacc + .mouse.hor.thr.entry delete 0 end + .mouse.hor.thr.entry insert 0 $mousethr + + .screen.val.rb.blank [expr "{$screenbla}=={blank} ? {select} : {deselect}"] + .screen.val.rb.pat [expr "{$screenbla}!={blank} ? {select} : {deselect}"] + .screen.val.le.tim.entry delete 0 end + .screen.val.le.tim.entry insert 0 $screentim + .screen.val.le.cyc.entry delete 0 end + .screen.val.le.cyc.entry insert 0 $screencyc +} + + +# +# Create all windows, and pack them +# + +proc labelentry {path text length} { + frame $path + label $path.label -text $text + entry $path.entry -width $length -relief sunken + pack $path.label -side left -expand y + pack $path.entry -side right -expand y +} + +proc createwindows {} { + # + # Buttons + # + + frame .buttons + button .buttons.ok -command "ok" -text "Ok" + button .buttons.apply -command "writesettings" -text "Apply" + button .buttons.cancel -command "cancel" -text "Cancel" + button .buttons.quit -command "quit" -text "Quit" + + pack .buttons.ok .buttons.apply .buttons.cancel .buttons.quit \ + -side left -expand yes -pady 5 + + # + # Bell settings + # + + frame .bell -relief raised -borderwidth 2 + label .bell.label -text "Bell Settings" + scale .bell.vol \ + -from 0 -to 100 -length 200 -tickinterval 20 \ + -label "Volume (%)" -orient horizontal + + frame .bell.val + labelentry .bell.val.pit "Pitch (Hz)" 6 + labelentry .bell.val.dur "Duration (ms)" 6 + pack .bell.val.pit -side left -padx 5 + pack .bell.val.dur -side right -padx 5 + pack .bell.label .bell.vol .bell.val -side top -expand yes + + # + # Keyboard settings + # + + frame .kbd -relief raised -borderwidth 2 + + label .kbd.label -text "Keyboard Repeat Settings" + + frame .kbd.val + checkbutton .kbd.val.onoff \ + -text "On" \ + -onvalue "on" -offvalue "off" -variable kbdrep \ + -relief flat + scale .kbd.val.cli \ + -from 0 -to 100 -length 200 -tickinterval 20 \ + -label "Click Volume (%)" -orient horizontal + pack .kbd.val.onoff -side left -expand yes -fill both + pack .kbd.val.cli -side left -expand yes + + pack .kbd.label -side top -expand yes + pack .kbd.val -side top -expand yes -pady 2 -fill x + + # + # Mouse settings + # + + frame .mouse -relief raised -borderwidth 2 + + label .mouse.label -text "Mouse Settings" + frame .mouse.hor + labelentry .mouse.hor.acc "Acceleration" 3 + labelentry .mouse.hor.thr "Threshold (pixels)" 3 + + pack .mouse.hor.acc -side left + pack .mouse.hor.thr -side right + + pack .mouse.label -side top + pack .mouse.hor -side top -expand yes + + # + # Screen Saver settings + # + + frame .screen -relief raised -borderwidth 2 + + label .screen.label -text "Screen-saver Settings" + frame .screen.val + + frame .screen.val.rb + radiobutton .screen.val.rb.blank \ + -variable screenblank -text "Blank" -relief flat \ + -value "blank" -variable screenbla + radiobutton .screen.val.rb.pat \ + -variable screenblank -text "Pattern" -relief flat \ + -value "noblank" -variable screenbla + pack .screen.val.rb.blank .screen.val.rb.pat -side top -pady 2 -anchor w + frame .screen.val.le + labelentry .screen.val.le.tim "Timeout (s)" 5 + labelentry .screen.val.le.cyc "Cycle (s)" 5 + pack .screen.val.le.tim .screen.val.le.cyc -side top -pady 2 -anchor e + + pack .screen.val.rb .screen.val.le -side left + + pack .screen.label -side top + pack .screen.val -side top -expand y + + # + # Main window + # + + pack .buttons -side top -fill both + pack .bell .kbd .mouse .screen -side top -fill both -ipady 5 -expand yes + + # + # Let the user resize our window + # + wm minsize . 10 10 +} + +############################################################################## +# Main program + +# +# Listen what "xset" tells us... +# + +readsettings + +# +# Create all windows +# + +createwindows + +# +# Write xset parameters +# + +dispsettings + +# +# Now, wait for user actions... +# diff --git a/library/demos/label.tcl b/library/demos/label.tcl new file mode 100644 index 0000000..2e0b027 --- /dev/null +++ b/library/demos/label.tcl @@ -0,0 +1,40 @@ +# label.tcl -- +# +# This demonstration script creates a toplevel window containing +# several label widgets. +# +# SCCS: @(#) label.tcl 1.7 97/03/02 16:25:27 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .label +catch {destroy $w} +toplevel $w +wm title $w "Label Demonstration" +wm iconname $w "label" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "Five labels are displayed below: three textual ones on the left, and a bitmap label and a text label on the right. Labels are pretty boring because you can't do anything with them." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.left +frame $w.right +pack $w.left $w.right -side left -expand yes -padx 10 -pady 10 -fill both + +label $w.left.l1 -text "First label" +label $w.left.l2 -text "Second label, raised" -relief raised +label $w.left.l3 -text "Third label, sunken" -relief sunken +pack $w.left.l1 $w.left.l2 $w.left.l3 -side top -expand yes -pady 2 -anchor w + +label $w.right.bitmap -borderwidth 2 -relief sunken \ + -bitmap @[file join $tk_library demos images face.bmp] +label $w.right.caption -text "Tcl/Tk Proprietor" +pack $w.right.bitmap $w.right.caption -side top diff --git a/library/demos/menu.tcl b/library/demos/menu.tcl new file mode 100644 index 0000000..78ec625 --- /dev/null +++ b/library/demos/menu.tcl @@ -0,0 +1,152 @@ +# menu.tcl -- +# +# This demonstration script creates a window with a bunch of menus +# and cascaded menus using menubars. +# +# SCCS: @(#) menu.tcl 1.17 97/06/26 15:45:04 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .menu +catch {destroy $w} +toplevel $w +wm title $w "Menu Demonstration" +wm iconname $w "menu" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left +if {$tcl_platform(platform) == "macintosh"} { + $w.msg configure -text "This window contains a menubar with cascaded menus. You can invoke entries with an accelerator by typing Command+x, where \"x\" is the character next to the command key symbol. The rightmost menu can be torn off into a palette by dragging outside of its bounds and releasing the mouse." +} else { + $w.msg configure -text "This window contains a menubar with cascaded menus. You can post a menu from the keyboard by typing Alt+x, where \"x\" is the character underlined on the menu. You can then traverse among the menus using the arrow keys. When a menu is posted, you can invoke the current entry by typing space, or you can invoke any entry by typing its underlined character. If a menu entry has an accelerator, you can invoke the entry without posting the menu just by typing the accelerator. The rightmost menu can be torn off into a palette by selecting the first item in the menu." +} +pack $w.msg -side top + +set menustatus " " +frame $w.statusBar +label $w.statusBar.label -textvariable menustatus -relief sunken -bd 1 -font "Helvetica 10" -anchor w +pack $w.statusBar.label -side left -padx 2 -expand yes -fill both +pack $w.statusBar -side bottom -fill x -pady 2 + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +menu $w.menu -tearoff 0 + +set m $w.menu.file +menu $m -tearoff 0 +$w.menu add cascade -label "File" -menu $m -underline 0 +$m add command -label "Open..." -command {error "this is just a demo: no action has been defined for the \"Open...\" entry"} +$m add command -label "New" -command {error "this is just a demo: no action has been defined for the \"New\" entry"} +$m add command -label "Save" -command {error "this is just a demo: no action has been defined for the \"Save\" entry"} +$m add command -label "Save As..." -command {error "this is just a demo: no action has been defined for the \"Save As...\" entry"} +$m add separator +$m add command -label "Print Setup..." -command {error "this is just a demo: no action has been defined for the \"Print Setup...\" entry"} +$m add command -label "Print..." -command {error "this is just a demo: no action has been defined for the \"Print...\" entry"} +$m add separator +$m add command -label "Dismiss Menus Demo" -command "destroy $w" + +set m $w.menu.basic +$w.menu add cascade -label "Basic" -menu $m -underline 0 +menu $m -tearoff 0 +$m add command -label "Long entry that does nothing" +if {$tcl_platform(platform) == "macintosh"} { + set modifier Command +} elseif {$tcl_platform(platform) == "windows"} { + set modifier Control +} else { + set modifier Meta +} +foreach i {A B C D E F} { + $m add command -label "Print letter \"$i\"" -underline 14 \ + -accelerator Meta+$i -command "puts $i" -accelerator $modifier+$i + bind $w <$modifier-[string tolower $i]> "puts $i" +} + +set m $w.menu.cascade +$w.menu add cascade -label "Cascades" -menu $m -underline 0 +menu $m -tearoff 0 +$m add command -label "Print hello" \ + -command {puts stdout "Hello"} -accelerator $modifier+H -underline 6 +bind $w <$modifier-h> {puts stdout "Hello"} +$m add command -label "Print goodbye" -command {\ + puts stdout "Goodbye"} -accelerator $modifier+G -underline 6 +bind $w <$modifier-g> {puts stdout "Goodbye"} +$m add cascade -label "Check buttons" \ + -menu $w.menu.cascade.check -underline 0 +$m add cascade -label "Radio buttons" \ + -menu $w.menu.cascade.radio -underline 0 + +set m $w.menu.cascade.check +menu $m -tearoff 0 +$m add check -label "Oil checked" -variable oil +$m add check -label "Transmission checked" -variable trans +$m add check -label "Brakes checked" -variable brakes +$m add check -label "Lights checked" -variable lights +$m add separator +$m add command -label "Show current values" \ + -command "showVars $w.menu.cascade.dialog oil trans brakes lights" +$m invoke 1 +$m invoke 3 + +set m $w.menu.cascade.radio +menu $m -tearoff 0 +$m add radio -label "10 point" -variable pointSize -value 10 +$m add radio -label "14 point" -variable pointSize -value 14 +$m add radio -label "18 point" -variable pointSize -value 18 +$m add radio -label "24 point" -variable pointSize -value 24 +$m add radio -label "32 point" -variable pointSize -value 32 +$m add sep +$m add radio -label "Roman" -variable style -value roman +$m add radio -label "Bold" -variable style -value bold +$m add radio -label "Italic" -variable style -value italic +$m add sep +$m add command -label "Show current values" \ + -command "showVars $w.menu.cascade.dialog pointSize style" +$m invoke 1 +$m invoke 7 + +set m $w.menu.icon +$w.menu add cascade -label "Icons" -menu $m -underline 0 +menu $m -tearoff 0 +$m add command \ + -bitmap @[file join $tk_library demos images pattern.bmp] \ + -hidemargin 1 \ + -command { + tk_dialog .pattern {Bitmap Menu Entry} {The menu entry you invoked displays a bitmap rather than a text string. Other than this, it is just like any other menu entry.} {} 0 OK +} +foreach i {info questhead error} { + $m add command -bitmap $i -command "puts {You invoked the $i bitmap}" -hidemargin 1 +} +$m entryconfigure 2 -columnbreak 1 + +set m $w.menu.more +$w.menu add cascade -label "More" -menu $m -underline 0 +menu $m -tearoff 0 +foreach i {{An entry} {Another entry} {Does nothing} {Does almost nothing} {Make life meaningful}} { + $m add command -label $i -command [list puts "You invoked \"$i\""] +} + +set m $w.menu.colors +$w.menu add cascade -label "Colors" -menu $m -underline 1 +menu $m +foreach i {red orange yellow green blue} { + $m add command -label $i -background $i \ + -command [list puts "You invoked \"$i\""] +} + +$w configure -menu $w.menu + +bind Menu <<MenuSelect>> { + global $menustatus + if {[catch {%W entrycget active -label} label]} { + set label " " + } + set menustatus $label + update idletasks +} diff --git a/library/demos/menubu.tcl b/library/demos/menubu.tcl new file mode 100644 index 0000000..2a76e30 --- /dev/null +++ b/library/demos/menubu.tcl @@ -0,0 +1,93 @@ +# menubutton.tcl -- +# +# This demonstration script creates a window with a bunch of menus +# and cascaded menus using menubuttons. +# +# # SCCS: @(#) menubu.tcl 1.9 97/06/19 18:11:06 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .menubutton +catch {destroy $w} +toplevel $w +wm title $w "Menu Button Demonstration" +wm iconname $w "menubutton" +positionWindow $w + + +frame $w.body +pack $w.body -expand 1 -fill both + +menubutton $w.body.below -text "Below" -underline 0 -direction below -menu $w.body.below.m -relief raised +menu $w.body.below.m -tearoff 0 +$w.body.below.m add command -label "Below menu: first item" -command "puts \"You have selected the first item from the Below menu.\"" +$w.body.below.m add command -label "Below menu: second item" -command "puts \"You have selected the second item from the Below menu.\"" +grid $w.body.below -row 0 -column 1 -sticky n +menubutton $w.body.right -text "Right" -underline 0 -direction right -menu $w.body.right.m -relief raised +menu $w.body.right.m -tearoff 0 +$w.body.right.m add command -label "Right menu: first item" -command "puts \"You have selected the first item from the Right menu.\"" +$w.body.right.m add command -label "Right menu: second item" -command "puts \"You have selected the second item from the Right menu.\"" +frame $w.body.center +menubutton $w.body.left -text "Left" -underline 0 -direction left -menu $w.body.left.m -relief raised +menu $w.body.left.m -tearoff 0 +$w.body.left.m add command -label "Left menu: first item" -command "puts \"You have selected the first item from the Left menu.\"" +$w.body.left.m add command -label "Left menu: second item" -command "puts \"You have selected the second item from the Left menu.\"" +grid $w.body.right -row 1 -column 0 -sticky w +grid $w.body.center -row 1 -column 1 -sticky news +grid $w.body.left -row 1 -column 2 -sticky e +menubutton $w.body.above -text "Above" -underline 0 -direction above -menu $w.body.above.m -relief raised +menu $w.body.above.m -tearoff 0 +$w.body.above.m add command -label "Above menu: first item" -command "puts \"You have selected the first item from the Above menu.\"" +$w.body.above.m add command -label "Above menu: second item" -command "puts \"You have selected the second item from the Above menu.\"" +grid $w.body.above -row 2 -column 1 -sticky s + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode .menubu" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +set body $w.body.center +label $body.label -wraplength 300 -font "Helvetica 14" -justify left -text "This is a demonstration of menubuttons. The \"Below\" menubutton pops its menu below the button; the \"Right\" button pops to the right, etc. There are two option menus directly below this text; one is just a standard menu and the other is a 16-color palette." +pack $body.label -side top -padx 25 -pady 25 +frame $body.buttons +pack $body.buttons -padx 25 -pady 25 +tk_optionMenu $body.buttons.options menubuttonoptions one two three +pack $body.buttons.options -side left -padx 25 -pady 25 +set m [tk_optionMenu $body.buttons.colors paletteColor Black red4 DarkGreen NavyBlue gray75 Red Green Blue gray50 Yellow Cyan Magenta White Brown DarkSeaGreen DarkViolet] +if {$tcl_platform(platform) == "macintosh"} { + set topBorderColor Black + set bottomBorderColor Black +} else { + set topBorderColor gray50 + set bottomBorderColor gray75 +} +for {set i 0} {$i <= [$m index last]} {incr i} { + set name [$m entrycget $i -label] + image create photo image_$name -height 16 -width 16 + image_$name put $topBorderColor -to 0 0 16 1 + image_$name put $topBorderColor -to 0 1 1 16 + image_$name put $bottomBorderColor -to 0 15 16 16 + image_$name put $bottomBorderColor -to 15 1 16 16 + image_$name put $name -to 1 1 15 15 + + image create photo image_${name}_s -height 16 -width 16 + image_${name}_s put Black -to 0 0 16 2 + image_${name}_s put Black -to 0 2 2 16 + image_${name}_s put Black -to 2 14 16 16 + image_${name}_s put Black -to 14 2 16 14 + image_${name}_s put $name -to 2 2 14 14 + + $m entryconfigure $i -image image_$name -selectimage image_${name}_s -hidemargin 1 +} +$m configure -tearoff 1 +foreach i {Black gray75 gray50 White} { + $m entryconfigure $i -columnbreak 1 +} + +pack $body.buttons.colors -side left -padx 25 -pady 25 + + + diff --git a/library/demos/msgbox.tcl b/library/demos/msgbox.tcl new file mode 100644 index 0000000..52b648f --- /dev/null +++ b/library/demos/msgbox.tcl @@ -0,0 +1,65 @@ +# msgbox.tcl -- +# +# This demonstration script creates message boxes of various type +# +# SCCS: @(#) msgbox.tcl 1.3 97/03/02 16:26:07 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .msgbox +catch {destroy $w} +toplevel $w +wm title $w "Message Box Demonstration" +wm iconname $w "messagebox" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "Choose the icon and type option of the message box. Then press the \"Message Box\" button to see the message box." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +button $w.buttons.vars -text "Message Box" \ + -command "showMessageBox $w" +pack $w.buttons.dismiss $w.buttons.code $w.buttons.vars -side left -expand 1 + +frame $w.left +frame $w.right +pack $w.left $w.right -side left -expand yes -fill y -pady .5c -padx .5c + +label $w.left.label -text "Icon" +frame $w.left.sep -relief ridge -bd 1 -height 2 +pack $w.left.label -side top +pack $w.left.sep -side top -fill x -expand no + +set msgboxIcon info +foreach i {error info question warning} { + radiobutton $w.left.b$i -text $i -variable msgboxIcon \ + -relief flat -value $i -width 16 -anchor w + pack $w.left.b$i -side top -pady 2 -anchor w -fill x +} + +label $w.right.label -text "Type" +frame $w.right.sep -relief ridge -bd 1 -height 2 +pack $w.right.label -side top +pack $w.right.sep -side top -fill x -expand no + +set msgboxType ok +foreach t {abortretryignore ok okcancel retrycancel yesno yesnocancel} { + radiobutton $w.right.$t -text $t -variable msgboxType \ + -relief flat -value $t -width 16 -anchor w + pack $w.right.$t -side top -pady 2 -anchor w -fill x +} + +proc showMessageBox {w} { + global msgboxIcon msgboxType + set button [tk_messageBox -icon $msgboxIcon -type $msgboxType \ + -title Message -parent $w\ + -message "This is a \"$msgboxType\" type messagebox with the \"$msgboxIcon\" icon"] + + tk_messageBox -icon info -message "You have selected \"$button\"" -type ok\ + -parent $w +} diff --git a/library/demos/plot.tcl b/library/demos/plot.tcl new file mode 100644 index 0000000..6067979 --- /dev/null +++ b/library/demos/plot.tcl @@ -0,0 +1,98 @@ +# plot.tcl -- +# +# This demonstration script creates a canvas widget showing a 2-D +# plot with data points that can be dragged with the mouse. +# +# SCCS: @(#) plot.tcl 1.5 97/03/02 16:26:19 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .plot +catch {destroy $w} +toplevel $w +wm title $w "Plot Demonstration" +wm iconname $w "Plot" +positionWindow $w +set c $w.c + +label $w.msg -font $font -wraplength 4i -justify left -text "This window displays a canvas widget containing a simple 2-dimensional plot. You can doctor the data by dragging any of the points with mouse button 1." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +canvas $c -relief raised -width 450 -height 300 +pack $w.c -side top -fill x + +set plotFont {Helvetica 18} + +$c create line 100 250 400 250 -width 2 +$c create line 100 250 100 50 -width 2 +$c create text 225 20 -text "A Simple Plot" -font $plotFont -fill brown + +for {set i 0} {$i <= 10} {incr i} { + set x [expr {100 + ($i*30)}] + $c create line $x 250 $x 245 -width 2 + $c create text $x 254 -text [expr 10*$i] -anchor n -font $plotFont +} +for {set i 0} {$i <= 5} {incr i} { + set y [expr {250 - ($i*40)}] + $c create line 100 $y 105 $y -width 2 + $c create text 96 $y -text [expr $i*50].0 -anchor e -font $plotFont +} + +foreach point {{12 56} {20 94} {33 98} {32 120} {61 180} + {75 160} {98 223}} { + set x [expr {100 + (3*[lindex $point 0])}] + set y [expr {250 - (4*[lindex $point 1])/5}] + set item [$c create oval [expr $x-6] [expr $y-6] \ + [expr $x+6] [expr $y+6] -width 1 -outline black \ + -fill SkyBlue2] + $c addtag point withtag $item +} + +$c bind point <Any-Enter> "$c itemconfig current -fill red" +$c bind point <Any-Leave> "$c itemconfig current -fill SkyBlue2" +$c bind point <1> "plotDown $c %x %y" +$c bind point <ButtonRelease-1> "$c dtag selected" +bind $c <B1-Motion> "plotMove $c %x %y" + +set plot(lastX) 0 +set plot(lastY) 0 + +# plotDown -- +# This procedure is invoked when the mouse is pressed over one of the +# data points. It sets up state to allow the point to be dragged. +# +# Arguments: +# w - The canvas window. +# x, y - The coordinates of the mouse press. + +proc plotDown {w x y} { + global plot + $w dtag selected + $w addtag selected withtag current + $w raise current + set plot(lastX) $x + set plot(lastY) $y +} + +# plotMove -- +# This procedure is invoked during mouse motion events. It drags the +# current item. +# +# Arguments: +# w - The canvas window. +# x, y - The coordinates of the mouse. + +proc plotMove {w x y} { + global plot + $w move selected [expr $x-$plot(lastX)] [expr $y-$plot(lastY)] + set plot(lastX) $x + set plot(lastY) $y +} diff --git a/library/demos/puzzle.tcl b/library/demos/puzzle.tcl new file mode 100644 index 0000000..7e3d9c8 --- /dev/null +++ b/library/demos/puzzle.tcl @@ -0,0 +1,73 @@ +# puzzle.tcl -- +# +# This demonstration script creates a 15-puzzle game using a collection +# of buttons. +# +# SCCS: @(#) puzzle.tcl 1.5 97/03/02 16:26:32 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +# puzzleSwitch -- +# This procedure is invoked when the user clicks on a particular button; +# if the button is next to the empty space, it moves the button into th +# empty space. + +proc puzzleSwitch {w num} { + global xpos ypos + if {(($ypos($num) >= ($ypos(space) - .01)) + && ($ypos($num) <= ($ypos(space) + .01)) + && ($xpos($num) >= ($xpos(space) - .26)) + && ($xpos($num) <= ($xpos(space) + .26))) + || (($xpos($num) >= ($xpos(space) - .01)) + && ($xpos($num) <= ($xpos(space) + .01)) + && ($ypos($num) >= ($ypos(space) - .26)) + && ($ypos($num) <= ($ypos(space) + .26)))} { + set tmp $xpos(space) + set xpos(space) $xpos($num) + set xpos($num) $tmp + set tmp $ypos(space) + set ypos(space) $ypos($num) + set ypos($num) $tmp + place $w.frame.$num -relx $xpos($num) -rely $ypos($num) + } +} + +set w .puzzle +catch {destroy $w} +toplevel $w +wm title $w "15-Puzzle Demonstration" +wm iconname $w "15-Puzzle" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "A 15-puzzle appears below as a collection of buttons. Click on any of the pieces next to the space, and that piece will slide over the space. Continue this until the pieces are arranged in numerical order from upper-left to lower-right." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +# Special trick: select a darker color for the space by creating a +# scrollbar widget and using its trough color. + +scrollbar $w.s +frame $w.frame -width 120 -height 120 -borderwidth 2 -relief sunken \ + -bg [$w.s cget -troughcolor] +pack $w.frame -side top -pady 1c -padx 1c +destroy $w.s + +set order {3 1 6 2 5 7 15 13 4 11 8 9 14 10 12} +for {set i 0} {$i < 15} {set i [expr $i+1]} { + set num [lindex $order $i] + set xpos($num) [expr ($i%4)*.25] + set ypos($num) [expr ($i/4)*.25] + button $w.frame.$num -relief raised -text $num -highlightthickness 0 \ + -command "puzzleSwitch $w $num" + place $w.frame.$num -relx $xpos($num) -rely $ypos($num) \ + -relwidth .25 -relheight .25 +} +set xpos(space) .75 +set ypos(space) .75 diff --git a/library/demos/radio.tcl b/library/demos/radio.tcl new file mode 100644 index 0000000..2b73739 --- /dev/null +++ b/library/demos/radio.tcl @@ -0,0 +1,44 @@ +# radio.tcl -- +# +# This demonstration script creates a toplevel window containing +# several radiobutton widgets. +# +# SCCS: @(#) radio.tcl 1.5 97/03/02 16:26:57 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .radio +catch {destroy $w} +toplevel $w +wm title $w "Radiobutton Demonstration" +wm iconname $w "radio" +positionWindow $w +label $w.msg -font $font -wraplength 5i -justify left -text "Two groups of radiobuttons are displayed below. If you click on a button then the button will become selected exclusively among all the buttons in its group. A Tcl variable is associated with each group to indicate which of the group's buttons is selected. Click the \"See Variables\" button to see the current values of the variables." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +button $w.buttons.vars -text "See Variables" \ + -command "showVars $w.dialog size color" +pack $w.buttons.dismiss $w.buttons.code $w.buttons.vars -side left -expand 1 + +frame $w.left +frame $w.right +pack $w.left $w.right -side left -expand yes -pady .5c -padx .5c + +foreach i {10 12 18 24} { + radiobutton $w.left.b$i -text "Point Size $i" -variable size \ + -relief flat -value $i + pack $w.left.b$i -side top -pady 2 -anchor w +} + +foreach color {Red Green Blue Yellow Orange Purple} { + set lower [string tolower $color] + radiobutton $w.right.$lower -text $color -variable color \ + -relief flat -value $lower + pack $w.right.$lower -side top -pady 2 -anchor w +} diff --git a/library/demos/rmt b/library/demos/rmt new file mode 100644 index 0000000..9310475 --- /dev/null +++ b/library/demos/rmt @@ -0,0 +1,205 @@ +#!/bin/sh +# the next line restarts using wish \ +exec wish "$0" "$@" + +# rmt -- +# This script implements a simple remote-control mechanism for +# Tk applications. It allows you to select an application and +# then type commands to that application. +# +# SCCS: @(#) rmt 1.10 96/06/24 16:42:38 + +wm title . "Tk Remote Controller" +wm iconname . "Tk Remote" +wm minsize . 1 1 + +# The global variable below keeps track of the remote application +# that we're sending to. If it's an empty string then we execute +# the commands locally. + +set app "local" + +# The global variable below keeps track of whether we're in the +# middle of executing a command entered via the text. + +set executing 0 + +# The global variable below keeps track of the last command executed, +# so it can be re-executed in response to !! commands. + +set lastCommand "" + +# Create menu bar. Arrange to recreate all the information in the +# applications sub-menu whenever it is cascaded to. + +frame .menu -relief raised -bd 2 +pack .menu -side top -fill x +menubutton .menu.file -text "File" -menu .menu.file.m -underline 0 +menu .menu.file.m +.menu.file.m add cascade -label "Select Application" \ + -menu .menu.file.m.apps -underline 0 +.menu.file.m add command -label "Quit" -command "destroy ." -underline 0 +menu .menu.file.m.apps -postcommand fillAppsMenu +pack .menu.file -side left + +# Create text window and scrollbar. + +text .t -relief sunken -bd 2 -yscrollcommand ".s set" -setgrid true +scrollbar .s -command ".t yview" +pack .s -side right -fill both +pack .t -side left + +# Create a binding to forward commands to the target application, +# plus modify many of the built-in bindings so that only information +# in the current command can be deleted (can still set the cursor +# earlier in the text and select and insert; just can't delete). + +bindtags .t {.t Text . all} +bind .t <Return> { + .t mark set insert {end - 1c} + .t insert insert \n + invoke + break +} +bind .t <Delete> { + catch {.t tag remove sel sel.first promptEnd} + if {[.t tag nextrange sel 1.0 end] == ""} { + if [.t compare insert < promptEnd] { + break + } + } +} +bind .t <BackSpace> { + catch {.t tag remove sel sel.first promptEnd} + if {[.t tag nextrange sel 1.0 end] == ""} { + if [.t compare insert <= promptEnd] { + break + } + } +} +bind .t <Control-d> { + if [.t compare insert < promptEnd] { + break + } +} +bind .t <Control-k> { + if [.t compare insert < promptEnd] { + .t mark set insert promptEnd + } +} +bind .t <Control-t> { + if [.t compare insert < promptEnd] { + break + } +} +bind .t <Meta-d> { + if [.t compare insert < promptEnd] { + break + } +} +bind .t <Meta-BackSpace> { + if [.t compare insert <= promptEnd] { + break + } +} +bind .t <Control-h> { + if [.t compare insert <= promptEnd] { + break + } +} +auto_load tkTextInsert +proc tkTextInsert {w s} { + if {$s == ""} { + return + } + catch { + if {[$w compare sel.first <= insert] + && [$w compare sel.last >= insert]} { + $w tag remove sel sel.first promptEnd + $w delete sel.first sel.last + } + } + $w insert insert $s + $w see insert +} + +.t tag configure bold -font {Courier 12 bold} + +# The procedure below is used to print out a prompt at the +# insertion point (which should be at the beginning of a line +# right now). + +proc prompt {} { + global app + .t insert insert "$app: " + .t mark set promptEnd {insert} + .t mark gravity promptEnd left + .t tag add bold {promptEnd linestart} promptEnd +} + +# The procedure below executes a command (it takes everything on the +# current line after the prompt and either sends it to the remote +# application or executes it locally, depending on "app". + +proc invoke {} { + global app executing lastCommand + set cmd [.t get promptEnd insert] + incr executing 1 + if [info complete $cmd] { + if {$cmd == "!!\n"} { + set cmd $lastCommand + } else { + set lastCommand $cmd + } + if {$app == "local"} { + set result [catch [list uplevel #0 $cmd] msg] + } else { + set result [catch [list send $app $cmd] msg] + } + if {$result != 0} { + .t insert insert "Error: $msg\n" + } else { + if {$msg != ""} { + .t insert insert $msg\n + } + } + prompt + .t mark set promptEnd insert + } + incr executing -1 + .t yview -pickplace insert +} + +# The following procedure is invoked to change the application that +# we're talking to. It also updates the prompt for the current +# command, unless we're in the middle of executing a command from +# the text item (in which case a new prompt is about to be output +# so there's no need to change the old one). + +proc newApp appName { + global app executing + set app $appName + if !$executing { + .t mark gravity promptEnd right + .t delete "promptEnd linestart" promptEnd + .t insert promptEnd "$appName: " + .t tag add bold "promptEnd linestart" promptEnd + .t mark gravity promptEnd left + } + return {} +} + +# The procedure below will fill in the applications sub-menu with a list +# of all the applications that currently exist. + +proc fillAppsMenu {} { + catch {.menu.file.m.apps delete 0 last} + foreach i [lsort [winfo interps]] { + .menu.file.m.apps add command -label $i -command [list newApp $i] + } + .menu.file.m.apps add command -label local -command {newApp local} +} + +set app [winfo name .] +prompt +focus .t diff --git a/library/demos/rolodex b/library/demos/rolodex new file mode 100644 index 0000000..e3e0e5a --- /dev/null +++ b/library/demos/rolodex @@ -0,0 +1,196 @@ +#!/bin/sh +# the next line restarts using wish \ +exec wish "$0" "$@" + +# rolodex -- +# This script was written as an entry in Tom LaStrange's rolodex +# benchmark. It creates something that has some of the look and +# feel of a rolodex program, although it's lifeless and doesn't +# actually do the rolodex application. +# +# SCCS: @(#) rolodex 1.7 96/02/16 10:49:23 + +foreach i [winfo child .] { + catch {destroy $i} +} + +#------------------------------------------ +# Phase 0: create the front end. +#------------------------------------------ + +frame .frame -relief flat +pack .frame -side top -fill y -anchor center + +set names {{} Name: Address: {} {} {Home Phone:} {Work Phone:} Fax:} +foreach i {1 2 3 4 5 6 7} { + frame .frame.$i + pack .frame.$i -side top -pady 2 -anchor e + + label .frame.$i.label -text [lindex $names $i] -anchor e + entry .frame.$i.entry -width 30 -relief sunken + pack .frame.$i.entry .frame.$i.label -side right +} + +frame .buttons +pack .buttons -side bottom -pady 2 -anchor center +button .buttons.clear -text Clear +button .buttons.add -text Add +button .buttons.search -text Search +button .buttons.delete -text "Delete ..." +pack .buttons.clear .buttons.add .buttons.search .buttons.delete \ + -side left -padx 2 + +#------------------------------------------ +# Phase 1: Add menus, dialog boxes +#------------------------------------------ + +frame .menu -relief raised -borderwidth 1 +pack .menu -before .frame -side top -fill x + +menubutton .menu.file -text "File" -menu .menu.file.m -underline 0 +menu .menu.file.m +.menu.file.m add command -label "Load ..." -command fileAction -underline 0 +.menu.file.m add command -label "Exit" -command {destroy .} -underline 0 +pack .menu.file -side left + +menubutton .menu.help -text "Help" -menu .menu.help.m -underline 0 +menu .menu.help.m +pack .menu.help -side right + +proc deleteAction {} { + if {[tk_dialog .delete {Confirm Action} {Are you sure?} {} 0 Cancel] + == 0} { + clearAction + } +} +.buttons.delete config -command deleteAction + +proc fileAction {} { + tk_dialog .fileSelection {File Selection} {This is a dummy file selection dialog box, which is used because there isn't a good file selection dialog built into Tk yet.} {} 0 OK + puts stderr {dummy file name} +} + +#------------------------------------------ +# Phase 3: Print contents of card +#------------------------------------------ + +proc addAction {} { + global names + foreach i {1 2 3 4 5 6 7} { + puts stderr [format "%-12s %s" [lindex $names $i] [.frame.$i.entry get]] + } +} +.buttons.add config -command addAction + +#------------------------------------------ +# Phase 4: Miscellaneous other actions +#------------------------------------------ + +proc clearAction {} { + foreach i {1 2 3 4 5 6 7} { + .frame.$i.entry delete 0 end + } +} +.buttons.clear config -command clearAction + +proc fillCard {} { + clearAction + .frame.1.entry insert 0 "John Ousterhout" + .frame.2.entry insert 0 "CS Division, Department of EECS" + .frame.3.entry insert 0 "University of California" + .frame.4.entry insert 0 "Berkeley, CA 94720" + .frame.5.entry insert 0 "private" + .frame.6.entry insert 0 "510-642-0865" + .frame.7.entry insert 0 "510-642-5775" +} +.buttons.search config -command "addAction; fillCard" + +#---------------------------------------------------- +# Phase 5: Accelerators, mnemonics, command-line info +#---------------------------------------------------- + +.buttons.clear config -text "Clear Ctrl+C" +bind . <Control-c> clearAction +.buttons.add config -text "Add Ctrl+A" +bind . <Control-a> addAction +.buttons.search config -text "Search Ctrl+S" +bind . <Control-s> "addAction; fillCard" +.buttons.delete config -text "Delete... Ctrl+D" +bind . <Control-d> deleteAction + +.menu.file.m entryconfig 1 -accel Ctrl+F +bind . <Control-f> fileAction +.menu.file.m entryconfig 2 -accel Ctrl+Q +bind . <Control-q> {destroy .} + +focus .frame.1.entry + +#---------------------------------------------------- +# Phase 6: help +#---------------------------------------------------- + +proc Help {topic {x 0} {y 0}} { + global helpTopics helpCmds + if {$topic == ""} return + while {[info exists helpCmds($topic)]} { + set topic [eval $helpCmds($topic)] + } + if [info exists helpTopics($topic)] { + set msg $helpTopics($topic) + } else { + set msg "Sorry, but no help is available for this topic" + } + tk_dialog .help {Rolodex Help} "Information on $topic:\n\n$msg" \ + {} 0 OK +} + +proc getMenuTopic {w x y} { + return $w.[$w index @[expr $y-[winfo rooty $w]]] +} + +bind . <Any-F1> {Help [winfo containing %X %Y] %X %Y} +bind . <Any-Help> {Help [winfo containing %X %Y] %X %Y} + +# Help text and commands follow: + +set helpTopics(.menu.file) {This is the "file" menu. It can be used to invoke some overall operations on the rolodex applications, such as loading a file or exiting.} + +set helpCmds(.menu.file.m) {getMenuTopic $topic $x $y} +set helpTopics(.menu.file.m.0) {The "Load" entry in the "File" menu posts a dialog box that you can use to select a rolodex file} +set helpTopics(.menu.file.m.1) {The "Exit" entry in the "File" menu causes the rolodex application to terminate} +set helpCmds(.menu.file.m.none) {set topic ".menu.file"} + +set helpTopics(.frame.1.entry) {In this field of the rolodex entry you should type the person's name} +set helpTopics(.frame.2.entry) {In this field of the rolodex entry you should type the first line of the person's address} +set helpTopics(.frame.3.entry) {In this field of the rolodex entry you should type the second line of the person's address} +set helpTopics(.frame.4.entry) {In this field of the rolodex entry you should type the third line of the person's address} +set helpTopics(.frame.5.entry) {In this field of the rolodex entry you should type the person's home phone number, or "private" if the person doesn't want his or her number publicized} +set helpTopics(.frame.6.entry) {In this field of the rolodex entry you should type the person's work phone number} +set helpTopics(.frame.7.entry) {In this field of the rolodex entry you should type the phone number for the person's FAX machine} + +set helpCmds(.frame.1.label) {set topic .frame.1.entry} +set helpCmds(.frame.2.label) {set topic .frame.2.entry} +set helpCmds(.frame.3.label) {set topic .frame.3.entry} +set helpCmds(.frame.4.label) {set topic .frame.4.entry} +set helpCmds(.frame.5.label) {set topic .frame.5.entry} +set helpCmds(.frame.6.label) {set topic .frame.6.entry} +set helpCmds(.frame.7.label) {set topic .frame.7.entry} + +set helpTopics(context) {Unfortunately, this application doesn't support context-sensitive help in the usual way, because when this demo was written Tk didn't have a grab mechanism and this is needed for context-sensitive help. Instead, you can achieve much the same effect by simply moving the mouse over the window you're curious about and pressing the Help or F1 keys. You can do this anytime.} +set helpTopics(help) {This application provides only very crude help. Besides the entries in this menu, you can get help on individual windows by moving the mouse cursor over the window and pressing the Help or F1 keys.} +set helpTopics(window) {This window is a dummy rolodex application created as part of Tom LaStrange's toolkit benchmark. It doesn't really do anything useful except to demonstrate a few features of the Tk toolkit.} +set helpTopics(keys) "The following accelerator keys are defined for this application (in addition to those already available for the entry windows):\n\nCtrl+A:\t\tAdd\nCtrl+C:\t\tClear\nCtrl+D:\t\tDelete\nCtrl+F:\t\tEnter file name\nCtrl+Q:\t\tExit application (quit)\nCtrl+S:\t\tSearch (dummy operation)" +set helpTopics(version) {This is version 1.0.} + +# Entries in "Help" menu + +.menu.help.m add command -label "On Context..." -command {Help context} \ + -underline 3 +.menu.help.m add command -label "On Help..." -command {Help help} \ + -underline 3 +.menu.help.m add command -label "On Window..." -command {Help window} \ + -underline 3 +.menu.help.m add command -label "On Keys..." -command {Help keys} \ + -underline 3 +.menu.help.m add command -label "On Version..." -command {Help version} \ + -underline 3 diff --git a/library/demos/ruler.tcl b/library/demos/ruler.tcl new file mode 100644 index 0000000..3c77c72 --- /dev/null +++ b/library/demos/ruler.tcl @@ -0,0 +1,173 @@ +# ruler.tcl -- +# +# This demonstration script creates a canvas widget that displays a ruler +# with tab stops that can be set, moved, and deleted. +# +# SCCS: @(#) ruler.tcl 1.9 97/03/02 16:17:33 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +# rulerMkTab -- +# This procedure creates a new triangular polygon in a canvas to +# represent a tab stop. +# +# Arguments: +# c - The canvas window. +# x, y - Coordinates at which to create the tab stop. + +proc rulerMkTab {c x y} { + upvar #0 demo_rulerInfo v + $c create polygon $x $y [expr $x+$v(size)] [expr $y+$v(size)] \ + [expr $x-$v(size)] [expr $y+$v(size)] +} + +set w .ruler +global tk_library +catch {destroy $w} +toplevel $w +wm title $w "Ruler Demonstration" +wm iconname $w "ruler" +positionWindow $w +set c $w.c + +label $w.msg -font $font -wraplength 5i -justify left -text "This canvas widget shows a mock-up of a ruler. You can create tab stops by dragging them out of the well to the right of the ruler. You can also drag existing tab stops. If you drag a tab stop far enough up or down so that it turns dim, it will be deleted when you release the mouse button." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +canvas $c -width 14.8c -height 2.5c +pack $w.c -side top -fill x + +set demo_rulerInfo(grid) .25c +set demo_rulerInfo(left) [winfo fpixels $c 1c] +set demo_rulerInfo(right) [winfo fpixels $c 13c] +set demo_rulerInfo(top) [winfo fpixels $c 1c] +set demo_rulerInfo(bottom) [winfo fpixels $c 1.5c] +set demo_rulerInfo(size) [winfo fpixels $c .2c] +set demo_rulerInfo(normalStyle) "-fill black" +if {[winfo depth $c] > 1} { + set demo_rulerInfo(activeStyle) "-fill red -stipple {}" + set demo_rulerInfo(deleteStyle) [list -fill red \ + -stipple @[file join $tk_library demos images gray25.bmp]] +} else { + set demo_rulerInfo(activeStyle) "-fill black -stipple {}" + set demo_rulerInfo(deleteStyle) [list -fill black \ + -stipple @[file join $tk_library demos images gray25.bmp]] +} + +$c create line 1c 0.5c 1c 1c 13c 1c 13c 0.5c -width 1 +for {set i 0} {$i < 12} {incr i} { + set x [expr $i+1] + $c create line ${x}c 1c ${x}c 0.6c -width 1 + $c create line $x.25c 1c $x.25c 0.8c -width 1 + $c create line $x.5c 1c $x.5c 0.7c -width 1 + $c create line $x.75c 1c $x.75c 0.8c -width 1 + $c create text $x.15c .75c -text $i -anchor sw +} +$c addtag well withtag [$c create rect 13.2c 1c 13.8c 0.5c \ + -outline black -fill [lindex [$c config -bg] 4]] +$c addtag well withtag [rulerMkTab $c [winfo pixels $c 13.5c] \ + [winfo pixels $c .65c]] + +$c bind well <1> "rulerNewTab $c %x %y" +$c bind tab <1> "rulerSelectTab $c %x %y" +bind $c <B1-Motion> "rulerMoveTab $c %x %y" +bind $c <Any-ButtonRelease-1> "rulerReleaseTab $c" + +# rulerNewTab -- +# Does all the work of creating a tab stop, including creating the +# triangle object and adding tags to it to give it tab behavior. +# +# Arguments: +# c - The canvas window. +# x, y - The coordinates of the tab stop. + +proc rulerNewTab {c x y} { + upvar #0 demo_rulerInfo v + $c addtag active withtag [rulerMkTab $c $x $y] + $c addtag tab withtag active + set v(x) $x + set v(y) $y + rulerMoveTab $c $x $y +} + +# rulerSelectTab -- +# This procedure is invoked when mouse button 1 is pressed over +# a tab. It remembers information about the tab so that it can +# be dragged interactively. +# +# Arguments: +# c - The canvas widget. +# x, y - The coordinates of the mouse (identifies the point by +# which the tab was picked up for dragging). + +proc rulerSelectTab {c x y} { + upvar #0 demo_rulerInfo v + set v(x) [$c canvasx $x $v(grid)] + set v(y) [expr $v(top)+2] + $c addtag active withtag current + eval "$c itemconf active $v(activeStyle)" + $c raise active +} + +# rulerMoveTab -- +# This procedure is invoked during mouse motion events to drag a tab. +# It adjusts the position of the tab, and changes its appearance if +# it is about to be dragged out of the ruler. +# +# Arguments: +# c - The canvas widget. +# x, y - The coordinates of the mouse. + +proc rulerMoveTab {c x y} { + upvar #0 demo_rulerInfo v + if {[$c find withtag active] == ""} { + return + } + set cx [$c canvasx $x $v(grid)] + set cy [$c canvasy $y] + if {$cx < $v(left)} { + set cx $v(left) + } + if {$cx > $v(right)} { + set cx $v(right) + } + if {($cy >= $v(top)) && ($cy <= $v(bottom))} { + set cy [expr $v(top)+2] + eval "$c itemconf active $v(activeStyle)" + } else { + set cy [expr $cy-$v(size)-2] + eval "$c itemconf active $v(deleteStyle)" + } + $c move active [expr $cx-$v(x)] [expr $cy-$v(y)] + set v(x) $cx + set v(y) $cy +} + +# rulerReleaseTab -- +# This procedure is invoked during button release events that end +# a tab drag operation. It deselects the tab and deletes the tab if +# it was dragged out of the ruler. +# +# Arguments: +# c - The canvas widget. +# x, y - The coordinates of the mouse. + +proc rulerReleaseTab c { + upvar #0 demo_rulerInfo v + if {[$c find withtag active] == {}} { + return + } + if {$v(y) != [expr $v(top)+2]} { + $c delete active + } else { + eval "$c itemconf active $v(normalStyle)" + $c dtag active + } +} diff --git a/library/demos/sayings.tcl b/library/demos/sayings.tcl new file mode 100644 index 0000000..b4952c5 --- /dev/null +++ b/library/demos/sayings.tcl @@ -0,0 +1,46 @@ +# sayings.tcl -- +# +# This demonstration script creates a listbox that can be scrolled +# both horizontally and vertically. It displays a collection of +# well-known sayings. +# +# SCCS: @(#) sayings.tcl 1.7 97/03/02 16:27:10 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .sayings +catch {destroy $w} +toplevel $w +wm title $w "Listbox Demonstration (well-known sayings)" +wm iconname $w "sayings" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "The listbox below contains a collection of well-known sayings. You can scan the list using either of the scrollbars or by dragging in the listbox window with button 2 pressed." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.frame -borderwidth 10 +pack $w.frame -side top -expand yes -fill y + + +scrollbar $w.frame.yscroll -command "$w.frame.list yview" +scrollbar $w.frame.xscroll -orient horizontal \ + -command "$w.frame.list xview" +listbox $w.frame.list -width 20 -height 10 -setgrid 1 \ + -yscroll "$w.frame.yscroll set" -xscroll "$w.frame.xscroll set" + +grid $w.frame.list -row 0 -column 0 -rowspan 1 -columnspan 1 -sticky news +grid $w.frame.yscroll -row 0 -column 1 -rowspan 1 -columnspan 1 -sticky news +grid $w.frame.xscroll -row 1 -column 0 -rowspan 1 -columnspan 1 -sticky news +grid rowconfig $w.frame 0 -weight 1 -minsize 0 +grid columnconfig $w.frame 0 -weight 1 -minsize 0 + + +$w.frame.list insert 0 "Waste not, want not" "Early to bed and early to rise makes a man healthy, wealthy, and wise" "Ask not what your country can do for you, ask what you can do for your country" "I shall return" "NOT" "A picture is worth a thousand words" "User interfaces are hard to build" "Thou shalt not steal" "A penny for your thoughts" "Fool me once, shame on you; fool me twice, shame on me" "Every cloud has a silver lining" "Where there's smoke there's fire" "It takes one to know one" "Curiosity killed the cat" "Take this job and shove it" "Up a creek without a paddle" "I'm mad as hell and I'm not going to take it any more" "An apple a day keeps the doctor away" "Don't look a gift horse in the mouth" diff --git a/library/demos/search.tcl b/library/demos/search.tcl new file mode 100644 index 0000000..ffefd82 --- /dev/null +++ b/library/demos/search.tcl @@ -0,0 +1,141 @@ +# search.tcl -- +# +# This demonstration script creates a collection of widgets that +# allow you to load a file into a text widget, then perform searches +# on that file. +# +# SCCS: @(#) search.tcl 1.5 97/03/02 16:27:25 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +# textLoadFile -- +# This procedure below loads a file into a text widget, discarding +# the previous contents of the widget. Tags for the old widget are +# not affected, however. +# +# Arguments: +# w - The window into which to load the file. Must be a +# text widget. +# file - The name of the file to load. Must be readable. + +proc textLoadFile {w file} { + set f [open $file] + $w delete 1.0 end + while {![eof $f]} { + $w insert end [read $f 10000] + } + close $f +} + +# textSearch -- +# Search for all instances of a given string in a text widget and +# apply a given tag to each instance found. +# +# Arguments: +# w - The window in which to search. Must be a text widget. +# string - The string to search for. The search is done using +# exact matching only; no special characters. +# tag - Tag to apply to each instance of a matching string. + +proc textSearch {w string tag} { + $w tag remove search 0.0 end + if {$string == ""} { + return + } + set cur 1.0 + while 1 { + set cur [$w search -count length $string $cur end] + if {$cur == ""} { + break + } + $w tag add $tag $cur "$cur + $length char" + set cur [$w index "$cur + $length char"] + } +} + +# textToggle -- +# This procedure is invoked repeatedly to invoke two commands at +# periodic intervals. It normally reschedules itself after each +# execution but if an error occurs (e.g. because the window was +# deleted) then it doesn't reschedule itself. +# +# Arguments: +# cmd1 - Command to execute when procedure is called. +# sleep1 - Ms to sleep after executing cmd1 before executing cmd2. +# cmd2 - Command to execute in the *next* invocation of this +# procedure. +# sleep2 - Ms to sleep after executing cmd2 before executing cmd1 again. + +proc textToggle {cmd1 sleep1 cmd2 sleep2} { + catch { + eval $cmd1 + after $sleep1 [list textToggle $cmd2 $sleep2 $cmd1 $sleep1] + } +} + +set w .search +catch {destroy $w} +toplevel $w +wm title $w "Text Demonstration - Search and Highlight" +wm iconname $w "search" +positionWindow $w + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.file +label $w.file.label -text "File name:" -width 13 -anchor w +entry $w.file.entry -width 40 -textvariable fileName +button $w.file.button -text "Load File" \ + -command "textLoadFile $w.text \$fileName" +pack $w.file.label $w.file.entry -side left +pack $w.file.button -side left -pady 5 -padx 10 +bind $w.file.entry <Return> " + textLoadFile $w.text \$fileName + focus $w.string.entry +" +focus $w.file.entry + +frame $w.string +label $w.string.label -text "Search string:" -width 13 -anchor w +entry $w.string.entry -width 40 -textvariable searchString +button $w.string.button -text "Highlight" \ + -command "textSearch $w.text \$searchString search" +pack $w.string.label $w.string.entry -side left +pack $w.string.button -side left -pady 5 -padx 10 +bind $w.string.entry <Return> "textSearch $w.text \$searchString search" + +text $w.text -yscrollcommand "$w.scroll set" -setgrid true +scrollbar $w.scroll -command "$w.text yview" +pack $w.file $w.string -side top -fill x +pack $w.scroll -side right -fill y +pack $w.text -expand yes -fill both + +# Set up display styles for text highlighting. + +if {[winfo depth $w] > 1} { + textToggle "$w.text tag configure search -background \ + #ce5555 -foreground white" 800 "$w.text tag configure \ + search -background {} -foreground {}" 200 +} else { + textToggle "$w.text tag configure search -background \ + black -foreground white" 800 "$w.text tag configure \ + search -background {} -foreground {}" 200 +} +$w.text insert 1.0 \ +{This window demonstrates how to use the tagging facilities in text +widgets to implement a searching mechanism. First, type a file name +in the top entry, then type <Return> or click on "Load File". Then +type a string in the lower entry and type <Return> or click on +"Load File". This will cause all of the instances of the string to +be tagged with the tag "search", and it will arrange for the tag's +display attributes to change to make all of the strings blink.} +$w.text mark set insert 0.0 + +set fileName "" +set searchString "" diff --git a/library/demos/square b/library/demos/square new file mode 100644 index 0000000..743016f --- /dev/null +++ b/library/demos/square @@ -0,0 +1,55 @@ +#!/bin/sh +# the next line restarts using wish \ +exec wish "$0" "$@" + +# square -- +# This script generates a demo application containing only a "square" +# widget. It's only usable in the "tktest" application or if Tk has +# been compiled with tkSquare.c. This demo arranges the following +# bindings for the widget: +# +# Button-1 press/drag: moves square to mouse +# "a": toggle size animation on/off +# +# SCCS: @(#) square 1.7 97/02/24 16:42:31 + +square .s +pack .s -expand yes -fill both +wm minsize . 1 1 + +bind .s <1> {center %x %y} +bind .s <B1-Motion> {center %x %y} +bind .s a animate +focus .s + +# The procedure below centers the square on a given position. + +proc center {x y} { + set a [.s size] + .s position [expr $x-($a/2)] [expr $y-($a/2)] +} + +# The procedures below provide a simple form of animation where +# the box changes size in a pulsing pattern: larger, smaller, larger, +# and so on. + +set inc 0 +proc animate {} { + global inc + if {$inc == 0} { + set inc 3 + timer + } else { + set inc 0 + } +} + +proc timer {} { + global inc + set s [.s size] + if {$inc == 0} return + if {$s >= 40} {set inc -3} + if {$s <= 10} {set inc 3} + .s size [expr {$s+$inc}] + after 30 timer +} diff --git a/library/demos/states.tcl b/library/demos/states.tcl new file mode 100644 index 0000000..23905a2 --- /dev/null +++ b/library/demos/states.tcl @@ -0,0 +1,45 @@ +# states.tcl -- +# +# This demonstration script creates a listbox widget that displays +# the names of the 50 states in the United States of America. +# +# SCCS: @(#) states.tcl 1.4 97/03/02 16:27:37 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .states +catch {destroy $w} +toplevel $w +wm title $w "Listbox Demonstration (50 states)" +wm iconname $w "states" +positionWindow $w + +label $w.msg -font $font -wraplength 4i -justify left -text "A listbox containing the 50 states is displayed below, along with a scrollbar. You can scan the list either using the scrollbar or by scanning. To scan, press button 2 in the widget and drag up or down." +pack $w.msg -side top + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.frame -borderwidth .5c +pack $w.frame -side top -expand yes -fill y + +scrollbar $w.frame.scroll -command "$w.frame.list yview" +listbox $w.frame.list -yscroll "$w.frame.scroll set" -setgrid 1 -height 12 +pack $w.frame.scroll -side right -fill y +pack $w.frame.list -side left -expand 1 -fill both + +$w.frame.list insert 0 Alabama Alaska Arizona Arkansas California \ + Colorado Connecticut Delaware Florida Georgia Hawaii Idaho Illinois \ + Indiana Iowa Kansas Kentucky Louisiana Maine Maryland \ + Massachusetts Michigan Minnesota Mississippi Missouri \ + Montana Nebraska Nevada "New Hampshire" "New Jersey" "New Mexico" \ + "New York" "North Carolina" "North Dakota" \ + Ohio Oklahoma Oregon Pennsylvania "Rhode Island" \ + "South Carolina" "South Dakota" \ + Tennessee Texas Utah Vermont Virginia Washington \ + "West Virginia" Wisconsin Wyoming diff --git a/library/demos/style.tcl b/library/demos/style.tcl new file mode 100644 index 0000000..6ed31f8 --- /dev/null +++ b/library/demos/style.tcl @@ -0,0 +1,152 @@ +# style.tcl -- +# +# This demonstration script creates a text widget that illustrates the +# various display styles that may be set for tags. +# +# SCCS: @(#) style.tcl 1.8 97/04/18 11:41:47 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .style +catch {destroy $w} +toplevel $w +wm title $w "Text Demonstration - Display Styles" +wm iconname $w "style" +positionWindow $w + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +text $w.text -yscrollcommand "$w.scroll set" -setgrid true \ + -width 70 -height 32 -wrap word +scrollbar $w.scroll -command "$w.text yview" +pack $w.scroll -side right -fill y +pack $w.text -expand yes -fill both + +# Set up display styles + +$w.text tag configure bold -font {Courier 12 bold italic} +$w.text tag configure big -font {Courier 14 bold} +$w.text tag configure verybig -font {Helvetica 24 bold} +if {[winfo depth $w] > 1} { + $w.text tag configure color1 -background #a0b7ce + $w.text tag configure color2 -foreground red + $w.text tag configure raised -relief raised -borderwidth 1 + $w.text tag configure sunken -relief sunken -borderwidth 1 +} else { + $w.text tag configure color1 -background black -foreground white + $w.text tag configure color2 -background black -foreground white + $w.text tag configure raised -background white -relief raised \ + -borderwidth 1 + $w.text tag configure sunken -background white -relief sunken \ + -borderwidth 1 +} +$w.text tag configure bgstipple -background black -borderwidth 0 \ + -bgstipple gray12 +$w.text tag configure fgstipple -fgstipple gray50 +$w.text tag configure underline -underline on +$w.text tag configure overstrike -overstrike on +$w.text tag configure right -justify right +$w.text tag configure center -justify center +$w.text tag configure super -offset 4p -font {Courier 10} +$w.text tag configure sub -offset -2p -font {Courier 10} +$w.text tag configure margins -lmargin1 12m -lmargin2 6m -rmargin 10m +$w.text tag configure spacing -spacing1 10p -spacing2 2p \ + -lmargin1 12m -lmargin2 6m -rmargin 10m + +$w.text insert end {Text widgets like this one allow you to display information in a +variety of styles. Display styles are controlled using a mechanism +called } +$w.text insert end tags bold +$w.text insert end {. Tags are just textual names that you can apply to one +or more ranges of characters within a text widget. You can configure +tags with various display styles. If you do this, then the tagged +characters will be displayed with the styles you chose. The +available display styles are: +} +$w.text insert end "\n1. Font." big +$w.text insert end " You can choose any X font, " +$w.text insert end large verybig +$w.text insert end " or " +$w.text insert end "small.\n" +$w.text insert end "\n2. Color." big +$w.text insert end " You can change either the " +$w.text insert end background color1 +$w.text insert end " or " +$w.text insert end foreground color2 +$w.text insert end "\ncolor, or " +$w.text insert end both {color1 color2} +$w.text insert end ".\n" +$w.text insert end "\n3. Stippling." big +$w.text insert end " You can cause either the " +$w.text insert end background bgstipple +$w.text insert end " or " +$w.text insert end foreground fgstipple +$w.text insert end { +information to be drawn with a stipple fill instead of a solid fill. +} +$w.text insert end "\n4. Underlining." big +$w.text insert end " You can " +$w.text insert end underline underline +$w.text insert end " ranges of text.\n" +$w.text insert end "\n5. Overstrikes." big +$w.text insert end " You can " +$w.text insert end "draw lines through" overstrike +$w.text insert end " ranges of text.\n" +$w.text insert end "\n6. 3-D effects." big +$w.text insert end { You can arrange for the background to be drawn +with a border that makes characters appear either } +$w.text insert end raised raised +$w.text insert end " or " +$w.text insert end sunken sunken +$w.text insert end ".\n" +$w.text insert end "\n7. Justification." big +$w.text insert end " You can arrange for lines to be displayed\n" +$w.text insert end "left-justified,\n" +$w.text insert end "right-justified, or\n" right +$w.text insert end "centered.\n" center +$w.text insert end "\n8. Superscripts and subscripts." big +$w.text insert end " You can control the vertical\n" +$w.text insert end "position of text to generate superscript effects like 10" +$w.text insert end "n" super +$w.text insert end " or\nsubscript effects like X" +$w.text insert end "i" sub +$w.text insert end ".\n" +$w.text insert end "\n9. Margins." big +$w.text insert end " You can control the amount of extra space left" +$w.text insert end " on\neach side of the text:\n" +$w.text insert end "This paragraph is an example of the use of " margins +$w.text insert end "margins. It consists of a single line of text " margins +$w.text insert end "that wraps around on the screen. There are two " margins +$w.text insert end "separate left margin values, one for the first " margins +$w.text insert end "display line associated with the text line, " margins +$w.text insert end "and one for the subsequent display lines, which " margins +$w.text insert end "occur because of wrapping. There is also a " margins +$w.text insert end "separate specification for the right margin, " margins +$w.text insert end "which is used to choose wrap points for lines.\n" margins +$w.text insert end "\n10. Spacing." big +$w.text insert end " You can control the spacing of lines with three\n" +$w.text insert end "separate parameters. \"Spacing1\" tells how much " +$w.text insert end "extra space to leave\nabove a line, \"spacing3\" " +$w.text insert end "tells how much space to leave below a line,\nand " +$w.text insert end "if a text line wraps, \"spacing2\" tells how much " +$w.text insert end "space to leave\nbetween the display lines that " +$w.text insert end "make up the text line.\n" +$w.text insert end "These indented paragraphs illustrate how spacing " spacing +$w.text insert end "can be used. Each paragraph is actually a " spacing +$w.text insert end "single line in the text widget, which is " spacing +$w.text insert end "word-wrapped by the widget.\n" spacing +$w.text insert end "Spacing1 is set to 10 points for this text, " spacing +$w.text insert end "which results in relatively large gaps between " spacing +$w.text insert end "the paragraphs. Spacing2 is set to 2 points, " spacing +$w.text insert end "which results in just a bit of extra space " spacing +$w.text insert end "within a pararaph. Spacing3 isn't used " spacing +$w.text insert end "in this example.\n" spacing +$w.text insert end "To see where the space is, select ranges of " spacing +$w.text insert end "text within these paragraphs. The selection " spacing +$w.text insert end "highlight will cover the extra space." spacing diff --git a/library/demos/tclIndex b/library/demos/tclIndex new file mode 100644 index 0000000..86a72e2 --- /dev/null +++ b/library/demos/tclIndex @@ -0,0 +1,67 @@ +# Tcl autoload index file, version 2.0 +# This file is generated by the "auto_mkindex" command +# and sourced to set up indexing information for one or +# more commands. Typically each line is a command that +# sets an element in the auto_index array, where the +# element name is the name of a command and the value is +# a script that loads the command. + +set auto_index(arrowSetup) [list source [file join $dir arrow.tcl]] +set auto_index(arrowMove1) [list source [file join $dir arrow.tcl]] +set auto_index(arrowMove2) [list source [file join $dir arrow.tcl]] +set auto_index(arrowMove3) [list source [file join $dir arrow.tcl]] +set auto_index(textLoadFile) [list source [file join $dir search.tcl]] +set auto_index(textSearch) [list source [file join $dir search.tcl]] +set auto_index(textToggle) [list source [file join $dir search.tcl]] +set auto_index(itemEnter) [list source [file join $dir items.tcl]] +set auto_index(itemLeave) [list source [file join $dir items.tcl]] +set auto_index(itemMark) [list source [file join $dir items.tcl]] +set auto_index(itemStroke) [list source [file join $dir items.tcl]] +set auto_index(itemsUnderArea) [list source [file join $dir items.tcl]] +set auto_index(itemStartDrag) [list source [file join $dir items.tcl]] +set auto_index(itemDrag) [list source [file join $dir items.tcl]] +set auto_index(butPress) [list source [file join $dir items.tcl]] +set auto_index(loadDir) [list source [file join $dir image2.tcl]] +set auto_index(loadImage) [list source [file join $dir image2.tcl]] +set auto_index(rulerMkTab) [list source [file join $dir ruler.tcl]] +set auto_index(rulerNewTab) [list source [file join $dir ruler.tcl]] +set auto_index(rulerSelectTab) [list source [file join $dir ruler.tcl]] +set auto_index(rulerMoveTab) [list source [file join $dir ruler.tcl]] +set auto_index(rulerReleaseTab) [list source [file join $dir ruler.tcl]] +set auto_index(mkTextConfig) [list source [file join $dir ctext.tcl]] +set auto_index(textEnter) [list source [file join $dir ctext.tcl]] +set auto_index(textInsert) [list source [file join $dir ctext.tcl]] +set auto_index(textPaste) [list source [file join $dir ctext.tcl]] +set auto_index(textB1Press) [list source [file join $dir ctext.tcl]] +set auto_index(textB1Move) [list source [file join $dir ctext.tcl]] +set auto_index(textBs) [list source [file join $dir ctext.tcl]] +set auto_index(textDel) [list source [file join $dir ctext.tcl]] +set auto_index(bitmapRow) [list source [file join $dir bitmap.tcl]] +set auto_index(scrollEnter) [list source [file join $dir cscroll.tcl]] +set auto_index(scrollLeave) [list source [file join $dir cscroll.tcl]] +set auto_index(scrollButton) [list source [file join $dir cscroll.tcl]] +set auto_index(textWindOn) [list source [file join $dir twind.tcl]] +set auto_index(textWindOff) [list source [file join $dir twind.tcl]] +set auto_index(textWindPlot) [list source [file join $dir twind.tcl]] +set auto_index(embPlotDown) [list source [file join $dir twind.tcl]] +set auto_index(embPlotMove) [list source [file join $dir twind.tcl]] +set auto_index(textWindDel) [list source [file join $dir twind.tcl]] +set auto_index(embDefBg) [list source [file join $dir twind.tcl]] +set auto_index(floorDisplay) [list source [file join $dir floor.tcl]] +set auto_index(newRoom) [list source [file join $dir floor.tcl]] +set auto_index(roomChanged) [list source [file join $dir floor.tcl]] +set auto_index(bg1) [list source [file join $dir floor.tcl]] +set auto_index(bg2) [list source [file join $dir floor.tcl]] +set auto_index(bg3) [list source [file join $dir floor.tcl]] +set auto_index(fg1) [list source [file join $dir floor.tcl]] +set auto_index(fg2) [list source [file join $dir floor.tcl]] +set auto_index(fg3) [list source [file join $dir floor.tcl]] +set auto_index(setWidth) [list source [file join $dir hscale.tcl]] +set auto_index(plotDown) [list source [file join $dir plot.tcl]] +set auto_index(plotMove) [list source [file join $dir plot.tcl]] +set auto_index(puzzleSwitch) [list source [file join $dir puzzle.tcl]] +set auto_index(setHeight) [list source [file join $dir vscale.tcl]] +set auto_index(showMessageBox) [list source [file join $dir msgbox.tcl]] +set auto_index(setColor) [list source [file join $dir clrpick.tcl]] +set auto_index(setColor_helper) [list source [file join $dir clrpick.tcl]] +set auto_index(fileDialog) [list source [file join $dir filebox.tcl]] diff --git a/library/demos/tcolor b/library/demos/tcolor new file mode 100644 index 0000000..50c0e68 --- /dev/null +++ b/library/demos/tcolor @@ -0,0 +1,358 @@ +#!/bin/sh +# the next line restarts using wish \ +exec wish "$0" "$@" + +# tcolor -- +# This script implements a simple color editor, where you can +# create colors using either the RGB, HSB, or CYM color spaces +# and apply the color to existing applications. +# +# SCCS: @(#) tcolor 1.11 96/06/24 16:43:11 + +wm title . "Color Editor" + +# Global variables that control the program: +# +# colorSpace - Color space currently being used for +# editing. Must be "rgb", "cmy", or "hsb". +# label1, label2, label3 - Labels for the scales. +# red, green, blue - Current color intensities in decimal +# on a scale of 0-65535. +# color - A string giving the current color value +# in the proper form for x: +# #RRRRGGGGBBBB +# updating - Non-zero means that we're in the middle of +# updating the scales to load a new color,so +# information shouldn't be propagating back +# from the scales to other elements of the +# program: this would make an infinite loop. +# command - Holds the command that has been typed +# into the "Command" entry. +# autoUpdate - 1 means execute the update command +# automatically whenever the color changes. +# name - Name for new color, typed into entry. + +set colorSpace hsb +set red 65535 +set green 0 +set blue 0 +set color #ffff00000000 +set updating 0 +set autoUpdate 1 +set name "" + +# Create the menu bar at the top of the window. + +frame .menu -relief raised -borderwidth 2 +pack .menu -side top -fill x +menubutton .menu.file -text File -menu .menu.file.m -underline 0 +menu .menu.file.m +.menu.file.m add radio -label "RGB color space" -variable colorSpace \ + -value rgb -underline 0 -command {changeColorSpace rgb} +.menu.file.m add radio -label "CMY color space" -variable colorSpace \ + -value cmy -underline 0 -command {changeColorSpace cmy} +.menu.file.m add radio -label "HSB color space" -variable colorSpace \ + -value hsb -underline 0 -command {changeColorSpace hsb} +.menu.file.m add separator +.menu.file.m add radio -label "Automatic updates" -variable autoUpdate \ + -value 1 -underline 0 +.menu.file.m add radio -label "Manual updates" -variable autoUpdate \ + -value 0 -underline 0 +.menu.file.m add separator +.menu.file.m add command -label "Exit program" -underline 0 \ + -command "destroy ." +pack .menu.file -side left + +# Create the command entry window at the bottom of the window, along +# with the update button. + +frame .bot -relief raised -borderwidth 2 +pack .bot -side bottom -fill x +label .commandLabel -text "Command:" +entry .command -relief sunken -borderwidth 2 -textvariable command \ + -font {Courier 12} +button .update -text Update -command doUpdate +pack .commandLabel -in .bot -side left +pack .update -in .bot -side right -pady .1c -padx .25c +pack .command -in .bot -expand yes -fill x -ipadx 0.25c + +# Create the listbox that holds all of the color names in rgb.txt, +# if an rgb.txt file can be found. + +frame .middle -relief raised -borderwidth 2 +pack .middle -side top -fill both +foreach i {/usr/local/lib/X11/rgb.txt /usr/lib/X11/rgb.txt + /X11/R5/lib/X11/rgb.txt /X11/R4/lib/rgb/rgb.txt + /usr/openwin/lib/X11/rgb.txt} { + if ![file readable $i] { + continue; + } + set f [open $i] + frame .middle.left + pack .middle.left -side left -padx .25c -pady .25c + listbox .names -width 20 -height 12 -yscrollcommand ".scroll set" \ + -relief sunken -borderwidth 2 -exportselection false + bind .names <Double-1> { + tc_loadNamedColor [.names get [.names curselection]] + } + scrollbar .scroll -orient vertical -command ".names yview" \ + -relief sunken -borderwidth 2 + pack .names -in .middle.left -side left + pack .scroll -in .middle.left -side right -fill y + while {[gets $f line] >= 0} { + if {[llength $line] == 4} { + .names insert end [lindex $line 3] + } + } + close $f + break +} + +# Create the three scales for editing the color, and the entry for +# typing in a color value. + +frame .middle.middle +pack .middle.middle -side left -expand yes -fill y +frame .middle.middle.1 +frame .middle.middle.2 +frame .middle.middle.3 +frame .middle.middle.4 +pack .middle.middle.1 .middle.middle.2 .middle.middle.3 -side top -expand yes +pack .middle.middle.4 -side top -expand yes -fill x +foreach i {1 2 3} { + label .label$i -textvariable label$i + scale .scale$i -from 0 -to 1000 -length 6c -orient horizontal \ + -command tc_scaleChanged + pack .scale$i .label$i -in .middle.middle.$i -side top -anchor w +} +label .nameLabel -text "Name:" +entry .name -relief sunken -borderwidth 2 -textvariable name -width 10 \ + -font {Courier 12} +pack .nameLabel -in .middle.middle.4 -side left +pack .name -in .middle.middle.4 -side right -expand 1 -fill x +bind .name <Return> {tc_loadNamedColor $name} + +# Create the color display swatch on the right side of the window. + +frame .middle.right +pack .middle.right -side left -pady .25c -padx .25c -anchor s +frame .swatch -width 2c -height 5c -background $color +label .value -textvariable color -width 13 -font {Courier 12} +pack .swatch -in .middle.right -side top -expand yes -fill both +pack .value -in .middle.right -side bottom -pady .25c + +# The procedure below is invoked when one of the scales is adjusted. +# It propagates color information from the current scale readings +# to everywhere else that it is used. + +proc tc_scaleChanged args { + global red green blue colorSpace color updating autoUpdate + if $updating { + return + } + if {$colorSpace == "rgb"} { + set red [format %.0f [expr [.scale1 get]*65.535]] + set green [format %.0f [expr [.scale2 get]*65.535]] + set blue [format %.0f [expr [.scale3 get]*65.535]] + } else { + if {$colorSpace == "cmy"} { + set red [format %.0f [expr {65535 - [.scale1 get]*65.535}]] + set green [format %.0f [expr {65535 - [.scale2 get]*65.535}]] + set blue [format %.0f [expr {65535 - [.scale3 get]*65.535}]] + } else { + set list [hsbToRgb [expr {[.scale1 get]/1000.0}] \ + [expr {[.scale2 get]/1000.0}] \ + [expr {[.scale3 get]/1000.0}]] + set red [lindex $list 0] + set green [lindex $list 1] + set blue [lindex $list 2] + } + } + set color [format "#%04x%04x%04x" $red $green $blue] + .swatch config -bg $color + if $autoUpdate doUpdate + update idletasks +} + +# The procedure below is invoked to update the scales from the +# current red, green, and blue intensities. It's invoked after +# a change in the color space and after a named color value has +# been loaded. + +proc tc_setScales {} { + global red green blue colorSpace updating + set updating 1 + if {$colorSpace == "rgb"} { + .scale1 set [format %.0f [expr $red/65.535]] + .scale2 set [format %.0f [expr $green/65.535]] + .scale3 set [format %.0f [expr $blue/65.535]] + } else { + if {$colorSpace == "cmy"} { + .scale1 set [format %.0f [expr (65535-$red)/65.535]] + .scale2 set [format %.0f [expr (65535-$green)/65.535]] + .scale3 set [format %.0f [expr (65535-$blue)/65.535]] + } else { + set list [rgbToHsv $red $green $blue] + .scale1 set [format %.0f [expr {[lindex $list 0] * 1000.0}]] + .scale2 set [format %.0f [expr {[lindex $list 1] * 1000.0}]] + .scale3 set [format %.0f [expr {[lindex $list 2] * 1000.0}]] + } + } + set updating 0 +} + +# The procedure below is invoked when a named color has been +# selected from the listbox or typed into the entry. It loads +# the color into the editor. + +proc tc_loadNamedColor name { + global red green blue color autoUpdate + + if {[string index $name 0] != "#"} { + set list [winfo rgb .swatch $name] + set red [lindex $list 0] + set green [lindex $list 1] + set blue [lindex $list 2] + } else { + case [string length $name] { + 4 {set format "#%1x%1x%1x"; set shift 12} + 7 {set format "#%2x%2x%2x"; set shift 8} + 10 {set format "#%3x%3x%3x"; set shift 4} + 13 {set format "#%4x%4x%4x"; set shift 0} + default {error "syntax error in color name \"$name\""} + } + if {[scan $name $format red green blue] != 3} { + error "syntax error in color name \"$name\"" + } + set red [expr $red<<$shift] + set green [expr $green<<$shift] + set blue [expr $blue<<$shift] + } + tc_setScales + set color [format "#%04x%04x%04x" $red $green $blue] + .swatch config -bg $color + if $autoUpdate doUpdate +} + +# The procedure below is invoked when a new color space is selected. +# It changes the labels on the scales and re-loads the scales with +# the appropriate values for the current color in the new color space + +proc changeColorSpace space { + global label1 label2 label3 + if {$space == "rgb"} { + set label1 Red + set label2 Green + set label3 Blue + tc_setScales + return + } + if {$space == "cmy"} { + set label1 Cyan + set label2 Magenta + set label3 Yellow + tc_setScales + return + } + if {$space == "hsb"} { + set label1 Hue + set label2 Saturation + set label3 Brightness + tc_setScales + return + } +} + +# The procedure below converts an RGB value to HSB. It takes red, green, +# and blue components (0-65535) as arguments, and returns a list containing +# HSB components (floating-point, 0-1) as result. The code here is a copy +# of the code on page 615 of "Fundamentals of Interactive Computer Graphics" +# by Foley and Van Dam. + +proc rgbToHsv {red green blue} { + if {$red > $green} { + set max $red.0 + set min $green.0 + } else { + set max $green.0 + set min $red.0 + } + if {$blue > $max} { + set max $blue.0 + } else { + if {$blue < $min} { + set min $blue.0 + } + } + set range [expr $max-$min] + if {$max == 0} { + set sat 0 + } else { + set sat [expr {($max-$min)/$max}] + } + if {$sat == 0} { + set hue 0 + } else { + set rc [expr {($max - $red)/$range}] + set gc [expr {($max - $green)/$range}] + set bc [expr {($max - $blue)/$range}] + if {$red == $max} { + set hue [expr {.166667*($bc - $gc)}] + } else { + if {$green == $max} { + set hue [expr {.166667*(2 + $rc - $bc)}] + } else { + set hue [expr {.166667*(4 + $gc - $rc)}] + } + } + if {$hue < 0.0} { + set hue [expr $hue + 1.0] + } + } + return [list $hue $sat [expr {$max/65535}]] +} + +# The procedure below converts an HSB value to RGB. It takes hue, saturation, +# and value components (floating-point, 0-1.0) as arguments, and returns a +# list containing RGB components (integers, 0-65535) as result. The code +# here is a copy of the code on page 616 of "Fundamentals of Interactive +# Computer Graphics" by Foley and Van Dam. + +proc hsbToRgb {hue sat value} { + set v [format %.0f [expr 65535.0*$value]] + if {$sat == 0} { + return "$v $v $v" + } else { + set hue [expr $hue*6.0] + if {$hue >= 6.0} { + set hue 0.0 + } + scan $hue. %d i + set f [expr $hue-$i] + set p [format %.0f [expr {65535.0*$value*(1 - $sat)}]] + set q [format %.0f [expr {65535.0*$value*(1 - ($sat*$f))}]] + set t [format %.0f [expr {65535.0*$value*(1 - ($sat*(1 - $f)))}]] + case $i \ + 0 {return "$v $t $p"} \ + 1 {return "$q $v $p"} \ + 2 {return "$p $v $t"} \ + 3 {return "$p $q $v"} \ + 4 {return "$t $p $v"} \ + 5 {return "$v $p $q"} + error "i value $i is out of range" + } +} + +# The procedure below is invoked when the "Update" button is pressed, +# and whenever the color changes if update mode is enabled. It +# propagates color information as determined by the command in the +# Command entry. + +proc doUpdate {} { + global color command + set newCmd $command + regsub -all %% $command $color newCmd + eval $newCmd +} + +changeColorSpace hsb diff --git a/library/demos/text.tcl b/library/demos/text.tcl new file mode 100644 index 0000000..97df780 --- /dev/null +++ b/library/demos/text.tcl @@ -0,0 +1,76 @@ +# text.tcl -- +# +# This demonstration script creates a text widget that describes +# the basic editing functions. +# +# SCCS: @(#) text.tcl 1.6 97/03/02 16:28:12 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .text +catch {destroy $w} +toplevel $w +wm title $w "Text Demonstration - Basic Facilities" +wm iconname $w "text" +positionWindow $w + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +text $w.text -relief sunken -bd 2 -yscrollcommand "$w.scroll set" -setgrid 1 \ + -height 30 +scrollbar $w.scroll -command "$w.text yview" +pack $w.scroll -side right -fill y +pack $w.text -expand yes -fill both +$w.text insert 0.0 \ +{This window is a text widget. It displays one or more lines of text +and allows you to edit the text. Here is a summary of the things you +can do to a text widget: + +1. Scrolling. Use the scrollbar to adjust the view in the text window. + +2. Scanning. Press mouse button 2 in the text window and drag up or down. +This will drag the text at high speed to allow you to scan its contents. + +3. Insert text. Press mouse button 1 to set the insertion cursor, then +type text. What you type will be added to the widget. + +4. Select. Press mouse button 1 and drag to select a range of characters. +Once you've released the button, you can adjust the selection by pressing +button 1 with the shift key down. This will reset the end of the +selection nearest the mouse cursor and you can drag that end of the +selection by dragging the mouse before releasing the mouse button. +You can double-click to select whole words or triple-click to select +whole lines. + +5. Delete and replace. To delete text, select the characters you'd like +to delete and type Backspace or Delete. Alternatively, you can type new +text, in which case it will replace the selected text. + +6. Copy the selection. To copy the selection into this window, select +what you want to copy (either here or in another application), then +click button 2 to copy the selection to the point of the mouse cursor. + +7. Edit. Text widgets support the standard Motif editing characters +plus many Emacs editing characters. Backspace and Control-h erase the +character to the left of the insertion cursor. Delete and Control-d +erase the character to the right of the insertion cursor. Meta-backspace +deletes the word to the left of the insertion cursor, and Meta-d deletes +the word to the right of the insertion cursor. Control-k deletes from +the insertion cursor to the end of the line, or it deletes the newline +character if that is the only thing left on the line. Control-o opens +a new line by inserting a newline character to the right of the insertion +cursor. Control-t transposes the two characters on either side of the +insertion cursor. + +7. Resize the window. This widget has been configured with the "setGrid" +option on, so that if you resize the window it will always resize to an +even number of characters high and wide. Also, if you make the window +narrow you can see that long lines automatically wrap around onto +additional lines so that all the information is always visible.} +$w.text mark set insert 0.0 diff --git a/library/demos/timer b/library/demos/timer new file mode 100644 index 0000000..b2edd11 --- /dev/null +++ b/library/demos/timer @@ -0,0 +1,40 @@ +#!/bin/sh +# the next line restarts using wish \ +exec wish "$0" "$@" + +# timer -- +# This script generates a counter with start and stop buttons. +# +# SCCS: @(#) timer 1.6 96/02/16 10:49:20 + +label .counter -text 0.00 -relief raised -width 10 +button .start -text Start -command { + if $stopped { + set stopped 0 + tick + } +} +button .stop -text Stop -command {set stopped 1} +pack .counter -side bottom -fill both +pack .start -side left -fill both -expand yes +pack .stop -side right -fill both -expand yes + +set seconds 0 +set hundredths 0 +set stopped 1 + +proc tick {} { + global seconds hundredths stopped + if $stopped return + after 50 tick + set hundredths [expr $hundredths+5] + if {$hundredths >= 100} { + set hundredths 0 + set seconds [expr $seconds+1] + } + .counter config -text [format "%d.%02d" $seconds $hundredths] +} + +bind . <Control-c> {destroy .} +bind . <Control-q> {destroy .} +focus . diff --git a/library/demos/twind.tcl b/library/demos/twind.tcl new file mode 100644 index 0000000..75e732c --- /dev/null +++ b/library/demos/twind.tcl @@ -0,0 +1,196 @@ +# twind.tcl -- +# +# This demonstration script creates a text widget with a bunch of +# embedded windows. +# +# SCCS: @(#) twind.tcl 1.7 97/03/02 16:28:22 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .twind +catch {destroy $w} +toplevel $w +wm title $w "Text Demonstration - Embedded Windows" +wm iconname $w "Embedded Windows" +positionWindow $w + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.f -highlightthickness 2 -borderwidth 2 -relief sunken +set t $w.f.text +text $t -yscrollcommand "$w.scroll set" -setgrid true -font $font -width 70 \ + -height 35 -wrap word -highlightthickness 0 -borderwidth 0 +pack $t -expand yes -fill both +scrollbar $w.scroll -command "$t yview" +pack $w.scroll -side right -fill y +pack $w.f -expand yes -fill both +$t tag configure center -justify center -spacing1 5m -spacing3 5m +$t tag configure buttons -lmargin1 1c -lmargin2 1c -rmargin 1c \ + -spacing1 3m -spacing2 0 -spacing3 0 + +button $t.on -text "Turn On" -command "textWindOn $w" \ + -cursor top_left_arrow +button $t.off -text "Turn Off" -command "textWindOff $w" \ + -cursor top_left_arrow +button $t.click -text "Click Here" -command "textWindPlot $t" \ + -cursor top_left_arrow +button $t.delete -text "Delete" -command "textWindDel $w" \ + -cursor top_left_arrow + +$t insert end "A text widget can contain other widgets embedded " +$t insert end "it. These are called \"embedded windows\", " +$t insert end "and they can consist of arbitrary widgets. " +$t insert end "For example, here are two embedded button " +$t insert end "widgets. You can click on the first button to " +$t window create end -window $t.on +$t insert end " horizontal scrolling, which also turns off " +$t insert end "word wrapping. Or, you can click on the second " +$t insert end "button to\n" +$t window create end -window $t.off +$t insert end " horizontal scrolling and turn back on word wrapping.\n\n" + +$t insert end "Or, here is another example. If you " +$t window create end -window $t.click +$t insert end " a canvas displaying an x-y plot will appear right here." +$t mark set plot insert +$t mark gravity plot left +$t insert end " You can drag the data points around with the mouse, " +$t insert end "or you can click here to " +$t window create end -window $t.delete +$t insert end " the plot again.\n\n" + +$t insert end "You may also find it useful to put embedded windows in " +$t insert end "a text without any actual text. In this case the " +$t insert end "text widget acts like a geometry manager. For " +$t insert end "example, here is a collection of buttons laid out " +$t insert end "neatly into rows by the text widget. These buttons " +$t insert end "can be used to change the background color of the " +$t insert end "text widget (\"Default\" restores the color to " +$t insert end "its default). If you click on the button labeled " +$t insert end "\"Short\", it changes to a longer string so that " +$t insert end "you can see how the text widget automatically " +$t insert end "changes the layout. Click on the button again " +$t insert end "to restore the short string.\n" + +button $t.default -text Default -command "embDefBg $t" \ + -cursor top_left_arrow +$t window create end -window $t.default -padx 3 +global embToggle +set embToggle Short +checkbutton $t.toggle -textvariable embToggle -indicatoron 0 \ + -variable embToggle -onvalue "A much longer string" \ + -offvalue "Short" -cursor top_left_arrow -pady 5 -padx 2 +$t window create end -window $t.toggle -padx 3 -pady 2 +set i 1 +foreach color {AntiqueWhite3 Bisque1 Bisque2 Bisque3 Bisque4 + SlateBlue3 RoyalBlue1 SteelBlue2 DeepSkyBlue3 LightBlue1 + DarkSlateGray1 Aquamarine2 DarkSeaGreen2 SeaGreen1 + Yellow1 IndianRed1 IndianRed2 Tan1 Tan4} { + button $t.color$i -text $color -cursor top_left_arrow -command \ + "$t configure -bg $color" + $t window create end -window $t.color$i -padx 3 -pady 2 + incr i +} +$t tag add buttons $t.default end + +proc textWindOn w { + catch {destroy $w.scroll2} + set t $w.f.text + scrollbar $w.scroll2 -orient horizontal -command "$t xview" + pack $w.scroll2 -after $w.buttons -side bottom -fill x + $t configure -xscrollcommand "$w.scroll2 set" -wrap none +} + +proc textWindOff w { + catch {destroy $w.scroll2} + set t $w.f.text + $t configure -xscrollcommand {} -wrap word +} + +proc textWindPlot t { + set c $t.c + if [winfo exists $c] { + return + } + canvas $c -relief sunken -width 450 -height 300 -cursor top_left_arrow + + set font {Helvetica 18} + + $c create line 100 250 400 250 -width 2 + $c create line 100 250 100 50 -width 2 + $c create text 225 20 -text "A Simple Plot" -font $font -fill brown + + for {set i 0} {$i <= 10} {incr i} { + set x [expr {100 + ($i*30)}] + $c create line $x 250 $x 245 -width 2 + $c create text $x 254 -text [expr 10*$i] -anchor n -font $font + } + for {set i 0} {$i <= 5} {incr i} { + set y [expr {250 - ($i*40)}] + $c create line 100 $y 105 $y -width 2 + $c create text 96 $y -text [expr $i*50].0 -anchor e -font $font + } + + foreach point {{12 56} {20 94} {33 98} {32 120} {61 180} + {75 160} {98 223}} { + set x [expr {100 + (3*[lindex $point 0])}] + set y [expr {250 - (4*[lindex $point 1])/5}] + set item [$c create oval [expr $x-6] [expr $y-6] \ + [expr $x+6] [expr $y+6] -width 1 -outline black \ + -fill SkyBlue2] + $c addtag point withtag $item + } + + $c bind point <Any-Enter> "$c itemconfig current -fill red" + $c bind point <Any-Leave> "$c itemconfig current -fill SkyBlue2" + $c bind point <1> "embPlotDown $c %x %y" + $c bind point <ButtonRelease-1> "$c dtag selected" + bind $c <B1-Motion> "embPlotMove $c %x %y" + while {[string first [$t get plot] " \t\n"] >= 0} { + $t delete plot + } + $t insert plot "\n" + $t window create plot -window $c + $t tag add center plot + $t insert plot "\n" +} + +set embPlot(lastX) 0 +set embPlot(lastY) 0 + +proc embPlotDown {w x y} { + global embPlot + $w dtag selected + $w addtag selected withtag current + $w raise current + set embPlot(lastX) $x + set embPlot(lastY) $y +} + +proc embPlotMove {w x y} { + global embPlot + $w move selected [expr $x-$embPlot(lastX)] [expr $y-$embPlot(lastY)] + set embPlot(lastX) $x + set embPlot(lastY) $y +} + +proc textWindDel w { + set t $w.f.text + if [winfo exists $t.c] { + $t delete $t.c + while {[string first [$t get plot] " \t\n"] >= 0} { + $t delete plot + } + $t insert plot " " + } +} + +proc embDefBg t { + $t configure -background [lindex [$t configure -background] 3] +} diff --git a/library/demos/vscale.tcl b/library/demos/vscale.tcl new file mode 100644 index 0000000..ed78ac0 --- /dev/null +++ b/library/demos/vscale.tcl @@ -0,0 +1,48 @@ +# vscale.tcl -- +# +# This demonstration script shows an example with a vertical scale. +# +# SCCS: @(#) vscale.tcl 1.4 97/03/02 16:28:34 + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +set w .vscale +catch {destroy $w} +toplevel $w +wm title $w "Vertical Scale Demonstration" +wm iconname $w "vscale" +positionWindow $w + +label $w.msg -font $font -wraplength 3.5i -justify left -text "An arrow and a vertical scale are displayed below. If you click or drag mouse button 1 in the scale, you can change the size of the arrow." +pack $w.msg -side top -padx .5c + +frame $w.buttons +pack $w.buttons -side bottom -fill x -pady 2m +button $w.buttons.dismiss -text Dismiss -command "destroy $w" +button $w.buttons.code -text "See Code" -command "showCode $w" +pack $w.buttons.dismiss $w.buttons.code -side left -expand 1 + +frame $w.frame -borderwidth 10 +pack $w.frame + +scale $w.frame.scale -orient vertical -length 284 -from 0 -to 250 \ + -command "setHeight $w.frame.canvas" -tickinterval 50 +canvas $w.frame.canvas -width 50 -height 50 -bd 0 -highlightthickness 0 +$w.frame.canvas create polygon 0 0 1 1 2 2 -fill SeaGreen3 -tags poly +$w.frame.canvas create line 0 0 1 1 2 2 0 0 -fill black -tags line +frame $w.frame.right -borderwidth 15 +pack $w.frame.scale -side left -anchor ne +pack $w.frame.canvas -side left -anchor nw -fill y +$w.frame.scale set 75 + +proc setHeight {w height} { + incr height 21 + set y2 [expr $height - 30] + if {$y2 < 21} { + set y2 21 + } + $w coords poly 15 20 35 20 35 $y2 45 $y2 25 $height 5 $y2 15 $y2 15 20 + $w coords line 15 20 35 20 35 $y2 45 $y2 25 $height 5 $y2 15 $y2 15 20 +} diff --git a/library/demos/widget b/library/demos/widget new file mode 100644 index 0000000..05c89cd --- /dev/null +++ b/library/demos/widget @@ -0,0 +1,391 @@ +#!/bin/sh +# the next line restarts using wish \ +exec wish "$0" "$@" + +# widget -- +# This script demonstrates the various widgets provided by Tk, +# along with many of the features of the Tk toolkit. This file +# only contains code to generate the main window for the +# application, which invokes individual demonstrations. The +# code for the actual demonstrations is contained in separate +# ".tcl" files is this directory, which are sourced by this script +# as needed. +# +# SCCS: @(#) widget 1.35 97/07/19 15:42:22 + +eval destroy [winfo child .] +wm title . "Widget Demonstration" +set widgetDemo 1 + +#---------------------------------------------------------------- +# The code below create the main window, consisting of a menu bar +# and a text widget that explains how to use the program, plus lists +# all of the demos as hypertext items. +#---------------------------------------------------------------- + +set font {Helvetica 14} +menu .menuBar -tearoff 0 +.menuBar add cascade -menu .menuBar.file -label "File" -underline 0 +menu .menuBar.file -tearoff 0 + +# On the Mac use the specia .apple menu for the about item +if {$tcl_platform(platform) == "macintosh"} { + .menuBar add cascade -menu .menuBar.apple + menu .menuBar.apple -tearoff 0 + .menuBar.apple add command -label "About..." -command "aboutBox" +} else { + .menuBar.file add command -label "About..." -command "aboutBox" \ + -underline 0 -accelerator "<F1>" + .menuBar.file add sep +} + +.menuBar.file add command -label "Quit" -command "exit" -underline 0 \ + -accelerator "Meta-Q" +. configure -menu .menuBar +bind . <F1> aboutBox + +frame .statusBar +label .statusBar.lab -text " " -relief sunken -bd 1 \ + -font -*-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* -anchor w +label .statusBar.foo -width 8 -relief sunken -bd 1 \ + -font -*-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* -anchor w +pack .statusBar.lab -side left -padx 2 -expand yes -fill both +pack .statusBar.foo -side left -padx 2 +pack .statusBar -side bottom -fill x -pady 2 + +frame .textFrame +scrollbar .s -orient vertical -command {.t yview} -highlightthickness 0 \ + -takefocus 1 +pack .s -in .textFrame -side right -fill y +text .t -yscrollcommand {.s set} -wrap word -width 60 -height 30 -font $font \ + -setgrid 1 -highlightthickness 0 -padx 4 -pady 2 -takefocus 0 +pack .t -in .textFrame -expand y -fill both -padx 1 +pack .textFrame -expand yes -fill both + +# Create a bunch of tags to use in the text widget, such as those for +# section titles and demo descriptions. Also define the bindings for +# tags. + +.t tag configure title -font {Helvetica 18 bold} + +# We put some "space" characters to the left and right of each demo description +# so that the descriptions are highlighted only when the mouse cursor +# is right over them (but not when the cursor is to their left or right) +# +.t tag configure demospace -lmargin1 1c -lmargin2 1c + + +if {[winfo depth .] == 1} { + .t tag configure demo -lmargin1 1c -lmargin2 1c \ + -underline 1 + .t tag configure visited -lmargin1 1c -lmargin2 1c \ + -underline 1 + .t tag configure hot -background black -foreground white +} else { + .t tag configure demo -lmargin1 1c -lmargin2 1c \ + -foreground blue -underline 1 + .t tag configure visited -lmargin1 1c -lmargin2 1c \ + -foreground #303080 -underline 1 + .t tag configure hot -foreground red -underline 1 +} +.t tag bind demo <ButtonRelease-1> { + invoke [.t index {@%x,%y}] +} +set lastLine "" +.t tag bind demo <Enter> { + set lastLine [.t index {@%x,%y linestart}] + .t tag add hot "$lastLine +1 chars" "$lastLine lineend -1 chars" + .t config -cursor hand2 + showStatus [.t index {@%x,%y}] +} +.t tag bind demo <Leave> { + .t tag remove hot 1.0 end + .t config -cursor xterm + .statusBar.lab config -text "" +} +.t tag bind demo <Motion> { + set newLine [.t index {@%x,%y linestart}] + if {[string compare $newLine $lastLine] != 0} { + .t tag remove hot 1.0 end + set lastLine $newLine + + set tags [.t tag names {@%x,%y}] + set i [lsearch -glob $tags demo-*] + if {$i >= 0} { + .t tag add hot "$lastLine +1 chars" "$lastLine lineend -1 chars" + } + } + showStatus [.t index {@%x,%y}] +} + +# Create the text for the text widget. + +.t insert end "Tk Widget Demonstrations\n" title +.t insert end { +This application provides a front end for several short scripts that demonstrate what you can do with Tk widgets. Each of the numbered lines below describes a demonstration; you can click on it to invoke the demonstration. Once the demonstration window appears, you can click the "See Code" button to see the Tcl/Tk code that created the demonstration. If you wish, you can edit the code and click the "Rerun Demo" button in the code window to reinvoke the demonstration with the modified code. + +} +.t insert end "Labels, buttons, checkbuttons, and radiobuttons" title +.t insert end " \n " {demospace} +.t insert end "1. Labels (text and bitmaps)." {demo demo-label} +.t insert end " \n " {demospace} +.t insert end "2. Buttons." {demo demo-button} +.t insert end " \n " {demospace} +.t insert end "3. Checkbuttons (select any of a group)." {demo demo-check} +.t insert end " \n " {demospace} +.t insert end "4. Radiobuttons (select one of a group)." {demo demo-radio} +.t insert end " \n " {demospace} +.t insert end "5. A 15-puzzle game made out of buttons." {demo demo-puzzle} +.t insert end " \n " {demospace} +.t insert end "6. Iconic buttons that use bitmaps." {demo demo-icon} +.t insert end " \n " {demospace} +.t insert end "7. Two labels displaying images." {demo demo-image1} +.t insert end " \n " {demospace} +.t insert end "8. A simple user interface for viewing images." \ + {demo demo-image2} +.t insert end " \n " {demospace} + +.t insert end \n {} "Listboxes" title +.t insert end " \n " {demospace} +.t insert end "1. 50 states." {demo demo-states} +.t insert end " \n " {demospace} +.t insert end "2. Colors: change the color scheme for the application." \ + {demo demo-colors} +.t insert end " \n " {demospace} +.t insert end "3. A collection of famous sayings." {demo demo-sayings} +.t insert end " \n " {demospace} + +.t insert end \n {} "Entries" title +.t insert end " \n " {demospace} +.t insert end "1. Without scrollbars." {demo demo-entry1} +.t insert end " \n " {demospace} +.t insert end "2. With scrollbars." {demo demo-entry2} +.t insert end " \n " {demospace} +.t insert end "3. Simple Rolodex-like form." {demo demo-form} +.t insert end " \n " {demospace} + +.t insert end \n {} "Text" title +.t insert end " \n " {demospace} +.t insert end "1. Basic editable text." {demo demo-text} +.t insert end " \n " {demospace} +.t insert end "2. Text display styles." {demo demo-style} +.t insert end " \n " {demospace} +.t insert end "3. Hypertext (tag bindings)." {demo demo-bind} +.t insert end " \n " {demospace} +.t insert end "4. A text widget with embedded windows." {demo demo-twind} +.t insert end " \n " {demospace} +.t insert end "5. A search tool built with a text widget." {demo demo-search} +.t insert end " \n " {demospace} + +.t insert end \n {} "Canvases" title +.t insert end " \n " {demospace} +.t insert end "1. The canvas item types." {demo demo-items} +.t insert end " \n " {demospace} +.t insert end "2. A simple 2-D plot." {demo demo-plot} +.t insert end " \n " {demospace} +.t insert end "3. Text items in canvases." {demo demo-ctext} +.t insert end " \n " {demospace} +.t insert end "4. An editor for arrowheads on canvas lines." {demo demo-arrow} +.t insert end " \n " {demospace} +.t insert end "5. A ruler with adjustable tab stops." {demo demo-ruler} +.t insert end " \n " {demospace} +.t insert end "6. A building floor plan." {demo demo-floor} +.t insert end " \n " {demospace} +.t insert end "7. A simple scrollable canvas." {demo demo-cscroll} +.t insert end " \n " {demospace} + +.t insert end \n {} "Scales" title +.t insert end " \n " {demospace} +.t insert end "1. Vertical scale." {demo demo-vscale} +.t insert end " \n " {demospace} +.t insert end "2. Horizontal scale." {demo demo-hscale} +.t insert end " \n " {demospace} + +.t insert end \n {} "Menus" title +.t insert end " \n " {demospace} +.t insert end "1. Menus and cascades." \ + {demo demo-menu} +.t insert end " \n " {demospace} +.t insert end "2. Menubuttons"\ + {demo demo-menubu} +.t insert end " \n " {demospace} + +.t insert end \n {} "Common Dialogs" title +.t insert end " \n " {demospace} +.t insert end "1. Message boxes." {demo demo-msgbox} +.t insert end " \n " {demospace} +.t insert end "2. File selection dialog." {demo demo-filebox} +.t insert end " \n " {demospace} +.t insert end "3. Color picker." {demo demo-clrpick} +.t insert end " \n " {demospace} + +.t insert end \n {} "Miscellaneous" title +.t insert end " \n " {demospace} +.t insert end "1. The built-in bitmaps." {demo demo-bitmap} +.t insert end " \n " {demospace} +.t insert end "2. A dialog box with a local grab." {demo demo-dialog1} +.t insert end " \n " {demospace} +.t insert end "3. A dialog box with a global grab." {demo demo-dialog2} +.t insert end " \n " {demospace} + +.t configure -state disabled +focus .s + +# positionWindow -- +# This procedure is invoked by most of the demos to position a +# new demo window. +# +# Arguments: +# w - The name of the window to position. + +proc positionWindow w { + wm geometry $w +300+300 +} + +# showVars -- +# Displays the values of one or more variables in a window, and +# updates the display whenever any of the variables changes. +# +# Arguments: +# w - Name of new window to create for display. +# args - Any number of names of variables. + +proc showVars {w args} { + catch {destroy $w} + toplevel $w + wm title $w "Variable values" + label $w.title -text "Variable values:" -width 20 -anchor center \ + -font {Helvetica 18} + pack $w.title -side top -fill x + set len 1 + foreach i $args { + if {[string length $i] > $len} { + set len [string length $i] + } + } + foreach i $args { + frame $w.$i + label $w.$i.name -text "$i: " -width [expr $len + 2] -anchor w + label $w.$i.value -textvar $i -anchor w + pack $w.$i.name -side left + pack $w.$i.value -side left -expand 1 -fill x + pack $w.$i -side top -anchor w -fill x + } + button $w.ok -text OK -command "destroy $w" -default active + bind $w <Return> "tkButtonInvoke $w.ok" + pack $w.ok -side bottom -pady 2 +} + +# invoke -- +# This procedure is called when the user clicks on a demo description. +# It is responsible for invoking the demonstration. +# +# Arguments: +# index - The index of the character that the user clicked on. + +proc invoke index { + global tk_library + set tags [.t tag names $index] + set i [lsearch -glob $tags demo-*] + if {$i < 0} { + return + } + set cursor [.t cget -cursor] + .t configure -cursor watch + update + set demo [string range [lindex $tags $i] 5 end] + uplevel [list source [file join $tk_library demos $demo.tcl]] + update + .t configure -cursor $cursor + + .t tag add visited "$index linestart +1 chars" "$index lineend -1 chars" +} + +# showStatus -- +# +# Show the name of the demo program in the status bar. This procedure +# is called when the user moves the cursor over a demo description. +# +proc showStatus index { + global tk_library + set tags [.t tag names $index] + set i [lsearch -glob $tags demo-*] + set cursor [.t cget -cursor] + if {$i < 0} { + .statusBar.lab config -text " " + set newcursor xterm + } else { + set demo [string range [lindex $tags $i] 5 end] + .statusBar.lab config -text "Run the \"$demo\" sample program" + set newcursor hand2 + } + if [string compare $cursor $newcursor] { + .t config -cursor $newcursor + } +} + + +# showCode -- +# This procedure creates a toplevel window that displays the code for +# a demonstration and allows it to be edited and reinvoked. +# +# Arguments: +# w - The name of the demonstration's window, which can be +# used to derive the name of the file containing its code. + +proc showCode w { + global tk_library + set file [string range $w 1 end].tcl + if ![winfo exists .code] { + toplevel .code + frame .code.buttons + pack .code.buttons -side bottom -fill x + button .code.buttons.dismiss -text Dismiss \ + -default active -command "destroy .code" + button .code.buttons.rerun -text "Rerun Demo" -command { + eval [.code.text get 1.0 end] + } + pack .code.buttons.dismiss .code.buttons.rerun -side left \ + -expand 1 -pady 2 + frame .code.frame + pack .code.frame -expand yes -fill both -padx 1 -pady 1 + text .code.text -height 40 -wrap word\ + -xscrollcommand ".code.xscroll set" \ + -yscrollcommand ".code.yscroll set" \ + -setgrid 1 -highlightthickness 0 -pady 2 -padx 3 + scrollbar .code.xscroll -command ".code.text xview" \ + -highlightthickness 0 -orient horizontal + scrollbar .code.yscroll -command ".code.text yview" \ + -highlightthickness 0 -orient vertical + + grid .code.text -in .code.frame -padx 1 -pady 1 \ + -row 0 -column 0 -rowspan 1 -columnspan 1 -sticky news + grid .code.yscroll -in .code.frame -padx 1 -pady 1 \ + -row 0 -column 1 -rowspan 1 -columnspan 1 -sticky news +# grid .code.xscroll -in .code.frame -padx 1 -pady 1 \ +# -row 1 -column 0 -rowspan 1 -columnspan 1 -sticky news + grid rowconfig .code.frame 0 -weight 1 -minsize 0 + grid columnconfig .code.frame 0 -weight 1 -minsize 0 + } else { + wm deiconify .code + raise .code + } + wm title .code "Demo code: [file join $tk_library demos $file]" + wm iconname .code $file + set id [open [file join $tk_library demos $file]] + .code.text delete 1.0 end + .code.text insert 1.0 [read $id] + .code.text mark set insert 1.0 + close $id +} + +# aboutBox -- +# +# Pops up a message box with an "about" message +# +proc aboutBox {} { + tk_messageBox -icon info -type ok -title "About Widget Demo" -message \ +"Tk widget demonstration\n\n\ +Copyright (c) 1996-1997 Sun Microsystems, Inc." +} + diff --git a/library/dialog.tcl b/library/dialog.tcl new file mode 100644 index 0000000..a9fcfa5 --- /dev/null +++ b/library/dialog.tcl @@ -0,0 +1,174 @@ +# dialog.tcl -- +# +# This file defines the procedure tk_dialog, which creates a dialog +# box containing a bitmap, a message, and one or more buttons. +# +# SCCS: @(#) dialog.tcl 1.33 97/06/06 11:20:04 +# +# Copyright (c) 1992-1993 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# +# tk_dialog: +# +# This procedure displays a dialog box, waits for a button in the dialog +# to be invoked, then returns the index of the selected button. If the +# dialog somehow gets destroyed, -1 is returned. +# +# Arguments: +# w - Window to use for dialog top-level. +# title - Title to display in dialog's decorative frame. +# text - Message to display in dialog. +# bitmap - Bitmap to display in dialog (empty string means none). +# default - Index of button that is to display the default ring +# (-1 means none). +# args - One or more strings to display in buttons across the +# bottom of the dialog box. + +proc tk_dialog {w title text bitmap default args} { + global tkPriv tcl_platform + + # 1. Create the top-level window and divide it into top + # and bottom parts. + + catch {destroy $w} + toplevel $w -class Dialog + wm title $w $title + wm iconname $w Dialog + wm protocol $w WM_DELETE_WINDOW { } + + # The following command means that the dialog won't be posted if + # [winfo parent $w] is iconified, but it's really needed; otherwise + # the dialog can become obscured by other windows in the application, + # even though its grab keeps the rest of the application from being used. + + wm transient $w [winfo toplevel [winfo parent $w]] + if {$tcl_platform(platform) == "macintosh"} { + unsupported1 style $w dBoxProc + } + + frame $w.bot + frame $w.top + if {$tcl_platform(platform) == "unix"} { + $w.bot configure -relief raised -bd 1 + $w.top configure -relief raised -bd 1 + } + pack $w.bot -side bottom -fill both + pack $w.top -side top -fill both -expand 1 + + # 2. Fill the top part with bitmap and message (use the option + # database for -wraplength so that it can be overridden by + # the caller). + + option add *Dialog.msg.wrapLength 3i widgetDefault + label $w.msg -justify left -text $text + if {$tcl_platform(platform) == "macintosh"} { + $w.msg configure -font system + } else { + $w.msg configure -font {Times 18} + } + pack $w.msg -in $w.top -side right -expand 1 -fill both -padx 3m -pady 3m + if {$bitmap != ""} { + if {($tcl_platform(platform) == "macintosh") && ($bitmap == "error")} { + set bitmap "stop" + } + label $w.bitmap -bitmap $bitmap + pack $w.bitmap -in $w.top -side left -padx 3m -pady 3m + } + + # 3. Create a row of buttons at the bottom of the dialog. + + set i 0 + foreach but $args { + button $w.button$i -text $but -command "set tkPriv(button) $i" + if {$i == $default} { + $w.button$i configure -default active + } else { + $w.button$i configure -default normal + } + grid $w.button$i -in $w.bot -column $i -row 0 -sticky ew -padx 10 + grid columnconfigure $w.bot $i + # We boost the size of some Mac buttons for l&f + if {$tcl_platform(platform) == "macintosh"} { + set tmp [string tolower $but] + if {($tmp == "ok") || ($tmp == "cancel")} { + grid columnconfigure $w.bot $i -minsize [expr 59 + 20] + } + } + incr i + } + + # 4. Create a binding for <Return> on the dialog if there is a + # default button. + + if {$default >= 0} { + bind $w <Return> " + $w.button$default configure -state active -relief sunken + update idletasks + after 100 + set tkPriv(button) $default + " + } + + # 5. Create a <Destroy> binding for the window that sets the + # button variable to -1; this is needed in case something happens + # that destroys the window, such as its parent window being destroyed. + + bind $w <Destroy> {set tkPriv(button) -1} + + # 6. Withdraw the window, then update all the geometry information + # so we know how big it wants to be, then center the window in the + # display and de-iconify it. + + wm withdraw $w + update idletasks + set x [expr [winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \ + - [winfo vrootx [winfo parent $w]]] + set y [expr [winfo screenheight $w]/2 - [winfo reqheight $w]/2 \ + - [winfo vrooty [winfo parent $w]]] + wm geom $w +$x+$y + wm deiconify $w + + # 7. Set a grab and claim the focus too. + + set oldFocus [focus] + set oldGrab [grab current $w] + if {$oldGrab != ""} { + set grabStatus [grab status $oldGrab] + } + grab $w + if {$default >= 0} { + focus $w.button$default + } else { + focus $w + } + + # 8. Wait for the user to respond, then restore the focus and + # return the index of the selected button. Restore the focus + # before deleting the window, since otherwise the window manager + # may take the focus away so we can't redirect it. Finally, + # restore any grab that was in effect. + + tkwait variable tkPriv(button) + catch {focus $oldFocus} + catch { + # It's possible that the window has already been destroyed, + # hence this "catch". Delete the Destroy handler so that + # tkPriv(button) doesn't get reset by it. + + bind $w <Destroy> {} + destroy $w + } + if {$oldGrab != ""} { + if {$grabStatus == "global"} { + grab -global $oldGrab + } else { + grab $oldGrab + } + } + return $tkPriv(button) +} diff --git a/library/entry.tcl b/library/entry.tcl new file mode 100644 index 0000000..4a0b764 --- /dev/null +++ b/library/entry.tcl @@ -0,0 +1,607 @@ +# entry.tcl -- +# +# This file defines the default bindings for Tk entry widgets and provides +# procedures that help in implementing those bindings. +# +# SCCS: @(#) entry.tcl 1.49 97/09/17 19:08:48 +# +# Copyright (c) 1992-1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +#------------------------------------------------------------------------- +# Elements of tkPriv that are used in this file: +# +# afterId - If non-null, it means that auto-scanning is underway +# and it gives the "after" id for the next auto-scan +# command to be executed. +# mouseMoved - Non-zero means the mouse has moved a significant +# amount since the button went down (so, for example, +# start dragging out a selection). +# pressX - X-coordinate at which the mouse button was pressed. +# selectMode - The style of selection currently underway: +# char, word, or line. +# x, y - Last known mouse coordinates for scanning +# and auto-scanning. +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# The code below creates the default class bindings for entries. +#------------------------------------------------------------------------- + +bind Entry <<Cut>> { + if {![catch {set data [string range [%W get] [%W index sel.first]\ + [expr [%W index sel.last] - 1]]}]} { + clipboard clear -displayof %W + clipboard append -displayof %W $data + %W delete sel.first sel.last + } +} +bind Entry <<Copy>> { + if {![catch {set data [string range [%W get] [%W index sel.first]\ + [expr [%W index sel.last] - 1]]}]} { + clipboard clear -displayof %W + clipboard append -displayof %W $data + } +} +bind Entry <<Paste>> { + global tcl_platform + catch { + if {"$tcl_platform(platform)" != "unix"} { + catch { + %W delete sel.first sel.last + } + } + %W insert insert [selection get -displayof %W -selection CLIPBOARD] + tkEntrySeeInsert %W + } +} +bind Entry <<Clear>> { + %W delete sel.first sel.last +} + +# Standard Motif bindings: + +bind Entry <1> { + tkEntryButton1 %W %x + %W selection clear +} +bind Entry <B1-Motion> { + set tkPriv(x) %x + tkEntryMouseSelect %W %x +} +bind Entry <Double-1> { + set tkPriv(selectMode) word + tkEntryMouseSelect %W %x + catch {%W icursor sel.first} +} +bind Entry <Triple-1> { + set tkPriv(selectMode) line + tkEntryMouseSelect %W %x + %W icursor 0 +} +bind Entry <Shift-1> { + set tkPriv(selectMode) char + %W selection adjust @%x +} +bind Entry <Double-Shift-1> { + set tkPriv(selectMode) word + tkEntryMouseSelect %W %x +} +bind Entry <Triple-Shift-1> { + set tkPriv(selectMode) line + tkEntryMouseSelect %W %x +} +bind Entry <B1-Leave> { + set tkPriv(x) %x + tkEntryAutoScan %W +} +bind Entry <B1-Enter> { + tkCancelRepeat +} +bind Entry <ButtonRelease-1> { + tkCancelRepeat +} +bind Entry <Control-1> { + %W icursor @%x +} +bind Entry <ButtonRelease-2> { + if {!$tkPriv(mouseMoved) || $tk_strictMotif} { + tkEntryPaste %W %x + } +} + +bind Entry <Left> { + tkEntrySetCursor %W [expr [%W index insert] - 1] +} +bind Entry <Right> { + tkEntrySetCursor %W [expr [%W index insert] + 1] +} +bind Entry <Shift-Left> { + tkEntryKeySelect %W [expr [%W index insert] - 1] + tkEntrySeeInsert %W +} +bind Entry <Shift-Right> { + tkEntryKeySelect %W [expr [%W index insert] + 1] + tkEntrySeeInsert %W +} +bind Entry <Control-Left> { + tkEntrySetCursor %W [tkEntryPreviousWord %W insert] +} +bind Entry <Control-Right> { + tkEntrySetCursor %W [tkEntryNextWord %W insert] +} +bind Entry <Shift-Control-Left> { + tkEntryKeySelect %W [tkEntryPreviousWord %W insert] + tkEntrySeeInsert %W +} +bind Entry <Shift-Control-Right> { + tkEntryKeySelect %W [tkEntryNextWord %W insert] + tkEntrySeeInsert %W +} +bind Entry <Home> { + tkEntrySetCursor %W 0 +} +bind Entry <Shift-Home> { + tkEntryKeySelect %W 0 + tkEntrySeeInsert %W +} +bind Entry <End> { + tkEntrySetCursor %W end +} +bind Entry <Shift-End> { + tkEntryKeySelect %W end + tkEntrySeeInsert %W +} + +bind Entry <Delete> { + if [%W selection present] { + %W delete sel.first sel.last + } else { + %W delete insert + } +} +bind Entry <BackSpace> { + tkEntryBackspace %W +} + +bind Entry <Control-space> { + %W selection from insert +} +bind Entry <Select> { + %W selection from insert +} +bind Entry <Control-Shift-space> { + %W selection adjust insert +} +bind Entry <Shift-Select> { + %W selection adjust insert +} +bind Entry <Control-slash> { + %W selection range 0 end +} +bind Entry <Control-backslash> { + %W selection clear +} +bind Entry <KeyPress> { + tkEntryInsert %W %A +} + +# Ignore all Alt, Meta, and Control keypresses unless explicitly bound. +# Otherwise, if a widget binding for one of these is defined, the +# <KeyPress> class binding will also fire and insert the character, +# which is wrong. Ditto for Escape, Return, and Tab. + +bind Entry <Alt-KeyPress> {# nothing} +bind Entry <Meta-KeyPress> {# nothing} +bind Entry <Control-KeyPress> {# nothing} +bind Entry <Escape> {# nothing} +bind Entry <Return> {# nothing} +bind Entry <KP_Enter> {# nothing} +bind Entry <Tab> {# nothing} +if {$tcl_platform(platform) == "macintosh"} { + bind Entry <Command-KeyPress> {# nothing} +} + +bind Entry <Insert> { + catch {tkEntryInsert %W [selection get -displayof %W]} +} + +# Additional emacs-like bindings: + +bind Entry <Control-a> { + if !$tk_strictMotif { + tkEntrySetCursor %W 0 + } +} +bind Entry <Control-b> { + if !$tk_strictMotif { + tkEntrySetCursor %W [expr [%W index insert] - 1] + } +} +bind Entry <Control-d> { + if !$tk_strictMotif { + %W delete insert + } +} +bind Entry <Control-e> { + if !$tk_strictMotif { + tkEntrySetCursor %W end + } +} +bind Entry <Control-f> { + if !$tk_strictMotif { + tkEntrySetCursor %W [expr [%W index insert] + 1] + } +} +bind Entry <Control-h> { + if !$tk_strictMotif { + tkEntryBackspace %W + } +} +bind Entry <Control-k> { + if !$tk_strictMotif { + %W delete insert end + } +} +bind Entry <Control-t> { + if !$tk_strictMotif { + tkEntryTranspose %W + } +} +bind Entry <Meta-b> { + if !$tk_strictMotif { + tkEntrySetCursor %W [tkEntryPreviousWord %W insert] + } +} +bind Entry <Meta-d> { + if !$tk_strictMotif { + %W delete insert [tkEntryNextWord %W insert] + } +} +bind Entry <Meta-f> { + if !$tk_strictMotif { + tkEntrySetCursor %W [tkEntryNextWord %W insert] + } +} +bind Entry <Meta-BackSpace> { + if !$tk_strictMotif { + %W delete [tkEntryPreviousWord %W insert] insert + } +} +bind Entry <Meta-Delete> { + if !$tk_strictMotif { + %W delete [tkEntryPreviousWord %W insert] insert + } +} + +# A few additional bindings of my own. + +bind Entry <2> { + if !$tk_strictMotif { + %W scan mark %x + set tkPriv(x) %x + set tkPriv(y) %y + set tkPriv(mouseMoved) 0 + } +} +bind Entry <B2-Motion> { + if !$tk_strictMotif { + if {abs(%x-$tkPriv(x)) > 2} { + set tkPriv(mouseMoved) 1 + } + %W scan dragto %x + } +} + +# tkEntryClosestGap -- +# Given x and y coordinates, this procedure finds the closest boundary +# between characters to the given coordinates and returns the index +# of the character just after the boundary. +# +# Arguments: +# w - The entry window. +# x - X-coordinate within the window. + +proc tkEntryClosestGap {w x} { + set pos [$w index @$x] + set bbox [$w bbox $pos] + if {($x - [lindex $bbox 0]) < ([lindex $bbox 2]/2)} { + return $pos + } + incr pos +} + +# tkEntryButton1 -- +# This procedure is invoked to handle button-1 presses in entry +# widgets. It moves the insertion cursor, sets the selection anchor, +# and claims the input focus. +# +# Arguments: +# w - The entry window in which the button was pressed. +# x - The x-coordinate of the button press. + +proc tkEntryButton1 {w x} { + global tkPriv + + set tkPriv(selectMode) char + set tkPriv(mouseMoved) 0 + set tkPriv(pressX) $x + $w icursor [tkEntryClosestGap $w $x] + $w selection from insert + if {[lindex [$w configure -state] 4] == "normal"} {focus $w} +} + +# tkEntryMouseSelect -- +# This procedure is invoked when dragging out a selection with +# the mouse. Depending on the selection mode (character, word, +# line) it selects in different-sized units. This procedure +# ignores mouse motions initially until the mouse has moved from +# one character to another or until there have been multiple clicks. +# +# Arguments: +# w - The entry window in which the button was pressed. +# x - The x-coordinate of the mouse. + +proc tkEntryMouseSelect {w x} { + global tkPriv + + set cur [tkEntryClosestGap $w $x] + set anchor [$w index anchor] + if {($cur != $anchor) || (abs($tkPriv(pressX) - $x) >= 3)} { + set tkPriv(mouseMoved) 1 + } + switch $tkPriv(selectMode) { + char { + if $tkPriv(mouseMoved) { + if {$cur < $anchor} { + $w selection range $cur $anchor + } elseif {$cur > $anchor} { + $w selection range $anchor $cur + } else { + $w selection clear + } + } + } + word { + if {$cur < [$w index anchor]} { + set before [tcl_wordBreakBefore [$w get] $cur] + set after [tcl_wordBreakAfter [$w get] [expr $anchor-1]] + } else { + set before [tcl_wordBreakBefore [$w get] $anchor] + set after [tcl_wordBreakAfter [$w get] [expr $cur - 1]] + } + if {$before < 0} { + set before 0 + } + if {$after < 0} { + set after end + } + $w selection range $before $after + } + line { + $w selection range 0 end + } + } + update idletasks +} + +# tkEntryPaste -- +# This procedure sets the insertion cursor to the current mouse position, +# pastes the selection there, and sets the focus to the window. +# +# Arguments: +# w - The entry window. +# x - X position of the mouse. + +proc tkEntryPaste {w x} { + global tkPriv + + $w icursor [tkEntryClosestGap $w $x] + catch {$w insert insert [selection get -displayof $w]} + if {[lindex [$w configure -state] 4] == "normal"} {focus $w} +} + +# tkEntryAutoScan -- +# This procedure is invoked when the mouse leaves an entry window +# with button 1 down. It scrolls the window left or right, +# depending on where the mouse is, and reschedules itself as an +# "after" command so that the window continues to scroll until the +# mouse moves back into the window or the mouse button is released. +# +# Arguments: +# w - The entry window. + +proc tkEntryAutoScan {w} { + global tkPriv + set x $tkPriv(x) + if {![winfo exists $w]} return + if {$x >= [winfo width $w]} { + $w xview scroll 2 units + tkEntryMouseSelect $w $x + } elseif {$x < 0} { + $w xview scroll -2 units + tkEntryMouseSelect $w $x + } + set tkPriv(afterId) [after 50 tkEntryAutoScan $w] +} + +# tkEntryKeySelect -- +# This procedure is invoked when stroking out selections using the +# keyboard. It moves the cursor to a new position, then extends +# the selection to that position. +# +# Arguments: +# w - The entry window. +# new - A new position for the insertion cursor (the cursor hasn't +# actually been moved to this position yet). + +proc tkEntryKeySelect {w new} { + if ![$w selection present] { + $w selection from insert + $w selection to $new + } else { + $w selection adjust $new + } + $w icursor $new +} + +# tkEntryInsert -- +# Insert a string into an entry at the point of the insertion cursor. +# If there is a selection in the entry, and it covers the point of the +# insertion cursor, then delete the selection before inserting. +# +# Arguments: +# w - The entry window in which to insert the string +# s - The string to insert (usually just a single character) + +proc tkEntryInsert {w s} { + if {$s == ""} { + return + } + catch { + set insert [$w index insert] + if {([$w index sel.first] <= $insert) + && ([$w index sel.last] >= $insert)} { + $w delete sel.first sel.last + } + } + $w insert insert $s + tkEntrySeeInsert $w +} + +# tkEntryBackspace -- +# Backspace over the character just before the insertion cursor. +# If backspacing would move the cursor off the left edge of the +# window, reposition the cursor at about the middle of the window. +# +# Arguments: +# w - The entry window in which to backspace. + +proc tkEntryBackspace w { + if [$w selection present] { + $w delete sel.first sel.last + } else { + set x [expr {[$w index insert] - 1}] + if {$x >= 0} {$w delete $x} + if {[$w index @0] >= [$w index insert]} { + set range [$w xview] + set left [lindex $range 0] + set right [lindex $range 1] + $w xview moveto [expr $left - ($right - $left)/2.0] + } + } +} + +# tkEntrySeeInsert -- +# Make sure that the insertion cursor is visible in the entry window. +# If not, adjust the view so that it is. +# +# Arguments: +# w - The entry window. + +proc tkEntrySeeInsert w { + set c [$w index insert] + set left [$w index @0] + if {$left > $c} { + $w xview $c + return + } + set x [winfo width $w] + while {([$w index @$x] <= $c) && ($left < $c)} { + incr left + $w xview $left + } +} + +# tkEntrySetCursor - +# Move the insertion cursor to a given position in an entry. Also +# clears the selection, if there is one in the entry, and makes sure +# that the insertion cursor is visible. +# +# Arguments: +# w - The entry window. +# pos - The desired new position for the cursor in the window. + +proc tkEntrySetCursor {w pos} { + $w icursor $pos + $w selection clear + tkEntrySeeInsert $w +} + +# tkEntryTranspose - +# This procedure implements the "transpose" function for entry widgets. +# It tranposes the characters on either side of the insertion cursor, +# unless the cursor is at the end of the line. In this case it +# transposes the two characters to the left of the cursor. In either +# case, the cursor ends up to the right of the transposed characters. +# +# Arguments: +# w - The entry window. + +proc tkEntryTranspose w { + set i [$w index insert] + if {$i < [$w index end]} { + incr i + } + set first [expr $i-2] + if {$first < 0} { + return + } + set new [string index [$w get] [expr $i-1]][string index [$w get] $first] + $w delete $first $i + $w insert insert $new + tkEntrySeeInsert $w +} + +# tkEntryNextWord -- +# Returns the index of the next word position after a given position in the +# entry. The next word is platform dependent and may be either the next +# end-of-word position or the next start-of-word position after the next +# end-of-word position. +# +# Arguments: +# w - The entry window in which the cursor is to move. +# start - Position at which to start search. + +if {$tcl_platform(platform) == "windows"} { + proc tkEntryNextWord {w start} { + set pos [tcl_endOfWord [$w get] [$w index $start]] + if {$pos >= 0} { + set pos [tcl_startOfNextWord [$w get] $pos] + } + if {$pos < 0} { + return end + } + return $pos + } +} else { + proc tkEntryNextWord {w start} { + set pos [tcl_endOfWord [$w get] [$w index $start]] + if {$pos < 0} { + return end + } + return $pos + } +} + +# tkEntryPreviousWord -- +# +# Returns the index of the previous word position before a given +# position in the entry. +# +# Arguments: +# w - The entry window in which the cursor is to move. +# start - Position at which to start search. + +proc tkEntryPreviousWord {w start} { + set pos [tcl_startOfPreviousWord [$w get] [$w index $start]] + if {$pos < 0} { + return 0 + } + return $pos +} + diff --git a/library/focus.tcl b/library/focus.tcl new file mode 100644 index 0000000..bf0476d --- /dev/null +++ b/library/focus.tcl @@ -0,0 +1,180 @@ +# focus.tcl -- +# +# This file defines several procedures for managing the input +# focus. +# +# SCCS: @(#) focus.tcl 1.17 96/02/16 10:48:21 +# +# Copyright (c) 1994-1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# tk_focusNext -- +# This procedure returns the name of the next window after "w" in +# "focus order" (the window that should receive the focus next if +# Tab is typed in w). "Next" is defined by a pre-order search +# of a top-level and its non-top-level descendants, with the stacking +# order determining the order of siblings. The "-takefocus" options +# on windows determine whether or not they should be skipped. +# +# Arguments: +# w - Name of a window. + +proc tk_focusNext w { + set cur $w + while 1 { + + # Descend to just before the first child of the current widget. + + set parent $cur + set children [winfo children $cur] + set i -1 + + # Look for the next sibling that isn't a top-level. + + while 1 { + incr i + if {$i < [llength $children]} { + set cur [lindex $children $i] + if {[winfo toplevel $cur] == $cur} { + continue + } else { + break + } + } + + # No more siblings, so go to the current widget's parent. + # If it's a top-level, break out of the loop, otherwise + # look for its next sibling. + + set cur $parent + if {[winfo toplevel $cur] == $cur} { + break + } + set parent [winfo parent $parent] + set children [winfo children $parent] + set i [lsearch -exact $children $cur] + } + if {($cur == $w) || [tkFocusOK $cur]} { + return $cur + } + } +} + +# tk_focusPrev -- +# This procedure returns the name of the previous window before "w" in +# "focus order" (the window that should receive the focus next if +# Shift-Tab is typed in w). "Next" is defined by a pre-order search +# of a top-level and its non-top-level descendants, with the stacking +# order determining the order of siblings. The "-takefocus" options +# on windows determine whether or not they should be skipped. +# +# Arguments: +# w - Name of a window. + +proc tk_focusPrev w { + set cur $w + while 1 { + + # Collect information about the current window's position + # among its siblings. Also, if the window is a top-level, + # then reposition to just after the last child of the window. + + if {[winfo toplevel $cur] == $cur} { + set parent $cur + set children [winfo children $cur] + set i [llength $children] + } else { + set parent [winfo parent $cur] + set children [winfo children $parent] + set i [lsearch -exact $children $cur] + } + + # Go to the previous sibling, then descend to its last descendant + # (highest in stacking order. While doing this, ignore top-levels + # and their descendants. When we run out of descendants, go up + # one level to the parent. + + while {$i > 0} { + incr i -1 + set cur [lindex $children $i] + if {[winfo toplevel $cur] == $cur} { + continue + } + set parent $cur + set children [winfo children $parent] + set i [llength $children] + } + set cur $parent + if {($cur == $w) || [tkFocusOK $cur]} { + return $cur + } + } +} + +# tkFocusOK -- +# +# This procedure is invoked to decide whether or not to focus on +# a given window. It returns 1 if it's OK to focus on the window, +# 0 if it's not OK. The code first checks whether the window is +# viewable. If not, then it never focuses on the window. Then it +# checks the -takefocus option for the window and uses it if it's +# set. If there's no -takefocus option, the procedure checks to +# see if (a) the widget isn't disabled, and (b) it has some key +# bindings. If all of these are true, then 1 is returned. +# +# Arguments: +# w - Name of a window. + +proc tkFocusOK w { + set code [catch {$w cget -takefocus} value] + if {($code == 0) && ($value != "")} { + if {$value == 0} { + return 0 + } elseif {$value == 1} { + return [winfo viewable $w] + } else { + set value [uplevel #0 $value $w] + if {$value != ""} { + return $value + } + } + } + if {![winfo viewable $w]} { + return 0 + } + set code [catch {$w cget -state} value] + if {($code == 0) && ($value == "disabled")} { + return 0 + } + regexp Key|Focus "[bind $w] [bind [winfo class $w]]" +} + +# tk_focusFollowsMouse -- +# +# If this procedure is invoked, Tk will enter "focus-follows-mouse" +# mode, where the focus is always on whatever window contains the +# mouse. If this procedure isn't invoked, then the user typically +# has to click on a window to give it the focus. +# +# Arguments: +# None. + +proc tk_focusFollowsMouse {} { + set old [bind all <Enter>] + set script { + if {("%d" == "NotifyAncestor") || ("%d" == "NotifyNonlinear") + || ("%d" == "NotifyInferior")} { + if [tkFocusOK %W] { + focus %W + } + } + } + if {$old != ""} { + bind all <Enter> "$old; $script" + } else { + bind all <Enter> $script + } +} diff --git a/library/images/README b/library/images/README new file mode 100644 index 0000000..176b6e2 --- /dev/null +++ b/library/images/README @@ -0,0 +1,12 @@ +README - images directory + +SCCS: @(#) README 1.1 97/08/06 13:19:19 + + +This directory includes images for the Tcl Logo and the Tcl Powered +Logo. Please feel free to use the Tcl Powered Logo on any of your +products that employ the use of Tcl or Tk. The Tcl logo may also be +used to promote Tcl in your product documentation, web site or other +places you so desire. + + diff --git a/library/images/logo100.gif b/library/images/logo100.gif new file mode 100644 index 0000000..fcdfd36 --- /dev/null +++ b/library/images/logo100.gif @@ -0,0 +1,8 @@ +GIF89aDd÷ÿÿÿÿÿÿÌÿÿ™ÿÿfÿÿ3ÿÿÿÌÿÿÌÌÿÌ™ÿÌfÿÌ3ÿÌÿ™ÿÿ™Ìÿ™™ÿ™fÿ™3ÿ™ÿfÿÿfÌÿf™ÿffÿf3ÿfÿ3ÿÿ3Ìÿ3™ÿ3fÿ33ÿ3ÿÿÿÌÿ™ÿfÿ3ÿÌÿÿÌÿÌÌÿ™ÌÿfÌÿ3ÌÿÌÌÿÌÌÌÌÌ™ÌÌfÌÌ3ÌÌÌ™ÿÌ™ÌÌ™™Ì™fÌ™3Ì™ÌfÿÌfÌÌf™ÌffÌf3ÌfÌ3ÿÌ3ÌÌ3™Ì3fÌ33Ì3ÌÿÌÌÌ™ÌfÌ3Ì™ÿÿ™ÿÌ™ÿ™™ÿf™ÿ3™ÿ™Ìÿ™Ì̙̙™Ìf™Ì3™Ì™™ÿ™™Ì™™™™™f™™3™™™fÿ™fÌ™f™™ff™f3™f™3ÿ™3Ì™3™™3f™33™3™ÿ™Ì™™™f™3™fÿÿfÿÌfÿ™fÿffÿ3fÿfÌÿfÌÌfÌ™fÌffÌ3fÌf™ÿf™Ìf™™f™ff™3f™ffÿffÌff™fffff3fff3ÿf3Ìf3™f3ff33f3fÿfÌf™fff3f3ÿÿ3ÿÌ3ÿ™3ÿf3ÿ33ÿ3Ìÿ3ÌÌ3Ì™3Ìf3Ì33Ì3™ÿ3™Ì3™™3™f3™33™3fÿ3fÌ3f™3ff3f33f33ÿ33Ì33™33f333333ÿ3Ì3™3f333ÿÿÿÌÿ™ÿfÿ3ÿÌÿÌÌÌ™ÌfÌ3Ì™ÿ™Ì™™™f™3™fÿfÌf™fff3f3ÿ3Ì3™3f333ÿÌ™f3îÝ»ªˆwUD"îÝ»ªˆwUD"îÝ»ªˆwUD"îîîÝÝÝ»»»ªªªˆˆˆwwwUUUDDD""",DdÿH° Áƒ*\È°¡ÀzöHt@Q†Œ92æpà°ãÀzõ$@@ÑEŒuY¹2ˆË—0c™qÀcB,[ÆÜɳ§Ï ë1qbM2~*]ªÈÆ‹s¨ÌS†@L³jݺ“#¬\Êõ‰àêسhƒ›¶Ö£ÜÊ] +D(€¸m™ëÈ@¼Z÷îܱƒoO¿3=²cÁÁG"(ðØpLíq]°à%ãÉ +[†™ã#¬Ÿ+ïåüXðh—¥ž^¡³ËÈ‚¸~írÁÙK#Gp] Æîzõ¶µ:øÒÐ{Ô°ÝsïFœÇÃzè\)t—ŒWÿr€= Ù·nÐݧôÛ;r§?¢Ã€zOªÔsþ-A¨‰gÕé TÈ8£ ímU9pµeÙQW=¤(¨!2] eß@nõ™n1Yx€= j¨!gÕEPˆÕÆÓ¨¢ŠÎM‹Á¨•cÇñ†8:ƒÌ!;”\‰=aöbX@*YZ†E®ÂÓ¡ÁåN±
4ƒˆòt@E*ÈâN5@Ý€k’VPR5Vbö”é’È¡¦g2òÔ¥@pÁNY¤*³)w›žÃÝVC£;17[‹aéš…(–©cNÁ˜šk5ØUA”GØ¥Šã!œÊ`—ÑÅÿ§Õz_‰x*LP‰ã*ª ãkFW[;=X+Z@¬p£ÎÀ‚m¹”± E_̪ØE°«mõá_Öæ j¶¥å ×£ÄÊd¸g‘ƒ®Ì®ÂzAš.Lˆ¤XXîÂkç!‘)Sù²;–»ËÚ9F=2èukVNt^»9$\fõÐ+`Vʆì²Èø» +I÷úÔ1wÈâHJÂú@¯X’þ––*’OÂV<P²O17—Ö*+Zr cÑŠ²XØ¢!ت¨Oƒ[•e€bIÄ> +®"®ŠV¶e¬@T‡U“=T2øºíüÓ׎u€ +++ˆˆ¬ÈAFÈ®ûdÕO¨ÿHÆ=º®HDÈ"äcÔª®’¬¿÷ðÇãA‡kU¨†Šgª¢=¨ÍSÁÿ‰u„‰×µ,)õÀúøÔž;`…†ûÔ·, ç}ÔJ ¹º‘ˆÐ¹¬ÐN°Þ>ó›ƒ +"“»*Z±¯XßÊ̯ÄIF*à(ÃòbÏ>298£ØsõuìbáÐ9> >å@ à;SçÏÿÓ˜9ÃûY«ß–Ñš9Xô¡?þÝéŽC‹ÑÊ·äCzûSÑ䧹ž,Yü^øT”ƒ—¡¥gwIKäF'ÊÁÆ~J!£ƒåÎrÓ³úÎ⛂¬`:Dg% à#€h9Y©ÿ$„U c ZÐHqC¦ñ`9Â!¡¸zŒnˆay¢ç0s@8£ŠËªBÏ¢E·å!E@ ›ŠV`®´DlRS +&¢°)!̨„ˆÉ)(:kçb- Ü#A‡†dpG<äK…ÄÐ4@dÎ-ƒ„d!óAŠôÍ’‹‹ö––#a9PV×æÒ¼¶Í%‡8Ó\Œ¹è€"0qÙ½€ð´qZ=BŽæÊ_é8åÚ-wâÔ8}ŸƒVL¤"¥`1Ej ÛmæŤî|š3£…¾r©rqJ',ˆ6Mô•—¹ËÎ7µ‘˜<à.ž*WüPÿ˗Ъ=ܼ_"„È<8ñ»Ì±nS®hÒ'ÿ,Q@uc•ÓtÐ3…‰ü<ãq–æ»Wϼ9/ƒ²GQÛœáç~9N~%„é©DPMX53¥Jš4uÓÑrB¨4X„I
=¦$«ÀW8™é‚@¾zxê–ø +Éf£¾vÖ'&#ÈI9¨_,ÁV_âçä$¬YÍLu*ÄV.9¥ž‰ëOþÔÄíæuå-õ¥W¾,¯}%_‹I‚•°\åBë!826-å9ìc³Ùíd*gm¤ƒ¢G²®D#2 ˆDd˜¢ˆD$%)ÉIP¯f6² F<› diff --git a/library/images/logo64.gif b/library/images/logo64.gif new file mode 100644 index 0000000..d967821 --- /dev/null +++ b/library/images/logo64.gif @@ -0,0 +1,2 @@ +GIF89a+@÷ÿÿÿÿÿÿÌÿÿ™ÿÿfÿÿ3ÿÿÿÌÿÿÌÌÿÌ™ÿÌfÿÌ3ÿÌÿ™ÿÿ™Ìÿ™™ÿ™fÿ™3ÿ™ÿfÿÿfÌÿf™ÿffÿf3ÿfÿ3ÿÿ3Ìÿ3™ÿ3fÿ33ÿ3ÿÿÿÌÿ™ÿfÿ3ÿÌÿÿÌÿÌÌÿ™ÌÿfÌÿ3ÌÿÌÌÿÌÌÌÌÌ™ÌÌfÌÌ3ÌÌÌ™ÿÌ™ÌÌ™™Ì™fÌ™3Ì™ÌfÿÌfÌÌf™ÌffÌf3ÌfÌ3ÿÌ3ÌÌ3™Ì3fÌ33Ì3ÌÿÌÌÌ™ÌfÌ3Ì™ÿÿ™ÿÌ™ÿ™™ÿf™ÿ3™ÿ™Ìÿ™Ì̙̙™Ìf™Ì3™Ì™™ÿ™™Ì™™™™™f™™3™™™fÿ™fÌ™f™™ff™f3™f™3ÿ™3Ì™3™™3f™33™3™ÿ™Ì™™™f™3™fÿÿfÿÌfÿ™fÿffÿ3fÿfÌÿfÌÌfÌ™fÌffÌ3fÌf™ÿf™Ìf™™f™ff™3f™ffÿffÌff™fffff3fff3ÿf3Ìf3™f3ff33f3fÿfÌf™fff3f3ÿÿ3ÿÌ3ÿ™3ÿf3ÿ33ÿ3Ìÿ3ÌÌ3Ì™3Ìf3Ì33Ì3™ÿ3™Ì3™™3™f3™33™3fÿ3fÌ3f™3ff3f33f33ÿ33Ì33™33f333333ÿ3Ì3™3f333ÿÿÿÌÿ™ÿfÿ3ÿÌÿÌÌÌ™ÌfÌ3Ì™ÿ™Ì™™™f™3™fÿfÌf™fff3f3ÿ3Ì3™3f333ÿÌ™f3îÝ»ªˆwUD"îÝ»ªˆwUD"îÝ»ªˆwUD"îîîÝÝÝ»»»ªªªˆˆˆwwwUUUDDD""",+@ÿH° Ázö(tpÀ Âõ@à ¢Œ92æФ# AÉÑð¡ÁCª\ɲ%)Z”¡1aË›8s¶´W/¥ÎŸ@ƒÐ3¨ÑœCø¼y$䑦GW긴åŽ5®FU™ƒjÎ;žF(Pc+W¯-ìXD-[³*gÔÁ´F¦`¡:mkT†ÀLw„ÝA/ßuð7pÛa9PïɆq2Xg•G€Ô˃̙3}AKv\dèyL›>”º1Î#õ:ˆ-{UPÑgxvZ¡ŠlÓdTæòYeR2†‡¼WZ6"l*ÆYäÀè9›ÿÉÁÛ´o¡!óÑrª@Å9µ‘Q9|õràÅÙõ½ÎîVg2È<á€Z͵Ôðý šö>d“Uf!ÉåP@¡3« _‚-ù%пyá>(‡aH›€"‡* +˜ÏìÝãŒ@©HJ}2ÐõSI2ÕÔ* R)3¼È‘öp’‡ä#›>UÝœ@EéT’]èa_”åJG ð„‡a"LJ¹’>“ƒ'æ€ÙOî
$§S2x¸J ÞóçYuy¡ƒªˆAõIÔ¡m=a£¦‘r œE©Ó@x>Õ²i™ñx›VBiú<ÿàäJÏé`«¯:3†¬Ö“*‡]8ãju]è×ë¯@å€Ì°¦‘
æ2«Üãá!8«´FAÊ*øxxß©C-N‚©3ÈÈ0ëJ˜ûÓxòŒx:CŠ±@Åx.NÔÝË[>@¼«RŒà}šƒ‡8ÄÖîQ¥lÆ‘²gP& œQúècÜØõ5¶?ÝG[TrN3¸„>鄯´ ³BîÕVsH…$âS,Ý´¢@¼9^ÏA%¢Ð9$]ôÈíÕC×38ÀóS[¡ƒ±“mÄ3ÌeŸ9‹VðØÑ}´tS@ˆ¿ diff --git a/library/images/logoLarge.gif b/library/images/logoLarge.gif new file mode 100644 index 0000000..4e2db80 --- /dev/null +++ b/library/images/logoLarge.gif @@ -0,0 +1,63 @@ +GIF89ab÷ÿÿÿÿÿÿÌÿÿ™ÿÿfÿÿ3ÿÿÿÌÿÿÌÌÿÌ™ÿÌfÿÌ3ÿÌÿ™ÿÿ™Ìÿ™™ÿ™fÿ™3ÿ™ÿfÿÿfÌÿf™ÿffÿf3ÿfÿ3ÿÿ3Ìÿ3™ÿ3fÿ33ÿ3ÿÿÿÌÿ™ÿfÿ3ÿÌÿÿÌÿÌÌÿ™ÌÿfÌÿ3ÌÿÌÌÿÌÌÌÌÌ™ÌÌfÌÌ3ÌÌÌ™ÿÌ™ÌÌ™™Ì™fÌ™3Ì™ÌfÿÌfÌÌf™ÌffÌf3ÌfÌ3ÿÌ3ÌÌ3™Ì3fÌ33Ì3ÌÿÌÌÌ™ÌfÌ3Ì™ÿÿ™ÿÌ™ÿ™™ÿf™ÿ3™ÿ™Ìÿ™Ì̙̙™Ìf™Ì3™Ì™™ÿ™™Ì™™™™™f™™3™™™fÿ™fÌ™f™™ff™f3™f™3ÿ™3Ì™3™™3f™33™3™ÿ™Ì™™™f™3™fÿÿfÿÌfÿ™fÿffÿ3fÿfÌÿfÌÌfÌ™fÌffÌ3fÌf™ÿf™Ìf™™f™ff™3f™ffÿffÌff™fffff3fff3ÿf3Ìf3™f3ff33f3fÿfÌf™fff3f3ÿÿ3ÿÌ3ÿ™3ÿf3ÿ33ÿ3Ìÿ3ÌÌ3Ì™3Ìf3Ì33Ì3™ÿ3™Ì3™™3™f3™33™3fÿ3fÌ3f™3ff3f33f33ÿ33Ì33™33f333333ÿ3Ì3™3f333ÿÿÿÌÿ™ÿfÿ3ÿÌÿÌÌÌ™ÌfÌ3Ì™ÿ™Ì™™™f™3™fÿfÌf™fff3f3ÿ3Ì3™3f333ÿÌ™f3îÝ»ªˆwUD"îÝ»ªˆwUD"îÝ»ªˆwUD"îîîÝÝÝ»»»ªªªˆˆˆwwwUUUDDD""",bÿH° Áƒ*\È°¡Ã‡#JœH±¢Å‹3jÜȱ£Ç 'Ö;pÀÞ(8X‰À^È—0cÊœI³¦Çz8O¦\éàÏ:‚ +Õ$ˆÑ£Fu<8`³©Ó§P£>%I’gOŸCh-„+Ò¯`ÃÕá@ªÙ³hÓÆÄ™³dJ? +K·®Ý»H,UË·¯_¨#홤ºóg¡[ñ*^Ìx±õþJžL!Û“'ÆŠ¸±çÏ =+eZ¹´i™„ynFœ8´ë×°]y|º¶m‚lë
Ö©r5ÑØÀƒ~T/éÛÈk +ÞÍîϬZ‰KŸN]úãɳG¬`$‚Ì+ãÿæ쵺ùóè§Ö~{$I•á}怽|úûøóW'Ë~²ú(à€·W|=Pà‚6HÝc‘!x–‚Vhá…¢(!Fݹ÷Þq Qˆáˆ$–XDÕšù4y‰=Àˆ&Öh£ƒz¹ÔwÜ`OÍùöp2.DãH&)``÷QPzØÜUXÍGTt©Jvée~ë)tYjñ=§ƒ•AÙWbYqùå›pR7[™rÁˆeœa!À›xöéçŸêÙ& „jèp@€ˆ‡6êè£xá¤B@jé¥JÊ£˜vê©Ÿ:4„€šŸ–jª‰¡2t©§¶ê*ƒ©.ÿT«¯Öjë}Z*·öêëp¹&4ë¯ÄlCë첟±É€ÌF+m]‚>;íµØ¥hBÐfëí²Û"Ôí·äþ¡µå¦ÛëC¨ëî«@<tä»ôbëŒõæÛé½Fêë/¤Á*4ï¿ûpB|¬pŸÎî¹ðÃxVë0Ä{)ñ gŒd¸‹jìqTéÇ$cx®ª%§ŒãɬòËê0)Ê0׬¿²Ú¬ó}8/´óÏæ¬ÐDK'tBE'\Ã
)íôk£ûôÔŒE½Ð¸Tg]WÈâ>¼C„ÁZSÇõAXŸºC
`/ Ü×Ä-w]¶p‰F”ö§;„ÿ-wÁõ=÷àußœ:Êëj„Çøàn8l:°Œ¯©‚xlCùä”K4°¥™Ïí6瞧^Àæ ƒÖs¿|/à¹Ý¯í ºê‡vtˆ¥Êþ9l¥ß®yîŸíÞ±§N»k¾?;ñ§˜/÷é¯%/¼Øt¿<ôw1-*ò©ÿ™íÎÓ]ƒùà/&þ¦ž¦Ž=óÎKÞ~hV/D½¥ÚË]lý#ûîǘ¼EÄe–jžé€'<Ö04„e½¸94 +„Üø™Id‚Ž +àü@À¸Ùƒ¡©Ü1•A¦…& +óº…€…ÏsM O8C׉„Wªàÿ=SÁ¸É°‡‹‘ÞA’EAÏm°1%|"£÷CþEîˆwAŸ§%„‰!ü]hDÈEØäOV{+Tÿ¤¨-š‹eEÒH¨þeωq|ÍÙ¸•ÀÆÑÏyÍ»©²/ýãa 33ˆ´«ÊûãܹȻTdt„Rà“ÈJºæ’}ü›$ýçIR“€R éâF–Ò”A埚§ÈÅ´p•$Ú +õåŃ$¬Q´M+éö¥8`EïyÀ.ÝÕKƒì˜¢$!äpé ëèŽïjfAžy¨æQ².Ü$‰hãzÈ2]g„$(ÍáÙˆœùe½Ò©¿PÖ/á¼Ñû"ÿÏw
òxzœ8³¸ETýsKþJÜ +!%Ðv^¯FÚ˜¾,÷êqß‹!KzF$ØÌ– +)bQ5ºˆÓçAÂÍriŠ¤¤;icò9¢ +P4#çœV
²*H¡šH)è…"jT¡ +zÐCª°‚m•Ô[;eˆ=BÚ'ÁÕ(Ú»gši*‚ΫX±Š. h 9VD 2Õ>^5½Ð>r@ c¬xë‚ ƒã´Ô[kH[!yUë½õ<HÀš×ƆõEqUÕjöÑ3Y½PbWÀXÇzVd›Òº¬Ä*d²xbœghê ÚžíX÷Z–žÿ¢ó"¨ØcØ +Íu U¸«l‡ëÈ2%·ÆZ)ÚH7P±dÖAÆ{-q§KÖ˜S]Ê5ráÔÜ°Ä•AÆ«uÇ«Š*<UZ¤È#9ÓH‚WLz¯|‘F‘ÞTq ¤f+»‹+…Ø£³ò¥n¬ÚoyÐ"¤Õ-5µ—ÑóŒô ‹
p€IQÐ# †Ó¨™Áÿ襖°ˆóPÜ_$Ãpjð~‹·‘XÄFÆ!ÈX‚ øM¾Ës ”¿zÀÆÞÇ2‹UãôÓUßÐ|d «bÈDÆÈ‘[•A'ùo“%\`rýÖ!SÆ ô`¶xËÓí²—¥ì«ë'ÿ½‚=3š‡»Wu™V!=U’óc5ÎÎy¼3Vœ'bÛZõ6KYÁŸÉee
Z"£ºÕ~Ô3-/:Íï*3E"m+7ßgЖ¾4é¥iB7úQ{NøB-êØ:ӱǩUeýŒÉ–í*f¬¨:IJ†szgç:¶jv—¯‘µÝFMšÏyñ±=[çzy õhö¡œŸ€‰wÚžÕ‡¿®-lwzp9F¦W \pçõÉ]²ò}¾ümJ“òöÌÅê!gw‡5Ù6ê›Ø6Œ!z;ÄÞ…vЊíïƾZI¥›…î|µ`/0=pþvÃÇ*ä7
s
FOv ¹8w¢'X÷ÿØx^^¯µmà:ôœVñ3ò徊Ûê.¿U>Ûô|
†®
gžžÜ¸PøN¢¤ÍsÈžléã/+å· £×J“éA9ÏÅjáól¸ˆ&ÇlêBn«¿ +ëçIïηîŒjߧ„ºÌóíše;äè€ +ÙuW¦«üáøºÜbî¹tƒi#a¾T+
/ô*ší]×Ï0Ý{>î]8äHž1UÊS'XÆæ¹Ûõ#øÈÛòʼ@oŹ¥ýdo:¯ƒSzyðòKCüÍ/^†ç‘ÜP»â8Ç•'i Àžím_Pçq÷ã¨æ";;ó{è«‚A“úÿ(Ù) …^ä¼—Rå~ê÷³\òª;>R<ŸFZý¡$ÿtrevÿ½Aá·:vùbëDLr"íçoð~ªCwÚCwd€ŽqÕQfÆvï á'u:Æ{dv_á*H“lx~ò7ÛGi‚Þô lå
|Ĭ#~JVĉF1h
{7z"BØ9èª7(87O'Óoච+BF±á;EQ(³ç'nT…_‘+HØp8 ¨×…tc† ‘|RS*Z$‚Ÿ!1X8m.賡=á†)Å@¸ rXqjwÄñ`§r<èÆÿôçR±!sÀÁ8vh…xZCˆˆÇ2¡×pJhJñ(g“÷…F6p(HqŠx¢Eª˜'Ø–‡¹ö}Š&ê$L9ô׊®ÈxWUÑ4–†î¶†I¡!tÑI]8‹±Al¸‰qÃx`HŸèn{h ™hnrG€ ñ5r`f'fo(Õb[÷~@à&ØÃxKœc!¥vbC(;D÷ñ\M'@@c ¤@ +€GµñH›gw(ØËúXvžÈˆ^yÃeLe‚
Ykt(a¸zù¨€Ãá,õ {¹"Faæ7…EX(% !ÿ™InjӦ +ª0gÈ–Ž«¥pr“9Ikƒˆ7a‹Ð7^«p6Ç[©ö'K MÒxZR:•"v2pëÅIÔ(Y [ÙMMÕâ“b)_dÐ33ðô(™H)Hfz<y‘sÙd³qwy”3X(vöPrph@¿˜¦…vIDä(‰i‹Ù*ªeŒÂn c3†eQ˜ŒÑJ]y!÷¨˜6HZ"—Ÿ9j¢Y¤¹è(©i’˜Äá,Ûøš˜›1›Švbw5†~ršA (é›Ó…‹)›¼%Ž„bœQ_|ƒ(¤±ˆÎI]v0–<ûÿ'ÖùØ™.#åšÝÙXö>ÛEœr“°+ù+
¸žžÅV³]žG’a”°&P‰ŸbµGáTÈ%ž–²–‘ùR$+I ÄUgƒ6“w¡@ʉ!{iˆôR$ì(¡ÃU`æ¨yí„Ž²¡š8OŠ¢²õ€ÃzHA„—‚}ú.‚Ò›,*V¯žh)7Àˆ!4*QõB*¡Õf5jKÅø(ýøé+@ #a™£bU`ƒ I…—Ò¤ñ¤¾ÂJ¥ïÆ=ãŒAÐ9—'\*‘õÒ)'¦yµ£¾ÄÍó£Ržá¥·Òê ¢Õö>¤U‡ûmÉ,ýxŸTÚeáeNÿØ)ò)…º,ýˆ£9Š‹|•}JŠ’—ò¨8Ù¦ +§x%§¨>ê)ª•ž +EŠŸ]¶Ÿ´i¢–‚¢x橬ª^a9 +N2…)²šfj¨P«bj Iq¤ÕPŸ“ñ«’ +o +ªaõ§Uy¡ú×)yžÚ§ª¨*2d‚“¦RŠÁ¬ŽÚºž8¢&©c§%r›ˆœPj®ÐúX^iÀ†Ošº/×Jù*hôZ¯GêL‹ñS¦œñ¯éâ|çÚ"j9Çú–žÂ©ó ‹½’(ñ.j™9œãéŸ!¡°.u”*¡¯5¤š¡HB±XŠN%K úEP6®rªÿa±½‚/˪F0 ¶ØØ)½š¢6º³VÇf©ŠÒ²Ï®…2´|Ô¡F`_ulæ|£G16¯¤s¨.0µãE +y°ª\Ö³:—[äص0¡§¶RbK]6mú¹MÙr™á¶µ¢»hylÄZfL»,ðŠSõ¢V j^ulu,zk/âš·mš¸‹†Âúg¡¥vòz°1ñ¸¯Â‚~¦¢oüâ¹—!¡µÓºVÏ*jÖ0¹*-»®ô’M¶A)V]Ÿ]q2¦»©1¡ºÒBM6ÆV¤€kZ¨©½b³A¼Ñ’¼0Z»›ªz‹EQ-ƒ+-Òÿ‹ªõB»ëdE1aE•VËWç¼¼³K.äcÄ +Î@ +ö¡F[2¹¹‚·¿ßå`Õv€°Ídzÿ뵪â¿{ZÀty« ½
+_ßÔK,<®úâ’"VÎP·€¶œ!À:Õ¯÷'Á·Â‘öjd€¿ÛÛ¼#åÀ®‚§"¡Ã¶"Ã|c@ +ŸÚjza»è)ßû-è{¶FqzÍ9gBÆäZ,<,Kì-M¬Á^Q^À‹6©âîR»åfÆñ©Ö›ÂFAÀ.‘ÁãEî[*hlŠÒ‚“ÕÆÔUm5¼¢£k]Ы,wj|(ŠÿL\]6 ˆ +ddIŸ**‡l(x|‹Ü¢]v&|¢¶ +}•¤•—\(+¼K@<]w+PÄ‹F3PǧÁ
qÊ„bdw±ÊÄõj@°‘1ÅMYÊä/¶|9ÍŠVvÁÇ£fdðÈ—c–ú/.ŒÌRºuÁ̱yd!Æ[¦ŒK´*iKöK]Ó<Ÿ,DzŠ©*åÜ'=3:ìHáÊ€ŒfÝx¸ä-¯3:¼ìjH¡âÎŽõ€“ÅÑÁ¥RC2€¼wÒÅ!Z€!‘<^âÌL4áП²Sõª° +‡€¼ŸÅáÍÂŽÕÏÚÑÍ~¦ÁHÿAŸ,ÌòÕqSÈàÑë+·GT)Åf›Ðm£41È?mžÖÌF1:"º"Ïÿµ4³,J$÷pUÑÿVЂ5ÌsÌYMÈQ¶¹ÖòUì¬@¦ÐSÍçGYÑdrÒ +ìÄC×÷g×Î9Ÿ¼×òåÒaË—R¸‘›Zb’\ÓE
É"¦ÓcdqŽÂØØÚx¼58,íø(ñ(A>}+Mž=GÍžH1O9É]£ß‚º2Ó:Û+‡]PÛ"¦ +%MѱS0|*<-¼Mž)Íå¡×0gª°%]–˜š.ËmÈ×lÿÍqåÑjm«}+á[ŠMÏÞMÖÅ1ÙT¹ Pó)X}ËÝ]¬[Õ5ýÊßsƾ±Þ±jÍ=}ËßGAçòºö}¹²ÅÒbÖM“ߟ
djÖçòݲ5cÃÔ_jàÀŠ¾=VÁÜþ(jc°¦çm+,„ÌÒÛqÝÖ\†°õý(œÝÙÑRÑ<]ÄzÒmãFLCà²ã,-íÞGa~iQJ,ÜÂ5¡ÙžâãSŠÏÅ!Þ°Êe†åKá-3áÎíä]1Ù7¼h‡0vë./¾¬f>ÄÅáß°ügdY9)dΗÑ"u^Ác‘88
d]ÿp1Hn)ž Þ)
s«€áHa]µ(j9 (‹nß5Ñâ—é“cåâÿ]âÛœé¸QÊ2áéJøpÒÏù¤Æ[c«`é2©êÃK»!°N\Ó³~µ>–Ëê¶rßÊ÷Øáë ùÒMì—v8^/éÝÐÒr/ýìÅå)¾hùpäÖV}'Ú®ÍÓåv@àåûüg‰^Éý*Ë]îorî0¦îjÎážÕ rž4Fîèu.2pÏ|ÝxnØ[¦ +Nåùâæÿ-S.2›ÌÈyqðD®Î^p2þ+ºÝ¶Ór_ñÃU¿Ò—¶kY›/ÿgYZº,ÂÿVdP£[€Íõ‚°0±éqâ,Œòë²Ucp27nÁâóIî×ê=-ZR)Σnó—6I_ŸL?GNŸëèÞ¢SåsF®ô:žõAö_•Òõ
Üaêùé{hß(X;sß%±R)é|ØÐþöR.1Uî-f¿w¯$#eY¶Þþå&d€ïµ2ø×YøIb@–Eòžx‹Ÿç[Yî/’ož”Ÿ$¤anBïX£ÇîF=Æ*¬ËúÒè_4úHR-rú5z…¬p/ÛŸ¯/Ên²¯O Q?¡„ݘÛúê/¿²v-Z¢ lïXj¹ÿãg+1Èž³3ÿ!æŸ +²÷Ô¥fDühoCïŽo›þE^Ó*`þ[Öq¹¢þÓýíO÷ª
A€¨rVÐàA„Éa„Œ=Ø#•ÐâÅ„‡>àAC!EŽ$YÒäI”)U®4ɱãK˜1eÆ<„åMœ9uîdx "†‡0^\ØðaGŠC•&³±ãGžQ¥N¥*ÒåL¬YaÖ¬ÚÕ«W]Š°(Ã1%Þ+ÛÖYÓ :::øZ×îÝ WµîÅ +ï_À$ˆµ9Æ3Ugƒ¤íÈö°Ò¢:êIôØòå“rùn–Ióg».ëépøXñ˜—Ž_LÌHØŸ eƒÖÌÙ¶ÿDϳuGMšŒi¨¯Æ¨Ê&ÃÁ±w/¿[û¶íÜÌ¥¯”è› ÛÓ©‰_ÔØð*×éá¥:¾9ºxô"}zx½b}Ú·g)9âèôùo)ª~aûˆ}ƒO¾ùêεõððA“øë³ÿ DÏ%τ¤ø†K𠸼4KI ùªÐDé4óKòZk¨Ãµ><H± $‘ÅQLQ«yÜM³±sk•ã¢1"Õ>4.$…4q½³ +RJÙ€P‹¡ßÚÚ'É – ÉU ˆ(±„Ê*gºRÍÏ`³‰÷”ú$RtòÌõÀƒS?6ÛŒ©‚?wKŽÐ¼ÿ3Om\!û¨¬Ðôô¥)ýl†ˆ¬s¨;b´Fß +©Ü4ͶKcÊTUË\d¨À²BehT&KuÇ«Þ„U7V[ÅôWÌÐ Hí\TÏq„ÍAb¥VX‰rˆö²°ê!«ÖeýO±®.9j%‚V\¼ÃÏ0nñdv;3ë“ÈWt/Ó«Ü^÷+—|kKÆ[ß%îѼFÜw·{©Í÷àæ&pCQ^àõ&eø³„…]øâº|¢ˆöv¾ãªŽcÙ8-W¢Qî*,¿>ÅH1\Ç,U1Ø,v90òÖwgž8â*Ù¡h–8HOú²ž…-ré©äÂè™Ýÿ™¸'‚í<¨ñjºÕ§»ŽÊa#Ë2úêÕBÕ!€‰~û«¯/
ûmÂú¨Ë¥Î&5Á“£—nªÖ^9\Àwâèã÷¬Þ›dH'ãºp¯"]ynÈW’k,ÍV<×2‹ +ËÏÊážlpCG ˆzð“Ù"½9Ÿ¯»ËÁ4½+-—tö›Â"jÖñÝõ튲ç\Ü«2–ôâWâè#Þ¢Yˆ’Únäp;yžŽ_¹tìE’(v!Ãú‰*Ú®)É®ï^'íËå~ý†Ðï¡J&…|é‰â5õuPþ‘LKXï`Sš¥”Lø3ßÄâò¿ü€ !W¹$¸>Žè€~Q ƒ—ÿÉ\p‚A`«Dˆ= `‰RŠW€”沉±NXÀ^ê†É;Ph5”Gé£ +0$ŽF¢ƒõì~¤–q÷{¡yч†h®þ‹†'ª »—1Ž$’Â
Ä+J$‹e!X}ð»ˆüOŒœgw„#ûN#²F¥Ì5:x€¥â8Ç“€QPr d°A‹dm1~ A© +<À†ì#G¨È6yr}HÔÁê"É1äá%–¬Z\˜8QUƒ‹% +ƒU,%I©\åaâ¿Bf¥–ð›åʬ…H«äÀŒITÙ@¦dn„£¹†¹¾bÿ–ëšÅÓÁ–éŒfÖ,š!«a@>â!³>Õ¼T:‘©ƒè#oF§[Ú(2tÁ +q§:ãÂNA`‹ï”§ø¸TÏÄÕúPAp:6DrªÇ@©ƒ.ÌÓ55˃¢ND†1üÐ ¤øD#úÏ•Uô¤ ÉhãGÒŽT¡-MHaJgÜ2+W¹ú‰LH2å¥/‘éRT1†Cˆ#:ÈãNÊÉ*i‹§®YÊ£A¾¢êª LeÏTÕEÑ«AÀiA¬úB‰dU«\µc÷Àš"±Ð¢!QjB~&´2 ZÝ*ô5Ö,®ëã_J–y×Cøñ{å+LðSæ°ÿJƒ]ßêñW“èñ"IJlGVÀXbtöØæú$û#ÊaCs
ªY2?Öƒ•Û¹*á{ÚpvÅÄcIZ{#£Äv¶ÄÉÇNkÀíMPp÷qÀÏ2W´àòs¸QERu\Pæv„Óª‡dÇB½\«Êº +ØìNH·³#t¤ª¤§ED†ñvdº‡ÄUJ‹Áä*—m3YÁ=îa{°rA@ȯùÚ…gÍÕŸéíS±÷Öˆ¨Õ"|th;ÒQ’¡OÇeHVÖÖ®e·õ-NüôG=hÕ8×=n6M(FÁ¤ +û•d °ªÕC˜¸S$‚Ã(ÆWÖ#ÁnÿØò +
7Ë¿DŽÛPÜ5ç¬`Ç«9‹“cª+ãÀ&D@«tå®± +Ä« îáY]ÍpÀëõçD/õß·Õ†Lni³í¡«1ÔÍسó"‘Ù ÛÓ(ûìH©Œc^<ÃÏÌ?Š´Ø®e6Ư¸vT`%á“N:E••ö‹[mÚÁêšJf†ˆzB¤ÆrZW#Éë×I@(&±'ëþ€º{¬:5pÒ8&z5ÔƒIo[®ˆÖf\6 +×|¾ãYØ«¸íÏI¯rí²´ùÇ ‚kA;¢Ç“ã÷f[¿¹ÇBwº©µÒÚ`#ÂœçCWŸÖ~ÿO¿}¤$õ["†j#ì•Ü6©E&±Ý’$U?´iÊz´=V‰s†âˆxþs?¶ØfA‘¯ì4¯ê9¡y‰²3œµÊý92/îø%›8?d½“sKÜ©âW?|k:Ò9æÔ’ºYeóS‚$Xú®_`!{Ü—'ç¿Ö"É +r#µÑãG±“ý±fß•wÐDNÄí'‚;™Ÿeö¥ü³ÒŒË˜ã6Å]¢Áú‚œcr¥Ì0,Šlß>™ÛW¢p,6b·w( kÐëËD2_¶îA¾kûÇè]âé
"£×t$Æe邉ÿ zÄÞ6£‡ß!ž =Fh"þ¡E¿÷Câ…j
‘^Ôn}Dø|>ô‘‡zduAz<d/÷;_(¤¨Â’gXb"â}û$áömÎ_üæHjœ®¡;îk•ûÃ?ckŸÙº'¤£ô›?=:6¡;#J@44ěٺ}“À‘9¾À¢gè›/# +
´ŠVy=t+#þ›@†£‰°³
¬7€ë?‰ Á”—vòÀw°ˆè¤2Â,ÁäŒ=6áÁ©ÛÁ¾§xÂÌ6‘ƒ8Ы ªÓÀBS/+œ ‡Ó$/Ò‹žû‡#$ïú•-ìèBÓ!¤ÿÒ$@€°¬ÑÉB´-5yC8t9ƒ•4,5D&#‹ ;|;kúKÂ>¾p6Ò8ŒCðÁŽ8ĆøFL˜Ä8Œ‰M„öùLä!C܉`i¾Ý@¼ÇbÂbqĽ ¼Ê:Eè"XaÅP|QLYt+ZÌ ½èEÁEWÄŒú3©2¤R4ãÒb$–cäa4E˜XFçCyÆ_‰ÆXLÆ_Ä íé-gÅb¼ŒWšU|eä VÉÅüÐFXá@+ñÆjšNRxTyÄŠt,µoÄ ½èGÐÈGMÙG7É’÷—uÜ çÈJȯ HJ1H™pȆCÿ9üi´…Ô $¢±Žé!6IG‰,”Bì‹ì‰˜ØÈ5ùGœ`•A¬V8ã!Gb9ÉòpECbÉéȺ‘H”Š™$I›üœ|\I…tɛЋûJ™,J@¤ÂŒ\Êzä çxÊŠŒJ˜pGY®*IJ˜àIñÉœ8š¬É˜ ʯ,ÇX±ÄQ³J¥¼´Ì *éG¨ŒH©T•@”A²| ³d‰2|€ +€ÈŽaÊÜiF¯ØËÆìKMùÈÉÀý±‰«¬Ìý©8'šh®¯¸K€ÊÆ´‰¯Ìœ +‚,$O\ÍÕÊÝ€E¬ -»x£9ä¤z¨Í9¬‡˜Œ* p8ôAÿq¤ +м çè +Ü$~ÂÍ€+#Èsœ 6´Øœ Ù¬nÊ鬡`q/ƪ(N¼GªKiJÈÔ +XÏõlÃdÏLzÇꔉëä—I|#š`M4“̶ÛÀK$Nż‰¼¬ +>œD™8€Äç„ÌH°ìœ ×ϺŒ8jìÌâ ñd VL‘pLÚaІpP¸”Š=Pê¬Pã K˜e„¬ŒŠ«ˆÑ’Q¶|‰~JŽá4‘¥‰-˯x%·iš M‰µÑä˶ôJý™f;Ñ©øÑRÁŒœ˜¨sìQHR•ˆ”% ¥ +‚̽c‘Ò©ˆÎÛÀFÿÒ®H²’ØÒí½ +*1¼1E;4S.eŠ| 6Š«ÌÑŽ3’ÈUÉ:å rQÅ<EÏ·ŒŸ(…“?ýOºtSªÈ˜‘Å0UÔ—HT§PŽmR&}RH¡JeL¼Tª(!ÚÌÑéÓ.
Pã\ÒQ… ·4UþlEJmPER• +€¢³Ì¤ÐEeÈ>q¹G +\t8K9Rý8BV”pÕñ ke /] VaÖ®,ÕBíUK•jÍŠm5 l¥Qm•nU‰F}LR•×'UÓ”¬‹£äŒT=‰uµG[½‹wM‰«ØWWzå'›¬
5‘¿ÜŒ{õ´+ÍÔv€E‰ÿå’Ö•hÖì±É¢O4ͪœÇKØ©8ÉtU‰Š½Öû˜S15Ø\å'‰›Ýì‘åG+‹ªØ“ÖdeG¥!S—%ÔDÕa…†U‘›IbýW»HÙDš——BqÚê Z©ÙƒYœ +X5ÎHsZ“¨mÕØ H¨úØœPÎòXX€-ZT–8©[“舨…Ú©ýÃÍ;P–ýµEʤíOÔd'©BÙµÄ º-‰oZ¼=Xªµ»‰µ¿µ¿À‚M˜ÂµX_µS¦mÊÆ…T]uR˜õO«Íù„‰bìWBbHóô$˜ÔÎe ±eÜ!ƒA<+ɼ“ ´õÖ±¬\®ŒÿL˜âˆN…Ør%Ó£¬×‹<ÜŒ%Q°ÍÝM *}ÜVýGûø/&Z/ûÑÄU\½]ZLu +{è[ÜE)šè[À¨Þ•µŒ‚–4Ë +ÂPïkýÞCý\ÎÝŠ$©²Y^+EÚYý• +0òM9$Œ©C·IŽ€Õ4ÏÇZMõ-2V}[ÃŠÉ IôDm½ÏD diff --git a/library/images/logoMed.gif b/library/images/logoMed.gif new file mode 100644 index 0000000..53baa92 --- /dev/null +++ b/library/images/logoMed.gif @@ -0,0 +1,16 @@ +GIF87axµ÷ÿÿÿÿÜþñòþëòþÍýÚåý½üãäûÖ×ûÈ×û¯úÈÉú¸Ëú¡ +ù§½ù“øº¼ø˜°ø†÷¬®öëøöž¡ö‰£özõÙìõ{•õoô‘“ôm‡ôbó„†ó`{óXò¶Ñòvyñ§ÄñhkñUmñNð—¶ðI`ðDïZ^îLPî?Rî;!íÙòí?Cí5Cí3#ìlŽì,6ì*&ë15ê¶×ê`ê#(çIfåy£ãÆëãl•âµÞâ_‡â#/ß•ÄßHmÞ>_Üy©Ü4RÛkœÚ#6ÙµåÙ_ŽØ¤××”ÊÓw°Ò*KÑ^•Ñ"<Ï¢ÞΔÑÎG{Ëw¶Ë3_È"CÆQŽÅF€Ä“×Áv½¿!K¹ƒÑ·v÷2m¶)_µ[©µ!R®uÊ®1t¬g¼¬)fª X©O¢§E•£1z¡gà _ŸZ¶œD›š:Ž˜0€”Z¼” fD¢Œ0‡Š'zˆm†NµƒC©/ŽzsvC°q/”mze7©\€P.¢I‡1%›,”,xµÿH° ÁƒD° !„
7ˆPAQŽ‹_l8 °£Ç C<аa…ˆ*ªx±¥Ë—0q€ ²¦M„%<ŒHBeÌŸ@ƒþÔÈñ¦Q7¤¬XC¨Ó§PŸÎ<z3ªÕ«XÖðP”jA’%'@ÌJ¶lV +ȹâRŠ,ÍÊ+·†ŠtóêÝË7hÓ¾€—µ(¸°a§+^ܲ'ãLJ7†L¹¯äʘ÷V˜œ¹sÙ$ÏøaÆÏ 8`á9ë‚
}Kᧂ`´¾ŠöÞsÇü`°öî¨|ç1@†˜,2`p¹rºê†Y`à€ÒÕ£ÖÿH¾—@ã/3L°=<T*ìÈú%s L» +^øÅ@è·T$à_^ÀL0„ÂVm ^ÄÐ^Kê9Ga…æ¥^0ÝWà‡QU"]ê¡×Rv| W Ô¸!d€€^ÙÉøRw$–•AsY€YŽüÀ„.5ø`V,tw‹Œ! ’0
8€Ve˜
¤WtöÍF%Tt`hP&¦^qº”!“V¥)`ôÈŸøQDŒw¥^g:@yôÄ€Fˆ<Ÿ@qÑe¤Km•žÐ!é¨OüÀØ¥p&×s-@ ]ÿ´ƒŸ£JºÇŒ%(ªfÁÚÒmuBå*ÖZëŒY¸«`©U +Í]als<¦lªÍ ГNÍÒN+)¦2¦â²€¹ZŸSi†+. €ã@"¦^°B¹êî»fA’äfuÝζ¤üþù†Y3¬••H6«B)J ó1—yàéA×é¥í’N5(jÂ:!˜_tmPXƒ\þÔÝ(ÿ™†S,À(³vJ蔡ǧSÄQ€pÆQÝ6çQªL˜zÕ=¢2T
.
“ÔVÿ„õ‚|©çéOĹöÏQ•ÝµK®‚ ”®±ÿ½×mÜê€=ûqUtÆà–N]»by$ Ü=SqUÙ·àÛ@9î·^æÝøÒ€„£\mL3äŒQƒøºÄãNÛ·ÀI¥Ó(Rîê00çuHôKøêÀ pA·ï»d¬‘ +(Þ-Á<PÈ×Î×tA)ºÊ†ã@EmáBA¢ãðêÅ,ÄSïÁö-
@yÆ|ÔÚHæp0²á™Å [K›K¢ó¼°Iª×{‰«Œ'ö%ØsNæÀQ¢C +V^V?½”`€¿ÀÓ:©; í%©ÁV°&¼ðòk vÀÂZ}ÁeÄA„ÿ4”b2ÐBGe„oe.;w“ß«Ãn‰‘2œv\¢¨ šÅqè +°¨9 Î{2[Ô^ÀxDƈŒ€ÊŒ¢HœšEvT„ +(Ç?ý@Qâ"£òÒ=x@Gè£Æšã0mÙÑ,…ÙaPH8¾¡AƒÄ2Iú
D’†AáH©Î}< A@Y€¡8—`À¼¾„•…y%õ€8*Y…u¹%et9Ò‰‹R»‘ébD@€2b×Àö.'tçLð›K3?§3ˆË
c \Õ>ÀLq Ü<ÌŒˆ@4pTwÐ2ÃÆÇ-&
Æú xøÿ®.,*›€©g:
ócý€
•^õ<¢“2T¨•ÆÄ0Êiù¡g2L!e‡9¡Vo0ˆi,8œè1E£`2Y«,PÁáœrhOD1ÂH;%õ. ¦µ²Ã)“œê"z”áªqùaw)ª·%¯7Hê8XBS§e¹Ê° FÈêàIýì Ý*ÓÌ0 +Æ Å~@´FJc™ikß*ñÕêLWâ倚3!UäË@؉ƒ €¤qÄA ,P£Ì“žˆª]¥øృÕC”`´deÖ0áHq0„
¾«µ*=ŒC ’Øùÿ€¶V?ÁOß5¨(&¥{
Œ@ +WØ`·â2ÜÚêE Æ””傱Zù!‚(=maRÔHáày8/„87/æé. p@„ðŠK
eLscž5H
zÔXÞƒü¥0òæ¨:ëØý+ /£ÌlKh/X¡V•6+©ã.³QŒz¢°ZõP8R©¹¬`ê_Á(¸Å&,.>`×ZR
¥sR¬ÕÿIä…‰c+Ü$Õ¬80‘†?æœ7Åi~)Ë ù˜F>N3|J!¸±¨``¦íK@†QYîZþ뀼,0/Fÿ=½2š‰ë]âxñ0nV€>*ç4Kª³'®Ì”!˜sžV”ÊÂZ1(AY›Œh?GêgÄa3_
òL*û¸Ïtî„„àò‚˜¨¹K2ÆÔnL€•‹›hcI6rÿ櫳°êÁÙÕòÕõbÀaJמ(€]e6zê¾Xà½Õ@ÓÅ0û1(°€¤¢‡fÕJêƒëÒ4sR¯Ç$€ÉD®4…ÓÐÒT¦žçí‹Ðý³'°˜‰<ß}xóåöö»Ù; ßÊ©Žû
™l!RÕ½›<—)Æñ7_š©ÎÖX©ÉBvpTÈx€áÿBdz:ñ?ÍLF³¸ÓLó%‹80ƒ{§%s¶$S…á€Çvú'XaçÆB3fš¹âX@?èÆA^«#´NÊ<ÌÈ`(ÔÁ¯ B‘U(.øv1+8c)}Q +Q/ ®+bÔfý0:BwÉ@…ÊýOk`h©ï~˜Piøš98*)À°v+cˆ£^¬ûÛ¨åà ²£Ç€Ÿ+w|¨åÈÌ a€¨éÝÖ¾3H bfº—úÀÜì~œ:…ý€³g— µL\°B*ä Tp}$ÔWÆ[œ@õ?À÷¿èóý@,,€+DÿPmƤø™™A¢ßÙôJ +Cå·Í2ó)£v- òQùÒ3?`W°F $5ÕFͦ?Ð?TîÒY XÈ€wÑ‘P]u"@Õ!/‘i=áAChnw &XЂðŠ2s/-øAC6·)ÐÐéQzVA)pƒ‘ƒ:؃/hYA„ñGˆCèƒ.!ÀöN(\´…)p `S y3Ø‚?‘…€…W¡ `¨„ÄÃc†1†¶´…k؆oH….¡4E‡0a‡ŠE6
``
ð…3( +ÿÐ
à†0ˆšSr- +Ð/øYx¸ˆyÑr(
‡0a`ƒ8@ “‡…øC‰.‘…-`°È“§(‰.áŠÁƒEø¶ˆ@†-‘Œá„)`Œ¨½ˆ¿ ‰‘¯‹|è?ÎxD˜-ÐÕx×ølø?1Žvæg¨‰‹|‘ŽV±Ž.ÑŽN1ŽÑ±=ãˆDhåÈx䋨è<H.aÄè9†òX‡EȆpŽzq-€ÀØÂøh Š¢:™… ‰ 9×|1Á†` +ðÙø4Њ +ÿ0Ûȃ diff --git a/library/images/pwrdLogo100.gif b/library/images/pwrdLogo100.gif new file mode 100644 index 0000000..51f7068 --- /dev/null +++ b/library/images/pwrdLogo100.gif @@ -0,0 +1,27 @@ +GIF89a?d÷½½½ç91s)sç1ç)Þ91{µµ½½µµ!kç1Æƽ½ÆƵ½Æ÷9Þ1ï11sçB9{ç)ÿÿÿÞJ)÷”B{!B„ÖkZÎ{k¥µÞR1µÆ΄”¥ï{Z)sƵ½ÎÆÆ”œÆ”ŒïZ9÷ŒsïkJïZ÷„11cÆ1!9RŒ1k1s)B„”19ÞZB΄sÿÞÖÆ¥ÿïçÿ÷ïÿÎ)kZ1RÆœ”ÿµ¥ïcBÿ”÷œ{k„œ1J„„Œµççï{1BÆ¥¥µ9)Ö1çŒ{÷„kÖcJÎ9çJ!ï1÷ÿ½ÿçÿÿRk”BZŒ¥Î½½ÖJ1Z÷ï÷1)ïsR÷½ÿÖÆÿÞÎïsÿïÎÎÆ¥½Æœ¥{Œ¥9Z”1RŒ9{ÎÎÞÖŒ„ÎŒ{ÿZ1ÿƵÞJ!ÿÆZk”µÎB1Zc1Jÿ÷÷ï½½¥11”))ï)ÿJJkœ9ZŒs„cBRŒ)k!Z÷÷ÿÆÆÞ9)RB!JÆΔŒÿœŒ÷ÎÆïR1÷1ÿ¥Œ÷BïƵç÷ÿRs¥JcŒZkœ{„B9cÞÖçs1JŒ19„„ÎssœRRŒBBœ1)¥)ïB!ÿ{Zÿ9ïk½ÎΔ½Bkœ{”½Rs”¥ÆÎÖçJcœ!BŒ9R”cs¥kµ½ÞRZ„¥¥Æss¥)!ZkcŒ”ŒJ)J¥{„„19{!)ïÞÞçÎÎkkµ)!ÆB1çµ½RBÖJ1ÞcJÎR9ÆŒ{ÿŒkÿsJïJ½ÆÎÆÞçï÷ÖÞç„œ½)R”ÆÎÞcs”„Œ¥s{19kÎÎÖRÖÎÞcBcZ!BR!9„”s)9„)9”JR„!)Öµµ½ŒŒµ{{Þ””œccZZ”11¥1)œJBÎ9)ÿc9ÿνÿÖ½Öç÷1cœkŒ½œ¥µ)cŒœÆ{Œ½{sœ„{”ZJsœµsR{{Rk„Zsµœ¥c1œks!ù,?d@ÿH° A
6XØÀÆœH‚88 À±#Ç +¢,0 “/ x\€,c²4ÀÃA‚ Ø ³ã‚9Hr$¹ ÀFBV XºôÀŽž@¨Ð‘‰^DÐàÏBÃÂ\lU”2pàP• „Ã+Ì(Tz$¡…Ä0Ðz3c¨+ pŠ7€é€>gâ@YÄ$
p1¸`‚–¾".`§‘ˆÆª «¢€-¬#v…x‰™ãƒJÆt˜ kLjð°FÒ‚<àpÑš-.) +î+ÌÀ¬ˆÚô 6GåZÿøÓ‹H*ü\èÔ%Éaï-Á~Që=~às, æÌ_AJ°ÒØÏl1hð°Ý$Ðe°Cw,0(ÐöKû¥` +Òp‚9êÇMô€ƒ1À•P‚Ž4Ô<…E€>–‰E¥ñVhÐÜ"Xq†+€)0„4g!Á"ÄdXA† +”BÄ(àÂ$È@¢ÀfD”ÒäDRÆ‘°ˆ“EÕ94€'#tÐA c0óˆd0e˜ˆ¶”n춢V×5°Äa<}… ”EUxéµÒt-0\ÀFL@’K°ºà£}ÿÌF1Uà… +ØEC
U€8XpÆ+Ñï ç}]4Áe,Á”XUqrÃ)Í1Õ´A°‚O ÁO´¡(`F„àÀ¤ð€ˆ<‘eïEpq‡9@°L?ð@éºFA\¥A£L¤0A"¸±e‹7ÊDö¢5xøè]_dÀîœ €’K²P„ C]8r¤oô@2f`#J#Ðy¡Ô"#bÓ
zƒÌ€sK¼†{'êg7ag%ˆÀÄ^½R–ˆX(r * +hÒ)GR@"Vƒ°À€,°ðiÖ?j½@2ÔqŽ(:0ÿœÖu>3dUŸÛ ¼X„'«^ LJHe´à¡Òµ¤ÅšøÝóiÅÀg +ð/HpÜê¬À–½°/jlNA묇†ñDk"ºV˜\®ÕZé²g+@ñÉ×»¼ò±[}övS6a<˜
l þ3Êà´ßþ𶄠în‘á¼çŸÿá°:°ÁÌÝ"†ò`@ +mК縒¬-j×û
¬€*Ü•§3$Ô‡8AÚzò4ú8¨<¡Oƒžè78FøP¯d`ÖЩ]O'%’É¿ÿÚ°‚
Šª£P‹c(…ŸA@€‚ +ô‚/|&F:A:!À+=1€ +èpÁeÃ;À&¤ ³)`K¤”È/(Xå4žˆŒ[ìÖò4à€i„BWò:`1h—@>ð¿x©á΃Ýx”`ÆŽ6ŠÉâp ˆ!gü Á)ð;p]Üêq +‹‡ˆÎƃazr@ +ýh;X`˜P|a…G²HÈ¡w…PÁQ±B-ˆi–"2ÐFÔ‘-´¢Mhš+…ò€kd@jÂξÁM@¼xAcÔsÿƒ<É“Ààè–µÔ¡ð¡}Â0i–ìôxQr°°%¼È¢ /)Þ„{¨ÃÏ E$!EÃB*P# ¤H ÄÛ5
è¡= •e¡Ÿ¡Ä,¢ñʘˆ&èáunB‚ H@\Þ)@ªÀ¶Üã¬YT,dæ9'pà,ª2 7Ï ¥€Á.n¡˜
‹àVTyO„0C#… +LP°£žå×êÊ€dÀ)ÝÁÑ äP¦€4ŠA
¼b9@€h?=0ê£b @j$ÓŠð¢,sÐO +à h!$1€¶„gÿUˆ[øE`³ª¤b§°S¢€8(à÷o`BŽ@Ô"; D¦+ƒê†#Y C¶Û$0 H€€6XÜõÝls˜îå<E9Æ¢¡|‡WCø:ÆcÀHN#; Hã
1h 1„HœAËS…"!‡!ï
D C˜ú@"PáL}ÀÂ(š”+ÃÁlQ@$'ò§˜øÄ%Á@иøÅ*vbP¨øÎ탤ô€Jaçz[±žý¶"þÕi #` HÀ€ƒ% bA¦‚Žêaá]C¢eÞ5(„ÈÞöL`€/|à!¼Ü¶9µyÿ"صV±Ê}²s@Œ‘РáÁg¾lƒBwÏ…ß|ÛQÿ$RÀU‰r …/$P®1ÁÑú^‚£Ñ ½¡$¥â…HcP_€‚T6´¤Ä021àü“/en[“e×IP…® (Ľõ +E”INPX¨Á+§8ÀóÈT•'@aƒù1pI"°Æ´…3ƒdE˜Ä#JÀí.CUÕÖ®‘W¾ªÚ@ô#¹ @TöÊcË ê“©À&^HÉ~h +„AM}ad¡ +nE˜B™<@<( *wÿ™L®Äàc+j@Öiîå,H8[dðöµ/*ø–sõ`麦AÀ(DÌ:܈@F2)‚à¸pv
0¾(LË#’`.Ý{»
€ôR”-vDZ(h´=qW2‰À¦ä±œAê]ïqeGÔ‡‡à8v˜Enή¯]&AÒVIѪ6ü‘…ÎïÕ(¢Þr!ä)ñH8ê"¢¨êIŸVdÒ^˜ÅºÀJ*ˆ¥êº¢Œ\¾6‹˜†3@7Ôëì@CBY` +§¿‰&è´L–Ô¸„„™¢€XV?Hè¥ÿ,ê™(Ó
ì¡‹ãH Û˜zS®À nzDïÐ@ƒšå.nØß(À +{ ÈáVÀp‰ *úyðK +% Á!£Ñè_`†ÐÍ! KÓD0§t\±M˜g²° kðv‹2\@µQ3ÊÐ>6
02˜§$}TL¡Ë`iÇHu +`Pmàp„-qŒÀ®Cç!;,€Z…¡w8ð¿GBбtƒpGÓ@
k YNãû·Tn™Q…ø@4Fƒ4l¡ ?‡ÂÁ:Sm0 +šðè—j€:ÿ€†}˜2°ß§%än Ž Rñ¢Æ!Àpzp&
x°>àgð±6jQY€SBDx0ãA@uµ ¼Ð˜Ãk€ƒ#&À L8V-PZ:t>p› 2Gpht`ÃÀ…U!$LÈ ~S:Å°€¡
kàGs°HQõUVæ6y ‚0[’†`Í¡ö ˆë˜„0n¼uVUpÑðË ËÂ`,¡ lC PV@BÀp +2Ðé0Ó1›å<d£3Wà9ì#°h`l¬6WöQ`’7§Nt#Uÿ9Z9¬ö„è×"G!Ãm¶UÊ–““bŒÀt›El SÙQªâ/ ´Z'Дå! Âz@à=ÉFj
ð;@ $×MÀX'0Cîq"tO`–-q\NÀèJÂHŒua0ò3•R/q e¡>ÐRpd1AØø `/Âs´Çð™ š°žy\в8™Ÿæ T£@b·\Í• Ðu,À0 p;¸Ó:ð›°›"ðÄy:,ðpW;°–€À<)ð;²ã:ÓcÚ¹õå°Á?#ÿÐÊC_ÒC|ð›ežÐ KQŸÚ¢±"Ð VÐ0àV $æD00 F2®ðrðÐÐK +à +¦àa2&¦`&bBâ¸<Éð +¯P¥£àŸ±r8‰³ fePU€¡Ë£C`‘ð& U€pä diff --git a/library/images/pwrdLogo150.gif b/library/images/pwrdLogo150.gif new file mode 100644 index 0000000..70721f2 --- /dev/null +++ b/library/images/pwrdLogo150.gif @@ -0,0 +1,55 @@ +GIF89a_–÷½½½ç91s)sç1Þ1½µµµ½½1{Æƽç)ï9½ÆÆ!kÿÿÿµµçB){1sçJ!ç!1sç!Ö9µµ½9{ÿ÷ÿ÷÷÷„µÆÎÎÆÆ{Œ¥!sïRÞJ)ï{Zïc÷ÖcJ!J„µ1)ÖscÿÞÎc{œççï„ŒµÿÞ)J„Æ¥¥ï„s÷ƽÞZ9ï1΄kÿçÞB{ïï÷ÞÞçïkJÞR1ÿïçïsB1ZïsR÷Œk½µB„1k!1k{1B”œœ11Î1Æœ”ÿν¥µ!1{”11÷œÖkR÷¥Œ÷œRc”½1!ÿÎ1R„R9ZÞR9ÿÖÿ!k11c÷µ¥ï„kïcBRk”÷÷ÿ9)ZÆ)Ö)ÿƵZs”½½ÖÆ”Œç”„÷”{)1k91cÖÎÞR1R91ÎŒ„ÎŒ{ïJ!ïZ19ZŒœÎJc”9RŒœ¥ÆBRŒµµÎ½œœÞJ1÷½ÎÖçs„csœ1B{c1J¥!ïZ9÷ÖÎk{œBZŒcs1BÎJ1Æ1ïR)Δ„„œ½sŒµc{cs¥JZ”œœ½ÎÆÖZ!Bœ!!ÖJB÷cBÿ½ÿ”sk„œ„”¥Zs¥))ZJ!Jc1R„19ÿçç÷œ„ÆÎνÆÎkŒs„¥½B1ÿ”œ½Æ¥½Ö)Z”Bc”½ÖJcŒ!c„Œ¥c!!Z½µÎœ”{kŒ”„”¥Œœÿï÷c!9Œs{εs)9„!)ŒBB”!!½JB¥B9!Ö{kÖŒ{÷Z1ÿB÷{R{”½9R”BR”„„ZJBkkc„çÞçεŒŒ½ssŒ))¥1)ç½µÖkJïB½ÎÞµÆ֌ֽÎç)9kB9k¥œ½cR{cBZ{csc9RsRc„BR{!1Œ!)çÖÖÆçÆƽŒŒ¥ss”JJRRÆZJÿµ„½œµc„µRœŒµ)B!B„{Œ½„”„JZ!ù,_–@ÿH° Áƒ`°Ã‡JœxЋÌP £Ç ¢¡H +JdY‰¥D0cÊ„)rfGOÔ)'€)ØüH‚Jˆš"]d!rhGsúär@•ª“B:%°#ˆOŸv@s!«V=4p°I@9–5@·n]D¦,8Ëšˆ-晑G¾8`9 +S#®$°K›,X8ìQ$<
TÔìH! +Ñ4A@·“% >ØÉ ¨Y¾1µQ6—²ïÊÍ‚©pƒ¥]msÁ"4›àì‹ÆÇ-sÁ—@ |ÿ2Ù7O&6Ø`t8c¾{AE—P+cXƒJÁ‘iGÿ¨¨€ô
Hdp1ŒŽDP]TðVÜͤZttT§“`Ø
D +.¨ì•aÌÀÃLˆ@%(Ád”
0)<|¡s'vdEœx@ˆ`% Š8˜x¢1¨PÎ]\Œƒ-ôV׳³ÁôØØ;ØNéÄ€)E( €lþGÀN”3bŒ‘•2øÉ…ÌA†—0½ù@DPèA˜Ò@j¶¹æ¢AP" /&8P!
´²Áðè%50Ö}%`^Hÿê‘qNpÃÄ\œ3‚PΨ Ãm²>5ƒbÞ§S` ÅΪgYðÅ@ÐS$A(×a›s!Šš(N¹Á¥>µ« +ìjÃ]×…2LŠ2l·L8JÐ+á!0 +èþ¡£©ÿp:a€¡ `pˆ•¿uìñÇ ‡,2]¾š1ˆC‚»±x’°ð,VP‚%Uô6€u8 Ièa%Rä‚7LÖÀ9àA%/L6”„QÇ ½5Љ,°ÐuPÕõ"«¥-Å'”ÀÛp'À@,aÄ›˜aG'Üÿ ø*à¾þ[t<‡²ÚøNQC +)˜`ù˜‹0’^€a[ +lFô¤gq—±Ò*0 áÐW«ªju »ªD™c‚KP×hë!dáÂ{P@‚ô Ä +ou¼³j¨XqÀºL/ý—V@0”?ðà@“Üš'UÀ¡¬)€…rÅÀ0Á÷6…à‚I#!6à‡[y¬B›IJ
¸ Mi¸–›(Â`0à +V`ë@ÎÆ;8ÀS)ÀaËÇ|à"d@0”B°âxd„%‰ Lõ£èláe^Xÿ:PŠ@h82lAepüUDÐ)ª‰¨^0¨‚\G ù+˶܀Ö0È–à+òD!1X# +8 €è`øbÛzÂ-(‚NЇ4`NCÄDa‡ÂÑ¥Â( þÈj/nˆÀ
·Gü”â‹HØY¦uTà.&6PéØE:±p€âTÂsc›ö€g$r@”|!@&Šá ÖÐÉNxÊS¨!x–Å"À–/n;A/€Éx¡ +áñÄ j€'º°æÇx…E‹aÞ‚ÜAèv‚-$ðTP‚Õ¤ÿ‚ ÀH^À1y îÜ–LààݧP XÂ
"àpóD +ÁÁ†)dÂ-@ ˆ!‡‹žJ0H–`-´iZØF0K*Pp¾ôU>¨Áæ«^LBÉIC@Þ€.&Q%:`ÄŸ, ä‹êÜG$Öb0q‚æ'Ô›\YB´HŒ@£]ÀDˆkH.p$ GhBa+ø€
kXC*PFö°DXËüUl°‚újPa¯{mB^7‹‚)t¶³u½À&pˆ6 :á‰ð°])9`Aþ@#_ÿ1]À¤v‚6àau8CZÀ‚œ R`ôÀ¥à¸ýoÏ°34pZÃrЬ<íìÕˆ +Å \ pè=ïy ÇÞöJ§ý,œÔFFß
à°ˆOö•û¡íbò0Eü›Z…Šme‹›<„]¢ìP×4Ôöf“Ú0 L¶Ã0DrG¨ x{ØCÐ@âÄar”»Æ%Lp>¸vÈâ„EãÛ¸Æ8žpAð·hj¥$H +@‚¸€ +áËê&0ƒKÌà +;àÃ47ZÏyNuB1ŽŽ•=”-D#€„ MòçA +Ë¡ÀhÅfH=jÿ”5è@ZwÌPk&ÎË‚oè¿¥à&3`Ä& €?µùÍŽšjÜ;%Ì€I"È@é¹™Mmú¨rfðÍèP8rè6K“'Ö$â@VÜPayŽ +À\W¸HL¬K¬¤b¥*xfãcxêjXË„#2Ãé1€ÏÈQ3HzÀl gVS•.ƒ
Æ€1pA ‡:ÀÈäJoµ‰ù¨–+ +rPS¶Æ±L™2r H9 +T0•q>Ú¢f§‰r”`ƒ
¨@«ñ_ô®€TÐ#„pq=4µx‚R€,gaÿPÂ6˜]ߌ#Šj¸
Ns–°aA
8A~?.–"ú;@ÐCÎ
2]Á6ØHóžÁ³,§Ü÷Ø8m aä'JAô†B;= )>”!:0CõÍ“RìØ^ZÀ¼± WÂl4gT ¸gh6N<ÞIÁ0 6U²vš³˜:Ãnk4€Z!¡s„:2@6V}‘H3øyL´iÔ#þD€.& Šy°üŒB]@"4u/Ê“µ@ÅÏR\+I»‹'Æà„ÜA™Å.¤¸û¿àæ¯ÍìG +PšT&°l@‹ +¸Èr°Áÿ*\Ûš<„A øS´>!N +qL1ü-Æ zš(À }°”éG¼>p°
0 Uj—öfg€aMf£VG¢~Y§; î0!Qò-àHæT &ÀøN`ŒF$…Mñ`õwl?à‚° Çt'˜'D0@`£¦P€VqM .Ð +•p}[hЬÁ‹ƒŽd#ÓXTïtñ´*<¸FŒRKs"ÀðšR8 +Ç€ ÅÐëÒ|'rEm"`OB0<0 +Æ/½ Ð0~l „¶-Æ‘j¡VF+sÿ8¤ô½a0ƒÐ8 » j)è4ÀPÙ³_nC°é- +`…àP "`ÉP
Ð
Ö0¨À²Cuòlà9±‡là`w2!$TOŒaUàOÐòN: ^õmÆQýRVr†¬%0….uøT;ä&Žá# U5a÷rU³6à]³òkö#.3etâTðõˆUêÓXæ&ðŽ`h©±Yö‚†2€w;S÷äf; 3@l™1_@üa;0;@W(|¢¤v€ˆæ’ŽÂ"EPþ´zÿAr2oqÕ“>é“<™óV,<Â0l `,W>YD0…•QÉ fT_ViÆÄ ZùxJ°aF¿A8â!8”8RÃFhùJmy%H2oé–&ƒã*¹ÖyÀgÐ,2
ТÀô Ùà +Ì69@Ѐ“À§ÐDƒ~ÐÁçm~0 µu6ãXÓÀ[°¹°l"ur6¡Áw8yç+‡äJ5ƒã‡ôz_ÿ÷^5bHÿG2c“ã¥Z>‘†œo“œÌ7Îùœ†K œ€7`@/ð)ji–WÙ1
€_ÄÿYýEö3cØÛƒcÂ3^óžÇ¹œo3Óy‡ð'P°ï%/°m¬9úl;laBM¶;³s2¡†>áejs¡‘=ÖŠëÐpP"J9)°b,æb¤µXF:£ó¢0:\‘{¥ 0…^¶ øqMùChXö¢meY†€
¬ƒî!mÁÔ°5P£¶ã;AI`¥ Ú"*¢OÐ¥,–ñ‡€xõç<X°ÌdT
¤Ôƒ‹DJ¤(OÐhfrpj8”Ì#”Xpqö¸)ð‹.üÖ’/ÿ‰Ð³gÂ@XÀ…ŠEe¡´ag?FYPT"od†dP:ÕãöA&a&O°Œ3AdX`iÿ1AQ`€¢Á?Ð*`*~wR)… ƒQX@6ªÍ“&…61 6PëƒTñLïtVŒ¶ƒÄúcXàͳ? +TA €°D²é¼pyo:J…Ãò#z$ððÖtÍúê“€€kl‰yP"²BˆÈ8×Êa¯Â©GvÁ÷’y€þôÿtŠZjq`°)C0ð«N1Aä(ÖÂa@. ã61Li‹v6ºo'¶*Xÿë=oñ[ywÁ(J@FmQd¢AgJ¨o
¤àÉÙÚPˆˆñ<QÀ°áÀu;K•iÂM@†
T«19TS ‡„`l†ÒAðm"n”(P°RÐu†…²6¤k‚C„z„8À «z¸QXÀ¬Á$aP·D±’ +W0: b+o‘:nQ€s\UÀIý¥*Jn%ÐH<àYûOIùà8TÁ,I.`l ±d¤–+D'£*"‡‰!´7¡©à7ÐuZ)—Ò±m@þR•ö¦5±>À06BÿrÈrO°§:y«Í ˆp•
ðJ`½ÿAjátÀ¬8îwPD¨ˆ ÐÛ1>€¯ÉT€¬e‡P8†¾×Z;ü[, + ßÐOV9G +øVï늀oPFá©Ä;$Åš!4Ëv•n@ <´¿° pØ`ÑÂܱ:áa3Âð¾1@jÛúÁ0¡qªi`0l·@tWp +;‹Ÿ²T€Y×½÷•_Ë_³Å²VP•@ŸÀ’wÐÓ†—tk*vUh?:ų2”‰`Fe”¨À'wˆÿð2`æëtPP{æéPcšxÜa? Œ@pfT!ÀBÇ–ÇÈ¿ûÞÇE:¼=©•§Œ}¤ç}`M°À\#ÀFãøˆZQÃi^ñ!ðŠàª¼WËzð‘5âW
½%H@Æ!)µ +’L6– ñwÌŠÌ!H80yæ4à ,Àæ$e9°Sªü>w@x¬o}”‘Ü!H,2!àdP~š”¸àÔJ”÷¼ %¼ƒ@ +µ°€¬„ +gP•tÑÍ´ +†c 9@ˆ³ŒEÀ+$¬,)s€Ý# +ÐL¼ÿ`ouA
«ÔJlÔ¯à]àøW‚À +sSÌ×ÊøJ="™ÐÝ0!0Èàx@~°ÝÐi\¦@Ììh»Ðk2= +Jå³ÀX°»ï$Kªîj⢠+»0ä\Î# íPwtR`'‰yÂÅSò00™Ør9‘°ÜIn³ +¾T,e[`LuƒL„íL'ýª
{_Æm‹ÈRxõ +0 +£àå!IH%cX–€ 6ð`|±.iVh5˜* (¸×˜-È ™-Û."HPí19X +¢ho‰@Ü0¡ ìpÙÜUÿrÖNðL©¬ ±=±Á +A(Á˜Å$D` Ä Übs°@#à±J{ÐëÙÇn#B€·€òK# `0ôí“P8à "ðSÓúÙ[E…£úå6œY˜àC©Ñ!ç†UÝN$M ÷ ˆáZá[ÆnP
>jЪ4` k—ÀæfNÑ¡502>+gaš tà +£$3û°+°´Ç/‚*
—ßPs +( +p¨8º=â²P9iæ@L°¾’ÖeÀÇ÷JÎ`ø/Õe;ˆM§àˆÅb@€çëÿK‰iÍr³
NPÞ ¡¢Mà¾MvÐÆH€Ý“.*gHª—0‰Xþí%[`íE/@QÂ-½72``¥, pjPæŒRÀ6´ƒMW»œ0¤– +,°[0%Åo’R~2P‘rÇ>dfqÃ0ðnЕ +O®‡àO϶í111ÀS®£PÀîþa9ú˜ÈÎ6”kG3ëŽ à6 érf1ælåOçàÀ9dqÔ£!÷¢nK:Pˆ[åºý( +PŽM+8ã SRÿijB1 ?ð6`CÞï¶XQN‘‰ˆò~C¾‚.™ñX1ÖøÓ3 i°:>?ðpG#`ƒ¹mò¦V§ùî6¥âLßToQÀæÃ0QÔd`£5+:…~·ñ&JÐNLœà&ð8bÙZ©‡àÆ¢VõŸƒ>e?„0+?P6 @À¸à< DÏŒ]1ìàfP.nž0ZÆ«[¤˜:¬ó&]ð—_=o²‹‘ôå2å=’÷ 1s@,š»ã»ˆ2}ä}§8=TìïC¹ueWxÕ¡poÐüÍÿYH0S@WÔ_üÖ¿Øoý8oÛÿ±ÇP0\0€üo üE ‚`b°DPCàŸeZ$•eô‹Îò‹ø/•ö" XPB *,RaÈ"Ÿ=H—Äb4f˜D +(8ÒäI”)U®dÙeƒC`©ñ€T éÒçO AOXáQãHkv4r£§IN0`ä€BìÜ©jRH†2 U’R©šT‹àd!fц•:ÉErÄY3!¬Có°h¡‡“
ìàÀèŽ
°ÀÓ¦ŠŸ
ËÚèÙbµÚ¤ŒÐ€IŽ:zr0±:€I›‘ÀŠlÿÐ ÇÃwžV•ðÁèR7eJÙ-rÀàŽt‹&W‹!RXLê9àE“&9Èñ¢çggd{¾ ê'(å05»t'RZà´{@o£|p̹Ä;J×"ùϤnˆÄ‘?^áªî0„‰"¹ã.×:ùc<Þ¹ãH^@+;䆹N0å)$(n€ diff --git a/library/images/pwrdLogo175.gif b/library/images/pwrdLogo175.gif new file mode 100644 index 0000000..4d7fa25 --- /dev/null +++ b/library/images/pwrdLogo175.gif @@ -0,0 +1,52 @@ +GIF89ao¯÷½½½ç91sÞ9µ½½)s½µµç11{ÿÿÿÆƽç)!k½ÆÆï9µµ1sç!9{÷÷÷çJ!çBç!µÎÎ1s){)J„!1kÖ19{ÞR1ïsÎ{k÷¥Œ÷„ÖcJÿïÿ÷½1!ÞJ)Æ”Œ!B„÷çç11cœ¥ÿ÷ïÿÖB{ïZ9œ11ïZÿν½ÿ½Ö)÷„kB1ZR1R÷µ¥ï{c9RŒk1JïµÿçÞ÷œÿçBcŒÖsc÷œ„Æ¥œ„19ÞZBÖkRïcBï”{ÿÞÎÿÎÿÎÆ÷œïsRJc”ïç÷Î1ïRRk”ckœçÞïZ1RïR)ÿÆŒœ„”¥ÎÆÆ¥11÷)B„ïï÷s„¥k{œ9J„BR”„„µ1)Z{1Bï)ïkJ1ZŒk„¥ÆÞÖçÆ¥¥ÎŒ{{Œ¥ÆÆÖÆ1!Æ)÷”{¥µZs”)k!kc)1kµµÎ¥)!Æ¥Zs¥¥¥µ¥91ÎŒ„ç„sBcœkZ1JÞçïJcŒÎÎçÖÆÞ{!1½)÷J)Δ„ÿc9ÎÎÆï÷÷c{œks¥””½ccœŒ))µB1ÖJ1ÎB)ïJ!9Z”¥ÆÖÖç½½ÖŒŒµc)B„1BÆ÷ÎÎçcRïœÿ{Zÿ¥Œ”ƽÆÖ1BsµÖZc”œœ½{{¥œ½½µÎJ9cïÞÞ””ïÆÆïB”µ„¥µ”¥ÎŒ”cs¥Œs„kBZs1B{)9ŒRZ„BJ¥RR½ZZ½Ö{cÿB÷sJZ1)cÖÎÖR)J½œµ{Zs¥„””k{Þ½ÆÎœ¥œck”BJ”眔¥Þ¥œ½cRÖÎÆÆÎÎ1c”Bc¥9J{ss”kkŒkZ„œŒ{c„”{”Z!B{Rcµ„”µss¥cc½RJ¥!ÎRBµRB¥)ƽÆνÎçJJŒB9kcZ„”¥œs„µ{Œk)”Zc!ù,o¯@ÿH° Áƒ*\È°¡C„D$ É3jܨ1‚$>pÄ$ “L¦Dɲe€0c^„ù’¦KŒFHháovœâÂ…ÊŒ| )Ƥ J}ŠÑ‚¬NJ•«×`3R@Ñ ¢@Š{¦x)¨ÐŒ2d ýP‚‰W¡|$H0ÁBP @•`nß¾R–ç@³i°¨˜%‰”PY‘ “„ƒC6â`ãV5j¸¨!·£%€8=à¡A¸$ìy!PæÊ#0©ñ[ã$-61†8(変Š½ œ°Ñqi “ŠÿQ|ÀŠ €£›'Zžoy€ÂŒ5€™ëonæÄŒ3PÀ]‘ BqB9péi@€ïQô=QtÁÌ'ÔŒ4Ss¬š~ä_¥XÕ¬¤at–l€hpp–ZÔ@ È÷ât„@“y–ÁÂøÀúÀM) øâFà0£´·“{9RÔ@8Rj¸€ €‘BsðÁˆ +{|Ö\ÄÓD;d8eK 0I{4aAuŒæ|xðƒ2 +†ŠÐ2K~,'ZÞ$°XÝÉ’&¤RŸ’…JЮHišn´Ä
V†€RŒÿ0dH:XF ¡C/¥:ÒEdQdý À×à‚ ¨úŠ>ˆÃ ð1JVððaz°(ñL`ê,G ñžcm©À%:ß0„ðí䀅 LkØ:_$B”ãrDA½·ed +ˆA=4[ð7$0ˆ¤|ÂÁ£šø[À8«úX0N 4ÙÉ’IÔ0ht1òMt1‡ Œq̾|m˜œnŸ +TA8p0’¤ìEÁY@0dµÅ{ ùÛX´P§Îo
lŽÆDŇDKœ‘d&Є·™@ñ¡X`‘† I|À Nì•…¿>ÿA§Ó\Ó7¨(1¢s.›ÆQifÀãR˜ÐE1ÑC8d~ÅåœóbÄç wa‚ä¤sÀ¨?®ºãS…ÉxM2UPĹ[’ߤ…ˆû¶¡m;"ï‚å¾»îƒ ?ü~`°Ÿ´›ÕÓc_|ƒ|áoz|aÇT¤ }@¡I@ÁƒhA…<@ð{ +TtÐAçëŸO¼&TÒþõé äa¡ë!‘QKO˜#.$7¹á‚P-lA‘8„4 ¸/w 4Þ~Ò#€0ði¤BÙA`Ð nèCP0Ã7ØC@ÂFp„ž€@Wÿ2s€qh8¢e2r¡!' +Ї,°¡VotIA ËW¢ ÀF$¿ÀkHà‚ î +Ü[0„ìda[2ÀŠ .Ŭ¤nÌÈJ˜P‚@VæÈvö2 TÍN#;À +!J`"ëšRJPƒ»°d˜“ Àé5ç§zY}6°‹7 €ä|Ê„¹„f hJT™È€ Lâ)äI0HA~!7ôq–"(&G,PŠäâv#l’P€$¡mAŒGp +*Œâ¥#ÈÒYpD(:`Êl*ÊŒ˜Ó¥Üâÿ íE8@ùXà3µP¤BiiÀ2©)t¡H‚9’"^¡†z + âÈ‚ +°À4g9 é„óp´“ õ¤EàC+3¦E"¢ôVÀ%L ××qtvÎH@º‘PA¼è¥ehŒHcVv€8¸IQ…°øUÏÜ! Ã;=ƒa€–äRŽ`‹_¬8p¢1˜™.Â*ˆˆcX#;-˜¤ lœ%Gñ¢@²Q ³i +kKDa5lÍ54À
ˆð,œõNÁk´LP
fà@³”ÚÒr¨L’©"NHÙê&pfЂÿd¡W:“$
+z.ÂéFÈÁËHHÛ:†6<5xf@Æ.{Xlv"*È5¼Tδ …*Ô€iømI )@*ªQŒr\¢âbð‡0€Z&àˆP5pbd Mp¯7²Û‚„M,ˆipY‚4¥n;Ð +5'` +*D·r€=áÁæHÉj@í²¢ËaÐ|•Æ®ìì Jh[ˆ3r·öDÊò×¢eÏûøÇ@¶§@V•mÁ¢†éËËÀ0€`Cò€‡NÂM`&P6ð… +†è‚§6ƒx*ª€S¨"ÿ[¿ëÀÀpŠA†„¨@DÆÀ&à&,ªXR
úЈNt +^ F7Z~£Íè†ðÎ
²¦±Âýl-Ž‘ˆ¨'rE„ôÓí`Ã:ªQ¯ºÄ¢Áz– +n‘ÚC¬À’xÔÀ>Öó\m@‹e)‹±•½Åtõ¡4˜! +Pм8Â@PÉؤ7¸Ç-n³„ &C˜Èn›È§o‰‹^“x`(@¶m(äBLû²°öµµÃ|—8hP¬.R²`œejÀ¬D*¾tALRƒh¶fƇD‚ª‰õ§ŸPW#ÿ ¤lLóšï€<Ux‰[‰®v ´8¿Q„©‘€¤˜å¤ñ`à„ë0r0pªhÃp_÷iÏÄKÆ3ïx!6ALj
2!áXa(Îv1«åœ´I}É|6’J¦48ÂÉ[BÌ /€© hòi™íexƒÉÎõJ/Mfîá©Áwªž<¡„Ÿw‰ƒ®Á‘#Sã_r‚;¶ú ˆå–â…Ío$ož(e6 Ñ +…âB]ÂóÙ¯<#1(L)ö¼r ?¹S¼à—€¿eÐesVLcXå%[ ÀIÎÒîœñW€(ìО ÚB(È:ÿGÊx _``ˆé1p…+lNA¨ÀHX꛹ºX&l=ÀXBsÇGˆ×5` +ˆ€b›&½` +Ý„OAq¶T é‚&EEàNâP+
1P1W~óQ/%‘ÀY?s!J÷"Oò}7BS¥I8ð·§!Rp„!*‚%w€oA¾€mE>¸Ðw–ðð²”h}˜ZðbPªö';Iár(®²ëqðõTWp[R(Ù'Às,ÙÕ(Ð#¾ÒRZãhRö×ÿ ~`JÔ"†U0°"R«j‚Õ²`ˆaxvn“6«Àªç*½mÀ]ƒ]àO@;J`ˆz’`%Xž÷
®—* aNE<psà7§à>»”à`)'°‡.áF€f¨j'ó<9ÒÐ`•Y‘- +ØVŸàz)¦Ä©`^ÈS€PaÀ©†j±¶ À q3» ;Ô™ðQ“‡æ`[¸õ2‹Ð
B!½…]«Öe¥S#Žé@<+00€-d`J>`‘t0U¤Byt°…51Dà=`…f°²¢ÿiŒÕ‡b‘.1p•„jhѵ°
932¦wP$)+V`8ƨ7ÐQ7\š•@‚Æ0
@‰ªT +Ý0"Õb q%•‚±RP0Ð?>ùI"—Ù\ð°ÁOmˆ ©Ðrà®%9pz°$F¢˜vÉt
@R +s. +@V0h³? +®PQD3e0yN¢i—-Á¬t@(ƒ`/1߈ƒ/‘œ ~2U —Ы(=0oy¡™btÖõ„ĉg0›w’ƒ´0î`_35Su1Á³3@ w Pbç* +ÿ ô„1àœð$Ë
W@Kpe ±˜àÃYŸ9—©f,½&÷µù¥3BäÐ4~sOôrÆÑy>ójj1žî3S`¹0i—ïr*($(—VoŠrn0ž6AB04zÉP¦'à¡Qq;ÐN/Ý”tOA5+È0¢ š/ÒzëÂŒÁeXYA3 @H*v2)úÚ_äRM0]>ªI0%¦²]ª‡ @Т™!X@=òQŠ.ŠrNpƒã²“$*^daÀŒ25¦:qúrw³°6Ac€1Ïrÿ ’ÓŸÃ=p9€+°°(°cœÊ©êá*û1-2%SZª¦Ê©¤º©ª +a`2ÏC}ð³2=x‚¸š«Ù”<ËkIæ= B `ð +¸™=q0Æú +Âúg‰À zð†p +x\&) ˆÐH® fUÆú¿#lÐH·pgw¦ +Ô¹0yÉh(ˆØ”0{ÉŠ{@šcPÍU<0 ï`°`ðÅóf¶õãdU0‰ðu~J>sVšP<€ +`PËZëˆ%Z²BQÏ¥«*»²öÄcð[ù«4³4«ÿ$A·q³ +³;k³6{
ÝGA,pAP òÇhéB·Ú€pô'ˆ@„k{Zl€en¡Ö@ò…j¹ñAõÀZb@$ðA¦¸{2dW«jxkt隨†P‚hµhñm½fj«fR΃‘·ÙR‹@È9rTdx‰k2ÉÖ¸ÈÖ[…¹ì´¸{ûk,ÄBýæoÓÖ×öÃ@p<tà'pºBÔ+E„D0 ¶q¸’«å `p¦{ ¢ƒ:ETDJÔn!~û˜!0o°[x{lÉf¹Ð{–Û@0Ô§F·I´)@p„‚¤FEÿHÆK.5qG0º¤[º¦ûCl +¥9xìV(!ÊQ¨!E({ûG{'a%.hŸž¤8S’ô†Z¿óQ{%¿áLáàGã;ct´YzR¨x50ÿLµdzzYÙY$erL†äÁŠg‡•¥š1AúyñªIÄÑ·ÀSb0 !@;Pvz'w3;wÈæLs—LÀs\œD N™ÛJ`t‹¤6ÀŒvÐt½†.ÀGãë‡ta"ü+Ðu^· ”<À*Ðu£JG’‚e,
àñŽã‘DŠq´ÿÐuq0W×ScP
ŒpÄàÈLL8p'wB!±qHœáuU@Ê°/s)D¸wƒLœ9‡2p÷˜Y‘×ÑsÕw¬—”ã5×ët”ܞ콿rI¤ÔcÍ9%p$Â#·€K”q'E±Âp¼ ð
~ª_y.2V,0àQ@EöØpzÅ<µ×Io|×&˜MG7!ŠLŠ÷¿a c _ ‡À@eÀzƯႿ’ À Ö³z@•AqUüçra©EÐО<%. ¼p…Ñ¥ÿ‡ÿ¹#Å'!M‚.€Ñ›êdc Ÿ[RÃ`‹óÁLP|üMPÓu¢nc7:ð-¦!.àÃŒ°Å‘E’enËÊz ŽÝ+ÂÀ”@Õ:…˜@Ê€ö‡"¯œìIkŒzP$ñºTTÑø"Ò4´ñ·ðÍ@¦{®ÐM£ a-ÅoapÈ_*ß·Øý"‘Ý4J S}‚PüåM‰ñ@G[èdÒ&ÄYfA4ðÊ÷0f'x–÷FDÑI +CÍ%sÀ=.XÓ~®]Žp>ÿ€[@|V<ŒXNKƒ<Èa|vCçÝ€°¨FQË/Ø*½Ú'XûÎ2\I +)d¼PUÓ+¾DÏŽ‰„¡uTq!7lÝ’iµ˜ÀÍ:}$À•a‡MÜ·•Å¥J™
VØ;¥¹ð€¶•ƒãâP>ûMxZ«Ò÷2Ä
3p’ "$b Ð:ÏoáÇÉṉgzoíQ]PŽ®bž1€¸Ù;¾ ZÕëýQe0¯[+ ã°ŒÅ6€'ІrÀ஢ªðã½³>àJ¾ä}ð¸@@•2w›æ.ÿö#! 5Aq¸(F ±à õ”°À7\ã—8#<Àk
ANl˶¼üÅÏà90ÔÎ!£`1Òã8œ²~¸ÛtëiÌ°—˜Uê{ U@˜Q5
QPQmU4¼lú2 Xäóä–´@ž¨R‡È_ð¬ŠR VÊ ØŽw€ŸÐV°a#CrÞ߸Àªké+ÇwÑÐ0GÐ\[ŽL°ÀÍI7ÁÓxè±ß\âù쎞oa70ž!’ÅTý¢xð
°á0]•Òý'DU€
Ýè,°Q¶åãœñ𓂉7W\•T@¸hÿhI
`G¥)C׳°SIÈ)ÌÁÛ0oÙçKnwT׋œW¤›à7Ä™Ð:@.56“ÂË JW&PÔZÀÁü µ('êIµ:°¿põ'@9)pW%™éR 3,ˆ—<@¶
£¥) ? ¹‘ÝhÙVf0xõ^' Ä]¢’zúeëj¯TXó#p÷d“زøŠò 0M0¨¿”“ŸjgÞ’ç©™3… (Oú’xž>0ë½æÐvÔÎe +
/¹æaxO0FP$nÕXøüê+°ŒÐJ`ôŠ‘Y¿ÿ8X$ÿÊŽ3p‡³‘HWsßVÉPKGµûb„%Ìú©†#ã™ +¾OO0
80"µ/WÆw€eIs ÀA„ .d¸ð’H Ñ@EŒ(ƒÇDC!ÈbW6ð±E) (ðËnÀ°!ÒgÇ
&^|±"‹™áðÓ)ÂŽ˜š¹¡¦X HI³:3$uÂàÓ§<И8±¢·/PðàÅŠ¦h:–‚+E%¨RàoŽ¨)ò–`F…³z}8BC¨Ñ¤'*øƒoÂC]ZôiÒ(P8`p3?
pÿ–ÀOÌ”ì.Ð!Ž’ª.\£q“ŠA€X8Cf´ B! 4“Iy–`
n™)³#øs‘ªÝ4(z\£ÜŒBš£g¸ ‰Š:Áäzlˆ6 ¼” +`@™%X£/=.È,®£Üà2¸bÁ…HCJÀCiFH ‘¸ +¯XT #2: ÁŒæŠ"¶È®ZLh,&˜„ó
+Ô0±+3Byl4á² ßC®"ìØ
Ç&¡:À CÔÈc&3¤ %MŽDÀr–¸)KŸ„𽊊RÀHŒÈ‘̓xÌ"ŽÁ€š(#<<ÂÑAAÿ<z€ˆ2Ã)ŒXè@bH4¡8 ç2êA…8b3œbî¼S$}kÆÌ€c&b0õTÒ®À+‹ $˜©‡f¥õ ¦4Ê(¨( ƒ
LðµÅÖZc²WBH`)~)ضdÔ¬.:“ÅóAte :ˆlOu`ÑÚ„*°¬½7%R@‹IðÖEZÎ‚Æ +A_„,h¢…že!ËÜs#WÿZÉÒ¢m¡%,
µpZà¬Ò4Y\`‡`X÷àP0nX÷ "&϶‰±B4ÏQœPâ†Lf\ít°À´‹“FziŒ›Nú ÜŠ—®ÿ:4pXæ,Ða,",† +†0ïã¼níãUâ³Pf„¶~‹.´Àà°†´æºà‘Xb¬6nvG´…vši¥w:!X6J¸Ê–e³Þ:%H!ûÂ.Ûûž07Ï~ bž"BΣÕàT‡‚³"!‚¼"s`Ðav8}$ûœd‡Ö)|ÐÁ‰ SôÓÕ·ÞñÆA£…ëú"È32ÉpEwÈÙ“OW¸ôO=àŒ‹#»qC |§GkŸ`0½ýK½OJ©’afR)ñ-„ñUŽx§Y9âÖ³*£ð<„ÿðÁýq€rƒ Lƒœá…Èô°b(2`ÃÝäp7àa{¸ñ…/Ü€p$"ñ +gàEÎàDF1]0¡ 0áœ@‹¸Äzæ)¿„çˆ+ÀwsÃê%bcÝøF8ÆÑ41L. ”ø ^ÀäøG@RƒW €GÅè8q©xùHHFÒÀà³0=@Ž^ðÉ؈’)X…‘Ž”’ÐPЕRyJ |²•2ñ$(O¹JY²1–¯œd%—öh¦"’ºeª0Vx"aR!!°‡ ¸‚¬˜€€ŽÿT2"mH& Añ|Á +†(üh˜cNš<0Qo^V@¡* á Dh¥˜HÁ9#ø´ÇUœ”I(1—t"¸)€¢ÀBä¨hƒÀó…8D! +¯HD"&Pð0@m˜@Z¡J0à˜cafA;MD¬¡rôD"òð…(ìažáá'L¤@()/›äA%‘‡f¨BHD¬€8XíDU€*$1D0œmH<U‰Î(´bD;;À†@â;åŠ*òÓ†2Ì”@]4“MäR}#AOdµÑ@\1Œ_{KV”Š],Š)ù
Ø5J˜ÉàXÀfV³›åìfé)IÐN +Ô"o§¤Vµ«e-Xð×Âöµ±¥-jÁ‚-„Á‡PC +ü¨Ô̆V ÂF0˜½JN¹z„öH%4 º + î/ë°8DB<Ð@ +RYÈÎö‘\±Ãr%ÌEÂE½ºrg´Ç/ÂG˜,£n¸ð‰ÔZ€ƒny«È°rƒÅl11ÌWBÃr¯y1'Ef“ù"rJ;,·\‘ÕåÂ? Úý†!TÂ4ÐÊ]6ÁŠl°ªÜ diff --git a/library/images/pwrdLogo200.gif b/library/images/pwrdLogo200.gif new file mode 100644 index 0000000..467cd43 --- /dev/null +++ b/library/images/pwrdLogo200.gif @@ -0,0 +1,60 @@ +GIF89aÈ÷½½½ç91sµµ½½µµÞ9ÿÿÿ)s1{ç1ç1Æƽ9{½ÆÆ!kç)ÿççB1sÞ)ÿ÷÷Þ1÷!J„ÿ÷çJ!Þ!µÎÎïs1)Ö1ÞR1÷Ƶ){9ZŒï91RŒÖ9!ïRïsRÿÞÖÆ¥œïR)œ¥1k)1cÆ1!ÞJ)ÞZ9ÿÆŒœk{œc1JÆ”ŒÞcB!1k¥Æ÷”µÆ1ƥƵÎ÷ï÷µ1!ïcŒ19œ11B1Zÿïï΄sÎŒ{ÿïç!B„ïçï{1BÎ{kï{cïŒkÿçÞÿÖÿÞ¥µ1{ÎÆÆç!ÿÎÆÖkR{Œ¥J1RZ1Rÿ½Rs”BcŒ„„91c„9BÖR9ç!ÖcJ÷µ¥÷¥Œ÷sJc{œ1B„ïZ9÷µœ÷ŒZsœ÷÷ÿ{s¥ÖÆÞçÆÆ÷œ„½ÎÆœ”ÖsZÿ”sc÷”{ïcBï{ZÎÎÆB{”Œµ÷ÖÖ„”¥s„œk9RÆÆÆÿƵ9Z”!9{ÆÆÖÆÖ!ï1ïÎÆï„k÷”Bc”)kRZ”ccœkcœR1ZçÖç÷)ï)B9c÷çï„19½!÷ŒkïkJcŒÖÖç½½Ökk¥çÞçŒ11ÞZJÆB1ÖÎÆŒœ½Rcœ¥¥Î¥œ½çÞïs1JçÆscÿR!!1c½½Æœœ½cZŒ½µÖÖµµ¥ss”11¥B9ïJ!÷Bÿ½¥Jk”¥µÎJZ”!Z19sBJŒœŒµ”{”ÞÎÖ½Œ”Æ¥¥ss½cc½JBÖscïsZ÷kBÿ½”ÿµ{œ½µ½ÖÞÞïÎÎïJJŒRRJsŒ{B)JZ9cJ!J„Rc{BRµs{çµµÎ9)½ÎÖc„”¥Æ!cc1!JÞÎçsJZÖŒ””9B¥ZZœJJÆZR¥¥RJ”!)ÞkZ½1!R{k”„kŒ”k”µ”sRksBc„BZçÎÖœZkÖœ¥”ck½„Œœ19!ù,È@ÿH° Áƒ*\È°¡Ã‡ (@#h̨±£Ç$(ÀÁ‚'˜°ð$F àÈ¥Í +d#†
`>ýáE†¢"$MpHÓ§P3Èi0` Ø 4äL¯47Ž´ƒ‰¯_Ç–=©QæÍ·pãʽY¡U‚W V¼Ú@ŒÌ°hsœ`!G„š L@ÁpÒíÜŽxHžìFZ#‚Q èÁãψ٠ðjÞÒUõ¨¬ëÖ_3ax¡BGÁ!50!b I/‚>\ÂÐȼ˜80õi¬Í-"G™ ¶ß*8Ñ{pâàƒ#ÿ TóõÇ@ž@Xo¢|Ç0pøè‚á.èP8±éçY Fv6Ù`'u„,ÐÅ
,0 !Hh‚’i‘Áy&ÄÀ€Ü'œW¤W97€ +ø˜d8“ ‚4*8Í*UHÆD‹ÁXŽæÁ
Â Ç +Z¡hs´è¢\ +Ðq@<2e ‚ŒdixÖVó=Ù*":° x¨dAsðøn°Ñ¤Àµx¤„ˆÂ…Äàp¥‚üˆ“bÂbpÈ°@Ayöœ@²Z¨F€ Ù#8pÀŸ`á
Dà€§x,¸ I˜œÀMH:éG#ˆÿH‚(j®YUU)ô‰GpöêšiŠ‡…w8aÀÅçÀ’åôêM±&º(®ÜšæsWñô=P…Å027t0A*ôÀ„‚‚]K]:h>šd¶¥I€#¼)pœ^Mp +¡œÛÂ%¼!컶àÂ( AözTAªÙÚ¯A+ EÀ—ìëWÜQßtpI,ש-‘adlS +ë»&¿X- ûßf¬€ +(AF\rÀ 0ÄÄ$±l³Eâ:ß$ÇüRtb^-pÅ»¸gôÄñ]ÔCì ŠI@ŒŸ5GÐÑõMDÿÀƒ‰x¥VÑøö{ÇõE³¨@„WÞàɉÃ5Ç&:×ÜUÌç,7Íyh`üÙHFÄ ®ð"ôš^ùM/–íi€>ÃÛ!xp“óP…—i Åd' Á#y”@ê¬Þz[Âk0»\Ô@·V
`ÆÛx¡ö´p¾•€ +N}h`¶×Ïl±ép-Ð0Ä^°aôïÿ}ýÃ’HÀbé>°Öè4JXN&“„F4mÀdz€„b1À
xD®`€.àlHÂÛžFˆÉt?ÀÁdz šb2k(Ö1™HtBÀÿ¸ð(Gi+E€ –6Ä"i +|ᙟ¡X¤MQQˆL”"~4¥Å*jJ€0âP¤‚0°_¦QR'‚;ÓP„oŒ#–FF dxE ôÁkÀ…HpH€\ÌbÁxŒQpd«£ÏTC•Xò’–”6ɤ€rC
Di„Ra¨œPÀ`ƒD ˆÀ$&ñZ>à–pÊœ2‚Ö)À3V0ÂßÀ‘b"$’fä@“€Ä`=1hÞG&`õ@@@hæ2×7X˜;È6 ’äà™íq^ÔŸ0Hy€*†-ÜÁz³›Ï×ÿ(Õ,°ï4>"(p€ +Ë`0t‹ÌÏ+:@9p% E°s§æ¤`Z0è6Q¢Ì5, **j“fš€ÈD9?ÂN(°å<püÐh¢‰À²ûL ð´P'sÄÃ!8OË‹ÀÐÐÒLX3›ÔÉAP²ƒàçHŠÎ^´µõ=&óŸH"`,Õ€Á©Æ 0¤!ç™@=Uë[ +`Ÿ"qa?þR
“Üd²„¾I¸\”…UÌ‹xpr€1JˆèÃýuF&}àz7•xhà8ôb‘øB Й½@Á9 t°Yÿ 6[E0+€*%™*| ;mž”ð€Àn2kï¸I!2@Œ?ìíÔD–Šé¢–‚EJÏÅ!hÀR/¬‘;`7¼Ê¹à>zàgt
‚-ìÊ^È"B2ˆ%Hbl¨r‰sjTÂx¸Þ ±…)QIšƒ °XwR +@*(¡04,fá À€âz °Áö¢ãÆpm‚€åNÆb¯h d€ý,ì°a1UZß~r4s›‚pœë½ãJ! ‚‘ß +‡(þ0
hlÂÿYŸ]Ôû±GåáQ+šÎ`³W X!°Ä%&
Ø.ÿÀp†¸Y°á®V@#Á”(ÔŒ]”> E@CÀ®
:%´@‡œq³#0Â]ruàé@$”P¹’Þ'h‚ +€®&ÜÌU-.¬ªcƒ
¤h cVpBÐ’ªGŒšÀ:œ”¡c( +@IÍIu½ÉŽp„0<ú-/(wºYÏz¹(Ñ48†D š (¨BN`&À€P +…"&£…Û„å}6H"p95=gnž5
tV€T x và‚ì à÷ÀÁÿí +4¼ß‡ø³íž…m +Xäb7ÎñŽ0?Q¸–½w +€(¼5jmÿèºq†fÉ°™Ä&( çá0`ð0± «Iƒ¿Rà„F±†–)†97€#šÅWÀk@xHÐVh8‚
nØ.5ÁÑHö45f˜ØÇNö²ÏÀ\Ú×Îö¶·‡D€D4%{Üã ¼BmMlÛk«Œ@à +ÙŒ©F./ä9¼Bðˆ"Da+ÐN= R?U0¥%ÇÎÃñóž÷üÅÿ~«Òoòô(Dê;ÙIa¤àõ)Pý@OûÐ×þörTHUj0”®Ø—“ø¥ð¡’i} .#é³MƧ€I”@Eà%RILn ×߀ö]}zPÊ!È´´ÿS0ÒÏP,ˆ&HFÒ!k®9P¾¼m¢„?+–êõ™T@
PP`€~P 9#ó§V`;YÑ%à"6aò1) ð +8-§=³·9(}A[…1j M©–€°32hGpЂ†Õs2I‚§%8S QÇ ƒ§ TXsÑ +ÉÖ5Æàj]§nÔ5-bÍ4-b)à ¿1@èòa =LÒOb…)ÀOBÑÔ +0—bwÂqØæ" @Ðg€-&VG&“ÂPTò7e€!»c@.ÿ02¡îg¦cˆeÁARŸOÄÀ€uD¶Òn„@¸1h`§Ð'w.¨€pWkA€†”X£â[ˆ=…þQ( p1ñŠÀ{‹¤Rk0hI£A:â*ÍÄNˆ$¡3å.øyhT+
°øˆUôl`tw'Þ ¹VW‘‚OÀŽ 1â[Vt”&QºaLðŽñ,ÐvÀ%söðçhÈQC€'$Òw@#8rŽ.ò°v(@Ùa/ )6E ÐจýTb|Q…2·ÿ !Y#Œ
p v@<hezõäà’]Ö@L"çV9h°H` +'€!d€O·1-Càšeiwv@5; 7Põà ¨Åt`38¸játW`=È/iˆÑ&S| nñ.57°¡@P#!P0°>A["°Y#Ø/Ø’Ø`“ýÇ[B@V"-s |p +û%œÖ[˜8#Е J¹93my‘‡`Q¼E`¶ F`{ Zâq» ^¨˜é";pà‹¢/ŽbG eè"@‡î‚5°Ss€ò +>`epœ.ÿ+À†gÃ8mï.
ƒpA4 ˜@IàdQ´ž`c°’.22ù3eTb°b怷p
ù a@‡°PšyòÊ +,˜ƒq9ðšNˆ‡`°˜1`j0`.Â-ð-–â. +S3/™8 +°âxïÃQ$àŸ¡Uä 0?pa×ÉT³0 ¦vqù¤`ó><NUa6-8@«ð /Š¤JhÕy7Z9Л76—FyÀ*¦¥(°ÃÑ]à0IŠó@OYÁ¡~)0…j¨`Ð9©•OvàU³¦†ÿÀ.• uy2€ N`'ÀMEÀ@!؃¢z¢3%•}¨—Õ)€
lp5ç‚'upe¥¸7"¦F
DG1kf]ób¼!°`tò¡˜€lÀP*—FUg;êw±:fP9að“Kw.…†Âœ/9੬ÉZ³Q~°B”6×£ËH +ßQ¦,ûY€iðëã7!Ziû*4`äñh#q¥Ð^p m‰ÃÁÆPE¹7#!iiÚƒ¸’š0%!€ +;; ,ÄÐ;°€Îß°yG2 S²iªø§-lepù%DÿÀâ9;µ38<Š;+и~B* pƒq²Ë—^q>Y5«ŠhM ´àê²%ð7Ï ›Ð@´7Á®¢µÀ’¡˜@´Ìs*дx@µÁað„"‹µ’LÉoƒ!ka€¶P´G ,ôÒ`Æé¶pëh€k·w«°Ä„ÌѵÄ!>|³°K°¡¿¤Óã¹”KºÕDkµU;º
–kÜ-°±ò¦e:%åj +!àCh0Æ;Ç0.ðBÐB –ðX-!ÿó?QSr@âq½Þû½ýÿ#Õ;¾7ÐY0½è‹JðëÛ¾–à¼ÎËJbð00b0xωi;™üÛ¿5"ŠBiëÅ-WàŒ´¿þ›À#’”²Êw§ÄR#)·R ‘p»ÐÃZÀ-´‰vÀg 2+-tÄ!q`Ü@û%2D +8×xrSiWÃÍBu¥
àn€ŸÎÂx|7Rù¾Yt]`52ð8HàÐßÐ ûõ4"m0*R` +°„v“@8'kET÷nÐ0{Çw=¥À|ÜÇ`$Ì™†‚7™þ4zIxGÿ0yðxW`‚THH !g¦HÜq w';…Ì^ƒÌƒˆl+M¹/¨‘Š¼ÈÀG‘÷Gf°šp–wO”EQÔH9±•k°v—Ø‚{µ×³Œ"6q¤xv4{ÃH»xFb„º¯5ÊÐÍÒ<ÍÔ¼UÁ1×lÓ‡¦¨Ç…À®{50Î5PKpÎVð6ð%Ð΀K/°r@àTÍqÄŸ‡"âLÎF°E`ÎV0ÐVý®KÏðL|-º…’K`°5`ϸb{½Q¥7“>sð¤;|ˆ|gñ´¹¡3 ðs =Ûw}¨ÿ—£4ÎЪ@Ðb`0ðÓ0ð/`<3«ìu;öN À€‰(A Ödía:ºÛRÅÇNÒ3!Y +¨`ð7ëu;oÔû·•r9€ ΃~Öô‚¯¼»FMùÌzqÖWí<é±îdWR
ñ×וKº
(~\ÿFÒèç ÕlTðª‡m>`ÊL±[aÙȸU‘½Öxá +»§ý‘fgfÄFÓµ½û8P^Q‹"ÚOU@:ðZ©³hhÔwIИyN7…š Í” 9Á#ƒ»æl•“0À®{?ˆç—uÿð¡‹†Ý p»:ƒ2È5@úõwF*–Û
)(RÓÁ2HFWwŒp
(À5 +Úp"¶cÌ°y`ï” õ¨… ±2ˆƒðVÐ S«3#˜›yaó(çè"pÞéÄ…*k®¸NFÔ +ë-% izm¥$¸Óbë‘*ÕëÖ"Ç •8/0”9«‚øQ¯ÂN¸Êâ \@YP›8m¢8ú’¤V(=ŽPq¡m雊%-Ã`±‡@"@j@‰¦ó»…|È™Ããm@pˆnM°nIp»äËwÿò~Þ}Ë~(‘Ø[Ë”ÖtÍL`1@æ7¡t:I@ÓÙæ)ø~¹d±a ƒù’¯YGxiîL@Ùp‘Á‚_;@ ‡Žš~Í=M¥îÔQ0*Cä3€Ó +0㨩P@çoñ“¥`À„™‡¡±K²ƒê‘OÍNàà¿(³¯
¨MÞ‡8Iwp !XP32v óO¹Ò¥žÜÎÚŽµÂå€ÅSt´î3N1`š¾~@§PÅ5’Z#0€
ò€‘ð2h•^MTg!;?ð‹[pg¿,8eu]ÿ`ìÔÑ0W@i[´Ì
D›™Øçð·ÞBð‹}À)óbÂÃn° 3rw°sk àóA„•p'EB Šã¡ã³sl€)ük $YõAâ#â
„à’`;:‚+’³Ó1tàØ~@¬PÁ"µ3•Oð&P~rQ^P$ (É=Á"•3 àV i["³eP³ÖQø.B—E"[Ï‘vù™ww¬AN~
™íp^#]‡ŒàÙRúžX™—o’(¹ô Bw +ÊŠWºÏÞRr@ÄŽ%<àÕѧ±»õt§ a©9¥ÿ</ ûq1˜°Hàv×ë†h )&^(à‹ÂÇcíœÙòì8ŠÜ*@äˆF%”e È ÀA„ .d˜°€\XÀ"€3Z$€ÀFŒ6$Y²¡)U +ᢅ•1U(f ‚‘&u’Œ(‘ËŒ/z$ŠÑcÆsrîdª Âd" 1!ž™2_6YÊÔëÁ0ð³@¨Ñ¡ 3~ ªëW† ¤96¡ž*t@WiϬ*¼Éðîa¼/èÐxöâƳ½=œÐ U^¬W‚!ˆxøs–•UéÉ%ÏP´;®…ÿ]ãꆗ
ìfÓ%/À)Ñ˃À:àV
I"@iÃit¶¬CÌ´»‡£FgÎèõ⢄“pÈc"ÀRAÁƒ÷TÖ^’…b EÑBæ{}ËÀ̲ +
– dº†O†ñd7˜P µ0Ôð
3äðCC •¶Èï(Çô‹k²ð Ý|¸ ¸•øD’Th£ÁÀpÀ +(ÐàE’\H‰¤ÛO#´¬»¨E"aÔ€¤˜ê†àƒ4Ó$¢¤ìÀ0J…<Hé‚ü„ªN¿Ô´H‰Èc*õ˜jˆ>p€ºtà +È`L2@‚ÿ€:K¶¡R<+ˆ8£|‚¹o=,`LJ$è²7àƒ22G8”±Ç`;ÊɳV€”̘ @‹A¦¢A’DèÔ´x™ÐRÉ„„„ÕjtUØd"R"'@ãˆd¨Y!$¡3=hŒ)„kö¼£Ð††¸b5K±ºvWDP0‡G•¨5$ÇÐv¥hÙSpúÂØÙšDŠ£XCÝB5PĉàM©lÁ¬Þ{…c%”=#èw!Uf‹Q&A¾h-ÚWV¹T¥v(ab{³bÏ4(ƒ¾£‚õS•#¢X€f£”ë:þжåÞ R½©‚˜äÿ›qîWÖdRUc¢%…CZb‚¸é§e¾A›èÌ ç„`h ÍTU,ªºØX(xÁlóœ¦X¦°ð
+š€[¡¹‰r“º ˆZÀHr:PŽiÁc^Ï’ZˆP|ñ„6¨Ž6Gaºò½U¨‚µÍ@»Þ©À)â4 +ÖèRyëcg`¸Hãœà öÒ6›[zÀ +:H?(…þ62–îŽa8Òo¡QZ.1ÏS¢Ö–È b7;¬ ˆV@9rÇHFÀ’Ÿã•ä!(ºò”J$ðI<À`†ªÖ!‚(‚!Š`xv?!…¢èÓÿ\D&§@%=aj +¨)/,@@ë° ðËzªàÙÀ¦“ÉEB¡ä‚‡1œ>p£|â•œq‘.;+×±òç‡.§P¸ÜnPBŒB +€aÅŠ >U,%ˆà«mŒŠ÷sŒZò ‰Ïh±P +ˆ +@ˆ6¤O9%°‡Ž¶#†ò@Lgî©ê#B™¶®+ëQ‚!œ†¨äâ¨à(?GþÌggñž½0AXJP–!Ò +’>ÐbpC(S‚iÄ/ Ôâ"‚¯nÄ„SLp=è‚‚ÿ€âÇYÏ.ôáì\àAýWÅ‹ˆ‚€‘4û4°øŒ%&°¥EĤ¿¨BîÉ™ðL•¬òÈŒ@<ù]¨Îhð@3øB”¿ CÄùN#´"6MR]b6„8Â-ø)±ŽP+ùCØþ£°™‚$"J„ÔzAB&
’,¸ôŸ°‚@#‰NQ ‹K€\t†šàƒÿdˆ6€CYd}úÌRs6©Q·±Œ@´`ªÆåWåp…˜!%Á N˜“ì†'È †4@ +5 +IÀZø³šÒ3$yP€‚ÿ1\´$y5À^oC¨ØÁþ¬B^PG™âoÂé4 ±=*(Ìv€-¡°Z(kÙ†
‚íìˆ2Àƒ>6[M^i’
l)3¼=ˆ˜°M~QÍc’‡ðªW!2Dc @ +ð”XRp–á…e2€L¡×"o‘H’ÜÝ€ + …Þ–-€@KQÀm³ËÕímJ`Bò"gÙÂ’çÞ†h +ñuÊw†úî&Š9%ŒüËÜ„€€,Ü"€`'Í4 +$ Ì0 b7UˆT€Öh€z& €ÀADÈÀnˆP†0ÿºMr0Óh(LÞ
*@’þ6Av°Ðvð&0áÇ ±eÐÀ„D¤9 I´Å÷k¤PZÀFÖÅ~Æ/®Ná(úÙz €[³ê‘5ä^¸²“¡&ˆÄÉ…ÆêPVÜâ,4ÚÑ ô ?I‘uD7
ÜIfÀ«vA«;Ð!á4ȼЂ¶ð-¸z}Hd!4 Áˆd';ø³-»VGÛ«¦öª+Plg[!uuªS^PtZÄyþ
*P—½:ÖAP±±0/°à¹¦w?Ó%|ç»F÷Žˆ½ùý™z·0ÿøÀ뽌mlƒgxz•©ƒÑÖ(×÷ÖwÅ-~qŒ[|,2ømè›(d+ã#'yÉM¾FŠ,YKIÈ}r˜Ç\抩lì|CŒÌàå2‘z ᜊX(~( §ç=š¸Ì–ž•ž?½K)gÒÀˆ«Q%m0@ö`€\°@[º0€pÐ BtÝJäú(P +*Iàë¾ Ñ¤p¨;p`W¤Ý1a€+þX +‹’h’`€5hݺpø‚×ä›ënà„L!º»Á¼ ç7ºa€EhK +nðÄßEßDB&,èünº—±üýñ›ÿùO¡D‹R`¯áƒeÅ‹@UðV5<ã»#q¯Ý£è3ºîËb7¥`D.v3ž˜H¡ó¹X†D)¿û"ž@ÿ%` +0c‰ŸÉâ›1ŠS0€Á0±:•Šë’@@“ˆ3„5„µã¹3äH¾÷C‚EA¨••dè.ðŒô%`€E AÓp3P™j“;ƒš9 ‘ÃA@$›šØ9!\B&” —ž¹¼ÐZ*¬Â**ÄÂÐB-œ*ôÂC1üÂ/|èƒØ.@áDÁ5r°›ŠÀ&´?(œŽµ ÈP¦zŒÙC?T0\QÈX¸3฀Ð7t0H„à „rI9³¡:´?”
«Ã¹Ÿ©Â)ÈQðC¼?Ø‚-XÄ@Ž°¦H”CQº€è¨3eÒžßa]ôüáÁIòE`üÅ*` diff --git a/library/images/pwrdLogo75.gif b/library/images/pwrdLogo75.gif new file mode 100644 index 0000000..274a4e7 --- /dev/null +++ b/library/images/pwrdLogo75.gif @@ -0,0 +1,24 @@ +GIF89a/K÷½½½ç9)s1sç1½ÆÆç)ç1!kÞ9Æƽ1{µ½½½µµï1Þ1÷9çBï99{)kÞ)){ç)!1kÞJ)ç9ÞB!ï)Îƽ9sB„)J„9RŒÖ9÷”Î{kÞZ9µÆν½Æ1!ïs÷œ„ïkBZŒ1J„÷ƽÖcJÞR1÷„½Æ11cR1RÎÆÆ΄sçB!Æ¥œ÷”÷µŒœ{Œ¥cµµ½µk)JÎœ”Æ„{÷sZç!ÖkRïcBk„œ9Z”!B{œ¥½Æ”Œ½9!÷¥Œ¥µ{”µRk”Zs¥1s¥ÆŒ”½Æ÷œï{cïZ9ïsR÷R)÷½Î”„Æ¥ÿÆœ¥Æs{B1Z{1Bœœ¥91Þœ”ï„sÖkZïR1ÿÞÖ÷Z1ïJ!ïBçœ÷„cÿÖÆƵïRÿ÷œ¥)Z”JcŒ„œÆŒ”)1cÆ))ZZBk9!JJ!J¥”œçÆÆÆ¥¥ZZ¥11¥1)Î1甄÷”{÷Œsï”{ÿkBÞJ!ÿœ{ÿ”s÷ÿÞ÷ÿÿŒ¥µµÆÖ½ÎBcœs„¥ŒœÆJZ”!cÖÖçÆÆÞœ”çÞçs1JÿççœBB”11µ1)µRJç!ç¥ÖscÆJ9県çJ!÷Bÿ9ÿƵçBÿÖ½ÎÎ¥½Æ½ÆÎÖÞçc{œZs”!R”JŒBŒÞç÷”¥ÆJk!c!cZkœ!ZZc”!Z19sJJ{)!ZZRsR9cƵÆ{RkkBZœ„Œs1B„)9ŒBJ”9BÿÿÿÞ½½ÞµµÎ¥¥µkkÖŒ„çï½µÞscµB1ç„sÆcRçBÿçÖÿ÷ïÞï÷”ÆkŒŒÖ9kk„ZRcœskŒ)JB)RJ1R”{”{c{„k{ÖÆε¥ŒRk”k{ֽƔ{„{BRs)9Ö¥¥ksŒRZœJR½ck!ù,/K@ÿX Á&^!\hP`ƒ‡JœHq` 2jŒAT +/h@€@mmq0²eFŠHdP€‡Œ pˆ0"BFn*!@ÔÂÖ”ˆpàB +G4\X‘‒üHGŒ.3€PJŠ€@ `Ï4|†…@Æ”ŒÖ¥!’,XàUDÉYˆe1V£„à )À` Œb$4&©¥€>*ì €AˆÆ8SÈÀÀ™•%Îas€@Áà䌂$¦jÛ~™¡ì +|€ÀBÎ4mP±åJ“ +Ú¨ÂHÑâá#ÿ‚·$C >«žÑõˆß»g{–~ýøïyt¨`2 +ØÁ€“1ðÃ<!-$1Á €@„üà_±PÀ:Šô•Ñ+8ÇSÉáE +h°YI,ÀXpQ€\PÄM-5ÃhD„› ÑÃZp"\„$V×@
˜À…‡aýÅPk%
o˜!M +#Œ”“„``5TÅTjdÀo†4DCÇY päfWÑ"Ð pL+²QÆ/ð±ˆhˆ c…mŽTy`(POа'k9=Ì ·œuÉÏ B¨m” C^<ÿ ˆp=®–šH/C‚#xb%€lÔpi(°ô•¬¹è€pÀT«ÕBª™m®=y–PÒÂh<1Fã +@8£ñĸ,|Üò„ˆy É…ÈD/ÀCl Âm¬bá0P\’Ã`•ÂÑ 8à\Ø€ÃL'Ààáè‚(ÄÀJ´”€tƒ‡Ñ¯ôB›>Eà͉—Ã6»H(Àì8p§ªµJÙÔ4‘`€Há CµÀÈ£%…ž: G +!0³Ê„•2`‚
`=R(¶¦Å Ìÿ73HQË$¶b@Ë1Ô€OšÍ @“aX@uo–€Ô,—åZº‘†ØÄp[K0qÉ>(PM€°i"`°À%@q˜Ah±jcˆ±ÀþUVÀ®W9,X €'ò| ÊŒ¢B"Am«èÅ…½â_a}…Elã7C!Âk`=§PŒ+PVjÂ;ln#* Âh–§‚DJR$ ÖÔ cP#¸ÆȈJ ¦ŒpÁ)v×¼@)À$€°'¿4ÁèA ˆ± + †{_Ô20µ8aÉ(ac8`=”á(ÿìƪ
t¡g'(€í¨à +Ü!cˆ”d
9°^²„'`ÈÓ‹¶à‚
90B HRE
T€0ÈÁˆ8$0„¶Ã +DÀPabà
Ì1rÂ߉CÎ`aˆ$
& „J"#$(‚b³Ð˜Z0%€A}TPîÀ¯H<Á…SÈDz0‰LÜ’˜ÜC;@`9,Qb²€!@¦Û’Ù ~=OiðÙÜ{Þã'(ÀR&bs‚ýÉ›ªAj €›©ÌCªð1,a \‚
H@Š3¡ø<Ø
6ðÿ‚ h¨g4¡‰Ò3ø UØUÅ*æ€’Ä "¹@äÐ:¾¤b8¶š7ÀO2N:ž4BJrjÆšmqŽAxÒÔ`€±ðdD8ÑZ€*0„ëhD™¾ª5] +¸6Ù°3¾€hâ;+*N:_ÔŒ0e[«UˆÀ[„ ÷YKr„5RÄF]ýP#—‘ü¹¹ Ò 5º¬à6<YÁ@ŠVÔ¯&qÉÖDB6ü!XBm°#-I+š€ À-„6H,O>ä€6܉(€ 2°„4t¸Àt0Çÿ0Ea@ò"„’ä(Liî€Ô²ÅÍ0"Ö‘<8Bš„·ßn†W@—4ÙBl#X’4âP`s¸ ‚@Û8àÎcK–, ‡i4qÀiKR1„À?•*4ðÀ@À/,Áž\øa¨á)“a#ì§R'AŠç’VÁe pqm €0kB‰pàpK…Gä¡Cj2¤BE¶V9àï#ïûK$΂€Pœ@=ý‚ +R¬Œèá Ô^Öê—Däai¾¸‚až÷uœ&ÈØCê"<?<€ÿË-!€Ê …DB(@¶0TnÍC¦9ÆHCìÁ}XÔP&œâ?± ´©¡t¼qE‰@ÇgB3 +„BkXÀ˜`" +p…msT@#Q… †¡†5ÜÀ¢3~DŒ À¹ÃÈ@xa/@d8ÇØéÖ¼€à¤2~-©¼Á +À ÆlY˜‚Ú~)† $ÄC‡’Ò‚&,Ѓz¸ÃyðŠuV@7àŸ@·¤`\ôÁ´G"šý’TA¦ +ØÁò
é`… ·ØÞa ¬±•p¬{Æ`Û1@ r@pI §ÿP( +@px43;U|£I2Pò*w±2 +øÁò4ĤÁ +Ò… À +VÄÍÌÀ,ÕÈp5ô¥ˆ‹Bh†7@ÃK4k PØqBYo‡ ¬LdAC) –fD 0áï(@ÁÁ÷°F[Ϫµ0f'Çh¤R‹–Xþò–_æ7ÏùË (È@„~˜ |€-Ái'ð ´þñ5=QL?³€ ¾ˆAe,+&ç!g‚z1J›8¥0!@Db èA`ñ„` +yHÚYveÔAB’ÐR„”6ñ»pšD™PjñMx`€îO€ diff --git a/library/listbox.tcl b/library/listbox.tcl new file mode 100644 index 0000000..4e84b3a --- /dev/null +++ b/library/listbox.tcl @@ -0,0 +1,452 @@ +# listbox.tcl -- +# +# This file defines the default bindings for Tk listbox widgets +# and provides procedures that help in implementing those bindings. +# +# SCCS: @(#) listbox.tcl 1.21 97/06/10 17:13:55 +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. + +#-------------------------------------------------------------------------- +# tkPriv elements used in this file: +# +# afterId - Token returned by "after" for autoscanning. +# listboxPrev - The last element to be selected or deselected +# during a selection operation. +# listboxSelection - All of the items that were selected before the +# current selection operation (such as a mouse +# drag) started; used to cancel an operation. +#-------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# The code below creates the default class bindings for listboxes. +#------------------------------------------------------------------------- + +# Note: the check for existence of %W below is because this binding +# is sometimes invoked after a window has been deleted (e.g. because +# there is a double-click binding on the widget that deletes it). Users +# can put "break"s in their bindings to avoid the error, but this check +# makes that unnecessary. + +bind Listbox <1> { + if [winfo exists %W] { + tkListboxBeginSelect %W [%W index @%x,%y] + } +} + +# Ignore double clicks so that users can define their own behaviors. +# Among other things, this prevents errors if the user deletes the +# listbox on a double click. + +bind Listbox <Double-1> { + # Empty script +} + +bind Listbox <B1-Motion> { + set tkPriv(x) %x + set tkPriv(y) %y + tkListboxMotion %W [%W index @%x,%y] +} +bind Listbox <ButtonRelease-1> { + tkCancelRepeat + %W activate @%x,%y +} +bind Listbox <Shift-1> { + tkListboxBeginExtend %W [%W index @%x,%y] +} +bind Listbox <Control-1> { + tkListboxBeginToggle %W [%W index @%x,%y] +} +bind Listbox <B1-Leave> { + set tkPriv(x) %x + set tkPriv(y) %y + tkListboxAutoScan %W +} +bind Listbox <B1-Enter> { + tkCancelRepeat +} + +bind Listbox <Up> { + tkListboxUpDown %W -1 +} +bind Listbox <Shift-Up> { + tkListboxExtendUpDown %W -1 +} +bind Listbox <Down> { + tkListboxUpDown %W 1 +} +bind Listbox <Shift-Down> { + tkListboxExtendUpDown %W 1 +} +bind Listbox <Left> { + %W xview scroll -1 units +} +bind Listbox <Control-Left> { + %W xview scroll -1 pages +} +bind Listbox <Right> { + %W xview scroll 1 units +} +bind Listbox <Control-Right> { + %W xview scroll 1 pages +} +bind Listbox <Prior> { + %W yview scroll -1 pages + %W activate @0,0 +} +bind Listbox <Next> { + %W yview scroll 1 pages + %W activate @0,0 +} +bind Listbox <Control-Prior> { + %W xview scroll -1 pages +} +bind Listbox <Control-Next> { + %W xview scroll 1 pages +} +bind Listbox <Home> { + %W xview moveto 0 +} +bind Listbox <End> { + %W xview moveto 1 +} +bind Listbox <Control-Home> { + %W activate 0 + %W see 0 + %W selection clear 0 end + %W selection set 0 +} +bind Listbox <Shift-Control-Home> { + tkListboxDataExtend %W 0 +} +bind Listbox <Control-End> { + %W activate end + %W see end + %W selection clear 0 end + %W selection set end +} +bind Listbox <Shift-Control-End> { + tkListboxDataExtend %W [%W index end] +} +bind Listbox <<Copy>> { + if {[selection own -displayof %W] == "%W"} { + clipboard clear -displayof %W + clipboard append -displayof %W [selection get -displayof %W] + } +} +bind Listbox <space> { + tkListboxBeginSelect %W [%W index active] +} +bind Listbox <Select> { + tkListboxBeginSelect %W [%W index active] +} +bind Listbox <Control-Shift-space> { + tkListboxBeginExtend %W [%W index active] +} +bind Listbox <Shift-Select> { + tkListboxBeginExtend %W [%W index active] +} +bind Listbox <Escape> { + tkListboxCancel %W +} +bind Listbox <Control-slash> { + tkListboxSelectAll %W +} +bind Listbox <Control-backslash> { + if {[%W cget -selectmode] != "browse"} { + %W selection clear 0 end + } +} + +# Additional Tk bindings that aren't part of the Motif look and feel: + +bind Listbox <2> { + %W scan mark %x %y +} +bind Listbox <B2-Motion> { + %W scan dragto %x %y +} + +# tkListboxBeginSelect -- +# +# This procedure is typically invoked on button-1 presses. It begins +# the process of making a selection in the listbox. Its exact behavior +# depends on the selection mode currently in effect for the listbox; +# see the Motif documentation for details. +# +# Arguments: +# w - The listbox widget. +# el - The element for the selection operation (typically the +# one under the pointer). Must be in numerical form. + +proc tkListboxBeginSelect {w el} { + global tkPriv + if {[$w cget -selectmode] == "multiple"} { + if [$w selection includes $el] { + $w selection clear $el + } else { + $w selection set $el + } + } else { + $w selection clear 0 end + $w selection set $el + $w selection anchor $el + set tkPriv(listboxSelection) {} + set tkPriv(listboxPrev) $el + } +} + +# tkListboxMotion -- +# +# This procedure is called to process mouse motion events while +# button 1 is down. It may move or extend the selection, depending +# on the listbox's selection mode. +# +# Arguments: +# w - The listbox widget. +# el - The element under the pointer (must be a number). + +proc tkListboxMotion {w el} { + global tkPriv + if {$el == $tkPriv(listboxPrev)} { + return + } + set anchor [$w index anchor] + switch [$w cget -selectmode] { + browse { + $w selection clear 0 end + $w selection set $el + set tkPriv(listboxPrev) $el + } + extended { + set i $tkPriv(listboxPrev) + if [$w selection includes anchor] { + $w selection clear $i $el + $w selection set anchor $el + } else { + $w selection clear $i $el + $w selection clear anchor $el + } + while {($i < $el) && ($i < $anchor)} { + if {[lsearch $tkPriv(listboxSelection) $i] >= 0} { + $w selection set $i + } + incr i + } + while {($i > $el) && ($i > $anchor)} { + if {[lsearch $tkPriv(listboxSelection) $i] >= 0} { + $w selection set $i + } + incr i -1 + } + set tkPriv(listboxPrev) $el + } + } +} + +# tkListboxBeginExtend -- +# +# This procedure is typically invoked on shift-button-1 presses. It +# begins the process of extending a selection in the listbox. Its +# exact behavior depends on the selection mode currently in effect +# for the listbox; see the Motif documentation for details. +# +# Arguments: +# w - The listbox widget. +# el - The element for the selection operation (typically the +# one under the pointer). Must be in numerical form. + +proc tkListboxBeginExtend {w el} { + if {[$w cget -selectmode] == "extended"} { + if {[$w selection includes anchor]} { + tkListboxMotion $w $el + } else { + # No selection yet; simulate the begin-select operation. + + tkListboxBeginSelect $w $el + } + } +} + +# tkListboxBeginToggle -- +# +# This procedure is typically invoked on control-button-1 presses. It +# begins the process of toggling a selection in the listbox. Its +# exact behavior depends on the selection mode currently in effect +# for the listbox; see the Motif documentation for details. +# +# Arguments: +# w - The listbox widget. +# el - The element for the selection operation (typically the +# one under the pointer). Must be in numerical form. + +proc tkListboxBeginToggle {w el} { + global tkPriv + if {[$w cget -selectmode] == "extended"} { + set tkPriv(listboxSelection) [$w curselection] + set tkPriv(listboxPrev) $el + $w selection anchor $el + if [$w selection includes $el] { + $w selection clear $el + } else { + $w selection set $el + } + } +} + +# tkListboxAutoScan -- +# This procedure is invoked when the mouse leaves an entry window +# with button 1 down. It scrolls the window up, down, left, or +# right, depending on where the mouse left the window, and reschedules +# itself as an "after" command so that the window continues to scroll until +# the mouse moves back into the window or the mouse button is released. +# +# Arguments: +# w - The entry window. + +proc tkListboxAutoScan {w} { + global tkPriv + if {![winfo exists $w]} return + set x $tkPriv(x) + set y $tkPriv(y) + if {$y >= [winfo height $w]} { + $w yview scroll 1 units + } elseif {$y < 0} { + $w yview scroll -1 units + } elseif {$x >= [winfo width $w]} { + $w xview scroll 2 units + } elseif {$x < 0} { + $w xview scroll -2 units + } else { + return + } + tkListboxMotion $w [$w index @$x,$y] + set tkPriv(afterId) [after 50 tkListboxAutoScan $w] +} + +# tkListboxUpDown -- +# +# Moves the location cursor (active element) up or down by one element, +# and changes the selection if we're in browse or extended selection +# mode. +# +# Arguments: +# w - The listbox widget. +# amount - +1 to move down one item, -1 to move back one item. + +proc tkListboxUpDown {w amount} { + global tkPriv + $w activate [expr [$w index active] + $amount] + $w see active + switch [$w cget -selectmode] { + browse { + $w selection clear 0 end + $w selection set active + } + extended { + $w selection clear 0 end + $w selection set active + $w selection anchor active + set tkPriv(listboxPrev) [$w index active] + set tkPriv(listboxSelection) {} + } + } +} + +# tkListboxExtendUpDown -- +# +# Does nothing unless we're in extended selection mode; in this +# case it moves the location cursor (active element) up or down by +# one element, and extends the selection to that point. +# +# Arguments: +# w - The listbox widget. +# amount - +1 to move down one item, -1 to move back one item. + +proc tkListboxExtendUpDown {w amount} { + if {[$w cget -selectmode] != "extended"} { + return + } + $w activate [expr [$w index active] + $amount] + $w see active + tkListboxMotion $w [$w index active] +} + +# tkListboxDataExtend +# +# This procedure is called for key-presses such as Shift-KEndData. +# If the selection mode isn't multiple or extend then it does nothing. +# Otherwise it moves the active element to el and, if we're in +# extended mode, extends the selection to that point. +# +# Arguments: +# w - The listbox widget. +# el - An integer element number. + +proc tkListboxDataExtend {w el} { + set mode [$w cget -selectmode] + if {$mode == "extended"} { + $w activate $el + $w see $el + if [$w selection includes anchor] { + tkListboxMotion $w $el + } + } elseif {$mode == "multiple"} { + $w activate $el + $w see $el + } +} + +# tkListboxCancel +# +# This procedure is invoked to cancel an extended selection in +# progress. If there is an extended selection in progress, it +# restores all of the items between the active one and the anchor +# to their previous selection state. +# +# Arguments: +# w - The listbox widget. + +proc tkListboxCancel w { + global tkPriv + if {[$w cget -selectmode] != "extended"} { + return + } + set first [$w index anchor] + set last $tkPriv(listboxPrev) + if {$first > $last} { + set tmp $first + set first $last + set last $tmp + } + $w selection clear $first $last + while {$first <= $last} { + if {[lsearch $tkPriv(listboxSelection) $first] >= 0} { + $w selection set $first + } + incr first + } +} + +# tkListboxSelectAll +# +# This procedure is invoked to handle the "select all" operation. +# For single and browse mode, it just selects the active element. +# Otherwise it selects everything in the widget. +# +# Arguments: +# w - The listbox widget. + +proc tkListboxSelectAll w { + set mode [$w cget -selectmode] + if {($mode == "single") || ($mode == "browse")} { + $w selection clear 0 end + $w selection set active + } else { + $w selection set 0 end + } +} diff --git a/library/menu.tcl b/library/menu.tcl new file mode 100644 index 0000000..21b69d9 --- /dev/null +++ b/library/menu.tcl @@ -0,0 +1,1235 @@ +# menu.tcl -- +# +# This file defines the default bindings for Tk menus and menubuttons. +# It also implements keyboard traversal of menus and implements a few +# other utility procedures related to menus. +# +# SCCS: @(#) menu.tcl 1.103 97/10/31 15:26:08 +# +# Copyright (c) 1992-1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +#------------------------------------------------------------------------- +# Elements of tkPriv that are used in this file: +# +# cursor - Saves the -cursor option for the posted menubutton. +# focus - Saves the focus during a menu selection operation. +# Focus gets restored here when the menu is unposted. +# grabGlobal - Used in conjunction with tkPriv(oldGrab): if +# tkPriv(oldGrab) is non-empty, then tkPriv(grabGlobal) +# contains either an empty string or "-global" to +# indicate whether the old grab was a local one or +# a global one. +# inMenubutton - The name of the menubutton widget containing +# the mouse, or an empty string if the mouse is +# not over any menubutton. +# menuBar - The name of the menubar that is the root +# of the cascade hierarchy which is currently +# posted. This is null when there is no menu currently +# being pulled down from a menu bar. +# oldGrab - Window that had the grab before a menu was posted. +# Used to restore the grab state after the menu +# is unposted. Empty string means there was no +# grab previously set. +# popup - If a menu has been popped up via tk_popup, this +# gives the name of the menu. Otherwise this +# value is empty. +# postedMb - Name of the menubutton whose menu is currently +# posted, or an empty string if nothing is posted +# A grab is set on this widget. +# relief - Used to save the original relief of the current +# menubutton. +# window - When the mouse is over a menu, this holds the +# name of the menu; it's cleared when the mouse +# leaves the menu. +# tearoff - Whether the last menu posted was a tearoff or not. +# This is true always for unix, for tearoffs for Mac +# and Windows. +# activeMenu - This is the last active menu for use +# with the <<MenuSelect>> virtual event. +# activeItem - This is the last active menu item for +# use with the <<MenuSelect>> virtual event. +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Overall note: +# This file is tricky because there are five different ways that menus +# can be used: +# +# 1. As a pulldown from a menubutton. In this style, the variable +# tkPriv(postedMb) identifies the posted menubutton. +# 2. As a torn-off menu copied from some other menu. In this style +# tkPriv(postedMb) is empty, and menu's type is "tearoff". +# 3. As an option menu, triggered from an option menubutton. In this +# style tkPriv(postedMb) identifies the posted menubutton. +# 4. As a popup menu. In this style tkPriv(postedMb) is empty and +# the top-level menu's type is "normal". +# 5. As a pulldown from a menubar. The variable tkPriv(menubar) has +# the owning menubar, and the menu itself is of type "normal". +# +# The various binding procedures use the state described above to +# distinguish the various cases and take different actions in each +# case. +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# The code below creates the default class bindings for menus +# and menubuttons. +#------------------------------------------------------------------------- + +bind Menubutton <FocusIn> {} +bind Menubutton <Enter> { + tkMbEnter %W +} +bind Menubutton <Leave> { + tkMbLeave %W +} +bind Menubutton <1> { + if {$tkPriv(inMenubutton) != ""} { + tkMbPost $tkPriv(inMenubutton) %X %Y + } +} +bind Menubutton <Motion> { + tkMbMotion %W up %X %Y +} +bind Menubutton <B1-Motion> { + tkMbMotion %W down %X %Y +} +bind Menubutton <ButtonRelease-1> { + tkMbButtonUp %W +} +bind Menubutton <space> { + tkMbPost %W + tkMenuFirstEntry [%W cget -menu] +} + +# Must set focus when mouse enters a menu, in order to allow +# mixed-mode processing using both the mouse and the keyboard. +# Don't set the focus if the event comes from a grab release, +# though: such an event can happen after as part of unposting +# a cascaded chain of menus, after the focus has already been +# restored to wherever it was before menu selection started. + +bind Menu <FocusIn> {} + +bind Menu <Enter> { + set tkPriv(window) %W + if {[%W cget -type] == "tearoff"} { + if {"%m" != "NotifyUngrab"} { + if {$tcl_platform(platform) == "unix"} { + tk_menuSetFocus %W + } + } + } + tkMenuMotion %W %x %y %s +} + +bind Menu <Leave> { + tkMenuLeave %W %X %Y %s +} +bind Menu <Motion> { + tkMenuMotion %W %x %y %s +} +bind Menu <ButtonPress> { + tkMenuButtonDown %W +} +bind Menu <ButtonRelease> { + tkMenuInvoke %W 1 +} +bind Menu <space> { + tkMenuInvoke %W 0 +} +bind Menu <Return> { + tkMenuInvoke %W 0 +} +bind Menu <Escape> { + tkMenuEscape %W +} +bind Menu <Left> { + tkMenuLeftArrow %W +} +bind Menu <Right> { + tkMenuRightArrow %W +} +bind Menu <Up> { + tkMenuUpArrow %W +} +bind Menu <Down> { + tkMenuDownArrow %W +} +bind Menu <KeyPress> { + tkTraverseWithinMenu %W %A +} + +# The following bindings apply to all windows, and are used to +# implement keyboard menu traversal. + +if {$tcl_platform(platform) == "unix"} { + bind all <Alt-KeyPress> { + tkTraverseToMenu %W %A + } + + bind all <F10> { + tkFirstMenu %W + } +} else { + bind Menubutton <Alt-KeyPress> { + tkTraverseToMenu %W %A + } + + bind Menubutton <F10> { + tkFirstMenu %W + } +} + +# tkMbEnter -- +# This procedure is invoked when the mouse enters a menubutton +# widget. It activates the widget unless it is disabled. Note: +# this procedure is only invoked when mouse button 1 is *not* down. +# The procedure tkMbB1Enter is invoked if the button is down. +# +# Arguments: +# w - The name of the widget. + +proc tkMbEnter w { + global tkPriv + + if {$tkPriv(inMenubutton) != ""} { + tkMbLeave $tkPriv(inMenubutton) + } + set tkPriv(inMenubutton) $w + if {[$w cget -state] != "disabled"} { + $w configure -state active + } +} + +# tkMbLeave -- +# This procedure is invoked when the mouse leaves a menubutton widget. +# It de-activates the widget, if the widget still exists. +# +# Arguments: +# w - The name of the widget. + +proc tkMbLeave w { + global tkPriv + + set tkPriv(inMenubutton) {} + if ![winfo exists $w] { + return + } + if {[$w cget -state] == "active"} { + $w configure -state normal + } +} + +# tkMbPost -- +# Given a menubutton, this procedure does all the work of posting +# its associated menu and unposting any other menu that is currently +# posted. +# +# Arguments: +# w - The name of the menubutton widget whose menu +# is to be posted. +# x, y - Root coordinates of cursor, used for positioning +# option menus. If not specified, then the center +# of the menubutton is used for an option menu. + +proc tkMbPost {w {x {}} {y {}}} { + global tkPriv errorInfo + global tcl_platform + + if {([$w cget -state] == "disabled") || ($w == $tkPriv(postedMb))} { + return + } + set menu [$w cget -menu] + if {$menu == ""} { + return + } + set tearoff [expr {($tcl_platform(platform) == "unix") \ + || ([$menu cget -type] == "tearoff")}] + if {[string first $w $menu] != 0} { + error "can't post $menu: it isn't a descendant of $w (this is a new requirement in Tk versions 3.0 and later)" + } + set cur $tkPriv(postedMb) + if {$cur != ""} { + tkMenuUnpost {} + } + set tkPriv(cursor) [$w cget -cursor] + set tkPriv(relief) [$w cget -relief] + $w configure -cursor arrow + $w configure -relief raised + + set tkPriv(postedMb) $w + set tkPriv(focus) [focus] + $menu activate none + tkGenerateMenuSelect $menu + + # If this looks like an option menubutton then post the menu so + # that the current entry is on top of the mouse. Otherwise post + # the menu just below the menubutton, as for a pull-down. + + update idletasks + if [catch { + switch [$w cget -direction] { + above { + set x [winfo rootx $w] + set y [expr [winfo rooty $w] - [winfo reqheight $menu]] + $menu post $x $y + } + below { + set x [winfo rootx $w] + set y [expr [winfo rooty $w] + [winfo height $w]] + $menu post $x $y + } + left { + set x [expr [winfo rootx $w] - [winfo reqwidth $menu]] + set y [expr (2 * [winfo rooty $w] + [winfo height $w]) / 2] + set entry [tkMenuFindName $menu [$w cget -text]] + if [$w cget -indicatoron] { + if {$entry == [$menu index last]} { + incr y [expr -([$menu yposition $entry] \ + + [winfo reqheight $menu])/2] + } else { + incr y [expr -([$menu yposition $entry] \ + + [$menu yposition [expr $entry+1]])/2] + } + } + $menu post $x $y + if {($entry != {}) && ([$menu entrycget $entry -state] != "disabled")} { + $menu activate $entry + tkGenerateMenuSelect $menu + } + } + right { + set x [expr [winfo rootx $w] + [winfo width $w]] + set y [expr (2 * [winfo rooty $w] + [winfo height $w]) / 2] + set entry [tkMenuFindName $menu [$w cget -text]] + if [$w cget -indicatoron] { + if {$entry == [$menu index last]} { + incr y [expr -([$menu yposition $entry] \ + + [winfo reqheight $menu])/2] + } else { + incr y [expr -([$menu yposition $entry] \ + + [$menu yposition [expr $entry+1]])/2] + } + } + $menu post $x $y + if {($entry != {}) && ([$menu entrycget $entry -state] != "disabled")} { + $menu activate $entry + tkGenerateMenuSelect $menu + } + } + default { + if [$w cget -indicatoron] { + if {$y == ""} { + set x [expr [winfo rootx $w] + [winfo width $w]/2] + set y [expr [winfo rooty $w] + [winfo height $w]/2] + } + tkPostOverPoint $menu $x $y [tkMenuFindName $menu [$w cget -text]] + } else { + $menu post [winfo rootx $w] [expr [winfo rooty $w]+[winfo height $w]] + } + } + } + } msg] { + # Error posting menu (e.g. bogus -postcommand). Unpost it and + # reflect the error. + + set savedInfo $errorInfo + tkMenuUnpost {} + error $msg $savedInfo + + } + + set tkPriv(tearoff) $tearoff + if {$tearoff != 0} { + focus $menu + tkSaveGrabInfo $w + grab -global $w + } +} + +# tkMenuUnpost -- +# This procedure unposts a given menu, plus all of its ancestors up +# to (and including) a menubutton, if any. It also restores various +# values to what they were before the menu was posted, and releases +# a grab if there's a menubutton involved. Special notes: +# 1. It's important to unpost all menus before releasing the grab, so +# that any Enter-Leave events (e.g. from menu back to main +# application) have mode NotifyGrab. +# 2. Be sure to enclose various groups of commands in "catch" so that +# the procedure will complete even if the menubutton or the menu +# or the grab window has been deleted. +# +# Arguments: +# menu - Name of a menu to unpost. Ignored if there +# is a posted menubutton. + +proc tkMenuUnpost menu { + global tcl_platform + global tkPriv + set mb $tkPriv(postedMb) + + # Restore focus right away (otherwise X will take focus away when + # the menu is unmapped and under some window managers (e.g. olvwm) + # we'll lose the focus completely). + + catch {focus $tkPriv(focus)} + set tkPriv(focus) "" + + # Unpost menu(s) and restore some stuff that's dependent on + # what was posted. + + catch { + if {$mb != ""} { + set menu [$mb cget -menu] + $menu unpost + set tkPriv(postedMb) {} + $mb configure -cursor $tkPriv(cursor) + $mb configure -relief $tkPriv(relief) + } elseif {$tkPriv(popup) != ""} { + $tkPriv(popup) unpost + set tkPriv(popup) {} + } elseif {(!([$menu cget -type] == "menubar") + && !([$menu cget -type] == "tearoff"))} { + # We're in a cascaded sub-menu from a torn-off menu or popup. + # Unpost all the menus up to the toplevel one (but not + # including the top-level torn-off one) and deactivate the + # top-level torn off menu if there is one. + + while 1 { + set parent [winfo parent $menu] + if {([winfo class $parent] != "Menu") + || ![winfo ismapped $parent]} { + break + } + $parent activate none + $parent postcascade none + tkGenerateMenuSelect $parent + set type [$parent cget -type] + if {($type == "menubar")|| ($type == "tearoff")} { + break + } + set menu $parent + } + if {[$menu cget -type] != "menubar"} { + $menu unpost + } + } + } + + if {($tkPriv(tearoff) != 0) || ($tkPriv(menuBar) != "")} { + # Release grab, if any, and restore the previous grab, if there + # was one. + + if {$menu != ""} { + set grab [grab current $menu] + if {$grab != ""} { + grab release $grab + } + } + tkRestoreOldGrab + if {$tkPriv(menuBar) != ""} { + $tkPriv(menuBar) configure -cursor $tkPriv(cursor) + set tkPriv(menuBar) {} + } + if {$tcl_platform(platform) != "unix"} { + set tkPriv(tearoff) 0 + } + } +} + +# tkMbMotion -- +# This procedure handles mouse motion events inside menubuttons, and +# also outside menubuttons when a menubutton has a grab (e.g. when a +# menu selection operation is in progress). +# +# Arguments: +# w - The name of the menubutton widget. +# upDown - "down" means button 1 is pressed, "up" means +# it isn't. +# rootx, rooty - Coordinates of mouse, in (virtual?) root window. + +proc tkMbMotion {w upDown rootx rooty} { + global tkPriv + + if {$tkPriv(inMenubutton) == $w} { + return + } + set new [winfo containing $rootx $rooty] + if {($new != $tkPriv(inMenubutton)) && (($new == "") + || ([winfo toplevel $new] == [winfo toplevel $w]))} { + if {$tkPriv(inMenubutton) != ""} { + tkMbLeave $tkPriv(inMenubutton) + } + if {($new != "") && ([winfo class $new] == "Menubutton") + && ([$new cget -indicatoron] == 0) + && ([$w cget -indicatoron] == 0)} { + if {$upDown == "down"} { + tkMbPost $new $rootx $rooty + } else { + tkMbEnter $new + } + } + } +} + +# tkMbButtonUp -- +# This procedure is invoked to handle button 1 releases for menubuttons. +# If the release happens inside the menubutton then leave its menu +# posted with element 0 activated. Otherwise, unpost the menu. +# +# Arguments: +# w - The name of the menubutton widget. + +proc tkMbButtonUp w { + global tkPriv + global tcl_platform + + set tearoff [expr {($tcl_platform(platform) == "unix") \ + || ([[$w cget -menu] cget -type] == "tearoff")}] + if {($tearoff != 0) && ($tkPriv(postedMb) == $w) + && ($tkPriv(inMenubutton) == $w)} { + tkMenuFirstEntry [$tkPriv(postedMb) cget -menu] + } else { + tkMenuUnpost {} + } +} + +# tkMenuMotion -- +# This procedure is called to handle mouse motion events for menus. +# It does two things. First, it resets the active element in the +# menu, if the mouse is over the menu. Second, if a mouse button +# is down, it posts and unposts cascade entries to match the mouse +# position. +# +# Arguments: +# menu - The menu window. +# x - The x position of the mouse. +# y - The y position of the mouse. +# state - Modifier state (tells whether buttons are down). + +proc tkMenuMotion {menu x y state} { + global tkPriv + if {$menu == $tkPriv(window)} { + if {[$menu cget -type] == "menubar"} { + if {[info exists tkPriv(focus)] && \ + ([string compare $menu $tkPriv(focus)] != 0)} { + $menu activate @$x,$y + tkGenerateMenuSelect $menu + } + } else { + $menu activate @$x,$y + tkGenerateMenuSelect $menu + } + } + if {($state & 0x1f00) != 0} { + $menu postcascade active + } +} + +# tkMenuButtonDown -- +# Handles button presses in menus. There are a couple of tricky things +# here: +# 1. Change the posted cascade entry (if any) to match the mouse position. +# 2. If there is a posted menubutton, must grab to the menubutton; this +# overrrides the implicit grab on button press, so that the menu +# button can track mouse motions over other menubuttons and change +# the posted menu. +# 3. If there's no posted menubutton (e.g. because we're a torn-off menu +# or one of its descendants) must grab to the top-level menu so that +# we can track mouse motions across the entire menu hierarchy. +# +# Arguments: +# menu - The menu window. + +proc tkMenuButtonDown menu { + global tkPriv + global tcl_platform + $menu postcascade active + if {$tkPriv(postedMb) != ""} { + grab -global $tkPriv(postedMb) + } else { + while {([$menu cget -type] == "normal") + && ([winfo class [winfo parent $menu]] == "Menu") + && [winfo ismapped [winfo parent $menu]]} { + set menu [winfo parent $menu] + } + + if {$tkPriv(menuBar) == {}} { + set tkPriv(menuBar) $menu + set tkPriv(cursor) [$menu cget -cursor] + $menu configure -cursor arrow + } + + # Don't update grab information if the grab window isn't changing. + # Otherwise, we'll get an error when we unpost the menus and + # restore the grab, since the old grab window will not be viewable + # anymore. + + if {$menu != [grab current $menu]} { + tkSaveGrabInfo $menu + } + + # Must re-grab even if the grab window hasn't changed, in order + # to release the implicit grab from the button press. + + if {$tcl_platform(platform) == "unix"} { + grab -global $menu + } + } +} + +# tkMenuLeave -- +# This procedure is invoked to handle Leave events for a menu. It +# deactivates everything unless the active element is a cascade element +# and the mouse is now over the submenu. +# +# Arguments: +# menu - The menu window. +# rootx, rooty - Root coordinates of mouse. +# state - Modifier state. + +proc tkMenuLeave {menu rootx rooty state} { + global tkPriv + set tkPriv(window) {} + if {[$menu index active] == "none"} { + return + } + if {([$menu type active] == "cascade") + && ([winfo containing $rootx $rooty] + == [$menu entrycget active -menu])} { + return + } + $menu activate none + tkGenerateMenuSelect $menu +} + +# tkMenuInvoke -- +# This procedure is invoked when button 1 is released over a menu. +# It invokes the appropriate menu action and unposts the menu if +# it came from a menubutton. +# +# Arguments: +# w - Name of the menu widget. +# buttonRelease - 1 means this procedure is called because of +# a button release; 0 means because of keystroke. + +proc tkMenuInvoke {w buttonRelease} { + global tkPriv + + if {$buttonRelease && ($tkPriv(window) == "")} { + # Mouse was pressed over a menu without a menu button, then + # dragged off the menu (possibly with a cascade posted) and + # released. Unpost everything and quit. + + $w postcascade none + $w activate none + event generate $w <<MenuSelect>> + tkMenuUnpost $w + return + } + if {[$w type active] == "cascade"} { + $w postcascade active + set menu [$w entrycget active -menu] + tkMenuFirstEntry $menu + } elseif {[$w type active] == "tearoff"} { + tkMenuUnpost $w + tkTearOffMenu $w + } elseif {[$w cget -type] == "menubar"} { + $w postcascade none + $w activate none + event generate $w <<MenuSelect>> + tkMenuUnpost $w + } else { + tkMenuUnpost $w + uplevel #0 [list $w invoke active] + } +} + +# tkMenuEscape -- +# This procedure is invoked for the Cancel (or Escape) key. It unposts +# the given menu and, if it is the top-level menu for a menu button, +# unposts the menu button as well. +# +# Arguments: +# menu - Name of the menu window. + +proc tkMenuEscape menu { + set parent [winfo parent $menu] + if {([winfo class $parent] != "Menu")} { + tkMenuUnpost $menu + } elseif {([$parent cget -type] == "menubar")} { + tkMenuUnpost $menu + tkRestoreOldGrab + } else { + tkMenuNextMenu $menu left + } +} + +# The following routines handle arrow keys. Arrow keys behave +# differently depending on whether the menu is a menu bar or not. + +proc tkMenuUpArrow {menu} { + if {[$menu cget -type] == "menubar"} { + tkMenuNextMenu $menu left + } else { + tkMenuNextEntry $menu -1 + } +} + +proc tkMenuDownArrow {menu} { + if {[$menu cget -type] == "menubar"} { + tkMenuNextMenu $menu right + } else { + tkMenuNextEntry $menu 1 + } +} + +proc tkMenuLeftArrow {menu} { + if {[$menu cget -type] == "menubar"} { + tkMenuNextEntry $menu -1 + } else { + tkMenuNextMenu $menu left + } +} + +proc tkMenuRightArrow {menu} { + if {[$menu cget -type] == "menubar"} { + tkMenuNextEntry $menu 1 + } else { + tkMenuNextMenu $menu right + } +} + +# tkMenuNextMenu -- +# This procedure is invoked to handle "left" and "right" traversal +# motions in menus. It traverses to the next menu in a menu bar, +# or into or out of a cascaded menu. +# +# Arguments: +# menu - The menu that received the keyboard +# event. +# direction - Direction in which to move: "left" or "right" + +proc tkMenuNextMenu {menu direction} { + global tkPriv + + # First handle traversals into and out of cascaded menus. + + if {$direction == "right"} { + set count 1 + set parent [winfo parent $menu] + set class [winfo class $parent] + if {[$menu type active] == "cascade"} { + $menu postcascade active + set m2 [$menu entrycget active -menu] + if {$m2 != ""} { + tkMenuFirstEntry $m2 + } + return + } else { + set parent [winfo parent $menu] + while {($parent != ".")} { + if {([winfo class $parent] == "Menu") + && ([$parent cget -type] == "menubar")} { + tk_menuSetFocus $parent + tkMenuNextEntry $parent 1 + return + } + set parent [winfo parent $parent] + } + } + } else { + set count -1 + set m2 [winfo parent $menu] + if {[winfo class $m2] == "Menu"} { + if {[$m2 cget -type] != "menubar"} { + $menu activate none + tkGenerateMenuSelect $menu + tk_menuSetFocus $m2 + + # This code unposts any posted submenu in the parent. + + set tmp [$m2 index active] + $m2 activate none + $m2 activate $tmp + return + } + } + } + + # Can't traverse into or out of a cascaded menu. Go to the next + # or previous menubutton, if that makes sense. + + set m2 [winfo parent $menu] + if {[winfo class $m2] == "Menu"} { + if {[$m2 cget -type] == "menubar"} { + tk_menuSetFocus $m2 + tkMenuNextEntry $m2 -1 + return + } + } + + set w $tkPriv(postedMb) + if {$w == ""} { + return + } + set buttons [winfo children [winfo parent $w]] + set length [llength $buttons] + set i [expr [lsearch -exact $buttons $w] + $count] + while 1 { + while {$i < 0} { + incr i $length + } + while {$i >= $length} { + incr i -$length + } + set mb [lindex $buttons $i] + if {([winfo class $mb] == "Menubutton") + && ([$mb cget -state] != "disabled") + && ([$mb cget -menu] != "") + && ([[$mb cget -menu] index last] != "none")} { + break + } + if {$mb == $w} { + return + } + incr i $count + } + tkMbPost $mb + tkMenuFirstEntry [$mb cget -menu] +} + +# tkMenuNextEntry -- +# Activate the next higher or lower entry in the posted menu, +# wrapping around at the ends. Disabled entries are skipped. +# +# Arguments: +# menu - Menu window that received the keystroke. +# count - 1 means go to the next lower entry, +# -1 means go to the next higher entry. + +proc tkMenuNextEntry {menu count} { + global tkPriv + + if {[$menu index last] == "none"} { + return + } + set length [expr [$menu index last]+1] + set quitAfter $length + set active [$menu index active] + if {$active == "none"} { + set i 0 + } else { + set i [expr $active + $count] + } + while 1 { + if {$quitAfter <= 0} { + # We've tried every entry in the menu. Either there are + # none, or they're all disabled. Just give up. + + return + } + while {$i < 0} { + incr i $length + } + while {$i >= $length} { + incr i -$length + } + if {[catch {$menu entrycget $i -state} state] == 0} { + if {$state != "disabled"} { + break + } + } + if {$i == $active} { + return + } + incr i $count + incr quitAfter -1 + } + $menu activate $i + tkGenerateMenuSelect $menu + if {[$menu type $i] == "cascade"} { + set cascade [$menu entrycget $i -menu] + if {[string compare $cascade ""] != 0} { + $menu postcascade $i + tkMenuFirstEntry $cascade + } + } +} + +# tkMenuFind -- +# This procedure searches the entire window hierarchy under w for +# a menubutton that isn't disabled and whose underlined character +# is "char" or an entry in a menubar that isn't disabled and whose +# underlined character is "char". +# It returns the name of that window, if found, or an +# empty string if no matching window was found. If "char" is an +# empty string then the procedure returns the name of the first +# menubutton found that isn't disabled. +# +# Arguments: +# w - Name of window where key was typed. +# char - Underlined character to search for; +# may be either upper or lower case, and +# will match either upper or lower case. + +proc tkMenuFind {w char} { + global tkPriv + set char [string tolower $char] + set windowlist [winfo child $w] + + foreach child $windowlist { + switch [winfo class $child] { + Menu { + if {[$child cget -type] == "menubar"} { + if {$char == ""} { + return $child + } + set last [$child index last] + for {set i [$child cget -tearoff]} {$i <= $last} {incr i} { + if {[$child type $i] == "separator"} { + continue + } + set char2 [string index [$child entrycget $i -label] \ + [$child entrycget $i -underline]] + if {([string compare $char [string tolower $char2]] \ + == 0) || ($char == "")} { + if {[$child entrycget $i -state] != "disabled"} { + return $child + } + } + } + } + } + } + } + + foreach child $windowlist { + switch [winfo class $child] { + Menubutton { + set char2 [string index [$child cget -text] \ + [$child cget -underline]] + if {([string compare $char [string tolower $char2]] == 0) + || ($char == "")} { + if {[$child cget -state] != "disabled"} { + return $child + } + } + } + + default { + set match [tkMenuFind $child $char] + if {$match != ""} { + return $match + } + } + } + } + return {} +} + +# tkTraverseToMenu -- +# This procedure implements keyboard traversal of menus. Given an +# ASCII character "char", it looks for a menubutton with that character +# underlined. If one is found, it posts the menubutton's menu +# +# Arguments: +# w - Window in which the key was typed (selects +# a toplevel window). +# char - Character that selects a menu. The case +# is ignored. If an empty string, nothing +# happens. + +proc tkTraverseToMenu {w char} { + global tkPriv + if {$char == ""} { + return + } + while {[winfo class $w] == "Menu"} { + if {([$w cget -type] != "menubar") && ($tkPriv(postedMb) == "")} { + return + } + if {[$w cget -type] == "menubar"} { + break + } + set w [winfo parent $w] + } + set w [tkMenuFind [winfo toplevel $w] $char] + if {$w != ""} { + if {[winfo class $w] == "Menu"} { + tk_menuSetFocus $w + set tkPriv(window) $w + tkSaveGrabInfo $w + grab -global $w + tkTraverseWithinMenu $w $char + } else { + tkMbPost $w + tkMenuFirstEntry [$w cget -menu] + } + } +} + +# tkFirstMenu -- +# This procedure traverses to the first menubutton in the toplevel +# for a given window, and posts that menubutton's menu. +# +# Arguments: +# w - Name of a window. Selects which toplevel +# to search for menubuttons. + +proc tkFirstMenu w { + set w [tkMenuFind [winfo toplevel $w] ""] + if {$w != ""} { + if {[winfo class $w] == "Menu"} { + tk_menuSetFocus $w + set tkPriv(window) $w + tkSaveGrabInfo $w + grab -global $w + tkMenuFirstEntry $w + } else { + tkMbPost $w + tkMenuFirstEntry [$w cget -menu] + } + } +} + +# tkTraverseWithinMenu +# This procedure implements keyboard traversal within a menu. It +# searches for an entry in the menu that has "char" underlined. If +# such an entry is found, it is invoked and the menu is unposted. +# +# Arguments: +# w - The name of the menu widget. +# char - The character to look for; case is +# ignored. If the string is empty then +# nothing happens. + +proc tkTraverseWithinMenu {w char} { + if {$char == ""} { + return + } + set char [string tolower $char] + set last [$w index last] + if {$last == "none"} { + return + } + for {set i 0} {$i <= $last} {incr i} { + if [catch {set char2 [string index \ + [$w entrycget $i -label] \ + [$w entrycget $i -underline]]}] { + continue + } + if {[string compare $char [string tolower $char2]] == 0} { + if {[$w type $i] == "cascade"} { + $w activate $i + $w postcascade active + event generate $w <<MenuSelect>> + set m2 [$w entrycget $i -menu] + if {$m2 != ""} { + tkMenuFirstEntry $m2 + } + } else { + tkMenuUnpost $w + uplevel #0 [list $w invoke $i] + } + return + } + } +} + +# tkMenuFirstEntry -- +# Given a menu, this procedure finds the first entry that isn't +# disabled or a tear-off or separator, and activates that entry. +# However, if there is already an active entry in the menu (e.g., +# because of a previous call to tkPostOverPoint) then the active +# entry isn't changed. This procedure also sets the input focus +# to the menu. +# +# Arguments: +# menu - Name of the menu window (possibly empty). + +proc tkMenuFirstEntry menu { + if {$menu == ""} { + return + } + tk_menuSetFocus $menu + if {[$menu index active] != "none"} { + return + } + set last [$menu index last] + if {$last == "none"} { + return + } + for {set i 0} {$i <= $last} {incr i} { + if {([catch {set state [$menu entrycget $i -state]}] == 0) + && ($state != "disabled") && ([$menu type $i] != "tearoff")} { + $menu activate $i + tkGenerateMenuSelect $menu + if {[$menu type $i] == "cascade"} { + set cascade [$menu entrycget $i -menu] + if {[string compare $cascade ""] != 0} { + $menu postcascade $i + tkMenuFirstEntry $cascade + } + } + return + } + } +} + +# tkMenuFindName -- +# Given a menu and a text string, return the index of the menu entry +# that displays the string as its label. If there is no such entry, +# return an empty string. This procedure is tricky because some names +# like "active" have a special meaning in menu commands, so we can't +# always use the "index" widget command. +# +# Arguments: +# menu - Name of the menu widget. +# s - String to look for. + +proc tkMenuFindName {menu s} { + set i "" + if {![regexp {^active$|^last$|^none$|^[0-9]|^@} $s]} { + catch {set i [$menu index $s]} + return $i + } + set last [$menu index last] + if {$last == "none"} { + return + } + for {set i 0} {$i <= $last} {incr i} { + if ![catch {$menu entrycget $i -label} label] { + if {$label == $s} { + return $i + } + } + } + return "" +} + +# tkPostOverPoint -- +# This procedure posts a given menu such that a given entry in the +# menu is centered over a given point in the root window. It also +# activates the given entry. +# +# Arguments: +# menu - Menu to post. +# x, y - Root coordinates of point. +# entry - Index of entry within menu to center over (x,y). +# If omitted or specified as {}, then the menu's +# upper-left corner goes at (x,y). + +proc tkPostOverPoint {menu x y {entry {}}} { + global tcl_platform + + if {$entry != {}} { + if {$entry == [$menu index last]} { + incr y [expr -([$menu yposition $entry] \ + + [winfo reqheight $menu])/2] + } else { + incr y [expr -([$menu yposition $entry] \ + + [$menu yposition [expr $entry+1]])/2] + } + incr x [expr -[winfo reqwidth $menu]/2] + } + $menu post $x $y + if {($entry != {}) && ([$menu entrycget $entry -state] != "disabled")} { + $menu activate $entry + tkGenerateMenuSelect $menu + } +} + +# tkSaveGrabInfo -- +# Sets the variables tkPriv(oldGrab) and tkPriv(grabStatus) to record +# the state of any existing grab on the w's display. +# +# Arguments: +# w - Name of a window; used to select the display +# whose grab information is to be recorded. + +proc tkSaveGrabInfo w { + global tkPriv + set tkPriv(oldGrab) [grab current $w] + if {$tkPriv(oldGrab) != ""} { + set tkPriv(grabStatus) [grab status $tkPriv(oldGrab)] + } +} + +# tkRestoreOldGrab -- +# Restores the grab to what it was before TkSaveGrabInfo was called. +# + +proc tkRestoreOldGrab {} { + global tkPriv + + if {$tkPriv(oldGrab) != ""} { + + # Be careful restoring the old grab, since it's window may not + # be visible anymore. + + catch { + if {$tkPriv(grabStatus) == "global"} { + grab set -global $tkPriv(oldGrab) + } else { + grab set $tkPriv(oldGrab) + } + } + set tkPriv(oldGrab) "" + } +} + +proc tk_menuSetFocus {menu} { + global tkPriv + if {![info exists tkPriv(focus)] || [string length $tkPriv(focus)] == 0} { + set tkPriv(focus) [focus] + } + focus $menu +} + +proc tkGenerateMenuSelect {menu} { + global tkPriv + + if {([string compare $tkPriv(activeMenu) $menu] == 0) \ + && ([string compare $tkPriv(activeItem) [$menu index active]] \ + == 0)} { + return + } + + set tkPriv(activeMenu) $menu + set tkPriv(activeItem) [$menu index active] + event generate $menu <<MenuSelect>> +} + +# tk_popup -- +# This procedure pops up a menu and sets things up for traversing +# the menu and its submenus. +# +# Arguments: +# menu - Name of the menu to be popped up. +# x, y - Root coordinates at which to pop up the +# menu. +# entry - Index of a menu entry to center over (x,y). +# If omitted or specified as {}, then menu's +# upper-left corner goes at (x,y). + +proc tk_popup {menu x y {entry {}}} { + global tkPriv + global tcl_platform + if {($tkPriv(popup) != "") || ($tkPriv(postedMb) != "")} { + tkMenuUnpost {} + } + tkPostOverPoint $menu $x $y $entry + if {$tcl_platform(platform) == "unix"} { + tkSaveGrabInfo $menu + grab -global $menu + set tkPriv(popup) $menu + tk_menuSetFocus $menu + } +} diff --git a/library/msgbox.tcl b/library/msgbox.tcl new file mode 100644 index 0000000..07df82b --- /dev/null +++ b/library/msgbox.tcl @@ -0,0 +1,257 @@ +# msgbox.tcl -- +# +# Implements messageboxes for platforms that do not have native +# messagebox support. +# +# SCCS: @(#) msgbox.tcl 1.8 97/07/28 17:20:01 +# +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + + +# tkMessageBox -- +# +# Pops up a messagebox with an application-supplied message with +# an icon and a list of buttons. This procedure will be called +# by tk_messageBox if the platform does not have native +# messagebox support, or if the particular type of messagebox is +# not supported natively. +# +# This procedure is a private procedure shouldn't be called +# directly. Call tk_messageBox instead. +# +# See the user documentation for details on what tk_messageBox does. +# +proc tkMessageBox {args} { + global tkPriv tcl_platform + + set w tkPrivMsgBox + upvar #0 $w data + + # + # The default value of the title is space (" ") not the empty string + # because for some window managers, a + # wm title .foo "" + # causes the window title to be "foo" instead of the empty string. + # + set specs { + {-default "" "" ""} + {-icon "" "" "info"} + {-message "" "" ""} + {-parent "" "" .} + {-title "" "" " "} + {-type "" "" "ok"} + } + + tclParseConfigSpec $w $specs "" $args + + if {[lsearch {info warning error question} $data(-icon)] == -1} { + error "invalid icon \"$data(-icon)\", must be error, info, question or warning" + } + if {$tcl_platform(platform) == "macintosh"} { + if {$data(-icon) == "error"} { + set data(-icon) "stop" + } elseif {$data(-icon) == "warning"} { + set data(-icon) "caution" + } elseif {$data(-icon) == "info"} { + set data(-icon) "note" + } + } + + if ![winfo exists $data(-parent)] { + error "bad window path name \"$data(-parent)\"" + } + + case $data(-type) { + abortretryignore { + set buttons { + {abort -width 6 -text Abort -under 0} + {retry -width 6 -text Retry -under 0} + {ignore -width 6 -text Ignore -under 0} + } + } + ok { + set buttons { + {ok -width 6 -text OK -under 0} + } + if {$data(-default) == ""} { + set data(-default) "ok" + } + } + okcancel { + set buttons { + {ok -width 6 -text OK -under 0} + {cancel -width 6 -text Cancel -under 0} + } + } + retrycancel { + set buttons { + {retry -width 6 -text Retry -under 0} + {cancel -width 6 -text Cancel -under 0} + } + } + yesno { + set buttons { + {yes -width 6 -text Yes -under 0} + {no -width 6 -text No -under 0} + } + } + yesnocancel { + set buttons { + {yes -width 6 -text Yes -under 0} + {no -width 6 -text No -under 0} + {cancel -width 6 -text Cancel -under 0} + } + } + default { + error "invalid message box type \"$data(-type)\", must be abortretryignore, ok, okcancel, retrycancel, yesno or yesnocancel" + } + } + + if [string compare $data(-default) ""] { + set valid 0 + foreach btn $buttons { + if ![string compare [lindex $btn 0] $data(-default)] { + set valid 1 + break + } + } + if !$valid { + error "invalid default button \"$data(-default)\"" + } + } + + # 2. Set the dialog to be a child window of $parent + # + # + if [string compare $data(-parent) .] { + set w $data(-parent).__tk__messagebox + } else { + set w .__tk__messagebox + } + + # 3. Create the top-level window and divide it into top + # and bottom parts. + + catch {destroy $w} + toplevel $w -class Dialog + wm title $w $data(-title) + wm iconname $w Dialog + wm protocol $w WM_DELETE_WINDOW { } + wm transient $w $data(-parent) + if {$tcl_platform(platform) == "macintosh"} { + unsupported1 style $w dBoxProc + } + + frame $w.bot + pack $w.bot -side bottom -fill both + frame $w.top + pack $w.top -side top -fill both -expand 1 + if {$tcl_platform(platform) != "macintosh"} { + $w.bot configure -relief raised -bd 1 + $w.top configure -relief raised -bd 1 + } + + # 4. Fill the top part with bitmap and message (use the option + # database for -wraplength so that it can be overridden by + # the caller). + + option add *Dialog.msg.wrapLength 3i widgetDefault + label $w.msg -justify left -text $data(-message) + catch {$w.msg configure -font \ + -Adobe-Times-Medium-R-Normal--*-180-*-*-*-*-*-* + } + pack $w.msg -in $w.top -side right -expand 1 -fill both -padx 3m -pady 3m + if {$data(-icon) != ""} { + label $w.bitmap -bitmap $data(-icon) + pack $w.bitmap -in $w.top -side left -padx 3m -pady 3m + } + + # 5. Create a row of buttons at the bottom of the dialog. + + set i 0 + foreach but $buttons { + set name [lindex $but 0] + set opts [lrange $but 1 end] + if ![string compare $opts {}] { + # Capitalize the first letter of $name + set capName \ + [string toupper \ + [string index $name 0]][string range $name 1 end] + set opts [list -text $capName] + } + + eval button $w.$name $opts -command [list "set tkPriv(button) $name"] + + if ![string compare $name $data(-default)] { + $w.$name configure -default active + } + pack $w.$name -in $w.bot -side left -expand 1 \ + -padx 3m -pady 2m + + # create the binding for the key accelerator, based on the underline + # + set underIdx [$w.$name cget -under] + if {$underIdx >= 0} { + set key [string index [$w.$name cget -text] $underIdx] + bind $w <Alt-[string tolower $key]> "$w.$name invoke" + bind $w <Alt-[string toupper $key]> "$w.$name invoke" + } + incr i + } + + # 6. Create a binding for <Return> on the dialog if there is a + # default button. + + if [string compare $data(-default) ""] { + bind $w <Return> "tkButtonInvoke $w.$data(-default)" + } + + # 7. Withdraw the window, then update all the geometry information + # so we know how big it wants to be, then center the window in the + # display and de-iconify it. + + wm withdraw $w + update idletasks + set x [expr [winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \ + - [winfo vrootx [winfo parent $w]]] + set y [expr [winfo screenheight $w]/2 - [winfo reqheight $w]/2 \ + - [winfo vrooty [winfo parent $w]]] + wm geom $w +$x+$y + wm deiconify $w + + # 8. Set a grab and claim the focus too. + + set oldFocus [focus] + set oldGrab [grab current $w] + if {$oldGrab != ""} { + set grabStatus [grab status $oldGrab] + } + grab $w + if [string compare $data(-default) ""] { + focus $w.$data(-default) + } else { + focus $w + } + + # 9. Wait for the user to respond, then restore the focus and + # return the index of the selected button. Restore the focus + # before deleting the window, since otherwise the window manager + # may take the focus away so we can't redirect it. Finally, + # restore any grab that was in effect. + + tkwait variable tkPriv(button) + catch {focus $oldFocus} + destroy $w + if {$oldGrab != ""} { + if {$grabStatus == "global"} { + grab -global $oldGrab + } else { + grab $oldGrab + } + } + return $tkPriv(button) +} diff --git a/library/obsolete.tcl b/library/obsolete.tcl new file mode 100644 index 0000000..7fc1fb3 --- /dev/null +++ b/library/obsolete.tcl @@ -0,0 +1,21 @@ +# obsolete.tcl -- +# +# This file contains obsolete procedures that people really shouldn't +# be using anymore, but which are kept around for backward compatibility. +# +# SCCS: @(#) obsolete.tcl 1.3 96/02/16 10:48:19 +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# The procedures below are here strictly for backward compatibility with +# Tk version 3.6 and earlier. The procedures are no longer needed, so +# they are no-ops. You should not use these procedures anymore, since +# they may be removed in some future release. + +proc tk_menuBar args {} +proc tk_bindForTraversal args {} diff --git a/library/optMenu.tcl b/library/optMenu.tcl new file mode 100644 index 0000000..32ca096c --- /dev/null +++ b/library/optMenu.tcl @@ -0,0 +1,45 @@ +# optMenu.tcl -- +# +# This file defines the procedure tk_optionMenu, which creates +# an option button and its associated menu. +# +# SCCS: @(#) optMenu.tcl 1.11 97/08/22 14:21:13 +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# tk_optionMenu -- +# This procedure creates an option button named $w and an associated +# menu. Together they provide the functionality of Motif option menus: +# they can be used to select one of many values, and the current value +# appears in the global variable varName, as well as in the text of +# the option menubutton. The name of the menu is returned as the +# procedure's result, so that the caller can use it to change configuration +# options on the menu or otherwise manipulate it. +# +# Arguments: +# w - The name to use for the menubutton. +# varName - Global variable to hold the currently selected value. +# firstValue - First of legal values for option (must be >= 1). +# args - Any number of additional values. + +proc tk_optionMenu {w varName firstValue args} { + upvar #0 $varName var + + if ![info exists var] { + set var $firstValue + } + menubutton $w -textvariable $varName -indicatoron 1 -menu $w.menu \ + -relief raised -bd 2 -highlightthickness 2 -anchor c \ + -direction flush + menu $w.menu -tearoff 0 + $w.menu add radiobutton -label $firstValue -variable $varName + foreach i $args { + $w.menu add radiobutton -label $i -variable $varName + } + return $w.menu +} diff --git a/library/palette.tcl b/library/palette.tcl new file mode 100644 index 0000000..5d5318e --- /dev/null +++ b/library/palette.tcl @@ -0,0 +1,222 @@ +# palette.tcl -- +# +# This file contains procedures that change the color palette used +# by Tk. +# +# SCCS: @(#) palette.tcl 1.11 97/06/23 20:35:44 +# +# Copyright (c) 1995-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# tk_setPalette -- +# Changes the default color scheme for a Tk application by setting +# default colors in the option database and by modifying all of the +# color options for existing widgets that have the default value. +# +# Arguments: +# The arguments consist of either a single color name, which +# will be used as the new background color (all other colors will +# be computed from this) or an even number of values consisting of +# option names and values. The name for an option is the one used +# for the option database, such as activeForeground, not -activeforeground. + +proc tk_setPalette {args} { + global tkPalette + + # Create an array that has the complete new palette. If some colors + # aren't specified, compute them from other colors that are specified. + + if {[llength $args] == 1} { + set new(background) [lindex $args 0] + } else { + array set new $args + } + if ![info exists new(background)] { + error "must specify a background color" + } + if ![info exists new(foreground)] { + set new(foreground) black + } + set bg [winfo rgb . $new(background)] + set fg [winfo rgb . $new(foreground)] + set darkerBg [format #%02x%02x%02x [expr (9*[lindex $bg 0])/2560] \ + [expr (9*[lindex $bg 1])/2560] [expr (9*[lindex $bg 2])/2560]] + foreach i {activeForeground insertBackground selectForeground \ + highlightColor} { + if ![info exists new($i)] { + set new($i) $new(foreground) + } + } + if ![info exists new(disabledForeground)] { + set new(disabledForeground) [format #%02x%02x%02x \ + [expr (3*[lindex $bg 0] + [lindex $fg 0])/1024] \ + [expr (3*[lindex $bg 1] + [lindex $fg 1])/1024] \ + [expr (3*[lindex $bg 2] + [lindex $fg 2])/1024]] + } + if ![info exists new(highlightBackground)] { + set new(highlightBackground) $new(background) + } + if ![info exists new(activeBackground)] { + # Pick a default active background that islighter than the + # normal background. To do this, round each color component + # up by 15% or 1/3 of the way to full white, whichever is + # greater. + + foreach i {0 1 2} { + set light($i) [expr [lindex $bg $i]/256] + set inc1 [expr ($light($i)*15)/100] + set inc2 [expr (255-$light($i))/3] + if {$inc1 > $inc2} { + incr light($i) $inc1 + } else { + incr light($i) $inc2 + } + if {$light($i) > 255} { + set light($i) 255 + } + } + set new(activeBackground) [format #%02x%02x%02x $light(0) \ + $light(1) $light(2)] + } + if ![info exists new(selectBackground)] { + set new(selectBackground) $darkerBg + } + if ![info exists new(troughColor)] { + set new(troughColor) $darkerBg + } + if ![info exists new(selectColor)] { + set new(selectColor) #b03060 + } + + # let's make one of each of the widgets so we know what the + # defaults are currently for this platform. + toplevel .___tk_set_palette + wm withdraw .___tk_set_palette + foreach q {button canvas checkbutton entry frame label listbox menubutton menu message \ + radiobutton scale scrollbar text} { + $q .___tk_set_palette.$q + } + + # Walk the widget hierarchy, recoloring all existing windows. + # The option database must be set according to what we do here, + # but it breaks things if we set things in the database while + # we are changing colors...so, tkRecolorTree now returns the + # option database changes that need to be made, and they + # need to be evalled here to take effect. + # We have to walk the whole widget tree instead of just + # relying on the widgets we've created above to do the work + # because different extensions may provide other kinds + # of widgets that we don't currently know about, so we'll + # walk the whole hierarchy just in case. + + eval [tkRecolorTree . new] + + catch {destroy .___tk_set_palette} + + # Change the option database so that future windows will get the + # same colors. + + foreach option [array names new] { + option add *$option $new($option) widgetDefault + } + + # Save the options in the global variable tkPalette, for use the + # next time we change the options. + + array set tkPalette [array get new] +} + +# tkRecolorTree -- +# This procedure changes the colors in a window and all of its +# descendants, according to information provided by the colors +# argument. This looks at the defaults provided by the option +# database, if it exists, and if not, then it looks at the default +# value of the widget itself. +# +# Arguments: +# w - The name of a window. This window and all its +# descendants are recolored. +# colors - The name of an array variable in the caller, +# which contains color information. Each element +# is named after a widget configuration option, and +# each value is the value for that option. + +proc tkRecolorTree {w colors} { + global tkPalette + upvar $colors c + set result {} + foreach dbOption [array names c] { + set option -[string tolower $dbOption] + if {![catch {$w config $option} value]} { + # if the option database has a preference for this + # dbOption, then use it, otherwise use the defaults + # for the widget. + set defaultcolor [option get $w $dbOption widgetDefault] + if {[string match {} $defaultcolor]} { + set defaultcolor [winfo rgb . [lindex $value 3]] + } else { + set defaultcolor [winfo rgb . $defaultcolor] + } + set chosencolor [winfo rgb . [lindex $value 4]] + if {[string match $defaultcolor $chosencolor]} { + # Change the option database so that future windows will get + # the same colors. + append result ";\noption add [list \ + *[winfo class $w].$dbOption $c($dbOption) 60]" + $w configure $option $c($dbOption) + } + } + } + foreach child [winfo children $w] { + append result ";\n[tkRecolorTree $child c]" + } + return $result +} + +# tkDarken -- +# Given a color name, computes a new color value that darkens (or +# brightens) the given color by a given percent. +# +# Arguments: +# color - Name of starting color. +# perecent - Integer telling how much to brighten or darken as a +# percent: 50 means darken by 50%, 110 means brighten +# by 10%. + +proc tkDarken {color percent} { + set l [winfo rgb . $color] + set red [expr [lindex $l 0]/256] + set green [expr [lindex $l 1]/256] + set blue [expr [lindex $l 2]/256] + set red [expr ($red*$percent)/100] + if {$red > 255} { + set red 255 + } + set green [expr ($green*$percent)/100] + if {$green > 255} { + set green 255 + } + set blue [expr ($blue*$percent)/100] + if {$blue > 255} { + set blue 255 + } + format #%02x%02x%02x $red $green $blue +} + +# tk_bisque -- +# Reset the Tk color palette to the old "bisque" colors. +# +# Arguments: +# None. + +proc tk_bisque {} { + tk_setPalette activeBackground #e6ceb1 activeForeground black \ + background #ffe4c4 disabledForeground #b0b0b0 foreground black \ + highlightBackground #ffe4c4 highlightColor black \ + insertBackground black selectColor #b03060 \ + selectBackground #e6ceb1 selectForeground black \ + troughColor #cdb79e +} diff --git a/library/prolog.ps b/library/prolog.ps new file mode 100644 index 0000000..378d503 --- /dev/null +++ b/library/prolog.ps @@ -0,0 +1,284 @@ +%%BeginProlog +50 dict begin + +% This is a standard prolog for Postscript generated by Tk's canvas +% widget. +% SCCS: @(#) prolog.ps 1.7 96/07/08 17:52:14 + +% The definitions below just define all of the variables used in +% any of the procedures here. This is needed for obscure reasons +% explained on p. 716 of the Postscript manual (Section H.2.7, +% "Initializing Variables," in the section on Encapsulated Postscript). + +/baseline 0 def +/stipimage 0 def +/height 0 def +/justify 0 def +/lineLength 0 def +/spacing 0 def +/stipple 0 def +/strings 0 def +/xoffset 0 def +/yoffset 0 def +/tmpstip null def + +% Define the array ISOLatin1Encoding (which specifies how characters are +% encoded for ISO-8859-1 fonts), if it isn't already present (Postscript +% level 2 is supposed to define it, but level 1 doesn't). + +systemdict /ISOLatin1Encoding known not { + /ISOLatin1Encoding [ + /space /space /space /space /space /space /space /space + /space /space /space /space /space /space /space /space + /space /space /space /space /space /space /space /space + /space /space /space /space /space /space /space /space + /space /exclam /quotedbl /numbersign /dollar /percent /ampersand + /quoteright + /parenleft /parenright /asterisk /plus /comma /minus /period /slash + /zero /one /two /three /four /five /six /seven + /eight /nine /colon /semicolon /less /equal /greater /question + /at /A /B /C /D /E /F /G + /H /I /J /K /L /M /N /O + /P /Q /R /S /T /U /V /W + /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore + /quoteleft /a /b /c /d /e /f /g + /h /i /j /k /l /m /n /o + /p /q /r /s /t /u /v /w + /x /y /z /braceleft /bar /braceright /asciitilde /space + /space /space /space /space /space /space /space /space + /space /space /space /space /space /space /space /space + /dotlessi /grave /acute /circumflex /tilde /macron /breve /dotaccent + /dieresis /space /ring /cedilla /space /hungarumlaut /ogonek /caron + /space /exclamdown /cent /sterling /currency /yen /brokenbar /section + /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen + /registered /macron + /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph + /periodcentered + /cedillar /onesuperior /ordmasculine /guillemotright /onequarter + /onehalf /threequarters /questiondown + /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla + /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex + /Idieresis + /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply + /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn + /germandbls + /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla + /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex + /idieresis + /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide + /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn + /ydieresis + ] def +} if + +% font ISOEncode font +% This procedure changes the encoding of a font from the default +% Postscript encoding to ISOLatin1. It's typically invoked just +% before invoking "setfont". The body of this procedure comes from +% Section 5.6.1 of the Postscript book. + +/ISOEncode { + dup length dict begin + {1 index /FID ne {def} {pop pop} ifelse} forall + /Encoding ISOLatin1Encoding def + currentdict + end + + % I'm not sure why it's necessary to use "definefont" on this new + % font, but it seems to be important; just use the name "Temporary" + % for the font. + + /Temporary exch definefont +} bind def + +% StrokeClip +% +% This procedure converts the current path into a clip area under +% the assumption of stroking. It's a bit tricky because some Postscript +% interpreters get errors during strokepath for dashed lines. If +% this happens then turn off dashes and try again. + +/StrokeClip { + {strokepath} stopped { + (This Postscript printer gets limitcheck overflows when) = + (stippling dashed lines; lines will be printed solid instead.) = + [] 0 setdash strokepath} if + clip +} bind def + +% desiredSize EvenPixels closestSize +% +% The procedure below is used for stippling. Given the optimal size +% of a dot in a stipple pattern in the current user coordinate system, +% compute the closest size that is an exact multiple of the device's +% pixel size. This allows stipple patterns to be displayed without +% aliasing effects. + +/EvenPixels { + % Compute exact number of device pixels per stipple dot. + dup 0 matrix currentmatrix dtransform + dup mul exch dup mul add sqrt + + % Round to an integer, make sure the number is at least 1, and compute + % user coord distance corresponding to this. + dup round dup 1 lt {pop 1} if + exch div mul +} bind def + +% width height string StippleFill -- +% +% Given a path already set up and a clipping region generated from +% it, this procedure will fill the clipping region with a stipple +% pattern. "String" contains a proper image description of the +% stipple pattern and "width" and "height" give its dimensions. Each +% stipple dot is assumed to be about one unit across in the current +% user coordinate system. This procedure trashes the graphics state. + +/StippleFill { + % The following code is needed to work around a NeWSprint bug. + + /tmpstip 1 index def + + % Change the scaling so that one user unit in user coordinates + % corresponds to the size of one stipple dot. + 1 EvenPixels dup scale + + % Compute the bounding box occupied by the path (which is now + % the clipping region), and round the lower coordinates down + % to the nearest starting point for the stipple pattern. Be + % careful about negative numbers, since the rounding works + % differently on them. + + pathbbox + 4 2 roll + 5 index div dup 0 lt {1 sub} if cvi 5 index mul 4 1 roll + 6 index div dup 0 lt {1 sub} if cvi 6 index mul 3 2 roll + + % Stack now: width height string y1 y2 x1 x2 + % Below is a doubly-nested for loop to iterate across this area + % in units of the stipple pattern size, going up columns then + % across rows, blasting out a stipple-pattern-sized rectangle at + % each position + + 6 index exch { + 2 index 5 index 3 index { + % Stack now: width height string y1 y2 x y + + gsave + 1 index exch translate + 5 index 5 index true matrix tmpstip imagemask + grestore + } for + pop + } for + pop pop pop pop pop +} bind def + +% -- AdjustColor -- +% Given a color value already set for output by the caller, adjusts +% that value to a grayscale or mono value if requested by the CL +% variable. + +/AdjustColor { + CL 2 lt { + currentgray + CL 0 eq { + .5 lt {0} {1} ifelse + } if + setgray + } if +} bind def + +% x y strings spacing xoffset yoffset justify stipple DrawText -- +% This procedure does all of the real work of drawing text. The +% color and font must already have been set by the caller, and the +% following arguments must be on the stack: +% +% x, y - Coordinates at which to draw text. +% strings - An array of strings, one for each line of the text item, +% in order from top to bottom. +% spacing - Spacing between lines. +% xoffset - Horizontal offset for text bbox relative to x and y: 0 for +% nw/w/sw anchor, -0.5 for n/center/s, and -1.0 for ne/e/se. +% yoffset - Vertical offset for text bbox relative to x and y: 0 for +% nw/n/ne anchor, +0.5 for w/center/e, and +1.0 for sw/s/se. +% justify - 0 for left justification, 0.5 for center, 1 for right justify. +% stipple - Boolean value indicating whether or not text is to be +% drawn in stippled fashion. If text is stippled, +% procedure StippleText must have been defined to call +% StippleFill in the right way. +% +% Also, when this procedure is invoked, the color and font must already +% have been set for the text. + +/DrawText { + /stipple exch def + /justify exch def + /yoffset exch def + /xoffset exch def + /spacing exch def + /strings exch def + + % First scan through all of the text to find the widest line. + + /lineLength 0 def + strings { + stringwidth pop + dup lineLength gt {/lineLength exch def} {pop} ifelse + newpath + } forall + + % Compute the baseline offset and the actual font height. + + 0 0 moveto (TXygqPZ) false charpath + pathbbox dup /baseline exch def + exch pop exch sub /height exch def pop + newpath + + % Translate coordinates first so that the origin is at the upper-left + % corner of the text's bounding box. Remember that x and y for + % positioning are still on the stack. + + translate + lineLength xoffset mul + strings length 1 sub spacing mul height add yoffset mul translate + + % Now use the baseline and justification information to translate so + % that the origin is at the baseline and positioning point for the + % first line of text. + + justify lineLength mul baseline neg translate + + % Iterate over each of the lines to output it. For each line, + % compute its width again so it can be properly justified, then + % display it. + + strings { + dup stringwidth pop + justify neg mul 0 moveto + stipple { + + % The text is stippled, so turn it into a path and print + % by calling StippledText, which in turn calls StippleFill. + % Unfortunately, many Postscript interpreters will get + % overflow errors if we try to do the whole string at + % once, so do it a character at a time. + + gsave + /char (X) def + { + char 0 3 -1 roll put + currentpoint + gsave + char true charpath clip StippleText + grestore + char stringwidth translate + moveto + } forall + grestore + } {show} ifelse + 0 spacing neg translate + } forall +} bind def + +%%EndProlog diff --git a/library/safetk.tcl b/library/safetk.tcl new file mode 100644 index 0000000..1cabcd5 --- /dev/null +++ b/library/safetk.tcl @@ -0,0 +1,148 @@ +# safetk.tcl -- +# +# Support procs to use Tk in safe interpreters. +# +# SCCS: @(#) safetk.tcl 1.8 97/10/29 14:59:16 +# +# Copyright (c) 1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. + +# see safetk.n for documentation + +# +# +# Note: It is UNSAFE to let any untrusted code being executed +# between the creation of the interp and the actual loading +# of Tk in that interp. +# You should "loadTk $slave" right after safe::tkInterpCreate +# Otherwise, if you are using an application with Tk +# and don't want safe slaves to have access to Tk, potentially +# in a malevolent way, you should use +# ::safe::interpCreate -nostatics -accesspath {directories...} +# where the directory list does NOT contain any Tk dynamically +# loadable library +# + +# We use opt (optional arguments parsing) +package require opt 0.1; + +namespace eval ::safe { + + # counter for safe toplevels + variable tkSafeId 0; + + # + # tkInterpInit : prepare the slave interpreter for tk loading + # + # returns the slave name (tkInterpInit does) + # + proc ::safe::tkInterpInit {slave} { + global env tk_library + if {[info exists env(DISPLAY)]} { + $slave eval [list set env(DISPLAY) $env(DISPLAY)]; + } + # there seems to be an obscure case where the tk_library + # variable value is changed to point to a sym link destination + # dir instead of the sym link itself, and thus where the $tk_library + # would then not be anymore one of the auto_path dir, so we use + # the addToAccessPath which adds if it's not already in instead + # of the more conventional findInAccessPath + ::interp eval $slave [list set tk_library [::safe::interpAddToAccessPath $slave $tk_library]] + return $slave; + } + + +# tkInterpLoadTk : +# Do additional configuration as needed (calling tkInterpInit) +# and actually load Tk into the slave. +# +# Either contained in the specified windowId (-use) or +# creating a decorated toplevel for it. + +# empty definition for auto_mkIndex +proc ::safe::loadTk {} {} + + ::tcl::OptProc loadTk { + {slave -interp "name of the slave interpreter"} + {-use -windowId {} "window Id to use (new toplevel otherwise)"} + } { + if {![::tcl::OptProcArgGiven "-use"]} { + # create a decorated toplevel + ::tcl::Lassign [tkTopLevel $slave] w use; + # set our delete hook (slave arg is added by interpDelete) + Set [DeleteHookName $slave] [list tkDelete {} $w]; + } + tkInterpInit $slave; + ::interp eval $slave [list set argv [list "-use" $use]]; + ::interp eval $slave [list set argc 2]; + load {} Tk $slave + # Remove env(DISPLAY) if it's in there (if it has been set by + # tkInterpInit) + ::interp eval $slave {catch {unset env(DISPLAY)}} + return $slave + } + + proc ::safe::tkDelete {W window slave} { + # we are going to be called for each widget... skip untill it's + # top level + Log $slave "Called tkDelete $W $window" NOTICE; + if {[::interp exists $slave]} { + if {[catch {::safe::interpDelete $slave} msg]} { + Log $slave "Deletion error : $msg"; + } + } + if {[winfo exists $window]} { + Log $slave "Destroy toplevel $window" NOTICE; + destroy $window; + } + } + +proc ::safe::tkTopLevel {slave} { + variable tkSafeId; + incr tkSafeId; + set w ".safe$tkSafeId"; + if {[catch {toplevel $w -class SafeTk} msg]} { + return -code error "Unable to create toplevel for\ + safe slave \"$slave\" ($msg)"; + } + Log $slave "New toplevel $w" NOTICE + + set msg "Untrusted Tcl applet ($slave)" + wm title $w $msg; + + # Control frame + set wc $w.fc + frame $wc -bg red -borderwidth 3 -relief ridge ; + + # We will destroy the interp when the window is destroyed + bindtags $wc [concat Safe$wc [bindtags $wc]] + bind Safe$wc <Destroy> [list ::safe::tkDelete %W $w $slave]; + + label $wc.l -text $msg \ + -padx 2 -pady 0 -anchor w; + + # We want the button to be the last visible item + # (so be packed first) and at the right and not resizing horizontally + + # frame the button so it does not expand horizontally + # but still have the default background instead of red one from the parent + frame $wc.fb -bd 0 ; + button $wc.fb.b -text "Delete" \ + -bd 1 -padx 2 -pady 0 -highlightthickness 0 \ + -command [list ::safe::tkDelete $w $w $slave] + pack $wc.fb.b -side right -fill both ; + pack $wc.fb -side right -fill both -expand 1; + pack $wc.l -side left -fill both -expand 1; + pack $wc -side bottom -fill x ; + + # Container frame + frame $w.c -container 1; + pack $w.c -fill both -expand 1; + + # return both the toplevel window name and the id to use for embedding + list $w [winfo id $w.c] ; +} + +} diff --git a/library/scale.tcl b/library/scale.tcl new file mode 100644 index 0000000..8e96176 --- /dev/null +++ b/library/scale.tcl @@ -0,0 +1,265 @@ +# scale.tcl -- +# +# This file defines the default bindings for Tk scale widgets and provides +# procedures that help in implementing the bindings. +# +# SCCS: @(#) scale.tcl 1.12 96/04/16 11:42:25 +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +#------------------------------------------------------------------------- +# The code below creates the default class bindings for entries. +#------------------------------------------------------------------------- + +# Standard Motif bindings: + +bind Scale <Enter> { + if $tk_strictMotif { + set tkPriv(activeBg) [%W cget -activebackground] + %W config -activebackground [%W cget -background] + } + tkScaleActivate %W %x %y +} +bind Scale <Motion> { + tkScaleActivate %W %x %y +} +bind Scale <Leave> { + if $tk_strictMotif { + %W config -activebackground $tkPriv(activeBg) + } + if {[%W cget -state] == "active"} { + %W configure -state normal + } +} +bind Scale <1> { + tkScaleButtonDown %W %x %y +} +bind Scale <B1-Motion> { + tkScaleDrag %W %x %y +} +bind Scale <B1-Leave> { } +bind Scale <B1-Enter> { } +bind Scale <ButtonRelease-1> { + tkCancelRepeat + tkScaleEndDrag %W + tkScaleActivate %W %x %y +} +bind Scale <2> { + tkScaleButton2Down %W %x %y +} +bind Scale <B2-Motion> { + tkScaleDrag %W %x %y +} +bind Scale <B2-Leave> { } +bind Scale <B2-Enter> { } +bind Scale <ButtonRelease-2> { + tkCancelRepeat + tkScaleEndDrag %W + tkScaleActivate %W %x %y +} +bind Scale <Control-1> { + tkScaleControlPress %W %x %y +} +bind Scale <Up> { + tkScaleIncrement %W up little noRepeat +} +bind Scale <Down> { + tkScaleIncrement %W down little noRepeat +} +bind Scale <Left> { + tkScaleIncrement %W up little noRepeat +} +bind Scale <Right> { + tkScaleIncrement %W down little noRepeat +} +bind Scale <Control-Up> { + tkScaleIncrement %W up big noRepeat +} +bind Scale <Control-Down> { + tkScaleIncrement %W down big noRepeat +} +bind Scale <Control-Left> { + tkScaleIncrement %W up big noRepeat +} +bind Scale <Control-Right> { + tkScaleIncrement %W down big noRepeat +} +bind Scale <Home> { + %W set [%W cget -from] +} +bind Scale <End> { + %W set [%W cget -to] +} + +# tkScaleActivate -- +# This procedure is invoked to check a given x-y position in the +# scale and activate the slider if the x-y position falls within +# the slider. +# +# Arguments: +# w - The scale widget. +# x, y - Mouse coordinates. + +proc tkScaleActivate {w x y} { + global tkPriv + if {[$w cget -state] == "disabled"} { + return; + } + if {[$w identify $x $y] == "slider"} { + $w configure -state active + } else { + $w configure -state normal + } +} + +# tkScaleButtonDown -- +# This procedure is invoked when a button is pressed in a scale. It +# takes different actions depending on where the button was pressed. +# +# Arguments: +# w - The scale widget. +# x, y - Mouse coordinates of button press. + +proc tkScaleButtonDown {w x y} { + global tkPriv + set tkPriv(dragging) 0 + set el [$w identify $x $y] + if {$el == "trough1"} { + tkScaleIncrement $w up little initial + } elseif {$el == "trough2"} { + tkScaleIncrement $w down little initial + } elseif {$el == "slider"} { + set tkPriv(dragging) 1 + set tkPriv(initValue) [$w get] + set coords [$w coords] + set tkPriv(deltaX) [expr $x - [lindex $coords 0]] + set tkPriv(deltaY) [expr $y - [lindex $coords 1]] + $w configure -sliderrelief sunken + } +} + +# tkScaleDrag -- +# This procedure is called when the mouse is dragged with +# mouse button 1 down. If the drag started inside the slider +# (i.e. the scale is active) then the scale's value is adjusted +# to reflect the mouse's position. +# +# Arguments: +# w - The scale widget. +# x, y - Mouse coordinates. + +proc tkScaleDrag {w x y} { + global tkPriv + if !$tkPriv(dragging) { + return + } + $w set [$w get [expr $x - $tkPriv(deltaX)] \ + [expr $y - $tkPriv(deltaY)]] +} + +# tkScaleEndDrag -- +# This procedure is called to end an interactive drag of the +# slider. It just marks the drag as over. +# +# Arguments: +# w - The scale widget. + +proc tkScaleEndDrag {w} { + global tkPriv + set tkPriv(dragging) 0 + $w configure -sliderrelief raised +} + +# tkScaleIncrement -- +# This procedure is invoked to increment the value of a scale and +# to set up auto-repeating of the action if that is desired. The +# way the value is incremented depends on the "dir" and "big" +# arguments. +# +# Arguments: +# w - The scale widget. +# dir - "up" means move value towards -from, "down" means +# move towards -to. +# big - Size of increments: "big" or "little". +# repeat - Whether and how to auto-repeat the action: "noRepeat" +# means don't auto-repeat, "initial" means this is the +# first action in an auto-repeat sequence, and "again" +# means this is the second repetition or later. + +proc tkScaleIncrement {w dir big repeat} { + global tkPriv + if {![winfo exists $w]} return + if {$big == "big"} { + set inc [$w cget -bigincrement] + if {$inc == 0} { + set inc [expr abs([$w cget -to] - [$w cget -from])/10.0] + } + if {$inc < [$w cget -resolution]} { + set inc [$w cget -resolution] + } + } else { + set inc [$w cget -resolution] + } + if {([$w cget -from] > [$w cget -to]) ^ ($dir == "up")} { + set inc [expr -$inc] + } + $w set [expr [$w get] + $inc] + + if {$repeat == "again"} { + set tkPriv(afterId) [after [$w cget -repeatinterval] \ + tkScaleIncrement $w $dir $big again] + } elseif {$repeat == "initial"} { + set delay [$w cget -repeatdelay] + if {$delay > 0} { + set tkPriv(afterId) [after $delay \ + tkScaleIncrement $w $dir $big again] + } + } +} + +# tkScaleControlPress -- +# This procedure handles button presses that are made with the Control +# key down. Depending on the mouse position, it adjusts the scale +# value to one end of the range or the other. +# +# Arguments: +# w - The scale widget. +# x, y - Mouse coordinates where the button was pressed. + +proc tkScaleControlPress {w x y} { + set el [$w identify $x $y] + if {$el == "trough1"} { + $w set [$w cget -from] + } elseif {$el == "trough2"} { + $w set [$w cget -to] + } +} + +# tkScaleButton2Down +# This procedure is invoked when button 2 is pressed over a scale. +# It sets the value to correspond to the mouse position and starts +# a slider drag. +# +# Arguments: +# w - The scrollbar widget. +# x, y - Mouse coordinates within the widget. + +proc tkScaleButton2Down {w x y} { + global tkPriv + + if {[$w cget -state] == "disabled"} { + return; + } + $w configure -state active + $w set [$w get $x $y] + set tkPriv(dragging) 1 + set tkPriv(initValue) [$w get] + set coords "$x $y" + set tkPriv(deltaX) 0 + set tkPriv(deltaY) 0 +} diff --git a/library/scrlbar.tcl b/library/scrlbar.tcl new file mode 100644 index 0000000..e2b04b7 --- /dev/null +++ b/library/scrlbar.tcl @@ -0,0 +1,417 @@ +# scrlbar.tcl -- +# +# This file defines the default bindings for Tk scrollbar widgets. +# It also provides procedures that help in implementing the bindings. +# +# SCCS: @(#) scrlbar.tcl 1.26 96/11/30 17:19:16 +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +#------------------------------------------------------------------------- +# The code below creates the default class bindings for scrollbars. +#------------------------------------------------------------------------- + +# Standard Motif bindings: +if {($tcl_platform(platform) != "windows") && + ($tcl_platform(platform) != "macintosh")} { +bind Scrollbar <Enter> { + if $tk_strictMotif { + set tkPriv(activeBg) [%W cget -activebackground] + %W config -activebackground [%W cget -background] + } + %W activate [%W identify %x %y] +} +bind Scrollbar <Motion> { + %W activate [%W identify %x %y] +} + +# The "info exists" command in the following binding handles the +# situation where a Leave event occurs for a scrollbar without the Enter +# event. This seems to happen on some systems (such as Solaris 2.4) for +# unknown reasons. + +bind Scrollbar <Leave> { + if {$tk_strictMotif && [info exists tkPriv(activeBg)]} { + %W config -activebackground $tkPriv(activeBg) + } + %W activate {} +} +bind Scrollbar <1> { + tkScrollButtonDown %W %x %y +} +bind Scrollbar <B1-Motion> { + tkScrollDrag %W %x %y +} +bind Scrollbar <B1-B2-Motion> { + tkScrollDrag %W %x %y +} +bind Scrollbar <ButtonRelease-1> { + tkScrollButtonUp %W %x %y +} +bind Scrollbar <B1-Leave> { + # Prevents <Leave> binding from being invoked. +} +bind Scrollbar <B1-Enter> { + # Prevents <Enter> binding from being invoked. +} +bind Scrollbar <2> { + tkScrollButton2Down %W %x %y +} +bind Scrollbar <B1-2> { + # Do nothing, since button 1 is already down. +} +bind Scrollbar <B2-1> { + # Do nothing, since button 2 is already down. +} +bind Scrollbar <B2-Motion> { + tkScrollDrag %W %x %y +} +bind Scrollbar <ButtonRelease-2> { + tkScrollButtonUp %W %x %y +} +bind Scrollbar <B1-ButtonRelease-2> { + # Do nothing: B1 release will handle it. +} +bind Scrollbar <B2-ButtonRelease-1> { + # Do nothing: B2 release will handle it. +} +bind Scrollbar <B2-Leave> { + # Prevents <Leave> binding from being invoked. +} +bind Scrollbar <B2-Enter> { + # Prevents <Enter> binding from being invoked. +} +bind Scrollbar <Control-1> { + tkScrollTopBottom %W %x %y +} +bind Scrollbar <Control-2> { + tkScrollTopBottom %W %x %y +} + +bind Scrollbar <Up> { + tkScrollByUnits %W v -1 +} +bind Scrollbar <Down> { + tkScrollByUnits %W v 1 +} +bind Scrollbar <Control-Up> { + tkScrollByPages %W v -1 +} +bind Scrollbar <Control-Down> { + tkScrollByPages %W v 1 +} +bind Scrollbar <Left> { + tkScrollByUnits %W h -1 +} +bind Scrollbar <Right> { + tkScrollByUnits %W h 1 +} +bind Scrollbar <Control-Left> { + tkScrollByPages %W h -1 +} +bind Scrollbar <Control-Right> { + tkScrollByPages %W h 1 +} +bind Scrollbar <Prior> { + tkScrollByPages %W hv -1 +} +bind Scrollbar <Next> { + tkScrollByPages %W hv 1 +} +bind Scrollbar <Home> { + tkScrollToPos %W 0 +} +bind Scrollbar <End> { + tkScrollToPos %W 1 +} +} +# tkScrollButtonDown -- +# This procedure is invoked when a button is pressed in a scrollbar. +# It changes the way the scrollbar is displayed and takes actions +# depending on where the mouse is. +# +# Arguments: +# w - The scrollbar widget. +# x, y - Mouse coordinates. + +proc tkScrollButtonDown {w x y} { + global tkPriv + set tkPriv(relief) [$w cget -activerelief] + $w configure -activerelief sunken + set element [$w identify $x $y] + if {$element == "slider"} { + tkScrollStartDrag $w $x $y + } else { + tkScrollSelect $w $element initial + } +} + +# tkScrollButtonUp -- +# This procedure is invoked when a button is released in a scrollbar. +# It cancels scans and auto-repeats that were in progress, and restores +# the way the active element is displayed. +# +# Arguments: +# w - The scrollbar widget. +# x, y - Mouse coordinates. + +proc tkScrollButtonUp {w x y} { + global tkPriv + tkCancelRepeat + $w configure -activerelief $tkPriv(relief) + tkScrollEndDrag $w $x $y + $w activate [$w identify $x $y] +} + +# tkScrollSelect -- +# This procedure is invoked when a button is pressed over the scrollbar. +# It invokes one of several scrolling actions depending on where in +# the scrollbar the button was pressed. +# +# Arguments: +# w - The scrollbar widget. +# element - The element of the scrollbar that was selected, such +# as "arrow1" or "trough2". Shouldn't be "slider". +# repeat - Whether and how to auto-repeat the action: "noRepeat" +# means don't auto-repeat, "initial" means this is the +# first action in an auto-repeat sequence, and "again" +# means this is the second repetition or later. + +proc tkScrollSelect {w element repeat} { + global tkPriv + if {![winfo exists $w]} return + if {$element == "arrow1"} { + tkScrollByUnits $w hv -1 + } elseif {$element == "trough1"} { + tkScrollByPages $w hv -1 + } elseif {$element == "trough2"} { + tkScrollByPages $w hv 1 + } elseif {$element == "arrow2"} { + tkScrollByUnits $w hv 1 + } else { + return + } + if {$repeat == "again"} { + set tkPriv(afterId) [after [$w cget -repeatinterval] \ + tkScrollSelect $w $element again] + } elseif {$repeat == "initial"} { + set delay [$w cget -repeatdelay] + if {$delay > 0} { + set tkPriv(afterId) [after $delay tkScrollSelect $w $element again] + } + } +} + +# tkScrollStartDrag -- +# This procedure is called to initiate a drag of the slider. It just +# remembers the starting position of the mouse and slider. +# +# Arguments: +# w - The scrollbar widget. +# x, y - The mouse position at the start of the drag operation. + +proc tkScrollStartDrag {w x y} { + global tkPriv + + if {[$w cget -command] == ""} { + return + } + set tkPriv(pressX) $x + set tkPriv(pressY) $y + set tkPriv(initValues) [$w get] + set iv0 [lindex $tkPriv(initValues) 0] + if {[llength $tkPriv(initValues)] == 2} { + set tkPriv(initPos) $iv0 + } else { + if {$iv0 == 0} { + set tkPriv(initPos) 0.0 + } else { + set tkPriv(initPos) [expr (double([lindex $tkPriv(initValues) 2])) \ + / [lindex $tkPriv(initValues) 0]] + } + } +} + +# tkScrollDrag -- +# This procedure is called for each mouse motion even when the slider +# is being dragged. It notifies the associated widget if we're not +# jump scrolling, and it just updates the scrollbar if we are jump +# scrolling. +# +# Arguments: +# w - The scrollbar widget. +# x, y - The current mouse position. + +proc tkScrollDrag {w x y} { + global tkPriv + + if {$tkPriv(initPos) == ""} { + return + } + set delta [$w delta [expr $x - $tkPriv(pressX)] [expr $y - $tkPriv(pressY)]] + if [$w cget -jump] { + if {[llength $tkPriv(initValues)] == 2} { + $w set [expr [lindex $tkPriv(initValues) 0] + $delta] \ + [expr [lindex $tkPriv(initValues) 1] + $delta] + } else { + set delta [expr round($delta * [lindex $tkPriv(initValues) 0])] + eval $w set [lreplace $tkPriv(initValues) 2 3 \ + [expr [lindex $tkPriv(initValues) 2] + $delta] \ + [expr [lindex $tkPriv(initValues) 3] + $delta]] + } + } else { + tkScrollToPos $w [expr $tkPriv(initPos) + $delta] + } +} + +# tkScrollEndDrag -- +# This procedure is called to end an interactive drag of the slider. +# It scrolls the window if we're in jump mode, otherwise it does nothing. +# +# Arguments: +# w - The scrollbar widget. +# x, y - The mouse position at the end of the drag operation. + +proc tkScrollEndDrag {w x y} { + global tkPriv + + if {$tkPriv(initPos) == ""} { + return + } + if [$w cget -jump] { + set delta [$w delta [expr $x - $tkPriv(pressX)] \ + [expr $y - $tkPriv(pressY)]] + tkScrollToPos $w [expr $tkPriv(initPos) + $delta] + } + set tkPriv(initPos) "" +} + +# tkScrollByUnits -- +# This procedure tells the scrollbar's associated widget to scroll up +# or down by a given number of units. It notifies the associated widget +# in different ways for old and new command syntaxes. +# +# Arguments: +# w - The scrollbar widget. +# orient - Which kinds of scrollbars this applies to: "h" for +# horizontal, "v" for vertical, "hv" for both. +# amount - How many units to scroll: typically 1 or -1. + +proc tkScrollByUnits {w orient amount} { + set cmd [$w cget -command] + if {($cmd == "") || ([string first \ + [string index [$w cget -orient] 0] $orient] < 0)} { + return + } + set info [$w get] + if {[llength $info] == 2} { + uplevel #0 $cmd scroll $amount units + } else { + uplevel #0 $cmd [expr [lindex $info 2] + $amount] + } +} + +# tkScrollByPages -- +# This procedure tells the scrollbar's associated widget to scroll up +# or down by a given number of screenfuls. It notifies the associated +# widget in different ways for old and new command syntaxes. +# +# Arguments: +# w - The scrollbar widget. +# orient - Which kinds of scrollbars this applies to: "h" for +# horizontal, "v" for vertical, "hv" for both. +# amount - How many screens to scroll: typically 1 or -1. + +proc tkScrollByPages {w orient amount} { + set cmd [$w cget -command] + if {($cmd == "") || ([string first \ + [string index [$w cget -orient] 0] $orient] < 0)} { + return + } + set info [$w get] + if {[llength $info] == 2} { + uplevel #0 $cmd scroll $amount pages + } else { + uplevel #0 $cmd [expr [lindex $info 2] + $amount*([lindex $info 1] - 1)] + } +} + +# tkScrollToPos -- +# This procedure tells the scrollbar's associated widget to scroll to +# a particular location, given by a fraction between 0 and 1. It notifies +# the associated widget in different ways for old and new command syntaxes. +# +# Arguments: +# w - The scrollbar widget. +# pos - A fraction between 0 and 1 indicating a desired position +# in the document. + +proc tkScrollToPos {w pos} { + set cmd [$w cget -command] + if {($cmd == "")} { + return + } + set info [$w get] + if {[llength $info] == 2} { + uplevel #0 $cmd moveto $pos + } else { + uplevel #0 $cmd [expr round([lindex $info 0]*$pos)] + } +} + +# tkScrollTopBottom +# Scroll to the top or bottom of the document, depending on the mouse +# position. +# +# Arguments: +# w - The scrollbar widget. +# x, y - Mouse coordinates within the widget. + +proc tkScrollTopBottom {w x y} { + global tkPriv + set element [$w identify $x $y] + if [string match *1 $element] { + tkScrollToPos $w 0 + } elseif [string match *2 $element] { + tkScrollToPos $w 1 + } + + # Set tkPriv(relief), since it's needed by tkScrollButtonUp. + + set tkPriv(relief) [$w cget -activerelief] +} + +# tkScrollButton2Down +# This procedure is invoked when button 2 is pressed over a scrollbar. +# If the button is over the trough or slider, it sets the scrollbar to +# the mouse position and starts a slider drag. Otherwise it just +# behaves the same as button 1. +# +# Arguments: +# w - The scrollbar widget. +# x, y - Mouse coordinates within the widget. + +proc tkScrollButton2Down {w x y} { + global tkPriv + set element [$w identify $x $y] + if {($element == "arrow1") || ($element == "arrow2")} { + tkScrollButtonDown $w $x $y + return + } + tkScrollToPos $w [$w fraction $x $y] + set tkPriv(relief) [$w cget -activerelief] + + # Need the "update idletasks" below so that the widget calls us + # back to reset the actual scrollbar position before we start the + # slider drag. + + update idletasks + $w configure -activerelief sunken + $w activate slider + tkScrollStartDrag $w $x $y +} diff --git a/library/tclIndex b/library/tclIndex new file mode 100644 index 0000000..e65708e --- /dev/null +++ b/library/tclIndex @@ -0,0 +1,241 @@ +# Tcl autoload index file, version 2.0 +# This file is generated by the "auto_mkindex" command +# and sourced to set up indexing information for one or +# more commands. Typically each line is a command that +# sets an element in the auto_index array, where the +# element name is the name of a command and the value is +# a script that loads the command. + +set auto_index(tkButtonEnter) [list source [file join $dir button.tcl]] +set auto_index(tkButtonLeave) [list source [file join $dir button.tcl]] +set auto_index(tkCheckRadioEnter) [list source [file join $dir button.tcl]] +set auto_index(tkButtonDown) [list source [file join $dir button.tcl]] +set auto_index(tkCheckRadioDown) [list source [file join $dir button.tcl]] +set auto_index(tkButtonUp) [list source [file join $dir button.tcl]] +set auto_index(tkButtonEnter) [list source [file join $dir button.tcl]] +set auto_index(tkButtonLeave) [list source [file join $dir button.tcl]] +set auto_index(tkButtonDown) [list source [file join $dir button.tcl]] +set auto_index(tkButtonUp) [list source [file join $dir button.tcl]] +set auto_index(tkButtonEnter) [list source [file join $dir button.tcl]] +set auto_index(tkButtonLeave) [list source [file join $dir button.tcl]] +set auto_index(tkButtonDown) [list source [file join $dir button.tcl]] +set auto_index(tkButtonUp) [list source [file join $dir button.tcl]] +set auto_index(tkButtonInvoke) [list source [file join $dir button.tcl]] +set auto_index(tkCheckRadioInvoke) [list source [file join $dir button.tcl]] +set auto_index(tk_dialog) [list source [file join $dir dialog.tcl]] +set auto_index(tkEntryClosestGap) [list source [file join $dir entry.tcl]] +set auto_index(tkEntryButton1) [list source [file join $dir entry.tcl]] +set auto_index(tkEntryMouseSelect) [list source [file join $dir entry.tcl]] +set auto_index(tkEntryPaste) [list source [file join $dir entry.tcl]] +set auto_index(tkEntryAutoScan) [list source [file join $dir entry.tcl]] +set auto_index(tkEntryKeySelect) [list source [file join $dir entry.tcl]] +set auto_index(tkEntryInsert) [list source [file join $dir entry.tcl]] +set auto_index(tkEntryBackspace) [list source [file join $dir entry.tcl]] +set auto_index(tkEntrySeeInsert) [list source [file join $dir entry.tcl]] +set auto_index(tkEntrySetCursor) [list source [file join $dir entry.tcl]] +set auto_index(tkEntryTranspose) [list source [file join $dir entry.tcl]] +set auto_index(tkEntryPreviousWord) [list source [file join $dir entry.tcl]] +set auto_index(tkListboxBeginSelect) [list source [file join $dir listbox.tcl]] +set auto_index(tkListboxMotion) [list source [file join $dir listbox.tcl]] +set auto_index(tkListboxBeginExtend) [list source [file join $dir listbox.tcl]] +set auto_index(tkListboxBeginToggle) [list source [file join $dir listbox.tcl]] +set auto_index(tkListboxAutoScan) [list source [file join $dir listbox.tcl]] +set auto_index(tkListboxUpDown) [list source [file join $dir listbox.tcl]] +set auto_index(tkListboxExtendUpDown) [list source [file join $dir listbox.tcl]] +set auto_index(tkListboxDataExtend) [list source [file join $dir listbox.tcl]] +set auto_index(tkListboxCancel) [list source [file join $dir listbox.tcl]] +set auto_index(tkListboxSelectAll) [list source [file join $dir listbox.tcl]] +set auto_index(tkMbEnter) [list source [file join $dir menu.tcl]] +set auto_index(tkMbLeave) [list source [file join $dir menu.tcl]] +set auto_index(tkMbPost) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuUnpost) [list source [file join $dir menu.tcl]] +set auto_index(tkMbMotion) [list source [file join $dir menu.tcl]] +set auto_index(tkMbButtonUp) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuMotion) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuButtonDown) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuLeave) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuInvoke) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuEscape) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuUpArrow) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuDownArrow) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuLeftArrow) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuRightArrow) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuNextMenu) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuNextEntry) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuFind) [list source [file join $dir menu.tcl]] +set auto_index(tkTraverseToMenu) [list source [file join $dir menu.tcl]] +set auto_index(tkFirstMenu) [list source [file join $dir menu.tcl]] +set auto_index(tkTraverseWithinMenu) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuFirstEntry) [list source [file join $dir menu.tcl]] +set auto_index(tkMenuFindName) [list source [file join $dir menu.tcl]] +set auto_index(tkPostOverPoint) [list source [file join $dir menu.tcl]] +set auto_index(tkSaveGrabInfo) [list source [file join $dir menu.tcl]] +set auto_index(tkRestoreOldGrab) [list source [file join $dir menu.tcl]] +set auto_index(tk_menuSetFocus) [list source [file join $dir menu.tcl]] +set auto_index(tk_popup) [list source [file join $dir menu.tcl]] +set auto_index(tkScrollButtonDown) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkScrollButtonUp) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkScrollSelect) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkScrollStartDrag) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkScrollDrag) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkScrollEndDrag) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkScrollByUnits) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkScrollByPages) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkScrollToPos) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkScrollTopBottom) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkScrollButton2Down) [list source [file join $dir scrlbar.tcl]] +set auto_index(tkTextClosestGap) [list source [file join $dir text.tcl]] +set auto_index(tkTextButton1) [list source [file join $dir text.tcl]] +set auto_index(tkTextSelectTo) [list source [file join $dir text.tcl]] +set auto_index(tkTextKeyExtend) [list source [file join $dir text.tcl]] +set auto_index(tkTextPaste) [list source [file join $dir text.tcl]] +set auto_index(tkTextAutoScan) [list source [file join $dir text.tcl]] +set auto_index(tkTextSetCursor) [list source [file join $dir text.tcl]] +set auto_index(tkTextKeySelect) [list source [file join $dir text.tcl]] +set auto_index(tkTextResetAnchor) [list source [file join $dir text.tcl]] +set auto_index(tkTextInsert) [list source [file join $dir text.tcl]] +set auto_index(tkTextUpDownLine) [list source [file join $dir text.tcl]] +set auto_index(tkTextPrevPara) [list source [file join $dir text.tcl]] +set auto_index(tkTextNextPara) [list source [file join $dir text.tcl]] +set auto_index(tkTextScrollPages) [list source [file join $dir text.tcl]] +set auto_index(tkTextTranspose) [list source [file join $dir text.tcl]] +set auto_index(tk_textCopy) [list source [file join $dir text.tcl]] +set auto_index(tk_textCut) [list source [file join $dir text.tcl]] +set auto_index(tk_textPaste) [list source [file join $dir text.tcl]] +set auto_index(tkTextNextPos) [list source [file join $dir text.tcl]] +set auto_index(tkTextPrevPos) [list source [file join $dir text.tcl]] +set auto_index(tkScreenChanged) [list source [file join $dir tk.tcl]] +set auto_index(tkEventMotifBindings) [list source [file join $dir tk.tcl]] +set auto_index(tkCancelRepeat) [list source [file join $dir tk.tcl]] +set auto_index(tkTabToWindow) [list source [file join $dir tk.tcl]] +set auto_index(bgerror) [list source [file join $dir bgerror.tcl]] +set auto_index(tkScaleActivate) [list source [file join $dir scale.tcl]] +set auto_index(tkScaleButtonDown) [list source [file join $dir scale.tcl]] +set auto_index(tkScaleDrag) [list source [file join $dir scale.tcl]] +set auto_index(tkScaleEndDrag) [list source [file join $dir scale.tcl]] +set auto_index(tkScaleIncrement) [list source [file join $dir scale.tcl]] +set auto_index(tkScaleControlPress) [list source [file join $dir scale.tcl]] +set auto_index(tkScaleButton2Down) [list source [file join $dir scale.tcl]] +set auto_index(tk_optionMenu) [list source [file join $dir optMenu.tcl]] +set auto_index(tkTearOffMenu) [list source [file join $dir tearoff.tcl]] +set auto_index(tkMenuDup) [list source [file join $dir tearoff.tcl]] +set auto_index(tk_menuBar) [list source [file join $dir obsolete.tcl]] +set auto_index(tk_bindForTraversal) [list source [file join $dir obsolete.tcl]] +set auto_index(tk_focusNext) [list source [file join $dir focus.tcl]] +set auto_index(tk_focusPrev) [list source [file join $dir focus.tcl]] +set auto_index(tkFocusOK) [list source [file join $dir focus.tcl]] +set auto_index(tk_focusFollowsMouse) [list source [file join $dir focus.tcl]] +set auto_index(tkConsoleInit) [list source [file join $dir console.tcl]] +set auto_index(tkConsoleSource) [list source [file join $dir console.tcl]] +set auto_index(tkConsoleInvoke) [list source [file join $dir console.tcl]] +set auto_index(tkConsoleHistory) [list source [file join $dir console.tcl]] +set auto_index(tkConsolePrompt) [list source [file join $dir console.tcl]] +set auto_index(tkConsoleBind) [list source [file join $dir console.tcl]] +set auto_index(tkConsoleInsert) [list source [file join $dir console.tcl]] +set auto_index(tkConsoleOutput) [list source [file join $dir console.tcl]] +set auto_index(tkConsoleExit) [list source [file join $dir console.tcl]] +set auto_index(tkConsoleAbout) [list source [file join $dir console.tcl]] +set auto_index(tk_setPalette) [list source [file join $dir palette.tcl]] +set auto_index(tkRecolorTree) [list source [file join $dir palette.tcl]] +set auto_index(tkDarken) [list source [file join $dir palette.tcl]] +set auto_index(tk_bisque) [list source [file join $dir palette.tcl]] +set auto_index(tkColorDialog) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_InitValues) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_Config) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_BuildDialog) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_SetRGBValue) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_XToRgb) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_RgbToX) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_DrawColorScale) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_CreateSelector) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_RedrawFinalColor) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_RedrawColorBars) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_StartMove) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_MoveSelector) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_ReleaseMouse) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_ResizeColorBars) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_HandleSelEntry) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_HandleRGBEntry) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_EnterColorBar) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_LeaveColorBar) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_OkCmd) [list source [file join $dir clrpick.tcl]] +set auto_index(tkColorDialog_CancelCmd) [list source [file join $dir clrpick.tcl]] +set auto_index(tclParseConfigSpec) [list source [file join $dir comdlg.tcl]] +set auto_index(tclListValidFlags) [list source [file join $dir comdlg.tcl]] +set auto_index(tclSortNoCase) [list source [file join $dir comdlg.tcl]] +set auto_index(tclVerifyInteger) [list source [file join $dir comdlg.tcl]] +set auto_index(tkFocusGroup_Create) [list source [file join $dir comdlg.tcl]] +set auto_index(tkFocusGroup_BindIn) [list source [file join $dir comdlg.tcl]] +set auto_index(tkFocusGroup_BindOut) [list source [file join $dir comdlg.tcl]] +set auto_index(tkFocusGroup_Destroy) [list source [file join $dir comdlg.tcl]] +set auto_index(tkFocusGroup_In) [list source [file join $dir comdlg.tcl]] +set auto_index(tkFocusGroup_Out) [list source [file join $dir comdlg.tcl]] +set auto_index(tkFDGetFileTypes) [list source [file join $dir comdlg.tcl]] +set auto_index(::safe::loadTk) [list source [file join $dir safetk.tcl]] +set auto_index(::safe::tkTopLevel) [list source [file join $dir safetk.tcl]] +set auto_index(tkMessageBox) [list source [file join $dir msgbox.tcl]] +set auto_index(tkIconList) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Config) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Create) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_AutoScan) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_DeleteAll) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Add) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Arrange) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Invoke) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_See) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_SelectAtXY) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Select) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Unselect) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Get) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Btn1) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Motion1) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Double1) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_ReturnKey) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Leave1) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_FocusIn) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_UpDown) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_LeftRight) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_KeyPress) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Goto) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkIconList_Reset) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_Config) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_Create) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_UpdateWhenIdle) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_Update) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_SetPathSilently) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_SetPath) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_SetFilter) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialogResolveFile) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_EntFocusIn) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_EntFocusOut) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_ActivateEnt) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_InvokeBtn) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_UpDirCmd) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_JoinFile) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_OkCmd) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_CancelCmd) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_ListBrowse) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_ListInvoke) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkFDialog_Done) [list source [file join $dir tkfbox.tcl]] +set auto_index(tkMotifFDialog) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_Config) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_Create) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_MakeSList) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_BrowseDList) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_ActivateDList) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_BrowseFList) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_ActivateFList) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_ActivateFEnt) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_InterpFilter) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_ActivateSEnt) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_OkCmd) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_FilterCmd) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_CancelCmd) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_Update) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkMotifFDialog_LoadFiles) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkListBoxKeyAccel_Set) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkListBoxKeyAccel_Unset) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkListBoxKeyAccel_Key) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkListBoxKeyAccel_Goto) [list source [file join $dir xmfbox.tcl]] +set auto_index(tkListBoxKeyAccel_Reset) [list source [file join $dir xmfbox.tcl]] diff --git a/library/tearoff.tcl b/library/tearoff.tcl new file mode 100644 index 0000000..7cbe8e7 --- /dev/null +++ b/library/tearoff.tcl @@ -0,0 +1,145 @@ +# tearoff.tcl -- +# +# This file contains procedures that implement tear-off menus. +# +# SCCS: @(#) tearoff.tcl 1.20 97/08/21 14:49:27 +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# tkTearoffMenu -- +# Given the name of a menu, this procedure creates a torn-off menu +# that is identical to the given menu (including nested submenus). +# The new torn-off menu exists as a toplevel window managed by the +# window manager. The return value is the name of the new menu. +# The window is created at the point specified by x and y +# +# Arguments: +# w - The menu to be torn-off (duplicated). +# x - x coordinate where window is created +# y - y coordinate where window is created + +proc tkTearOffMenu {w {x 0} {y 0}} { + # Find a unique name to use for the torn-off menu. Find the first + # ancestor of w that is a toplevel but not a menu, and use this as + # the parent of the new menu. This guarantees that the torn off + # menu will be on the same screen as the original menu. By making + # it a child of the ancestor, rather than a child of the menu, it + # can continue to live even if the menu is deleted; it will go + # away when the toplevel goes away. + + if {$x == 0} { + set x [winfo rootx $w] + } + if {$y == 0} { + set y [winfo rooty $w] + } + + set parent [winfo parent $w] + while {([winfo toplevel $parent] != $parent) + || ([winfo class $parent] == "Menu")} { + set parent [winfo parent $parent] + } + if {$parent == "."} { + set parent "" + } + for {set i 1} 1 {incr i} { + set menu $parent.tearoff$i + if ![winfo exists $menu] { + break + } + } + + $w clone $menu tearoff + + # Pick a title for the new menu by looking at the parent of the + # original: if the parent is a menu, then use the text of the active + # entry. If it's a menubutton then use its text. + + set parent [winfo parent $w] + if {[$menu cget -title] != ""} { + wm title $menu [$menu cget -title] + } else { + switch [winfo class $parent] { + Menubutton { + wm title $menu [$parent cget -text] + } + Menu { + wm title $menu [$parent entrycget active -label] + } + } + } + + $menu post $x $y + + if {[winfo exists $menu] == 0} { + return "" + } + + # Set tkPriv(focus) on entry: otherwise the focus will get lost + # after keyboard invocation of a sub-menu (it will stay on the + # submenu). + + bind $menu <Enter> { + set tkPriv(focus) %W + } + + # If there is a -tearoffcommand option for the menu, invoke it + # now. + + set cmd [$w cget -tearoffcommand] + if {$cmd != ""} { + uplevel #0 $cmd $w $menu + } + return $menu +} + +# tkMenuDup -- +# Given a menu (hierarchy), create a duplicate menu (hierarchy) +# in a given window. +# +# Arguments: +# src - Source window. Must be a menu. It and its +# menu descendants will be duplicated at dst. +# dst - Name to use for topmost menu in duplicate +# hierarchy. + +proc tkMenuDup {src dst type} { + set cmd [list menu $dst -type $type] + foreach option [$src configure] { + if {[llength $option] == 2} { + continue + } + if {[string compare [lindex $option 0] "-type"] == 0} { + continue + } + lappend cmd [lindex $option 0] [lindex $option 4] + } + eval $cmd + set last [$src index last] + if {$last == "none"} { + return + } + for {set i [$src cget -tearoff]} {$i <= $last} {incr i} { + set cmd [list $dst add [$src type $i]] + foreach option [$src entryconfigure $i] { + lappend cmd [lindex $option 0] [lindex $option 4] + } + eval $cmd + } + + # Duplicate the binding tags and bindings from the source menu. + + regsub -all . $src {\\&} quotedSrc + regsub -all . $dst {\\&} quotedDst + regsub -all $quotedSrc [bindtags $src] $dst x + bindtags $dst $x + foreach event [bind $src] { + regsub -all $quotedSrc [bind $src $event] $dst x + bind $dst $event $x + } +} diff --git a/library/text.tcl b/library/text.tcl new file mode 100644 index 0000000..891a9ed --- /dev/null +++ b/library/text.tcl @@ -0,0 +1,1010 @@ +# text.tcl -- +# +# This file defines the default bindings for Tk text widgets and provides +# procedures that help in implementing the bindings. +# +# SCCS: @(#) text.tcl 1.58 97/09/17 18:54:56 +# +# Copyright (c) 1992-1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +#------------------------------------------------------------------------- +# Elements of tkPriv that are used in this file: +# +# afterId - If non-null, it means that auto-scanning is underway +# and it gives the "after" id for the next auto-scan +# command to be executed. +# char - Character position on the line; kept in order +# to allow moving up or down past short lines while +# still remembering the desired position. +# mouseMoved - Non-zero means the mouse has moved a significant +# amount since the button went down (so, for example, +# start dragging out a selection). +# prevPos - Used when moving up or down lines via the keyboard. +# Keeps track of the previous insert position, so +# we can distinguish a series of ups and downs, all +# in a row, from a new up or down. +# selectMode - The style of selection currently underway: +# char, word, or line. +# x, y - Last known mouse coordinates for scanning +# and auto-scanning. +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# The code below creates the default class bindings for entries. +#------------------------------------------------------------------------- + +# Standard Motif bindings: + +bind Text <1> { + tkTextButton1 %W %x %y + %W tag remove sel 0.0 end +} +bind Text <B1-Motion> { + set tkPriv(x) %x + set tkPriv(y) %y + tkTextSelectTo %W %x %y +} +bind Text <Double-1> { + set tkPriv(selectMode) word + tkTextSelectTo %W %x %y + catch {%W mark set insert sel.first} +} +bind Text <Triple-1> { + set tkPriv(selectMode) line + tkTextSelectTo %W %x %y + catch {%W mark set insert sel.first} +} +bind Text <Shift-1> { + tkTextResetAnchor %W @%x,%y + set tkPriv(selectMode) char + tkTextSelectTo %W %x %y +} +bind Text <Double-Shift-1> { + set tkPriv(selectMode) word + tkTextSelectTo %W %x %y +} +bind Text <Triple-Shift-1> { + set tkPriv(selectMode) line + tkTextSelectTo %W %x %y +} +bind Text <B1-Leave> { + set tkPriv(x) %x + set tkPriv(y) %y + tkTextAutoScan %W +} +bind Text <B1-Enter> { + tkCancelRepeat +} +bind Text <ButtonRelease-1> { + tkCancelRepeat +} +bind Text <Control-1> { + %W mark set insert @%x,%y +} +bind Text <ButtonRelease-2> { + if {!$tkPriv(mouseMoved) || $tk_strictMotif} { + tkTextPaste %W %x %y + } +} +bind Text <Left> { + tkTextSetCursor %W insert-1c +} +bind Text <Right> { + tkTextSetCursor %W insert+1c +} +bind Text <Up> { + tkTextSetCursor %W [tkTextUpDownLine %W -1] +} +bind Text <Down> { + tkTextSetCursor %W [tkTextUpDownLine %W 1] +} +bind Text <Shift-Left> { + tkTextKeySelect %W [%W index {insert - 1c}] +} +bind Text <Shift-Right> { + tkTextKeySelect %W [%W index {insert + 1c}] +} +bind Text <Shift-Up> { + tkTextKeySelect %W [tkTextUpDownLine %W -1] +} +bind Text <Shift-Down> { + tkTextKeySelect %W [tkTextUpDownLine %W 1] +} +bind Text <Control-Left> { + tkTextSetCursor %W [tkTextPrevPos %W insert tcl_startOfPreviousWord] +} +bind Text <Control-Right> { + tkTextSetCursor %W [tkTextNextWord %W insert] +} +bind Text <Control-Up> { + tkTextSetCursor %W [tkTextPrevPara %W insert] +} +bind Text <Control-Down> { + tkTextSetCursor %W [tkTextNextPara %W insert] +} +bind Text <Shift-Control-Left> { + tkTextKeySelect %W [tkTextPrevPos %W insert tcl_startOfPreviousWord] +} +bind Text <Shift-Control-Right> { + tkTextKeySelect %W [tkTextNextWord %W insert] +} +bind Text <Shift-Control-Up> { + tkTextKeySelect %W [tkTextPrevPara %W insert] +} +bind Text <Shift-Control-Down> { + tkTextKeySelect %W [tkTextNextPara %W insert] +} +bind Text <Prior> { + tkTextSetCursor %W [tkTextScrollPages %W -1] +} +bind Text <Shift-Prior> { + tkTextKeySelect %W [tkTextScrollPages %W -1] +} +bind Text <Next> { + tkTextSetCursor %W [tkTextScrollPages %W 1] +} +bind Text <Shift-Next> { + tkTextKeySelect %W [tkTextScrollPages %W 1] +} +bind Text <Control-Prior> { + %W xview scroll -1 page +} +bind Text <Control-Next> { + %W xview scroll 1 page +} + +bind Text <Home> { + tkTextSetCursor %W {insert linestart} +} +bind Text <Shift-Home> { + tkTextKeySelect %W {insert linestart} +} +bind Text <End> { + tkTextSetCursor %W {insert lineend} +} +bind Text <Shift-End> { + tkTextKeySelect %W {insert lineend} +} +bind Text <Control-Home> { + tkTextSetCursor %W 1.0 +} +bind Text <Control-Shift-Home> { + tkTextKeySelect %W 1.0 +} +bind Text <Control-End> { + tkTextSetCursor %W {end - 1 char} +} +bind Text <Control-Shift-End> { + tkTextKeySelect %W {end - 1 char} +} + +bind Text <Tab> { + tkTextInsert %W \t + focus %W + break +} +bind Text <Shift-Tab> { + # Needed only to keep <Tab> binding from triggering; doesn't + # have to actually do anything. + break +} +bind Text <Control-Tab> { + focus [tk_focusNext %W] +} +bind Text <Control-Shift-Tab> { + focus [tk_focusPrev %W] +} +bind Text <Control-i> { + tkTextInsert %W \t +} +bind Text <Return> { + tkTextInsert %W \n +} +bind Text <Delete> { + if {[%W tag nextrange sel 1.0 end] != ""} { + %W delete sel.first sel.last + } else { + %W delete insert + %W see insert + } +} +bind Text <BackSpace> { + if {[%W tag nextrange sel 1.0 end] != ""} { + %W delete sel.first sel.last + } elseif [%W compare insert != 1.0] { + %W delete insert-1c + %W see insert + } +} + +bind Text <Control-space> { + %W mark set anchor insert +} +bind Text <Select> { + %W mark set anchor insert +} +bind Text <Control-Shift-space> { + set tkPriv(selectMode) char + tkTextKeyExtend %W insert +} +bind Text <Shift-Select> { + set tkPriv(selectMode) char + tkTextKeyExtend %W insert +} +bind Text <Control-slash> { + %W tag add sel 1.0 end +} +bind Text <Control-backslash> { + %W tag remove sel 1.0 end +} +bind Text <<Cut>> { + tk_textCut %W +} +bind Text <<Copy>> { + tk_textCopy %W +} +bind Text <<Paste>> { + tk_textPaste %W +} +bind Text <<Clear>> { + catch {%W delete sel.first sel.last} +} +bind Text <Insert> { + catch {tkTextInsert %W [selection get -displayof %W]} +} +bind Text <KeyPress> { + tkTextInsert %W %A +} + +# Ignore all Alt, Meta, and Control keypresses unless explicitly bound. +# Otherwise, if a widget binding for one of these is defined, the +# <KeyPress> class binding will also fire and insert the character, +# which is wrong. Ditto for <Escape>. + +bind Text <Alt-KeyPress> {# nothing } +bind Text <Meta-KeyPress> {# nothing} +bind Text <Control-KeyPress> {# nothing} +bind Text <Escape> {# nothing} +bind Text <KP_Enter> {# nothing} +if {$tcl_platform(platform) == "macintosh"} { + bind Text <Command-KeyPress> {# nothing} +} + +# Additional emacs-like bindings: + +bind Text <Control-a> { + if !$tk_strictMotif { + tkTextSetCursor %W {insert linestart} + } +} +bind Text <Control-b> { + if !$tk_strictMotif { + tkTextSetCursor %W insert-1c + } +} +bind Text <Control-d> { + if !$tk_strictMotif { + %W delete insert + } +} +bind Text <Control-e> { + if !$tk_strictMotif { + tkTextSetCursor %W {insert lineend} + } +} +bind Text <Control-f> { + if !$tk_strictMotif { + tkTextSetCursor %W insert+1c + } +} +bind Text <Control-k> { + if !$tk_strictMotif { + if [%W compare insert == {insert lineend}] { + %W delete insert + } else { + %W delete insert {insert lineend} + } + } +} +bind Text <Control-n> { + if !$tk_strictMotif { + tkTextSetCursor %W [tkTextUpDownLine %W 1] + } +} +bind Text <Control-o> { + if !$tk_strictMotif { + %W insert insert \n + %W mark set insert insert-1c + } +} +bind Text <Control-p> { + if !$tk_strictMotif { + tkTextSetCursor %W [tkTextUpDownLine %W -1] + } +} +bind Text <Control-t> { + if !$tk_strictMotif { + tkTextTranspose %W + } +} + +if {$tcl_platform(platform) != "windows"} { +bind Text <Control-v> { + if !$tk_strictMotif { + tkTextScrollPages %W 1 + } +} +} + +bind Text <Meta-b> { + if !$tk_strictMotif { + tkTextSetCursor %W [tkTextPrevPos %W insert tcl_startOfPreviousWord] + } +} +bind Text <Meta-d> { + if !$tk_strictMotif { + %W delete insert [tkTextNextWord %W insert] + } +} +bind Text <Meta-f> { + if !$tk_strictMotif { + tkTextSetCursor %W [tkTextNextWord %W insert] + } +} +bind Text <Meta-less> { + if !$tk_strictMotif { + tkTextSetCursor %W 1.0 + } +} +bind Text <Meta-greater> { + if !$tk_strictMotif { + tkTextSetCursor %W end-1c + } +} +bind Text <Meta-BackSpace> { + if !$tk_strictMotif { + %W delete [tkTextPrevPos %W insert tcl_startOfPreviousWord] insert + } +} +bind Text <Meta-Delete> { + if !$tk_strictMotif { + %W delete [tkTextPrevPos %W insert tcl_startOfPreviousWord] insert + } +} + +# Macintosh only bindings: + +# if text black & highlight black -> text white, other text the same +if {$tcl_platform(platform) == "macintosh"} { +bind Text <FocusIn> { + %W tag configure sel -borderwidth 0 + %W configure -selectbackground systemHighlight -selectforeground systemHighlightText +} +bind Text <FocusOut> { + %W tag configure sel -borderwidth 1 + %W configure -selectbackground white -selectforeground black +} +bind Text <Option-Left> { + tkTextSetCursor %W [tkTextPrevPos %W insert tcl_startOfPreviousWord] +} +bind Text <Option-Right> { + tkTextSetCursor %W [tkTextNextWord %W insert] +} +bind Text <Option-Up> { + tkTextSetCursor %W [tkTextPrevPara %W insert] +} +bind Text <Option-Down> { + tkTextSetCursor %W [tkTextNextPara %W insert] +} +bind Text <Shift-Option-Left> { + tkTextKeySelect %W [tkTextPrevPos %W insert tcl_startOfPreviousWord] +} +bind Text <Shift-Option-Right> { + tkTextKeySelect %W [tkTextNextWord %W insert] +} +bind Text <Shift-Option-Up> { + tkTextKeySelect %W [tkTextPrevPara %W insert] +} +bind Text <Shift-Option-Down> { + tkTextKeySelect %W [tkTextNextPara %W insert] +} + +# End of Mac only bindings +} + +# A few additional bindings of my own. + +bind Text <Control-h> { + if !$tk_strictMotif { + if [%W compare insert != 1.0] { + %W delete insert-1c + %W see insert + } + } +} +bind Text <2> { + if !$tk_strictMotif { + %W scan mark %x %y + set tkPriv(x) %x + set tkPriv(y) %y + set tkPriv(mouseMoved) 0 + } +} +bind Text <B2-Motion> { + if !$tk_strictMotif { + if {(%x != $tkPriv(x)) || (%y != $tkPriv(y))} { + set tkPriv(mouseMoved) 1 + } + if $tkPriv(mouseMoved) { + %W scan dragto %x %y + } + } +} +set tkPriv(prevPos) {} + +# tkTextClosestGap -- +# Given x and y coordinates, this procedure finds the closest boundary +# between characters to the given coordinates and returns the index +# of the character just after the boundary. +# +# Arguments: +# w - The text window. +# x - X-coordinate within the window. +# y - Y-coordinate within the window. + +proc tkTextClosestGap {w x y} { + set pos [$w index @$x,$y] + set bbox [$w bbox $pos] + if ![string compare $bbox ""] { + return $pos + } + if {($x - [lindex $bbox 0]) < ([lindex $bbox 2]/2)} { + return $pos + } + $w index "$pos + 1 char" +} + +# tkTextButton1 -- +# This procedure is invoked to handle button-1 presses in text +# widgets. It moves the insertion cursor, sets the selection anchor, +# and claims the input focus. +# +# Arguments: +# w - The text window in which the button was pressed. +# x - The x-coordinate of the button press. +# y - The x-coordinate of the button press. + +proc tkTextButton1 {w x y} { + global tkPriv + + set tkPriv(selectMode) char + set tkPriv(mouseMoved) 0 + set tkPriv(pressX) $x + $w mark set insert [tkTextClosestGap $w $x $y] + $w mark set anchor insert + if {[$w cget -state] == "normal"} {focus $w} +} + +# tkTextSelectTo -- +# This procedure is invoked to extend the selection, typically when +# dragging it with the mouse. Depending on the selection mode (character, +# word, line) it selects in different-sized units. This procedure +# ignores mouse motions initially until the mouse has moved from +# one character to another or until there have been multiple clicks. +# +# Arguments: +# w - The text window in which the button was pressed. +# x - Mouse x position. +# y - Mouse y position. + +proc tkTextSelectTo {w x y} { + global tkPriv tcl_platform + + set cur [tkTextClosestGap $w $x $y] + if [catch {$w index anchor}] { + $w mark set anchor $cur + } + set anchor [$w index anchor] + if {[$w compare $cur != $anchor] || (abs($tkPriv(pressX) - $x) >= 3)} { + set tkPriv(mouseMoved) 1 + } + switch $tkPriv(selectMode) { + char { + if [$w compare $cur < anchor] { + set first $cur + set last anchor + } else { + set first anchor + set last $cur + } + } + word { + if [$w compare $cur < anchor] { + set first [tkTextPrevPos $w "$cur + 1c" tcl_wordBreakBefore] + set last [tkTextNextPos $w "anchor" tcl_wordBreakAfter] + } else { + set first [tkTextPrevPos $w anchor tcl_wordBreakBefore] + set last [tkTextNextPos $w "$cur - 1c" tcl_wordBreakAfter] + } + } + line { + if [$w compare $cur < anchor] { + set first [$w index "$cur linestart"] + set last [$w index "anchor - 1c lineend + 1c"] + } else { + set first [$w index "anchor linestart"] + set last [$w index "$cur lineend + 1c"] + } + } + } + if {$tkPriv(mouseMoved) || ($tkPriv(selectMode) != "char")} { + if {$tcl_platform(platform) != "unix" && [$w compare $cur < anchor]} { + $w mark set insert $first + } else { + $w mark set insert $last + } + $w tag remove sel 0.0 $first + $w tag add sel $first $last + $w tag remove sel $last end + update idletasks + } +} + +# tkTextKeyExtend -- +# This procedure handles extending the selection from the keyboard, +# where the point to extend to is really the boundary between two +# characters rather than a particular character. +# +# Arguments: +# w - The text window. +# index - The point to which the selection is to be extended. + +proc tkTextKeyExtend {w index} { + global tkPriv + + set cur [$w index $index] + if [catch {$w index anchor}] { + $w mark set anchor $cur + } + set anchor [$w index anchor] + if [$w compare $cur < anchor] { + set first $cur + set last anchor + } else { + set first anchor + set last $cur + } + $w tag remove sel 0.0 $first + $w tag add sel $first $last + $w tag remove sel $last end +} + +# tkTextPaste -- +# This procedure sets the insertion cursor to the mouse position, +# inserts the selection, and sets the focus to the window. +# +# Arguments: +# w - The text window. +# x, y - Position of the mouse. + +proc tkTextPaste {w x y} { + $w mark set insert [tkTextClosestGap $w $x $y] + catch {$w insert insert [selection get -displayof $w]} + if {[$w cget -state] == "normal"} {focus $w} +} + +# tkTextAutoScan -- +# This procedure is invoked when the mouse leaves a text window +# with button 1 down. It scrolls the window up, down, left, or right, +# depending on where the mouse is (this information was saved in +# tkPriv(x) and tkPriv(y)), and reschedules itself as an "after" +# command so that the window continues to scroll until the mouse +# moves back into the window or the mouse button is released. +# +# Arguments: +# w - The text window. + +proc tkTextAutoScan {w} { + global tkPriv + if {![winfo exists $w]} return + if {$tkPriv(y) >= [winfo height $w]} { + $w yview scroll 2 units + } elseif {$tkPriv(y) < 0} { + $w yview scroll -2 units + } elseif {$tkPriv(x) >= [winfo width $w]} { + $w xview scroll 2 units + } elseif {$tkPriv(x) < 0} { + $w xview scroll -2 units + } else { + return + } + tkTextSelectTo $w $tkPriv(x) $tkPriv(y) + set tkPriv(afterId) [after 50 tkTextAutoScan $w] +} + +# tkTextSetCursor +# Move the insertion cursor to a given position in a text. Also +# clears the selection, if there is one in the text, and makes sure +# that the insertion cursor is visible. Also, don't let the insertion +# cursor appear on the dummy last line of the text. +# +# Arguments: +# w - The text window. +# pos - The desired new position for the cursor in the window. + +proc tkTextSetCursor {w pos} { + global tkPriv + + if [$w compare $pos == end] { + set pos {end - 1 chars} + } + $w mark set insert $pos + $w tag remove sel 1.0 end + $w see insert +} + +# tkTextKeySelect +# This procedure is invoked when stroking out selections using the +# keyboard. It moves the cursor to a new position, then extends +# the selection to that position. +# +# Arguments: +# w - The text window. +# new - A new position for the insertion cursor (the cursor hasn't +# actually been moved to this position yet). + +proc tkTextKeySelect {w new} { + global tkPriv + + if {[$w tag nextrange sel 1.0 end] == ""} { + if [$w compare $new < insert] { + $w tag add sel $new insert + } else { + $w tag add sel insert $new + } + $w mark set anchor insert + } else { + if [$w compare $new < anchor] { + set first $new + set last anchor + } else { + set first anchor + set last $new + } + $w tag remove sel 1.0 $first + $w tag add sel $first $last + $w tag remove sel $last end + } + $w mark set insert $new + $w see insert + update idletasks +} + +# tkTextResetAnchor -- +# Set the selection anchor to whichever end is farthest from the +# index argument. One special trick: if the selection has two or +# fewer characters, just leave the anchor where it is. In this +# case it doesn't matter which point gets chosen for the anchor, +# and for the things like Shift-Left and Shift-Right this produces +# better behavior when the cursor moves back and forth across the +# anchor. +# +# Arguments: +# w - The text widget. +# index - Position at which mouse button was pressed, which determines +# which end of selection should be used as anchor point. + +proc tkTextResetAnchor {w index} { + global tkPriv + + if {[$w tag ranges sel] == ""} { + $w mark set anchor $index + return + } + set a [$w index $index] + set b [$w index sel.first] + set c [$w index sel.last] + if [$w compare $a < $b] { + $w mark set anchor sel.last + return + } + if [$w compare $a > $c] { + $w mark set anchor sel.first + return + } + scan $a "%d.%d" lineA chA + scan $b "%d.%d" lineB chB + scan $c "%d.%d" lineC chC + if {$lineB < $lineC+2} { + set total [string length [$w get $b $c]] + if {$total <= 2} { + return + } + if {[string length [$w get $b $a]] < ($total/2)} { + $w mark set anchor sel.last + } else { + $w mark set anchor sel.first + } + return + } + if {($lineA-$lineB) < ($lineC-$lineA)} { + $w mark set anchor sel.last + } else { + $w mark set anchor sel.first + } +} + +# tkTextInsert -- +# Insert a string into a text at the point of the insertion cursor. +# If there is a selection in the text, and it covers the point of the +# insertion cursor, then delete the selection before inserting. +# +# Arguments: +# w - The text window in which to insert the string +# s - The string to insert (usually just a single character) + +proc tkTextInsert {w s} { + if {($s == "") || ([$w cget -state] == "disabled")} { + return + } + catch { + if {[$w compare sel.first <= insert] + && [$w compare sel.last >= insert]} { + $w delete sel.first sel.last + } + } + $w insert insert $s + $w see insert +} + +# tkTextUpDownLine -- +# Returns the index of the character one line above or below the +# insertion cursor. There are two tricky things here. First, +# we want to maintain the original column across repeated operations, +# even though some lines that will get passed through don't have +# enough characters to cover the original column. Second, don't +# try to scroll past the beginning or end of the text. +# +# Arguments: +# w - The text window in which the cursor is to move. +# n - The number of lines to move: -1 for up one line, +# +1 for down one line. + +proc tkTextUpDownLine {w n} { + global tkPriv + + set i [$w index insert] + scan $i "%d.%d" line char + if {[string compare $tkPriv(prevPos) $i] != 0} { + set tkPriv(char) $char + } + set new [$w index [expr $line + $n].$tkPriv(char)] + if {[$w compare $new == end] || [$w compare $new == "insert linestart"]} { + set new $i + } + set tkPriv(prevPos) $new + return $new +} + +# tkTextPrevPara -- +# Returns the index of the beginning of the paragraph just before a given +# position in the text (the beginning of a paragraph is the first non-blank +# character after a blank line). +# +# Arguments: +# w - The text window in which the cursor is to move. +# pos - Position at which to start search. + +proc tkTextPrevPara {w pos} { + set pos [$w index "$pos linestart"] + while 1 { + if {(([$w get "$pos - 1 line"] == "\n") && ([$w get $pos] != "\n")) + || ($pos == "1.0")} { + if [regexp -indices {^[ ]+(.)} [$w get $pos "$pos lineend"] \ + dummy index] { + set pos [$w index "$pos + [lindex $index 0] chars"] + } + if {[$w compare $pos != insert] || ($pos == "1.0")} { + return $pos + } + } + set pos [$w index "$pos - 1 line"] + } +} + +# tkTextNextPara -- +# Returns the index of the beginning of the paragraph just after a given +# position in the text (the beginning of a paragraph is the first non-blank +# character after a blank line). +# +# Arguments: +# w - The text window in which the cursor is to move. +# start - Position at which to start search. + +proc tkTextNextPara {w start} { + set pos [$w index "$start linestart + 1 line"] + while {[$w get $pos] != "\n"} { + if [$w compare $pos == end] { + return [$w index "end - 1c"] + } + set pos [$w index "$pos + 1 line"] + } + while {[$w get $pos] == "\n"} { + set pos [$w index "$pos + 1 line"] + if [$w compare $pos == end] { + return [$w index "end - 1c"] + } + } + if [regexp -indices {^[ ]+(.)} [$w get $pos "$pos lineend"] \ + dummy index] { + return [$w index "$pos + [lindex $index 0] chars"] + } + return $pos +} + +# tkTextScrollPages -- +# This is a utility procedure used in bindings for moving up and down +# pages and possibly extending the selection along the way. It scrolls +# the view in the widget by the number of pages, and it returns the +# index of the character that is at the same position in the new view +# as the insertion cursor used to be in the old view. +# +# Arguments: +# w - The text window in which the cursor is to move. +# count - Number of pages forward to scroll; may be negative +# to scroll backwards. + +proc tkTextScrollPages {w count} { + set bbox [$w bbox insert] + $w yview scroll $count pages + if {$bbox == ""} { + return [$w index @[expr [winfo height $w]/2],0] + } + return [$w index @[lindex $bbox 0],[lindex $bbox 1]] +} + +# tkTextTranspose -- +# This procedure implements the "transpose" function for text widgets. +# It tranposes the characters on either side of the insertion cursor, +# unless the cursor is at the end of the line. In this case it +# transposes the two characters to the left of the cursor. In either +# case, the cursor ends up to the right of the transposed characters. +# +# Arguments: +# w - Text window in which to transpose. + +proc tkTextTranspose w { + set pos insert + if [$w compare $pos != "$pos lineend"] { + set pos [$w index "$pos + 1 char"] + } + set new [$w get "$pos - 1 char"][$w get "$pos - 2 char"] + if [$w compare "$pos - 1 char" == 1.0] { + return + } + $w delete "$pos - 2 char" $pos + $w insert insert $new + $w see insert +} + +# tk_textCopy -- +# This procedure copies the selection from a text widget into the +# clipboard. +# +# Arguments: +# w - Name of a text widget. + +proc tk_textCopy w { + if {![catch {set data [$w get sel.first sel.last]}]} { + clipboard clear -displayof $w + clipboard append -displayof $w $data + } +} + +# tk_textCut -- +# This procedure copies the selection from a text widget into the +# clipboard, then deletes the selection (if it exists in the given +# widget). +# +# Arguments: +# w - Name of a text widget. + +proc tk_textCut w { + if {![catch {set data [$w get sel.first sel.last]}]} { + clipboard clear -displayof $w + clipboard append -displayof $w $data + $w delete sel.first sel.last + } +} + +# tk_textPaste -- +# This procedure pastes the contents of the clipboard to the insertion +# point in a text widget. +# +# Arguments: +# w - Name of a text widget. + +proc tk_textPaste w { + global tcl_platform + catch { + if {"$tcl_platform(platform)" != "unix"} { + catch { + $w delete sel.first sel.last + } + } + $w insert insert [selection get -displayof $w -selection CLIPBOARD] + } +} + +# tkTextNextWord -- +# Returns the index of the next word position after a given position in the +# text. The next word is platform dependent and may be either the next +# end-of-word position or the next start-of-word position after the next +# end-of-word position. +# +# Arguments: +# w - The text window in which the cursor is to move. +# start - Position at which to start search. + +if {$tcl_platform(platform) == "windows"} { + proc tkTextNextWord {w start} { + tkTextNextPos $w [tkTextNextPos $w $start tcl_endOfWord] \ + tcl_startOfNextWord + } +} else { + proc tkTextNextWord {w start} { + tkTextNextPos $w $start tcl_endOfWord + } +} + +# tkTextNextPos -- +# Returns the index of the next position after the given starting +# position in the text as computed by a specified function. +# +# Arguments: +# w - The text window in which the cursor is to move. +# start - Position at which to start search. +# op - Function to use to find next position. + +proc tkTextNextPos {w start op} { + set text "" + set cur $start + while {[$w compare $cur < end]} { + set text "$text[$w get $cur "$cur lineend + 1c"]" + set pos [$op $text 0] + if {$pos >= 0} { + return [$w index "$start + $pos c"] + } + set cur [$w index "$cur lineend +1c"] + } + return end +} + +# tkTextPrevPos -- +# Returns the index of the previous position before the given starting +# position in the text as computed by a specified function. +# +# Arguments: +# w - The text window in which the cursor is to move. +# start - Position at which to start search. +# op - Function to use to find next position. + +proc tkTextPrevPos {w start op} { + set text "" + set cur $start + while {[$w compare $cur > 0.0]} { + set text "[$w get "$cur linestart - 1c" $cur]$text" + set pos [$op $text end] + if {$pos >= 0} { + return [$w index "$cur linestart - 1c + $pos c"] + } + set cur [$w index "$cur linestart - 1c"] + } + return 0.0 +} + diff --git a/library/tk.tcl b/library/tk.tcl new file mode 100644 index 0000000..4ecbeaf --- /dev/null +++ b/library/tk.tcl @@ -0,0 +1,189 @@ +# tk.tcl -- +# +# Initialization script normally executed in the interpreter for each +# Tk-based application. Arranges class bindings for widgets. +# +# SCCS: @(#) tk.tcl 1.98 97/10/28 15:21:04 +# +# Copyright (c) 1992-1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. + +# Insist on running with compatible versions of Tcl and Tk. + +package require -exact Tk 8.0 +package require -exact Tcl 8.0 + +# Add Tk's directory to the end of the auto-load search path, if it +# isn't already on the path: + +if {[info exists auto_path]} { + if {[lsearch -exact $auto_path $tk_library] < 0} { + lappend auto_path $tk_library + } +} + +# Turn off strict Motif look and feel as a default. + +set tk_strictMotif 0 + +# tkScreenChanged -- +# This procedure is invoked by the binding mechanism whenever the +# "current" screen is changing. The procedure does two things. +# First, it uses "upvar" to make global variable "tkPriv" point at an +# array variable that holds state for the current display. Second, +# it initializes the array if it didn't already exist. +# +# Arguments: +# screen - The name of the new screen. + +proc tkScreenChanged screen { + set x [string last . $screen] + if {$x > 0} { + set disp [string range $screen 0 [expr $x - 1]] + } else { + set disp $screen + } + + uplevel #0 upvar #0 tkPriv.$disp tkPriv + global tkPriv + global tcl_platform + + if [info exists tkPriv] { + set tkPriv(screen) $screen + return + } + set tkPriv(activeMenu) {} + set tkPriv(activeItem) {} + set tkPriv(afterId) {} + set tkPriv(buttons) 0 + set tkPriv(buttonWindow) {} + set tkPriv(dragging) 0 + set tkPriv(focus) {} + set tkPriv(grab) {} + set tkPriv(initPos) {} + set tkPriv(inMenubutton) {} + set tkPriv(listboxPrev) {} + set tkPriv(menuBar) {} + set tkPriv(mouseMoved) 0 + set tkPriv(oldGrab) {} + set tkPriv(popup) {} + set tkPriv(postedMb) {} + set tkPriv(pressX) 0 + set tkPriv(pressY) 0 + set tkPriv(prevPos) 0 + set tkPriv(screen) $screen + set tkPriv(selectMode) char + if {[string compare $tcl_platform(platform) "unix"] == 0} { + set tkPriv(tearoff) 1 + } else { + set tkPriv(tearoff) 0 + } + set tkPriv(window) {} +} + +# Do initial setup for tkPriv, so that it is always bound to something +# (otherwise, if someone references it, it may get set to a non-upvar-ed +# value, which will cause trouble later). + +tkScreenChanged [winfo screen .] + +# tkEventMotifBindings -- +# This procedure is invoked as a trace whenever tk_strictMotif is +# changed. It is used to turn on or turn off the motif virtual +# bindings. +# +# Arguments: +# n1 - the name of the variable being changed ("tk_strictMotif"). + +proc tkEventMotifBindings {n1 dummy dummy} { + upvar $n1 name + + if $name { + set op delete + } else { + set op add + } + + event $op <<Cut>> <Control-Key-w> + event $op <<Copy>> <Meta-Key-w> + event $op <<Paste>> <Control-Key-y> +} + +#---------------------------------------------------------------------- +# Define the set of common virtual events. +#---------------------------------------------------------------------- + +switch $tcl_platform(platform) { + "unix" { + event add <<Cut>> <Control-Key-x> <Key-F20> + event add <<Copy>> <Control-Key-c> <Key-F16> + event add <<Paste>> <Control-Key-v> <Key-F18> + trace variable tk_strictMotif w tkEventMotifBindings + set tk_strictMotif $tk_strictMotif + } + "windows" { + event add <<Cut>> <Control-Key-x> <Shift-Key-Delete> + event add <<Copy>> <Control-Key-c> <Control-Key-Insert> + event add <<Paste>> <Control-Key-v> <Shift-Key-Insert> + } + "macintosh" { + event add <<Cut>> <Control-Key-x> <Key-F2> + event add <<Copy>> <Control-Key-c> <Key-F3> + event add <<Paste>> <Control-Key-v> <Key-F4> + event add <<Clear>> <Clear> + } +} + +# ---------------------------------------------------------------------- +# Read in files that define all of the class bindings. +# ---------------------------------------------------------------------- + +if {$tcl_platform(platform) != "macintosh"} { + source $tk_library/button.tcl + source $tk_library/entry.tcl + source $tk_library/listbox.tcl + source $tk_library/menu.tcl + source $tk_library/scale.tcl + source $tk_library/scrlbar.tcl + source $tk_library/text.tcl +} + +# ---------------------------------------------------------------------- +# Default bindings for keyboard traversal. +# ---------------------------------------------------------------------- + +bind all <Tab> {tkTabToWindow [tk_focusNext %W]} +bind all <Shift-Tab> {tkTabToWindow [tk_focusPrev %W]} + +# tkCancelRepeat -- +# This procedure is invoked to cancel an auto-repeat action described +# by tkPriv(afterId). It's used by several widgets to auto-scroll +# the widget when the mouse is dragged out of the widget with a +# button pressed. +# +# Arguments: +# None. + +proc tkCancelRepeat {} { + global tkPriv + after cancel $tkPriv(afterId) + set tkPriv(afterId) {} +} + +# tkTabToWindow -- +# This procedure moves the focus to the given widget. If the widget +# is an entry, it selects the entire contents of the widget. +# +# Arguments: +# w - Window to which focus should be set. + +proc tkTabToWindow {w} { + if {"[winfo class $w]" == "Entry"} { + $w select range 0 end + $w icur end + } + focus $w +} diff --git a/library/tkfbox.tcl b/library/tkfbox.tcl new file mode 100644 index 0000000..d81a5a2 --- /dev/null +++ b/library/tkfbox.tcl @@ -0,0 +1,1437 @@ +# tkfbox.tcl -- +# +# Implements the "TK" standard file selection dialog box. This +# dialog box is used on the Unix platforms whenever the tk_strictMotif +# flag is not set. +# +# The "TK" standard file selection dialog box is similar to the +# file selection dialog box on Win95(TM). The user can navigate +# the directories by clicking on the folder icons or by +# selectinf the "Directory" option menu. The user can select +# files by clicking on the file icons or by entering a filename +# in the "Filename:" entry. +# +# SCCS: @(#) tkfbox.tcl 1.13 97/10/01 14:51:01 +# +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +#---------------------------------------------------------------------- +# +# I C O N L I S T +# +# This is a pseudo-widget that implements the icon list inside the +# tkFDialog dialog box. +# +#---------------------------------------------------------------------- + +# tkIconList -- +# +# Creates an IconList widget. +# +proc tkIconList {w args} { + upvar #0 $w data + + tkIconList_Config $w $args + tkIconList_Create $w +} + +# tkIconList_Config -- +# +# Configure the widget variables of IconList, according to the command +# line arguments. +# +proc tkIconList_Config {w argList} { + upvar #0 $w data + + # 1: the configuration specs + # + set specs { + {-browsecmd "" "" ""} + {-command "" "" ""} + } + + # 2: parse the arguments + # + tclParseConfigSpec $w $specs "" $argList +} + +# tkIconList_Create -- +# +# Creates an IconList widget by assembling a canvas widget and a +# scrollbar widget. Sets all the bindings necessary for the IconList's +# operations. +# +proc tkIconList_Create {w} { + upvar #0 $w data + + frame $w + set data(sbar) [scrollbar $w.sbar -orient horizontal \ + -highlightthickness 0 -takefocus 0] + set data(canvas) [canvas $w.canvas -bd 2 -relief sunken \ + -width 400 -height 120 -takefocus 1] + pack $data(sbar) -side bottom -fill x -padx 2 + pack $data(canvas) -expand yes -fill both + + $data(sbar) config -command "$data(canvas) xview" + $data(canvas) config -xscrollcommand "$data(sbar) set" + + # Initializes the max icon/text width and height and other variables + # + set data(maxIW) 1 + set data(maxIH) 1 + set data(maxTW) 1 + set data(maxTH) 1 + set data(numItems) 0 + set data(curItem) {} + set data(noScroll) 1 + + # Creates the event bindings. + # + bind $data(canvas) <Configure> "tkIconList_Arrange $w" + + bind $data(canvas) <1> "tkIconList_Btn1 $w %x %y" + bind $data(canvas) <B1-Motion> "tkIconList_Motion1 $w %x %y" + bind $data(canvas) <Double-1> "tkIconList_Double1 $w %x %y" + bind $data(canvas) <ButtonRelease-1> "tkCancelRepeat" + bind $data(canvas) <B1-Leave> "tkIconList_Leave1 $w %x %y" + bind $data(canvas) <B1-Enter> "tkCancelRepeat" + + bind $data(canvas) <Up> "tkIconList_UpDown $w -1" + bind $data(canvas) <Down> "tkIconList_UpDown $w 1" + bind $data(canvas) <Left> "tkIconList_LeftRight $w -1" + bind $data(canvas) <Right> "tkIconList_LeftRight $w 1" + bind $data(canvas) <Return> "tkIconList_ReturnKey $w" + bind $data(canvas) <KeyPress> "tkIconList_KeyPress $w %A" + bind $data(canvas) <Control-KeyPress> ";" + bind $data(canvas) <Alt-KeyPress> ";" + + bind $data(canvas) <FocusIn> "tkIconList_FocusIn $w" + + return $w +} + +# tkIconList_AutoScan -- +# +# This procedure is invoked when the mouse leaves an entry window +# with button 1 down. It scrolls the window up, down, left, or +# right, depending on where the mouse left the window, and reschedules +# itself as an "after" command so that the window continues to scroll until +# the mouse moves back into the window or the mouse button is released. +# +# Arguments: +# w - The IconList window. +# +proc tkIconList_AutoScan {w} { + upvar #0 $w data + global tkPriv + + if {![winfo exists $w]} return + set x $tkPriv(x) + set y $tkPriv(y) + + if $data(noScroll) { + return + } + if {$x >= [winfo width $data(canvas)]} { + $data(canvas) xview scroll 1 units + } elseif {$x < 0} { + $data(canvas) xview scroll -1 units + } elseif {$y >= [winfo height $data(canvas)]} { + # do nothing + } elseif {$y < 0} { + # do nothing + } else { + return + } + + tkIconList_Motion1 $w $x $y + set tkPriv(afterId) [after 50 tkIconList_AutoScan $w] +} + +# Deletes all the items inside the canvas subwidget and reset the IconList's +# state. +# +proc tkIconList_DeleteAll {w} { + upvar #0 $w data + upvar #0 $w:itemList itemList + + $data(canvas) delete all + catch {unset data(selected)} + catch {unset data(rect)} + catch {unset data(list)} + catch {unset itemList} + set data(maxIW) 1 + set data(maxIH) 1 + set data(maxTW) 1 + set data(maxTH) 1 + set data(numItems) 0 + set data(curItem) {} + set data(noScroll) 1 + $data(sbar) set 0.0 1.0 + $data(canvas) xview moveto 0 +} + +# Adds an icon into the IconList with the designated image and text +# +proc tkIconList_Add {w image text} { + upvar #0 $w data + upvar #0 $w:itemList itemList + upvar #0 $w:textList textList + + set iTag [$data(canvas) create image 0 0 -image $image -anchor nw] + set tTag [$data(canvas) create text 0 0 -text $text -anchor nw \ + -font $data(font)] + set rTag [$data(canvas) create rect 0 0 0 0 -fill "" -outline ""] + + set b [$data(canvas) bbox $iTag] + set iW [expr [lindex $b 2]-[lindex $b 0]] + set iH [expr [lindex $b 3]-[lindex $b 1]] + if {$data(maxIW) < $iW} { + set data(maxIW) $iW + } + if {$data(maxIH) < $iH} { + set data(maxIH) $iH + } + + set b [$data(canvas) bbox $tTag] + set tW [expr [lindex $b 2]-[lindex $b 0]] + set tH [expr [lindex $b 3]-[lindex $b 1]] + if {$data(maxTW) < $tW} { + set data(maxTW) $tW + } + if {$data(maxTH) < $tH} { + set data(maxTH) $tH + } + + lappend data(list) [list $iTag $tTag $rTag $iW $iH $tW $tH $data(numItems)] + set itemList($rTag) [list $iTag $tTag $text $data(numItems)] + set textList($data(numItems)) [string tolower $text] + incr data(numItems) +} + +# Places the icons in a column-major arrangement. +# +proc tkIconList_Arrange {w} { + upvar #0 $w data + + if ![info exists data(list)] { + if {[info exists data(canvas)] && [winfo exists $data(canvas)]} { + set data(noScroll) 1 + $data(sbar) config -command "" + } + return + } + + set W [winfo width $data(canvas)] + set H [winfo height $data(canvas)] + set pad [expr [$data(canvas) cget -highlightthickness] + \ + [$data(canvas) cget -bd]] + if {$pad < 2} { + set pad 2 + } + + incr W -[expr $pad*2] + incr H -[expr $pad*2] + + set dx [expr $data(maxIW) + $data(maxTW) + 8] + if {$data(maxTH) > $data(maxIH)} { + set dy $data(maxTH) + } else { + set dy $data(maxIH) + } + incr dy 2 + set shift [expr $data(maxIW) + 4] + + set x [expr $pad * 2] + set y [expr $pad * 1] + set usedColumn 0 + foreach sublist $data(list) { + set usedColumn 1 + set iTag [lindex $sublist 0] + set tTag [lindex $sublist 1] + set rTag [lindex $sublist 2] + set iW [lindex $sublist 3] + set iH [lindex $sublist 4] + set tW [lindex $sublist 5] + set tH [lindex $sublist 6] + + set i_dy [expr ($dy - $iH)/2] + set t_dy [expr ($dy - $tH)/2] + + $data(canvas) coords $iTag $x [expr $y + $i_dy] + $data(canvas) coords $tTag [expr $x + $shift] [expr $y + $t_dy] + $data(canvas) coords $tTag [expr $x + $shift] [expr $y + $t_dy] + $data(canvas) coords $rTag $x $y [expr $x+$dx] [expr $y+$dy] + + incr y $dy + if {[expr $y + $dy] > $H} { + set y [expr $pad * 1] + incr x $dx + set usedColumn 0 + } + } + + if {$usedColumn} { + set sW [expr $x + $dx] + } else { + set sW $x + } + + if {$sW < $W} { + $data(canvas) config -scrollregion "$pad $pad $sW $H" + $data(sbar) config -command "" + $data(canvas) xview moveto 0 + set data(noScroll) 1 + } else { + $data(canvas) config -scrollregion "$pad $pad $sW $H" + $data(sbar) config -command "$data(canvas) xview" + set data(noScroll) 0 + } + + set data(itemsPerColumn) [expr ($H-$pad)/$dy] + if {$data(itemsPerColumn) < 1} { + set data(itemsPerColumn) 1 + } + + if {$data(curItem) != {}} { + tkIconList_Select $w [lindex [lindex $data(list) $data(curItem)] 2] 0 + } +} + +# Gets called when the user invokes the IconList (usually by double-clicking +# or pressing the Return key). +# +proc tkIconList_Invoke {w} { + upvar #0 $w data + + if {[string compare $data(-command) ""] && [info exists data(selected)]} { + eval $data(-command) [list $data(selected)] + } +} + +# tkIconList_See -- +# +# If the item is not (completely) visible, scroll the canvas so that +# it becomes visible. +proc tkIconList_See {w rTag} { + upvar #0 $w data + upvar #0 $w:itemList itemList + + if $data(noScroll) { + return + } + set sRegion [$data(canvas) cget -scrollregion] + if ![string compare $sRegion {}] { + return + } + + if ![info exists itemList($rTag)] { + return + } + + + set bbox [$data(canvas) bbox $rTag] + set pad [expr [$data(canvas) cget -highlightthickness] + \ + [$data(canvas) cget -bd]] + + set x1 [lindex $bbox 0] + set x2 [lindex $bbox 2] + incr x1 -[expr $pad * 2] + incr x2 -[expr $pad * 1] + + set cW [expr [winfo width $data(canvas)] - $pad*2] + + set scrollW [expr [lindex $sRegion 2]-[lindex $sRegion 0]+1] + set dispX [expr int([lindex [$data(canvas) xview] 0]*$scrollW)] + set oldDispX $dispX + + # check if out of the right edge + # + if {[expr $x2 - $dispX] >= $cW} { + set dispX [expr $x2 - $cW] + } + # check if out of the left edge + # + if {[expr $x1 - $dispX] < 0} { + set dispX $x1 + } + + if {$oldDispX != $dispX} { + set fraction [expr double($dispX)/double($scrollW)] + $data(canvas) xview moveto $fraction + } +} + +proc tkIconList_SelectAtXY {w x y} { + upvar #0 $w data + + tkIconList_Select $w [$data(canvas) find closest \ + [$data(canvas) canvasx $x] [$data(canvas) canvasy $y]] +} + +proc tkIconList_Select {w rTag {callBrowse 1}} { + upvar #0 $w data + upvar #0 $w:itemList itemList + + if ![info exists itemList($rTag)] { + return + } + set iTag [lindex $itemList($rTag) 0] + set tTag [lindex $itemList($rTag) 1] + set text [lindex $itemList($rTag) 2] + set serial [lindex $itemList($rTag) 3] + + if ![info exists data(rect)] { + set data(rect) [$data(canvas) create rect 0 0 0 0 \ + -fill #a0a0ff -outline #a0a0ff] + } + $data(canvas) lower $data(rect) + set bbox [$data(canvas) bbox $tTag] + eval $data(canvas) coords $data(rect) $bbox + + set data(curItem) $serial + set data(selected) $text + + if {$callBrowse} { + if [string compare $data(-browsecmd) ""] { + eval $data(-browsecmd) [list $text] + } + } +} + +proc tkIconList_Unselect {w} { + upvar #0 $w data + + if [info exists data(rect)] { + $data(canvas) delete $data(rect) + unset data(rect) + } + if [info exists data(selected)] { + unset data(selected) + } + set data(curItem) {} +} + +# Returns the selected item +# +proc tkIconList_Get {w} { + upvar #0 $w data + + if [info exists data(selected)] { + return $data(selected) + } else { + return "" + } +} + + +proc tkIconList_Btn1 {w x y} { + upvar #0 $w data + + focus $data(canvas) + tkIconList_SelectAtXY $w $x $y +} + +# Gets called on button-1 motions +# +proc tkIconList_Motion1 {w x y} { + global tkPriv + set tkPriv(x) $x + set tkPriv(y) $y + + tkIconList_SelectAtXY $w $x $y +} + +proc tkIconList_Double1 {w x y} { + upvar #0 $w data + + if {$data(curItem) != {}} { + tkIconList_Invoke $w + } +} + +proc tkIconList_ReturnKey {w} { + tkIconList_Invoke $w +} + +proc tkIconList_Leave1 {w x y} { + global tkPriv + + set tkPriv(x) $x + set tkPriv(y) $y + tkIconList_AutoScan $w +} + +proc tkIconList_FocusIn {w} { + upvar #0 $w data + + if ![info exists data(list)] { + return + } + + if {$data(curItem) == {}} { + set rTag [lindex [lindex $data(list) 0] 2] + tkIconList_Select $w $rTag + } +} + +# tkIconList_UpDown -- +# +# Moves the active element up or down by one element +# +# Arguments: +# w - The IconList widget. +# amount - +1 to move down one item, -1 to move back one item. +# +proc tkIconList_UpDown {w amount} { + upvar #0 $w data + + if ![info exists data(list)] { + return + } + + if {$data(curItem) == {}} { + set rTag [lindex [lindex $data(list) 0] 2] + } else { + set oldRTag [lindex [lindex $data(list) $data(curItem)] 2] + set rTag [lindex [lindex $data(list) [expr $data(curItem)+$amount]] 2] + if ![string compare $rTag ""] { + set rTag $oldRTag + } + } + + if [string compare $rTag ""] { + tkIconList_Select $w $rTag + tkIconList_See $w $rTag + } +} + +# tkIconList_LeftRight -- +# +# Moves the active element left or right by one column +# +# Arguments: +# w - The IconList widget. +# amount - +1 to move right one column, -1 to move left one column. +# +proc tkIconList_LeftRight {w amount} { + upvar #0 $w data + + if ![info exists data(list)] { + return + } + if {$data(curItem) == {}} { + set rTag [lindex [lindex $data(list) 0] 2] + } else { + set oldRTag [lindex [lindex $data(list) $data(curItem)] 2] + set newItem [expr $data(curItem)+($amount*$data(itemsPerColumn))] + set rTag [lindex [lindex $data(list) $newItem] 2] + if ![string compare $rTag ""] { + set rTag $oldRTag + } + } + + if [string compare $rTag ""] { + tkIconList_Select $w $rTag + tkIconList_See $w $rTag + } +} + +#---------------------------------------------------------------------- +# Accelerator key bindings +#---------------------------------------------------------------------- + +# tkIconList_KeyPress -- +# +# Gets called when user enters an arbitrary key in the listbox. +# +proc tkIconList_KeyPress {w key} { + global tkPriv + + append tkPriv(ILAccel,$w) $key + tkIconList_Goto $w $tkPriv(ILAccel,$w) + catch { + after cancel $tkPriv(ILAccel,$w,afterId) + } + set tkPriv(ILAccel,$w,afterId) [after 500 tkIconList_Reset $w] +} + +proc tkIconList_Goto {w text} { + upvar #0 $w data + upvar #0 $w:textList textList + global tkPriv + + if ![info exists data(list)] { + return + } + + if {[string length $text] == 0} { + return + } + + if {$data(curItem) == {} || $data(curItem) == 0} { + set start 0 + } else { + set start $data(curItem) + } + + set text [string tolower $text] + set theIndex -1 + set less 0 + set len [string length $text] + set len0 [expr $len-1] + set i $start + + # Search forward until we find a filename whose prefix is an exact match + # with $text + while 1 { + set sub [string range $textList($i) 0 $len0] + if {[string compare $text $sub] == 0} { + set theIndex $i + break + } + incr i + if {$i == $data(numItems)} { + set i 0 + } + if {$i == $start} { + break + } + } + + if {$theIndex > -1} { + set rTag [lindex [lindex $data(list) $theIndex] 2] + tkIconList_Select $w $rTag 0 + tkIconList_See $w $rTag + } +} + +proc tkIconList_Reset {w} { + global tkPriv + + catch {unset tkPriv(ILAccel,$w)} +} + +#---------------------------------------------------------------------- +# +# F I L E D I A L O G +# +#---------------------------------------------------------------------- + +# tkFDialog -- +# +# Implements the TK file selection dialog. This dialog is used when +# the tk_strictMotif flag is set to false. This procedure shouldn't +# be called directly. Call tk_getOpenFile or tk_getSaveFile instead. +# +proc tkFDialog {args} { + global tkPriv + set w __tk_filedialog + upvar #0 $w data + + if ![string compare [lindex [info level 0] 0] tk_getOpenFile] { + set type open + } else { + set type save + } + + tkFDialog_Config $w $type $args + + if {![string compare $data(-parent) .]} { + set w .$w + } else { + set w $data(-parent).$w + } + + # (re)create the dialog box if necessary + # + if {![winfo exists $w]} { + tkFDialog_Create $w + } elseif {[string compare [winfo class $w] TkFDialog]} { + destroy $w + tkFDialog_Create $w + } + wm transient $w $data(-parent) + + # 5. Initialize the file types menu + # + if {$data(-filetypes) != {}} { + $data(typeMenu) delete 0 end + foreach type $data(-filetypes) { + set title [lindex $type 0] + set filter [lindex $type 1] + $data(typeMenu) add command -label $title \ + -command [list tkFDialog_SetFilter $w $type] + } + tkFDialog_SetFilter $w [lindex $data(-filetypes) 0] + $data(typeMenuBtn) config -state normal + $data(typeMenuLab) config -state normal + } else { + set data(filter) "*" + $data(typeMenuBtn) config -state disabled -takefocus 0 + $data(typeMenuLab) config -state disabled + } + + tkFDialog_UpdateWhenIdle $w + + # 6. Withdraw the window, then update all the geometry information + # so we know how big it wants to be, then center the window in the + # display and de-iconify it. + + wm withdraw $w + update idletasks + set x [expr [winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \ + - [winfo vrootx [winfo parent $w]]] + set y [expr [winfo screenheight $w]/2 - [winfo reqheight $w]/2 \ + - [winfo vrooty [winfo parent $w]]] + wm geom $w [winfo reqwidth $w]x[winfo reqheight $w]+$x+$y + wm deiconify $w + wm title $w $data(-title) + + # 7. Set a grab and claim the focus too. + + set oldFocus [focus] + set oldGrab [grab current $w] + if {$oldGrab != ""} { + set grabStatus [grab status $oldGrab] + } + grab $w + focus $data(ent) + $data(ent) delete 0 end + $data(ent) insert 0 $data(selectFile) + $data(ent) select from 0 + $data(ent) select to end + $data(ent) icursor end + + # 8. Wait for the user to respond, then restore the focus and + # return the index of the selected button. Restore the focus + # before deleting the window, since otherwise the window manager + # may take the focus away so we can't redirect it. Finally, + # restore any grab that was in effect. + + tkwait variable tkPriv(selectFilePath) + catch {focus $oldFocus} + grab release $w + wm withdraw $w + if {$oldGrab != ""} { + if {$grabStatus == "global"} { + grab -global $oldGrab + } else { + grab $oldGrab + } + } + return $tkPriv(selectFilePath) +} + +# tkFDialog_Config -- +# +# Configures the TK filedialog according to the argument list +# +proc tkFDialog_Config {w type argList} { + upvar #0 $w data + + set data(type) $type + + # 1: the configuration specs + # + set specs { + {-defaultextension "" "" ""} + {-filetypes "" "" ""} + {-initialdir "" "" ""} + {-initialfile "" "" ""} + {-parent "" "" "."} + {-title "" "" ""} + } + + # 2: default values depending on the type of the dialog + # + if ![info exists data(selectPath)] { + # first time the dialog has been popped up + set data(selectPath) [pwd] + set data(selectFile) "" + } + + # 3: parse the arguments + # + tclParseConfigSpec $w $specs "" $argList + + if ![string compare $data(-title) ""] { + if ![string compare $type "open"] { + set data(-title) "Open" + } else { + set data(-title) "Save As" + } + } + + # 4: set the default directory and selection according to the -initial + # settings + # + if [string compare $data(-initialdir) ""] { + if [file isdirectory $data(-initialdir)] { + set data(selectPath) [glob $data(-initialdir)] + } else { + error "\"$data(-initialdir)\" is not a valid directory" + } + } + set data(selectFile) $data(-initialfile) + + # 5. Parse the -filetypes option + # + set data(-filetypes) [tkFDGetFileTypes $data(-filetypes)] + + if ![winfo exists $data(-parent)] { + error "bad window path name \"$data(-parent)\"" + } +} + +proc tkFDialog_Create {w} { + set dataName [lindex [split $w .] end] + upvar #0 $dataName data + global tk_library + + toplevel $w -class TkFDialog + + # f1: the frame with the directory option menu + # + set f1 [frame $w.f1] + label $f1.lab -text "Directory:" -under 0 + set data(dirMenuBtn) $f1.menu + set data(dirMenu) [tk_optionMenu $f1.menu [format %s(selectPath) $dataName] ""] + set data(upBtn) [button $f1.up] + if ![info exists tkPriv(updirImage)] { + set tkPriv(updirImage) [image create bitmap -data { +#define updir_width 28 +#define updir_height 16 +static char updir_bits[] = { + 0x00, 0x00, 0x00, 0x00, 0x80, 0x1f, 0x00, 0x00, 0x40, 0x20, 0x00, 0x00, + 0x20, 0x40, 0x00, 0x00, 0xf0, 0xff, 0xff, 0x01, 0x10, 0x00, 0x00, 0x01, + 0x10, 0x02, 0x00, 0x01, 0x10, 0x07, 0x00, 0x01, 0x90, 0x0f, 0x00, 0x01, + 0x10, 0x02, 0x00, 0x01, 0x10, 0x02, 0x00, 0x01, 0x10, 0x02, 0x00, 0x01, + 0x10, 0xfe, 0x07, 0x01, 0x10, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00, 0x01, + 0xf0, 0xff, 0xff, 0x01};}] + } + $data(upBtn) config -image $tkPriv(updirImage) + + $f1.menu config -takefocus 1 -highlightthickness 2 + + pack $data(upBtn) -side right -padx 4 -fill both + pack $f1.lab -side left -padx 4 -fill both + pack $f1.menu -expand yes -fill both -padx 4 + + # data(icons): the IconList that list the files and directories. + # + set data(icons) [tkIconList $w.icons \ + -browsecmd "tkFDialog_ListBrowse $w" \ + -command "tkFDialog_ListInvoke $w"] + + # f2: the frame with the OK button and the "file name" field + # + set f2 [frame $w.f2 -bd 0] + label $f2.lab -text "File name:" -anchor e -width 14 -under 5 -pady 0 + set data(ent) [entry $f2.ent] + + # The font to use for the icons. The default Canvas font on Unix + # is just deviant. + global $w.icons + set $w.icons(font) [$data(ent) cget -font] + + # f3: the frame with the cancel button and the file types field + # + set f3 [frame $w.f3 -bd 0] + + # The "File of types:" label needs to be grayed-out when + # -filetypes are not specified. The label widget does not support + # grayed-out text on monochrome displays. Therefore, we have to + # use a button widget to emulate a label widget (by setting its + # bindtags) + + set data(typeMenuLab) [button $f3.lab -text "Files of type:" \ + -anchor e -width 14 -under 9 \ + -bd [$f2.lab cget -bd] \ + -highlightthickness [$f2.lab cget -highlightthickness] \ + -relief [$f2.lab cget -relief] \ + -padx [$f2.lab cget -padx] \ + -pady [$f2.lab cget -pady]] + bindtags $data(typeMenuLab) [list $data(typeMenuLab) Label \ + [winfo toplevel $data(typeMenuLab)] all] + + set data(typeMenuBtn) [menubutton $f3.menu -indicatoron 1 -menu $f3.menu.m] + set data(typeMenu) [menu $data(typeMenuBtn).m -tearoff 0] + $data(typeMenuBtn) config -takefocus 1 -highlightthickness 2 \ + -relief raised -bd 2 -anchor w + + # the okBtn is created after the typeMenu so that the keyboard traversal + # is in the right order + set data(okBtn) [button $f2.ok -text OK -under 0 -width 6 \ + -default active -pady 3] + set data(cancelBtn) [button $f3.cancel -text Cancel -under 0 -width 6\ + -default normal -pady 3] + + # pack the widgets in f2 and f3 + # + pack $data(okBtn) -side right -padx 4 -anchor e + pack $f2.lab -side left -padx 4 + pack $f2.ent -expand yes -fill x -padx 2 -pady 0 + + pack $data(cancelBtn) -side right -padx 4 -anchor w + pack $data(typeMenuLab) -side left -padx 4 + pack $data(typeMenuBtn) -expand yes -fill x -side right + + # Pack all the frames together. We are done with widget construction. + # + pack $f1 -side top -fill x -pady 4 + pack $f3 -side bottom -fill x + pack $f2 -side bottom -fill x + pack $data(icons) -expand yes -fill both -padx 4 -pady 1 + + # Set up the event handlers + # + bind $data(ent) <Return> "tkFDialog_ActivateEnt $w" + + $data(upBtn) config -command "tkFDialog_UpDirCmd $w" + $data(okBtn) config -command "tkFDialog_OkCmd $w" + $data(cancelBtn) config -command "tkFDialog_CancelCmd $w" + + trace variable data(selectPath) w "tkFDialog_SetPath $w" + + bind $w <Alt-d> "focus $data(dirMenuBtn)" + bind $w <Alt-t> [format { + if {"[%s cget -state]" == "normal"} { + focus %s + } + } $data(typeMenuBtn) $data(typeMenuBtn)] + bind $w <Alt-n> "focus $data(ent)" + bind $w <KeyPress-Escape> "tkButtonInvoke $data(cancelBtn)" + bind $w <Alt-c> "tkButtonInvoke $data(cancelBtn)" + bind $w <Alt-o> "tkFDialog_InvokeBtn $w Open" + bind $w <Alt-s> "tkFDialog_InvokeBtn $w Save" + + wm protocol $w WM_DELETE_WINDOW "tkFDialog_CancelCmd $w" + + # Build the focus group for all the entries + # + tkFocusGroup_Create $w + tkFocusGroup_BindIn $w $data(ent) "tkFDialog_EntFocusIn $w" + tkFocusGroup_BindOut $w $data(ent) "tkFDialog_EntFocusOut $w" +} + +# tkFDialog_UpdateWhenIdle -- +# +# Creates an idle event handler which updates the dialog in idle +# time. This is important because loading the directory may take a long +# time and we don't want to load the same directory for multiple times +# due to multiple concurrent events. +# +proc tkFDialog_UpdateWhenIdle {w} { + upvar #0 [winfo name $w] data + + if [info exists data(updateId)] { + return + } else { + set data(updateId) [after idle tkFDialog_Update $w] + } +} + +# tkFDialog_Update -- +# +# Loads the files and directories into the IconList widget. Also +# sets up the directory option menu for quick access to parent +# directories. +# +proc tkFDialog_Update {w} { + set dataName [winfo name $w] + upvar #0 $dataName data + global tk_library tkPriv + + # This proc may be called within an idle handler. Make sure that the + # window has not been destroyed before this proc is called + if {![winfo exists $w] || [string compare [winfo class $w] TkFDialog]} { + return + } else { + catch {unset data(updateId)} + } + + set TRANSPARENT_GIF_COLOR [$w cget -bg] + if ![info exists tkPriv(folderImage)] { + set tkPriv(folderImage) [image create photo -data { +R0lGODlhEAAMAKEAAAD//wAAAPD/gAAAACH5BAEAAAAALAAAAAAQAAwAAAIghINhyycvVFsB +QtmS3rjaH1Hg141WaT5ouprt2HHcUgAAOw==}] + set tkPriv(fileImage) [image create photo -data { +R0lGODlhDAAMAKEAALLA3AAAAP//8wAAACH5BAEAAAAALAAAAAAMAAwAAAIgRI4Ha+IfWHsO +rSASvJTGhnhcV3EJlo3kh53ltF5nAhQAOw==}] + } + set folder $tkPriv(folderImage) + set file $tkPriv(fileImage) + + set appPWD [pwd] + if [catch { + cd $data(selectPath) + }] { + # We cannot change directory to $data(selectPath). $data(selectPath) + # should have been checked before tkFDialog_Update is called, so + # we normally won't come to here. Anyways, give an error and abort + # action. + tk_messageBox -type ok -parent $data(-parent) -message \ + "Cannot change to the directory \"$data(selectPath)\".\nPermission denied."\ + -icon warning + cd $appPWD + return + } + + # Turn on the busy cursor. BUG?? We haven't disabled X events, though, + # so the user may still click and cause havoc ... + # + set entCursor [$data(ent) cget -cursor] + set dlgCursor [$w cget -cursor] + $data(ent) config -cursor watch + $w config -cursor watch + update idletasks + + tkIconList_DeleteAll $data(icons) + + # Make the dir list + # + foreach f [lsort -dictionary [glob -nocomplain .* *]] { + if ![string compare $f .] { + continue + } + if ![string compare $f ..] { + continue + } + if [file isdir ./$f] { + if ![info exists hasDoneDir($f)] { + tkIconList_Add $data(icons) $folder $f + set hasDoneDir($f) 1 + } + } + } + # Make the file list + # + if ![string compare $data(filter) *] { + set files [lsort -dictionary \ + [glob -nocomplain .* *]] + } else { + set files [lsort -dictionary \ + [eval glob -nocomplain $data(filter)]] + } + + set top 0 + foreach f $files { + if ![file isdir ./$f] { + if ![info exists hasDoneFile($f)] { + tkIconList_Add $data(icons) $file $f + set hasDoneFile($f) 1 + } + } + } + + tkIconList_Arrange $data(icons) + + # Update the Directory: option menu + # + set list "" + set dir "" + foreach subdir [file split $data(selectPath)] { + set dir [file join $dir $subdir] + lappend list $dir + } + + $data(dirMenu) delete 0 end + set var [format %s(selectPath) $dataName] + foreach path $list { + $data(dirMenu) add command -label $path -command [list set $var $path] + } + + # Restore the PWD to the application's PWD + # + cd $appPWD + + # turn off the busy cursor. + # + $data(ent) config -cursor $entCursor + $w config -cursor $dlgCursor +} + +# tkFDialog_SetPathSilently -- +# +# Sets data(selectPath) without invoking the trace procedure +# +proc tkFDialog_SetPathSilently {w path} { + upvar #0 [winfo name $w] data + + trace vdelete data(selectPath) w "tkFDialog_SetPath $w" + set data(selectPath) $path + trace variable data(selectPath) w "tkFDialog_SetPath $w" +} + + +# This proc gets called whenever data(selectPath) is set +# +proc tkFDialog_SetPath {w name1 name2 op} { + upvar #0 [winfo name $w] data + tkFDialog_UpdateWhenIdle $w +} + +# This proc gets called whenever data(filter) is set +# +proc tkFDialog_SetFilter {w type} { + upvar #0 [winfo name $w] data + upvar \#0 $data(icons) icons + + set data(filter) [lindex $type 1] + $data(typeMenuBtn) config -text [lindex $type 0] -indicatoron 1 + + $icons(sbar) set 0.0 0.0 + + tkFDialog_UpdateWhenIdle $w +} + +# tkFDialogResolveFile -- +# +# Interpret the user's text input in a file selection dialog. +# Performs: +# +# (1) ~ substitution +# (2) resolve all instances of . and .. +# (3) check for non-existent files/directories +# (4) check for chdir permissions +# +# Arguments: +# context: the current directory you are in +# text: the text entered by the user +# defaultext: the default extension to add to files with no extension +# +# Return vaue: +# [list $flag $directory $file] +# +# flag = OK : valid input +# = PATTERN : valid directory/pattern +# = PATH : the directory does not exist +# = FILE : the directory exists by the file doesn't +# exist +# = CHDIR : Cannot change to the directory +# = ERROR : Invalid entry +# +# directory : valid only if flag = OK or PATTERN or FILE +# file : valid only if flag = OK or PATTERN +# +# directory may not be the same as context, because text may contain +# a subdirectory name +# +proc tkFDialogResolveFile {context text defaultext} { + + set appPWD [pwd] + + set path [tkFDialog_JoinFile $context $text] + + if {[file ext $path] == ""} { + set path "$path$defaultext" + } + + if [catch {file exists $path}] { + return [list ERROR $path ""] + } + + if [catch {if [file exists $path] {}}] { + # This "if" block can be safely removed if the following code returns + # an error. It currently (7/22/97) doesn't + # + # file exists ~nonsuchuser + # + return [list ERROR $path ""] + } + + if [file exists $path] { + if [file isdirectory $path] { + if [catch { + cd $path + }] { + return [list CHDIR $path ""] + } + set directory [pwd] + set file "" + set flag OK + cd $appPWD + } else { + if [catch { + cd [file dirname $path] + }] { + return [list CHDIR [file dirname $path] ""] + } + set directory [pwd] + set file [file tail $path] + set flag OK + cd $appPWD + } + } else { + set dirname [file dirname $path] + if [file exists $dirname] { + if [catch { + cd $dirname + }] { + return [list CHDIR $dirname ""] + } + set directory [pwd] + set file [file tail $path] + if [regexp {[*]|[?]} $file] { + set flag PATTERN + } else { + set flag FILE + } + cd $appPWD + } else { + set directory $dirname + set file [file tail $path] + set flag PATH + } + } + + return [list $flag $directory $file] +} + + +# Gets called when the entry box gets keyboard focus. We clear the selection +# from the icon list . This way the user can be certain that the input in the +# entry box is the selection. +# +proc tkFDialog_EntFocusIn {w} { + upvar #0 [winfo name $w] data + + if [string compare [$data(ent) get] ""] { + $data(ent) selection from 0 + $data(ent) selection to end + $data(ent) icursor end + } else { + $data(ent) selection clear + } + + tkIconList_Unselect $data(icons) + + if ![string compare $data(type) open] { + $data(okBtn) config -text "Open" + } else { + $data(okBtn) config -text "Save" + } +} + +proc tkFDialog_EntFocusOut {w} { + upvar #0 [winfo name $w] data + + $data(ent) selection clear +} + + +# Gets called when user presses Return in the "File name" entry. +# +proc tkFDialog_ActivateEnt {w} { + upvar #0 [winfo name $w] data + + set text [string trim [$data(ent) get]] + set list [tkFDialogResolveFile $data(selectPath) $text \ + $data(-defaultextension)] + set flag [lindex $list 0] + set path [lindex $list 1] + set file [lindex $list 2] + + case $flag { + OK { + if ![string compare $file ""] { + # user has entered an existing (sub)directory + set data(selectPath) $path + $data(ent) delete 0 end + } else { + tkFDialog_SetPathSilently $w $path + set data(selectFile) $file + tkFDialog_Done $w + } + } + PATTERN { + set data(selectPath) $path + set data(filter) $file + } + FILE { + if ![string compare $data(type) open] { + tk_messageBox -icon warning -type ok -parent $data(-parent) \ + -message "File \"[file join $path $file]\" does not exist." + $data(ent) select from 0 + $data(ent) select to end + $data(ent) icursor end + } else { + tkFDialog_SetPathSilently $w $path + set data(selectFile) $file + tkFDialog_Done $w + } + } + PATH { + tk_messageBox -icon warning -type ok -parent $data(-parent) \ + -message "Directory \"$path\" does not exist." + $data(ent) select from 0 + $data(ent) select to end + $data(ent) icursor end + } + CHDIR { + tk_messageBox -type ok -parent $data(-parent) -message \ + "Cannot change to the directory \"$path\".\nPermission denied."\ + -icon warning + $data(ent) select from 0 + $data(ent) select to end + $data(ent) icursor end + } + ERROR { + tk_messageBox -type ok -parent $data(-parent) -message \ + "Invalid file name \"$path\"."\ + -icon warning + $data(ent) select from 0 + $data(ent) select to end + $data(ent) icursor end + } + } +} + +# Gets called when user presses the Alt-s or Alt-o keys. +# +proc tkFDialog_InvokeBtn {w key} { + upvar #0 [winfo name $w] data + + if ![string compare [$data(okBtn) cget -text] $key] { + tkButtonInvoke $data(okBtn) + } +} + +# Gets called when user presses the "parent directory" button +# +proc tkFDialog_UpDirCmd {w} { + upvar #0 [winfo name $w] data + + if [string compare $data(selectPath) "/"] { + set data(selectPath) [file dirname $data(selectPath)] + } +} + +# Join a file name to a path name. The "file join" command will break +# if the filename begins with ~ +# +proc tkFDialog_JoinFile {path file} { + if {[string match {~*} $file] && [file exists $path/$file]} { + return [file join $path ./$file] + } else { + return [file join $path $file] + } +} + + + +# Gets called when user presses the "OK" button +# +proc tkFDialog_OkCmd {w} { + upvar #0 [winfo name $w] data + + set text [tkIconList_Get $data(icons)] + if [string compare $text ""] { + set file [tkFDialog_JoinFile $data(selectPath) $text] + if [file isdirectory $file] { + tkFDialog_ListInvoke $w $text + return + } + } + + tkFDialog_ActivateEnt $w +} + +# Gets called when user presses the "Cancel" button +# +proc tkFDialog_CancelCmd {w} { + upvar #0 [winfo name $w] data + global tkPriv + + set tkPriv(selectFilePath) "" +} + +# Gets called when user browses the IconList widget (dragging mouse, arrow +# keys, etc) +# +proc tkFDialog_ListBrowse {w text} { + upvar #0 [winfo name $w] data + + if {$text == ""} { + return + } + + set file [tkFDialog_JoinFile $data(selectPath) $text] + if ![file isdirectory $file] { + $data(ent) delete 0 end + $data(ent) insert 0 $text + + if ![string compare $data(type) open] { + $data(okBtn) config -text "Open" + } else { + $data(okBtn) config -text "Save" + } + } else { + $data(okBtn) config -text "Open" + } +} + +# Gets called when user invokes the IconList widget (double-click, +# Return key, etc) +# +proc tkFDialog_ListInvoke {w text} { + upvar #0 [winfo name $w] data + + if {$text == ""} { + return + } + + set file [tkFDialog_JoinFile $data(selectPath) $text] + + if [file isdirectory $file] { + set appPWD [pwd] + if [catch {cd $file}] { + tk_messageBox -type ok -parent $data(-parent) -message \ + "Cannot change to the directory \"$file\".\nPermission denied."\ + -icon warning + } else { + cd $appPWD + set data(selectPath) $file + } + } else { + set data(selectFile) $file + tkFDialog_Done $w + } +} + +# tkFDialog_Done -- +# +# Gets called when user has input a valid filename. Pops up a +# dialog box to confirm selection when necessary. Sets the +# tkPriv(selectFilePath) variable, which will break the "tkwait" +# loop in tkFDialog and return the selected filename to the +# script that calls tk_getOpenFile or tk_getSaveFile +# +proc tkFDialog_Done {w {selectFilePath ""}} { + upvar #0 [winfo name $w] data + global tkPriv + + if ![string compare $selectFilePath ""] { + set selectFilePath [tkFDialog_JoinFile $data(selectPath) \ + $data(selectFile)] + set tkPriv(selectFile) $data(selectFile) + set tkPriv(selectPath) $data(selectPath) + + if {[file exists $selectFilePath] && + ![string compare $data(type) save]} { + + set reply [tk_messageBox -icon warning -type yesno -parent $data(-parent) \ + -message "File \"$selectFilePath\" already exists.\nDo you want to overwrite it?"] + if ![string compare $reply "no"] { + return + } + } + } + set tkPriv(selectFilePath) $selectFilePath +} + diff --git a/library/xmfbox.tcl b/library/xmfbox.tcl new file mode 100644 index 0000000..52f8b33 --- /dev/null +++ b/library/xmfbox.tcl @@ -0,0 +1,635 @@ +# xmfbox.tcl -- +# +# Implements the "Motif" style file selection dialog for the +# Unix platform. This implementation is used only if the +# "tk_strictMotif" flag is set. +# +# SCCS: @(#) xmfbox.tcl 1.6 97/10/01 15:06:07 +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + + +# tkMotifFDialog -- +# +# Implements a file dialog similar to the standard Motif file +# selection box. +# +# Return value: +# +# A list of two members. The first member is the absolute +# pathname of the selected file or "" if user hits cancel. The +# second member is the name of the selected file type, or "" +# which stands for "default file type" +# +proc tkMotifFDialog {args} { + global tkPriv + set w __tk_filedialog + upvar #0 $w data + + if ![string compare [lindex [info level 0] 0] tk_getOpenFile] { + set type open + } else { + set type save + } + + tkMotifFDialog_Config $w $type $args + + if {![string compare $data(-parent) .]} { + set w .$w + } else { + set w $data(-parent).$w + } + + # (re)create the dialog box if necessary + # + if {![winfo exists $w]} { + tkMotifFDialog_Create $w + } elseif {[string compare [winfo class $w] TkMotifFDialog]} { + destroy $w + tkMotifFDialog_Create $w + } + wm transient $w $data(-parent) + + tkMotifFDialog_Update $w + + # 5. Withdraw the window, then update all the geometry information + # so we know how big it wants to be, then center the window in the + # display and de-iconify it. + + wm withdraw $w + update idletasks + set x [expr [winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \ + - [winfo vrootx [winfo parent $w]]] + set y [expr [winfo screenheight $w]/2 - [winfo reqheight $w]/2 \ + - [winfo vrooty [winfo parent $w]]] + wm geom $w +$x+$y + wm deiconify $w + wm title $w $data(-title) + + # 6. Set a grab and claim the focus too. + + set oldFocus [focus] + set oldGrab [grab current $w] + if {$oldGrab != ""} { + set grabStatus [grab status $oldGrab] + } + grab $w + focus $data(sEnt) + $data(sEnt) select from 0 + $data(sEnt) select to end + + # 7. Wait for the user to respond, then restore the focus and + # return the index of the selected button. Restore the focus + # before deleting the window, since otherwise the window manager + # may take the focus away so we can't redirect it. Finally, + # restore any grab that was in effect. + + tkwait variable tkPriv(selectFilePath) + catch {focus $oldFocus} + grab release $w + wm withdraw $w + if {$oldGrab != ""} { + if {$grabStatus == "global"} { + grab -global $oldGrab + } else { + grab $oldGrab + } + } + return $tkPriv(selectFilePath) +} + +proc tkMotifFDialog_Config {w type argList} { + upvar #0 $w data + + set data(type) $type + + # 1: the configuration specs + # + set specs { + {-defaultextension "" "" ""} + {-filetypes "" "" ""} + {-initialdir "" "" ""} + {-initialfile "" "" ""} + {-parent "" "" "."} + {-title "" "" ""} + } + + # 2: default values depending on the type of the dialog + # + if ![info exists data(selectPath)] { + # first time the dialog has been popped up + set data(selectPath) [pwd] + set data(selectFile) "" + } + + # 3: parse the arguments + # + tclParseConfigSpec $w $specs "" $argList + + if ![string compare $data(-title) ""] { + if ![string compare $type "open"] { + set data(-title) "Open" + } else { + set data(-title) "Save As" + } + } + + # 4: set the default directory and selection according to the -initial + # settings + # + if [string compare $data(-initialdir) ""] { + if [file isdirectory $data(-initialdir)] { + set data(selectPath) [glob $data(-initialdir)] + } else { + error "\"$data(-initialdir)\" is not a valid directory" + } + } + set data(selectFile) $data(-initialfile) + + # 5. Parse the -filetypes option. It is not used by the motif + # file dialog, but we check for validity of the value to make sure + # the application code also runs fine with the TK file dialog. + # + set data(-filetypes) [tkFDGetFileTypes $data(-filetypes)] + + if ![info exists data(filter)] { + set data(filter) * + } + if ![winfo exists $data(-parent)] { + error "bad window path name \"$data(-parent)\"" + } +} + +proc tkMotifFDialog_Create {w} { + set dataName [lindex [split $w .] end] + upvar #0 $dataName data + + # 1: Create the dialog ... + # + toplevel $w -class TkMotifFDialog + set top [frame $w.top -relief raised -bd 1] + set bot [frame $w.bot -relief raised -bd 1] + + pack $w.bot -side bottom -fill x + pack $w.top -side top -expand yes -fill both + + set f1 [frame $top.f1] + set f2 [frame $top.f2] + set f3 [frame $top.f3] + + pack $f1 -side top -fill x + pack $f3 -side bottom -fill x + pack $f2 -expand yes -fill both + + set f2a [frame $f2.a] + set f2b [frame $f2.b] + + grid $f2a -row 0 -column 0 -rowspan 1 -columnspan 1 -padx 4 -pady 4 \ + -sticky news + grid $f2b -row 0 -column 1 -rowspan 1 -columnspan 1 -padx 4 -pady 4 \ + -sticky news + grid rowconfig $f2 0 -minsize 0 -weight 1 + grid columnconfig $f2 0 -minsize 0 -weight 1 + grid columnconfig $f2 1 -minsize 150 -weight 2 + + # The Filter box + # + label $f1.lab -text "Filter:" -under 3 -anchor w + entry $f1.ent + pack $f1.lab -side top -fill x -padx 6 -pady 4 + pack $f1.ent -side top -fill x -padx 4 -pady 0 + set data(fEnt) $f1.ent + + # The file and directory lists + # + set data(dList) [tkMotifFDialog_MakeSList $w $f2a Directory: 0 DList] + set data(fList) [tkMotifFDialog_MakeSList $w $f2b Files: 2 FList] + + # The Selection box + # + label $f3.lab -text "Selection:" -under 0 -anchor w + entry $f3.ent + pack $f3.lab -side top -fill x -padx 6 -pady 0 + pack $f3.ent -side top -fill x -padx 4 -pady 4 + set data(sEnt) $f3.ent + + # The buttons + # + set data(okBtn) [button $bot.ok -text OK -width 6 -under 0 \ + -command "tkMotifFDialog_OkCmd $w"] + set data(filterBtn) [button $bot.filter -text Filter -width 6 -under 0 \ + -command "tkMotifFDialog_FilterCmd $w"] + set data(cancelBtn) [button $bot.cancel -text Cancel -width 6 -under 0 \ + -command "tkMotifFDialog_CancelCmd $w"] + + pack $bot.ok $bot.filter $bot.cancel -padx 10 -pady 10 -expand yes \ + -side left + + # Create the bindings: + # + bind $w <Alt-t> "focus $data(fEnt)" + bind $w <Alt-d> "focus $data(dList)" + bind $w <Alt-l> "focus $data(fList)" + bind $w <Alt-s> "focus $data(sEnt)" + + bind $w <Alt-o> "tkButtonInvoke $bot.ok " + bind $w <Alt-f> "tkButtonInvoke $bot.filter" + bind $w <Alt-c> "tkButtonInvoke $bot.cancel" + + bind $data(fEnt) <Return> "tkMotifFDialog_ActivateFEnt $w" + bind $data(sEnt) <Return> "tkMotifFDialog_ActivateSEnt $w" + + wm protocol $w WM_DELETE_WINDOW "tkMotifFDialog_CancelCmd $w" +} + +proc tkMotifFDialog_MakeSList {w f label under cmd} { + label $f.lab -text $label -under $under -anchor w + listbox $f.l -width 12 -height 5 -selectmode browse -exportselection 0\ + -xscrollcommand "$f.h set" \ + -yscrollcommand "$f.v set" + scrollbar $f.v -orient vertical -takefocus 0 \ + -command "$f.l yview" + scrollbar $f.h -orient horizontal -takefocus 0 \ + -command "$f.l xview" + grid $f.lab -row 0 -column 0 -sticky news -rowspan 1 -columnspan 2 \ + -padx 2 -pady 2 + grid $f.l -row 1 -column 0 -rowspan 1 -columnspan 1 -sticky news + grid $f.v -row 1 -column 1 -rowspan 1 -columnspan 1 -sticky news + grid $f.h -row 2 -column 0 -rowspan 1 -columnspan 1 -sticky news + + grid rowconfig $f 0 -weight 0 -minsize 0 + grid rowconfig $f 1 -weight 1 -minsize 0 + grid columnconfig $f 0 -weight 1 -minsize 0 + + # bindings for the listboxes + # + set list $f.l + bind $list <Up> "tkMotifFDialog_Browse$cmd $w" + bind $list <Down> "tkMotifFDialog_Browse$cmd $w" + bind $list <space> "tkMotifFDialog_Browse$cmd $w" + bind $list <1> "tkMotifFDialog_Browse$cmd $w" + bind $list <B1-Motion> "tkMotifFDialog_Browse$cmd $w" + bind $list <Double-1> "tkMotifFDialog_Activate$cmd $w" + bind $list <Return> "tkMotifFDialog_Browse$cmd $w; tkMotifFDialog_Activate$cmd $w" + + bindtags $list "Listbox $list [winfo toplevel $list] all" + tkListBoxKeyAccel_Set $list + + return $f.l +} + +proc tkMotifFDialog_BrowseDList {w} { + upvar #0 [winfo name $w] data + + focus $data(dList) + if ![string compare [$data(dList) curselection] ""] { + return + } + set subdir [$data(dList) get [$data(dList) curselection]] + if ![string compare $subdir ""] { + return + } + + $data(fList) selection clear 0 end + + set list [tkMotifFDialog_InterpFilter $w] + set data(filter) [lindex $list 1] + + case $subdir { + . { + set newSpec [file join $data(selectPath) $data(filter)] + } + .. { + set newSpec [file join [file dirname $data(selectPath)] \ + $data(filter)] + } + default { + set newSpec [file join $data(selectPath) $subdir $data(filter)] + } + } + + $data(fEnt) delete 0 end + $data(fEnt) insert 0 $newSpec +} + +proc tkMotifFDialog_ActivateDList {w} { + upvar #0 [winfo name $w] data + + if ![string compare [$data(dList) curselection] ""] { + return + } + set subdir [$data(dList) get [$data(dList) curselection]] + if ![string compare $subdir ""] { + return + } + + $data(fList) selection clear 0 end + + case $subdir { + . { + set newDir $data(selectPath) + } + .. { + set newDir [file dirname $data(selectPath)] + } + default { + set newDir [file join $data(selectPath) $subdir] + } + } + + set data(selectPath) $newDir + tkMotifFDialog_Update $w + + if [string compare $subdir ..] { + $data(dList) selection set 0 + $data(dList) activate 0 + } else { + $data(dList) selection set 1 + $data(dList) activate 1 + } +} + +proc tkMotifFDialog_BrowseFList {w} { + upvar #0 [winfo name $w] data + + focus $data(fList) + if ![string compare [$data(fList) curselection] ""] { + return + } + set data(selectFile) [$data(fList) get [$data(fList) curselection]] + if ![string compare $data(selectFile) ""] { + return + } + + $data(dList) selection clear 0 end + + $data(fEnt) delete 0 end + $data(fEnt) insert 0 [file join $data(selectPath) $data(filter)] + $data(fEnt) xview end + + $data(sEnt) delete 0 end + $data(sEnt) insert 0 [file join $data(selectPath) $data(selectFile)] + $data(sEnt) xview end +} + +proc tkMotifFDialog_ActivateFList {w} { + upvar #0 [winfo name $w] data + + if ![string compare [$data(fList) curselection] ""] { + return + } + set data(selectFile) [$data(fList) get [$data(fList) curselection]] + if ![string compare $data(selectFile) ""] { + return + } else { + tkMotifFDialog_ActivateSEnt $w + } +} + +proc tkMotifFDialog_ActivateFEnt {w} { + upvar #0 [winfo name $w] data + + set list [tkMotifFDialog_InterpFilter $w] + set data(selectPath) [lindex $list 0] + set data(filter) [lindex $list 1] + + tkMotifFDialog_Update $w +} + +proc tkMotifFDialog_InterpFilter {w} { + upvar #0 [winfo name $w] data + + set text [string trim [$data(fEnt) get]] + # Perform tilde substitution + # + if ![string compare [string index $text 0] ~] { + set list [file split $text] + set tilde [lindex $list 0] + catch { + set tilde [glob $tilde] + } + set text [eval file join [concat $tilde [lrange $list 1 end]]] + } + + set resolved [file join [file dirname $text] [file tail $text]] + + if [file isdirectory $resolved] { + set dir $resolved + set fil $data(filter) + } else { + set dir [file dirname $resolved] + set fil [file tail $resolved] + } + + return [list $dir $fil] +} + + +proc tkMotifFDialog_ActivateSEnt {w} { + global tkPriv + upvar #0 [winfo name $w] data + + set selectFilePath [string trim [$data(sEnt) get]] + set selectFile [file tail $selectFilePath] + set selectPath [file dirname $selectFilePath] + + + if {![string compare $selectFilePath ""]} { + tkMotifFDialog_FilterCmd $w + return + } + + if {[file isdirectory $selectFilePath]} { + set data(selectPath) [glob $selectFilePath] + set data(selectFile) "" + tkMotifFDialog_Update $w + return + } + + if [string compare [file pathtype $selectFilePath] "absolute"] { + tk_messageBox -icon warning -type ok \ + -message "\"$selectFilePath\" must be an absolute pathname" + return + } + + if ![file exists $selectPath] { + tk_messageBox -icon warning -type ok \ + -message "Directory \"$selectPath\" does not exist." + return + } + + if ![file exists $selectFilePath] { + if ![string compare $data(type) open] { + tk_messageBox -icon warning -type ok \ + -message "File \"$selectFilePath\" does not exist." + return + } + } else { + if ![string compare $data(type) save] { + set message [format %s%s \ + "File \"$selectFilePath\" already exists.\n\n" \ + "Replace existing file?"] + set answer [tk_messageBox -icon warning -type yesno \ + -message $message] + if ![string compare $answer "no"] { + return + } + } + } + + set tkPriv(selectFilePath) $selectFilePath + set tkPriv(selectFile) $selectFile + set tkPriv(selectPath) $selectPath +} + + +proc tkMotifFDialog_OkCmd {w} { + upvar #0 [winfo name $w] data + + tkMotifFDialog_ActivateSEnt $w +} + +proc tkMotifFDialog_FilterCmd {w} { + upvar #0 [winfo name $w] data + + tkMotifFDialog_ActivateFEnt $w +} + +proc tkMotifFDialog_CancelCmd {w} { + global tkPriv + + set tkPriv(selectFilePath) "" + set tkPriv(selectFile) "" + set tkPriv(selectPath) "" +} + +# tkMotifFDialog_Update +# +# Load the files and synchronize the "filter" and "selection" fields +# boxes. +# +# popup: +# If this is true, then update the selection field according to the +# "-selection" flag +# +proc tkMotifFDialog_Update {w} { + upvar #0 [winfo name $w] data + + $data(fEnt) delete 0 end + $data(fEnt) insert 0 [file join $data(selectPath) $data(filter)] + $data(sEnt) delete 0 end + $data(sEnt) insert 0 [file join $data(selectPath) $data(selectFile)] + + tkMotifFDialog_LoadFiles $w +} + +proc tkMotifFDialog_LoadFiles {w} { + upvar #0 [winfo name $w] data + + $data(dList) delete 0 end + $data(fList) delete 0 end + + set appPWD [pwd] + if [catch { + cd $data(selectPath) + }] { + cd $appPWD + + $data(dList) insert end ".." + return + } + + # Make the dir list + # + foreach f [lsort -command tclSortNoCase [glob -nocomplain .* *]] { + if [file isdir $f] { + $data(dList) insert end $f + } + } + # Make the file list + # + if ![string compare $data(filter) *] { + set files [lsort -command tclSortNoCase [glob -nocomplain .* *]] + } else { + set files [lsort -command tclSortNoCase \ + [glob -nocomplain $data(filter)]] + } + + set top 0 + foreach f $files { + if ![file isdir $f] { + $data(fList) insert end $f + if [string match .* $f] { + incr top + } + } + } + + # The user probably doesn't want to see the . files. We adjust the view + # so that the listbox displays all the non-dot files + $data(fList) yview $top + + cd $appPWD +} + +proc tkListBoxKeyAccel_Set {w} { + bind Listbox <Any-KeyPress> "" + bind $w <Destroy> "tkListBoxKeyAccel_Unset $w" + bind $w <Any-KeyPress> "tkListBoxKeyAccel_Key $w %A" +} + +proc tkListBoxKeyAccel_Unset {w} { + global tkPriv + + catch {after cancel $tkPriv(lbAccel,$w,afterId)} + catch {unset tkPriv(lbAccel,$w)} + catch {unset tkPriv(lbAccel,$w,afterId)} +} + +proc tkListBoxKeyAccel_Key {w key} { + global tkPriv + + append tkPriv(lbAccel,$w) $key + tkListBoxKeyAccel_Goto $w $tkPriv(lbAccel,$w) + catch { + after cancel $tkPriv(lbAccel,$w,afterId) + } + set tkPriv(lbAccel,$w,afterId) [after 500 tkListBoxKeyAccel_Reset $w] +} + +proc tkListBoxKeyAccel_Goto {w string} { + global tkPriv + + set string [string tolower $string] + set end [$w index end] + set theIndex -1 + + for {set i 0} {$i < $end} {incr i} { + set item [string tolower [$w get $i]] + if {[string compare $string $item] >= 0} { + set theIndex $i + } + if {[string compare $string $item] <= 0} { + set theIndex $i + break + } + } + + if {$theIndex >= 0} { + $w selection clear 0 end + $w selection set $theIndex $theIndex + $w activate $theIndex + $w see $theIndex + } +} + +proc tkListBoxKeyAccel_Reset {w} { + global tkPriv + + catch {unset tkPriv(lbAccel,$w)} +} + diff --git a/mac/MW_TkHeader.pch b/mac/MW_TkHeader.pch new file mode 100644 index 0000000..7b7e2a4 --- /dev/null +++ b/mac/MW_TkHeader.pch @@ -0,0 +1,129 @@ +/* + * MW_TkHeader.pch -- + * + * This file is the source for a pre-compilied header that gets used + * for all files in the Tk projects. This make compilies go a bit + * faster. This file is only intended to be used in the MetroWerks + * CodeWarrior environment. It essentially acts as a place to set + * compiler flags. See MetroWerks documention for more details. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) MW_TkHeader.pch 1.26 97/11/20 19:37:29 + */ + +/* + * To use the compilied header you need to set the "Prefix file" in + * the "C/C++ Language" preference panel to point to the created + * compilied header. The name of the header depends on the + * architecture we are compiling for (see the code below). For + * example, for a 68k app the prefix file should be: MW_TclHeader68K. + */ + +#if __POWERPC__ +#pragma precompile_target "MW_TkHeaderPPC" +#elif __CFM68K__ +#pragma precompile_target "MW_TkHeaderCFM68K" +#else +#pragma precompile_target "MW_TkHeader68K" +#endif + +/* + * Macintosh Tcl must be compiled with certain compiler options to + * ensure that it will work correctly. The following pragmas are + * used to ensure that those options are set correctly. An error + * will occur at compile time if they are not set correctly. + */ + +#if !__option(enumsalwaysint) +#error Tcl requires the Metrowerks setting "Enums always ints". +#endif + +#if !defined(__POWERPC__) +#if !__option(far_data) +#error Tcl requires the Metrowerks setting "Far data". +#endif +#endif + +#if !defined(__POWERPC__) +#if !__option(fourbyteints) +#error Tcl requires the Metrowerks setting "4 byte ints". +#endif +#endif + +#if !defined(__POWERPC__) +#if !__option(IEEEdoubles) +#error Tcl requires the Metrowerks setting "8 byte doubles". +#endif +#endif + +/* + * The define is used most everywhere to tell Tk (or any Tk + * extensions) that we are compiling for the Macintosh platform. + */ +#define MAC_TCL + +/* + * The following defines are for the Xlib.h file to force + * it to generate prototypes in the way we need it. This is + * defined here in case X.h & company are ever included before + * tk.h. + */ + +#define NeedFunctionPrototypes 1 +#define NeedWidePrototypes 0 + +/* + * The following defines control the behavior of the Macintosh + * Universial Headers. + */ + +#define SystemSevenOrLater 1 +#define STRICT_CONTROLS 0 +#define STRICT_WINDOWS 0 + +/* + * The appearance manager has not yet been shiped by Apple (10/29/97). + * It's currently in beta testing which is why we were able to write + * some code that depends on it. If you have access to the appearance + * manager you can define the symbol HAVE_APPEARANCE below to compile + * the code that uses the new appearance manager. + */ + +/* #define HAVE_APPEARANCE 1 */ + +/* + * Define the following symbol if you want + * comprehensive debugging turned on. + */ + +/* #define TCL_DEBUG */ + +#ifdef TCL_DEBUG +# define TCL_MEM_DEBUG +# define TK_TEST +# define TCL_TEST +#endif + +/* + * Apple's Universal Headers 2.0 & 3.0 change alot of names and constants. + * We will switch to the new names as soon as we can be reasonably sure the + * number of people with older versions of CodeWarrior, who will then not be + * able to build Tcl/Tk, is negligible. + */ + +#define OLDROUTINENAMES 1 + +/* + * Place any includes below that will are needed by the majority of the + * and is OK to be in any file in the system. + */ + +#include <tcl.h> +#pragma export on +#include "tk.h" +#include "tkInt.h" +#pragma export off diff --git a/mac/README b/mac/README new file mode 100644 index 0000000..3c8824a --- /dev/null +++ b/mac/README @@ -0,0 +1,299 @@ +Tk 8.0 for Macintosh + +by Ray Johnson +Sun Microsystems Laboratories +rjohnson@eng.sun.com + +SCCS: @(#) README 1.30 97/11/20 22:06:57 + +1. Introduction +--------------- + +This is the README file for the Macintosh version of the Tk +extension for the Tcl scripting language. The file consists of +information specific to the Macintosh version of Tcl and Tk. For more +general information please read the README file in the main Tk +directory. + +2. What's new? +------------- + +Native Look & Feel!!! We now try really hard to support the +Macintosh Look & Feel with Tcl/Tk 8.0. We aren't finished but +it look pretty good. Let me know what are the most "un-mac like" +problems and I'll fix them as quickly as I can. + +The button, checkbutton, radiobutton, and scrollbar widgets actually +use the Mac toolbox controls. This means that they will track the +look&feel if you use extension that change the appearance of +applications (like Aaron.) We also use "system" colors so the default +backgrounds etc. will also change colors. We plan to support this +feature - so let me know if something doesn't work quite right. +Unfortunantly, we are not able to change the colors of buttons under +MacOS 8. We are working on a solution to this. +In the meantime, if you really must have colored buttons, turn off the +"System-wide platinum appearance" option in the Appearance Control Panel, +and you will get the System 7, colorable, buttons back. + +We also now support native menus! By using the new -menu option +on toplevels you can have a menubar that is cross platform. You +can also place Tk menus in the Apple and Help menus! Check out +the documentation for more details. Syd Polk <icepick@eng.sun.com> is +the author of the new menu code. Feel free to contact him if you +have questions or comments about the menu mechanism. + +The "tk_messageBox" command on the Macintosh is now much more +mac-like. I'll probably still need to adjust this more - but it +looks a hell of alot better than it did before. + +I've also added a command that allows you to get more native window +styles. However, we have yet to decide on a cross platform solution +to the problem of varying window styles. None the less, I thought +it would be use full to add the capability in an unsupported means +to tide you over until a better solution is available. The command +is called "unsupported1". It can be used in the following way: + + toplevel .foo; unsupported1 style .foo zoomDocProc + +The above command will create a document window with a zoom box. +Type "unsupported1 style . ???" to get a list of the supported +styles. The command works like "wm overrideredirect" - you must +make the call before the window is mapped. + +As always - report the bugs you find - including asthetic ones +in the look & feel of widgets. + +3. Mac specific features +------------------------ + +There are several features or enhancements in Tk that are unique to +the Macintosh version of Tk. Here is a list of those features and +pointers to where you can find more information about the feature. + +* The menu command has special rules for accessing the Macintosh + Apple and Help menus. See the menu.m man page for details. + +* If you have the special Tcl function "tkAboutDialog" defined, it + will be called instead of displaying the default About Box in the + console or other parts of the Wish application. See below for + details. + +* In addition to the standard X cursors, the Mac version of Tk will + let you use any Mac cursor that is named and installed in your + application. See the GetCursor.3 man page for details. + +* The wish application has a couple of hooks to know about the exit, + "open document" and "Do Script" Mac High Level events. + See below for details. + +* The command unsupported1 will allow you to set the style of new + toplevel windows on the Macintosh. It is not really supported. + See below for details. + +* In addition to the standard built-in bitmaps that Tk supports, the + Mac version of Tk allows you to use several Mac specific icons. See + the GetBitmap.3 man page for a complete list. + +* The send command does not yet work on the Macintosh. We hope to + have it available in Tk 8.1. + +* The -use and -container options almost work. The focus bugs that + were in Tk8.0 final have been fixed. But there are still some + known bugs that cause some major problems. Be careful, if you + decide to use these features. (See bugs.doc for details.) + +4. The Distribution +------------------- + +Macintosh Tk is distributed in three different forms. This +should make it easier to only download what you need. The +packages are as follows: + +mactk8.0.sea.hqx + + This distribution is a "binary" only release. It contains an + installer program that will install a 68k, PowerPC, or Fat + version of the "Wish" application. In addition, in installs + the Tcl & Tk libraries in the Extensions folder inside your + System Folder. (No "INIT"'s or Control Pannels are installed.) + +mactcltk-full-8.0.sea.hqx + + This release contains the full release of Tcl and Tk for the + Macintosh plus the More Files package on which Macintosh Tcl and + Tk rely. + +mactk-source-8.0.sea.hqx + + This release contains the complete source to Tk for the Macintosh + In addition, Metrowerks CodeWarrior libraries and project files + are included. However, you must already have the More Files + package to compile this code. + +5. Documentation +---------------- + +Two books are currently available for Tcl. Both provide a good +introduction to the language. It is a good way to get started +if you haven't used the language before: + + Title: Tcl and the Tk Toolkit + Author: John K. Ousterhout + Publisher: Addison-Wesley + ISBN: 0-201-63337-X + + Title: Practical Programming in Tcl and Tk + Author: Brent Welch + Publisher: Prentice Hall + ISBN: 0-13-182007-9 + +The "doc" subdirectory contains reference in documentation +in the "man" format found on most UNIX machines. Unfortunately, +there is not a suitable way to view these pages on the Macintosh. +A version suitable for viewing on the Macintosh has yet to be +developed. We are working are having better documentation for +the Macintosh platform in the future. However, if you have WWW +access you may access the Man pages at the following URL: + + http://sunscript.sun.com/man/tcl8.0/contents.html + +Other documentation and sample Tcl scripts can be found at +the Tcl ftp site: + + ftp://ftp.neosoft.com/tcl/ + +The internet news group comp.lang.tcl is also a valuable +source of information about Tcl. A mailing list is also +available (see below). + +6. Compiling Tk +--------------- + +In order to compile Macintosh Tk you must have the +following items: + + CodeWarrior Pro 1 or higher (CodeWarrior release 9 or higher can work + and we have project files, but we are depricating support) + Mac Tcl 8.0 (source) + (which requires More Files 1.4.2 or 1.4.3) + Mac Tk 8.0 (source) + +The project files included with the Mac Tcl source should work +fine. The only thing you may need to update are the access paths. +As with Tcl, there is something in the initial release of the CW Pro 2 +linker that rendersthe CFM68K version of Wish very unstable. I am +working with Metrowerks to resolve the issue. + +Special notes: + +* Check out the file bugs.doc for information about known bugs. + +* We are starting to support the new Appearance Manager that shipped + with MacOS 8. At this point, the only feature that we are using is + the API to Iconify windows (so that wm iconify will work). However, + as of the release of Tk8.0p1, the SDK from Apple is still in Beta, so + we cannot ship it. So support for the Appearance Manager is turned off + in the source version of Tk8.0p1. + If you want to build Tk, and want to get the Appearance Manager features, + then need to do the following: + 1) get the SDK from Apple + 2) Uncomment the #define HAVE_APPEARANCE line in tk8.0:mac:MW_TkHeader.pch + 3) Add the Appearance.lib to tk8.0:mac:TkShells.¼, and put the include + directory of the SDK on your path in this project, and TkLibraries.¼. + +7. About Dialog +--------------- + +There is now a way to replace the default dialog box for the Wish +application. If you create the tcl procedure "tkAboutDialog" it will +be called instead of creating the default dialog box. Your procedure +is then responsible for displaying a window, removing it, etc. This +interface is experimental and may change in the future - tell me what +you think of it. + +8. Apple Events +--------------- + +Tcl/Tk currently doesn't have much in the way of support for Mac +Apple Events. There is no way to send an apple event (although you +could write an extension to do this) and no general purpose way to +recieve apple events. However, there are a couple of hooks for +dealing with some of the standard apple events. + + exit - Generally, Tcl cleans up after it self when you exit. + However, your application may want to do application specifc + cleanup like saving a users data. To do this you can rename + the exit command to something else. Define your own exit + command to do whatever clean up you like and then call the + origional exit command. For example, + + rename exit __exit + proc exit {} { + # Do your clean up hear + __exit + } + + Both incoming quit events and hitting the Quit menu item + will call the exit command. However, don't expect you can + abort the exit. Tk may exit anyway if the exit command it + calls does not actually quit the application. + + open - The other apple event Tk supports is the open event. The + open event is sent to Tk if, for example, you drop a file on + the Wish icon. If you define a Tcl procedure with the name + "tkOpenDocument" it will be invoked on any Open Document + events that the application receives. The a list of paths to + the various documents will be passed to the Tcl function. + Here is an example, + + proc tkOpenDocument args { + foreach file $args { + # Deal with passed in file path + } + } + + Note: This isn't every thing you need to do to make your + application dropable. You must still define a FREF resource + that makes sense for your application domain. (Out of the + box, you will not be able to drop files on the Wish + application. See the Inside Macintosh documentation for + details about the FREF resource. + + do script - This is a way for external applications to drive MacTk, or + to recieve information from it. From AppleScript, you can say: + + tell application "Wish8.0" + do script "console hide + pack [button .b1 -text {Hello world} -command exit]" + end tell + + which will get Tk to run the canonical hello world application. + +8. unsupported1 +--------------- + +The unsupported1 command is a short term hack we made available to +allow you to set the window style of a new toplevel window. It works +much like the "wm overrideredirect" and "wm transient" commands in +that it must be run before the window it's being applied to is mapped. + +The syntax of the command is as follows: + + unsupported1 style <window> ?style? + +The <window> must be a toplevel window. If the style is not given +then the current style for the window is returned. If you want to set +the style you must do so before the window gets mapped for the first +time. The possible window styles include: + + documentProc, dBoxProc, plainDBox, altDBoxProc, + movableDBoxProc, zoomDocProc, rDocProc, floatProc, + floatZoomProc, floatSideProc, or floatSideZoomProc + +NOTE: this is an unsupported command and it WILL go away in the +future. + + +If you have comments or Bug reports send them to: +Jim Ingham +jingham@eng.sun.com diff --git a/mac/bugs.doc b/mac/bugs.doc new file mode 100644 index 0000000..e522d8c --- /dev/null +++ b/mac/bugs.doc @@ -0,0 +1,40 @@ +Known bug list for Tk 8.0 for Macintosh + +by Ray Johnson +Sun Microsystems Laboratories +rjohnson@eng.sun.com + +SCCS: @(#) bugs.doc 1.10 97/11/03 17:16:00 + +We are now very close to passing the test suite for Tk. We are very +interested in finding remaining bugs that still linger. Please let us +know (and send us test cases) of any bugs you find. + +Known bugs: + +* Transient windows (set by wm transient) do not go away when the + master does. + +* Tearoff menus should be floating windows & floating windows should + float. They also shouldn't be resizable. + +* The -use and -container windows only work with other Tk windows in + the same process. Also, if you try really hard (for instance by binding + on Destroy of an embedded window and destroying the container's toplevel) + you can get Tk to crash. This should never be necessary, however, since + the destruction of the embedded window triggers the destruction of the + container, so you can watch that instead. + All the focus bugs in Tk8.0 have been fixed, however. + +* The send command is not yet implemented. + +* Drawing is not really correct. This shows up mostly in the canvas + when line widths are greater than one. Unfortunantly, this will not + be easy to fix. + +There are many other bugs. However, will no get listed until they +are reported at least once. Send those bug reports in! + + + +Ray diff --git a/mac/tclets.tcl b/mac/tclets.tcl new file mode 100644 index 0000000..c8726a8 --- /dev/null +++ b/mac/tclets.tcl @@ -0,0 +1,215 @@ +# tclets.tcl -- +# +# Drag & Drop Tclets +# by Ray Johnson +# +# A simple way to create Tcl applications. This applications will copy a droped Tcl file +# into a copy of a stub application (the user can pick). The file is placed into the +# TEXT resource named "tclshrc" which is automatically executed on startup. +# +# SCCS: @(#) tclets.tcl 1.2 97/08/15 09:25:56 +# +# Copyright (c) 1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# tkOpenDocument -- +# +# This procedure is a called whenever Wish recieves an "Open" event. The +# procedure must be named tkOpenDocument for this to work. Passed in files +# are assumed to be Tcl files that the user wants to be made into Tclets. +# (Only the first one is used.) The procedure then creates a copy of the +# stub app and places the Tcl file in the new application's resource fork. +# +# Parameters: +# args List of files +# +# Results: +# One success a new Tclet is created. + +proc tkOpenDocument {args} { + global droped_to_start + + # We only deal with the one file droped on the App + set tclFile [lindex $args 0] + set stub [GetStub] + + # Give a helper screen to guide user + toplevel .helper -menu .bar + unsupported1 style .helper dBoxProc + message .helper.m -aspect 300 -text \ + "Select the name & location of your target Tcl application." + pack .helper.m + wm geometry .helper +20+40 + update idletasks + + # Get the target file from the end user + set target [tk_getSaveFile] + destroy .helper + if {$target == ""} return + + # Copy stub, copy the droped file into the stubs text resource + file copy $stub $target + set id [open $tclFile r] + set rid [resource open $target w] + resource write -name tclshrc -file $rid TEXT [read $id] + resource close $rid + close $id + + # This is a hint to the start-up code - always set to true + set droped_to_start true +} + +# GetStub -- +# +# Get the location of our stub application. The value may be cached, +# in the preferences file, or we may need to ask the user. +# +# Parameters: +# None. +# +# Results: +# A path to the stub application. + +proc GetStub {} { + global env stub_location + + if {[info exists stub_location]} { + return $stub_location + } + + set file $env(PREF_FOLDER) + append file "D&D Tclet Preferences" + + + if {[file exists $file]} { + uplevel #0 [list source $file] + if {[info exists stub_location] && [file exists $stub_location]} { + return $stub_location + } + } + + SelectStub + + if {[info exists stub_location]} { + return $stub_location + } else { + exit + } +} + +# SelectStub -- +# +# This procedure uses tk_getOpenFile to allow the user to select +# the copy of "Wish" that is used as the basis for Tclets. The +# result is stored in a preferences file. +# +# Parameters: +# None. +# +# Results: +# None. The prefernce file is updated. + +proc SelectStub {} { + global env stub_location + + # Give a helper screen to guide user + toplevel .helper -menu .bar + unsupported1 style .helper dBoxProc + message .helper.m -aspect 300 -text \ + "Select \"Wish\" stub to clone. A copy of this application will be made to create your Tclet." \ + + pack .helper.m + wm geometry .helper +20+40 + update idletasks + + set new_location [tk_getOpenFile] + destroy .helper + if {$new_location != ""} { + set stub_location $new_location + set file [file join $env(PREF_FOLDER) "D&D Tclet Preferences"] + + set id [open $file w] + puts $id [list set stub_location $stub_location] + close $id + } +} + +# CreateMenus -- +# +# Create the menubar for this application. +# +# Parameters: +# None. +# +# Results: +# None. + +proc CreateMenus {} { + menu .bar + .bar add cascade -menu .bar.file -label File + .bar add cascade -menu .bar.apple + . configure -menu .bar + + menu .bar.apple -tearoff 0 + .bar.apple add command -label "About Drag & Drop Tclets..." -command {ShowAbout} + + menu .bar.file -tearoff 0 + .bar.file add command -label "Show Console..." -command {console show} + .bar.file add command -label "Select Wish Stub..." -command {SelectStub} + .bar.file add separator + .bar.file add command -label "Quit" -accel Command-Q -command exit +} + +# ShowAbout -- +# +# Show the about box for Drag & Drop Tclets. +# +# Parameters: +# None. +# +# Results: +# None. + +proc ShowAbout {} { + tk_messageBox -icon info -type ok -message \ +"Drag & Drop Tclets +by Ray Johnson\n\n\ +Copyright (c) 1997 Sun Microsystems, Inc." +} + +# Start -- +# +# This procedure provides the main start-up code for the application. +# It should be run first thing on start up. It will create the UI +# and set up the rest of the state of the application. +# +# Parameters: +# None. +# +# Results: +# None. + +proc Start {} { + global droped_to_start + + # Hide . & console - see if we ran as a droped item + wm geometry . 1x1-25000-25000 + console hide + + # Run update - if we get any drop events we know that we were + # started by a drag & drop - if so, we quit automatically when done + set droped_to_start false + update + if {$droped_to_start == "true"} { + exit + } + + # We were not started by a drag & drop - create the UI + CreateMenus +} + +# Now that everything is defined, lets start the app! +Start diff --git a/mac/tkMac.h b/mac/tkMac.h new file mode 100644 index 0000000..ce41c81 --- /dev/null +++ b/mac/tkMac.h @@ -0,0 +1,53 @@ +/* + * tkMacInt.h -- + * + * Declarations of Macintosh specific exported variables and procedures. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacInt.h 1.58 97/05/06 16:45:18 + */ + +#ifndef _TKMAC +#define _TKMAC + +#include <Windows.h> + +/* + * "export" is a MetroWerks specific pragma. It flags the linker that + * any symbols that are defined when this pragma is on will be exported + * to shared libraries that link with this library. + */ + +#pragma export on + +/* + * This variable is exported and can be used by extensions. It is the + * way Tk extensions should access the QD Globals. This is so Tk + * can support embedding itself in another window. + */ + +EXTERN QDGlobalsPtr tcl_macQdPtr; + +/* + * The following functions are needed to create a shell, and so they must be exported + * from the Tk library. However, these are not the final form of these interfaces, so + * they are not currently supported as public interfaces. + */ + +/* + * These functions are currently in tkMacInt.h. They are just copied over here + * so they can be exported. + */ + +EXTERN void TkMacInitMenus _ANSI_ARGS_((Tcl_Interp *interp)); +EXTERN void TkMacInitAppleEvents _ANSI_ARGS_((Tcl_Interp *interp)); + +EXTERN int TkMacConvertEvent _ANSI_ARGS_((EventRecord *eventPtr)); + +#pragma export reset + +#endif /* _TKMAC */ diff --git a/mac/tkMacAppInit.c b/mac/tkMacAppInit.c new file mode 100644 index 0000000..ebc2c18 --- /dev/null +++ b/mac/tkMacAppInit.c @@ -0,0 +1,374 @@ +/* + * tkMacAppInit.c -- + * + * Provides a version of the Tcl_AppInit procedure for the example shell. + * + * Copyright (c) 1993-1994 Lockheed Missle & Space Company, AI Center + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacAppInit.c 1.35 97/07/28 11:18:55 + */ + +#include <Gestalt.h> +#include <ToolUtils.h> +#include <Fonts.h> +#include <Dialogs.h> +#include <SegLoad.h> +#include <Traps.h> + +#include "tk.h" +#include "tkInt.h" +#include "tkMacInt.h" +#include "tclMac.h" + +#ifdef TK_TEST +EXTERN int Tktest_Init _ANSI_ARGS_((Tcl_Interp *interp)); +#endif /* TK_TEST */ + +#ifdef TCL_TEST +EXTERN int TclObjTest_Init _ANSI_ARGS_((Tcl_Interp *interp)); +EXTERN int Tcltest_Init _ANSI_ARGS_((Tcl_Interp *interp)); +#endif /* TCL_TEST */ + +Tcl_Interp *gStdoutInterp = NULL; + +int TkMacConvertEvent _ANSI_ARGS_((EventRecord *eventPtr)); + +/* + * Prototypes for functions the ANSI library needs to link against. + */ +short InstallConsole _ANSI_ARGS_((short fd)); +void RemoveConsole _ANSI_ARGS_((void)); +long WriteCharsToConsole _ANSI_ARGS_((char *buff, long n)); +long ReadCharsFromConsole _ANSI_ARGS_((char *buff, long n)); +extern char * __ttyname _ANSI_ARGS_((long fildes)); +short SIOUXHandleOneEvent _ANSI_ARGS_((EventRecord *event)); + +/* + * Prototypes for functions from the tkConsole.c file. + */ + +EXTERN void TkConsoleCreate _ANSI_ARGS_((void)); +EXTERN int TkConsoleInit _ANSI_ARGS_((Tcl_Interp *interp)); +EXTERN void TkConsolePrint _ANSI_ARGS_((Tcl_Interp *interp, + int devId, char *buffer, long size)); +/* + * Forward declarations for procedures defined later in this file: + */ + +static int MacintoshInit _ANSI_ARGS_((void)); +static int SetupMainInterp _ANSI_ARGS_((Tcl_Interp *interp)); + +/* + *---------------------------------------------------------------------- + * + * main -- + * + * Main program for Wish. + * + * Results: + * None. This procedure never returns (it exits the process when + * it's done + * + * Side effects: + * This procedure initializes the wish world and then + * calls Tk_Main. + * + *---------------------------------------------------------------------- + */ + +void +main( + int argc, /* Number of arguments. */ + char **argv) /* Array of argument strings. */ +{ + char *newArgv[2]; + + if (MacintoshInit() != TCL_OK) { + Tcl_Exit(1); + } + + argc = 1; + newArgv[0] = "Wish"; + newArgv[1] = NULL; + Tk_Main(argc, newArgv, Tcl_AppInit); +} + +/* + *---------------------------------------------------------------------- + * + * Tcl_AppInit -- + * + * This procedure performs application-specific initialization. + * Most applications, especially those that incorporate additional + * packages, will have their own version of this procedure. + * + * Results: + * Returns a standard Tcl completion code, and leaves an error + * message in interp->result if an error occurs. + * + * Side effects: + * Depends on the startup script. + * + *---------------------------------------------------------------------- + */ + +int +Tcl_AppInit( + Tcl_Interp *interp) /* Interpreter for application. */ +{ + if (Tcl_Init(interp) == TCL_ERROR) { + return TCL_ERROR; + } + if (Tk_Init(interp) == TCL_ERROR) { + return TCL_ERROR; + } + Tcl_StaticPackage(interp, "Tk", Tk_Init, Tk_SafeInit); + + /* + * Call the init procedures for included packages. Each call should + * look like this: + * + * if (Mod_Init(interp) == TCL_ERROR) { + * return TCL_ERROR; + * } + * + * where "Mod" is the name of the module. + */ + +#ifdef TCL_TEST + if (Tcltest_Init(interp) == TCL_ERROR) { + return TCL_ERROR; + } + Tcl_StaticPackage(interp, "Tcltest", Tcltest_Init, + (Tcl_PackageInitProc *) NULL); + if (TclObjTest_Init(interp) == TCL_ERROR) { + return TCL_ERROR; + } +#endif /* TCL_TEST */ + +#ifdef TK_TEST + if (Tktest_Init(interp) == TCL_ERROR) { + return TCL_ERROR; + } + Tcl_StaticPackage(interp, "Tktest", Tktest_Init, + (Tcl_PackageInitProc *) NULL); +#endif /* TK_TEST */ + + /* + * Call Tcl_CreateCommand for application-specific commands, if + * they weren't already created by the init procedures called above. + * Each call would look like this: + * + * Tcl_CreateCommand(interp, "tclName", CFuncCmd, NULL, NULL); + */ + + SetupMainInterp(interp); + + /* + * Specify a user-specific startup script to invoke if the application + * is run interactively. On the Mac we can specifiy either a TEXT resource + * which contains the script or the more UNIX like file location + * may also used. (I highly recommend using the resource method.) + */ + + Tcl_SetVar(interp, "tcl_rcRsrcName", "tclshrc", TCL_GLOBAL_ONLY); + /* Tcl_SetVar(interp, "tcl_rcFileName", "~/.tclshrc", TCL_GLOBAL_ONLY); */ + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * MacintoshInit -- + * + * This procedure calls Mac specific initilization calls. Most of + * these calls must be made as soon as possible in the startup + * process. + * + * Results: + * Returns TCL_OK if everything went fine. If it didn't the + * application should probably fail. + * + * Side effects: + * Inits the application. + * + *---------------------------------------------------------------------- + */ + +static int +MacintoshInit() +{ + int i; + long result, mask = 0x0700; /* mask = system 7.x */ + +#if GENERATING68K && !GENERATINGCFM + SetApplLimit(GetApplLimit() - (TK_MAC_68K_STACK_GROWTH)); +#endif + MaxApplZone(); + for (i = 0; i < 4; i++) { + (void) MoreMasters(); + } + + /* + * Tk needs us to set the qd pointer it uses. This is needed + * so Tk doesn't have to assume the availablity of the qd global + * variable. Which in turn allows Tk to be used in code resources. + */ + tcl_macQdPtr = &qd; + + InitGraf(&tcl_macQdPtr->thePort); + InitFonts(); + InitWindows(); + InitMenus(); + InitDialogs((long) NULL); + InitCursor(); + + /* + * Make sure we are running on system 7 or higher + */ + + if ((NGetTrapAddress(_Gestalt, ToolTrap) == + NGetTrapAddress(_Unimplemented, ToolTrap)) + || (((Gestalt(gestaltSystemVersion, &result) != noErr) + || (result < mask)))) { + panic("Tcl/Tk requires System 7 or higher."); + } + + /* + * Make sure we have color quick draw + * (this means we can't run on 68000 macs) + */ + + if (((Gestalt(gestaltQuickdrawVersion, &result) != noErr) + || (result < gestalt32BitQD13))) { + panic("Tk requires Color QuickDraw."); + } + + + FlushEvents(everyEvent, 0); + SetEventMask(everyEvent); + + + Tcl_MacSetEventProc(TkMacConvertEvent); + TkConsoleCreate(); + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * SetupMainInterp -- + * + * This procedure calls initalization routines require a Tcl + * interp as an argument. This call effectively makes the passed + * iterpreter the "main" interpreter for the application. + * + * Results: + * Returns TCL_OK if everything went fine. If it didn't the + * application should probably fail. + * + * Side effects: + * More initilization. + * + *---------------------------------------------------------------------- + */ + +static int +SetupMainInterp( + Tcl_Interp *interp) +{ + /* + * Initialize the console only if we are running as an interactive + * application. + */ + + TkMacInitAppleEvents(interp); + TkMacInitMenus(interp); + + if (strcmp(Tcl_GetVar(interp, "tcl_interactive", TCL_GLOBAL_ONLY), "1") + == 0) { + if (TkConsoleInit(interp) == TCL_ERROR) { + goto error; + } + } + + /* + * Attach the global interpreter to tk's expected global console + */ + + gStdoutInterp = interp; + + return TCL_OK; + +error: + panic(interp->result); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * InstallConsole, RemoveConsole, etc. -- + * + * The following functions provide the UI for the console package. + * Users wishing to replace SIOUX with their own console package + * need only provide the four functions below in a library. + * + * Results: + * See SIOUX documentation for details. + * + * Side effects: + * See SIOUX documentation for details. + * + *---------------------------------------------------------------------- + */ + +short +InstallConsole(short fd) +{ +#pragma unused (fd) + + return 0; +} + +void +RemoveConsole(void) +{ +} + +long +WriteCharsToConsole(char *buffer, long n) +{ + TkConsolePrint(gStdoutInterp, TCL_STDOUT, buffer, n); + return n; +} + +long +ReadCharsFromConsole(char *buffer, long n) +{ + return 0; +} + +extern char * +__ttyname(long fildes) +{ + static char *__devicename = "null device"; + + if (fildes >= 0 && fildes <= 2) { + return (__devicename); + } + + return (0L); +} + +short +SIOUXHandleOneEvent(EventRecord *event) +{ + return 0; +} diff --git a/mac/tkMacApplication.r b/mac/tkMacApplication.r new file mode 100644 index 0000000..365035d --- /dev/null +++ b/mac/tkMacApplication.r @@ -0,0 +1,267 @@ +/* + * tkMacApplication.r -- + * + * This file creates resources for use in the Wish application. + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacApplication.r 1.3 97/11/03 17:16:24 + */ + +#include <Types.r> +#include <SysTypes.r> +#include <AEUserTermTypes.r> + +/* + * The folowing include and defines help construct + * the version string for Tcl. + */ + +#define RESOURCE_INCLUDED +#include "tk.h" + +#if (TK_RELEASE_LEVEL == 0) +# define RELEASE_LEVEL alpha +#elif (TK_RELEASE_LEVEL == 1) +# define RELEASE_LEVEL beta +#elif (TK_RELEASE_LEVEL == 2) +# define RELEASE_LEVEL final +#endif + +#if (TK_RELEASE_LEVEL == 2) +# define MINOR_VERSION (TK_MINOR_VERSION * 16) + TK_RELEASE_SERIAL +#else +# define MINOR_VERSION TK_MINOR_VERSION * 16 +#endif + +#define RELEASE_CODE 0x00 + +resource 'vers' (1) { + TK_MAJOR_VERSION, MINOR_VERSION, + RELEASE_LEVEL, 0x00, verUS, + TK_PATCH_LEVEL, + TK_PATCH_LEVEL ", by Ray Johnson © 1993-1996" "\n" "Sun Microsystems Labratories" +}; + +resource 'vers' (2) { + TK_MAJOR_VERSION, MINOR_VERSION, + RELEASE_LEVEL, 0x00, verUS, + TK_PATCH_LEVEL, + "Wish " TK_PATCH_LEVEL " © 1993-1996" +}; + +#define TK_APP_RESOURCES 128 +#define TK_APP_CREATOR 'WIsH' + +/* + * The 'BNDL' resource is the primary link between a file's + * creator/type and its icon. This resource acts for all Tcl shared + * libraries; other libraries will not need one and ought to use + * custom icons rather than new file types for a different appearance. + */ + +resource 'BNDL' (TK_APP_RESOURCES, "Tk app bundle", purgeable) +{ + TK_APP_CREATOR, + 0, + { + 'FREF', + { + 0, TK_APP_RESOURCES, + 1, TK_APP_RESOURCES+1 + }, + 'ICN#', + { + 0, TK_APP_RESOURCES, + 1, TK_APP_RESOURCES+1 + } + } +}; + +resource 'FREF' (TK_APP_RESOURCES, purgeable) +{ + 'APPL', 0, "" +}; +resource 'FREF' (TK_APP_RESOURCES+1, purgeable) +{ + 'TEXT', 1, "" +}; + +type TK_APP_CREATOR as 'STR '; +resource TK_APP_CREATOR (0, purgeable) { + "Wish " TK_PATCH_LEVEL " © 1996" +}; + +/* + * The 'kind' resource works with a 'BNDL' in Macintosh Easy Open + * to affect the text the Finder displays in the "kind" column and + * file info dialog. This information will be applied to all files + * with the listed creator and type. + */ +resource 'kind' (TK_APP_RESOURCES, "Tcl kind", purgeable) { + TK_APP_CREATOR, + 0, /* region = USA */ + { + 'APPL', "Wish", + 'TEXT', "Tcl/Tk Script" + } +}; + +/* + * The following resource define the icon used by Tcl scripts. Any + * TEXT file with the creator of WIsH will get this icon. + */ + +data 'icl4' (TK_APP_RESOURCES + 1, "Tk Doc", purgeable) { + $"000F FFFF FFFF FFFF FFFF FFF0 0000 0000" + $"000F 3333 3333 3333 3333 33FF 0000 0000" + $"000F 3333 3333 3333 3433 33F2 F000 0000" + $"000F 3333 3333 3333 7D43 33F2 2F00 0000" + $"000F 3333 3333 3335 5623 33F2 22F0 0000" + $"000F 3333 3333 3356 6343 33FF FFFF 0000" + $"000F 3333 3333 256F 5223 3333 333F 0000" + $"000F 3333 3333 D666 2433 3333 333F 0000" + $"000F 3333 3333 D5F6 6633 3333 333F 0000" + $"000F 3333 3332 5666 6733 3333 333F 0000" + $"000F 3333 3336 E56F 6633 3333 333F 0000" + $"000F 3333 3336 5656 5733 3333 333F 0000" + $"000F 3333 3336 E5B6 5233 3333 333F 0000" + $"000F 3333 3336 5ED6 3333 3333 333F 0000" + $"000F 3333 3376 6475 6233 3333 333F 0000" + $"000F 3333 333D 5D56 7333 3333 333F 0000" + $"000F 3333 3336 6C55 6333 3333 333F 0000" + $"000F 3333 3336 5C56 7333 3333 333F 0000" + $"000F 3333 3362 6CE6 D333 3333 333F 0000" + $"000F 3333 3336 5C65 6333 3333 333F 0000" + $"000F 3333 3336 EC5E 3333 3333 333F 0000" + $"000F 3333 3336 5C56 6333 3333 333F 0000" + $"000F 3333 3333 5C75 3333 3333 333F 0000" + $"000F 3333 3333 5DD6 3333 3333 333F 0000" + $"000F 3333 3333 3CDD 3333 3333 333F 0000" + $"000F 3333 3333 3303 3333 3333 333F 0000" + $"000F 3333 3333 3C33 3333 3333 333F 0000" + $"000F 3333 3333 3C33 3333 3333 333F 0000" + $"000F 3333 3333 3C33 3333 3333 333F 0000" + $"000F 3333 3333 3333 3333 3333 333F 0000" + $"000F 3333 3333 3333 3333 3333 333F 0000" + $"000F FFFF FFFF FFFF FFFF FFFF FFFF 0000" +}; + +data 'ICN#' (TK_APP_RESOURCES + 1, "Tk Doc", purgeable) { + $"1FFF FE00 1000 0300 1000 F280 1003 F240" + $"1003 E220 1007 E3F0 100F C010 100F C010" + $"100F C010 101F F010 101F F010 101F F010" + $"101F F010 101F F010 101D E010 101D E010" + $"101D E010 101D C010 101D C010 101D C010" + $"101D C010 100D 8010 100D 8010 100D 8010" + $"1005 8010 1002 0010 1002 0010 1002 0010" + $"1002 0010 1002 0010 1000 0010 1FFF FFF0" + $"1FFF FE00 1FFF FF00 1FFF FF80 1FFF FFC0" + $"1FFF FFE0 1FFF FFF0 1FFF FFF0 1FFF FFF0" + $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" + $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" + $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" + $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" + $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" + $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" +}; + +data 'ics#' (TK_APP_RESOURCES + 1, "Tk Doc", purgeable) { + $"7FF0 41D8 419C 4384 43C4 47C4 47C4 4784" + $"4684 4684 4284 4284 4104 4104 4104 7FFC" + $"7FE0 7FF0 7FF8 7FFC 7FFC 7FFC 7FFC 7FFC" + $"7FFC 7FFC 7FFC 7FFC 7FFC 7FFC 7FFC 7FFC" +}; + +data 'ics4' (TK_APP_RESOURCES + 1, "Tk Doc", purgeable) { + $"0FFF FFFF FFFF 0000 0F33 3333 53F2 F000" + $"0F33 3335 52FF FF00 0F33 33E6 3333 3F00" + $"0F33 3256 6333 3F00 0F33 3556 6333 3F00" + $"0F33 3A5E 3333 3F00 0F33 65D6 D333 3F00" + $"0F33 3655 5333 3F00 0F33 65C6 3333 3F00" + $"0F33 3EC5 E333 3F00 0F33 36C6 3333 3F00" + $"0F33 33CD 3333 3F00 0F33 33C3 3333 3F00" + $"0F33 33C3 3333 3F00 0FFF FFFF FFFF FF00" +}; + +/* + * The following resources define the icons for the Wish + * application. + */ + +data 'icl4' (TK_APP_RESOURCES, "Tk App", purgeable) { + $"0000 0000 0000 000F 0000 0000 0000 0000" + $"0000 0000 0000 00FC F000 0000 0000 0000" + $"0000 0000 0000 0FCC CF66 0000 0000 0000" + $"0000 0000 0000 FCCC C556 0000 0000 0000" + $"0000 0000 000F CCCC 566F 0000 0000 0000" + $"0000 0000 00FC CCC5 6F5C F000 0000 0000" + $"0000 0000 0FCC CC66 66CC CF00 0000 0000" + $"0000 0000 FCCC CCD5 5666 CCF0 0000 0000" + $"0000 000F CCCC C656 5667 CCCF 0000 0000" + $"0000 00FC CCCC C6E5 5566 CCCC F000 0000" + $"0000 0FCC CCCC C656 5657 CCCC CF00 0000" + $"0000 FCCC CCCC C6E5 565C CCCC CCF0 0000" + $"000F CCCC CCCC C655 565C CCCC CCCF 0000" + $"00FC CCCC CCCC 7660 556C CCCC CCCC F000" + $"0FCC CCCC CCCC CD5D 567C CCCC CCCC CF00" + $"FCCC CCCC CCCC 6660 556C CCCC CCCC CCF0" + $"0FCC CCCC CCCC 665C 565C CCCC CCCC C0CF" + $"00FC CCCC CCCC 6660 E6DC CCCC CCCC CCF0" + $"000F CCCC CCCC C650 656C CCCC CCCC CF00" + $"0000 FCCC CCCC C6EC 5ECC CCCC CCCC F000" + $"0000 0FCC CCCC C650 566C CCCC CCCF 0000" + $"0000 00FC CCCC CC50 75CC CCCC CCF0 0000" + $"0000 000F CCCC CC50 56CC CCCC CF00 0000" + $"0000 0000 FCCC CCC0 5CCC CCCC F000 0000" + $"0000 0000 0FCC CCC0 CCCC CCCF 0000 0000" + $"0000 0000 00FC CCC0 CCCC CCF0 0000 0000" + $"0000 0000 000F CCC0 CCCC CF00 0000 0000" + $"0000 0000 0000 FCCC CCCC F000 0000 0000" + $"0000 0000 0000 0FCC CCCF 0000 0000 0000" + $"0000 0000 0000 00FC CCF0 0000 0000 0000" + $"0000 0000 0000 000F CF00 0000 0000 0000" + $"0000 0000 0000 0000 F000 0000 0000 0000" +}; + +data 'ICN#' (TK_APP_RESOURCES, "Tk App", purgeable) { + $"0001 0000 0002 8000 0004 7000 0008 7000" + $"0010 F000 0021 E800 0043 C400 0081 F200" + $"0107 F100 0207 F080 0407 F040 0807 E020" + $"1007 E010 200E E008 4002 E004 800E E002" + $"400E E001 200E C002 1006 E004 0806 C008" + $"0406 E010 0202 C020 0102 C040 0080 8080" + $"0041 0100 0021 0200 0011 0400 0009 0800" + $"0004 1000 0002 2000 0001 4000 0000 8000" + $"0001 0000 0003 8000 0007 F000 000F F000" + $"001F F000 003F F800 007F FC00 00FF FE00" + $"01FF FF00 03FF FF80 07FF FFC0 0FFF FFE0" + $"1FFF FFF0 3FFF FFF8 7FFF FFFC FFFF FFFE" + $"7FFF FFFF 3FFF FFFE 1FFF FFFC 0FFF FFF8" + $"07FF FFF0 03FF FFE0 01FF FFC0 00FF FF80" + $"007F FF00 003F FE00 001F FC00 000F F800" + $"0007 F000 0003 E000 0001 C000 0000 8000" +}; + +data 'ics#' (TK_APP_RESOURCES, "Tk App", purgeable) { + $"01C0 0260 04E0 09D0 1388 23C4 43C2 8281" + $"8282 4284 2188 1190 0920 0540 0280 0100" + $"01C0 03E0 07E0 0FF0 1FF8 3FFC 7FFE FFFF" + $"FFFE 7FFC 3FF8 1FF0 0FE0 07C0 0380 0100" +}; + +data 'ics4' (TK_APP_RESOURCES, "Tk App", purgeable) { + $"0000 000F C000 0000 0000 00FC 6600 0000" + $"0000 0FCC 6600 0000 0000 FCC6 66F0 0000" + $"000F CCD5 56CF 0000 00FC CC66 57CC F000" + $"0FCC CC65 56CC CF00 FCCC CC56 57CC CCF0" + $"0FCC CCC6 6CCC CCCF 00FC CCC6 5CCC CCF0" + $"000F CCC6 6CCC CF00 0000 FCCC 5CCC F000" + $"0000 0FCC CCCF 0000 0000 00FC CCF0 0000" + $"0000 000F CF00 0000 0000 0000 F000 0000" +}; + + diff --git a/mac/tkMacBitmap.c b/mac/tkMacBitmap.c new file mode 100644 index 0000000..fd08193 --- /dev/null +++ b/mac/tkMacBitmap.c @@ -0,0 +1,268 @@ +/* + * tkMacBitmap.c -- + * + * This file handles the implementation of native bitmaps. + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacBitmap.c 1.4 96/12/13 11:13:16 + */ + +#include "tkPort.h" +#include "tk.h" +#include "tkMacInt.h" + +#include <Icons.h> +#include <Dialogs.h> +#include <Resources.h> +#include <Strings.h> + +/* + * Depending on the resource type there are different ways to + * draw native icons. + */ +#define TYPE1 0 /* Family icon suite. */ +#define TYPE2 1 /* ICON resource. */ +#define TYPE3 2 /* cicn resource. */ + +/* + * This data structure describes the id and type of a given icon. + * It is used as the source for native icons. + */ +typedef struct { + int id; /* Resource Id for Icon. */ + long int type; /* Type of icon. */ +} NativeIcon; + +/* + * This structure holds information about native bitmaps. + */ + +typedef struct { + char *name; /* Name of icon. */ + long int type; /* Type of icon. */ + int id; /* Id of icon. */ + int size; /* Size of icon. */ +} BuiltInIcon; + +/* + * This array mapps a string name to the supported builtin icons + * on the Macintosh. + */ + +static BuiltInIcon builtInIcons[] = { + {"document", TYPE1, kGenericDocumentIconResource, 32}, + {"stationery", TYPE1, kGenericStationeryIconResource, 32}, + {"edition", TYPE1, kGenericEditionFileIconResource, 32}, + {"application", TYPE1, kGenericApplicationIconResource, 32}, + {"accessory", TYPE1, kGenericDeskAccessoryIconResource, 32}, + {"folder", TYPE1, kGenericFolderIconResource, 32}, + {"pfolder", TYPE1, kPrivateFolderIconResource, 32}, + {"trash", TYPE1, kTrashIconResource, 32}, + {"floppy", TYPE1, kFloppyIconResource, 32}, + {"ramdisk", TYPE1, kGenericRAMDiskIconResource, 32}, + {"cdrom", TYPE1, kGenericCDROMIconResource, 32}, + {"preferences", TYPE1, kGenericPreferencesIconResource, 32}, + {"querydoc", TYPE1, kGenericQueryDocumentIconResource, 32}, + {"stop", TYPE2, kStopIcon, 32}, + {"note", TYPE2, kNoteIcon, 32}, + {"caution", TYPE2, kCautionIcon, 32}, + {(char *) NULL, 0, 0, 0} +}; + +/* + *---------------------------------------------------------------------- + * + * TkpDefineNativeBitmaps -- + * + * Add native bitmaps. + * + * Results: + * A standard Tcl result. If an error occurs then TCL_ERROR is + * returned and a message is left in interp->result. + * + * Side effects: + * "Name" is entered into the bitmap table and may be used from + * here on to refer to the given bitmap. + * + *---------------------------------------------------------------------- + */ + +void +TkpDefineNativeBitmaps() +{ + int new; + Tcl_HashEntry *predefHashPtr; + TkPredefBitmap *predefPtr; + char * name; + BuiltInIcon *builtInPtr; + NativeIcon *nativeIconPtr; + + for (builtInPtr = builtInIcons; builtInPtr->name != NULL; builtInPtr++) { + name = Tk_GetUid(builtInPtr->name); + predefHashPtr = Tcl_CreateHashEntry(&tkPredefBitmapTable, name, &new); + if (!new) { + continue; + } + predefPtr = (TkPredefBitmap *) ckalloc(sizeof(TkPredefBitmap)); + nativeIconPtr = (NativeIcon *) ckalloc(sizeof(NativeIcon)); + nativeIconPtr->id = builtInPtr->id; + nativeIconPtr->type = builtInPtr->type; + predefPtr->source = (char *) nativeIconPtr; + predefPtr->width = builtInPtr->size; + predefPtr->height = builtInPtr->size; + predefPtr->native = 1; + Tcl_SetHashValue(predefHashPtr, predefPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpCreateNativeBitmap -- + * + * Add native bitmaps. + * + * Results: + * A standard Tcl result. If an error occurs then TCL_ERROR is + * returned and a message is left in interp->result. + * + * Side effects: + * "Name" is entered into the bitmap table and may be used from + * here on to refer to the given bitmap. + * + *---------------------------------------------------------------------- + */ + +Pixmap +TkpCreateNativeBitmap( + Display *display, + char * source) /* Info about the icon to build. */ +{ + Pixmap pix; + GWorldPtr destPort; + Rect destRect; + Handle icon; + CGrafPtr saveWorld; + GDHandle saveDevice; + NativeIcon *nativeIconPtr; + + pix = Tk_GetPixmap(display, None, 32, 32, 0); + destPort = TkMacGetDrawablePort(pix); + + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + nativeIconPtr = (NativeIcon *) source; + SetRect(&destRect, 0, 0, 32, 32); + if (nativeIconPtr->type == TYPE1) { + RGBColor white = {0xFFFF, 0xFFFF, 0xFFFF}; + + RGBForeColor(&white); + PaintRect(&destRect); + PlotIconID(&destRect, atAbsoluteCenter, ttNone, nativeIconPtr->id); + } else if (nativeIconPtr->type == TYPE2) { + icon = GetIcon(nativeIconPtr->id); + if (icon != NULL) { + RGBColor black = {0, 0, 0}; + + RGBForeColor(&black); + PlotIcon(&destRect, icon); + ReleaseResource(icon); + } + } + + SetGWorld(saveWorld, saveDevice); + return pix; +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetNativeAppBitmap -- + * + * Add native bitmaps. + * + * Results: + * A standard Tcl result. If an error occurs then TCL_ERROR is + * returned and a message is left in interp->result. + * + * Side effects: + * "Name" is entered into the bitmap table and may be used from + * here on to refer to the given bitmap. + * + *---------------------------------------------------------------------- + */ + +Pixmap +TkpGetNativeAppBitmap( + Display *display, /* The display. */ + char *name, /* The name of the bitmap. */ + int *width, /* The width & height of the bitmap. */ + int *height) +{ + Pixmap pix; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + Rect destRect; + Handle resource; + int type; + + c2pstr(name); + resource = GetNamedResource('cicn', (StringPtr) name); + if (resource != NULL) { + type = TYPE3; + } else { + resource = GetNamedResource('ICON', (StringPtr) name); + if (resource != NULL) { + type = TYPE2; + } + } + p2cstr((StringPtr) name); + + if (resource == NULL) { + return NULL; + } + + pix = Tk_GetPixmap(display, None, 32, 32, 0); + destPort = TkMacGetDrawablePort(pix); + + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + SetRect(&destRect, 0, 0, 32, 32); + if (type == TYPE2) { + RGBColor black = {0, 0, 0}; + + RGBForeColor(&black); + PlotIcon(&destRect, resource); + ReleaseResource(resource); + } else if (type == TYPE3) { + RGBColor white = {0xFFFF, 0xFFFF, 0xFFFF}; + short id; + ResType theType; + Str255 dummy; + + /* + * We need to first paint the background white. Also, for + * some reason we *must* use GetCIcon instead of GetNamedResource + * for PlotCIcon to work - so we use GetResInfo to get the id. + */ + RGBForeColor(&white); + PaintRect(&destRect); + GetResInfo(resource, &id, &theType, dummy); + ReleaseResource(resource); + resource = (Handle) GetCIcon(id); + PlotCIcon(&destRect, (CIconHandle) resource); + DisposeCIcon((CIconHandle) resource); + } + + *width = 32; + *height = 32; + SetGWorld(saveWorld, saveDevice); + return pix; +} diff --git a/mac/tkMacButton.c b/mac/tkMacButton.c new file mode 100644 index 0000000..767baff --- /dev/null +++ b/mac/tkMacButton.c @@ -0,0 +1,825 @@ +/* + * tkMacButton.c -- + * + * This file implements the Macintosh specific portion of the + * button widgets. + * + * Copyright (c) 1996-1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacButton.c 1.18 97/11/20 18:27:21 + */ + +#include "tkButton.h" +#include "tkMacInt.h" +#include <Controls.h> +#include <LowMem.h> + +/* + * Some defines used to control what type of control is drawn. + */ + +#define DRAW_LABEL 0 /* Labels are treated genericly. */ +#define DRAW_CONTROL 1 /* Draw using the Native control. */ +#define DRAW_CUSTOM 2 /* Make our own button drawing. */ + +/* + * The following structures are used to draw our controls. Rather than + * having many Mac controls we just use one control of each type and + * reuse them for all Tk widgets. When the windowRef variable is NULL + * it means none of the data structures have been allocated. + */ + +static WindowRef windowRef = NULL; +static CWindowRecord windowRecord; +static ControlRef buttonHandle; +static ControlRef checkHandle; +static ControlRef radioHandle; +static CCTabHandle buttonTabHandle; +static CCTabHandle checkTabHandle; +static CCTabHandle radioTabHandle; +static PixMapHandle oldPixPtr; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int UpdateControlColors _ANSI_ARGS_((TkButton *butPtr, + ControlRef controlHandle, CCTabHandle ccTabHandle, + RGBColor *saveColorPtr)); +static void DrawBufferedControl _ANSI_ARGS_((TkButton *butPtr, + GWorldPtr destPort)); +static void ChangeBackgroundWindowColor _ANSI_ARGS_(( + WindowRef macintoshWindow, RGBColor rgbColor, + RGBColor *oldColor)); +static void ButtonExitProc _ANSI_ARGS_((ClientData clientData)); + +/* + * The class procedure table for the button widgets. + */ + +TkClassProcs tkpButtonProcs = { + NULL, /* createProc. */ + TkButtonWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + +/* + *---------------------------------------------------------------------- + * + * TkpCreateButton -- + * + * Allocate a new TkButton structure. + * + * Results: + * Returns a newly allocated TkButton structure. + * + * Side effects: + * Registers an event handler for the widget. + * + *---------------------------------------------------------------------- + */ + +TkButton * +TkpCreateButton( + Tk_Window tkwin) +{ + return (TkButton *) ckalloc(sizeof(TkButton)); +} + +/* + *---------------------------------------------------------------------- + * + * TkpDisplayButton -- + * + * This procedure is invoked to display a button widget. It is + * normally invoked as an idle handler. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the button in its + * current mode. The REDRAW_PENDING flag is cleared. + * + *---------------------------------------------------------------------- + */ + +void +TkpDisplayButton( + ClientData clientData) /* Information about widget. */ +{ + TkButton *butPtr = (TkButton *) clientData; + Pixmap pixmap; + GC gc; + Tk_3DBorder border; + int x = 0; /* Initialization only needed to stop + * compiler warning. */ + int y, relief; + register Tk_Window tkwin = butPtr->tkwin; + int width, height; + int offset; /* 0 means this is a normal widget. 1 means + * it is an image button, so we offset the + * image to make the button appear to move + * up and down as the relief changes. */ + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + int drawType, borderWidth; + + GetGWorld(&saveWorld, &saveDevice); + + butPtr->flags &= ~REDRAW_PENDING; + if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + return; + } + + border = butPtr->normalBorder; + if ((butPtr->state == tkDisabledUid) && (butPtr->disabledFg != NULL)) { + gc = butPtr->disabledGC; + } else if ((butPtr->type == TYPE_BUTTON) && (butPtr->state == tkActiveUid)) { + gc = butPtr->activeTextGC; + border = butPtr->activeBorder; + } else { + gc = butPtr->normalTextGC; + } + if ((butPtr->flags & SELECTED) && (butPtr->state != tkActiveUid) + && (butPtr->selectBorder != NULL) && !butPtr->indicatorOn) { + border = butPtr->selectBorder; + } + + /* + * Override the relief specified for the button if this is a + * checkbutton or radiobutton and there's no indicator. + */ + + relief = butPtr->relief; + if ((butPtr->type >= TYPE_CHECK_BUTTON) && !butPtr->indicatorOn) { + relief = (butPtr->flags & SELECTED) ? TK_RELIEF_SUNKEN + : TK_RELIEF_RAISED; + } + + offset = ((butPtr->type == TYPE_BUTTON) && + ((butPtr->image != NULL) || (butPtr->bitmap != None))); + + /* + * In order to avoid screen flashes, this procedure redraws + * the button in a pixmap, then copies the pixmap to the + * screen in a single operation. This means that there's no + * point in time where the on-sreen image has been cleared. + */ + + pixmap = Tk_GetPixmap(butPtr->display, Tk_WindowId(tkwin), + Tk_Width(tkwin), Tk_Height(tkwin), Tk_Depth(tkwin)); + Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, + Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); + + + if (butPtr->type == TYPE_LABEL) { + drawType = DRAW_LABEL; + } else if (butPtr->type == TYPE_BUTTON) { + if ((butPtr->image == None) && (butPtr->bitmap == None)) { + drawType = DRAW_CONTROL; + } else { + drawType = DRAW_CUSTOM; + } + } else { + if (butPtr->indicatorOn) { + drawType = DRAW_CONTROL; + } else { + drawType = DRAW_CUSTOM; + } + } + + /* + * Draw the native portion of the buttons. Start by creating the control + * if it doesn't already exist. Then configure the Macintosh control from + * the Tk info. Finally, we call Draw1Control to draw to the screen. + */ + + if (drawType == DRAW_CONTROL) { + borderWidth = 0; + + /* + * This part uses Macintosh rather than Tk calls to draw + * to the screen. Make sure the ports etc. are set correctly. + */ + + destPort = TkMacGetDrawablePort(pixmap); + SetGWorld(destPort, NULL); + DrawBufferedControl(butPtr, destPort); + } + + if ((drawType == DRAW_CUSTOM) || (drawType == DRAW_LABEL)) { + borderWidth = butPtr->borderWidth; + } + + /* + * Display image or bitmap or text for button. + */ + + if (butPtr->image != None) { + Tk_SizeOfImage(butPtr->image, &width, &height); + + imageOrBitmap: + TkComputeAnchor(butPtr->anchor, tkwin, 0, 0, + butPtr->indicatorSpace + width, height, &x, &y); + x += butPtr->indicatorSpace; + + x += offset; + y += offset; + if (relief == TK_RELIEF_RAISED) { + x -= offset; + y -= offset; + } else if (relief == TK_RELIEF_SUNKEN) { + x += offset; + y += offset; + } + if (butPtr->image != NULL) { + if ((butPtr->selectImage != NULL) && (butPtr->flags & SELECTED)) { + Tk_RedrawImage(butPtr->selectImage, 0, 0, width, height, + pixmap, x, y); + } else { + Tk_RedrawImage(butPtr->image, 0, 0, width, height, pixmap, + x, y); + } + } else { + XSetClipOrigin(butPtr->display, gc, x, y); + XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, gc, 0, 0, + (unsigned int) width, (unsigned int) height, x, y, 1); + XSetClipOrigin(butPtr->display, gc, 0, 0); + } + y += height/2; + } else if (butPtr->bitmap != None) { + Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height); + goto imageOrBitmap; + } else { + TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY, + butPtr->indicatorSpace + butPtr->textWidth, butPtr->textHeight, + &x, &y); + + x += butPtr->indicatorSpace; + + Tk_DrawTextLayout(butPtr->display, pixmap, gc, butPtr->textLayout, + x, y, 0, -1); + y += butPtr->textHeight/2; + } + + /* + * If the button is disabled with a stipple rather than a special + * foreground color, generate the stippled effect. If the widget + * is selected and we use a different background color when selected, + * must temporarily modify the GC. + */ + + if ((butPtr->state == tkDisabledUid) + && ((butPtr->disabledFg == NULL) || (butPtr->image != NULL))) { + if ((butPtr->flags & SELECTED) && !butPtr->indicatorOn + && (butPtr->selectBorder != NULL)) { + XSetForeground(butPtr->display, butPtr->disabledGC, + Tk_3DBorderColor(butPtr->selectBorder)->pixel); + } + XFillRectangle(butPtr->display, pixmap, butPtr->disabledGC, + butPtr->inset, butPtr->inset, + (unsigned) (Tk_Width(tkwin) - 2*butPtr->inset), + (unsigned) (Tk_Height(tkwin) - 2*butPtr->inset)); + if ((butPtr->flags & SELECTED) && !butPtr->indicatorOn + && (butPtr->selectBorder != NULL)) { + XSetForeground(butPtr->display, butPtr->disabledGC, + Tk_3DBorderColor(butPtr->normalBorder)->pixel); + } + } + + /* + * Draw the border and traversal highlight last. This way, if the + * button's contents overflow they'll be covered up by the border. + */ + + if (relief != TK_RELIEF_FLAT) { + int inset = butPtr->highlightWidth; + Tk_Draw3DRectangle(tkwin, pixmap, border, inset, inset, + Tk_Width(tkwin) - 2*inset, Tk_Height(tkwin) - 2*inset, + butPtr->borderWidth, relief); + } + + /* + * Copy the information from the off-screen pixmap onto the screen, + * then delete the pixmap. + */ + + XCopyArea(butPtr->display, pixmap, Tk_WindowId(tkwin), + butPtr->copyGC, 0, 0, (unsigned) Tk_Width(tkwin), + (unsigned) Tk_Height(tkwin), 0, 0); + Tk_FreePixmap(butPtr->display, pixmap); + + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * TkpComputeButtonGeometry -- + * + * After changes in a button's text or bitmap, this procedure + * recomputes the button's geometry and passes this information + * along to the geometry manager for the window. + * + * Results: + * None. + * + * Side effects: + * The button's window may change size. + * + *---------------------------------------------------------------------- + */ + +void +TkpComputeButtonGeometry( + TkButton *butPtr) /* Button whose geometry may have changed. */ +{ + int width, height, avgWidth; + Tk_FontMetrics fm; + + if (butPtr->highlightWidth < 0) { + butPtr->highlightWidth = 0; + } + if ((butPtr->type == TYPE_BUTTON) && (butPtr->image == None) + && (butPtr->bitmap == None)) { + butPtr->inset = 0; + } else if ((butPtr->type != TYPE_LABEL) && butPtr->indicatorOn) { + butPtr->inset = 0; + } else { + butPtr->inset = butPtr->borderWidth; + } + + /* + * The highlight width corresponds to the default ring on the Macintosh. + * As such, the highlight width is only added if the button is the default + * button. The actual width of the default ring is one less than the + * highlight width as there is also one pixel of spacing. + */ + + if (butPtr->defaultState != tkDisabledUid) { + butPtr->inset += butPtr->highlightWidth; + } + butPtr->indicatorSpace = 0; + if (butPtr->image != NULL) { + Tk_SizeOfImage(butPtr->image, &width, &height); + imageOrBitmap: + if (butPtr->width > 0) { + width = butPtr->width; + } + if (butPtr->height > 0) { + height = butPtr->height; + } + if ((butPtr->type >= TYPE_CHECK_BUTTON) && butPtr->indicatorOn) { + butPtr->indicatorSpace = height; + if (butPtr->type == TYPE_CHECK_BUTTON) { + butPtr->indicatorDiameter = (65*height)/100; + } else { + butPtr->indicatorDiameter = (75*height)/100; + } + } + } else if (butPtr->bitmap != None) { + Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height); + goto imageOrBitmap; + } else { + Tk_FreeTextLayout(butPtr->textLayout); + butPtr->textLayout = Tk_ComputeTextLayout(butPtr->tkfont, + butPtr->text, -1, butPtr->wrapLength, butPtr->justify, 0, + &butPtr->textWidth, &butPtr->textHeight); + + width = butPtr->textWidth; + height = butPtr->textHeight; + avgWidth = Tk_TextWidth(butPtr->tkfont, "0", 1); + Tk_GetFontMetrics(butPtr->tkfont, &fm); + + if (butPtr->width > 0) { + width = butPtr->width * avgWidth; + } + if (butPtr->height > 0) { + height = butPtr->height * fm.linespace; + } + if ((butPtr->type >= TYPE_CHECK_BUTTON) && butPtr->indicatorOn) { + butPtr->indicatorDiameter = fm.linespace; + if (butPtr->type == TYPE_CHECK_BUTTON) { + butPtr->indicatorDiameter = (80*butPtr->indicatorDiameter)/100; + } + butPtr->indicatorSpace = butPtr->indicatorDiameter + avgWidth; + } + } + + /* + * When issuing the geometry request, add extra space for the indicator, + * if any, and for the border and padding, plus if this is an image two + * extra pixels so the display can be offset by 1 pixel in either + * direction for the raised or lowered effect. + */ + + if ((butPtr->image == NULL) && (butPtr->bitmap == None)) { + width += 2*butPtr->padX; + height += 2*butPtr->padY; + } + if ((butPtr->type == TYPE_BUTTON) && + ((butPtr->image != NULL) || (butPtr->bitmap != None))) { + width += 2; + height += 2; + } + Tk_GeometryRequest(butPtr->tkwin, (int) (width + butPtr->indicatorSpace + + 2*butPtr->inset), (int) (height + 2*butPtr->inset)); + Tk_SetInternalBorder(butPtr->tkwin, butPtr->inset); +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyButton -- + * + * Free data structures associated with the button control. + * + * Results: + * None. + * + * Side effects: + * Restores the default control state. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyButton( + TkButton *butPtr) +{ + /* Do nothing. */ +} + +/* + *-------------------------------------------------------------- + * + * DrawBufferedControl -- + * + * This function uses a dummy Macintosh window to allow + * drawing Mac controls to any GWorld (including off-screen + * bitmaps). In addition, this code may apply custom + * colors passed in the TkButton. + * + * Results: + * None. + * + * Side effects: + * Control is to the GWorld. Static state created on + * first invocation of this routine. + * + *-------------------------------------------------------------- + */ + +static void +DrawBufferedControl( + TkButton *butPtr, /* Tk button. */ + GWorldPtr destPort) /* Off screen GWorld. */ +{ + ControlRef controlHandle; + CCTabHandle ccTabHandle; + int windowColorChanged = false; + RGBColor saveBackColor; + + if (windowRef == NULL) { + Rect geometry = {0, 0, 10, 10}; + CWindowPeek windowList; + + /* + * Create a dummy window that we can draw to. We will + * actually replace this windows bitmap with a the one + * we want to draw to at a later time. This window and + * the data structures attached to it are only deallocated + * on exit of the application. + */ + + windowRef = NewCWindow(NULL, &geometry, "\pempty", false, + zoomDocProc, (WindowRef) -1, true, 0); + if (windowRef == NULL) { + panic("Can't allocate buffer window."); + } + + /* + * Now add the three standard controls to hidden window. We + * only create one of each and reuse them for every widget in + * Tk. + */ + + SetPort(windowRef); + buttonHandle = NewControl(windowRef, &geometry, "\p", + false, 1, 0, 1, pushButProc, (SInt32) 0); + checkHandle = NewControl(windowRef, &geometry, "\p", + false, 1, 0, 1, checkBoxProc, (SInt32) 0); + radioHandle = NewControl(windowRef, &geometry, "\p", + false, 1, 0, 1, radioButProc, (SInt32) 0); + ((CWindowPeek) windowRef)->visible = true; + + buttonTabHandle = (CCTabHandle) NewHandle(sizeof(CtlCTab)); + checkTabHandle = (CCTabHandle) NewHandle(sizeof(CtlCTab)); + radioTabHandle = (CCTabHandle) NewHandle(sizeof(CtlCTab)); + + /* + * Remove our window from the window list. This way our + * applications and others will not be confused that this + * window exists - but no one knows about it. + */ + + windowList = (CWindowPeek) LMGetWindowList(); + if (windowList == (CWindowPeek) windowRef) { + LMSetWindowList((WindowRef) windowList->nextWindow); + } else { + while ((windowList != NULL) + && (windowList->nextWindow != (CWindowPeek) windowRef)) { + windowList = windowList->nextWindow; + } + if (windowList != NULL) { + windowList->nextWindow = windowList->nextWindow->nextWindow; + } + } + ((CWindowPeek) windowRef)->nextWindow = NULL; + + /* + * Create an exit handler to clean up this mess if we our + * unloaded etc. We need to remember the windows portPixMap + * so it isn't leaked. + * + * TODO: The ButtonExitProc doesn't currently work and the + * code it includes will crash the Mac on exit from Tk. + + oldPixPtr = ((CWindowPeek) windowRef)->port.portPixMap; + Tcl_CreateExitHandler(ButtonExitProc, (ClientData) NULL); + */ + } + + /* + * Set up control in hidden window to match what we need + * to draw in the buffered window. + */ + + switch (butPtr->type) { + case TYPE_BUTTON: + controlHandle = buttonHandle; + ccTabHandle = buttonTabHandle; + break; + case TYPE_RADIO_BUTTON: + controlHandle = radioHandle; + ccTabHandle = radioTabHandle; + break; + case TYPE_CHECK_BUTTON: + controlHandle = checkHandle; + ccTabHandle = checkTabHandle; + break; + } + (**controlHandle).contrlRect.left = butPtr->inset; + (**controlHandle).contrlRect.top = butPtr->inset; + (**controlHandle).contrlRect.right = Tk_Width(butPtr->tkwin) + - butPtr->inset; + (**controlHandle).contrlRect.bottom = Tk_Height(butPtr->tkwin) + - butPtr->inset; + if ((**controlHandle).contrlVis != 255) { + (**controlHandle).contrlVis = 255; + } + if (butPtr->flags & SELECTED) { + (**controlHandle).contrlValue = 1; + } else { + (**controlHandle).contrlValue = 0; + } + if (butPtr->state == tkActiveUid) { + switch (butPtr->type) { + case TYPE_BUTTON: + (**controlHandle).contrlHilite = kControlButtonPart; + break; + case TYPE_RADIO_BUTTON: + (**controlHandle).contrlHilite = kControlRadioButtonPart; + break; + case TYPE_CHECK_BUTTON: + (**controlHandle).contrlHilite = kControlCheckBoxPart; + break; + } + } else if (butPtr->state == tkDisabledUid) { + (**controlHandle).contrlHilite = kControlInactivePart; + } else { + (**controlHandle).contrlHilite = kControlNoPart; + } + + /* + * Now swap in the passed in GWorld for the portBits of our fake + * window. We also adjust various fields in the WindowRecord to make + * the system think this is a normal window. + */ + + ((CWindowPeek) windowRef)->port.portPixMap = destPort->portPixMap; + ((CWindowPeek) windowRef)->port.portRect = destPort->portRect; + RectRgn(((CWindowPeek) windowRef)->port.visRgn, &destPort->portRect); + RectRgn(((CWindowPeek) windowRef)->strucRgn, &destPort->portRect); + RectRgn(((CWindowPeek) windowRef)->updateRgn, &destPort->portRect); + RectRgn(((CWindowPeek) windowRef)->contRgn, &destPort->portRect); + PortChanged(windowRef); + + /* + * Before we draw the control we must add the hidden window back to the + * main window list. Otherwise, radiobuttons and checkbuttons will draw + * incorrectly. I don't really know why - but clearly the control draw + * proc needs to have the controls window in the window list. + */ + + ((CWindowPeek) windowRef)->nextWindow = (CWindowPeek) LMGetWindowList(); + LMSetWindowList(windowRef); + + /* + * Now we can set the port to our doctered up window. We next need + * to muck with the colors for the port & window to draw the control + * with the proper Tk colors. If we need to we also draw a default + * ring for buttons. + */ + + SetPort(windowRef); + windowColorChanged = UpdateControlColors(butPtr, controlHandle, + ccTabHandle, &saveBackColor); + Draw1Control(controlHandle); + if ((butPtr->type == TYPE_BUTTON) && + (butPtr->defaultState == tkActiveUid)) { + Rect box = (**controlHandle).contrlRect; + RGBColor rgbColor; + + TkSetMacColor(butPtr->highlightColorPtr->pixel, &rgbColor); + RGBForeColor(&rgbColor); + PenSize(butPtr->highlightWidth - 1, butPtr->highlightWidth - 1); + InsetRect(&box, -butPtr->highlightWidth, -butPtr->highlightWidth); + FrameRoundRect(&box, 16, 16); + } + if (windowColorChanged) { + RGBColor dummyColor; + ChangeBackgroundWindowColor(windowRef, saveBackColor, &dummyColor); + } + + /* + * Clean up: remove the hidden window from the main window list. + */ + + LMSetWindowList((WindowRef) ((CWindowPeek) windowRef)->nextWindow); +} + +/* + *-------------------------------------------------------------- + * + * UpdateControlColors -- + * + * This function will review the colors used to display + * a Macintosh button. If any non-standard colors are + * used we create a custom palette for the button, populate + * with the colors for the button and install the palette. + * + * Results: + * None. + * + * Side effects: + * The Macintosh control may get a custom palette installed. + * + *-------------------------------------------------------------- + */ + +static int +UpdateControlColors( + TkButton *butPtr, + ControlRef controlHandle, + CCTabHandle ccTabHandle, + RGBColor *saveColorPtr) +{ + XColor *xcolor; + + xcolor = Tk_3DBorderColor(butPtr->normalBorder); + + (**ccTabHandle).ccSeed = 0; + (**ccTabHandle).ccRider = 0; + (**ccTabHandle).ctSize = 3; + (**ccTabHandle).ctTable[0].value = cBodyColor; + TkSetMacColor(xcolor->pixel, + &(**ccTabHandle).ctTable[0].rgb); + (**ccTabHandle).ctTable[1].value = cTextColor; + TkSetMacColor(butPtr->normalFg->pixel, + &(**ccTabHandle).ctTable[1].rgb); + (**ccTabHandle).ctTable[2].value = cFrameColor; + TkSetMacColor(butPtr->highlightColorPtr->pixel, + &(**ccTabHandle).ctTable[2].rgb); + SetControlColor(controlHandle, ccTabHandle); + + if (((xcolor->pixel >> 24) != CONTROL_BODY_PIXEL) && + ((butPtr->type == TYPE_CHECK_BUTTON) || + (butPtr->type == TYPE_RADIO_BUTTON))) { + RGBColor newColor; + + TkSetMacColor(xcolor->pixel, &newColor); + ChangeBackgroundWindowColor((**controlHandle).contrlOwner, + newColor, saveColorPtr); + return true; + } + + return false; +} + +/* + *-------------------------------------------------------------- + * + * ChangeBackgroundWindowColor -- + * + * This procedure will change the background color entry + * in the Window's colortable. The system isn't notified + * of the change. This call should only be used to fool + * the drawing routines for checkboxes and radiobuttons. + * Any change should be temporary and be reverted after + * the widget is drawn. + * + * Results: + * None. + * + * Side effects: + * The Window's color table will be adjusted. + * + *-------------------------------------------------------------- + */ + +static void +ChangeBackgroundWindowColor( + WindowRef macintoshWindow, /* A Mac window whose color to change. */ + RGBColor rgbColor, /* The new RGB Color for the background. */ + RGBColor *oldColor) /* The old color of the background. */ +{ + AuxWinHandle auxWinHandle; + WCTabHandle winCTabHandle; + short ctIndex; + ColorSpecPtr rgbScan; + + GetAuxWin(macintoshWindow, &auxWinHandle); + winCTabHandle = (WCTabHandle) ((**auxWinHandle).awCTable); + + /* + * Scan through the color table until we find the content + * (background) color for the window. Don't tell the system + * about the change - it will generate damage and we will get + * into an infinite loop. + */ + + ctIndex = (**winCTabHandle).ctSize; + while (ctIndex > -1) { + rgbScan = ctIndex + (**winCTabHandle).ctTable; + + if (rgbScan->value == wContentColor) { + *oldColor = rgbScan->rgb; + rgbScan->rgb = rgbColor; + break; + } + ctIndex--; + } +} + +/* + *---------------------------------------------------------------------- + * + * ButtonExitProc -- + * + * This procedure is invoked just before the application exits. + * It frees all of the control handles, our dummy window, etc. + * + * Results: + * None. + * + * Side effects: + * Memory is freed. + * + *---------------------------------------------------------------------- + */ + +static void +ButtonExitProc(clientData) + ClientData clientData; /* Not used. */ +{ + Rect pixRect = {0, 0, 10, 10}; + Rect rgnRect = {0, 0, 0, 0}; + + /* + * Restore our dummy window to it's origional state by putting it + * back in the window list and restoring it's bits. The destroy + * the controls and window. + */ + + ((CWindowPeek) windowRef)->nextWindow = (CWindowPeek) LMGetWindowList(); + LMSetWindowList(windowRef); + ((CWindowPeek) windowRef)->port.portPixMap = oldPixPtr; + ((CWindowPeek) windowRef)->port.portRect = pixRect; + RectRgn(((CWindowPeek) windowRef)->port.visRgn, &rgnRect); + RectRgn(((CWindowPeek) windowRef)->strucRgn, &rgnRect); + RectRgn(((CWindowPeek) windowRef)->updateRgn, &rgnRect); + RectRgn(((CWindowPeek) windowRef)->contRgn, &rgnRect); + PortChanged(windowRef); + + DisposeControl(buttonHandle); + DisposeControl(checkHandle); + DisposeControl(radioHandle); + DisposeWindow(windowRef); + windowRef = NULL; +} diff --git a/mac/tkMacClipboard.c b/mac/tkMacClipboard.c new file mode 100644 index 0000000..0c06f1d --- /dev/null +++ b/mac/tkMacClipboard.c @@ -0,0 +1,293 @@ +/* + * tkMacClipboard.c -- + * + * This file manages the clipboard for the Tk toolkit. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacClipboard.c 1.18 97/05/01 15:41:17 + */ + +#include "tkInt.h" +#include "tkPort.h" +#include "tkMacInt.h" + +#include <Scrap.h> +#include <Events.h> + +#include "tkSelect.h" + +/* + *---------------------------------------------------------------------- + * + * TkSelGetSelection -- + * + * Retrieve the specified selection from another process. For + * now, only fetching XA_STRING from CLIPBOARD is supported. + * Eventually other types should be allowed. + * + * Results: + * The return value is a standard Tcl return value. + * If an error occurs (such as no selection exists) + * then an error message is left in interp->result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkSelGetSelection( + Tcl_Interp *interp, /* Interpreter to use for reporting + * errors. */ + Tk_Window tkwin, /* Window on whose behalf to retrieve + * the selection (determines display + * from which to retrieve). */ + Atom selection, /* Selection to retrieve. */ + Atom target, /* Desired form in which selection + * is to be returned. */ + Tk_GetSelProc *proc, /* Procedure to call to process the + * selection, once it has been retrieved. */ + ClientData clientData) /* Arbitrary value to pass to proc. */ +{ + int result; + long length, offset = 0; + Handle handle; + + if ((selection == Tk_InternAtom(tkwin, "CLIPBOARD")) + && (target == XA_STRING)) { + /* + * Get the scrap from the Macintosh global clipboard. + */ + handle = NewHandle(1); + length = GetScrap(handle, 'TEXT', &offset); + if (length > 0) { + SetHandleSize(handle, (Size) length + 1); + HLock(handle); + (*handle)[length] = '\0'; + + result = (*proc)(clientData, interp, *handle); + + HUnlock(handle); + DisposeHandle(handle); + return result; + } + + DisposeHandle(handle); + } + + Tcl_AppendResult(interp, Tk_GetAtomName(tkwin, selection), + " selection doesn't exist or form \"", Tk_GetAtomName(tkwin, target), + "\" not defined", (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * TkSetSelectionOwner -- + * + * This function claims ownership of the specified selection. + * If the selection is CLIPBOARD, then we empty the system + * clipboard. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +XSetSelectionOwner( + Display* display, /* X Display. */ + Atom selection, /* What selection to own. */ + Window owner, /* Window to be the owner. */ + Time time) /* The current time? */ +{ + Tk_Window tkwin; + TkDisplay *dispPtr; + + /* + * This is a gross hack because the Tk_InternAtom interface is broken. + * It expects a Tk_Window, even though it only needs a Tk_Display. + */ + + tkwin = (Tk_Window)tkMainWindowList->winPtr; + + if (selection == Tk_InternAtom(tkwin, "CLIPBOARD")) { + + /* + * Only claim and empty the clipboard if we aren't already the + * owner of the clipboard. + */ + + dispPtr = tkMainWindowList->winPtr->dispPtr; + if (dispPtr->clipboardActive) { + return; + } + ZeroScrap(); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkSelUpdateClipboard -- + * + * This function is called to force the clipboard to be updated + * after new data is added. On the Mac we don't need to do + * anything. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkSelUpdateClipboard( + TkWindow *winPtr, /* Window associated with clipboard. */ + TkClipboardTarget *targetPtr) /* Info about the content. */ +{ +} + +/* + *-------------------------------------------------------------- + * + * TkSelEventProc -- + * + * This procedure is invoked whenever a selection-related + * event occurs. + * + * Results: + * None. + * + * Side effects: + * Lots: depends on the type of event. + * + *-------------------------------------------------------------- + */ + +void +TkSelEventProc( + Tk_Window tkwin, /* Window for which event was + * targeted. */ + register XEvent *eventPtr) /* X event: either SelectionClear, + * SelectionRequest, or + * SelectionNotify. */ +{ + if (eventPtr->type == SelectionClear) { + TkSelClearSelection(tkwin, eventPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkSelPropProc -- + * + * This procedure is invoked when property-change events + * occur on windows not known to the toolkit. This is a stub + * function under Windows. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkSelPropProc( + register XEvent *eventPtr) /* X PropertyChange event. */ +{ +} + +/* + *---------------------------------------------------------------------- + * + * TkSuspendClipboard -- + * + * Handle clipboard conversion as required by the suppend event. + * This function is also called on exit. + * + * Results: + * None. + * + * Side effects: + * The local scrap is moved to the global scrap. + * + *---------------------------------------------------------------------- + */ + +void +TkSuspendClipboard() +{ + TkClipboardTarget *targetPtr; + TkClipboardBuffer *cbPtr; + TkDisplay *dispPtr; + char *buffer, *p, *endPtr, *buffPtr; + long length; + + dispPtr = tkDisplayList; + if ((dispPtr == NULL) || !dispPtr->clipboardActive) { + return; + } + + for (targetPtr = dispPtr->clipTargetPtr; targetPtr != NULL; + targetPtr = targetPtr->nextPtr) { + if (targetPtr->type == XA_STRING) + break; + } + if (targetPtr != NULL) { + length = 0; + for (cbPtr = targetPtr->firstBufferPtr; cbPtr != NULL; + cbPtr = cbPtr->nextPtr) { + length += cbPtr->length; + } + + buffer = ckalloc(length); + buffPtr = buffer; + for (cbPtr = targetPtr->firstBufferPtr; cbPtr != NULL; + cbPtr = cbPtr->nextPtr) { + for (p = cbPtr->buffer, endPtr = p + cbPtr->length; + p < endPtr; p++) { + if (*p == '\n') { + *buffPtr++ = '\r'; + } else { + *buffPtr++ = *p; + } + } + } + + ZeroScrap(); + PutScrap(length, 'TEXT', buffer); + ckfree(buffer); + } + + /* + * The system now owns the scrap. We tell Tk that it has + * lost the selection so that it will look for it the next time + * it needs it. (Window list NULL if quiting.) + */ + + if (tkMainWindowList != NULL) { + Tk_ClearSelection((Tk_Window) tkMainWindowList->winPtr, + Tk_InternAtom((Tk_Window) tkMainWindowList->winPtr, + "CLIPBOARD")); + } + + return; +} diff --git a/mac/tkMacColor.c b/mac/tkMacColor.c new file mode 100644 index 0000000..56fe38d --- /dev/null +++ b/mac/tkMacColor.c @@ -0,0 +1,485 @@ +/* + * tkMacColor.c -- + * + * This file maintains a database of color values for the Tk + * toolkit, in order to avoid round-trips to the server to + * map color names to pixel values. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacColor.c 1.36 96/11/25 11:02:12 + */ + +#include <tkColor.h> +#include "tkMacInt.h" + +#include <LowMem.h> +#include <Palettes.h> +#include <Quickdraw.h> + +/* + * Default Auxillary Control Record for all controls. This is cached once + * and is updated by the system. We use this to get the default system + * colors used by controls. + */ +static AuxCtlHandle defaultAuxCtlHandle = NULL; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int GetControlPartColor _ANSI_ARGS_((short part, RGBColor *macColor)); +static int GetMenuPartColor _ANSI_ARGS_((int part, RGBColor *macColor)); +static int GetWindowPartColor _ANSI_ARGS_((short part, RGBColor *macColor)); + +/* + *---------------------------------------------------------------------- + * + * TkSetMacColor -- + * + * Populates a Macintosh RGBColor structure from a X style + * pixel value. + * + * Results: + * Returns false if not a real pixel, true otherwise. + * + * Side effects: + * The variable macColor is updated to the pixels value. + * + *---------------------------------------------------------------------- + */ + +int +TkSetMacColor( + unsigned long pixel, /* Pixel value to convert. */ + RGBColor *macColor) /* Mac color struct to modify. */ +{ + switch (pixel >> 24) { + case HIGHLIGHT_PIXEL: + LMGetHiliteRGB(macColor); + return true; + case HIGHLIGHT_TEXT_PIXEL: + LMGetHiliteRGB(macColor); + if ((macColor->red == 0) && (macColor->green == 0) + && (macColor->blue == 0)) { + macColor->red = macColor->green = macColor->blue = 0xFFFFFFFF; + } else { + macColor->red = macColor->green = macColor->blue = 0; + } + return true; + case CONTROL_TEXT_PIXEL: + GetControlPartColor(cTextColor, macColor); + return true; + case CONTROL_BODY_PIXEL: + GetControlPartColor(cBodyColor, macColor); + return true; + case CONTROL_FRAME_PIXEL: + GetControlPartColor(cFrameColor, macColor); + return true; + case WINDOW_BODY_PIXEL: + GetWindowPartColor(wContentColor, macColor); + return true; + case MENU_ACTIVE_PIXEL: + case MENU_ACTIVE_TEXT_PIXEL: + case MENU_BACKGROUND_PIXEL: + case MENU_DISABLED_PIXEL: + case MENU_TEXT_PIXEL: + GetMenuPartColor((pixel >> 24), macColor); + return true; + case PIXEL_MAGIC: + default: + macColor->blue = (unsigned short) ((pixel & 0xFF) << 8); + macColor->green = (unsigned short) (((pixel >> 8) & 0xFF) << 8); + macColor->red = (unsigned short) (((pixel >> 16) & 0xFF) << 8); + return true; + } +} + +/* + *---------------------------------------------------------------------- + * + * Stub functions -- + * + * These functions are just stubs for functions that either + * don't make sense on the Mac or have yet to be implemented. + * + * Results: + * None. + * + * Side effects: + * These calls do nothing - which may not be expected. + * + *---------------------------------------------------------------------- + */ + +Status +XAllocColor( + Display *display, /* Display. */ + Colormap map, /* Not used. */ + XColor *colorPtr) /* XColor struct to modify. */ +{ + display->request++; + colorPtr->pixel = TkpGetPixel(colorPtr); + return 1; +} + +Colormap +XCreateColormap( + Display *display, /* Display. */ + Window window, /* X window. */ + Visual *visual, /* Not used. */ + int alloc) /* Not used. */ +{ + static Colormap index = 1; + + /* + * Just return a new value each time. + */ + return index++; +} + +void +XFreeColormap( + Display* display, /* Display. */ + Colormap colormap) /* Colormap. */ +{ +} + +void +XFreeColors( + Display* display, /* Display. */ + Colormap colormap, /* Colormap. */ + unsigned long* pixels, /* Array of pixels. */ + int npixels, /* Number of pixels. */ + unsigned long planes) /* Number of pixel planes. */ +{ + /* + * The Macintosh version of Tk uses TrueColor. Nothing + * needs to be done to release colors as there really is + * no colormap in the Tk sense. + */ +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetColor -- + * + * Allocate a new TkColor for the color with the given name. + * + * Results: + * Returns a newly allocated TkColor, or NULL on failure. + * + * Side effects: + * May invalidate the colormap cache associated with tkwin upon + * allocating a new colormap entry. Allocates a new TkColor + * structure. + * + *---------------------------------------------------------------------- + */ + +TkColor * +TkpGetColor( + Tk_Window tkwin, /* Window in which color will be used. */ + Tk_Uid name) /* Name of color to allocated (in form + * suitable for passing to XParseColor). */ +{ + Display *display = Tk_Display(tkwin); + Colormap colormap = Tk_Colormap(tkwin); + TkColor *tkColPtr; + XColor color; + + /* + * Check to see if this is a system color. Otherwise, XParseColor + * will do all the work. + */ + if (strncasecmp(name, "system", 6) == 0) { + int foundSystemColor = false; + RGBColor rgbValue; + char pixelCode; + + if (!strcasecmp(name+6, "Highlight")) { + LMGetHiliteRGB(&rgbValue); + pixelCode = HIGHLIGHT_PIXEL; + foundSystemColor = true; + } else if (!strcasecmp(name+6, "HighlightText")) { + LMGetHiliteRGB(&rgbValue); + if ((rgbValue.red == 0) && (rgbValue.green == 0) + && (rgbValue.blue == 0)) { + rgbValue.red = rgbValue.green = rgbValue.blue = 0xFFFFFFFF; + } else { + rgbValue.red = rgbValue.green = rgbValue.blue = 0; + } + pixelCode = HIGHLIGHT_TEXT_PIXEL; + foundSystemColor = true; + } else if (!strcasecmp(name+6, "ButtonText")) { + GetControlPartColor(cTextColor, &rgbValue); + pixelCode = CONTROL_TEXT_PIXEL; + foundSystemColor = true; + } else if (!strcasecmp(name+6, "ButtonFace")) { + GetControlPartColor(cBodyColor, &rgbValue); + pixelCode = CONTROL_BODY_PIXEL; + foundSystemColor = true; + } else if (!strcasecmp(name+6, "ButtonFrame")) { + GetControlPartColor(cFrameColor, &rgbValue); + pixelCode = CONTROL_FRAME_PIXEL; + foundSystemColor = true; + } else if (!strcasecmp(name+6, "WindowBody")) { + GetWindowPartColor(wContentColor, &rgbValue); + pixelCode = WINDOW_BODY_PIXEL; + foundSystemColor = true; + } else if (!strcasecmp(name+6, "MenuActive")) { + GetMenuPartColor(MENU_ACTIVE_PIXEL, &rgbValue); + pixelCode = MENU_ACTIVE_PIXEL; + foundSystemColor = true; + } else if (!strcasecmp(name+6, "MenuActiveText")) { + GetMenuPartColor(MENU_ACTIVE_TEXT_PIXEL, &rgbValue); + pixelCode = MENU_ACTIVE_TEXT_PIXEL; + foundSystemColor = true; + } else if (!strcasecmp(name+6, "Menu")) { + GetMenuPartColor(MENU_BACKGROUND_PIXEL, &rgbValue); + pixelCode = MENU_BACKGROUND_PIXEL; + foundSystemColor = true; + } else if (!strcasecmp(name+6, "MenuDisabled")) { + GetMenuPartColor(MENU_DISABLED_PIXEL, &rgbValue); + pixelCode = MENU_DISABLED_PIXEL; + foundSystemColor = true; + } else if (!strcasecmp(name+6, "MenuText")) { + GetMenuPartColor(MENU_TEXT_PIXEL, &rgbValue); + pixelCode = MENU_TEXT_PIXEL; + foundSystemColor = true; + } + + if (foundSystemColor) { + color.red = rgbValue.red; + color.green = rgbValue.green; + color.blue = rgbValue.blue; + color.pixel = ((((((pixelCode << 8) + | ((color.red >> 8) & 0xff)) << 8) + | ((color.green >> 8) & 0xff)) << 8) + | ((color.blue >> 8) & 0xff)); + + tkColPtr = (TkColor *) ckalloc(sizeof(TkColor)); + tkColPtr->color = color; + return tkColPtr; + } + } + + if (XParseColor(display, colormap, name, &color) == 0) { + return (TkColor *) NULL; + } + + tkColPtr = (TkColor *) ckalloc(sizeof(TkColor)); + tkColPtr->color = color; + + return tkColPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetColorByValue -- + * + * Given a desired set of red-green-blue intensities for a color, + * locate a pixel value to use to draw that color in a given + * window. + * + * Results: + * The return value is a pointer to an TkColor structure that + * indicates the closest red, blue, and green intensities available + * to those specified in colorPtr, and also specifies a pixel + * value to use to draw in that color. + * + * Side effects: + * May invalidate the colormap cache for the specified window. + * Allocates a new TkColor structure. + * + *---------------------------------------------------------------------- + */ + +TkColor * +TkpGetColorByValue( + Tk_Window tkwin, /* Window in which color will be used. */ + XColor *colorPtr) /* Red, green, and blue fields indicate + * desired color. */ +{ + TkColor *tkColPtr = (TkColor *) ckalloc(sizeof(TkColor)); + + tkColPtr->color.red = colorPtr->red; + tkColPtr->color.green = colorPtr->green; + tkColPtr->color.blue = colorPtr->blue; + tkColPtr->color.pixel = TkpGetPixel(&tkColPtr->color); + return tkColPtr; +} + +/* + *---------------------------------------------------------------------- + * + * GetControlPartColor -- + * + * Given a part number this function will return the standard + * system default color for that part. It does this by looking + * in the system's 'cctb' resource. + * + * Results: + * True if a color is found, false otherwise. + * + * Side effects: + * If a color is found then the RGB variable will be changed to + * the parts color. + * + *---------------------------------------------------------------------- + */ + +static int +GetControlPartColor( + short part, /* Part code. */ + RGBColor *macColor) /* Pointer to Mac color. */ +{ + short index; + CCTabHandle ccTab; + + if (defaultAuxCtlHandle == NULL) { + GetAuxiliaryControlRecord(NULL, &defaultAuxCtlHandle); + } + ccTab = (**defaultAuxCtlHandle).acCTable; + if(ccTab && (ResError() == noErr)) { + for(index = 0; index <= (**ccTab).ctSize; index++) { + if((**ccTab).ctTable[index].value == part) { + *macColor = (**ccTab).ctTable[index].rgb; + return true; + } + } + } + return false; +} + +/* + *---------------------------------------------------------------------- + * + * GetWindowPartColor -- + * + * Given a part number this function will return the standard + * system default color for that part. It does this by looking + * in the system's 'wctb' resource. + * + * Results: + * True if a color is found, false otherwise. + * + * Side effects: + * If a color is found then the RGB variable will be changed to + * the parts color. + * + *---------------------------------------------------------------------- + */ + +static int +GetWindowPartColor( + short part, /* Part code. */ + RGBColor *macColor) /* Pointer to Mac color. */ +{ + short index; + WCTabHandle wcTab; + + wcTab = (WCTabHandle) GetResource('wctb', 0); + if(wcTab && (ResError() == noErr)) { + for(index = 0; index <= (**wcTab).ctSize; index++) { + if((**wcTab).ctTable[index].value == part) { + *macColor = (**wcTab).ctTable[index].rgb; + return true; + } + } + } + return false; +} + +/* + *---------------------------------------------------------------------- + * + * GetMenuPartColor -- + * + * Given a magic pixel value, returns the RGB color associated + * with it by looking the value up in the system's 'mctb' resource. + * + * Results: + * True if a color is found, false otherwise. + * + * Side effects: + * If a color is found then the RGB variable will be changed to + * the parts color. + * + *---------------------------------------------------------------------- + */ + +static int +GetMenuPartColor( + int pixel, /* The magic pixel value */ + RGBColor *macColor) /* Pointer to Mac color */ +{ + RGBColor backColor, foreColor; + GDHandle maxDevice; + Rect globalRect; + MCEntryPtr mcEntryPtr = GetMCEntry(0, 0); + + switch (pixel) { + case MENU_ACTIVE_PIXEL: + if (mcEntryPtr == NULL) { + macColor->red = macColor->blue = macColor->green = 0; + } else { + *macColor = mcEntryPtr->mctRGB3; + } + return 1; + case MENU_ACTIVE_TEXT_PIXEL: + if (mcEntryPtr == NULL) { + macColor->red = macColor->blue = macColor->green = 0xFFFF; + } else { + *macColor = mcEntryPtr->mctRGB2; + } + return 1; + case MENU_BACKGROUND_PIXEL: + if (mcEntryPtr == NULL) { + macColor->red = macColor->blue = macColor->green = 0xFFFF; + } else { + *macColor = mcEntryPtr->mctRGB2; + } + return 1; + case MENU_DISABLED_PIXEL: + if (mcEntryPtr == NULL) { + backColor.red = backColor.blue = backColor.green = 0xFFFF; + foreColor.red = foreColor.blue = foreColor.green = 0x0000; + } else { + backColor = mcEntryPtr->mctRGB2; + foreColor = mcEntryPtr->mctRGB3; + } + SetRect(&globalRect, SHRT_MIN, SHRT_MIN, SHRT_MAX, SHRT_MAX); + maxDevice = GetMaxDevice(&globalRect); + if (GetGray(maxDevice, &backColor, &foreColor)) { + *macColor = foreColor; + } else { + + /* + * Pointer may have been moved by GetMaxDevice or GetGray. + */ + + mcEntryPtr = GetMCEntry(0,0); + if (mcEntryPtr == NULL) { + macColor->red = macColor->green = macColor->blue = 0x7777; + } else { + *macColor = mcEntryPtr->mctRGB2; + } + } + return 1; + case MENU_TEXT_PIXEL: + if (mcEntryPtr == NULL) { + macColor->red = macColor->green = macColor->blue = 0; + } else { + *macColor = mcEntryPtr->mctRGB3; + } + return 1; + } + return 0; +} diff --git a/mac/tkMacCursor.c b/mac/tkMacCursor.c new file mode 100644 index 0000000..f221189 --- /dev/null +++ b/mac/tkMacCursor.c @@ -0,0 +1,360 @@ +/* + * tkMacCursor.c -- + * + * This file contains Macintosh specific cursor related routines. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacCursor.c 1.20 97/09/17 19:33:13 + */ + +#include "tkPort.h" +#include "tkInt.h" +#include "tkMacInt.h" + +#include <Resources.h> +#include <ToolUtils.h> +#include <Strings.h> + +/* + * There are three different ways to set the cursor on the Mac. + */ +#define ARROW 0 /* The arrow cursor. */ +#define COLOR 1 /* Cursors of type crsr. */ +#define NORMAL 2 /* Cursors of type CURS. */ + +/* + * The following data structure contains the system specific data + * necessary to control Windows cursors. + */ + +typedef struct { + TkCursor info; /* Generic cursor info used by tkCursor.c */ + Handle macCursor; /* Resource containing Macintosh cursor. */ + int type; /* Type of Mac cursor: arrow, crsr, CURS */ +} TkMacCursor; + +/* + * The table below is used to map from the name of a predefined cursor + * to its resource identifier. + */ + +static struct CursorName { + char *name; + int id; +} cursorNames[] = { + {"ibeam", 1}, + {"text", 1}, + {"xterm", 1}, + {"cross", 2}, + {"crosshair", 2}, + {"cross-hair", 2}, + {"plus", 3}, + {"watch", 4}, + {"arrow", 5}, + {NULL, 0} +}; + +/* + * Declarations of static variables used in this file. + */ + +static TkMacCursor * gCurrentCursor = NULL; /* A pointer to the current + * cursor. */ +static int gResizeOverride = false; /* A boolean indicating wether + * we should use the resize + * cursor during installations. */ + +/* + * Declarations of procedures local to this file + */ + +static void FindCursorByName _ANSI_ARGS_ ((TkMacCursor *macCursorPtr, + char *string)); + +/* + *---------------------------------------------------------------------- + * + * FindCursorByName -- + * + * Retrieve a system cursor by name, and fill the macCursorPtr + * structure. If the cursor cannot be found, the macCursor field + * will be NULL. The function first attempts to load a color + * cursor. If that fails it will attempt to load a black & white + * cursor. + * + * Results: + * Fills the macCursorPtr record. + * + * Side effects: + * None + * + *---------------------------------------------------------------------- + */ + +void +FindCursorByName( + TkMacCursor *macCursorPtr, + char *string) +{ + Handle resource; + Str255 curName; + + curName[0] = strlen(string); + if (curName[0] > 255) { + return; + } + + strcpy((char *) curName + 1, string); + resource = GetNamedResource('crsr', curName); + + if (resource != NULL) { + short id; + Str255 theName; + ResType theType; + + HLock(resource); + GetResInfo(resource, &id, &theType, theName); + HUnlock(resource); + macCursorPtr->macCursor = (Handle) GetCCursor(id); + macCursorPtr->type = COLOR; + } + + if (resource == NULL) { + macCursorPtr->macCursor = GetNamedResource('CURS', curName); + macCursorPtr->type = NORMAL; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkGetCursorByName -- + * + * Retrieve a system cursor by name. + * + * Results: + * Returns a new cursor, or NULL on errors. + * + * Side effects: + * Allocates a new cursor. + * + *---------------------------------------------------------------------- + */ + +TkCursor * +TkGetCursorByName( + Tcl_Interp *interp, /* Interpreter to use for error reporting. */ + Tk_Window tkwin, /* Window in which cursor will be used. */ + Tk_Uid string) /* Description of cursor. See manual entry + * for details on legal syntax. */ +{ + struct CursorName *namePtr; + TkMacCursor *macCursorPtr; + + macCursorPtr = (TkMacCursor *) ckalloc(sizeof(TkMacCursor)); + macCursorPtr->info.cursor = (Tk_Cursor) macCursorPtr; + + /* + * To find a cursor we must first determine if it is one of the + * builtin cursors or the standard arrow cursor. Otherwise, we + * attempt to load the cursor as a named Mac resource. + */ + + for (namePtr = cursorNames; namePtr->name != NULL; namePtr++) { + if (strcmp(namePtr->name, string) == 0) { + break; + } + } + + + if (namePtr->name != NULL) { + if (namePtr->id == 5) { + macCursorPtr->macCursor = (Handle) -1; + macCursorPtr->type = ARROW; + } else { + macCursorPtr->macCursor = (Handle) GetCursor(namePtr->id); + macCursorPtr->type = NORMAL; + } + } else { + FindCursorByName(macCursorPtr, string); + + if (macCursorPtr->macCursor == NULL) { + char **argv; + int argc, err; + + /* + * The user may be trying to specify an XCursor with fore + * & back colors. We don't want this to be an error, so pick + * off the first word, and try again. + */ + + err = Tcl_SplitList(interp, string, &argc, &argv); + if (err == TCL_OK ) { + if (argc > 1) { + FindCursorByName(macCursorPtr, argv[0]); + } + + ckfree((char *) argv); + } + } + } + + if (macCursorPtr->macCursor == NULL) { + ckfree((char *)macCursorPtr); + Tcl_AppendResult(interp, "bad cursor spec \"", string, "\"", + (char *) NULL); + return NULL; + } else { + return (TkCursor *) macCursorPtr; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkCreateCursorFromData -- + * + * Creates a cursor from the source and mask bits. + * + * Results: + * Returns a new cursor, or NULL on errors. + * + * Side effects: + * Allocates a new cursor. + * + *---------------------------------------------------------------------- + */ + +TkCursor * +TkCreateCursorFromData( + Tk_Window tkwin, /* Window in which cursor will be used. */ + char *source, /* Bitmap data for cursor shape. */ + char *mask, /* Bitmap data for cursor mask. */ + int width, int height, /* Dimensions of cursor. */ + int xHot, int yHot, /* Location of hot-spot in cursor. */ + XColor fgColor, /* Foreground color for cursor. */ + XColor bgColor) /* Background color for cursor. */ +{ + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TkFreeCursor -- + * + * This procedure is called to release a cursor allocated by + * TkGetCursorByName. + * + * Results: + * None. + * + * Side effects: + * The cursor data structure is deallocated. + * + *---------------------------------------------------------------------- + */ + +void +TkFreeCursor( + TkCursor *cursorPtr) +{ + TkMacCursor *macCursorPtr = (TkMacCursor *) cursorPtr; + + switch (macCursorPtr->type) { + case COLOR: + DisposeCCursor((CCrsrHandle) macCursorPtr->macCursor); + break; + case NORMAL: + ReleaseResource(macCursorPtr->macCursor); + break; + } + + if (macCursorPtr == gCurrentCursor) { + gCurrentCursor = NULL; + } + + ckfree((char *) macCursorPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TkMacInstallCursor -- + * + * Installs either the current cursor as defined by TkpSetCursor + * or a resize cursor as the cursor the Macintosh should currently + * display. + * + * Results: + * None. + * + * Side effects: + * Changes the Macintosh mouse cursor. + * + *---------------------------------------------------------------------- + */ + +void +TkMacInstallCursor( + int resizeOverride) +{ + TkMacCursor *macCursorPtr = gCurrentCursor; + CCrsrHandle ccursor; + CursHandle cursor; + + gResizeOverride = resizeOverride; + + if (resizeOverride) { + cursor = (CursHandle) GetNamedResource('CURS', "\presize"); + SetCursor(*cursor); + } else if (macCursorPtr == NULL || macCursorPtr->type == ARROW) { + SetCursor(&tcl_macQdPtr->arrow); + } else { + switch (macCursorPtr->type) { + case COLOR: + ccursor = (CCrsrHandle) macCursorPtr->macCursor; + SetCCursor(ccursor); + break; + case NORMAL: + cursor = (CursHandle) macCursorPtr->macCursor; + SetCursor(*cursor); + break; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpSetCursor -- + * + * Set the current cursor and install it. + * + * Results: + * None. + * + * Side effects: + * Changes the current cursor. + * + *---------------------------------------------------------------------- + */ + +void +TkpSetCursor( + TkpCursor cursor) +{ + if (cursor == None) { + gCurrentCursor = NULL; + } else { + gCurrentCursor = (TkMacCursor *) cursor; + } + + if (tkMacAppInFront) { + TkMacInstallCursor(gResizeOverride); + } +} diff --git a/mac/tkMacCursors.r b/mac/tkMacCursors.r new file mode 100644 index 0000000..44ad02e --- /dev/null +++ b/mac/tkMacCursors.r @@ -0,0 +1,130 @@ +/* + * tkMacCursors.r -- + * + * This file defines a set of Macintosh cursor resources that + * are only available on the Macintosh platform. + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacCursors.r 1.3 96/01/25 10:24:15 + */ + +/* + * These are resource definitions for Macintosh cursors. + * The are identified and loaded by the "name" of the + * cursor. However, the ids must be unique. + */ + +data 'CURS' (1000, "hand") { + $"0180 1A70 2648 264A 124D 1249 6809 9801" + $"8802 4002 2002 2004 1004 0808 0408 0408" + $"0180 1BF0 3FF8 3FFA 1FFF 1FFF 6FFF FFFF" + $"FFFE 7FFE 3FFE 3FFC 1FFC 0FF8 07F8 07F8" + $"0009 0008" +}; + +data 'CURS' (1002, "bucket") { + $"0000 0000 0600 0980 0940 0B30 0D18 090C" + $"129C 212C 104C 088C 050C 0208 0000 0000" + $"0000 0000 0600 0980 09C0 0BF0 0FF8 0FFC" + $"1FFC 3FEC 1FCC 0F8C 070C 0208 0000 0000" + $"000D 000C" +}; + +data 'CURS' (1003, "cancel") { + $"0000 0000 0000 0000 3180 4A40 4A40 3F80" + $"0A00 3F80 4A40 4A46 3186 0000 0000 0000" + $"0000 0000 0000 3180 7BC0 FFE0 FFE0 7FC0" + $"3F80 7FC0 FFE6 FFEF 7BCF 3186 0000 0000" + $"0008 0005" +}; + +data 'CURS' (1004, "Resize") { + $"FFFF 8001 BF01 A181 A1F9 A18D A18D BF8D" + $"9F8D 880D 880D 880D 8FFD 87FD 8001 FFFF" + $"FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF" + $"FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF" + $"0008 0008" +}; + +data 'CURS' (1005, "eyedrop") { + $"000E 001F 001F 00FF 007E 00B8 0118 0228" + $"0440 0880 1100 2200 4400 4800 B000 4000" + $"000E 001F 001F 00FF 007E 00F8 01F8 03E8" + $"07C0 0F80 1F00 3E00 7C00 7800 F000 4000" + $"000F 0000" +}; + +data 'CURS' (1006, "eyedrop-full") { + $"000E 001F 001F 00FF 007E 00B8 0118 0328" + $"07C0 0F80 1F00 3E00 7C00 7800 F000 4000" + $"000E 001F 001F 00FF 007E 00F8 01F8 03E8" + $"07C0 0F80 1F00 3E00 7C00 7800 F000 4000" + $"000F 0000" +}; + +data 'CURS' (1007, "zoom-in") { + $"0780 1860 2790 5868 5028 A014 AFD4 AFD4" + $"A014 5028 5868 2798 187C 078E 0007 0003" + $"0780 1FE0 3FF0 7878 7038 E01C EFDC EFDC" + $"E01C 7038 7878 3FF8 1FFC 078E 0007 0003" + $"0007 0007" +}; + +data 'CURS' (1008, "zoom-out") { + $"0780 1860 2790 5868 5328 A314 AFD4 AFD4" + $"A314 5328 5868 2798 187C 078E 0007 0003" + $"0780 1FE0 3FF0 7878 7338 E31C EFDC EFDC" + $"E31C 7338 7878 3FF8 1FFC 078E 0007 0003" + $"0007 0007" +}; + +/* + * The following are resource definitions for color + * cursors on the Macintosh. If a color cursor and + * a black & white cursor are both defined with the + * same name preference will be given to the color + * cursors. + */ + +data 'crsr' (1000, "hand") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 0180 1A70 2648 264A 124D 1249" + $"6809 9801 8802 4002 2002 2004 1004 0808" + $"0408 0408 0180 1BF0 3FF8 3FFA 1FFF 1FFF" + $"6FFF FFFF FFFE 7FFE 3FFE 3FFC 1FFC 0FF8" + $"07F8 07F8 0008 0008 0000 0000 0000 0000" + $"0000 0000 8004 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0002 0001 0002 0000 0000 0000 00D2 0000" + $"0000 0003 C000 03CD 7F00 0D7D 75C0 0D7D" + $"75CC 035D 75F7 035D 75D7 3CD5 55D7 D7D5" + $"5557 D5D5 555C 3555 555C 0D55 555C 0D55" + $"5570 0355 5570 00D5 55C0 0035 55C0 0035" + $"55C0 0000 0000 0000 0002 0000 FFFF FFFF" + $"FFFF 0001 FFFF CCCC 9999 0003 0000 0000" + $"0000" +}; + +data 'crsr' (1001, "fist") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0DB0 124C" + $"100A 0802 1802 2002 2002 2004 1004 0808" + $"0408 0408 0000 0000 0000 0000 0DB0 1FFC" + $"1FFE 0FFE 1FFE 3FFE 3FFE 3FFC 1FFC 0FF8" + $"07F8 07F8 0008 0008 0000 0000 0000 0000" + $"0000 0000 8004 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0002 0001 0002 0000 0000 0000 00D2 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 00F3 CF00 035D 75F0 0355 55DC 00D5" + $"555C 03D5 555C 0D55 555C 0D55 555C 0D55" + $"5570 0355 5570 00D5 55C0 0035 55C0 0035" + $"55C0 0000 0000 0000 0002 0000 FFFF FFFF" + $"FFFF 0001 FFFF CCCC 9999 0003 0000 0000" + $"0000" +}; + diff --git a/mac/tkMacDefault.h b/mac/tkMacDefault.h new file mode 100644 index 0000000..372d89b --- /dev/null +++ b/mac/tkMacDefault.h @@ -0,0 +1,461 @@ +/* + * tkMacDefault.h -- + * + * This file defines the defaults for all options for all of + * the Tk widgets. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacDefault.h 1.48 97/10/09 17:45:04 + */ + +#ifndef _TKMACDEFAULT +#define _TKMACDEFAULT + +/* + * The definitions below provide symbolic names for the default colors. + * NORMAL_BG - Normal background color. + * ACTIVE_BG - Background color when widget is active. + * SELECT_BG - Background color for selected text. + * SELECT_FG - Foreground color for selected text. + * TROUGH - Background color for troughs in scales and scrollbars. + * INDICATOR - Color for indicator when button is selected. + * DISABLED - Foreground color when widget is disabled. + */ + +#define BLACK "Black" +#define WHITE "White" + +#define NORMAL_BG "systemWindowBody" +#define ACTIVE_BG "#ececec" +#define SELECT_BG "systemHighlight" +#define SELECT_FG "systemHighlightText" +#define TROUGH "#c3c3c3" +#define INDICATOR "#b03060" +#define DISABLED "#a3a3a3" + +/* + * Defaults for labels, buttons, checkbuttons, and radiobuttons: + */ + +#define DEF_BUTTON_ANCHOR "center" +#define DEF_BUTTON_ACTIVE_BG_COLOR "systemButtonText" +#define DEF_BUTTON_ACTIVE_BG_MONO BLACK +#define DEF_BUTTON_ACTIVE_FG_COLOR "systemButtonFace" +#define DEF_CHKRAD_ACTIVE_FG_COLOR DEF_BUTTON_ACTIVE_FG_COLOR +#define DEF_BUTTON_ACTIVE_FG_MONO WHITE +#define DEF_BUTTON_BG_COLOR "systemButtonFace" +#define DEF_BUTTON_BG_MONO WHITE +#define DEF_BUTTON_BITMAP "" +#define DEF_BUTTON_BORDER_WIDTH "2" +#define DEF_BUTTON_CURSOR "" +#define DEF_BUTTON_COMMAND "" +#define DEF_BUTTON_DEFAULT "disabled" +#define DEF_BUTTON_DISABLED_FG_COLOR DISABLED +#define DEF_BUTTON_DISABLED_FG_MONO "" +#define DEF_BUTTON_FG "systemButtonText" +#define DEF_CHKRAD_FG DEF_BUTTON_FG +#define DEF_BUTTON_FONT "system" +#define DEF_BUTTON_HEIGHT "0" +#define DEF_BUTTON_HIGHLIGHT_BG NORMAL_BG +#define DEF_BUTTON_HIGHLIGHT "systemButtonFrame" +#define DEF_LABEL_HIGHLIGHT_WIDTH "0" +#define DEF_BUTTON_HIGHLIGHT_WIDTH "4" +#define DEF_BUTTON_IMAGE (char *) NULL +#define DEF_BUTTON_INDICATOR "1" +#define DEF_BUTTON_JUSTIFY "center" +#define DEF_BUTTON_OFF_VALUE "0" +#define DEF_BUTTON_ON_VALUE "1" +#define DEF_BUTTON_PADX "7" +#define DEF_LABCHKRAD_PADX "1" +#define DEF_BUTTON_PADY "3" +#define DEF_LABCHKRAD_PADY "1" +#define DEF_BUTTON_RELIEF "flat" +#define DEF_LABCHKRAD_RELIEF "flat" +#define DEF_BUTTON_SELECT_COLOR INDICATOR +#define DEF_BUTTON_SELECT_MONO BLACK +#define DEF_BUTTON_SELECT_IMAGE (char *) NULL +#define DEF_BUTTON_STATE "normal" +#define DEF_LABEL_TAKE_FOCUS "0" +#define DEF_BUTTON_TAKE_FOCUS (char *) NULL +#define DEF_BUTTON_TEXT "" +#define DEF_BUTTON_TEXT_VARIABLE "" +#define DEF_BUTTON_UNDERLINE "-1" +#define DEF_BUTTON_VALUE "" +#define DEF_BUTTON_WIDTH "0" +#define DEF_BUTTON_WRAP_LENGTH "0" +#define DEF_RADIOBUTTON_VARIABLE "selectedButton" +#define DEF_CHECKBUTTON_VARIABLE "" + +/* + * Defaults for canvases: + */ + +#define DEF_CANVAS_BG_COLOR NORMAL_BG +#define DEF_CANVAS_BG_MONO WHITE +#define DEF_CANVAS_BORDER_WIDTH "0" +#define DEF_CANVAS_CLOSE_ENOUGH "1" +#define DEF_CANVAS_CONFINE "1" +#define DEF_CANVAS_CURSOR "" +#define DEF_CANVAS_HEIGHT "7c" +#define DEF_CANVAS_HIGHLIGHT_BG NORMAL_BG +#define DEF_CANVAS_HIGHLIGHT BLACK +#define DEF_CANVAS_HIGHLIGHT_WIDTH "3" +#define DEF_CANVAS_INSERT_BG BLACK +#define DEF_CANVAS_INSERT_BD_COLOR "0" +#define DEF_CANVAS_INSERT_BD_MONO "0" +#define DEF_CANVAS_INSERT_OFF_TIME "300" +#define DEF_CANVAS_INSERT_ON_TIME "600" +#define DEF_CANVAS_INSERT_WIDTH "2" +#define DEF_CANVAS_RELIEF "flat" +#define DEF_CANVAS_SCROLL_REGION "" +#define DEF_CANVAS_SELECT_COLOR SELECT_BG +#define DEF_CANVAS_SELECT_MONO BLACK +#define DEF_CANVAS_SELECT_BD_COLOR "1" +#define DEF_CANVAS_SELECT_BD_MONO "0" +#define DEF_CANVAS_SELECT_FG_COLOR BLACK +#define DEF_CANVAS_SELECT_FG_MONO WHITE +#define DEF_CANVAS_TAKE_FOCUS (char *) NULL +#define DEF_CANVAS_WIDTH "10c" +#define DEF_CANVAS_X_SCROLL_CMD "" +#define DEF_CANVAS_X_SCROLL_INCREMENT "0" +#define DEF_CANVAS_Y_SCROLL_CMD "" +#define DEF_CANVAS_Y_SCROLL_INCREMENT "0" + +/* + * Defaults for entries: + */ + +#define DEF_ENTRY_BG_COLOR NORMAL_BG +#define DEF_ENTRY_BG_MONO WHITE +/* #define DEF_ENTRY_BORDER_WIDTH "2" */ +#define DEF_ENTRY_BORDER_WIDTH "1" +#define DEF_ENTRY_CURSOR "xterm" +#define DEF_ENTRY_EXPORT_SELECTION "1" +#define DEF_ENTRY_FONT "Helvetica 12" +#define DEF_ENTRY_FG BLACK +#define DEF_ENTRY_HIGHLIGHT_BG NORMAL_BG +#define DEF_ENTRY_HIGHLIGHT BLACK +/* #define DEF_ENTRY_HIGHLIGHT_WIDTH "3" */ +#define DEF_ENTRY_HIGHLIGHT_WIDTH "0" +#define DEF_ENTRY_INSERT_BG BLACK +#define DEF_ENTRY_INSERT_BD_COLOR "0" +#define DEF_ENTRY_INSERT_BD_MONO "0" +#define DEF_ENTRY_INSERT_OFF_TIME "300" +#define DEF_ENTRY_INSERT_ON_TIME "600" +/* #define DEF_ENTRY_INSERT_WIDTH "2" */ +#define DEF_ENTRY_INSERT_WIDTH "1" +#define DEF_ENTRY_JUSTIFY "left" +/* #define DEF_ENTRY_RELIEF "sunken" */ +#define DEF_ENTRY_RELIEF "solid" +#define DEF_ENTRY_SCROLL_COMMAND "" +#define DEF_ENTRY_SELECT_COLOR SELECT_BG +#define DEF_ENTRY_SELECT_MONO BLACK +#define DEF_ENTRY_SELECT_BD_COLOR "1" +#define DEF_ENTRY_SELECT_BD_MONO "0" +#define DEF_ENTRY_SELECT_FG_COLOR SELECT_FG +#define DEF_ENTRY_SELECT_FG_MONO WHITE +#define DEF_ENTRY_SHOW (char *) NULL +#define DEF_ENTRY_STATE "normal" +#define DEF_ENTRY_TAKE_FOCUS (char *) NULL +#define DEF_ENTRY_TEXT_VARIABLE "" +#define DEF_ENTRY_WIDTH "20" + +/* + * Defaults for frames: + */ + +#define DEF_FRAME_BG_COLOR NORMAL_BG +#define DEF_FRAME_BG_MONO WHITE +#define DEF_FRAME_BORDER_WIDTH "0" +#define DEF_FRAME_CLASS "Frame" +#define DEF_FRAME_COLORMAP "" +#define DEF_FRAME_CONTAINER "0" +#define DEF_FRAME_CURSOR "" +#define DEF_FRAME_HEIGHT "0" +#define DEF_FRAME_HIGHLIGHT_BG NORMAL_BG +#define DEF_FRAME_HIGHLIGHT BLACK +#define DEF_FRAME_HIGHLIGHT_WIDTH "0" +#define DEF_FRAME_RELIEF "flat" +#define DEF_FRAME_TAKE_FOCUS "0" +#define DEF_FRAME_USE "" +#define DEF_FRAME_VISUAL "" +#define DEF_FRAME_WIDTH "0" + +/* + * Defaults for listboxes: + */ + +#define DEF_LISTBOX_BG_COLOR NORMAL_BG +#define DEF_LISTBOX_BG_MONO WHITE +#define DEF_LISTBOX_BORDER_WIDTH "1" +#define DEF_LISTBOX_CURSOR "" +#define DEF_LISTBOX_EXPORT_SELECTION "1" +#define DEF_LISTBOX_FONT "application" +#define DEF_LISTBOX_FG BLACK +#define DEF_LISTBOX_HEIGHT "10" +#define DEF_LISTBOX_HIGHLIGHT_BG NORMAL_BG +#define DEF_LISTBOX_HIGHLIGHT BLACK +#define DEF_LISTBOX_HIGHLIGHT_WIDTH "0" +#define DEF_LISTBOX_RELIEF "solid" +#define DEF_LISTBOX_SCROLL_COMMAND "" +#define DEF_LISTBOX_SELECT_COLOR SELECT_BG +#define DEF_LISTBOX_SELECT_MONO BLACK +#define DEF_LISTBOX_SELECT_BD "0" +#define DEF_LISTBOX_SELECT_FG_COLOR SELECT_FG +#define DEF_LISTBOX_SELECT_FG_MONO WHITE +#define DEF_LISTBOX_SELECT_MODE "browse" +#define DEF_LISTBOX_SET_GRID "0" +#define DEF_LISTBOX_TAKE_FOCUS (char *) NULL +#define DEF_LISTBOX_WIDTH "20" + +/* + * Defaults for individual entries of menus: + */ + +#define DEF_MENU_ENTRY_ACTIVE_BG (char *) NULL +#define DEF_MENU_ENTRY_ACTIVE_FG (char *) NULL +#define DEF_MENU_ENTRY_ACCELERATOR (char *) NULL +#define DEF_MENU_ENTRY_BG (char *) NULL +#define DEF_MENU_ENTRY_BITMAP None +#define DEF_MENU_ENTRY_COLUMN_BREAK "0" +#define DEF_MENU_ENTRY_COMMAND (char *) NULL +#define DEF_MENU_ENTRY_FG (char *) NULL +#define DEF_MENU_ENTRY_FONT (char *) NULL +#define DEF_MENU_ENTRY_HIDE_MARGIN "0" +#define DEF_MENU_ENTRY_IMAGE (char *) NULL +#define DEF_MENU_ENTRY_INDICATOR "1" +#define DEF_MENU_ENTRY_LABEL (char *) NULL +#define DEF_MENU_ENTRY_MENU (char *) NULL +#define DEF_MENU_ENTRY_OFF_VALUE "0" +#define DEF_MENU_ENTRY_ON_VALUE "1" +#define DEF_MENU_ENTRY_SELECT_IMAGE (char *) NULL +#define DEF_MENU_ENTRY_STATE "normal" +#define DEF_MENU_ENTRY_VALUE (char *) NULL +#define DEF_MENU_ENTRY_CHECK_VARIABLE (char *) NULL +#define DEF_MENU_ENTRY_RADIO_VARIABLE "selectedButton" +#define DEF_MENU_ENTRY_SELECT (char *) NULL +#define DEF_MENU_ENTRY_UNDERLINE "-1" + +/* + * Defaults for menus overall: + */ + +#define DEF_MENU_ACTIVE_BG_COLOR "SystemMenuActive" +#define DEF_MENU_ACTIVE_BG_MONO BLACK +#define DEF_MENU_ACTIVE_BORDER_WIDTH "0" +#define DEF_MENU_ACTIVE_FG_COLOR "SystemMenuActiveText" +#define DEF_MENU_ACTIVE_FG_MONO WHITE +#define DEF_MENU_BG_COLOR "SystemMenu" +#define DEF_MENU_BG_MONO WHITE +#define DEF_MENU_BORDER_WIDTH "0" +#define DEF_MENU_CURSOR "arrow" +#define DEF_MENU_DISABLED_FG_COLOR "SystemMenuDisabled" +#define DEF_MENU_DISABLED_FG_MONO "" +#define DEF_MENU_FONT "system" +#define DEF_MENU_FG "SystemMenuText" +#define DEF_MENU_POST_COMMAND "" +#define DEF_MENU_RELIEF "flat" +#define DEF_MENU_SELECT_COLOR "SystemMenuActive" +#define DEF_MENU_SELECT_MONO BLACK +#define DEF_MENU_TAKE_FOCUS "0" +#define DEF_MENU_TEAROFF "1" +#define DEF_MENU_TEAROFF_CMD (char *) NULL +#define DEF_MENU_TITLE "" +#define DEF_MENU_TYPE "normal" + +/* + * Defaults for menubuttons: + */ + +#define DEF_MENUBUTTON_ANCHOR "center" +#define DEF_MENUBUTTON_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_MENUBUTTON_ACTIVE_BG_MONO BLACK +#define DEF_MENUBUTTON_ACTIVE_FG_COLOR BLACK +#define DEF_MENUBUTTON_ACTIVE_FG_MONO WHITE +#define DEF_MENUBUTTON_BG_COLOR NORMAL_BG +#define DEF_MENUBUTTON_BG_MONO WHITE +#define DEF_MENUBUTTON_BITMAP "" +#define DEF_MENUBUTTON_BORDER_WIDTH "2" +#define DEF_MENUBUTTON_CURSOR "" +#define DEF_MENUBUTTON_DIRECTION "below" +#define DEF_MENUBUTTON_DISABLED_FG_COLOR DISABLED +#define DEF_MENUBUTTON_DISABLED_FG_MONO "" +#define DEF_MENUBUTTON_FONT "system" +#define DEF_MENUBUTTON_FG BLACK +#define DEF_MENUBUTTON_HEIGHT "0" +#define DEF_MENUBUTTON_HIGHLIGHT_BG NORMAL_BG +#define DEF_MENUBUTTON_HIGHLIGHT BLACK +#define DEF_MENUBUTTON_HIGHLIGHT_WIDTH "0" +#define DEF_MENUBUTTON_IMAGE (char *) NULL +#define DEF_MENUBUTTON_INDICATOR "0" +/* #define DEF_MENUBUTTON_JUSTIFY "center" */ +#define DEF_MENUBUTTON_JUSTIFY "left" +#define DEF_MENUBUTTON_MENU "" +#define DEF_MENUBUTTON_PADX "4p" +#define DEF_MENUBUTTON_PADY "3p" +#define DEF_MENUBUTTON_RELIEF "flat" +#define DEF_MENUBUTTON_STATE "normal" +#define DEF_MENUBUTTON_TAKE_FOCUS "0" +#define DEF_MENUBUTTON_TEXT "" +#define DEF_MENUBUTTON_TEXT_VARIABLE "" +#define DEF_MENUBUTTON_UNDERLINE "-1" +#define DEF_MENUBUTTON_WIDTH "0" +#define DEF_MENUBUTTON_WRAP_LENGTH "0" + +/* + * Defaults for messages: + */ + +#define DEF_MESSAGE_ANCHOR "center" +#define DEF_MESSAGE_ASPECT "150" +#define DEF_MESSAGE_BG_COLOR NORMAL_BG +#define DEF_MESSAGE_BG_MONO WHITE +#define DEF_MESSAGE_BORDER_WIDTH "2" +#define DEF_MESSAGE_CURSOR "" +#define DEF_MESSAGE_FG BLACK +#define DEF_MESSAGE_FONT "system" +#define DEF_MESSAGE_HIGHLIGHT_BG NORMAL_BG +#define DEF_MESSAGE_HIGHLIGHT BLACK +#define DEF_MESSAGE_HIGHLIGHT_WIDTH "0" +#define DEF_MESSAGE_JUSTIFY "left" +#define DEF_MESSAGE_PADX "-1" +#define DEF_MESSAGE_PADY "-1" +#define DEF_MESSAGE_RELIEF "flat" +#define DEF_MESSAGE_TAKE_FOCUS "0" +#define DEF_MESSAGE_TEXT "" +#define DEF_MESSAGE_TEXT_VARIABLE "" +#define DEF_MESSAGE_WIDTH "0" + +/* + * Defaults for scales: + */ + +#define DEF_SCALE_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_SCALE_ACTIVE_BG_MONO BLACK +#define DEF_SCALE_BG_COLOR NORMAL_BG +#define DEF_SCALE_BG_MONO WHITE +#define DEF_SCALE_BIG_INCREMENT "0" +#define DEF_SCALE_BORDER_WIDTH "2" +#define DEF_SCALE_COMMAND "" +#define DEF_SCALE_CURSOR "" +#define DEF_SCALE_DIGITS "0" +#define DEF_SCALE_FONT "system" +#define DEF_SCALE_FG_COLOR BLACK +#define DEF_SCALE_FG_MONO BLACK +#define DEF_SCALE_FROM "0" +#define DEF_SCALE_HIGHLIGHT_BG NORMAL_BG +#define DEF_SCALE_HIGHLIGHT BLACK +#define DEF_SCALE_HIGHLIGHT_WIDTH "0" +#define DEF_SCALE_LABEL "" +#define DEF_SCALE_LENGTH "100" +#define DEF_SCALE_ORIENT "vertical" +#define DEF_SCALE_RELIEF "flat" +#define DEF_SCALE_REPEAT_DELAY "300" +#define DEF_SCALE_REPEAT_INTERVAL "100" +#define DEF_SCALE_RESOLUTION "1" +#define DEF_SCALE_TROUGH_COLOR TROUGH +#define DEF_SCALE_TROUGH_MONO WHITE +#define DEF_SCALE_SHOW_VALUE "1" +#define DEF_SCALE_SLIDER_LENGTH "30" +#define DEF_SCALE_SLIDER_RELIEF "raised" +#define DEF_SCALE_STATE "normal" +#define DEF_SCALE_TAKE_FOCUS (char *) NULL +#define DEF_SCALE_TICK_INTERVAL "0" +#define DEF_SCALE_TO "100" +#define DEF_SCALE_VARIABLE "" +#define DEF_SCALE_WIDTH "15" + +/* + * Defaults for scrollbars: + */ + +#define DEF_SCROLLBAR_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_SCROLLBAR_ACTIVE_BG_MONO BLACK +#define DEF_SCROLLBAR_ACTIVE_RELIEF "raised" +#define DEF_SCROLLBAR_BG_COLOR NORMAL_BG +#define DEF_SCROLLBAR_BG_MONO WHITE +/* #define DEF_SCROLLBAR_BORDER_WIDTH "2" */ +#define DEF_SCROLLBAR_BORDER_WIDTH "0" +#define DEF_SCROLLBAR_COMMAND "" +#define DEF_SCROLLBAR_CURSOR "" +#define DEF_SCROLLBAR_EL_BORDER_WIDTH "-1" +#define DEF_SCROLLBAR_HIGHLIGHT_BG NORMAL_BG +#define DEF_SCROLLBAR_HIGHLIGHT BLACK +/* #define DEF_SCROLLBAR_HIGHLIGHT_WIDTH "2" */ +#define DEF_SCROLLBAR_HIGHLIGHT_WIDTH "0" +#define DEF_SCROLLBAR_JUMP "0" +#define DEF_SCROLLBAR_ORIENT "vertical" +/*#define DEF_SCROLLBAR_RELIEF "sunken" */ +#define DEF_SCROLLBAR_RELIEF "flat" +#define DEF_SCROLLBAR_REPEAT_DELAY "300" +#define DEF_SCROLLBAR_REPEAT_INTERVAL "100" +#define DEF_SCROLLBAR_TAKE_FOCUS (char *) NULL +#define DEF_SCROLLBAR_TROUGH_COLOR TROUGH +#define DEF_SCROLLBAR_TROUGH_MONO WHITE +/*#define DEF_SCROLLBAR_WIDTH "15" */ +#define DEF_SCROLLBAR_WIDTH "16" + +/* + * Defaults for texts: + */ + +#define DEF_TEXT_BG_COLOR NORMAL_BG +#define DEF_TEXT_BG_MONO WHITE +#define DEF_TEXT_BORDER_WIDTH "0" +#define DEF_TEXT_CURSOR "xterm" +#define DEF_TEXT_FG BLACK +#define DEF_TEXT_EXPORT_SELECTION "1" +#define DEF_TEXT_FONT "Courier 12" +#define DEF_TEXT_HEIGHT "24" +#define DEF_TEXT_HIGHLIGHT_BG NORMAL_BG +#define DEF_TEXT_HIGHLIGHT BLACK +#define DEF_TEXT_HIGHLIGHT_WIDTH "3" +#define DEF_TEXT_INSERT_BG BLACK +#define DEF_TEXT_INSERT_BD_COLOR "0" +#define DEF_TEXT_INSERT_BD_MONO "0" +#define DEF_TEXT_INSERT_OFF_TIME "300" +#define DEF_TEXT_INSERT_ON_TIME "600" +#define DEF_TEXT_INSERT_WIDTH "1" +#define DEF_TEXT_PADX "1" +#define DEF_TEXT_PADY "1" +#define DEF_TEXT_RELIEF "flat" +#define DEF_TEXT_SELECT_COLOR SELECT_BG +#define DEF_TEXT_SELECT_MONO BLACK +#define DEF_TEXT_SELECT_BD_COLOR "1" +#define DEF_TEXT_SELECT_BD_MONO "0" +#define DEF_TEXT_SELECT_FG_COLOR SELECT_FG +#define DEF_TEXT_SELECT_FG_MONO WHITE +#define DEF_TEXT_SELECT_RELIEF "solid" +#define DEF_TEXT_SET_GRID "0" +#define DEF_TEXT_SPACING1 "0" +#define DEF_TEXT_SPACING2 "0" +#define DEF_TEXT_SPACING3 "0" +#define DEF_TEXT_STATE "normal" +#define DEF_TEXT_TABS "" +#define DEF_TEXT_TAKE_FOCUS (char *) NULL +#define DEF_TEXT_WIDTH "80" +#define DEF_TEXT_WRAP "char" +#define DEF_TEXT_XSCROLL_COMMAND "" +#define DEF_TEXT_YSCROLL_COMMAND "" + +/* + * Defaults for canvas text: + */ + +#define DEF_CANVTEXT_FONT "Helvetica 12" + +/* + * Defaults for toplevels (most of the defaults for frames also apply + * to toplevels): + */ + +#define DEF_TOPLEVEL_CLASS "Toplevel" +#define DEF_TOPLEVEL_MENU "" +#define DEF_TOPLEVEL_SCREEN "" + +#endif /* _TKMACDEFAULT */ diff --git a/mac/tkMacDialog.c b/mac/tkMacDialog.c new file mode 100644 index 0000000..43d11a5 --- /dev/null +++ b/mac/tkMacDialog.c @@ -0,0 +1,939 @@ +/* + * tkMacDialog.c -- + * + * Contains the Mac implementation of the common dialog boxes. + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacDialog.c 1.12 96/12/03 11:15:12 + * + */ + +#include <Gestalt.h> +#include <Aliases.h> +#include <Errors.h> +#include <Strings.h> +#include <MoreFiles.h> +#include <MoreFilesExtras.h> +#include <StandardFile.h> +#include <ColorPicker.h> +#include <Lowmem.h> +#include "tkPort.h" +#include "tkInt.h" +#include "tclMacInt.h" +#include "tkFileFilter.h" + +/* + * The following are ID's for resources that are defined in tkMacResource.r + */ +#define OPEN_BOX 130 +#define OPEN_POPUP 131 +#define OPEN_MENU 132 +#define OPEN_POPUP_ITEM 10 + +#define SAVE_FILE 0 +#define OPEN_FILE 1 + +#define MATCHED 0 +#define UNMATCHED 1 + +/* + * The following structure is used in the GetFileName() function. It stored + * information about the file dialog and the file filters. + */ +typedef struct _OpenFileData { + Tcl_Interp * interp; + char * initialFile; /* default file to appear in the + * save dialog */ + char * defExt; /* default extension (not used on the + * Mac) */ + FileFilterList fl; /* List of file filters. */ + SInt16 curType; /* The filetype currently being + * listed */ + int isOpen; /* True if this is an Open dialog, + * false if it is a Save dialog. */ + MenuHandle menu; /* Handle of the menu in the popup*/ + short dialogId; /* resource ID of the dialog */ + int popupId; /* resource ID of the popup */ + short popupItem; /* item number of the popup in the + * dialog */ + int usePopup; /* True if we show the popup menu (this + * is an open operation and the + * -filetypes option is set) + */ +} OpenFileData; + +static pascal Boolean FileFilterProc _ANSI_ARGS_((CInfoPBPtr pb, + void *myData)); +static int GetFileName _ANSI_ARGS_ (( + ClientData clientData, Tcl_Interp *interp, + int argc, char **argv, int isOpen )); +static Boolean MatchOneType _ANSI_ARGS_((CInfoPBPtr pb, + OpenFileData * myDataPtr, FileFilter * filterPtr)); +static pascal short OpenHookProc _ANSI_ARGS_((short item, + DialogPtr theDialog, OpenFileData * myDataPtr)); +static int ParseFileDlgArgs _ANSI_ARGS_ ((Tcl_Interp * interp, + OpenFileData * myDataPtr, int argc, char ** argv, + int isOpen)); + +/* + * Filter and hook functions used by the tk_getOpenFile and tk_getSaveFile + * commands. + */ + +static FileFilterYDUPP openFilter = NULL; +static DlgHookYDUPP openHook = NULL; +static DlgHookYDUPP saveHook = NULL; + + +/* + *---------------------------------------------------------------------- + * + * EvalArgv -- + * + * Invokes the Tcl procedure with the arguments. argv[0] is set by + * the caller of this function. It may be different than cmdName. + * The TCL command will see argv[0], not cmdName, as its name if it + * invokes [lindex [info level 0] 0] + * + * Results: + * TCL_ERROR if the command does not exist and cannot be autoloaded. + * Otherwise, return the result of the evaluation of the command. + * + * Side effects: + * The command may be autoloaded. + * + *---------------------------------------------------------------------- + */ + +static int +EvalArgv( + Tcl_Interp *interp, /* Current interpreter. */ + char * cmdName, /* Name of the TCL command to call */ + int argc, /* Number of arguments. */ + char **argv) /* Argument strings. */ +{ + Tcl_CmdInfo cmdInfo; + + if (!Tcl_GetCommandInfo(interp, cmdName, &cmdInfo)) { + char * cmdArgv[2]; + + /* + * This comand is not in the interpreter yet -- looks like we + * have to auto-load it + */ + if (!Tcl_GetCommandInfo(interp, "auto_load", &cmdInfo)) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "cannot execute command \"auto_load\"", + NULL); + return TCL_ERROR; + } + + cmdArgv[0] = "auto_load"; + cmdArgv[1] = cmdName; + + if ((*cmdInfo.proc)(cmdInfo.clientData, interp, 2, cmdArgv)!= TCL_OK){ + return TCL_ERROR; + } + + if (!Tcl_GetCommandInfo(interp, cmdName, &cmdInfo)) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "cannot auto-load command \"", + cmdName, "\"",NULL); + return TCL_ERROR; + } + } + + return (*cmdInfo.proc)(cmdInfo.clientData, interp, argc, argv); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_ChooseColorCmd -- + * + * This procedure implements the color dialog box for the Mac + * platform. See the user documentation for details on what it + * does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_ChooseColorCmd( + ClientData clientData, /* Main window associated with interpreter. */ + Tcl_Interp *interp, /* Current interpreter. */ + int argc, /* Number of arguments. */ + char **argv) /* Argument strings. */ +{ + Tk_Window parent = Tk_MainWindow(interp); + char * colorStr = NULL; + XColor * colorPtr = NULL; + char * title = "Choose a color:"; + int i, version; + long response = 0; + OSErr err = noErr; + char buff[40]; + static RGBColor in; + static inited = 0; + + /* + * Use the gestalt manager to determine how to bring + * up the color picker. If versin 2.0 isn't available + * we can assume version 1.0 is available as it comes with + * Color Quickdraw which Tk requires to run at all. + */ + + err = Gestalt(gestaltColorPicker, &response); + if ((err == noErr) || (response == 0x0200L)) { + version = 2; + } else { + version = 1; + } + + for (i=1; i<argc; i+=2) { + int v = i+1; + int len = strlen(argv[i]); + + if (strncmp(argv[i], "-initialcolor", len)==0) { + if (v==argc) {goto arg_missing;} + + colorStr = argv[v]; + } else if (strncmp(argv[i], "-parent", len)==0) { + if (v==argc) {goto arg_missing;} + + parent=Tk_NameToWindow(interp, argv[v], Tk_MainWindow(interp)); + if (parent == NULL) { + return TCL_ERROR; + } + } else if (strncmp(argv[i], "-title", len)==0) { + if (v==argc) {goto arg_missing;} + + title = argv[v]; + } else { + Tcl_AppendResult(interp, "unknown option \"", + argv[i], "\", must be -initialcolor, -parent or -title", + NULL); + return TCL_ERROR; + } + } + + if (colorStr) { + colorPtr = Tk_GetColor(interp, parent, colorStr); + if (colorPtr == NULL) { + return TCL_ERROR; + } + } + + if (!inited) { + inited = 1; + in.red = 0xffff; + in.green = 0xffff; + in.blue = 0xffff; + } + if (colorPtr) { + in.red = colorPtr->red; + in.green = colorPtr->green; + in.blue = colorPtr->blue; + } + + if (version == 1) { + /* + * Use version 1.0 of the color picker + */ + + RGBColor out; + Str255 prompt; + Point point = {-1, -1}; + + prompt[0] = strlen(title); + strncpy((char*) prompt+1, title, 255); + + if (GetColor(point, prompt, &in, &out)) { + /* + * user selected a color + */ + sprintf(buff, "#%02x%02x%02x", out.red >> 8, out.green >> 8, + out.blue >> 8); + Tcl_SetResult(interp, buff, TCL_VOLATILE); + + /* + * Save it for the next time + */ + in.red = out.red; + in.green = out.green; + in.blue = out.blue; + } else { + Tcl_ResetResult(interp); + } + } else { + /* + * Version 2.0 of the color picker is available. Let's use it + */ + ColorPickerInfo cpinfo; + + cpinfo.theColor.profile = 0L; + cpinfo.theColor.color.rgb.red = in.red; + cpinfo.theColor.color.rgb.green = in.green; + cpinfo.theColor.color.rgb.blue = in.blue; + cpinfo.dstProfile = 0L; + cpinfo.flags = CanModifyPalette | CanAnimatePalette; + cpinfo.placeWhere = kDeepestColorScreen; + cpinfo.pickerType = 0L; + cpinfo.eventProc = NULL; + cpinfo.colorProc = NULL; + cpinfo.colorProcData = NULL; + + cpinfo.prompt[0] = strlen(title); + strncpy((char*)cpinfo.prompt+1, title, 255); + + if ((PickColor(&cpinfo) == noErr) && cpinfo.newColorChosen) { + sprintf(buff, "#%02x%02x%02x", + cpinfo.theColor.color.rgb.red >> 8, + cpinfo.theColor.color.rgb.green >> 8, + cpinfo.theColor.color.rgb.blue >> 8); + Tcl_SetResult(interp, buff, TCL_VOLATILE); + + in.blue = cpinfo.theColor.color.rgb.red; + in.green = cpinfo.theColor.color.rgb.green; + in.blue = cpinfo.theColor.color.rgb.blue; + } else { + Tcl_ResetResult(interp); + } + } + + if (colorPtr) { + Tk_FreeColor(colorPtr); + } + + return TCL_OK; + + arg_missing: + Tcl_AppendResult(interp, "value for \"", argv[argc-1], "\" missing", + NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetOpenFileCmd -- + * + * This procedure implements the "open file" dialog box for the + * Mac platform. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See user documentation. + *---------------------------------------------------------------------- + */ + +int +Tk_GetOpenFileCmd( + ClientData clientData, /* Main window associated with interpreter. */ + Tcl_Interp *interp, /* Current interpreter. */ + int argc, /* Number of arguments. */ + char **argv) /* Argument strings. */ +{ + return GetFileName(clientData, interp, argc, argv, OPEN_FILE); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetSaveFileCmd -- + * + * Same as Tk_GetOpenFileCmd but opens a "save file" dialog box + * instead + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See user documentation. + *---------------------------------------------------------------------- + */ + +int +Tk_GetSaveFileCmd( + ClientData clientData, /* Main window associated with interpreter. */ + Tcl_Interp *interp, /* Current interpreter. */ + int argc, /* Number of arguments. */ + char **argv) /* Argument strings. */ +{ + return GetFileName(clientData, interp, argc, argv, SAVE_FILE); +} + +/* + *---------------------------------------------------------------------- + * + * GetFileName -- + * + * Calls the Mac file dialog functions for the user to choose a + * file to or save. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * If the user selects a file, the native pathname of the file + * is returned in interp->result. Otherwise an empty string + * is returned in interp->result. + * + *---------------------------------------------------------------------- + */ + +static int +GetFileName( + ClientData clientData, /* Main window associated with interpreter. */ + Tcl_Interp *interp, /* Current interpreter. */ + int argc, /* Number of arguments. */ + char **argv, /* Argument strings. */ + int isOpen) /* true if we should call GetOpenFileName(), + * false if we should call GetSaveFileName() */ +{ + int code = TCL_OK; + int i; + OpenFileData myData, *myDataPtr; + StandardFileReply reply; + Point mypoint; + Str255 str; + + myDataPtr = &myData; + + if (openFilter == NULL) { + openFilter = NewFileFilterYDProc(FileFilterProc); + openHook = NewDlgHookYDProc(OpenHookProc); + saveHook = NewDlgHookYDProc(OpenHookProc); + } + + /* + * 1. Parse the arguments. + */ + if (ParseFileDlgArgs(interp, myDataPtr, argc, argv, isOpen) + != TCL_OK) { + return TCL_ERROR; + } + + /* + * 2. Set the items in the file types popup. + */ + + /* + * Delete all the entries inside the popup menu, in case there's any + * left overs from previous invocation of this command + */ + + if (myDataPtr->usePopup) { + FileFilter * filterPtr; + + for (i=CountMItems(myDataPtr->menu); i>0; i--) { + /* + * The item indices are one based. Also, if we delete from + * the beginning, the items may be re-numbered. So we + * delete from the end + */ + DeleteMenuItem(myDataPtr->menu, i); + } + + if (myDataPtr->fl.filters) { + for (filterPtr=myDataPtr->fl.filters; filterPtr; + filterPtr=filterPtr->next) { + strncpy((char*)str+1, filterPtr->name, 254); + str[0] = strlen(filterPtr->name); + AppendMenu(myDataPtr->menu, (ConstStr255Param) str); + } + } else { + myDataPtr->usePopup = 0; + } + } + + /* + * 3. Call the toolbox file dialog function. + */ + SetPt(&mypoint, -1, -1); + TkpSetCursor(NULL); + + if (myDataPtr->isOpen) { + if (myDataPtr->usePopup) { + CustomGetFile(openFilter, (short) -1, NULL, &reply, + myDataPtr->dialogId, + mypoint, openHook, NULL, NULL, NULL, (void*)myDataPtr); + } else { + StandardGetFile(NULL, -1, NULL, &reply); + } + } else { + Str255 prompt, def; + + strcpy((char*)prompt+1, "Save as"); + prompt[0] = strlen("Save as"); + if (myDataPtr->initialFile) { + strncpy((char*)def+1, myDataPtr->initialFile, 254); + def[0] = strlen(myDataPtr->initialFile); + } else { + def[0] = 0; + } + if (myDataPtr->usePopup) { + /* + * Currently this never gets called because we don't use + * popup for the save dialog. + */ + CustomPutFile(prompt, def, &reply, myDataPtr->dialogId, mypoint, + saveHook, NULL, NULL, NULL, myDataPtr); + } else { + StandardPutFile(prompt, def, &reply); + } + } + + Tcl_ResetResult(interp); + if (reply.sfGood) { + int length; + Handle pathHandle = NULL; + char * pathName = NULL; + + FSpPathFromLocation(&reply.sfFile, &length, &pathHandle); + + if (pathHandle != NULL) { + HLock(pathHandle); + pathName = (char *) ckalloc((unsigned) (length + 1)); + strcpy(pathName, *pathHandle); + HUnlock(pathHandle); + DisposeHandle(pathHandle); + + /* + * Return the full pathname of the selected file + */ + + Tcl_SetResult(interp, pathName, TCL_DYNAMIC); + } + } + + done: + TkFreeFileFilters(&myDataPtr->fl); + return code; +} + +/* + *---------------------------------------------------------------------- + * + * ParseFileDlgArgs -- + * + * Parses the arguments passed to tk_getOpenFile and tk_getSaveFile. + * + * Results: + * A standard TCL return value. + * + * Side effects: + * The OpenFileData structure is initialized and modified according + * to the arguments. + * + *---------------------------------------------------------------------- + */ + +static int +ParseFileDlgArgs( + Tcl_Interp * interp, /* Current interpreter. */ + OpenFileData * myDataPtr, /* Information about the file dialog */ + int argc, /* Number of arguments */ + char ** argv, /* Argument strings */ + int isOpen) /* TRUE if this is an "open" dialog */ +{ + int i; + + myDataPtr->interp = interp; + myDataPtr->initialFile = NULL; + myDataPtr->curType = 0; + + TkInitFileFilters(&myDataPtr->fl); + + if (isOpen) { + myDataPtr->isOpen = 1; + myDataPtr->usePopup = 1; + myDataPtr->menu = GetMenu(OPEN_MENU); + myDataPtr->dialogId = OPEN_BOX; + myDataPtr->popupId = OPEN_POPUP; + myDataPtr->popupItem = OPEN_POPUP_ITEM; + if (myDataPtr->menu == NULL) { + Debugger(); + } + } else { + myDataPtr->isOpen = 0; + myDataPtr->usePopup = 0; + } + + for (i=1; i<argc; i+=2) { + int v = i+1; + int len = strlen(argv[i]); + + if (strncmp(argv[i], "-defaultextension", len)==0) { + if (v==argc) {goto arg_missing;} + + myDataPtr->defExt = argv[v]; + } + else if (strncmp(argv[i], "-filetypes", len)==0) { + if (v==argc) {goto arg_missing;} + + if (TkGetFileFilters(interp, &myDataPtr->fl,argv[v],0) != TCL_OK) { + return TCL_ERROR; + } + } + else if (strncmp(argv[i], "-initialdir", len)==0) { + FSSpec dirSpec; + char * dirName; + Tcl_DString dstring; + long dirID; + OSErr err; + Boolean isDirectory; + + if (v==argc) {goto arg_missing;} + + if (Tcl_TranslateFileName(interp, argv[v], &dstring) == NULL) { + return TCL_ERROR; + } + dirName = dstring.string; + if (FSpLocationFromPath(strlen(dirName), dirName, &dirSpec) != + noErr) { + Tcl_AppendResult(interp, "bad directory \"", argv[v], + "\"", NULL); + return TCL_ERROR; + } + err = FSpGetDirectoryID(&dirSpec, &dirID, &isDirectory); + if ((err != noErr) || !isDirectory) { + Tcl_AppendResult(interp, "bad directory \"", argv[v], + "\"", NULL); + return TCL_ERROR; + } + /* + * Make sure you negate -dirSpec.vRefNum because the standard file + * package wants it that way ! + */ + LMSetSFSaveDisk(-dirSpec.vRefNum); + LMSetCurDirStore(dirID); + Tcl_DStringFree(&dstring); + } + else if (strncmp(argv[i], "-initialfile", len)==0) { + if (v==argc) {goto arg_missing;} + + myDataPtr->initialFile = argv[v]; + } + else if (strncmp(argv[i], "-parent", len)==0) { + /* + * Ignored on the Mac, but make sure that it's a valid window + * pathname + */ + Tk_Window parent; + + if (v==argc) {goto arg_missing;} + + parent=Tk_NameToWindow(interp, argv[v], Tk_MainWindow(interp)); + if (parent == NULL) { + return TCL_ERROR; + } + } + else if (strncmp(argv[i], "-title", len)==0) { + if (v==argc) {goto arg_missing;} + + /* + * This option is ignored on the Mac because the Mac file + * dialog do not support titles. + */ + } + else { + Tcl_AppendResult(interp, "unknown option \"", + argv[i], "\", must be -defaultextension, ", + "-filetypes, -initialdir, -initialfile, -parent or -title", + NULL); + return TCL_ERROR; + } + } + + return TCL_OK; + + arg_missing: + Tcl_AppendResult(interp, "value for \"", argv[argc-1], "\" missing", + NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * OpenHookProc -- + * + * Gets called for various events that occur in the file dialog box. + * Initializes the popup menu or rebuild the file list depending on + * the type of the event. + * + * Results: + * A standard result understood by the Mac file dialog event dispatcher. + * + * Side effects: + * The contents in the file dialog may be changed depending on + * the type of the event. + *---------------------------------------------------------------------- + */ + +static pascal short +OpenHookProc( + short item, /* Event description. */ + DialogPtr theDialog, /* The dialog where the event occurs. */ + OpenFileData * myDataPtr) /* Information about the file dialog. */ +{ + short ignore; + Rect rect; + Handle handle; + int newType; + + switch (item) { + case sfHookFirstCall: + if (myDataPtr->usePopup) { + /* + * Set the popup list to display the selected type. + */ + GetDialogItem(theDialog, myDataPtr->popupItem, + &ignore, &handle, &rect); + SetControlValue((ControlRef) handle, myDataPtr->curType + 1); + } + return sfHookNullEvent; + + case OPEN_POPUP_ITEM: + if (myDataPtr->usePopup) { + GetDialogItem(theDialog, myDataPtr->popupItem, + &ignore, &handle, &rect); + newType = GetCtlValue((ControlRef) handle) - 1; + if (myDataPtr->curType != newType) { + if (newType<0 || newType>myDataPtr->fl.numFilters) { + /* + * Sanity check. Looks like the user selected an + * non-existent menu item?? Don't do anything. + */ + } else { + myDataPtr->curType = newType; + } + return sfHookRebuildList; + } + } + break; + } + + return item; +} + +/* + *---------------------------------------------------------------------- + * + * FileFilterProc -- + * + * Filters files according to file types. Get called whenever the + * file list needs to be updated inside the dialog box. + * + * Results: + * Returns MATCHED if the file should be shown in the listbox, returns + * UNMATCHED otherwise. + * + * Side effects: + * If MATCHED is returned, the file is shown in the listbox. + * + *---------------------------------------------------------------------- + */ + +static pascal Boolean +FileFilterProc( + CInfoPBPtr pb, /* Information about the file */ + void *myData) /* Client data for this file dialog */ +{ + int i; + OpenFileData * myDataPtr = (OpenFileData*)myData; + FileFilter * filterPtr; + + if (myDataPtr->fl.numFilters == 0) { + /* + * No types have been specified. List all files by default + */ + return MATCHED; + } + + if (pb->dirInfo.ioFlAttrib & 0x10) { + /* + * This is a directory: always show it + */ + return MATCHED; + } + + if (myDataPtr->usePopup) { + i = myDataPtr->curType; + for (filterPtr=myDataPtr->fl.filters; filterPtr && i>0; i--) { + filterPtr = filterPtr->next; + } + if (filterPtr) { + return MatchOneType(pb, myDataPtr, filterPtr); + } else { + return UNMATCHED; + } + } else { + /* + * We are not using the popup menu. In this case, the file is + * considered matched if it matches any of the file filters. + */ + + for (filterPtr=myDataPtr->fl.filters; filterPtr; + filterPtr=filterPtr->next) { + if (MatchOneType(pb, myDataPtr, filterPtr) == MATCHED) { + return MATCHED; + } + } + return UNMATCHED; + } +} + +/* + *---------------------------------------------------------------------- + * + * MatchOneType -- + * + * Match a file with one file type in the list of file types. + * + * Results: + * Returns MATCHED if the file matches with the file type; returns + * UNMATCHED otherwise. + * + * Side effects: + * None + * + *---------------------------------------------------------------------- + */ + +static Boolean +MatchOneType( + CInfoPBPtr pb, /* Information about the file */ + OpenFileData * myDataPtr, /* Information about this file dialog */ + FileFilter * filterPtr) /* Match the file described by pb against + * this filter */ +{ + FileFilterClause * clausePtr; + + /* + * A file matches with a file type if it matches with at least one + * clause of the type. + * + * If the clause has both glob patterns and ostypes, the file must + * match with at least one pattern AND at least one ostype. + * + * If the clause has glob patterns only, the file must match with at least + * one pattern. + * + * If the clause has mac types only, the file must match with at least + * one mac type. + * + * If the clause has neither glob patterns nor mac types, it's + * considered an error. + */ + + for (clausePtr=filterPtr->clauses; clausePtr; clausePtr=clausePtr->next) { + int macMatched = 0; + int globMatched = 0; + GlobPattern * globPtr; + MacFileType * mfPtr; + + if (clausePtr->patterns == NULL) { + globMatched = 1; + } + if (clausePtr->macTypes == NULL) { + macMatched = 1; + } + + for (globPtr=clausePtr->patterns; globPtr; globPtr=globPtr->next) { + char filename[256]; + int len; + char * p, *q, *ext; + + if (pb->hFileInfo.ioNamePtr == NULL) { + continue; + } + p = (char*)(pb->hFileInfo.ioNamePtr); + len = p[0]; + strncpy(filename, p+1, len); + filename[len] = '\0'; + ext = globPtr->pattern; + + if (ext[0] == '\0') { + /* + * We don't want any extensions: OK if the filename doesn't + * have "." in it + */ + for (q=filename; *q; q++) { + if (*q == '.') { + goto glob_unmatched; + } + } + goto glob_matched; + } + + if (Tcl_StringMatch(filename, ext)) { + goto glob_matched; + } else { + goto glob_unmatched; + } + + glob_unmatched: + continue; + + glob_matched: + globMatched = 1; + break; + } + + for (mfPtr=clausePtr->macTypes; mfPtr; mfPtr=mfPtr->next) { + if (pb->hFileInfo.ioFlFndrInfo.fdType == mfPtr->type) { + macMatched = 1; + break; + } + } + + if (globMatched && macMatched) { + return MATCHED; + } + } + + return UNMATCHED; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_MessageBoxCmd -- + * + * This procedure implements the MessageBox window for the + * Mac platform. See the user documentation for details on what + * it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See user documentation. + * + *---------------------------------------------------------------------- + */ + +int +Tk_MessageBoxCmd( + ClientData clientData, /* Main window associated with interpreter. */ + Tcl_Interp *interp, /* Current interpreter. */ + int argc, /* Number of arguments. */ + char **argv) /* Argument strings. */ +{ + return EvalArgv(interp, "tkMessageBox", argc, argv); +} diff --git a/mac/tkMacDraw.c b/mac/tkMacDraw.c new file mode 100644 index 0000000..9624041 --- /dev/null +++ b/mac/tkMacDraw.c @@ -0,0 +1,1130 @@ +/* + * tkMacDraw.c -- + * + * This file contains functions that preform drawing to + * Xlib windows. Most of the functions simple emulate + * Xlib functions. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacDraw.c 1.55 97/11/20 18:28:56 + */ + +#include "tkInt.h" +#include "X.h" +#include "Xlib.h" +#include <stdio.h> +#include <tcl.h> + +#include <Windows.h> +#include <Fonts.h> +#include <QDOffscreen.h> +#include "tkMacInt.h" + +#ifndef PI +# define PI 3.14159265358979323846 +#endif + +/* + * Temporary regions that can be reused. + */ +static RgnHandle tmpRgn = NULL; +static RgnHandle tmpRgn2 = NULL; + +static PixPatHandle gPenPat = NULL; + +/* + * Prototypes for functions used only in this file. + */ +static unsigned char InvertByte _ANSI_ARGS_((unsigned char data)); + +/* + *---------------------------------------------------------------------- + * + * XCopyArea -- + * + * Copies data from one drawable to another using block transfer + * routines. + * + * Results: + * None. + * + * Side effects: + * Data is moved from a window or bitmap to a second window or + * bitmap. + * + *---------------------------------------------------------------------- + */ + +void +XCopyArea( + Display* display, /* Display. */ + Drawable src, /* Source drawable. */ + Drawable dest, /* Destination drawable. */ + GC gc, /* GC to use. */ + int src_x, /* X & Y, width & height */ + int src_y, /* define the source rectangle */ + unsigned int width, /* the will be copied. */ + unsigned int height, + int dest_x, /* Dest X & Y on dest rect. */ + int dest_y) +{ + Rect srcRect, destRect; + BitMapPtr srcBit, destBit; + MacDrawable *srcDraw = (MacDrawable *) src; + MacDrawable *destDraw = (MacDrawable *) dest; + GWorldPtr srcPort, destPort; + CGrafPtr saveWorld; + GDHandle saveDevice; + short tmode; + RGBColor origForeColor, origBackColor, whiteColor, blackColor; + + destPort = TkMacGetDrawablePort(dest); + srcPort = TkMacGetDrawablePort(src); + + display->request++; + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + GetForeColor(&origForeColor); + GetBackColor(&origBackColor); + whiteColor.red = 0; + whiteColor.blue = 0; + whiteColor.green = 0; + RGBForeColor(&whiteColor); + blackColor.red = 0xFFFF; + blackColor.blue = 0xFFFF; + blackColor.green = 0xFFFF; + RGBBackColor(&blackColor); + + + TkMacSetUpClippingRgn(dest); + + /* + * We will change the clip rgn in this routine, so we need to + * be able to restore it when we exit. + */ + + if (tmpRgn2 == NULL) { + tmpRgn2 = NewRgn(); + } + GetClip(tmpRgn2); + + if (((TkpClipMask*)gc->clip_mask)->type == TKP_CLIP_REGION) { + RgnHandle clipRgn = (RgnHandle) + ((TkpClipMask*)gc->clip_mask)->value.region; + + int xOffset, yOffset; + + if (tmpRgn == NULL) { + tmpRgn = NewRgn(); + } + + xOffset = destDraw->xOff + gc->clip_x_origin; + yOffset = destDraw->yOff + gc->clip_y_origin; + + OffsetRgn(clipRgn, xOffset, yOffset); + + GetClip(tmpRgn); + SectRgn(tmpRgn, clipRgn, tmpRgn); + + SetClip(tmpRgn); + + OffsetRgn(clipRgn, -xOffset, -yOffset); + } + + srcBit = &((GrafPtr) srcPort)->portBits; + destBit = &((GrafPtr) destPort)->portBits; + SetRect(&srcRect, (short) (srcDraw->xOff + src_x), + (short) (srcDraw->yOff + src_y), + (short) (srcDraw->xOff + src_x + width), + (short) (srcDraw->yOff + src_y + height)); + SetRect(&destRect, (short) (destDraw->xOff + dest_x), + (short) (destDraw->yOff + dest_y), + (short) (destDraw->xOff + dest_x + width), + (short) (destDraw->yOff + dest_y + height)); + tmode = srcCopy; + + CopyBits(srcBit, destBit, &srcRect, &destRect, tmode, NULL); + RGBForeColor(&origForeColor); + RGBBackColor(&origBackColor); + SetClip(tmpRgn2); + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * XCopyPlane -- + * + * Copies a bitmap from a source drawable to a destination + * drawable. The plane argument specifies which bit plane of + * the source contains the bitmap. Note that this implementation + * ignores the gc->function. + * + * Results: + * None. + * + * Side effects: + * Changes the destination drawable. + * + *---------------------------------------------------------------------- + */ + +void +XCopyPlane( + Display* display, /* Display. */ + Drawable src, /* Source drawable. */ + Drawable dest, /* Destination drawable. */ + GC gc, /* The GC to use. */ + int src_x, /* X, Y, width & height */ + int src_y, /* define the source rect. */ + unsigned int width, + unsigned int height, + int dest_x, /* X & Y on dest where we will copy. */ + int dest_y, + unsigned long plane) /* Which plane to copy. */ +{ + Rect srcRect, destRect; + BitMapPtr srcBit, destBit, maskBit; + MacDrawable *srcDraw = (MacDrawable *) src; + MacDrawable *destDraw = (MacDrawable *) dest; + GWorldPtr srcPort, destPort, maskPort; + CGrafPtr saveWorld; + GDHandle saveDevice; + RGBColor macColor; + TkpClipMask *clipPtr = (TkpClipMask*)gc->clip_mask; + short tmode; + + destPort = TkMacGetDrawablePort(dest); + srcPort = TkMacGetDrawablePort(src); + + display->request++; + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(dest); + + srcBit = &((GrafPtr) srcPort)->portBits; + destBit = &((GrafPtr) destPort)->portBits; + SetRect(&srcRect, (short) (srcDraw->xOff + src_x), + (short) (srcDraw->yOff + src_y), + (short) (srcDraw->xOff + src_x + width), + (short) (srcDraw->yOff + src_y + height)); + SetRect(&destRect, (short) (destDraw->xOff + dest_x), + (short) (destDraw->yOff + dest_y), + (short) (destDraw->xOff + dest_x + width), + (short) (destDraw->yOff + dest_y + height)); + tmode = srcOr; + tmode = srcCopy + transparent; + + if (TkSetMacColor(gc->foreground, &macColor) == true) { + RGBForeColor(&macColor); + } + + if (clipPtr == NULL || clipPtr->type == TKP_CLIP_REGION) { + + /* + * Case 1: opaque bitmaps. + */ + + TkSetMacColor(gc->background, &macColor); + RGBBackColor(&macColor); + tmode = srcCopy; + CopyBits(srcBit, destBit, &srcRect, &destRect, tmode, NULL); + } else if (clipPtr->type == TKP_CLIP_PIXMAP) { + if (clipPtr->value.pixmap == src) { + /* + * Case 2: transparent bitmaps. If it's color we ignore + * the forecolor. + */ + if ((**(srcPort->portPixMap)).pixelSize == 1) { + tmode = srcOr; + } else { + tmode = transparent; + } + CopyBits(srcBit, destBit, &srcRect, &destRect, tmode, NULL); + } else { + /* + * Case 3: two arbitrary bitmaps. + */ + tmode = srcCopy; + maskPort = TkMacGetDrawablePort(clipPtr->value.pixmap); + maskBit = &((GrafPtr) maskPort)->portBits; + CopyDeepMask(srcBit, maskBit, destBit, &srcRect, &srcRect, &destRect, tmode, NULL); + } + } + + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * TkPutImage -- + * + * Copies a subimage from an in-memory image to a rectangle of + * of the specified drawable. + * + * Results: + * None. + * + * Side effects: + * Draws the image on the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +TkPutImage( + unsigned long *colors, /* Unused on Macintosh. */ + int ncolors, /* Unused on Macintosh. */ + Display* display, /* Display. */ + Drawable d, /* Drawable to place image on. */ + GC gc, /* GC to use. */ + XImage* image, /* Image to place. */ + int src_x, /* Source X & Y. */ + int src_y, + int dest_x, /* Destination X & Y. */ + int dest_y, + unsigned int width, /* Same width & height for both */ + unsigned int height) /* distination and source. */ +{ + MacDrawable *destDraw = (MacDrawable *) d; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + int i, j; + BitMap bitmap; + char *newData = NULL; + Rect destRect, srcRect; + + destPort = TkMacGetDrawablePort(d); + SetRect(&destRect, dest_x, dest_y, dest_x + width, dest_y + height); + SetRect(&srcRect, src_x, src_y, src_x + width, src_y + height); + + display->request++; + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(d); + + if (image->depth == 1) { + + /* + * This code assumes a pixel depth of 1 + */ + + bitmap.bounds.top = bitmap.bounds.left = 0; + bitmap.bounds.right = (short) image->width; + bitmap.bounds.bottom = (short) image->height; + if ((image->bytes_per_line % 2) == 1) { + char *newPtr, *oldPtr; + newData = (char *) ckalloc(image->height * + (image->bytes_per_line + 1)); + newPtr = newData; + oldPtr = image->data; + for (i = 0; i < image->height; i++) { + for (j = 0; j < image->bytes_per_line; j++) { + *newPtr = InvertByte((unsigned char) *oldPtr); + newPtr++, oldPtr++; + } + *newPtr = 0; + newPtr++; + } + bitmap.baseAddr = newData; + bitmap.rowBytes = image->bytes_per_line + 1; + } else { + newData = (char *) ckalloc(image->height * image->bytes_per_line); + for (i = 0; i < image->height * image->bytes_per_line; i++) { + newData[i] = InvertByte((unsigned char) image->data[i]); + } + bitmap.baseAddr = newData; + bitmap.rowBytes = image->bytes_per_line; + } + + CopyBits(&bitmap, &((GrafPtr) destPort)->portBits, + &srcRect, &destRect, srcCopy, NULL); + + } else { + /* Color image */ + PixMap pixmap; + + pixmap.bounds.left = 0; + pixmap.bounds.top = 0; + pixmap.bounds.right = (short) image->width; + pixmap.bounds.bottom = (short) image->height; + pixmap.pixelType = RGBDirect; + pixmap.pmVersion = 4; /* 32bit clean */ + pixmap.packType = 0; + pixmap.packSize = 0; + pixmap.hRes = 0x00480000; + pixmap.vRes = 0x00480000; + pixmap.pixelSize = 32; + pixmap.cmpCount = 3; + pixmap.cmpSize = 8; + pixmap.planeBytes = 0; + pixmap.pmTable = NULL; + pixmap.pmReserved = 0; + pixmap.baseAddr = image->data; + pixmap.rowBytes = image->bytes_per_line | 0x8000; + + CopyBits((BitMap *) &pixmap, &((GrafPtr) destPort)->portBits, + &srcRect, &destRect, srcCopy, NULL); + } + + if (newData != NULL) { + ckfree(newData); + } + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * XFillRectangles -- + * + * Fill multiple rectangular areas in the given drawable. + * + * Results: + * None. + * + * Side effects: + * Draws onto the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +XFillRectangles( + Display* display, /* Display. */ + Drawable d, /* Draw on this. */ + GC gc, /* Use this GC. */ + XRectangle *rectangles, /* Rectangle array. */ + int n_rectangels) /* Number of rectangles. */ +{ + MacDrawable *macWin = (MacDrawable *) d; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + Rect theRect; + int i; + + destPort = TkMacGetDrawablePort(d); + + display->request++; + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(d); + + TkMacSetUpGraphicsPort(gc); + + for (i=0; i<n_rectangels; i++) { + theRect.left = (short) (macWin->xOff + rectangles[i].x); + theRect.top = (short) (macWin->yOff + rectangles[i].y); + theRect.right = (short) (theRect.left + rectangles[i].width); + theRect.bottom = (short) (theRect.top + rectangles[i].height); + FillCRect(&theRect, gPenPat); + } + + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * XDrawLines -- + * + * Draw connected lines. + * + * Results: + * None. + * + * Side effects: + * Renders a series of connected lines. + * + *---------------------------------------------------------------------- + */ + +void +XDrawLines( + Display* display, /* Display. */ + Drawable d, /* Draw on this. */ + GC gc, /* Use this GC. */ + XPoint* points, /* Array of points. */ + int npoints, /* Number of points. */ + int mode) /* Line drawing mode. */ +{ + MacDrawable *macWin = (MacDrawable *) d; + CGrafPtr saveWorld; + GWorldPtr destPort; + GDHandle saveDevice; + int i; + + destPort = TkMacGetDrawablePort(d); + + display->request++; + if (npoints < 2) { + return; /* TODO: generate BadValue error. */ + } + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(d); + + TkMacSetUpGraphicsPort(gc); + + ShowPen(); + + PenPixPat(gPenPat); + MoveTo((short) (macWin->xOff + points[0].x), + (short) (macWin->yOff + points[0].y)); + for (i = 1; i < npoints; i++) { + if (mode == CoordModeOrigin) { + LineTo((short) (macWin->xOff + points[i].x), + (short) (macWin->yOff + points[i].y)); + } else { + Line((short) (macWin->xOff + points[i].x), + (short) (macWin->yOff + points[i].y)); + } + } + + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * XDrawSegments -- + * + * Draw unconnected lines. + * + * Results: + * None. + * + * Side effects: + * Renders a series of connected lines. + * + *---------------------------------------------------------------------- + */ + +void XDrawSegments( + Display *display, + Drawable d, + GC gc, + XSegment *segments, + int nsegments) +{ + MacDrawable *macWin = (MacDrawable *) d; + CGrafPtr saveWorld; + GWorldPtr destPort; + GDHandle saveDevice; + int i; + + destPort = TkMacGetDrawablePort(d); + + display->request++; + + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(d); + + TkMacSetUpGraphicsPort(gc); + + ShowPen(); + + PenPixPat(gPenPat); + for (i = 0; i < nsegments; i++) { + MoveTo((short) (macWin->xOff + segments[i].x1), + (short) (macWin->yOff + segments[i].y1)); + LineTo((short) (macWin->xOff + segments[i].x2), + (short) (macWin->yOff + segments[i].y2)); + } + + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * XFillPolygon -- + * + * Draws a filled polygon. + * + * Results: + * None. + * + * Side effects: + * Draws a filled polygon on the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +XFillPolygon( + Display* display, /* Display. */ + Drawable d, /* Draw on this. */ + GC gc, /* Use this GC. */ + XPoint* points, /* Array of points. */ + int npoints, /* Number of points. */ + int shape, /* Shape to draw. */ + int mode) /* Drawing mode. */ +{ + MacDrawable *macWin = (MacDrawable *) d; + PolyHandle polygon; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + int i; + + destPort = TkMacGetDrawablePort(d); + + display->request++; + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(d); + + TkMacSetUpGraphicsPort(gc); + + PenNormal(); + polygon = OpenPoly(); + + MoveTo((short) (macWin->xOff + points[0].x), + (short) (macWin->yOff + points[0].y)); + for (i = 1; i < npoints; i++) { + if (mode == CoordModePrevious) { + Line((short) (macWin->xOff + points[i].x), + (short) (macWin->yOff + points[i].y)); + } else { + LineTo((short) (macWin->xOff + points[i].x), + (short) (macWin->yOff + points[i].y)); + } + } + + ClosePoly(); + + FillCPoly(polygon, gPenPat); + + KillPoly(polygon); + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * XDrawRectangle -- + * + * Draws a rectangle. + * + * Results: + * None. + * + * Side effects: + * Draws a rectangle on the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +XDrawRectangle( + Display* display, /* Display. */ + Drawable d, /* Draw on this. */ + GC gc, /* Use this GC. */ + int x, /* Upper left corner. */ + int y, + unsigned int width, /* Width & height of rect. */ + unsigned int height) +{ + MacDrawable *macWin = (MacDrawable *) d; + Rect theRect; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + + destPort = TkMacGetDrawablePort(d); + + display->request++; + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(d); + + TkMacSetUpGraphicsPort(gc); + + theRect.left = (short) (macWin->xOff + x); + theRect.top = (short) (macWin->yOff + y); + theRect.right = (short) (theRect.left + width); + theRect.bottom = (short) (theRect.top + height); + + ShowPen(); + PenPixPat(gPenPat); + FrameRect(&theRect); + + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * XDrawArc -- + * + * Draw an arc. + * + * Results: + * None. + * + * Side effects: + * Draws an arc on the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +XDrawArc( + Display* display, /* Display. */ + Drawable d, /* Draw on this. */ + GC gc, /* Use this GC. */ + int x, /* Upper left of */ + int y, /* bounding rect. */ + unsigned int width, /* Width & height. */ + unsigned int height, + int angle1, /* Staring angle of arc. */ + int angle2) /* Ending angle of arc. */ +{ + MacDrawable *macWin = (MacDrawable *) d; + Rect theRect; + short start, extent; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + + destPort = TkMacGetDrawablePort(d); + + display->request++; + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(d); + + TkMacSetUpGraphicsPort(gc); + + theRect.left = (short) (macWin->xOff + x); + theRect.top = (short) (macWin->yOff + y); + theRect.right = (short) (theRect.left + width); + theRect.bottom = (short) (theRect.top + height); + start = (short) (90 - (angle1 / 64)); + extent = (short) (-(angle2 / 64)); + + ShowPen(); + PenPixPat(gPenPat); + FrameArc(&theRect, start, extent); + + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * XFillArc -- + * + * Draw a filled arc. + * + * Results: + * None. + * + * Side effects: + * Draws a filled arc on the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +XFillArc( + Display* display, /* Display. */ + Drawable d, /* Draw on this. */ + GC gc, /* Use this GC. */ + int x, /* Upper left of */ + int y, /* bounding rect. */ + unsigned int width, /* Width & height. */ + unsigned int height, + int angle1, /* Staring angle of arc. */ + int angle2) /* Ending angle of arc. */ +{ + MacDrawable *macWin = (MacDrawable *) d; + Rect theRect; + short start, extent; + PolyHandle polygon; + double sin1, cos1, sin2, cos2, angle; + double boxWidth, boxHeight; + double vertex[2], center1[2], center2[2]; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + + destPort = TkMacGetDrawablePort(d); + + display->request++; + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(d); + + TkMacSetUpGraphicsPort(gc); + + theRect.left = (short) (macWin->xOff + x); + theRect.top = (short) (macWin->yOff + y); + theRect.right = (short) (theRect.left + width); + theRect.bottom = (short) (theRect.top + height); + start = (short) (90 - (angle1 / 64)); + extent = (short) (- (angle2 / 64)); + + if (gc->arc_mode == ArcChord) { + boxWidth = theRect.right - theRect.left; + boxHeight = theRect.bottom - theRect.top; + angle = -(angle1/64.0)*PI/180.0; + sin1 = sin(angle); + cos1 = cos(angle); + angle -= (angle2/64.0)*PI/180.0; + sin2 = sin(angle); + cos2 = cos(angle); + vertex[0] = (theRect.left + theRect.right)/2.0; + vertex[1] = (theRect.top + theRect.bottom)/2.0; + center1[0] = vertex[0] + cos1*boxWidth/2.0; + center1[1] = vertex[1] + sin1*boxHeight/2.0; + center2[0] = vertex[0] + cos2*boxWidth/2.0; + center2[1] = vertex[1] + sin2*boxHeight/2.0; + + polygon = OpenPoly(); + MoveTo((short) ((theRect.left + theRect.right)/2), + (short) ((theRect.top + theRect.bottom)/2)); + + LineTo((short) (center1[0] + 0.5), (short) (center1[1] + 0.5)); + LineTo((short) (center2[0] + 0.5), (short) (center2[1] + 0.5)); + ClosePoly(); + + ShowPen(); + FillCArc(&theRect, start, extent, gPenPat); + FillCPoly(polygon, gPenPat); + + KillPoly(polygon); + } else { + ShowPen(); + FillCArc(&theRect, start, extent, gPenPat); + } + + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * TkScrollWindow -- + * + * Scroll a rectangle of the specified window and accumulate + * a damage region. + * + * Results: + * Returns 0 if the scroll genereated no additional damage. + * Otherwise, sets the region that needs to be repainted after + * scrolling and returns 1. + * + * Side effects: + * Scrolls the bits in the window. + * + *---------------------------------------------------------------------- + */ + +int +TkScrollWindow( + Tk_Window tkwin, /* The window to be scrolled. */ + GC gc, /* GC for window to be scrolled. */ + int x, /* Position rectangle to be scrolled. */ + int y, + int width, + int height, + int dx, /* Distance rectangle should be moved. */ + int dy, + TkRegion damageRgn) /* Region to accumulate damage in. */ +{ + MacDrawable *destDraw = (MacDrawable *) Tk_WindowId(tkwin); + RgnHandle rgn = (RgnHandle) damageRgn; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + Rect srcRect, scrollRect; + + destPort = TkMacGetDrawablePort(Tk_WindowId(tkwin)); + + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(Tk_WindowId(tkwin)); + + /* + * Due to the implementation below the behavior may be differnt + * than X in certain cases that should never occur in Tk. The + * scrollRect is the source rect extended by the offset (the union + * of the source rect and the offset rect). Everything + * in the extended scrollRect is scrolled. On X, it's possible + * to "skip" over an area if the offset makes the source and + * destination rects disjoint and non-aligned. + */ + + SetRect(&srcRect, (short) (destDraw->xOff + x), + (short) (destDraw->yOff + y), + (short) (destDraw->xOff + x + width), + (short) (destDraw->yOff + y + height)); + scrollRect = srcRect; + if (dx < 0) { + scrollRect.left += dx; + } else { + scrollRect.right += dx; + } + if (dy < 0) { + scrollRect.top += dy; + } else { + scrollRect.bottom += dy; + } + + /* + * Adjust clip region so that we don't copy any windows + * that may overlap us. + */ + RectRgn(rgn, &srcRect); + DiffRgn(rgn, destPort->visRgn, rgn); + OffsetRgn(rgn, dx, dy); + DiffRgn(destPort->clipRgn, rgn, destPort->clipRgn); + SetEmptyRgn(rgn); + + /* + * When a menu is up, the Mac does not expect drawing to occur and + * does not clip out the menu. We have to do it ourselves. This + * is pretty gross. + */ + + if (tkUseMenuCascadeRgn == 1) { + Point scratch = {0, 0}; + MacDrawable *macDraw = (MacDrawable *) Tk_WindowId(tkwin); + + LocalToGlobal(&scratch); + CopyRgn(tkMenuCascadeRgn, rgn); + OffsetRgn(rgn, -scratch.h, -scratch.v); + DiffRgn(destPort->clipRgn, rgn, destPort->clipRgn); + SetEmptyRgn(rgn); + macDraw->toplevel->flags |= TK_DRAWN_UNDER_MENU; + } + + ScrollRect(&scrollRect, dx, dy, rgn); + + SetGWorld(saveWorld, saveDevice); + + /* + * Fortunantly, the region returned by ScrollRect is symanticlly + * the same as what we need to return in this function. If the + * region is empty we return zero to denote that no damage was + * created. + */ + if (EmptyRgn(rgn)) { + return 0; + } else { + return 1; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacSetUpGraphicsPort -- + * + * Set up the graphics port from the given GC. + * + * Results: + * None. + * + * Side effects: + * The current port is adjusted. + * + *---------------------------------------------------------------------- + */ + +void +TkMacSetUpGraphicsPort( + GC gc) /* GC to apply to current port. */ +{ + RGBColor macColor; + + if (gPenPat == NULL) { + gPenPat = NewPixPat(); + } + + if (TkSetMacColor(gc->foreground, &macColor) == true) { + /* TODO: cache RGBPats for preformace - measure gains... */ + MakeRGBPat(gPenPat, &macColor); + } + + PenNormal(); + if(gc->function == GXxor) { + PenMode(patXor); + } + if (gc->line_width > 1) { + PenSize(gc->line_width, gc->line_width); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacSetUpClippingRgn -- + * + * Set up the clipping region so that drawing only occurs on the + * specified X subwindow. + * + * Results: + * None. + * + * Side effects: + * The clipping region in the current port is changed. + * + *---------------------------------------------------------------------- + */ + +void +TkMacSetUpClippingRgn( + Drawable drawable) /* Drawable to update. */ +{ + MacDrawable *macDraw = (MacDrawable *) drawable; + + if (macDraw->winPtr != NULL) { + if (macDraw->flags & TK_CLIP_INVALID) { + TkMacUpdateClipRgn(macDraw->winPtr); + } + + /* + * When a menu is up, the Mac does not expect drawing to occur and + * does not clip out the menu. We have to do it ourselves. This + * is pretty gross. + */ + + if (macDraw->clipRgn != NULL) { + if (tkUseMenuCascadeRgn == 1) { + Point scratch = {0, 0}; + GDHandle saveDevice; + GWorldPtr saveWorld; + + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(TkMacGetDrawablePort(drawable), NULL); + LocalToGlobal(&scratch); + SetGWorld(saveWorld, saveDevice); + if (tmpRgn == NULL) { + tmpRgn = NewRgn(); + } + CopyRgn(tkMenuCascadeRgn, tmpRgn); + OffsetRgn(tmpRgn, -scratch.h, -scratch.v); + DiffRgn(macDraw->clipRgn, tmpRgn, tmpRgn); + SetClip(tmpRgn); + macDraw->toplevel->flags |= TK_DRAWN_UNDER_MENU; + } else { + SetClip(macDraw->clipRgn); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacMakeStippleMap -- + * + * Given a drawable and a stipple pattern this function draws the + * pattern repeatedly over the drawable. The drawable can then + * be used as a mask for bit-bliting a stipple pattern over an + * object. + * + * Results: + * A BitMap data structure. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +BitMapPtr +TkMacMakeStippleMap( + Drawable drawable, /* Window to apply stipple. */ + Drawable stipple) /* The stipple pattern. */ +{ + MacDrawable *destDraw = (MacDrawable *) drawable; + GWorldPtr destPort; + BitMapPtr bitmapPtr; + int width, height, stippleHeight, stippleWidth; + int i, j; + char * data; + Rect bounds; + + destPort = TkMacGetDrawablePort(drawable); + width = destPort->portRect.right - destPort->portRect.left; + height = destPort->portRect.bottom - destPort->portRect.top; + + bitmapPtr = (BitMap *) ckalloc(sizeof(BitMap)); + data = (char *) ckalloc(height * ((width / 8) + 1)); + bitmapPtr->bounds.top = bitmapPtr->bounds.left = 0; + bitmapPtr->bounds.right = (short) width; + bitmapPtr->bounds.bottom = (short) height; + bitmapPtr->baseAddr = data; + bitmapPtr->rowBytes = (width / 8) + 1; + + destPort = TkMacGetDrawablePort(stipple); + stippleWidth = destPort->portRect.right - destPort->portRect.left; + stippleHeight = destPort->portRect.bottom - destPort->portRect.top; + + for (i = 0; i < height; i += stippleHeight) { + for (j = 0; j < width; j += stippleWidth) { + bounds.left = j; + bounds.top = i; + bounds.right = j + stippleWidth; + bounds.bottom = i + stippleHeight; + + CopyBits(&((GrafPtr) destPort)->portBits, bitmapPtr, + &((GrafPtr) destPort)->portRect, &bounds, srcCopy, NULL); + } + } + return bitmapPtr; +} + +/* + *---------------------------------------------------------------------- + * + * InvertByte -- + * + * This function reverses the bits in the passed in Byte of data. + * + * Results: + * The incoming byte in reverse bit order. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static unsigned char +InvertByte( + unsigned char data) /* Byte of data. */ +{ + unsigned char i; + unsigned char mask = 1, result = 0; + + for (i = (1 << 7); i != 0; i /= 2) { + if (data & mask) { + result |= i; + } + mask = mask << 1; + } + return result; +} diff --git a/mac/tkMacEmbed.c b/mac/tkMacEmbed.c new file mode 100644 index 0000000..7a73b54 --- /dev/null +++ b/mac/tkMacEmbed.c @@ -0,0 +1,1116 @@ +/* + * tkMacEmbed.c -- + * + * This file contains platform-specific procedures for theMac to provide + * basic operations needed for application embedding (where one + * application can use as its main window an internal window from + * some other application). + * Currently only Toplevel embedding within the same Tk application is + * allowed on the Macintosh. + * + * Copyright (c) 1996-97 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacEmbed.c 1.6 97/10/31 17:20:22 + */ + +#include "tkInt.h" +#include "tkPort.h" +#include "X.h" +#include "Xlib.h" +#include <stdio.h> + +#include <Windows.h> +#include <QDOffscreen.h> +#include "tkMacInt.h" + +/* + * One of the following structures exists for each container in this + * application. It keeps track of the container window and its + * associated embedded window. + */ + +typedef struct Container { + Window parent; /* The Mac Drawable for the parent of + * the pair (the container). */ + TkWindow *parentPtr; /* Tk's information about the container, + * or NULL if the container isn't + * in this process. */ + Window embedded; /* The MacDrawable for the embedded + * window. Starts off as None, but + * gets filled in when the window is + * eventually created. */ + TkWindow *embeddedPtr; /* Tk's information about the embedded + * window, or NULL if the + * embedded application isn't in + * this process. */ + struct Container *nextPtr; /* Next in list of all containers in + * this process. */ +} Container; + +static Container *firstContainerPtr = NULL; + /* First in list of all containers + * managed by this process. */ + +/* + * Prototypes for static procedures defined in this file: + */ + +static void ContainerEventProc _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +static void EmbeddedEventProc _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +static void EmbedActivateProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void EmbedFocusProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void EmbedGeometryRequest _ANSI_ARGS_(( + Container * containerPtr, int width, int height)); +static void EmbedSendConfigure _ANSI_ARGS_(( + Container *containerPtr)); +static void EmbedStructureProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void EmbedWindowDeleted _ANSI_ARGS_((TkWindow *winPtr)); + +/* WARNING - HACK */ +static void GenerateFocusEvents _ANSI_ARGS_((TkWindow *sourcePtr, + TkWindow *destPtr)); + + +/* + *---------------------------------------------------------------------- + * + * TkpMakeWindow -- + * + * Creates an X Window (Mac subwindow). + * + * Results: + * The window id is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Window +TkpMakeWindow( + TkWindow *winPtr, + Window parent) +{ + MacDrawable *macWin; + XEvent event; + + /* + * If this window is marked as embedded then + * the window structure should have already been + * created in the TkpUseWindow function. + */ + + if (Tk_IsEmbedded(winPtr)) { + return (Window) winPtr->privatePtr; + } + + /* + * Allocate sub window + */ + + macWin = (MacDrawable *) ckalloc(sizeof(MacDrawable)); + if (macWin == NULL) { + winPtr->privatePtr = NULL; + return None; + } + macWin->winPtr = winPtr; + winPtr->privatePtr = macWin; + macWin->clipRgn = NewRgn(); + macWin->aboveClipRgn = NewRgn(); + macWin->referenceCount = 0; + macWin->flags = TK_CLIP_INVALID; + + if (Tk_IsTopLevel(macWin->winPtr)) { + + /* + *This will be set when we are mapped. + */ + + macWin->portPtr = (GWorldPtr) NULL; + macWin->toplevel = macWin; + macWin->xOff = 0; + macWin->yOff = 0; + } else { + macWin->portPtr = NULL; + macWin->xOff = winPtr->parentPtr->privatePtr->xOff + + winPtr->parentPtr->changes.border_width + + winPtr->changes.x; + macWin->yOff = winPtr->parentPtr->privatePtr->yOff + + winPtr->parentPtr->changes.border_width + + winPtr->changes.y; + macWin->toplevel = winPtr->parentPtr->privatePtr->toplevel; + } + + macWin->toplevel->referenceCount++; + + /* + * TODO: need general solution for visibility events. + */ + event.xany.serial = Tk_Display(winPtr)->request; + event.xany.send_event = False; + event.xany.display = Tk_Display(winPtr); + + event.xvisibility.type = VisibilityNotify; + event.xvisibility.window = (Window) macWin;; + event.xvisibility.state = VisibilityUnobscured; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + + return (Window) macWin; +} + +/* + *---------------------------------------------------------------------- + * + * TkpUseWindow -- + * + * This procedure causes a Tk window to use a given X window as + * its parent window, rather than the root window for the screen. + * It is invoked by an embedded application to specify the window + * in which it is embedded. + * + * Results: + * The return value is normally TCL_OK. If an error occurs (such + * as string not being a valid window spec), then the return value + * is TCL_ERROR and an error message is left in interp->result if + * interp is non-NULL. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpUseWindow( + Tcl_Interp *interp, /* If not NULL, used for error reporting + * if string is bogus. */ + Tk_Window tkwin, /* Tk window that does not yet have an + * associated X window. */ + char *string) /* String identifying an X window to use + * for tkwin; must be an integer value. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + MacDrawable *parent, *macWin; + Container *containerPtr; + XEvent event; + int result; + + if (winPtr->window != None) { + panic("TkpUseWindow: X window already assigned"); + } + + /* + * Decode the container pointer, and look for it among the + *list of available containers. + * + * N.B. For now, we are limiting the containers to be in the same Tk + * application as tkwin, since otherwise they would not be in our list + * of containers. + * + */ + + if (Tcl_GetInt(interp, string, &result) != TCL_OK) { + return TCL_ERROR; + } + + parent = (MacDrawable *) result; + + /* + * Save information about the container and the embedded window + * in a Container structure. Currently, there must already be an existing + * Container structure, since we only allow the case where both container + * and embedded app. are in the same process. + */ + + for (containerPtr = firstContainerPtr; containerPtr != NULL; + containerPtr = containerPtr->nextPtr) { + if (containerPtr->parent == (Window) parent) { + winPtr->flags |= TK_BOTH_HALVES; + containerPtr->parentPtr->flags |= TK_BOTH_HALVES; + break; + } + } + + /* + * We should not get to this code until we start to allow + * embedding in other applications. + */ + + if (containerPtr == NULL) { + Tcl_AppendResult(interp, "The window ID ", string, + " does not correspond to a valid Tk Window.", + (char *) NULL); + return TCL_ERROR; + } + + /* + * Make the embedded window. + */ + + macWin = (MacDrawable *) ckalloc(sizeof(MacDrawable)); + if (macWin == NULL) { + winPtr->privatePtr = NULL; + return TCL_ERROR; + } + + macWin->winPtr = winPtr; + winPtr->privatePtr = macWin; + macWin->clipRgn = NewRgn(); + macWin->aboveClipRgn = NewRgn(); + macWin->referenceCount = 0; + macWin->flags = TK_CLIP_INVALID; + + winPtr->flags |= TK_EMBEDDED; + + /* + * Make a copy of the TK_EMBEDDED flag, since sometimes + * we need this to get the port after the TkWindow structure + * has been freed. + */ + + macWin->flags |= TK_EMBEDDED; + + /* + * The portPtr will be NULL for an embedded window. + * Always use TkMacGetDrawablePort to get the portPtr. + * It will correctly find the container's port. + */ + + macWin->portPtr = (GWorldPtr) NULL; + + macWin->toplevel = macWin; + macWin->xOff = parent->winPtr->privatePtr->xOff + + parent->winPtr->changes.border_width + + winPtr->changes.x; + macWin->yOff = parent->winPtr->privatePtr->yOff + + parent->winPtr->changes.border_width + + winPtr->changes.y; + + macWin->toplevel->referenceCount++; + + /* + * Finish filling up the container structure with the embedded window's + * information. + */ + + containerPtr->embedded = (Window) macWin; + containerPtr->embeddedPtr = macWin->winPtr; + + /* + * TODO: need general solution for visibility events. + */ + + event.xany.serial = Tk_Display(winPtr)->request; + event.xany.send_event = False; + event.xany.display = Tk_Display(winPtr); + + event.xvisibility.type = VisibilityNotify; + event.xvisibility.window = (Window) macWin;; + event.xvisibility.state = VisibilityUnobscured; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + + /* + * Create an event handler to clean up the Container structure when + * tkwin is eventually deleted. + */ + + Tk_CreateEventHandler(tkwin, StructureNotifyMask, EmbeddedEventProc, + (ClientData) winPtr); + + + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpMakeContainer -- + * + * This procedure is called to indicate that a particular window + * will be a container for an embedded application. This changes + * certain aspects of the window's behavior, such as whether it + * will receive events anymore. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpMakeContainer( + Tk_Window tkwin) /* Token for a window that is about to + * become a container. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + Container *containerPtr; + + /* + * Register the window as a container so that, for example, we can + * make sure the argument to -use is valid. + */ + + + Tk_MakeWindowExist(tkwin); + containerPtr = (Container *) ckalloc(sizeof(Container)); + containerPtr->parent = Tk_WindowId(tkwin); + containerPtr->parentPtr = winPtr; + containerPtr->embedded = None; + containerPtr->embeddedPtr = NULL; + containerPtr->nextPtr = firstContainerPtr; + firstContainerPtr = containerPtr; + winPtr->flags |= TK_CONTAINER; + + /* + * Request SubstructureNotify events so that we can find out when + * the embedded application creates its window or attempts to + * resize it. Also watch Configure events on the container so that + * we can resize the child to match. Also, pass activate events from + * the container down to the embedded toplevel. + */ + + Tk_CreateEventHandler(tkwin, + SubstructureNotifyMask|SubstructureRedirectMask, + ContainerEventProc, (ClientData) winPtr); + Tk_CreateEventHandler(tkwin, StructureNotifyMask, EmbedStructureProc, + (ClientData) containerPtr); + Tk_CreateEventHandler(tkwin, ActivateMask, EmbedActivateProc, + (ClientData) containerPtr); + Tk_CreateEventHandler(tkwin, FocusChangeMask, EmbedFocusProc, + (ClientData) containerPtr); + +} + +/* + *---------------------------------------------------------------------- + * + * TkMacContainerId -- + * + * Given an embedded window, this procedure returns the MacDrawable + * identifier for the associated container window. + * + * Results: + * The return value is the MacDrawable for winPtr's + * container window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +MacDrawable * +TkMacContainerId(winPtr) + TkWindow *winPtr; /* Tk's structure for an embedded window. */ +{ + Container *containerPtr; + + for (containerPtr = firstContainerPtr; containerPtr != NULL; + containerPtr = containerPtr->nextPtr) { + if (containerPtr->embeddedPtr == winPtr) { + return (MacDrawable *) containerPtr->parent; + } + } + panic("TkMacContainerId couldn't find window"); + return None; +} + +/* + *---------------------------------------------------------------------- + * + * TkMacGetHostToplevel -- + * + * Given the TkWindow, return the MacDrawable for the outermost + * toplevel containing it. This will be a real Macintosh window. + * + * Results: + * Returns a MacDrawable corresponding to a Macintosh Toplevel + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +MacDrawable * +TkMacGetHostToplevel( + TkWindow *winPtr) /* Tk's structure for a window. */ +{ + TkWindow *contWinPtr, *topWinPtr; + + topWinPtr = winPtr->privatePtr->toplevel->winPtr; + if (!Tk_IsEmbedded(topWinPtr)) { + return winPtr->privatePtr->toplevel; + } else { + contWinPtr = TkpGetOtherWindow(topWinPtr); + + /* + * NOTE: Here we should handle out of process embedding. + */ + + if (contWinPtr != NULL) { + return TkMacGetHostToplevel(contWinPtr); + } else { + return None; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpClaimFocus -- + * + * This procedure is invoked when someone asks for the input focus + * to be put on a window in an embedded application, but the + * application doesn't currently have the focus. It requests the + * input focus from the container application. + * + * Results: + * None. + * + * Side effects: + * The input focus may change. + * + *---------------------------------------------------------------------- + */ + +void +TkpClaimFocus( + TkWindow *topLevelPtr, /* Top-level window containing desired + * focus window; should be embedded. */ + int force) /* One means that the container should + * claim the focus if it doesn't + * currently have it. */ +{ + XEvent event; + Container *containerPtr; + + if (!(topLevelPtr->flags & TK_EMBEDDED)) { + return; + } + + for (containerPtr = firstContainerPtr; + containerPtr->embeddedPtr != topLevelPtr; + containerPtr = containerPtr->nextPtr) { + /* Empty loop body. */ + } + + + event.xfocus.type = FocusIn; + event.xfocus.serial = LastKnownRequestProcessed(topLevelPtr->display); + event.xfocus.send_event = 1; + event.xfocus.display = topLevelPtr->display; + event.xfocus.window = containerPtr->parent; + event.xfocus.mode = EMBEDDED_APP_WANTS_FOCUS; + event.xfocus.detail = force; + Tk_QueueWindowEvent(&event,TCL_QUEUE_TAIL); +} + +/* + *---------------------------------------------------------------------- + * + * TkpTestembedCmd -- + * + * This procedure implements the "testembed" command. It returns + * some or all of the information in the list pointed to by + * firstContainerPtr. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpTestembedCmd( + ClientData clientData, /* Main window for application. */ + Tcl_Interp *interp, /* Current interpreter. */ + int argc, /* Number of arguments. */ + char **argv) /* Argument strings. */ +{ + int all; + Container *containerPtr; + Tcl_DString dString; + char buffer[50]; + + if ((argc > 1) && (strcmp(argv[1], "all") == 0)) { + all = 1; + } else { + all = 0; + } + Tcl_DStringInit(&dString); + for (containerPtr = firstContainerPtr; containerPtr != NULL; + containerPtr = containerPtr->nextPtr) { + Tcl_DStringStartSublist(&dString); + if (containerPtr->parent == None) { + Tcl_DStringAppendElement(&dString, ""); + } else { + if (all) { + sprintf(buffer, "0x%x", (int) containerPtr->parent); + Tcl_DStringAppendElement(&dString, buffer); + } else { + Tcl_DStringAppendElement(&dString, "XXX"); + } + } + if (containerPtr->parentPtr == NULL) { + Tcl_DStringAppendElement(&dString, ""); + } else { + Tcl_DStringAppendElement(&dString, + containerPtr->parentPtr->pathName); + } + if (containerPtr->embedded == None) { + Tcl_DStringAppendElement(&dString, ""); + } else { + if (all) { + sprintf(buffer, "0x%x", (int) containerPtr->embedded); + Tcl_DStringAppendElement(&dString, buffer); + } else { + Tcl_DStringAppendElement(&dString, "XXX"); + } + } + if (containerPtr->embeddedPtr == NULL) { + Tcl_DStringAppendElement(&dString, ""); + } else { + Tcl_DStringAppendElement(&dString, + containerPtr->embeddedPtr->pathName); + } + Tcl_DStringEndSublist(&dString); + } + Tcl_DStringResult(interp, &dString); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpRedirectKeyEvent -- + * + * This procedure is invoked when a key press or release event + * arrives for an application that does not believe it owns the + * input focus. This can happen because of embedding; for example, + * X can send an event to an embedded application when the real + * focus window is in the container application and is an ancestor + * of the container. This procedure's job is to forward the event + * back to the application where it really belongs. + * + * Results: + * None. + * + * Side effects: + * The event may get sent to a different application. + * + *---------------------------------------------------------------------- + */ + +void +TkpRedirectKeyEvent( + TkWindow *winPtr, /* Window to which the event was originally + * reported. */ + XEvent *eventPtr) /* X event to redirect (should be KeyPress + * or KeyRelease). */ +{ +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetOtherWindow -- + * + * If both the container and embedded window are in the same + * process, this procedure will return either one, given the other. + * + * Results: + * If winPtr is a container, the return value is the token for the + * embedded window, and vice versa. If the "other" window isn't in + * this process, NULL is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkpGetOtherWindow( + TkWindow *winPtr) /* Tk's structure for a container or + * embedded window. */ +{ + Container *containerPtr; + + /* + * TkpGetOtherWindow returns NULL if both windows are not + * in the same process... + */ + + if (!(winPtr->flags & TK_BOTH_HALVES)) { + return NULL; + } + + for (containerPtr = firstContainerPtr; containerPtr != NULL; + containerPtr = containerPtr->nextPtr) { + if (containerPtr->embeddedPtr == winPtr) { + return containerPtr->parentPtr; + } else if (containerPtr->parentPtr == winPtr) { + return containerPtr->embeddedPtr; + } + } + return NULL; +} +/* + *---------------------------------------------------------------------- + * + * EmbeddedEventProc -- + * + * This procedure is invoked by the Tk event dispatcher when various + * useful events are received for a window that is embedded in + * another application. + * + * Results: + * None. + * + * Side effects: + * Our internal state gets cleaned up when an embedded window is + * destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +EmbeddedEventProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + TkWindow *winPtr = (TkWindow *) clientData; + + if (eventPtr->type == DestroyNotify) { + EmbedWindowDeleted(winPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * ContainerEventProc -- + * + * This procedure is invoked by the Tk event dispatcher when various + * useful events are received for the children of a container + * window. It forwards relevant information, such as geometry + * requests, from the events into the container's application. + * + * NOTE: on the Mac, only the DestroyNotify branch is ever taken. + * We don't synthesize the other events. + * + * Results: + * None. + * + * Side effects: + * Depends on the event. For example, when ConfigureRequest events + * occur, geometry information gets set for the container window. + * + *---------------------------------------------------------------------- + */ + +static void +ContainerEventProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + TkWindow *winPtr = (TkWindow *) clientData; + Container *containerPtr; + Tk_ErrorHandler errHandler; + + /* + * Ignore any X protocol errors that happen in this procedure + * (almost any operation could fail, for example, if the embedded + * application has deleted its window). + */ + + errHandler = Tk_CreateErrorHandler(eventPtr->xfocus.display, -1, + -1, -1, (Tk_ErrorProc *) NULL, (ClientData) NULL); + + /* + * Find the Container structure associated with the parent window. + */ + + for (containerPtr = firstContainerPtr; + containerPtr->parent != eventPtr->xmaprequest.parent; + containerPtr = containerPtr->nextPtr) { + if (containerPtr == NULL) { + panic("ContainerEventProc couldn't find Container record"); + } + } + + if (eventPtr->type == CreateNotify) { + /* + * A new child window has been created in the container. Record + * its id in the Container structure (if more than one child is + * created, just remember the last one and ignore the earlier + * ones). + */ + + containerPtr->embedded = eventPtr->xcreatewindow.window; + } else if (eventPtr->type == ConfigureRequest) { + if ((eventPtr->xconfigurerequest.x != 0) + || (eventPtr->xconfigurerequest.y != 0)) { + /* + * The embedded application is trying to move itself, which + * isn't legal. At this point, the window hasn't actually + * moved, but we need to send it a ConfigureNotify event to + * let it know that its request has been denied. If the + * embedded application was also trying to resize itself, a + * ConfigureNotify will be sent by the geometry management + * code below, so we don't need to do anything. Otherwise, + * generate a synthetic event. + */ + + if ((eventPtr->xconfigurerequest.width == winPtr->changes.width) + && (eventPtr->xconfigurerequest.height + == winPtr->changes.height)) { + EmbedSendConfigure(containerPtr); + } + } + EmbedGeometryRequest(containerPtr, + eventPtr->xconfigurerequest.width, + eventPtr->xconfigurerequest.height); + } else if (eventPtr->type == MapRequest) { + /* + * The embedded application's map request was ignored and simply + * passed on to us, so we have to map the window for it to appear + * on the screen. + */ + + XMapWindow(eventPtr->xmaprequest.display, + eventPtr->xmaprequest.window); + } else if (eventPtr->type == DestroyNotify) { + /* + * The embedded application is gone. Destroy the container window. + */ + + Tk_DestroyWindow((Tk_Window) winPtr); + } + Tk_DeleteErrorHandler(errHandler); +} + +/* + *---------------------------------------------------------------------- + * + * EmbedStructureProc -- + * + * This procedure is invoked by the Tk event dispatcher when + * a container window owned by this application gets resized + * (and also at several other times that we don't care about). + * This procedure reflects the size change in the embedded + * window that corresponds to the container. + * + * Results: + * None. + * + * Side effects: + * The embedded window gets resized to match the container. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedStructureProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + Container *containerPtr = (Container *) clientData; + Tk_ErrorHandler errHandler; + + if (eventPtr->type == ConfigureNotify) { + if (containerPtr->embedded != None) { + /* + * Ignore errors, since the embedded application could have + * deleted its window. + */ + + errHandler = Tk_CreateErrorHandler(eventPtr->xfocus.display, -1, + -1, -1, (Tk_ErrorProc *) NULL, (ClientData) NULL); + Tk_MoveResizeWindow((Tk_Window) containerPtr->embeddedPtr, 0, 0, + (unsigned int) Tk_Width( + (Tk_Window) containerPtr->parentPtr), + (unsigned int) Tk_Height( + (Tk_Window) containerPtr->parentPtr)); + Tk_DeleteErrorHandler(errHandler); + } + } else if (eventPtr->type == DestroyNotify) { + EmbedWindowDeleted(containerPtr->parentPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * EmbedActivateProc -- + * + * This procedure is invoked by the Tk event dispatcher when + * Activate and Deactivate events occur for a container window owned + * by this application. It is responsible for forwarding an activate + * event down into the embedded toplevel. + * + * Results: + * None. + * + * Side effects: + * The X focus may change. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedActivateProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + Container *containerPtr = (Container *) clientData; + + if (containerPtr->embeddedPtr != NULL) { + + if (eventPtr->type == ActivateNotify) { + TkGenerateActivateEvents(containerPtr->embeddedPtr, 1); + } else if (eventPtr->type == DeactivateNotify) { + TkGenerateActivateEvents(containerPtr->embeddedPtr, 0); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * EmbedFocusProc -- + * + * This procedure is invoked by the Tk event dispatcher when + * FocusIn and FocusOut events occur for a container window owned + * by this application. It is responsible for moving the focus + * back and forth between a container application and an embedded + * application. + * + * Results: + * None. + * + * Side effects: + * The X focus may change. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedFocusProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + Container *containerPtr = (Container *) clientData; + Display *display; + XEvent event; + + if (containerPtr->embeddedPtr != NULL) { + display = Tk_Display(containerPtr->parentPtr); + event.xfocus.serial = LastKnownRequestProcessed(display); + event.xfocus.send_event = false; + event.xfocus.display = display; + event.xfocus.mode = NotifyNormal; + event.xfocus.window = containerPtr->embedded; + + if (eventPtr->type == FocusIn) { + /* + * The focus just arrived at the container. Change the X focus + * to move it to the embedded application, if there is one. + * Ignore X errors that occur during this operation (it's + * possible that the new focus window isn't mapped). + */ + + event.xfocus.detail = NotifyNonlinear; + event.xfocus.type = FocusIn; + + } else if (eventPtr->type == FocusOut) { + /* When the container gets a FocusOut event, it has to tell the embedded app + * that it has lost the focus. + */ + + event.xfocus.type = FocusOut; + event.xfocus.detail = NotifyNonlinear; + } + + Tk_QueueWindowEvent(&event, TCL_QUEUE_MARK); + } +} + +/* + *---------------------------------------------------------------------- + * + * EmbedGeometryRequest -- + * + * This procedure is invoked when an embedded application requests + * a particular size. It processes the request (which may or may + * not actually honor the request) and reflects the results back + * to the embedded application. + * + * NOTE: On the Mac, this is a stub, since we don't synthesize + * ConfigureRequest events. + * + * Results: + * None. + * + * Side effects: + * If we deny the child's size change request, a Configure event + * is synthesized to let the child know how big it ought to be. + * Events get processed while we're waiting for the geometry + * managers to do their thing. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedGeometryRequest(containerPtr, width, height) + Container *containerPtr; /* Information about the embedding. */ + int width, height; /* Size that the child has requested. */ +{ + TkWindow *winPtr = containerPtr->parentPtr; + + /* + * Forward the requested size into our geometry management hierarchy + * via the container window. We need to send a Configure event back + * to the embedded application if we decide not to honor its + * request; to make this happen, process all idle event handlers + * synchronously here (so that the geometry managers have had a + * chance to do whatever they want to do), and if the window's size + * didn't change then generate a configure event. + */ + + Tk_GeometryRequest((Tk_Window) winPtr, width, height); + while (Tcl_DoOneEvent(TCL_IDLE_EVENTS)) { + /* Empty loop body. */ + } + if ((winPtr->changes.width != width) + || (winPtr->changes.height != height)) { + EmbedSendConfigure(containerPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * EmbedSendConfigure -- + * + * This is currently a stub. It is called to notify an + * embedded application of its current size and location. This + * procedure is called when the embedded application made a + * geometry request that we did not grant, so that the embedded + * application knows that its geometry didn't change after all. + * It is a response to ConfigureRequest events, which we do not + * currently synthesize on the Mac + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedSendConfigure(containerPtr) + Container *containerPtr; /* Information about the embedding. */ +{ +} + +/* + *---------------------------------------------------------------------- + * + * EmbedWindowDeleted -- + * + * This procedure is invoked when a window involved in embedding + * (as either the container or the embedded application) is + * destroyed. It cleans up the Container structure for the window. + * + * Results: + * None. + * + * Side effects: + * A Container structure may be freed. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedWindowDeleted(winPtr) + TkWindow *winPtr; /* Tk's information about window that + * was deleted. */ +{ + Container *containerPtr, *prevPtr; + + /* + * Find the Container structure for this window. Delete the + * information about the embedded application and free the container's + * record. + */ + + prevPtr = NULL; + containerPtr = firstContainerPtr; + while (1) { + if (containerPtr->embeddedPtr == winPtr) { + + /* + * We also have to destroy our parent, to clean up the container. + * Fabricate an event to do this. + */ + + if (containerPtr->parentPtr != NULL && + containerPtr->parentPtr->flags & TK_BOTH_HALVES) { + XEvent event; + + event.xany.serial = + Tk_Display(containerPtr->parentPtr)->request; + event.xany.send_event = False; + event.xany.display = Tk_Display(containerPtr->parentPtr); + + event.xany.type = DestroyNotify; + event.xany.window = containerPtr->parent; + event.xdestroywindow.event = containerPtr->parent; + Tk_QueueWindowEvent(&event, TCL_QUEUE_HEAD); + + } + + containerPtr->embedded = None; + containerPtr->embeddedPtr = NULL; + + break; + } + if (containerPtr->parentPtr == winPtr) { + containerPtr->parentPtr = NULL; + break; + } + prevPtr = containerPtr; + containerPtr = containerPtr->nextPtr; + } + if ((containerPtr->embeddedPtr == NULL) + && (containerPtr->parentPtr == NULL)) { + if (prevPtr == NULL) { + firstContainerPtr = containerPtr->nextPtr; + } else { + prevPtr->nextPtr = containerPtr->nextPtr; + } + ckfree((char *) containerPtr); + } +} + diff --git a/mac/tkMacFont.c b/mac/tkMacFont.c new file mode 100644 index 0000000..8619880 --- /dev/null +++ b/mac/tkMacFont.c @@ -0,0 +1,678 @@ +/* + * tkMacFont.c -- + * + * Contains the Macintosh implementation of the platform-independant + * font package interface. + * + * Copyright (c) 1990-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS:@(#) tkMacFont.c 1.52 97/11/20 18:29:51 + */ + +#include <Windows.h> +#include <Strings.h> +#include <Fonts.h> +#include <Resources.h> + +#include "tkMacInt.h" +#include "tkFont.h" +#include "tkPort.h" + +/* + * The following structure represents the Macintosh's' implementation of a + * font. + */ + +typedef struct MacFont { + TkFont font; /* Stuff used by generic font package. Must + * be first in structure. */ + short family; + short size; + short style; +} MacFont; + +static GWorldPtr gWorld = NULL; + +static TkFont * AllocMacFont _ANSI_ARGS_((TkFont *tkfont, + Tk_Window tkwin, int family, int size, int style)); + + +/* + *--------------------------------------------------------------------------- + * + * TkpGetNativeFont -- + * + * Map a platform-specific native font name to a TkFont. + * + * Results: + * The return value is a pointer to a TkFont that represents the + * native font. If a native font by the given name could not be + * found, the return value is NULL. + * + * Every call to this procedure returns a new TkFont structure, + * even if the name has already been seen before. The caller should + * call TkpDeleteFont() when the font is no longer needed. + * + * The caller is responsible for initializing the memory associated + * with the generic TkFont when this function returns and releasing + * the contents of the generics TkFont before calling TkpDeleteFont(). + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +TkFont * +TkpGetNativeFont( + Tk_Window tkwin, /* For display where font will be used. */ + CONST char *name) /* Platform-specific font name. */ +{ + short family; + + if (strcmp(name, "system") == 0) { + family = GetSysFont(); + } else if (strcmp(name, "application") == 0) { + family = GetAppFont(); + } else { + return NULL; + } + + return AllocMacFont(NULL, tkwin, family, 0, 0); +} + +/* + *--------------------------------------------------------------------------- + * + * TkpGetFontFromAttributes -- + * + * Given a desired set of attributes for a font, find a font with + * the closest matching attributes. + * + * Results: + * The return value is a pointer to a TkFont that represents the + * font with the desired attributes. If a font with the desired + * attributes could not be constructed, some other font will be + * substituted automatically. + * + * Every call to this procedure returns a new TkFont structure, + * even if the specified attributes have already been seen before. + * The caller should call TkpDeleteFont() to free the platform- + * specific data when the font is no longer needed. + * + * The caller is responsible for initializing the memory associated + * with the generic TkFont when this function returns and releasing + * the contents of the generic TkFont before calling TkpDeleteFont(). + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ +TkFont * +TkpGetFontFromAttributes( + TkFont *tkFontPtr, /* If non-NULL, store the information in + * this existing TkFont structure, rather than + * allocating a new structure to hold the + * font; the existing contents of the font + * will be released. If NULL, a new TkFont + * structure is allocated. */ + Tk_Window tkwin, /* For display where font will be used. */ + CONST TkFontAttributes *faPtr) /* Set of attributes to match. */ +{ + char buf[257]; + size_t len; + short family, size, style; + + if (faPtr->family == NULL) { + family = 0; + } else { + CONST char *familyName; + + familyName = faPtr->family; + if (strcasecmp(familyName, "Times New Roman") == 0) { + familyName = "Times"; + } else if (strcasecmp(familyName, "Courier New") == 0) { + familyName = "Courier"; + } else if (strcasecmp(familyName, "Arial") == 0) { + familyName = "Helvetica"; + } + + len = strlen(familyName); + if (len > 255) { + len = 255; + } + buf[0] = (char) len; + memcpy(buf + 1, familyName, len); + buf[len + 1] = '\0'; + GetFNum((StringPtr) buf, &family); + } + + size = faPtr->pointsize; + if (size <= 0) { + size = GetDefFontSize(); + } + + style = 0; + if (faPtr->weight != TK_FW_NORMAL) { + style |= bold; + } + if (faPtr->slant != TK_FS_ROMAN) { + style |= italic; + } + if (faPtr->underline) { + style |= underline; + } + + return AllocMacFont(tkFontPtr, tkwin, family, size, style); +} + +/* + *--------------------------------------------------------------------------- + * + * TkpDeleteFont -- + * + * Called to release a font allocated by TkpGetNativeFont() or + * TkpGetFontFromAttributes(). The caller should have already + * released the fields of the TkFont that are used exclusively by + * the generic TkFont code. + * + * Results: + * None. + * + * Side effects: + * TkFont is deallocated. + * + *--------------------------------------------------------------------------- + */ + +void +TkpDeleteFont( + TkFont *tkFontPtr) /* Token of font to be deleted. */ +{ + ckfree((char *) tkFontPtr); +} + +/* + *--------------------------------------------------------------------------- + * + * TkpGetFontFamilies -- + * + * Return information about the font families that are available + * on the display of the given window. + * + * Results: + * interp->result is modified to hold a list of all the available + * font families. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +void +TkpGetFontFamilies( + Tcl_Interp *interp, /* Interp to hold result. */ + Tk_Window tkwin) /* For display to query. */ +{ + MenuHandle fontMenu; + int i; + char itemText[257]; + + fontMenu = NewMenu(1, "\px"); + AddResMenu(fontMenu, 'FONT'); + + for (i = 1; i < CountMItems(fontMenu); i++) { + /* + * Each item is a pascal string. Convert it to C and append. + */ + GetMenuItemText(fontMenu, i, (unsigned char *) itemText); + itemText[itemText[0] + 1] = '\0'; + Tcl_AppendElement(interp, &itemText[1]); + } + DisposeMenu(fontMenu); +} + + +/* + *--------------------------------------------------------------------------- + * + * TkMacIsCharacterMissing -- + * + * Given a tkFont and a character determines whether the character has + * a glyph defined in the font or not. Note that this is potentially + * not compatible with Mac OS 8 as it looks at the font handle + * structure directly. Looks into the character array of the font + * handle to determine whether the glyph is defined or not. + * + * Results: + * Returns a 1 if the character is missing, a 0 if it is not. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +int +TkMacIsCharacterMissing( + Tk_Font tkfont, /* The font we are looking in. */ + unsigned int searchChar) /* The character we are looking for. */ +{ + MacFont *fontPtr = (MacFont *) tkfont; + FMInput fm; + FontRec **fontRecHandle; + + fm.family = fontPtr->family; + fm.size = fontPtr->size; + fm.face = fontPtr->style; + fm.needBits = 0; + fm.device = 0; + fm.numer.h = fm.numer.v = fm.denom.h = fm.denom.v = 1; + + /* + * This element of the FMOutput structure was changed between the 2.0 & 3.0 + * versions of the Universal Headers. + */ + +#if !defined(UNIVERSAL_INTERFACES_VERSION) || (UNIVERSAL_INTERFACES_VERSION < 0x0300) + fontRecHandle = (FontRec **) FMSwapFont(&fm)->fontResult; +#else + fontRecHandle = (FontRec **) FMSwapFont(&fm)->fontHandle; +#endif + return *(short *) ((long) &(*fontRecHandle)->owTLoc + + ((long)((*fontRecHandle)->owTLoc + searchChar + - (*fontRecHandle)->firstChar) * sizeof(short))) == -1; +} + + +/* + *--------------------------------------------------------------------------- + * + * Tk_MeasureChars -- + * + * Determine the number of characters from the string that will fit + * in the given horizontal span. The measurement is done under the + * assumption that Tk_DrawChars() will be used to actually display + * the characters. + * + * Results: + * The return value is the number of characters from source that + * fit into the span that extends from 0 to maxLength. *lengthPtr is + * filled with the x-coordinate of the right edge of the last + * character that did fit. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +int +Tk_MeasureChars( + Tk_Font tkfont, /* Font in which characters will be drawn. */ + CONST char *source, /* Characters to be displayed. Need not be + * '\0' terminated. */ + int numChars, /* Maximum number of characters to consider + * from source string. */ + int maxLength, /* If > 0, maxLength specifies the longest + * permissible line length; don't consider any + * character that would cross this + * x-position. If <= 0, then line length is + * unbounded and the flags argument is + * ignored. */ + int flags, /* Various flag bits OR-ed together: + * TK_PARTIAL_OK means include the last char + * which only partially fit on this line. + * TK_WHOLE_WORDS means stop on a word + * boundary, if possible. + * TK_AT_LEAST_ONE means return at least one + * character even if no characters fit. */ + int *lengthPtr) /* Filled with x-location just after the + * terminating character. */ +{ + short staticWidths[128]; + short *widths; + CONST char *p, *term; + int curX, termX, curIdx, sawNonSpace; + MacFont *fontPtr; + CGrafPtr saveWorld; + GDHandle saveDevice; + + if (numChars == 0) { + *lengthPtr = 0; + return 0; + } + + if (gWorld == NULL) { + Rect rect = {0, 0, 1, 1}; + + if (NewGWorld(&gWorld, 0, &rect, NULL, NULL, 0) != noErr) { + panic("NewGWorld failed in Tk_MeasureChars"); + } + } + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(gWorld, NULL); + + fontPtr = (MacFont *) tkfont; + TextFont(fontPtr->family); + TextSize(fontPtr->size); + TextFace(fontPtr->style); + + if (maxLength <= 0) { + *lengthPtr = TextWidth(source, 0, numChars); + SetGWorld(saveWorld, saveDevice); + return numChars; + } + + if (numChars > maxLength) { + /* + * Assume that all chars are at least 1 pixel wide, so there's no + * need to measure more characters than there are pixels. This + * assumption could be refined to an iterative approach that would + * use that as a starting point and try more chars if necessary (if + * there actually were some zero-width chars). + */ + + numChars = maxLength; + } + if (numChars > SHRT_MAX) { + /* + * If they are trying to measure more than 32767 chars at one time, + * it would require several separate measurements. + */ + + numChars = SHRT_MAX; + } + + widths = staticWidths; + if (numChars >= sizeof(staticWidths) / sizeof(staticWidths[0])) { + widths = (short *) ckalloc((numChars + 1) * sizeof(short)); + } + + MeasureText((short) numChars, source, widths); + + if (widths[numChars] <= maxLength) { + curX = widths[numChars]; + curIdx = numChars; + } else { + p = term = source; + curX = termX = 0; + + sawNonSpace = !isspace(UCHAR(*p)); + for (curIdx = 1; ; curIdx++) { + if (isspace(UCHAR(*p))) { + if (sawNonSpace) { + term = p; + termX = widths[curIdx - 1]; + sawNonSpace = 0; + } + } else { + sawNonSpace = 1; + } + if (widths[curIdx] > maxLength) { + curIdx--; + curX = widths[curIdx]; + break; + } + p++; + } + if (flags & TK_PARTIAL_OK) { + curIdx++; + curX = widths[curIdx]; + } + if ((curIdx == 0) && (flags & TK_AT_LEAST_ONE)) { + /* + * The space was too small to hold even one character. Since at + * least one character must always fit on a line, return the width + * of the first character. + */ + + curX = TextWidth(source, 0, 1); + curIdx = 1; + } else if (flags & TK_WHOLE_WORDS) { + /* + * Break at last word that fits on the line. + */ + + if ((flags & TK_AT_LEAST_ONE) && (term == source)) { + /* + * The space was too small to hold an entire word. This + * is the only word on the line, so just return the part of th + * word that fit. + */ + + ; + } else { + curIdx = term - source; + curX = termX; + } + } + } + + if (widths != staticWidths) { + ckfree((char *) widths); + } + + *lengthPtr = curX; + + SetGWorld(saveWorld, saveDevice); + + return curIdx; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_DrawChars -- + * + * Draw a string of characters on the screen. + * + * Results: + * None. + * + * Side effects: + * Information gets drawn on the screen. + * + *--------------------------------------------------------------------------- + */ + +void +Tk_DrawChars( + Display *display, /* Display on which to draw. */ + Drawable drawable, /* Window or pixmap in which to draw. */ + GC gc, /* Graphics context for drawing characters. */ + Tk_Font tkfont, /* Font in which characters will be drawn; + * must be the same as font used in GC. */ + CONST char *source, /* Characters to be displayed. Need not be + * '\0' terminated. All Tk meta-characters + * (tabs, control characters, and newlines) + * should be stripped out of the string that + * is passed to this function. If they are + * not stripped out, they will be displayed as + * regular printing characters. */ + int numChars, /* Number of characters in string. */ + int x, int y) /* Coordinates at which to place origin of + * string when drawing. */ +{ + MacFont *fontPtr; + MacDrawable *macWin; + RGBColor macColor, origColor; + GWorldPtr destPort; + CGrafPtr saveWorld; + GDHandle saveDevice; + short txFont, txFace, txSize; + BitMapPtr stippleMap; + + fontPtr = (MacFont *) tkfont; + macWin = (MacDrawable *) drawable; + + destPort = TkMacGetDrawablePort(drawable); + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + TkMacSetUpClippingRgn(drawable); + TkMacSetUpGraphicsPort(gc); + + txFont = tcl_macQdPtr->thePort->txFont; + txFace = tcl_macQdPtr->thePort->txFace; + txSize = tcl_macQdPtr->thePort->txSize; + GetForeColor(&origColor); + + if ((gc->fill_style == FillStippled + || gc->fill_style == FillOpaqueStippled) + && gc->stipple != None) { + Pixmap pixmap; + GWorldPtr bufferPort; + + stippleMap = TkMacMakeStippleMap(drawable, gc->stipple); + + pixmap = Tk_GetPixmap(display, drawable, + stippleMap->bounds.right, stippleMap->bounds.bottom, 0); + + bufferPort = TkMacGetDrawablePort(pixmap); + SetGWorld(bufferPort, NULL); + + TextFont(fontPtr->family); + TextSize(fontPtr->size); + TextFace(fontPtr->style); + + if (TkSetMacColor(gc->foreground, &macColor) == true) { + RGBForeColor(&macColor); + } + + ShowPen(); + MoveTo((short) 0, (short) 0); + FillRect(&stippleMap->bounds, &tcl_macQdPtr->white); + MoveTo((short) x, (short) y); + DrawText(source, 0, (short) numChars); + + SetGWorld(destPort, NULL); + CopyDeepMask(&((GrafPtr) bufferPort)->portBits, stippleMap, + &((GrafPtr) destPort)->portBits, &stippleMap->bounds, + &stippleMap->bounds, &((GrafPtr) destPort)->portRect, + srcOr, NULL); + + /* TODO: this doesn't work quite right - it does a blend. you can't + * draw white text when you have a stipple. + */ + + Tk_FreePixmap(display, pixmap); + ckfree(stippleMap->baseAddr); + ckfree((char *)stippleMap); + } else { + TextFont(fontPtr->family); + TextSize(fontPtr->size); + TextFace(fontPtr->style); + + if (TkSetMacColor(gc->foreground, &macColor) == true) { + RGBForeColor(&macColor); + } + + ShowPen(); + MoveTo((short) (macWin->xOff + x), (short) (macWin->yOff + y)); + DrawText(source, 0, (short) numChars); + } + + TextFont(txFont); + TextSize(txSize); + TextFace(txFace); + RGBForeColor(&origColor); + SetGWorld(saveWorld, saveDevice); +} + +/* + *--------------------------------------------------------------------------- + * + * AllocMacFont -- + * + * Helper for TkpGetNativeFont() and TkpGetFontFromAttributes(). + * Allocates and intializes the memory for a new TkFont that + * wraps the platform-specific data. + * + * Results: + * Returns pointer to newly constructed TkFont. + * + * The caller is responsible for initializing the fields of the + * TkFont that are used exclusively by the generic TkFont code, and + * for releasing those fields before calling TkpDeleteFont(). + * + * Side effects: + * Memory allocated. + * + *--------------------------------------------------------------------------- + */ + +static TkFont * +AllocMacFont( + TkFont *tkFontPtr, /* If non-NULL, store the information in + * this existing TkFont structure, rather than + * allocating a new structure to hold the + * font; the existing contents of the font + * will be released. If NULL, a new TkFont + * structure is allocated. */ + Tk_Window tkwin, /* For display where font will be used. */ + int family, /* Macintosh font family. */ + int size, /* Point size for Macintosh font. */ + int style) /* Macintosh style bits. */ +{ + char buf[257]; + FontInfo fi; + MacFont *fontPtr; + TkFontAttributes *faPtr; + TkFontMetrics *fmPtr; + CGrafPtr saveWorld; + GDHandle saveDevice; + + if (gWorld == NULL) { + Rect rect = {0, 0, 1, 1}; + + if (NewGWorld(&gWorld, 0, &rect, NULL, NULL, 0) != noErr) { + panic("NewGWorld failed in AllocMacFont"); + } + } + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(gWorld, NULL); + + if (tkFontPtr == NULL) { + fontPtr = (MacFont *) ckalloc(sizeof(MacFont)); + } else { + fontPtr = (MacFont *) tkFontPtr; + } + + fontPtr->font.fid = (Font) fontPtr; + + faPtr = &fontPtr->font.fa; + GetFontName(family, (StringPtr) buf); + buf[UCHAR(buf[0]) + 1] = '\0'; + faPtr->family = Tk_GetUid(buf + 1); + faPtr->pointsize = size; + faPtr->weight = (style & bold) ? TK_FW_BOLD : TK_FW_NORMAL; + faPtr->slant = (style & italic) ? TK_FS_ITALIC : TK_FS_ROMAN; + faPtr->underline = ((style & underline) != 0); + faPtr->overstrike = 0; + + fmPtr = &fontPtr->font.fm; + TextFont(family); + TextSize(size); + TextFace(style); + GetFontInfo(&fi); + fmPtr->ascent = fi.ascent; + fmPtr->descent = fi.descent; + fmPtr->maxWidth = fi.widMax; + fmPtr->fixed = (CharWidth('i') == CharWidth('w')); + + fontPtr->family = (short) family; + fontPtr->size = (short) size; + fontPtr->style = (short) style; + + SetGWorld(saveWorld, saveDevice); + + return (TkFont *) fontPtr; +} + diff --git a/mac/tkMacHLEvents.c b/mac/tkMacHLEvents.c new file mode 100644 index 0000000..39f7836 --- /dev/null +++ b/mac/tkMacHLEvents.c @@ -0,0 +1,437 @@ +/* + * tkMacHLEvents.c -- + * + * Implements high level event support for the Macintosh. Currently, + * the only event that really does anything is the Quit event. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacHLEvents.c 1.21 97/09/17 17:19:00 + */ + +#include "tcl.h" +#include "tclMacInt.h" +#include "tkMacInt.h" + +#include <Aliases.h> +#include <AppleEvents.h> +#include <SegLoad.h> +#include <ToolUtils.h> + +/* + * This is a Tcl_Event structure that the Quit AppleEvent handler + * uses to schedule the tkReallyKillMe function. + */ + +typedef struct KillEvent { + Tcl_Event header; /* Information that is standard for + * all events. */ + Tcl_Interp *interp; /* Interp that was passed to the + * Quit AppleEvent */ +} KillEvent; + +/* + * Static functions used only in this file. + */ + +static pascal OSErr QuitHandler _ANSI_ARGS_((AppleEvent* event, + AppleEvent* reply, long refcon)); +static pascal OSErr OappHandler _ANSI_ARGS_((AppleEvent* event, + AppleEvent* reply, long refcon)); +static pascal OSErr OdocHandler _ANSI_ARGS_((AppleEvent* event, + AppleEvent* reply, long refcon)); +static pascal OSErr PrintHandler _ANSI_ARGS_((AppleEvent* event, + AppleEvent* reply, long refcon)); +static pascal OSErr ScriptHandler _ANSI_ARGS_((AppleEvent* event, + AppleEvent* reply, long refcon)); +static int MissedAnyParameters _ANSI_ARGS_((AppleEvent *theEvent)); +static int ReallyKillMe _ANSI_ARGS_((Tcl_Event *eventPtr, int flags)); + +/* + *---------------------------------------------------------------------- + * + * TkMacInitAppleEvents -- + * + * Initilize the Apple Events on the Macintosh. This registers the + * core event handlers. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkMacInitAppleEvents( + Tcl_Interp *interp) /* Interp to handle basic events. */ +{ + OSErr err; + AEEventHandlerUPP OappHandlerUPP, OdocHandlerUPP, + PrintHandlerUPP, QuitHandlerUPP, ScriptHandlerUPP; + + /* + * Install event handlers for the core apple events. + */ + QuitHandlerUPP = NewAEEventHandlerProc(QuitHandler); + err = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication, + QuitHandlerUPP, (long) interp, false); + + OappHandlerUPP = NewAEEventHandlerProc(OappHandler); + err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication, + OappHandlerUPP, (long) interp, false); + + OdocHandlerUPP = NewAEEventHandlerProc(OdocHandler); + err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments, + OdocHandlerUPP, (long) interp, false); + + PrintHandlerUPP = NewAEEventHandlerProc(PrintHandler); + err = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments, + PrintHandlerUPP, (long) interp, false); + + if (interp != NULL) { + ScriptHandlerUPP = NewAEEventHandlerProc(ScriptHandler); + err = AEInstallEventHandler('misc', 'dosc', + ScriptHandlerUPP, (long) interp, false); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacDoHLEvent -- + * + * Dispatch incomming highlevel events. + * + * Results: + * None. + * + * Side effects: + * Depends on the incoming event. + * + *---------------------------------------------------------------------- + */ + +void +TkMacDoHLEvent( + EventRecord *theEvent) +{ + AEProcessAppleEvent(theEvent); + + return; +} + +/* + *---------------------------------------------------------------------- + * + * QuitHandler, OappHandler, etc. -- + * + * These are the core Apple event handlers. Only the Quit event does + * anything interesting. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static pascal OSErr +QuitHandler( + AppleEvent *theAppleEvent, + AppleEvent *reply, + long handlerRefcon) +{ + Tcl_Interp *interp = (Tcl_Interp *) handlerRefcon; + KillEvent *eventPtr; + + /* + * Call the exit command from the event loop, since you are not supposed + * to call ExitToShell in an Apple Event Handler. We put this at the head + * of Tcl's event queue because this message usually comes when the Mac is + * shutting down, and we want to kill the shell as quickly as possible. + */ + + eventPtr = (KillEvent *) ckalloc(sizeof(KillEvent)); + eventPtr->header.proc = ReallyKillMe; + eventPtr->interp = interp; + + Tcl_QueueEvent((Tcl_Event *) eventPtr, TCL_QUEUE_HEAD); + + return noErr; +} + +static pascal OSErr +OappHandler( + AppleEvent *theAppleEvent, + AppleEvent *reply, + long handlerRefcon) +{ + return noErr; +} + +static pascal OSErr +OdocHandler( + AppleEvent *theAppleEvent, + AppleEvent *reply, + long handlerRefcon) +{ + Tcl_Interp *interp = (Tcl_Interp *) handlerRefcon; + AEDescList fileSpecList; + FSSpec file; + OSErr err; + DescType type; + Size actual; + long count; + AEKeyword keyword; + long index; + Tcl_DString command; + Tcl_DString pathName; + Tcl_CmdInfo dummy; + + /* + * Don't bother if we don't have an interp or + * the open document procedure doesn't exist. + */ + + if ((interp == NULL) || + (Tcl_GetCommandInfo(interp, "tkOpenDocument", &dummy)) == 0) { + return noErr; + } + + /* + * If we get any errors wil retrieving our parameters + * we just return with no error. + */ + + err = AEGetParamDesc(theAppleEvent, keyDirectObject, + typeAEList, &fileSpecList); + if (err != noErr) { + return noErr; + } + + err = MissedAnyParameters(theAppleEvent); + if (err != noErr) { + return noErr; + } + + err = AECountItems(&fileSpecList, &count); + if (err != noErr) { + return noErr; + } + + Tcl_DStringInit(&command); + Tcl_DStringInit(&pathName); + Tcl_DStringAppend(&command, "tkOpenDocument", -1); + for (index = 1; index <= count; index++) { + int length; + Handle fullPath; + + Tcl_DStringSetLength(&pathName, 0); + err = AEGetNthPtr(&fileSpecList, index, typeFSS, + &keyword, &type, (Ptr) &file, sizeof(FSSpec), &actual); + if ( err != noErr ) { + continue; + } + + err = FSpPathFromLocation(&file, &length, &fullPath); + HLock(fullPath); + Tcl_DStringAppend(&pathName, *fullPath, length); + HUnlock(fullPath); + DisposeHandle(fullPath); + + Tcl_DStringAppendElement(&command, pathName.string); + } + + Tcl_GlobalEval(interp, command.string); + + Tcl_DStringFree(&command); + Tcl_DStringFree(&pathName); + return noErr; +} + +static pascal OSErr +PrintHandler( + AppleEvent *theAppleEvent, + AppleEvent *reply, + long handlerRefcon) +{ + return noErr; +} + +/* + *---------------------------------------------------------------------- + * + * DoScriptHandler -- + * + * This handler process the do script event. + * + * Results: + * Scedules the given event to be processed. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static pascal OSErr +ScriptHandler( + AppleEvent *theAppleEvent, + AppleEvent *reply, + long handlerRefcon) +{ + OSErr theErr; + AEDescList theDesc; + int tclErr = -1; + Tcl_Interp *interp; + char errString[128]; + + interp = (Tcl_Interp *) handlerRefcon; + + /* + * The do script event receives one parameter that should be data or a file. + */ + theErr = AEGetParamDesc(theAppleEvent, keyDirectObject, typeWildCard, + &theDesc); + if (theErr != noErr) { + sprintf(errString, "AEDoScriptHandler: GetParamDesc error %d", theErr); + theErr = AEPutParamPtr(reply, keyErrorString, typeChar, errString, + strlen(errString)); + } else if (MissedAnyParameters(theAppleEvent)) { + sprintf(errString, "AEDoScriptHandler: extra parameters"); + AEPutParamPtr(reply, keyErrorString, typeChar, errString, + strlen(errString)); + theErr = -1771; + } else { + if (theDesc.descriptorType == (DescType)'TEXT') { + short length, i; + + length = GetHandleSize(theDesc.dataHandle); + SetHandleSize(theDesc.dataHandle, length + 1); + *(*theDesc.dataHandle + length) = '\0'; + for (i=0; i<length; i++) { + if ((*theDesc.dataHandle)[i] == '\r') { + (*theDesc.dataHandle)[i] = '\n'; + } + } + + HLock(theDesc.dataHandle); + tclErr = Tcl_GlobalEval(interp, *theDesc.dataHandle); + HUnlock(theDesc.dataHandle); + } else if (theDesc.descriptorType == (DescType)'alis') { + Boolean dummy; + FSSpec theFSS; + Handle fullPath; + int length; + + theErr = ResolveAlias(NULL, (AliasHandle)theDesc.dataHandle, + &theFSS, &dummy); + if (theErr == noErr) { + FSpPathFromLocation(&theFSS, &length, &fullPath); + HLock(fullPath); + Tcl_EvalFile(interp, *fullPath); + HUnlock(fullPath); + DisposeHandle(fullPath); + } else { + sprintf(errString, "AEDoScriptHandler: file not found"); + AEPutParamPtr(reply, keyErrorString, typeChar, + errString, strlen(errString)); + } + } else { + sprintf(errString, + "AEDoScriptHandler: invalid script type '%-4.4s', must be 'alis' or 'TEXT'", + &theDesc.descriptorType); + AEPutParamPtr(reply, keyErrorString, typeChar, + errString, strlen(errString)); + theErr = -1770; + } + } + + /* + * If we actually go to run Tcl code - put the result in the reply. + */ + if (tclErr >= 0) { + if (tclErr == TCL_OK) { + AEPutParamPtr(reply, keyDirectObject, typeChar, + interp->result, strlen(interp->result)); + } else { + AEPutParamPtr(reply, keyErrorString, typeChar, + interp->result, strlen(interp->result)); + AEPutParamPtr(reply, keyErrorNumber, typeInteger, + (Ptr) &tclErr, sizeof(int)); + } + } + + AEDisposeDesc(&theDesc); + + return theErr; +} + +/* + *---------------------------------------------------------------------- + * + * ReallyKillMe -- + * + * This proc tries to kill the shell by running exit, and if that + * has not succeeded (e.g. because someone has renamed the exit + * command), calls Tcl_Exit to really kill the shell. Called from + * an event scheduled by the "Quit" AppleEvent handler. + * + * Results: + * Kills the shell. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +ReallyKillMe(Tcl_Event *eventPtr, int flags) +{ + Tcl_Interp *interp = ((KillEvent *) eventPtr)->interp; + if (interp != NULL) { + Tcl_GlobalEval(interp, "exit"); + } + Tcl_Exit(0); + + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * MissedAnyParameters -- + * + * Checks to see if parameters are still left in the event. + * + * Results: + * True or false. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +MissedAnyParameters( + AppleEvent *theEvent) +{ + DescType returnedType; + Size actualSize; + OSErr err; + + err = AEGetAttributePtr(theEvent, keyMissedKeywordAttr, typeWildCard, + &returnedType, NULL, 0, &actualSize); + + return (err != errAEDescNotFound); +} diff --git a/mac/tkMacInit.c b/mac/tkMacInit.c new file mode 100644 index 0000000..bb1f8b3 --- /dev/null +++ b/mac/tkMacInit.c @@ -0,0 +1,240 @@ +/* + * tkMacInit.c -- + * + * This file contains Mac-specific interpreter initialization + * functions. + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacInit.c 1.30 96/12/17 15:20:16 + */ + +#include <Resources.h> +#include <Files.h> +#include <TextUtils.h> +#include <Strings.h> +#include "tkInt.h" +#include "tkMacInt.h" +#include "tclMacInt.h" + +/* + * The following global is used by various parts of Tk to access + * information in the global qd variable. It is provided as a pointer + * in the AppInit because we don't assume that Tk is running as an + * application. For example, Tk could be a plugin and may not have + * access to the qd variable. This mechanism provides a way for the + * container application to give a pointer to the qd variable. + */ + +QDGlobalsPtr tcl_macQdPtr = NULL; + +/* + *---------------------------------------------------------------------- + * + * TkpInit -- + * + * Performs Mac-specific interpreter initialization related to the + * tk_library variable. + * + * Results: + * A standard Tcl completion code (TCL_OK or TCL_ERROR). Also + * leaves information in interp->result. + * + * Side effects: + * Sets "tk_library" Tcl variable, runs initialization scripts + * for Tk. + * + *---------------------------------------------------------------------- + */ + +int +TkpInit( + Tcl_Interp *interp) /* Interp to initialize. */ +{ + char *libDir, *tempPath; + Tcl_DString path; + int result; + + /* + * The following does not work with + * safe interps because file exists is restricted. + * to be fixed using [interp issafe] like in Unix & Windows. + */ + static char initCmd[] = + "if [file exists $tk_library:tk.tcl] {\n\ + source $tk_library:tk.tcl\n\ + source $tk_library:button.tcl\n\ + source $tk_library:entry.tcl\n\ + source $tk_library:listbox.tcl\n\ + source $tk_library:menu.tcl\n\ + source $tk_library:scale.tcl\n\ + source $tk_library:scrlbar.tcl\n\ + source $tk_library:text.tcl\n\ + source $tk_library:comdlg.tcl\n\ + source $tk_library:msgbox.tcl\n\ + } else {\n\ + set msg \"can't find tk resource or $tk_library:tk.tcl;\"\n\ + append msg \" perhaps you need to\\ninstall Tk or set your \"\n\ + append msg \"TK_LIBRARY environment variable?\"\n\ + error $msg\n\ + }"; + + Tcl_DStringInit(&path); + + /* + * The tk_library path can be found in several places. Here is the order + * in which the are searched. + * 1) the variable may already exist + * 2) env array + * 3) System Folder:Extensions:Tool Command Language: + */ + + libDir = Tcl_GetVar(interp, "tk_library", TCL_GLOBAL_ONLY); + if (libDir == NULL) { + libDir = Tcl_GetVar2(interp, "env", "TK_LIBRARY", TCL_GLOBAL_ONLY); + } + if (libDir == NULL) { + tempPath = Tcl_GetVar2(interp, "env", "EXT_FOLDER", TCL_GLOBAL_ONLY); + if (tempPath != NULL) { + Tcl_DString libPath; + + Tcl_JoinPath(1, &tempPath, &path); + + Tcl_DStringInit(&libPath); + Tcl_DStringAppend(&libPath, ":Tool Command Language:tk", -1); + Tcl_DStringAppend(&libPath, TK_VERSION, -1); + Tcl_JoinPath(1, &libPath.string, &path); + Tcl_DStringFree(&libPath); + libDir = path.string; + } + } + if (libDir == NULL) { + libDir = "no library"; + } + + /* + * Assign path to the global Tcl variable tcl_library. + */ + Tcl_SetVar(interp, "tk_library", libDir, TCL_GLOBAL_ONLY); + Tcl_DStringFree(&path); + + /* + * Source the needed Tk libraries from the resource + * fork of the application. + */ + result = Tcl_MacEvalResource(interp, "tk", 0, NULL); + result |= Tcl_MacEvalResource(interp, "button", 0, NULL); + result |= Tcl_MacEvalResource(interp, "entry", 0, NULL); + result |= Tcl_MacEvalResource(interp, "listbox", 0, NULL); + result |= Tcl_MacEvalResource(interp, "menu", 0, NULL); + result |= Tcl_MacEvalResource(interp, "scale", 0, NULL); + result |= Tcl_MacEvalResource(interp, "scrollbar", 0, NULL); + result |= Tcl_MacEvalResource(interp, "text", 0, NULL); + result |= Tcl_MacEvalResource(interp, "dialog", 0, NULL); + result |= Tcl_MacEvalResource(interp, "focus", 0, NULL); + result |= Tcl_MacEvalResource(interp, "optionMenu", 0, NULL); + result |= Tcl_MacEvalResource(interp, "palette", 0, NULL); + result |= Tcl_MacEvalResource(interp, "tearoff", 0, NULL); + result |= Tcl_MacEvalResource(interp, "tkerror", 0, NULL); + result |= Tcl_MacEvalResource(interp, "comdlg", 0, NULL); + result |= Tcl_MacEvalResource(interp, "msgbox", 0, NULL); + + if (result != TCL_OK) { + result = Tcl_Eval(interp, initCmd); + } + return result; +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetAppName -- + * + * Retrieves the name of the current application from a platform + * specific location. On the Macintosh we look to see if the + * App Name is specified in a resource. If not, the application + * name is the root of the tail of the path contained in the tcl + * variable argv0. + * + * Results: + * Returns the application name in the given Tcl_DString. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpGetAppName( + Tcl_Interp *interp, /* The main interpreter. */ + Tcl_DString *namePtr) /* A previously initialized Tcl_DString. */ +{ + int argc; + char **argv = NULL, *name, *p; + Handle h = NULL; + + h = GetNamedResource('STR ', "\pTk App Name"); + if (h != NULL) { + HLock(h); + Tcl_DStringAppend(namePtr, (*h)+1, **h); + HUnlock(h); + ReleaseResource(h); + return; + } + + name = Tcl_GetVar(interp, "argv0", TCL_GLOBAL_ONLY); + if (name != NULL) { + Tcl_SplitPath(name, &argc, &argv); + if (argc > 0) { + name = argv[argc-1]; + p = strrchr(name, '.'); + if (p != NULL) { + *p = '\0'; + } + } else { + name = NULL; + } + } + if ((name == NULL) || (*name == 0)) { + name = "tk"; + } + Tcl_DStringAppend(namePtr, name, -1); + if (argv != NULL) { + ckfree((char *)argv); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpDisplayWarning -- + * + * This routines is called from Tk_Main to display warning + * messages that occur during startup. + * + * Results: + * None. + * + * Side effects: + * Displays a message box. + * + *---------------------------------------------------------------------- + */ + +void +TkpDisplayWarning( + char *msg, /* Message to be displayed. */ + char *title) /* Title of warning. */ +{ + Tcl_DString ds; + Tcl_DStringInit(&ds); + Tcl_DStringAppend(&ds, title, -1); + Tcl_DStringAppend(&ds, ": ", -1); + Tcl_DStringAppend(&ds, msg, -1); + panic(Tcl_DStringValue(&ds)); + Tcl_DStringFree(&ds); +} diff --git a/mac/tkMacInt.h b/mac/tkMacInt.h new file mode 100644 index 0000000..fcb8174 --- /dev/null +++ b/mac/tkMacInt.h @@ -0,0 +1,282 @@ +/* + * tkMacInt.h -- + * + * Declarations of Macintosh specific shared variables and procedures. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacInt.h 1.67 97/11/20 18:30:38 + */ + +#ifndef _TKMACINT +#define _TKMACINT + +#include "tkInt.h" +#include "tkPort.h" + +#ifndef _TKMAC +# include "tkMac.h" +#endif /* _TKMAC */ + + +#include <AppleEvents.h> +#include <Windows.h> +#include <QDOffscreen.h> +#include <Menus.h> + +#define TK_MAC_68K_STACK_GROWTH (256*1024) + +struct TkWindowPrivate { + TkWindow *winPtr; /* Ptr to tk window or NULL if Pixmap */ + GWorldPtr portPtr; /* Either WindowRef or off screen world */ + int xOff; /* X offset from toplevel window */ + int yOff; /* Y offset from toplevel window */ + RgnHandle clipRgn; /* Visable region of window */ + RgnHandle aboveClipRgn; /* Visable region of window & it's children */ + int referenceCount; /* Don't delete toplevel until children are + * gone. */ + struct TkWindowPrivate *toplevel; /* Pointer to the toplevel + * datastruct. */ + int flags; /* Various state see defines below. */ +}; +typedef struct TkWindowPrivate MacDrawable; + +/* + * This list is used to keep track of toplevel windows that have a Mac + * window attached. This is useful for several things, not the least + * of which is maintaining floating windows. + */ + +typedef struct TkMacWindowList { + struct TkMacWindowList *nextPtr; /* The next window in the list. */ + TkWindow *winPtr; /* This window */ +} TkMacWindowList; + +/* + * Defines use for the flags field of the MacDrawable data structure. + */ + +#define TK_SCROLLBAR_GROW 1 +#define TK_CLIP_INVALID 2 +#define TK_HOST_EXISTS 4 +#define TK_DRAWN_UNDER_MENU 8 + +/* + * I am reserving TK_EMBEDDED = 0x100 in the MacDrawable flags + * This is defined in tk.h. We need to duplicate the TK_EMBEDDED flag in the + * TkWindow structure for the window, but in the MacWin. This way we can still tell + * what the correct port is after the TKWindow structure has been freed. This + * actually happens when you bind destroy of a toplevel to Destroy of a child. + */ + +/* + * Defines used for TkMacInvalidateWindow + */ + +#define TK_WINDOW_ONLY 0 +#define TK_PARENT_WINDOW 1 + +/* + * Accessor for the privatePtr flags field for the TK_HOST_EXISTS field + */ + +#define TkMacHostToplevelExists(tkwin) \ + (((TkWindow *) (tkwin))->privatePtr->toplevel->flags & TK_HOST_EXISTS) + +/* + * Defines use for the flags argument to TkGenWMConfigureEvent. + */ + +#define TK_LOCATION_CHANGED 1 +#define TK_SIZE_CHANGED 2 +#define TK_BOTH_CHANGED 3 + +/* + * Variables shared among various Mac Tk modules but are not + * exported to the outside world. + */ + +extern int tkMacAppInFront; + +/* + * Globals shared among Macintosh Tk + */ + +extern MenuHandle tkAppleMenu; /* Handle to the Apple Menu */ +extern MenuHandle tkFileMenu; /* Handles to menus */ +extern MenuHandle tkEditMenu; /* Handles to menus */ +extern RgnHandle tkMenuCascadeRgn; /* A region to clip with. */ +extern int tkUseMenuCascadeRgn; /* If this is 1, clipping code + * should intersect tkMenuCascadeRgn + * before drawing occurs. + * tkMenuCascadeRgn will only + * be valid when the value of this + * variable is 1. */ +extern TkMacWindowList *tkMacWindowListPtr; + /* The list of toplevels */ + +/* + * The following types and defines are for MDEF support. + */ + +#if STRUCTALIGNMENTSUPPORTED +#pragma options align=mac8k +#endif +typedef struct TkMenuLowMemGlobals { + long menuDisable; /* A combination of the menu and the item + * that the mouse is currently over. */ + short menuTop; /* Where in global coords the top of the + * menu is. */ + short menuBottom; /* Where in global coords the bottom of + * the menu is. */ + Rect itemRect; /* This is the rectangle of the currently + * selected item. */ + short scrollFlag; /* This is used by the MDEF and the + * Menu Manager to control when scrolling + * starts. With hierarchicals, an + * mChooseMsg can come before an + * mDrawMsg, and scrolling should not + * occur until after the mDrawMsg. + * The mDrawMsg sets this flag; + * mChooseMsg checks the flag and + * does not scroll if it is set; + * and then resets the flag. */ +} TkMenuLowMemGlobals; +#if STRUCTALIGNMENTSUPPORTED +#pragma options align=reset +#endif + +typedef pascal void (*TkMenuDefProcPtr) (short message, MenuHandle theMenu, + Rect *menuRectPtr, Point hitPt, short *whichItemPtr, + TkMenuLowMemGlobals *globalsPtr); +enum { + tkUppMenuDefProcInfo = kPascalStackBased + | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(short))) + | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(MenuRef))) + | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(Rect*))) + | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(Point))) + | STACK_ROUTINE_PARAMETER(5, SIZE_CODE(sizeof(short*))) + | STACK_ROUTINE_PARAMETER(6, SIZE_CODE(sizeof(TkMenuLowMemGlobals *))) +}; + +#if GENERATINGCFM +typedef UniversalProcPtr TkMenuDefUPP; +#else +typedef TkMenuDefProcPtr TkMenuDefUPP; +#endif + +#if GENERATINGCFM +#define TkNewMenuDefProc(userRoutine) \ + (TkMenuDefUPP) NewRoutineDescriptor((ProcPtr)(userRoutine), \ + tkUppMenuDefProcInfo, GetCurrentArchitecture()) +#else +#define TkNewMenuDefProc(userRoutine) \ + ((TkMenuDefUPP) (userRoutine)) +#endif + +#if GENERATINGCFM +#define TkCallMenuDefProc(userRoutine, message, theMenu, menuRectPtr, hitPt, \ + whichItemPtr, globalsPtr) \ + CallUniversalProc((UniversalProcPtr)(userRoutine), TkUppMenuDefProcInfo, \ + (message), (theMenu), (menuRectPtr), (hitPt), (whichItemPtr), \ + (globalsPtr)) +#else +#define TkCallMenuDefProc(userRoutine, message, theMenu, menuRectPtr, hitPt, \ + whichItemPtr, globalsPtr) \ + (*(userRoutine))((message), (theMenu), (menuRectPtr), (hitPt), \ + (whichItemPtr), (globalsPtr)) +#endif + +/* + * Internal procedures shared among Macintosh Tk modules but not exported + * to the outside world: + */ + +extern int HandleWMEvent _ANSI_ARGS_((EventRecord *theEvent)); +extern void TkAboutDlg _ANSI_ARGS_((void)); +extern void TkCreateMacEventSource _ANSI_ARGS_((void)); +extern void TkFontList _ANSI_ARGS_((Tcl_Interp *interp, + Display *display)); +extern Window TkGetTransientMaster _ANSI_ARGS_((TkWindow *winPtr)); +extern int TkGenerateButtonEvent _ANSI_ARGS_((int x, int y, + Window window, unsigned int state)); +extern int TkGetCharPositions _ANSI_ARGS_(( + XFontStruct *font_struct, char *string, + int count, short *buffer)); +extern void TkGenWMDestroyEvent _ANSI_ARGS_((Tk_Window tkwin)); +extern void TkGenWMConfigureEvent _ANSI_ARGS_((Tk_Window tkwin, + int x, int y, int width, int height, int flags)); +extern unsigned int TkMacButtonKeyState _ANSI_ARGS_((void)); +extern void TkMacClearMenubarActive _ANSI_ARGS_((void)); +extern int TkMacConvertEvent _ANSI_ARGS_((EventRecord *eventPtr)); +extern int TkMacDispatchMenuEvent _ANSI_ARGS_((int menuID, + int index)); +extern void TkMacInstallCursor _ANSI_ARGS_((int resizeOverride)); +extern int TkMacConvertTkEvent _ANSI_ARGS_((EventRecord *eventPtr, + Window window)); +extern void TkMacHandleTearoffMenu _ANSI_ARGS_((void)); +extern void tkMacInstallMWConsole _ANSI_ARGS_(( + Tcl_Interp *interp)); +extern void TkMacInvalClipRgns _ANSI_ARGS_((TkWindow *winPtr)); +extern void TkMacDoHLEvent _ANSI_ARGS_((EventRecord *theEvent)); +extern void TkMacFontInfo _ANSI_ARGS_((Font fontId, short *family, + short *style, short *size)); +extern Time TkMacGenerateTime _ANSI_ARGS_(()); +extern GWorldPtr TkMacGetDrawablePort _ANSI_ARGS_((Drawable drawable)); +extern TkWindow * TkMacGetScrollbarGrowWindow _ANSI_ARGS_(( + TkWindow *winPtr)); +extern Window TkMacGetXWindow _ANSI_ARGS_((WindowRef macWinPtr)); +extern int TkMacGrowToplevel _ANSI_ARGS_((WindowRef whichWindow, + Point start)); +extern void TkMacHandleMenuSelect _ANSI_ARGS_((long mResult, + int optionKeyPressed)); +extern void TkMacInitAppleEvents _ANSI_ARGS_((Tcl_Interp *interp)); +extern void TkMacInitMenus _ANSI_ARGS_((Tcl_Interp *interp)); +extern void TkMacInvalidateWindow _ANSI_ARGS_((MacDrawable *macWin, int flag)); +extern int TkMacIsCharacterMissing _ANSI_ARGS_((Tk_Font tkfont, + unsigned int searchChar)); +extern void TkMacMakeRealWindowExist _ANSI_ARGS_(( + TkWindow *winPtr)); +extern BitMapPtr TkMacMakeStippleMap(Drawable, Drawable); +extern void TkMacMenuClick _ANSI_ARGS_((void)); +extern void TkMacRegisterOffScreenWindow _ANSI_ARGS_((Window window, + GWorldPtr portPtr)); +extern int TkMacResizable _ANSI_ARGS_((TkWindow *winPtr)); +extern void TkMacSetEmbedRgn _ANSI_ARGS_((TkWindow *winPtr, RgnHandle rgn)); +extern void TkMacSetHelpMenuItemCount _ANSI_ARGS_((void)); +extern void TkMacSetScrollbarGrow _ANSI_ARGS_((TkWindow *winPtr, + int flag)); +extern void TkMacSetUpClippingRgn _ANSI_ARGS_((Drawable drawable)); +extern void TkMacSetUpGraphicsPort _ANSI_ARGS_((GC gc)); +extern void TkMacUpdateClipRgn _ANSI_ARGS_((TkWindow *winPtr)); +extern void TkMacUnregisterMacWindow _ANSI_ARGS_((GWorldPtr portPtr)); +extern int TkMacUseMenuID _ANSI_ARGS_((short macID)); +extern RgnHandle TkMacVisableClipRgn _ANSI_ARGS_((TkWindow *winPtr)); +extern void TkMacWinBounds _ANSI_ARGS_((TkWindow *winPtr, + Rect *geometry)); +extern void TkMacWindowOffset _ANSI_ARGS_((WindowRef wRef, + int *xOffset, int *yOffset)); +extern void TkResumeClipboard _ANSI_ARGS_((void)); +extern int TkSetMacColor _ANSI_ARGS_((unsigned long pixel, + RGBColor *macColor)); +extern void TkSetWMName _ANSI_ARGS_((TkWindow *winPtr, + Tk_Uid titleUid)); +extern void TkSuspendClipboard _ANSI_ARGS_((void)); +extern int TkWMGrowToplevel _ANSI_ARGS_((WindowRef whichWindow, + Point start)); +extern int TkMacZoomToplevel _ANSI_ARGS_((WindowPtr whichWindow, + Point where, short zoomPart)); +extern Tk_Window Tk_TopCoordsToWindow _ANSI_ARGS_((Tk_Window tkwin, + int rootX, int rootY, int *newX, int *newY)); +extern MacDrawable * TkMacContainerId _ANSI_ARGS_((TkWindow *winPtr)); +extern MacDrawable * TkMacGetHostToplevel _ANSI_ARGS_((TkWindow *winPtr)); +/* + * The following prototypes need to go into tkMac.h + */ +EXTERN void Tk_UpdatePointer _ANSI_ARGS_((Tk_Window tkwin, + int x, int y, int state)); + +#endif /* _TKMACINT */ diff --git a/mac/tkMacKeyboard.c b/mac/tkMacKeyboard.c new file mode 100644 index 0000000..a1dfad8 --- /dev/null +++ b/mac/tkMacKeyboard.c @@ -0,0 +1,384 @@ +/* + * tkMacKeyboard.c -- + * + * Routines to support keyboard events on the Macintosh. + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacKeyboard.c 1.14 96/08/15 15:34:00 + */ + +#include "tkInt.h" +#include "Xlib.h" +#include "keysym.h" + +#include <Events.h> +#include <Script.h> + +typedef struct { + short keycode; /* Macintosh keycode */ + KeySym keysym; /* X windows Keysym */ +} KeyInfo; + +static KeyInfo keyArray[] = { + {0x4C, XK_Return}, + {0x24, XK_Return}, + {0x33, XK_BackSpace}, + {0x75, XK_Delete}, + {0x30, XK_Tab}, + {0x74, XK_Page_Up}, + {0x79, XK_Page_Down}, + {0x73, XK_Home}, + {0x77, XK_End}, + {0x7B, XK_Left}, + {0x7C, XK_Right}, + {0x7E, XK_Up}, + {0x7D, XK_Down}, + {0x72, XK_Help}, + {0x35, XK_Escape}, + {0x47, XK_Clear}, + {0, 0} +}; + +static KeyInfo vituralkeyArray[] = { + {122, XK_F1}, + {120, XK_F2}, + {99, XK_F3}, + {118, XK_F4}, + {96, XK_F5}, + {97, XK_F6}, + {98, XK_F7}, + {100, XK_F8}, + {101, XK_F9}, + {109, XK_F10}, + {103, XK_F11}, + {111, XK_F12}, + {105, XK_F13}, + {107, XK_F14}, + {113, XK_F15}, + {0, 0} +}; + +static int initialized = 0; +static Tcl_HashTable keycodeTable; /* keyArray hashed by keycode value. */ +static Tcl_HashTable vkeyTable; /* vituralkeyArray hashed by virtual + keycode value. */ +static Ptr KCHRPtr; /* Pointer to 'KCHR' resource. */ + +/* + * Prototypes for static functions used in this file. + */ +static void InitKeyMaps _ANSI_ARGS_((void)); + + +/* + *---------------------------------------------------------------------- + * + * InitKeyMaps -- + * + * Creates hash tables used by some of the functions in this file. + * + * Results: + * None. + * + * Side effects: + * Allocates memory & creates some hash tables. + * + *---------------------------------------------------------------------- + */ + +static void +InitKeyMaps() +{ + register Tcl_HashEntry *hPtr; + register KeyInfo *kPtr; + int dummy; + + Tcl_InitHashTable(&keycodeTable, TCL_ONE_WORD_KEYS); + for (kPtr = keyArray; kPtr->keycode != 0; kPtr++) { + hPtr = Tcl_CreateHashEntry(&keycodeTable, (char *) kPtr->keycode, + &dummy); + Tcl_SetHashValue(hPtr, kPtr->keysym); + } + Tcl_InitHashTable(&vkeyTable, TCL_ONE_WORD_KEYS); + for (kPtr = vituralkeyArray; kPtr->keycode != 0; kPtr++) { + hPtr = Tcl_CreateHashEntry(&vkeyTable, (char *) kPtr->keycode, + &dummy); + Tcl_SetHashValue(hPtr, kPtr->keysym); + } + KCHRPtr = (Ptr) GetScriptManagerVariable(smKCHRCache); + initialized = 1; +} + +/* + *---------------------------------------------------------------------- + * + * XKeycodeToKeysym -- + * + * Translate from a system-dependent keycode to a + * system-independent keysym. + * + * Results: + * Returns the translated keysym, or NoSymbol on failure. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +KeySym +XKeycodeToKeysym( + Display* display, + KeyCode keycode, + int index) +{ + register Tcl_HashEntry *hPtr; + register char c; + char virtualKey; + int newKeycode; + unsigned long dummy, newChar; + + if (!initialized) { + InitKeyMaps(); + } + + c = keycode & charCodeMask; + virtualKey = (keycode & keyCodeMask) >> 8; + + /* + * When determining what keysym to produce we firt check to see if + * the key is a function key. We then check to see if the character + * is another non-printing key. Finally, we return the key syms + * for all ASCI chars. + */ + if (c == 0x10) { + hPtr = Tcl_FindHashEntry(&vkeyTable, (char *) virtualKey); + if (hPtr != NULL) { + return (KeySym) Tcl_GetHashValue(hPtr); + } + } + + + hPtr = Tcl_FindHashEntry(&keycodeTable, (char *) virtualKey); + if (hPtr != NULL) { + return (KeySym) Tcl_GetHashValue(hPtr); + } + + /* + * Recompute the character based on the Shift key only. + * TODO: The index may also specify the NUM_LOCK. + */ + newKeycode = virtualKey; + if (index & 0x01) { + newKeycode += 0x0200; + } + dummy = 0; + newChar = KeyTranslate(KCHRPtr, (short) newKeycode, &dummy); + c = newChar & charCodeMask; + + if (c >= XK_space && c < XK_asciitilde) { + return c; + } + + return NoSymbol; +} + +/* + *---------------------------------------------------------------------- + * + * XLookupString -- + * + * Retrieve the string equivalent for the given keyboard event. + * + * Results: + * Returns the number of characters stored in buffer_return. + * + * Side effects: + * Retrieves the characters stored in the event and inserts them + * into buffer_return. + * + *---------------------------------------------------------------------- + */ + +int +XLookupString( + XKeyEvent* event_struct, + char* buffer_return, + int bytes_buffer, + KeySym* keysym_return, + XComposeStatus* status_in_out) +{ + register Tcl_HashEntry *hPtr; + char string[3]; + char virtualKey; + char c; + + if (!initialized) { + InitKeyMaps(); + } + + c = event_struct->keycode & charCodeMask; + string[0] = c; + string[1] = '\0'; + + /* + * Just return NULL if the character is a function key or another + * non-printing key. + */ + if (c == 0x10) { + string[0] = '\0'; + } else { + virtualKey = (event_struct->keycode & keyCodeMask) >> 8; + hPtr = Tcl_FindHashEntry(&keycodeTable, (char *) virtualKey); + if (hPtr != NULL) { + string[0] = '\0'; + } + } + + if (buffer_return != NULL) { + strncpy(buffer_return, string, bytes_buffer); + } + + return strlen(string); +} + +/* + *---------------------------------------------------------------------- + * + * XGetModifierMapping -- + * + * Fetch the current keycodes used as modifiers. + * + * Results: + * Returns a new modifier map. + * + * Side effects: + * Allocates a new modifier map data structure. + * + *---------------------------------------------------------------------- + */ + +XModifierKeymap * +XGetModifierMapping( + Display* display) +{ + XModifierKeymap * modmap; + + modmap = (XModifierKeymap *) ckalloc(sizeof(XModifierKeymap)); + modmap->max_keypermod = 0; + modmap->modifiermap = NULL; + return modmap; +} + +/* + *---------------------------------------------------------------------- + * + * XFreeModifiermap -- + * + * Deallocate a modifier map that was created by + * XGetModifierMapping. + * + * Results: + * None. + * + * Side effects: + * Frees the datastructure referenced by modmap. + * + *---------------------------------------------------------------------- + */ + +void +XFreeModifiermap( + XModifierKeymap *modmap) +{ + if (modmap->modifiermap != NULL) { + ckfree((char *) modmap->modifiermap); + } + ckfree((char *) modmap); +} + +/* + *---------------------------------------------------------------------- + * + * XKeysymToString, XStringToKeysym -- + * + * These X window functions map Keysyms to strings & strings to + * keysyms. However, Tk already does this for the most common keysyms. + * Therefor, these functions only need to support keysyms that will be + * specific to the Macintosh. Currently, there are none. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +char * +XKeysymToString( + KeySym keysym) +{ + return NULL; +} + +KeySym +XStringToKeysym( + const char* string) +{ + return NoSymbol; +} + +/* + *---------------------------------------------------------------------- + * + * XKeysymToKeycode -- + * + * The function XKeysymToKeycode is only used by tkTest.c and + * currently only implementes the support for keys used in the + * Tk test suite. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +KeyCode +XKeysymToKeycode( + Display* display, + KeySym keysym) +{ + KeyCode keycode = 0; + char virtualKeyCode = 0; + + if ((keysym >= XK_space) && (XK_asciitilde)) { + if (keysym == 'a') { + virtualKeyCode = 0x00; + } else if (keysym == 'b' || keysym == 'B') { + virtualKeyCode = 0x0B; + } else if (keysym == 'c') { + virtualKeyCode = 0x08; + } else if (keysym == 'x' || keysym == 'X') { + virtualKeyCode = 0x07; + } else if (keysym == 'z') { + virtualKeyCode = 0x06; + } else if (keysym == ' ') { + virtualKeyCode = 0x31; + } else if (keysym == XK_Return) { + virtualKeyCode = 0x24; + keysym = '\r'; + } + keycode = keysym + ((virtualKeyCode << 8) & keyCodeMask); + } + + return keycode; +} diff --git a/mac/tkMacLibrary.r b/mac/tkMacLibrary.r new file mode 100644 index 0000000..c86954a --- /dev/null +++ b/mac/tkMacLibrary.r @@ -0,0 +1,510 @@ +/* + * tkMacLibrary.r -- + * + * This file creates resources for use in most Tk applications. + * This is designed to be an example of using the Tcl/Tk + * libraries in a Macintosh Application. + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacLibrary.r 1.9 97/11/20 18:31:20 + */ + +/* + * New style DLOG templates have an extra field for the positioning + * options for the Dialog Box. We will not use this, for now, so we + * turn it off here. + */ + +#define DLOG_RezTemplateVersion 0 + +#include <Types.r> +#include <SysTypes.r> +#include <AEUserTermTypes.r> + +/* + * The folowing include and defines help construct + * the version string for Tcl. + */ + +#define RESOURCE_INCLUDED +#include <tcl.h> +#include "tk.h" + +#if (TK_RELEASE_LEVEL == 0) +# define RELEASE_LEVEL alpha +#elif (TK_RELEASE_LEVEL == 1) +# define RELEASE_LEVEL beta +#elif (TK_RELEASE_LEVEL == 2) +# define RELEASE_LEVEL final +#endif + +#if (TK_RELEASE_LEVEL == 2) +# define MINOR_VERSION (TK_MINOR_VERSION * 16) + TK_RELEASE_SERIAL +#else +# define MINOR_VERSION TK_MINOR_VERSION * 16 +#endif + +#define RELEASE_CODE 0x00 + +resource 'vers' (1) { + TK_MAJOR_VERSION, MINOR_VERSION, + RELEASE_LEVEL, 0x00, verUS, + TK_PATCH_LEVEL, + TK_PATCH_LEVEL ", by Ray Johnson © 1993-1996" "\n" "Sun Microsystems Labratories" +}; + +resource 'vers' (2) { + TK_MAJOR_VERSION, MINOR_VERSION, + RELEASE_LEVEL, 0x00, verUS, + TK_PATCH_LEVEL, + "Tk Library " TK_PATCH_LEVEL " © 1993-1996" +}; + +#define TK_LIBRARY_RESOURCES 3000 +/* + * The -16397 string will be displayed by Finder when a user + * tries to open the shared library. The string should + * give the user a little detail about the library's capabilities + * and enough information to install the library in the correct location. + * A similar string should be placed in all shared libraries. + */ +resource 'STR ' (-16397, purgeable) { + "Tk Library\n\n" + "This is the library needed to run Tcl/Tk programs. " + "To work properly, it should be placed in the ŒTool Command Language¹ folder " + "within the Extensions folder." +}; + + +/* + * We now load the Tk library into the resource fork of the library. + */ + +read 'TEXT' (TK_LIBRARY_RESOURCES+1, "tk", purgeable) + "::library:tk.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+2, "button", purgeable) + "::library:button.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+3, "dialog", purgeable) + "::library:dialog.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+4, "entry", purgeable) + "::library:entry.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+5, "focus", purgeable) + "::library:focus.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+6, "listbox", purgeable) + "::library:listbox.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+7, "menu", purgeable) + "::library:menu.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+8, "optionMenu", purgeable) + "::library:optMenu.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+9, "palette", purgeable) + "::library:palette.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+10, "scale", purgeable) + "::library:scale.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+11, "scrollbar", purgeable) + "::library:scrlbar.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+12, "tearoff", purgeable) + "::library:tearoff.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+13, "text", purgeable) + "::library:text.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+14, "tkerror", purgeable) + "::library:bgerror.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+15, "Console", purgeable) + "::library:console.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+16, "msgbox", purgeable, preload) + "::library:msgbox.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+17, "comdlg", purgeable, preload) + "::library:comdlg.tcl"; +read 'TEXT' (TK_LIBRARY_RESOURCES+18, "prolog", purgeable, preload) + "::library:prolog.ps"; + +/* + * The following two resources define the default "About Box" for Mac Tk. + * This dialog appears if the "About Tk..." menu item is selected from + * the Apple menu. This dialog may be overridden by defining a Tcl procedure + * with the name of "tkAboutDialog". If this procedure is defined the + * default dialog will not be shown and the Tcl procedure is expected to + * create and manage an About Dialog box. + */ + +data 'DLOG' (128, "Default About Box", purgeable) { + $"0055 006B 00F3 0196 0001 0100 0100 0000" + $"0000 0081 0000 280A" +}; + +resource 'DITL' (129, "About Box", purgeable) { + { + {128, 128, 148, 186}, Button {enabled, "Ok"}, + { 14, 108, 117, 298}, StaticText {disabled, + "Wish - Windowing Shell" "\n" "based on Tcl " + TCL_PATCH_LEVEL " & Tk " TK_PATCH_LEVEL "\n\n" "Ray Johnson" + "Sun Microsystems Labs" "\n" "ray.johnson@eng.sun.com"}, + { 11, 24, 111, 92}, Picture {enabled, 128} + } +}; + +data 'PICT' (128, purgeable) { + $"13A4 0000 0000 0064 0044 0011 02FF 0C00" + $"FFFE 0000 0048 0000 0048 0000 0000 0000" + $"0064 0044 0000 0000 0001 000A 0000 0000" + $"0064 0044 0099 8044 0000 0000 0064 0044" + $"0000 0000 0000 0000 0048 0000 0048 0000" + $"0000 0008 0001 0008 0000 0000 0108 00D8" + $"0000 0000 0001 5A5A 8000 00FF 3736 FF00" + $"FF00 FF00 3535 FF00 FF00 CC00 3434 FF00" + $"FF00 9900 3333 FF00 FF00 6600 3736 FF00" + $"FF00 3300 3535 FF00 FF00 0000 3434 FF00" + $"CC00 FF00 3333 FF00 CC00 CC00 3736 FF00" + $"CC00 9900 3535 FF00 CC00 6600 FAFA FF00" + $"CC00 3300 3333 FF00 CC00 0000 3130 FF00" + $"9900 FF00 2F2F FF00 9900 CC00 FAFA FF00" + $"9900 9900 F9F9 FF00 9900 6600 3130 FF00" + $"9900 3300 2F2F FF00 9900 0000 2E2E FF00" + $"6600 FF00 F9F9 FF00 6600 CC00 3130 FF00" + $"6600 9900 2F2F FF00 6600 6600 2E2E FF00" + $"6600 3300 2D2D FF00 6600 0000 3130 FF00" + $"3300 FF00 2F2F FF00 3300 CC00 2E2E FF00" + $"3300 9900 2D2D FF00 3300 6600 3130 FF00" + $"3300 3300 2F2F FF00 3300 0000 2E2E FF00" + $"0000 FF00 2D2D FF00 0000 CC00 3130 FF00" + $"0000 9900 2F2F FF00 0000 6600 2E2E FF00" + $"0000 3300 2DF8 FF00 0000 0000 2B2A CC00" + $"FF00 FF00 2929 CC00 FF00 CC00 2828 CC00" + $"FF00 9900 27F8 CC00 FF00 6600 2B2A CC00" + $"FF00 3300 2929 CC00 FF00 0000 2828 CC00" + $"CC00 FF00 2727 CC00 CC00 CC00 2B2A CC00" + $"CC00 9900 2929 CC00 CC00 6600 2828 CC00" + $"CC00 3300 2727 CC00 CC00 0000 2B2A CC00" + $"9900 FF00 2929 CC00 9900 CC00 2828 CC00" + $"9900 9900 2727 CC00 9900 6600 DBDB CC00" + $"9900 3300 4747 CC00 9900 0000 4646 CC00" + $"6600 FF00 4545 CC00 6600 CC00 DBDB CC00" + $"6600 9900 4747 CC00 6600 6600 4646 CC00" + $"6600 3300 4545 CC00 6600 0000 DBDB CC00" + $"3300 FF00 4747 CC00 3300 CC00 4646 CC00" + $"3300 9900 4545 CC00 3300 6600 DBDB CC00" + $"3300 3300 4141 CC00 3300 0000 4040 CC00" + $"0000 FF00 3F3F CC00 0000 CC00 4342 CC00" + $"0000 9900 4141 CC00 0000 6600 4040 CC00" + $"0000 3300 3F3F CC00 0000 0000 4342 9900" + $"FF00 FF00 4141 9900 FF00 CC00 4040 9900" + $"FF00 9900 3F3F 9900 FF00 6600 4342 9900" + $"FF00 3300 4141 9900 FF00 0000 4040 9900" + $"CC00 FF00 3F3F 9900 CC00 CC00 4342 9900" + $"CC00 9900 4141 9900 CC00 6600 4040 9900" + $"CC00 3300 3F3F 9900 CC00 0000 4342 9900" + $"9900 FF00 4141 9900 9900 CC00 4040 9900" + $"9900 9900 3F3F 9900 9900 6600 3D3C 9900" + $"9900 3300 3B3B 9900 9900 0000 3A3A 9900" + $"6600 FF00 3939 9900 6600 CC00 3D3C 9900" + $"6600 9900 3B3B 9900 6600 6600 3A3A 9900" + $"6600 3300 3939 9900 6600 0000 3D3C 9900" + $"3300 FF00 3B3B 9900 3300 CC00 3A3A 9900" + $"3300 9900 3939 9900 3300 6600 3D3C 9900" + $"3300 3300 3B3B 9900 3300 0000 3A3A 9900" + $"0000 FF00 3939 9900 0000 CC00 3D3C 9900" + $"0000 9900 3B3B 9900 0000 6600 3A3A 9900" + $"0000 3300 3939 9900 0000 0000 3D3C 6600" + $"FF00 FF00 3B3B 6600 FF00 CC00 3A3A 6600" + $"FF00 9900 3939 6600 FF00 6600 3D3C 6600" + $"FF00 3300 3B3B 6600 FF00 0000 3A3A 6600" + $"CC00 FF00 3939 6600 CC00 CC00 3736 6600" + $"CC00 9900 3535 6600 CC00 6600 3434 6600" + $"CC00 3300 3333 6600 CC00 0000 3736 6600" + $"9900 FF00 3535 6600 9900 CC00 3434 6600" + $"9900 9900 3333 6600 9900 6600 3736 6600" + $"9900 3300 3535 6600 9900 0000 3434 6600" + $"6600 FF00 3333 6600 6600 CC00 3736 6600" + $"6600 9900 3535 6600 6600 6600 3434 6600" + $"6600 3300 3333 6600 6600 0000 3736 6600" + $"3300 FF00 3535 6600 3300 CC00 3434 6600" + $"3300 9900 3333 6600 3300 6600 3736 6600" + $"3300 3300 3535 6600 3300 0000 3434 6600" + $"0000 FF00 3333 6600 0000 CC00 3130 6600" + $"0000 9900 2F2F 6600 0000 6600 2E2E 6600" + $"0000 3300 F9F9 6600 0000 0000 3130 3300" + $"FF00 FF00 2F2F 3300 FF00 CC00 2E2E 3300" + $"FF00 9900 F9F9 3300 FF00 6600 3130 3300" + $"FF00 3300 2F2F 3300 FF00 0000 2E2E 3300" + $"CC00 FF00 2D2D 3300 CC00 CC00 3130 3300" + $"CC00 9900 2F2F 3300 CC00 6600 2E2E 3300" + $"CC00 3300 2D2D 3300 CC00 0000 3130 3300" + $"9900 FF00 2F2F 3300 9900 CC00 2E2E 3300" + $"9900 9900 2D2D 3300 9900 6600 3130 3300" + $"9900 3300 2F2F 3300 9900 0000 2E2E 3300" + $"6600 FF00 2DF8 3300 6600 CC00 2B2A 3300" + $"6600 9900 2929 3300 6600 6600 2828 3300" + $"6600 3300 27F8 3300 6600 0000 2B2A 3300" + $"3300 FF00 2929 3300 3300 CC00 2828 3300" + $"3300 9900 2727 3300 3300 6600 2B2A 3300" + $"3300 3300 2929 3300 3300 0000 2828 3300" + $"0000 FF00 2727 3300 0000 CC00 2B2A 3300" + $"0000 9900 2929 3300 0000 6600 2828 3300" + $"0000 3300 2727 3300 0000 0000 4948 0000" + $"FF00 FF00 4747 0000 FF00 CC00 4646 0000" + $"FF00 9900 4545 0000 FF00 6600 4948 0000" + $"FF00 3300 4747 0000 FF00 0000 4646 0000" + $"CC00 FF00 4545 0000 CC00 CC00 4948 0000" + $"CC00 9900 4747 0000 CC00 6600 4646 0000" + $"CC00 3300 4545 0000 CC00 0000 4342 0000" + $"9900 FF00 4141 0000 9900 CC00 4040 0000" + $"9900 9900 3F3F 0000 9900 6600 4342 0000" + $"9900 3300 4141 0000 9900 0000 4040 0000" + $"6600 FF00 3F3F 0000 6600 CC00 4342 0000" + $"6600 9900 4141 0000 6600 6600 4040 0000" + $"6600 3300 3F3F 0000 6600 0000 4342 0000" + $"3300 FF00 4141 0000 3300 CC00 4040 0000" + $"3300 9900 3F3F 0000 3300 6600 4342 0000" + $"3300 3300 4141 0000 3300 0000 4040 0000" + $"0000 FF00 3F3F 0000 0000 CC00 4342 0000" + $"0000 9900 4141 0000 0000 6600 4040 0000" + $"0000 3300 3F3F EE00 0000 0000 3D3C DD00" + $"0000 0000 3B3B BB00 0000 0000 3A3A AA00" + $"0000 0000 3939 8800 0000 0000 3D3C 7700" + $"0000 0000 3B3B 5500 0000 0000 3A3A 4400" + $"0000 0000 3939 2200 0000 0000 3D3C 1100" + $"0000 0000 3B3B 0000 EE00 0000 3A3A 0000" + $"DD00 0000 3939 0000 BB00 0000 3D3C 0000" + $"AA00 0000 3B3B 0000 8800 0000 3A3A 0000" + $"7700 0000 3939 0000 5500 0000 3D3C 0000" + $"4400 0000 3B3B 0000 2200 0000 3A3A 0000" + $"1100 0000 3939 0000 0000 EE00 3D3C 0000" + $"0000 DD00 3B3B 0000 0000 BB00 3A3A 0000" + $"0000 AA00 3939 0000 0000 8800 3D3C 0000" + $"0000 7700 3B3B 0000 0000 5500 3A3A 0000" + $"0000 4400 3939 0000 0000 2200 3736 0000" + $"0000 1100 3535 EE00 EE00 EE00 3434 DD00" + $"DD00 DD00 3333 BB00 BB00 BB00 3736 AA00" + $"AA00 AA00 3535 8800 8800 8800 3434 7700" + $"7700 7700 3333 5500 5500 5500 3736 4400" + $"4400 4400 3535 2200 2200 2200 3434 1100" + $"1100 1100 3333 0000 0000 0000 0000 0000" + $"0064 0044 0000 0000 0064 0044 0000 000A" + $"0000 0000 0064 0044 02BD 0013 E800 01F5" + $"F6FE 07FE 0E02 3232 33FD 3900 0EE6 001D" + $"FC00 01F5 F5FE 0700 08FE 0E02 3232 33FE" + $"3900 3AFC 40F2 4102 4033 07E9 0017 0100" + $"0EFC 40DC 4102 390E F5F5 0002 F5F5 F6FE" + $"0702 0E07 0016 0100 32D5 4104 4039 0E32" + $"33FD 3900 3AFC 40FC 4101 3200 0801 000E" + $"C141 010E 0008 0100 0EC1 4101 0800 0801" + $"000E C141 0107 0008 0100 0EC1 4101 0700" + $"0901 0007 C241 0240 F500 0E01 0007 E841" + $"0147 47DD 4102 4000 0012 0100 07F0 4100" + $"47FA 4101 3B3B DD41 0240 0000 1901 0007" + $"F141 0C47 3B0B 3B47 4141 4711 0505 3B47" + $"DF41 023A 0000 1701 00F6 F041 010B 0BFE" + $"4105 473B 0505 113B DE41 0239 0000 1A02" + $"00F5 40F3 410C 473B 053B 4741 4741 0B0B" + $"3B47 47DE 4102 3900 0018 0200 F540 F341" + $"0247 110B FE41 0447 1105 4147 DC41 0233" + $"0000 1B02 0000 40F3 4103 4711 1147 FE41" + $"0205 3547 F741 FD47 E941 0232 0000 1E02" + $"0000 40F2 4106 113B 4741 4735 0BF7 4106" + $"4741 390E 0E40 47EA 4102 0E00 0021 0200" + $"0040 F241 0711 3B47 4141 0B35 47F9 4102" + $"4740 07FE 0002 F640 47EB 4102 0E00 0023" + $"0200 0040 F341 0847 3541 4147 3B05 4147" + $"FA41 0947 3AF6 00F5 4F55 F50E 47EB 4102" + $"0700 0022 0200 003A F341 0147 3BFE 4101" + $"0B0B F941 0547 3AF5 0055 C8FE CE01 5640" + $"EB41 0207 0000 1F02 0000 39F0 4104 4741" + $"053B 47FB 4104 4740 F5F5 A4FC CE01 C85D" + $"EB41 02F6 0000 1F02 0000 39F0 4104 473B" + $"0541 47FC 4104 4740 07F6 C8FA CE00 64EC" + $"4103 40F5 0000 1C02 0000 39F0 4102 4711" + $"0BFA 4103 4708 2AC8 FACE 0164 D8EC 4100" + $"40FE 0025 0200 0039 EF41 020B 3B47 FC41" + $"0347 0FF5 A4FB CE02 C887 D8FC 41FE 47FC" + $"4100 47F9 4100 3AFE 0028 0200 0039 EF41" + $"020B 3B47 FD41 0347 3900 A4FA CE00 ABFA" + $"4109 3B11 3B41 4147 3B0B 3B47 FA41 0039" + $"FE00 2402 0000 33F1 4102 4741 0BFA 4101" + $"0779 F9CE 0064 FA41 0235 050B FD41 010B" + $"0BF9 4100 39FE 0028 0200 0032 F141 0247" + $"3B0B FC41 0247 39F6 F9CE 0187 D8FB 4103" + $"4741 050B FE41 0247 110B F941 0039 FE00" + $"2C02 0000 32F1 4102 473B 11FB 4101 0879" + $"FACE 05AA 4041 4147 47FE 410A 4741 0511" + $"4741 4147 3511 47FA 4100 32FE 002F 0200" + $"000E F141 0347 3B11 47FE 4103 4740 F6C8" + $"FACE 0564 D841 4039 39FE 4104 473B 053B" + $"47FE 4102 3541 47FA 4100 0EFE 0027 0200" + $"000E F141 0347 3B3B 47FE 4102 470F 79FA" + $"CE0C 8741 4032 F500 003A 4741 473B 05F2" + $"4100 0EFE 0027 0200 000E F141 0347 3B3B" + $"47FD 4101 0EA4 FACE 01AB AAFE C808 7900" + $"3947 4147 110B 47F3 4100 07FE 001C 0200" + $"000E EA41 0240 2BC8 F5CE 0881 0033 4741" + $"410B 3B47 F341 0007 FE00 1A02 0000 08EB" + $"4102 473A 55F4 CE06 5D00 3947 4741 0BF1" + $"4100 F6FE 001C 0200 0007 EB41 0247 3979" + $"F4CE 0739 0039 4747 3511 47F3 4101 40F5" + $"FE00 1C02 0000 07EB 4102 4739 A4F5 CE08" + $"AB0E 0040 4741 1141 47F3 4100 40FD 001B" + $"0200 0007 EB41 0247 39A4 F5CE 0787 0707" + $"4147 4111 47F2 4100 40FD 001B 0200 0007" + $"EB41 0247 39C8 F5CE 0763 F532 4747 3B3B" + $"47F2 4100 3AFD 001A 0300 00F6 40EC 4102" + $"4739 C8F5 CE05 39F5 4047 413B F041 0039" + $"FD00 1C03 0000 F540 EB41 0140 C8FD CE01" + $"C8A4 FCCE 03AB 080E 47ED 4100 39FD 001A" + $"FE00 0040 EB41 0040 FCCE 01A4 C8FC CE03" + $"FA07 4047 ED41 0032 FD00 1AFE 0000 40EA" + $"4100 AAFE CE02 87F9 C8FC CE02 560F 47EC" + $"4100 32FD 0019 FE00 0040 EA41 00AB FECE" + $"0264 56C8 FDCE 01C8 32EA 4100 0EFD 001B" + $"FE00 0040 ED41 030E 4047 87FE CE01 4055" + $"FCCE 01FA 40EA 4100 08FD 001A FE00 003A" + $"ED41 0807 0740 FBCE CEAB 3979 FDCE 00AB" + $"E841 0007 FD00 1CFE 0000 3AED 4108 0700" + $"F6A4 CECE 8733 79FD CE02 4147 47EA 4100" + $"07FD 001E FE00 0039 ED41 0807 2AA4 C8CE" + $"CE88 0E9D FECE 0364 1C39 39EB 4101 40F5" + $"FD00 1CFE 0000 39ED 4101 074F FDCE 0264" + $"F7A4 FECE 03AB 80F6 07EB 4100 40FC 001C" + $"FE00 0039 ED41 0108 79FE CE03 AB40 2BA4" + $"FCCE 02F7 0E47 EC41 0040 FC00 1CFE 0000" + $"39ED 4101 0879 FECE 03AB 40F6 C8FC CE02" + $"F615 47EC 4100 40FC 001E FE00 003A EE41" + $"0247 0E79 FECE 03AB 40F5 C8FD CE03 A4F5" + $"3A47 EC41 0040 FC00 1EFE 0000 3AEE 4102" + $"470E 56FE CE03 FB3A F6C8 FDCE 0280 F540" + $"EB41 0140 F5FD 001E FE00 0040 EE41 0947" + $"0F56 CECE C888 39F6 C8FD CE02 5601 40EB" + $"4101 40F5 FD00 1CFE 0000 40EE 4109 4739" + $"32CE CEC8 8839 2AC8 FDCE 0156 07E9 4100" + $"F6FD 001B FE00 0040 EE41 0847 3A32 CECE" + $"C864 152A FCCE 0132 07E9 4100 07FD 001A" + $"FE00 0040 ED41 0740 32AB CEC8 6439 4EFC" + $"CE01 3A07 E941 0007 FD00 1D03 0000 F540" + $"ED41 0740 0EAB CECE 640F 4EFD CE03 AB40" + $"0840 EA41 0007 FD00 1B03 0000 F540 EC41" + $"060F 81CE CE64 334E FDCE 02AB 400E E941" + $"000E FD00 1C02 0000 F6EC 4107 4715 FACE" + $"CE64 334E FDCE 0387 0F0E 47EA 4100 0EFD" + $"001C 0200 0007 EC41 0747 16F9 CEC8 6433" + $"4EFD CE03 6308 4047 EA41 000E FD00 1A02" + $"0000 07EB 4106 40F9 CEC8 6439 4EFD CE02" + $"3940 47E9 4100 32FD 001B 0200 0007 EA41" + $"0539 CECE 8839 F6FE CE04 AB41 4139 40EA" + $"4100 32FD 001C 0200 0007 EB41 0E47 3AC8" + $"CE88 39F6 C8CE CE64 15F6 F540 EA41 0033" + $"FD00 1A02 0000 07EA 410C 40A4 CE87 392A" + $"C8CE AB41 40F8 F6E9 4100 39FD 001B 0200" + $"000E EB41 0D47 41AB C887 39F5 C8CE ABAB" + $"CEA4 07E9 4100 39FD 001C 0200 000E ED41" + $"0947 3939 4787 C8AB 40F5 C8FD CE01 A40E" + $"E941 0039 FD00 1D02 0000 0EED 4109 473A" + $"0007 80CE AB40 F5C8 FDCE 0255 0E47 EA41" + $"0039 FD00 1B02 0000 0EEB 4107 0779 C8CE" + $"CE40 F6A4 FDCE 022B 3947 EA41 003A FD00" + $"1C02 0000 0EEC 4102 4739 79FE CE02 6407" + $"A4FE CE02 A407 40E9 4100 40FD 001A 0200" + $"0032 EA41 0632 A4CE CE88 0879 FECE 02F9" + $"0F47 E941 0040 FD00 1A02 0000 32EB 4107" + $"4740 F7C8 CE87 0E79 FECE 0132 40E8 4100" + $"40FD 0019 0200 0033 EA41 0B47 40F8 C8AB" + $"0E55 CECE 8015 47E8 4100 40FD 0017 0200" + $"0033 E941 0847 40F9 A439 4FCE CE5D E641" + $"0140 F5FE 0014 0200 0039 E841 0647 64FB" + $"392B C8AB E441 00F6 FE00 1102 0000 39E5" + $"4103 40F6 8764 E441 0007 FE00 1E02 0000" + $"39EB 4102 3A0E 0EFD 4102 0740 47F6 4104" + $"400F 0839 47F4 4100 07FE 0027 0200 0039" + $"FB41 0147 47F2 4102 0800 40FE 4102 0839" + $"47FC 4101 4747 FC41 0339 0039 47F4 4100" + $"07FE 0029 0200 0039 FB41 0140 39F3 4109" + $"470E F540 4141 470E 3347 FC41 0139 3AFD" + $"4104 4739 0039 47F4 4100 08FE 0036 0200" + $"003A FC41 0347 0E00 40FC 4102 4741 40FC" + $"4109 470E F540 4141 4733 0E47 FE41 0447" + $"4000 0E47 FE41 0447 3900 3941 FE40 F741" + $"000E FE00 3A02 0000 3AFD 410E 4740 0700" + $"0E40 4741 4147 390E 390E 40FE 4108 470E" + $"F540 4141 4739 0EFC 4103 0F00 0739 FE41" + $"0747 3900 3940 080F 39F7 4100 0EFE 0035" + $"0200 0040 FB41 020E 0040 FE41 0D47 4000" + $"3941 0032 4741 4147 0EF5 40FE 4101 4008" + $"FC41 023A 000E FD41 0547 3900 3939 33F5" + $"4100 0EFE 0039 0200 0040 FC41 0347 0E00" + $"40FE 4106 4732 0040 4139 40FE 4103 470E" + $"F540 FD41 0108 40FE 4104 4740 000E 47FE" + $"4106 4739 0007 F540 47F6 4100 32FE 003A" + $"0200 0040 FC41 0C47 0E00 4047 4141 470E" + $"0040 4747 FD41 0347 0EF5 40FE 410A 470E" + $"3947 4141 4740 000E 47FE 4107 4739 000E" + $"0007 4147 F741 0032 FE00 3802 0000 40FC" + $"4102 470E 00FD 4106 4739 003A 4740 39FE" + $"4102 470E F5FD 410A 4733 3347 4141 4740" + $"000E 47FE 4106 4739 0039 3900 0EF6 4100" + $"33FE 003A 0200 F540 FC41 0447 3200 0E39" + $"FD41 0B0E 0E40 333A 4741 413A 07F5 39FE" + $"4102 473A 0EFD 410F 40F5 0733 4041 4140" + $"0E00 0E40 0700 0E40 F841 0039 FE00 2902" + $"00F5 40FA 4101 3939 FB41 023A 3A40 FD41" + $"FD40 FD41 0240 0E40 FD41 0240 3940 FD41" + $"FA40 F741 0039 FE00 2A01 00F6 F941 0147" + $"47FB 4101 4747 FB41 0147 47FB 4101 3940" + $"FD41 0147 47FB 4100 47FE 4100 47F6 4100" + $"39FE 000D 0100 07E1 4100 40E4 4100 3AFE" + $"0009 0100 07C3 4100 3AFE 0009 0100 07C3" + $"4100 40FE 0009 0100 07C3 4100 40FE 0009" + $"0100 07C3 4100 40FE 000A 0100 0EC3 4103" + $"40F5 0000 0901 000E C241 02F6 0000 0901" + $"000E C241 0207 0000 0901 000E C241 0207" + $"0000 1101 000E ED41 FE40 003A F940 E241" + $"0207 0000 2B01 0032 F941 FE40 FE39 0632" + $"0E0E 0707 F6F5 F800 02F5 F5F6 FB07 FB0E" + $"0332 3233 33FB 3901 3A3A FB40 0207 0000" + $"0E0A 000E 3939 320E 0E07 07F6 F5C8 0002" + $"BD00 00FF" +}; + +/* + * Here is the custom file open dialog. This dialog is used instead of + * the default file dialog if the -filetypes flag is specified. + */ + +#define DLOG_RezTemplateVersion 0 + +resource 'DLOG' (130, purgeable) { + {0, 0, 195, 344}, dBoxProc, invisible, noGoAway, 0, + 130, "" +}; + +resource 'DITL' (130, "File Open Box", purgeable) { + { + {135, 252, 155, 332}, Button {enabled, "Open"}, + {104, 252, 124, 332}, Button {enabled, "Cancel"}, + { 0, 0, 0, 0}, HelpItem {disabled, HMScanhdlg {130}}, + { 8, 235, 24, 337}, UserItem {enabled}, + { 32, 252, 52, 332}, Button {enabled, "Eject"}, + { 60, 252, 80, 332}, Button {enabled, "Desktop"}, + { 29, 12, 159, 230}, UserItem {enabled}, + { 6, 12, 25, 230}, UserItem {enabled}, + { 91, 251, 92, 333}, Picture {disabled, 11}, + {168, 20, 187, 300}, Control {enabled, 131} + } +}; + +resource 'CNTL' (131, "File Types menu", purgeable) { + {168, 20, 187, 300}, + popupTitleLeftJust, + visible, + 80, + 132, + popupMenuCDEFProc, + 0, + "File Type:" +}; + + +resource 'MENU' (132, preload) { + 132, + textMenuProc, + 0xFFFF, enabled, "", {} +}; diff --git a/mac/tkMacMDEF.c b/mac/tkMacMDEF.c new file mode 100644 index 0000000..f7ce485 --- /dev/null +++ b/mac/tkMacMDEF.c @@ -0,0 +1,116 @@ +/* + * TkMacMDEF.c -- + * + * This module is implements the MDEF for tkMenus. The address of the + * real entry proc will be blasted into the MDEF. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacMDEF.c 1.5 97/07/11 %V% + */ + +#define MAC_TCL +#define NeedFunctionPrototypes 1 +#define NeedWidePrototypes 0 + +#include <Menus.h> +#include <LowMem.h> +#include "tkMacInt.h" + + +/* + * The following structure is built from assembly equates in MPW 3.0 + * AIncludes file: "Private.a." We're forced to update several locations not + * documented in "Inside Mac" to make our MDEF behave properly with hierarchical + * menus. + */ + +#if STRUCTALIGNMENTSUPPORTED +#pragma options align=mac68k +#endif +typedef struct mbPrivate { + Byte unknown[6]; + Rect mbItemRect; /* rect of currently chosen menu item */ +} mbPrivate; +#if STRUCTALIGNMENTSUPPORTED +#pragma options align=reset +#endif + +/* + * We are forced to update a low-memory global to get cascades to work. This + * global does not have a LMEquate associated with it. + */ + +#define SELECTRECT (*(Rect *)0x09fa) /* Menu select seems to need this */ +#define MBSAVELOC (*(short *)0x0B5C) /* address of handle to mbarproc private data redefined below */ + +pascal void main _ANSI_ARGS_((short message, + MenuHandle menu, Rect *menuRect, + Point hitPt, short *whichItem)); + + +/* + *---------------------------------------------------------------------- + * + * TkMacStdMenu -- + * + * The dispatch routine called by the system to handle menu drawing, + * scrolling, etc. This is a stub; the address of the real routine + * is blasted in. The real routine will be a UniversalProcPtr, + * which will give the real dispatch routine in Tk globals + * and the like. + * + * 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 + * + *---------------------------------------------------------------------- + */ + +pascal void +main( + short message, /* What action are we taking? */ + MenuHandle menu, /* The menu we are working with */ + Rect *menuRect, /* A pointer to the rect we are working with */ + Point hitPt, /* Where the mouse was hit for appropriate + * messages. */ + short *whichItemPtr) /* Output result. Which item was hit by + * the user? */ +{ + /* + * The constant 'MDEF' is what will be punched during menu intialization. + */ + + TkMenuDefProcPtr procPtr = (TkMenuDefProcPtr) 'MDEF'; + TkMenuLowMemGlobals globals; + short oldItem; + + globals.menuDisable = LMGetMenuDisable(); + globals.menuTop = LMGetTopMenuItem(); + globals.menuBottom = LMGetAtMenuBottom(); + if (MBSAVELOC == -1) { + globals.itemRect = (**(mbPrivate***)&MBSAVELOC)->mbItemRect; + } + if (message == mChooseMsg) { + oldItem = *whichItemPtr; + } + + TkCallMenuDefProc(procPtr, message, menu, menuRect, hitPt, whichItemPtr, + &globals); + + LMSetMenuDisable(globals.menuDisable); + LMSetTopMenuItem(globals.menuTop); + LMSetAtMenuBottom(globals.menuBottom); + if ((message == mChooseMsg) && (oldItem != *whichItemPtr) + && (MBSAVELOC != -1)) { + (**(mbPrivate***)&MBSAVELOC)->mbItemRect = globals.itemRect; + SELECTRECT = globals.itemRect; + } +} diff --git a/mac/tkMacMDEF.r b/mac/tkMacMDEF.r new file mode 100644 index 0000000..5c18104 --- /dev/null +++ b/mac/tkMacMDEF.r @@ -0,0 +1,45 @@ +/* + * tkMacMDEF.r -- + * + * This file contains the actual MDEF. Since this is not likely to + * change much, this seems the easiest method to use. The address + * of the routine descriptor is written into offset 0x24 hex, and + * then when the MDEF is called, the Mixed Mode Manager will take + * care of the setup. + * + * This file also contains the icons 'SICN' used by the menu code + * in menu items. + * + * Copyright (c) 1996-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacMDEF.r 1.6 97/07/11 18:09:47 + */ + +#include <Types.r> + +/* + * This code was generated by a project file and will not need to be changed. + * It is just a stub. The address of the real MDEF handler will be blasted + * in. + */ + +data 'MDEF' (591, preload) { + $"600A 0000 4D44 4546 024F 0000 4EFA 0004" /* `...MDEF.O..Nú.. */ + $"4E75 4E56 FFEE 48E7 1830 362E 0018 246E" /* NuNVÿîHç.06...$n */ + $"0008 267C 4D44 4546 594F 2EB8 0B54 201F" /* ..&|MDEFYO.¸.T . */ + $"2D40 FFEE 554F 3EB8 0A0A 301F 3D40 FFF2" /* -@ÿîUO>¸..0.=@ÿò */ + $"554F 3EB8 0A0C 301F 3D40 FFF4 0C78 FFFF" /* UO>¸..0.=@ÿô.xÿÿ */ + $"0B5C 6612 2078 0B5C 2050 2D68 0006 FFF6" /* .\f. x.\ P-h..ÿö */ + $"2D68 000A FFFA 0C43 0001 6602 3812 3F03" /* -h..ÿú.C..f.8.?. */ + $"2F2E 0014 2F2E 0010 2F2E 000C 2F0A 486E" /* /.../.../.../.Hn */ + $"FFEE 4E93 2F2E FFEE 21DF 0B54 3F2E FFF2" /* ÿîN“/.ÿî!ß.T?.ÿò */ + $"31DF 0A0A 3F2E FFF4 31DF 0A0C 0C43 0001" /* 1ß..?.ÿô1ß...C.. */ + $"662A B852 6726 0C78 FFFF 0B5C 671E 2078" /* f*¸Rg&.xÿÿ.\g. x */ + $"0B5C 2050 216E FFF6 0006 216E FFFA 000A" /* .\ P!nÿö..!nÿú.. */ + $"21EE FFF6 09FA 21EE FFFA 09FE 4CDF 0C18" /* !îÿöÆú!îÿúÆþLß.. */ + $"4E5E 205F 4FEF 0012 4ED0 846D 6169 6E00" /* N^ _Oï..NЄmain. */ + $"0000" /* .. */ +}; diff --git a/mac/tkMacMenu.c b/mac/tkMacMenu.c new file mode 100644 index 0000000..33bb82b --- /dev/null +++ b/mac/tkMacMenu.c @@ -0,0 +1,3994 @@ +/* + * tkMacMenu.c -- + * + * This module implements the Mac-platform specific features of menus. + * + * Copyright (c) 1996-1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacMenu.c 1.107 97/11/20 18:33:09 + */ + +#include <Menus.h> +#include <OSUtils.h> +#include <Palettes.h> +#include <Resources.h> +#include <string.h> +#include <ToolUtils.h> +#include <Balloons.h> +#undef Status +#include <Devices.h> +#include "tkMenu.h" +#include "tkMacInt.h" +#include "tkMenuButton.h" + +typedef struct MacMenu { + MenuHandle menuHdl; /* The Menu Manager data structure. */ + Rect menuRect; /* The rectangle as calculated in the + * MDEF. This is used to figure ou the + * clipping rgn before we push + * the <<MenuSelect>> virtual binding + * through. */ +} MacMenu; + +/* + * Various geometry definitions: + */ + +#define CASCADE_ARROW_HEIGHT 10 +#define CASCADE_ARROW_WIDTH 8 +#define DECORATION_BORDER_WIDTH 2 +#define MAC_MARGIN_WIDTH 8 + +/* + * The following are constants relating to the SICNs used for drawing the MDEF. + */ + +#define SICN_RESOURCE_NUMBER 128 + +#define SICN_HEIGHT 16 +#define SICN_ROWS 2 +#define CASCADE_ICON_WIDTH 7 +#define SHIFT_ICON_WIDTH 10 +#define OPTION_ICON_WIDTH 16 +#define CONTROL_ICON_WIDTH 12 +#define COMMAND_ICON_WIDTH 10 + +#define CASCADE_ARROW 0 +#define SHIFT_ICON 1 +#define OPTION_ICON 2 +#define CONTROL_ICON 3 +#define COMMAND_ICON 4 +#define DOWN_ARROW 5 +#define UP_ARROW 6 + +/* + * 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) + +/* + * 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. */ +} 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 SEPARATOR_TEXT "\p(-" + /* The text for a menu separator. */ + +#define MENUBAR_REDRAW_PENDING 1 + +RgnHandle tkMenuCascadeRgn = NULL; + /* The region to clip drawing to when the + * MDEF is up. */ +int tkUseMenuCascadeRgn = 0; /* If this is 1, clipping code + * should intersect tkMenuCascadeRgn + * before drawing occurs. + * tkMenuCascadeRgn will only + * be valid when the value of this + * variable is 1. */ + +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 helpItemCount; /* The number of items in the help menu. + * -1 means that the help menu is + * unavailable. This does not include + * the automatically generated separator. */ +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 unsigned char lastCascadeID; + /* Cascades have to have ids that are + * less than 256. */ +static MacDrawable macMDEFDrawable; + /* Drawable for use by MDEF code */ +static MDEFScrollFlag = 0; /* Used so that popups don't scroll too soon. */ +static int menuBarFlags; /* Used for whether the menu bar needs + * redrawing or not. */ +static TkMenuDefUPP menuDefProc;/* The routine descriptor to the MDEF proc. + * The MDEF is needed to draw menus with + * non-standard attributes and to support + * tearoff menus. */ +static struct TearoffSelect { + TkMenu *menuPtr; /* The menu that is torn off */ + Point point; /* The point to place the new menu */ + Rect excludeRect; /* We don't want to drag tearoff highlights + * when we are in this menu */ +} tearoffStruct; + +static RgnHandle totalMenuRgn = NULL; + /* Used to update windows which have been + * obscured by menus. */ +static RgnHandle utilRgn = NULL;/* Used when creating the region that is to + * be clipped out while the MDEF is active. */ + +static TopLevelMenubarList *windowListPtr; + /* A list of windows that have menubars set. */ + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void CompleteIdlers _ANSI_ARGS_((TkMenu *menuPtr)); +static void DrawMenuBarWhenIdle _ANSI_ARGS_(( + ClientData clientData)); +static void DrawMenuEntryAccelerator _ANSI_ARGS_(( + 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 _ANSI_ARGS_(( + TkMenu *menuPtr, TkMenuEntry *mePtr, + Drawable d, Tk_3DBorder activeBorder, + Tk_3DBorder bgBorder, int x, int y, + int width, int heigth)); +static void DrawMenuEntryIndicator _ANSI_ARGS_(( + 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 _ANSI_ARGS_(( + 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 _ANSI_ARGS_((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 _ANSI_ARGS_((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 FixMDEF _ANSI_ARGS_((void)); +static void GetMenuAccelGeometry _ANSI_ARGS_((TkMenu *menuPtr, + TkMenuEntry *mePtr, Tk_Font tkfont, + CONST Tk_FontMetrics *fmPtr, int *modWidthPtr, + int *textWidthPtr, int *heightPtr)); +static void GetMenuLabelGeometry _ANSI_ARGS_((TkMenuEntry *mePtr, + Tk_Font tkfont, CONST Tk_FontMetrics *fmPtr, + int *widthPtr, int *heightPtr)); +static void GetMenuIndicatorGeometry _ANSI_ARGS_(( + TkMenu *menuPtr, TkMenuEntry *mePtr, + Tk_Font tkfont, CONST Tk_FontMetrics *fmPtr, + int *widthPtr, int *heightPtr)); +static void GetMenuSeparatorGeometry _ANSI_ARGS_(( + TkMenu *menuPtr, TkMenuEntry *mePtr, + Tk_Font tkfont, CONST Tk_FontMetrics *fmPtr, + int *widthPtr, int *heightPtr)); +static void GetTearoffEntryGeometry _ANSI_ARGS_((TkMenu *menuPtr, + TkMenuEntry *mePtr, Tk_Font tkfont, + CONST Tk_FontMetrics *fmPtr, int *widthPtr, + int *heightPtr)); +static int GetNewID _ANSI_ARGS_((Tcl_Interp *interp, + TkMenu *menuInstPtr, int cascade, + short *menuIDPtr)); +static char FindMarkCharacter _ANSI_ARGS_((TkMenuEntry *mePtr)); +static void FreeID _ANSI_ARGS_((short menuID)); +static void InvalidateMDEFRgns _ANSI_ARGS_((void)); +static void MenuDefProc _ANSI_ARGS_((short message, + MenuHandle menu, Rect *menuRectPtr, + Point hitPt, short *whichItem, + TkMenuLowMemGlobals *globalsPtr)); +static void MenuSelectEvent _ANSI_ARGS_((TkMenu *menuPtr)); +static void ReconfigureIndividualMenu _ANSI_ARGS_(( + TkMenu *menuPtr, MenuHandle macMenuHdl, + int base)); +static void ReconfigureMacintoshMenu _ANSI_ARGS_ (( + ClientData clientData)); +static void RecursivelyClearActiveMenu _ANSI_ARGS_(( + TkMenu *menuPtr)); +static void RecursivelyDeleteMenu _ANSI_ARGS_(( + TkMenu *menuPtr)); +static void RecursivelyInsertMenu _ANSI_ARGS_(( + TkMenu *menuPtr)); +static void SetDefaultMenubar _ANSI_ARGS_((void)); +static int SetMenuCascade _ANSI_ARGS_((TkMenu *menuPtr)); +static void SetMenuIndicator _ANSI_ARGS_((TkMenuEntry *mePtr)); + + +/* + *---------------------------------------------------------------------- + * + * TkMacUseID -- + * + * 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 GetNewID 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 +TkMacUseMenuID( + short macID) /* The id to take out of the table */ +{ + Tcl_HashEntry *commandEntryPtr; + int newEntry; + + TkMenuInit(); + commandEntryPtr = Tcl_CreateHashEntry(&commandTable, (char *) macID, + &newEntry); + if (newEntry == 1) { + Tcl_SetHashValue(commandEntryPtr, NULL); + return TCL_OK; + } else { + return TCL_ERROR; + } +} + +/* + *---------------------------------------------------------------------- + * + * GetNewID -- + * + * 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. + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static int +GetNewID( + 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; + 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) { + commandEntryPtr = Tcl_CreateHashEntry(&commandTable, + (char *) curID, &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. + */ + + unsigned char curID = lastCascadeID + 1; + if (curID == 236) { + curID = 0; + } + + while (curID != lastCascadeID) { + commandEntryPtr = Tcl_CreateHashEntry(&commandTable, + (char *) curID, &newEntry); + if (newEntry == 1) { + found = 1; + lastCascadeID = returnID = curID; + break; + } + curID++; + if (curID == 236) { + curID = 0; + } + } + } + + if (found) { + Tcl_SetHashValue(commandEntryPtr, (char *) menuPtr); + *menuIDPtr = returnID; + return TCL_OK; + } else { + Tcl_AppendResult(interp, "No more menus can be allocated.", + (char *) NULL); + return TCL_ERROR; + } +} + +/* + *---------------------------------------------------------------------- + * + * FreeID -- + * + * Marks the id as free. + * + * Results: + * None. + * + * Side effects: + * The hash table entry for the ID is cleared. + * + *---------------------------------------------------------------------- + */ + +static void +FreeID( + short menuID) /* The id to free */ +{ + Tcl_HashEntry *entryPtr = Tcl_FindHashEntry(&commandTable, + (char *) menuID); + + if (entryPtr != NULL) { + Tcl_DeleteHashEntry(entryPtr); + } + if (menuID == currentAppleMenuID) { + currentAppleMenuID = 0; + } + if (menuID == currentHelpMenuID) { + currentHelpMenuID = 0; + } +} + +/* + *---------------------------------------------------------------------- + * + * 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; + Str255 itemText; + int length; + MenuHandle macMenuHdl; + int error = TCL_OK; + + error = GetNewID(menuPtr->interp, menuPtr, 0, &menuID); + if (error != TCL_OK) { + return error; + } + length = strlen(Tk_PathName(menuPtr->tkwin)); + memmove(&itemText[1], Tk_PathName(menuPtr->tkwin), + (length > 230) ? 230 : length); + itemText[0] = (length > 230) ? 230 : length; + macMenuHdl = NewMenu(menuID, itemText); +#ifdef GENERATINGCFM + { + Handle mdefProc = GetResource('MDEF', 591); + Handle sicnHandle = GetResource('SICN', SICN_RESOURCE_NUMBER); + if ((mdefProc != NULL) && (sicnHandle != NULL)) { + (*macMenuHdl)->menuProc = mdefProc; + } + } +#endif + menuPtr->platformData = (TkMenuPlatformData) ckalloc(sizeof(MacMenu)); + ((MacMenu *) menuPtr->platformData)->menuHdl = macMenuHdl; + SetRect(&((MacMenu *) menuPtr->platformData)->menuRect, 0, 0, 0, 0); + + 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, (ClientData *) 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 */ +{ + MenuHandle macMenuHdl = ((MacMenu *) menuPtr->platformData)->menuHdl; + + if (menuPtr->menuFlags & MENU_RECONFIGURE_PENDING) { + Tcl_CancelIdleCall(ReconfigureMacintoshMenu, (ClientData) menuPtr); + menuPtr->menuFlags &= ~MENU_RECONFIGURE_PENDING; + } + + if ((*macMenuHdl)->menuID == currentHelpMenuID) { + MenuHandle helpMenuHdl; + + if ((HMGetHelpMenuHandle(&helpMenuHdl) == noErr) + && (helpMenuHdl != NULL)) { + int i, count = CountMItems(helpMenuHdl); + + for (i = helpItemCount; i <= count; i++) { + DeleteMenuItem(helpMenuHdl, helpItemCount); + } + } + currentHelpMenuID = 0; + } + + if (menuPtr->platformData != NULL) { + DeleteMenu((*macMenuHdl)->menuID); + FreeID((*macMenuHdl)->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. + * + *---------------------------------------------------------------------- + */ + +static int +SetMenuCascade( + TkMenu* menuPtr) /* The menu we are setting up to be a + * cascade. */ +{ + MenuHandle macMenuHdl = ((MacMenu *) menuPtr->platformData)->menuHdl; + short newMenuID, menuID = (*macMenuHdl)->menuID; + int error = TCL_OK; + + if (menuID >= 256) { + error = GetNewID(menuPtr->interp, menuPtr, 1, &newMenuID); + if (error == TCL_OK) { + FreeID(menuID); + (*macMenuHdl)->menuID = 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. + * + * Results: + * itemText points to the new text for the item. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +GetEntryText( + TkMenuEntry *mePtr, /* A pointer to the menu entry. */ + Str255 itemText) /* The pascal string containing the text */ +{ + if (mePtr->type == TEAROFF_ENTRY) { + strcpy((char *)itemText, (const char *)"\p(Tear-off)"); + } else if (mePtr->imageString != NULL) { + strcpy((char *)itemText, (const char *)"\p(Image)"); + } else if (mePtr->bitmap != None) { + strcpy((char *)itemText, (const char *)"\p(Pixmap)"); + } else if (mePtr->label == NULL || mePtr->labelLength == 0) { + + /* + * The Mac menu manager does not like null strings. + */ + + strcpy((char *)itemText, (const char *)"\p "); + } else { + char *text = mePtr->label; + int i; + + itemText[0] = 0; + for (i = 1; (*text != '\0') && (i <= 230); i++, text++) { + if ((*text == '.') + && (*(text + 1) != '\0') && (*(text + 1) == '.') + && (*(text + 2) != '\0') && (*(text + 2) == '.')) { + itemText[i] = 'É'; + text += 2; + } else { + itemText[i] = *text; + } + itemText[0] += 1; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + * We try the following special mac characters. If none of them + * are present, just use the check mark. + * '' - Check mark character + * '¥' - Bullet character + * '' - Filled diamond + * '×' - Hollow diamond + * 'Ñ' = Long dash ("em dash") + * '-' = short dash (minus, "en dash"); + * + * Results: + * None. + * + * Side effects: + * New item is added to platform menu + * + *---------------------------------------------------------------------- + */ + +static char +FindMarkCharacter( + TkMenuEntry *mePtr) /* The entry we are finding the character + * for. */ +{ + char markChar; + Tk_Font tkfont = (mePtr->tkfont == NULL) ? mePtr->menuPtr->tkfont + : mePtr->tkfont; + + if (!TkMacIsCharacterMissing(tkfont, '')) { + markChar = ''; + } else if (!TkMacIsCharacterMissing(tkfont, '¥')) { + markChar = '¥'; + } else if (!TkMacIsCharacterMissing(tkfont, '')) { + markChar = ''; + } else if (!TkMacIsCharacterMissing(tkfont, '×')) { + markChar = '×'; + } else if (!TkMacIsCharacterMissing(tkfont, 'Ñ')) { + markChar = 'Ñ'; + } else if (!TkMacIsCharacterMissing(tkfont, '-')) { + markChar = '-'; + } else { + markChar = ''; + } + return markChar; +} + +/* + *---------------------------------------------------------------------- + * + * SetMenuIndicator -- + * + * Sets the Macintosh mark character based on the font of the + * item. + * + * Results: + * None. + * + * Side effects: + * New item is added to platform menu + * + *---------------------------------------------------------------------- + */ + +static void +SetMenuIndicator( + TkMenuEntry *mePtr) /* The entry we are setting */ +{ + TkMenu *menuPtr = mePtr->menuPtr; + MenuHandle macMenuHdl = ((MacMenu *) menuPtr->platformData)->menuHdl; + char markChar; + + /* + * There can be no indicators on menus that are not checkbuttons + * or radiobuttons. However, we should go ahead and set them + * so that menus look right when they are displayed. We should + * not set cascade entries, however, as the mark character + * means something different for cascade items on the Mac. + * Also, we do reflect the tearOff menu items in the Mac menu + * handle, so we ignore them. + */ + + if (mePtr->type == CASCADE_ENTRY) { + return; + } + + if (((mePtr->type == RADIO_BUTTON_ENTRY) + || (mePtr->type == CHECK_BUTTON_ENTRY)) + && (mePtr->indicatorOn) + && (mePtr->entryFlags & ENTRY_SELECTED)) { + markChar = FindMarkCharacter(mePtr); + } else { + markChar = 0; + } + SetItemMark(macMenuHdl, mePtr->index + 1, markChar); +} + +/* + *---------------------------------------------------------------------- + * + * SetMenuTitle -- + * + * Sets title of menu so that the text displays correctly in menubar. + * This code directly manipulates menu handle data. This code + * was originally part of an ancient Apple Developer Response mail. + * + * Results: + * None. + * + * Side effects: + * The menu handle will change size depending on the length of the + * title + * + *---------------------------------------------------------------------- + */ + +static void +SetMenuTitle( + MenuHandle menuHdl, /* The menu we are setting the title of. */ + char *title) /* The C string to set the title to. */ +{ + int oldLength, newLength, oldHandleSize, dataLength; + Ptr menuDataPtr; + + menuDataPtr = (Ptr) (*menuHdl)->menuData; + + if (strncmp(title, menuDataPtr + 1, menuDataPtr[0]) != 0) { + newLength = strlen(title) + 1; + oldLength = menuDataPtr[0] + 1; + oldHandleSize = GetHandleSize((Handle) menuHdl); + dataLength = oldHandleSize - (sizeof(MenuInfo) - sizeof(Str255)) + - oldLength; + if (newLength > oldLength) { + SetHandleSize((Handle) menuHdl, oldHandleSize + (newLength + - oldLength)); + menuDataPtr = (Ptr) (*menuHdl)->menuData; + } + + BlockMove(menuDataPtr + oldLength, menuDataPtr + newLength, + dataLength); + BlockMove(title, menuDataPtr + 1, newLength - 1); + menuDataPtr[0] = newLength - 1; + + if (newLength < oldLength) { + SetHandleSize((Handle) menuHdl, oldHandleSize + (newLength + - oldLength)); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpConfigureMenuEntry -- + * + * Processes configurations for menu entries. + * + * Results: + * Returns standard TCL result. If TCL_ERROR is returned, then + * interp->result contains an error message. + * + * Side effects: + * Configuration information get set for mePtr; old resources + * get freed, if any need it. + * + *---------------------------------------------------------------------- + */ + +int +TkpConfigureMenuEntry( + register TkMenuEntry *mePtr) /* Information about menu entry; may + * or may not already have values for + * some fields. */ +{ + TkMenu *menuPtr = mePtr->menuPtr; + int index = mePtr->index; + MenuHandle macMenuHdl = ((MacMenu *) menuPtr->platformData)->menuHdl; + MenuHandle helpMenuHdl = NULL; + + /* + * 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) { + SetMenuTitle(childMenuHdl, mePtr->label); + } + } + } + } + + /* + * 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) { + ((EntryGeometry *)mePtr->platformEntryData)->accelTextStart = -1; + } else { + char *accelString = mePtr->accel; + mePtr->entryFlags |= ~ENTRY_ACCEL_MASK; + + while (1) { + if ((0 == strncasecmp("Control", accelString, 6)) + && (('-' == accelString[6]) || ('+' == accelString[6]))) { + mePtr->entryFlags |= ENTRY_CONTROL_ACCEL; + accelString += 7; + } else if ((0 == strncasecmp("Ctrl", accelString, 4)) + && (('-' == accelString[4]) || ('+' == accelString[4]))) { + mePtr->entryFlags |= ENTRY_CONTROL_ACCEL; + accelString += 5; + } else if ((0 == strncasecmp("Shift", accelString, 5)) + && (('-' == accelString[5]) || ('+' == accelString[5]))) { + mePtr->entryFlags |= ENTRY_SHIFT_ACCEL; + accelString += 6; + } else if ((0 == strncasecmp("Option", accelString, 6)) + && (('-' == accelString[6]) || ('+' == accelString[6]))) { + mePtr->entryFlags |= ENTRY_OPTION_ACCEL; + accelString += 7; + } else if ((0 == strncasecmp("Opt", accelString, 3)) + && (('-' == accelString[3]) || ('+' == accelString[3]))) { + mePtr->entryFlags |= ENTRY_OPTION_ACCEL; + accelString += 4; + } else if ((0 == strncasecmp("Command", accelString, 7)) + && (('-' == accelString[7]) || ('+' == accelString[7]))) { + mePtr->entryFlags |= ENTRY_COMMAND_ACCEL; + accelString += 8; + } else if ((0 == strncasecmp("Cmd", accelString, 3)) + && (('-' == accelString[3]) || ('+' == accelString[3]))) { + mePtr->entryFlags |= ENTRY_COMMAND_ACCEL; + accelString += 4; + } else if ((0 == strncasecmp("Alt", accelString, 3)) + && (('-' == accelString[3]) || ('+' == accelString[3]))) { + mePtr->entryFlags |= ENTRY_OPTION_ACCEL; + accelString += 4; + } else if ((0 == strncasecmp("Meta", accelString, 4)) + && (('-' == accelString[4]) || ('+' == accelString[4]))) { + mePtr->entryFlags |= ENTRY_COMMAND_ACCEL; + accelString += 5; + } else { + break; + } + } + + ((EntryGeometry *)mePtr->platformEntryData)->accelTextStart + = ((long) accelString - (long) mePtr->accel); + } + + 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 + * + *---------------------------------------------------------------------- + */ + +static 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; + * helpMenuItemCount for help menus. */ +{ + int count; + int index; + TkMenuEntry *mePtr; + Str255 itemText; + int parentDisabled = 0; + + for (mePtr = menuPtr->menuRefPtr->parentEntryPtr; mePtr != NULL; + mePtr = mePtr->nextCascadePtr) { + if (strcmp(Tk_PathName(menuPtr->tkwin), mePtr->name) == 0) { + if (mePtr->state == tkDisabledUid) { + parentDisabled = 1; + } + break; + } + } + + /* + * First, we get rid of all of the old items. + */ + + count = CountMItems(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) { + AppendMenu(macMenuHdl, SEPARATOR_TEXT); + } else { + GetEntryText(mePtr, itemText); + AppendMenu(macMenuHdl, "\px"); + SetMenuItemText(macMenuHdl, base + index, itemText); + + /* + * Set enabling and disabling correctly. + */ + + if (parentDisabled || (mePtr->state == tkDisabledUid)) { + DisableItem(macMenuHdl, base + index); + } else { + EnableItem(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)) { + CheckItem(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) { + childMenuHdl = ((MacMenu *) mePtr->childMenuRefPtr + ->menuPtr->platformData)->menuHdl; + } + if (childMenuHdl != NULL) { + SetItemMark(macMenuHdl, base + index, + (*childMenuHdl)->menuID); + SetItemCmd(macMenuHdl, base + index, CASCADE_CMD); + } + /* + * 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) + && (ENTRY_COMMAND_ACCEL + == (mePtr->entryFlags & ENTRY_ACCEL_MASK))) { + SetItemCmd(macMenuHdl, index, mePtr + ->accel[((EntryGeometry *)mePtr->platformEntryData) + ->accelTextStart]); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static 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 (menuPtr->menuFlags & MENU_APPLE_MENU) { + AddResMenu(macMenuHdl, 'DRVR'); + } + + if ((*macMenuHdl)->menuID == currentHelpMenuID) { + HMGetHelpMenuHandle(&helpMenuHdl); + if (helpMenuHdl != NULL) { + ReconfigureIndividualMenu(menuPtr, helpMenuHdl, helpItemCount); + } + } + + if (menuPtr->menuType == MENUBAR) { + if (!(menuBarFlags & MENUBAR_REDRAW_PENDING)) { + Tcl_DoWhenIdle(DrawMenuBarWhenIdle, (ClientData *) 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. + * + *---------------------------------------------------------------------- + */ + +static 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) { + if ((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; + int oldMode; + + if (inPostMenu) { + Tcl_AppendResult(interp, + "Cannot call post menu while already posting menu", + (char *) NULL); + result = TCL_ERROR; + } else { + Window dummyWin; + unsigned int state; + int dummy, mouseX, mouseY; + short menuID; + Window window; + int oldWidth = menuPtr->totalWidth; + Tk_Window parentWindow = Tk_Parent(menuPtr->tkwin); + + inPostMenu++; + + result = TkPreprocessMenu(menuPtr); + if (result != TCL_OK) { + inPostMenu--; + return result; + } + + /* + * The post commands could have deleted the menu, which means + * we are dead and should go away. + */ + + if (menuPtr->tkwin == NULL) { + inPostMenu--; + return TCL_OK; + } + + CompleteIdlers(menuPtr); + if (menuBarFlags & MENUBAR_REDRAW_PENDING) { + Tcl_CancelIdleCall(DrawMenuBarWhenIdle, (ClientData *) NULL); + DrawMenuBarWhenIdle((ClientData *) NULL); + } + + if (NULL == parentWindow) { + tearoffStruct.excludeRect.top = tearoffStruct.excludeRect.left + = tearoffStruct.excludeRect.bottom + = tearoffStruct.excludeRect.right = SHRT_MAX; + } else { + int left, top; + + Tk_GetRootCoords(parentWindow, &left, &top); + tearoffStruct.excludeRect.left = left; + tearoffStruct.excludeRect.top = top; + tearoffStruct.excludeRect.right = left + Tk_Width(parentWindow); + tearoffStruct.excludeRect.bottom = top + Tk_Height(parentWindow); + if (Tk_Class(parentWindow) == Tk_GetUid("Menubutton")) { + TkWindow *parentWinPtr = (TkWindow *) parentWindow; + TkMenuButton *mbPtr = + (TkMenuButton *) parentWinPtr->instanceData; + int menuButtonWidth = Tk_Width(parentWindow) + - 2 * (mbPtr->highlightWidth + mbPtr->borderWidth + 1); + menuPtr->totalWidth = menuButtonWidth > menuPtr->totalWidth + ? menuButtonWidth : menuPtr->totalWidth; + } + } + + InsertMenu(macMenuHdl, -1); + RecursivelyInsertMenu(menuPtr); + CountMItems(macMenuHdl); + + FixMDEF(); + oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); + popUpResult = PopUpMenuSelect(macMenuHdl, y, x, menuPtr->active); + Tcl_SetServiceMode(oldMode); + + menuPtr->totalWidth = oldWidth; + RecursivelyDeleteMenu(menuPtr); + DeleteMenu((*macMenuHdl)->menuID); + + /* + * Simulate the mouse up. + */ + + XQueryPointer(NULL, None, &dummyWin, &dummyWin, &mouseX, + &mouseY, &dummy, &dummy, &state); + window = Tk_WindowId(menuPtr->tkwin); + TkGenerateButtonEvent(mouseX, mouseY, window, state); + + /* + * Dispatch the command. + */ + + menuID = HiWord(popUpResult); + if (menuID != 0) { + result = TkMacDispatchMenuEvent(menuID, LoWord(popUpResult)); + } else { + TkMacHandleTearoffMenu(); + result = TCL_OK; + } + InvalidateMDEFRgns(); + RecursivelyClearActiveMenu(menuPtr); + + 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; + mePtr->platformEntryData = (TkMenuPlatformEntryData) geometryPtr; + if (!(menuPtr->menuFlags & MENU_RECONFIGURE_PENDING)) { + menuPtr->menuFlags |= MENU_RECONFIGURE_PENDING; + Tcl_DoWhenIdle(ReconfigureMacintoshMenu, (ClientData) menuPtr); + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * + * DrawMenuBarWhenIdle -- + * + * Update the menu bar next time there is an idle event. + * + * Results: + * None. + * + * Side effects: + * Menu bar is redrawn. + * + *---------------------------------------------------------------------- + */ + +static void +DrawMenuBarWhenIdle( + ClientData clientData) /* ignored here */ +{ + TkMenuReferences *menuRefPtr; + TkMenu *appleMenuPtr, *helpMenuPtr; + MenuHandle macMenuHdl; + Tcl_HashEntry *hashEntryPtr; + + /* + * We need to clear the apple and help menus of any extra items. + */ + + if (currentAppleMenuID != 0) { + hashEntryPtr = Tcl_FindHashEntry(&commandTable, + (char *) 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 *) 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 != NULL) { + TkMenu *menuPtr, *menuBarPtr; + TkMenu *cascadeMenuPtr; + char *appleMenuName, *helpMenuName; + int appleIndex = -1, helpIndex = -1; + int 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 == NULL) { + SetDefaultMenubar(); + } else { + 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; + } else { + short appleID; + appleMenuPtr = menuBarPtr->entries[appleIndex] + ->childMenuRefPtr->menuPtr; + TkpDestroyMenu(appleMenuPtr); + GetNewID(appleMenuPtr->interp, appleMenuPtr, 0, + &appleID); + macMenuHdl = NewMenu(appleID, "\p\024"); + appleMenuPtr->platformData = + (TkMenuPlatformData) ckalloc(sizeof(MacMenu)); + ((MacMenu *)appleMenuPtr->platformData)->menuHdl + = macMenuHdl; + SetRect(&((MacMenu *) appleMenuPtr->platformData)->menuRect, + 0, 0, 0, 0); + 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; + } + if (helpIndex == -1) { + currentHelpMenuID = 0; + } + + for (i = 0; i < menuBarPtr->numEntries; i++) { + if (i == appleIndex) { + if (menuBarPtr->entries[i]->state == tkDisabledUid) { + DisableItem(((MacMenu *) menuBarPtr->entries[i] + ->childMenuRefPtr->menuPtr + ->platformData)->menuHdl, + 0); + } else { + EnableItem(((MacMenu *) menuBarPtr->entries[i] + ->childMenuRefPtr->menuPtr + ->platformData)->menuHdl, + 0); + } + continue; + } else if (i == helpIndex) { + TkMenu *helpMenuPtr = menuBarPtr->entries[i] + ->childMenuRefPtr->menuPtr; + MenuHandle helpMenuHdl = NULL; + + 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 = (*macMenuHdl)->menuID; + } 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((*macMenuHdl)->menuID); + InsertMenu(macMenuHdl, 0); + RecursivelyInsertMenu(cascadeMenuPtr); + if (menuBarPtr->entries[i]->state == tkDisabledUid) { + DisableItem(((MacMenu *) menuBarPtr->entries[i] + ->childMenuRefPtr->menuPtr + ->platformData)->menuHdl, + 0); + } else { + EnableItem(((MacMenu *) menuBarPtr->entries[i] + ->childMenuRefPtr->menuPtr + ->platformData)->menuHdl, + 0); + } + } + } + } + } + } else { + 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. + * + *---------------------------------------------------------------------- + */ + +static 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. + * + *---------------------------------------------------------------------- + */ + +static void +RecursivelyDeleteMenu( + 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; + DeleteMenu((*macMenuHdl)->menuID); + RecursivelyInsertMenu(cascadeMenuPtr); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * SetDefaultMenubar -- + * + * Puts the Apple, File and Edit menus into the Macintosh menubar. + * + * Results: + * None. + * + * Side effects: + * The menubar is changed. + * + *---------------------------------------------------------------------- + */ + +static void +SetDefaultMenubar() +{ + 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, (ClientData *) 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) TkMacGetDrawablePort(winPtr->window); + + if ((macWindowPtr == NULL) || (macWindowPtr != FrontWindow())) { + 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) { + menuPtr = menuPtr->masterMenuPtr; + searchWindow = menuPtr->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, (ClientData *) 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; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacDispatchMenuEvent -- + * + * Given a menu id and an item, dispatches the command associated + * with it. + * + * Results: + * None. + * + * Side effects: + * Commands get executed. + * + *---------------------------------------------------------------------- + */ + +int +TkMacDispatchMenuEvent( + 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)) { + int newIndex = index - helpItemCount - 1; + result = TkInvokeMenu(currentMenuBarInterp, + helpMenuRef->menuPtr, newIndex); + } + } + } else { + Tcl_HashEntry *commandEntryPtr = + Tcl_FindHashEntry(&commandTable, (char *) menuID); + TkMenu *menuPtr = (TkMenu *) Tcl_GetHashValue(commandEntryPtr); + if ((currentAppleMenuID == menuID) + && (index > menuPtr->numEntries + 1)) { + Str255 itemText; + + GetMenuItemText(GetMenuHandle(menuID), index, itemText); + OpenDeskAcc(itemText); + result = TCL_OK; + } else { + result = TkInvokeMenu(menuPtr->interp, menuPtr, index - 1); + } + } + } + return result; +} + +/* + *---------------------------------------------------------------------- + * + * GetMenuIndicatorGeometry -- + * + * Gets the width and height of the indicator area of a menu. + * + * Results: + * widthPtr and heightPtr are set. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static 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 */ +{ + char markChar; + + *heightPtr = fmPtr->linespace; + + markChar = (char) FindMarkCharacter(mePtr); + *widthPtr = Tk_TextWidth(tkfont, &markChar, 1) + 4; +} + +/* + *---------------------------------------------------------------------- + * + * GetMenuAccelGeometry -- + * + * Gets the width and height of the accelerator area of a menu. + * + * Results: + * widthPtr and heightPtr are set. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static 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; + *modWidthPtr = 0; + if (mePtr->type == CASCADE_ENTRY) { + *textWidthPtr = SICN_HEIGHT; + *modWidthPtr = Tk_TextWidth(tkfont, "W", 1); + } else if (0 == mePtr->accelLength) { + *textWidthPtr = 0; + } else { + + if (NULL == GetResource('SICN', SICN_RESOURCE_NUMBER)) { + *textWidthPtr = Tk_TextWidth(tkfont, mePtr->accel, + mePtr->accelLength); + } else { + int emWidth = Tk_TextWidth(tkfont, "W", 1) + 1; + if ((mePtr->entryFlags & ENTRY_ACCEL_MASK) == 0) { + int width = Tk_TextWidth(tkfont, mePtr->accel, + mePtr->accelLength); + *textWidthPtr = emWidth; + if (width < emWidth) { + *modWidthPtr = 0; + } else { + *modWidthPtr = width - emWidth; + } + } else { + int length = ((EntryGeometry *)mePtr->platformEntryData) + ->accelTextStart; + if (mePtr->entryFlags & ENTRY_CONTROL_ACCEL) { + *modWidthPtr += CONTROL_ICON_WIDTH; + } + if (mePtr->entryFlags & ENTRY_SHIFT_ACCEL) { + *modWidthPtr += SHIFT_ICON_WIDTH; + } + if (mePtr->entryFlags & ENTRY_OPTION_ACCEL) { + *modWidthPtr += OPTION_ICON_WIDTH; + } + if (mePtr->entryFlags & ENTRY_COMMAND_ACCEL) { + *modWidthPtr += COMMAND_ICON_WIDTH; + } + if (1 == (mePtr->accelLength - length)) { + *textWidthPtr = emWidth; + } else { + *textWidthPtr += Tk_TextWidth(tkfont, mePtr->accel + + length, mePtr->accelLength - length); + } + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * GetTearoffEntryGeometry -- + * + * Gets the width and height of of a tearoff entry. + * + * Results: + * widthPtr and heightPtr are set. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static 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 */ +{ + if ((GetResource('MDEF', 591) == NULL) && + (menuPtr->menuType == MASTER_MENU)) { + *heightPtr = fmPtr->linespace; + *widthPtr = 0; + } else { + *widthPtr = *heightPtr = 0; + } +} + +/* + *---------------------------------------------------------------------- + * + * GetMenuSeparatorGeometry -- + * + * Gets the width and height of menu separator. + * + * Results: + * widthPtr and heightPtr are set. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static 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 = fmPtr->linespace; +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static 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)) + && (mePtr->indicatorOn) + && (mePtr->entryFlags & ENTRY_SELECTED)) { + int baseline; + short markShort; + char markChar; + + baseline = y + (height + fmPtr->ascent - fmPtr->descent) / 2; + GetItemMark(((MacMenu *) menuPtr->platformData)->menuHdl, + mePtr->index + 1, &markShort); + if (markShort != 0) { + markChar = (char) markShort; + Tk_DrawChars(menuPtr->display, d, gc, tkfont, &markChar, 1, + x + 2, baseline); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * DrawSICN -- + * + * Given a resource id and an index, loads the appropriate SICN + * and draws it into a given drawable using the given gc. + * + * Results: + * Returns 1 if the SICN was found, 0 if not found. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ +static int +DrawSICN( + int resourceID, /* The resource # of the SICN table */ + int index, /* The index into the SICN table of the + * icon we want. */ + Drawable d, /* What we are drawing into */ + GC gc, /* The GC to draw with */ + int x, /* The left hand coord of the SICN */ + int y) /* The top coord of the SICN */ +{ + Handle sicnHandle = (Handle) GetResource('SICN', SICN_RESOURCE_NUMBER); + + if (NULL == sicnHandle) { + return 0; + } else { + BitMap sicnBitmap; + Rect destRect; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + BitMapPtr destBitMap; + RGBColor origForeColor, origBackColor, foreColor, backColor; + + HLock(sicnHandle); + destPort = TkMacGetDrawablePort(d); + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + TkMacSetUpClippingRgn(d); + TkMacSetUpGraphicsPort(gc); + GetForeColor(&origForeColor); + GetBackColor(&origBackColor); + + if (TkSetMacColor(gc->foreground, &foreColor) == true) { + RGBForeColor(&foreColor); + } + + if (TkSetMacColor(gc->background, &backColor) == true) { + RGBBackColor(&backColor); + } + + SetRect(&destRect, x, y, x + SICN_HEIGHT, y + SICN_HEIGHT); + sicnBitmap.baseAddr = (Ptr) (*sicnHandle) + index * SICN_HEIGHT + * SICN_ROWS; + sicnBitmap.rowBytes = SICN_ROWS; + SetRect(&sicnBitmap.bounds, 0, 0, 16, 16); + destBitMap = &((GrafPtr) destPort)->portBits; + CopyBits(&sicnBitmap, destBitMap, &sicnBitmap.bounds, &destRect, + destPort->txMode, NULL); + HUnlock(sicnHandle); + RGBForeColor(&origForeColor); + RGBBackColor(&origBackColor); + SetGWorld(saveWorld, saveDevice); + return 1; + } +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuEntryAccelerator -- + * + * This procedure draws the accelerator part of a menu. We + * need to decide what to draw here. Should we replace strings + * like "Control", "Command", etc? + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static 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) { + if (0 == DrawSICN(SICN_RESOURCE_NUMBER, CASCADE_ARROW, d, gc, + x + width - SICN_HEIGHT, (y + (height / 2)) + - (SICN_HEIGHT / 2))) { + XPoint points[3]; + Tk_Window tkwin = menuPtr->tkwin; + + if (mePtr->type == CASCADE_ENTRY) { + points[0].x = width - menuPtr->activeBorderWidth + - MAC_MARGIN_WIDTH - CASCADE_ARROW_WIDTH; + points[0].y = y + (height - CASCADE_ARROW_HEIGHT)/2; + points[1].x = points[0].x; + points[1].y = points[0].y + CASCADE_ARROW_HEIGHT; + points[2].x = points[0].x + CASCADE_ARROW_WIDTH; + points[2].y = points[0].y + CASCADE_ARROW_HEIGHT/2; + Tk_Fill3DPolygon(menuPtr->tkwin, d, activeBorder, points, + 3, DECORATION_BORDER_WIDTH, TK_RELIEF_FLAT); + } + } + } else if (mePtr->accelLength != 0) { + int leftEdge = x + width; + int baseline = y + (height + fmPtr->ascent - fmPtr->descent) / 2; + + if (NULL == GetResource('SICN', SICN_RESOURCE_NUMBER)) { + leftEdge -= ((EntryGeometry *) mePtr->platformEntryData) + ->accelTextWidth; + Tk_DrawChars(menuPtr->display, d, gc, tkfont, mePtr->accel, + mePtr->accelLength, leftEdge, baseline); + } else { + EntryGeometry *geometryPtr = + (EntryGeometry *) mePtr->platformEntryData; + int length = mePtr->accelLength - geometryPtr->accelTextStart; + + leftEdge -= geometryPtr->accelTextWidth; + if ((mePtr->entryFlags & ENTRY_ACCEL_MASK) == 0) { + leftEdge -= geometryPtr->modifierWidth; + } + + Tk_DrawChars(menuPtr->display, d, gc, tkfont, mePtr->accel + + geometryPtr->accelTextStart, length, leftEdge, baseline); + + if (mePtr->entryFlags & ENTRY_COMMAND_ACCEL) { + leftEdge -= COMMAND_ICON_WIDTH; + DrawSICN(SICN_RESOURCE_NUMBER, COMMAND_ICON, d, gc, + leftEdge, (y + (height / 2)) - (SICN_HEIGHT / 2) - 1); + } + + if (mePtr->entryFlags & ENTRY_OPTION_ACCEL) { + leftEdge -= OPTION_ICON_WIDTH; + DrawSICN(SICN_RESOURCE_NUMBER, OPTION_ICON, d, gc, + leftEdge, (y + (height / 2)) - (SICN_HEIGHT / 2) - 1); + } + + if (mePtr->entryFlags & ENTRY_SHIFT_ACCEL) { + leftEdge -= SHIFT_ICON_WIDTH; + DrawSICN(SICN_RESOURCE_NUMBER, SHIFT_ICON, d, gc, + leftEdge, (y + (height / 2)) - (SICN_HEIGHT / 2) - 1); + } + + if (mePtr->entryFlags & ENTRY_CONTROL_ACCEL) { + leftEdge -= CONTROL_ICON_WIDTH; + DrawSICN(SICN_RESOURCE_NUMBER, CONTROL_ICON, d, gc, + leftEdge, (y + (height / 2)) - (SICN_HEIGHT / 2) - 1); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuSeparator -- + * + * The menu separator is drawn. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static 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 */ +{ + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + + destPort = TkMacGetDrawablePort(d); + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + TkMacSetUpClippingRgn(d); + + /* + * We don't want to use the text GC for drawing the separator. It + * needs to be the same color as disabled items. + */ + + TkMacSetUpGraphicsPort(mePtr->disabledGC != None ? mePtr->disabledGC + : menuPtr->disabledGC); + + MoveTo(x, y + (height / 2)); + Line(width, 0); + + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static void +MenuDefProc( + short message, /* What action are we taking? */ + MenuHandle 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. */ + short *whichItem, /* Output result. Which item was + * hit by the user? */ + TkMenuLowMemGlobals *globalsPtr) /* The low mem globals we have + * to change */ +{ +#define SCREEN_MARGIN 5 + TkMenu *menuPtr; + TkMenuEntry *parentEntryPtr; + Tcl_HashEntry *commandEntryPtr; + GrafPtr windowMgrPort; + Tk_Font tkfont; + Tk_FontMetrics fontMetrics, entryMetrics; + Tk_FontMetrics *fmPtr; + TkMenuEntry *mePtr; + int i; + int maxMenuHeight; + int oldItem; + int newItem = -1; + GDHandle device; + Rect itemRect; + short windowPart; + WindowRef whichWindow; + RGBColor bgColor; + RGBColor fgColor; + RGBColor origFgColor; + PenState origPenState; + Rect dragRect; + Rect scratchRect = {-32768, -32768, 32767, 32767}; + RgnHandle oldClipRgn; + TkMenuReferences *menuRefPtr; + TkMenu *searchMenuPtr; + Rect menuClipRect; + + HLock((Handle) menu); + commandEntryPtr = Tcl_FindHashEntry(&commandTable, + (char *) (*menu)->menuID); + HUnlock((Handle) menu); + menuPtr = (TkMenu *) Tcl_GetHashValue(commandEntryPtr); + + switch (message) { + case mSizeMsg: + GetWMgrPort(&windowMgrPort); + maxMenuHeight = windowMgrPort->portRect.bottom + - windowMgrPort->portRect.top + - GetMBarHeight() - SCREEN_MARGIN; + (*menu)->menuWidth = menuPtr->totalWidth; + (*menu)->menuHeight = maxMenuHeight < menuPtr->totalHeight ? + maxMenuHeight : menuPtr->totalHeight; + break; + + case mDrawMsg: + + /* + * Store away the menu rectangle so we can keep track of the + * different regions that the menu obscures. + */ + + ((MacMenu *) menuPtr->platformData)->menuRect = *menuRectPtr; + if (tkMenuCascadeRgn == NULL) { + tkMenuCascadeRgn = NewRgn(); + } + if (utilRgn == NULL) { + utilRgn = NewRgn(); + } + if (totalMenuRgn == NULL) { + totalMenuRgn = NewRgn(); + } + SetEmptyRgn(tkMenuCascadeRgn); + for (searchMenuPtr = menuPtr; searchMenuPtr != NULL; ) { + RectRgn(utilRgn, + &((MacMenu *) searchMenuPtr->platformData)->menuRect); + InsetRgn(utilRgn, -1, -1); + UnionRgn(tkMenuCascadeRgn, utilRgn, tkMenuCascadeRgn); + OffsetRgn(utilRgn, 1, 1); + UnionRgn(tkMenuCascadeRgn, utilRgn, tkMenuCascadeRgn); + + if (searchMenuPtr->menuRefPtr->parentEntryPtr != NULL) { + searchMenuPtr = searchMenuPtr->menuRefPtr + ->parentEntryPtr->menuPtr; + } else { + break; + } + if (searchMenuPtr->menuType == MENUBAR) { + break; + } + } + UnionRgn(totalMenuRgn, tkMenuCascadeRgn, totalMenuRgn); + SetEmptyRgn(utilRgn); + + /* + * Next, figure out scrolling information. + */ + + GetGWorld(&macMDEFDrawable.portPtr, &device); + menuClipRect = *menuRectPtr; + if ((menuClipRect.bottom - menuClipRect.top) + < menuPtr->totalHeight) { + if (globalsPtr->menuTop < menuRectPtr->top) { + DrawSICN(SICN_RESOURCE_NUMBER, UP_ARROW, + (Drawable) &macMDEFDrawable, + menuPtr->textGC, + menuRectPtr->left + + menuPtr->entries[1]->indicatorSpace, + menuRectPtr->top); + menuClipRect.top += SICN_HEIGHT; + } + if ((globalsPtr->menuTop + menuPtr->totalHeight) + > menuRectPtr->bottom) { + DrawSICN(SICN_RESOURCE_NUMBER, DOWN_ARROW, + (Drawable) &macMDEFDrawable, + menuPtr->textGC, + menuRectPtr->left + + menuPtr->entries[1]->indicatorSpace, + menuRectPtr->bottom - SICN_HEIGHT); + menuClipRect.bottom -= SICN_HEIGHT; + } + GetClip(utilRgn); + } + + /* + * 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. + */ + + Tk_GetFontMetrics(menuPtr->tkfont, &fontMetrics); + for (i = 0; i < menuPtr->numEntries; i++) { + mePtr = menuPtr->entries[i]; + if (globalsPtr->menuTop + mePtr->y + mePtr->height + < menuClipRect.top) { + continue; + } else if (globalsPtr->menuTop + mePtr->y + > menuClipRect.bottom) { + continue; + } + ClipRect(&menuClipRect); + if (mePtr->tkfont == NULL) { + fmPtr = &fontMetrics; + tkfont = menuPtr->tkfont; + } else { + tkfont = mePtr->tkfont; + Tk_GetFontMetrics(tkfont, &entryMetrics); + fmPtr = &entryMetrics; + } + TkpDrawMenuEntry(mePtr, (Drawable) &macMDEFDrawable, + tkfont, fmPtr, menuRectPtr->left + mePtr->x, + globalsPtr->menuTop + mePtr->y, + (mePtr->entryFlags & ENTRY_LAST_COLUMN) ? + menuPtr->totalWidth - mePtr->x : mePtr->width, + menuPtr->entries[i]->height, 0, 1); + } + globalsPtr->menuBottom = globalsPtr->menuTop + + menuPtr->totalHeight; + if (!EmptyRgn(utilRgn)) { + SetClip(utilRgn); + SetEmptyRgn(utilRgn); + } + MDEFScrollFlag = 1; + break; + + case mChooseMsg: { + int hasTopScroll, hasBottomScroll; + enum { + DONT_SCROLL, DOWN_SCROLL, UP_SCROLL + } scrollDirection; + Rect updateRect; + short scrollAmt; + RGBColor origForeColor, origBackColor, foreColor, backColor; + + GetGWorld(&macMDEFDrawable.portPtr, &device); + GetForeColor(&origForeColor); + GetBackColor(&origBackColor); + + if (TkSetMacColor(menuPtr->textGC->foreground, + &foreColor) == true) { + RGBForeColor(&foreColor); + } + if (TkSetMacColor(menuPtr->textGC->background, + &backColor) == true) { + RGBBackColor(&backColor); + } + + /* + * Find out which item was hit. If it is the same as the old item, + * we don't need to do anything. + */ + + oldItem = *whichItem - 1; + + if (PtInRect(hitPt, menuRectPtr)) { + for (i = 0; i < menuPtr->numEntries; i++) { + mePtr = menuPtr->entries[i]; + itemRect.left = menuRectPtr->left + mePtr->x; + itemRect.top = globalsPtr->menuTop + mePtr->y; + if (mePtr->entryFlags & ENTRY_LAST_COLUMN) { + itemRect.right = itemRect.left + menuPtr->totalWidth + - mePtr->x; + } else { + itemRect.right = itemRect.left + mePtr->width; + } + itemRect.bottom = itemRect.top + + menuPtr->entries[i]->height; + if (PtInRect(hitPt, &itemRect)) { + if ((mePtr->type == SEPARATOR_ENTRY) + || (mePtr->state == tkDisabledUid)) { + newItem = -1; + } else { + TkMenuEntry *cascadeEntryPtr; + int parentDisabled = 0; + + for (cascadeEntryPtr + = menuPtr->menuRefPtr->parentEntryPtr; + cascadeEntryPtr != NULL; + cascadeEntryPtr + = cascadeEntryPtr->nextCascadePtr) { + if (strcmp(cascadeEntryPtr->name, + Tk_PathName(menuPtr->tkwin)) == 0) { + if (cascadeEntryPtr->state + == tkDisabledUid) { + parentDisabled = 1; + } + break; + } + } + if (parentDisabled) { + newItem = -1; + } else { + newItem = i; + if ((mePtr->type == CASCADE_ENTRY) + && (oldItem != newItem)) { + globalsPtr->itemRect = itemRect; + } + } + } + break; + } + } + } + + /* + * Now we need to take care of scrolling the menu. + */ + + hasTopScroll = globalsPtr->menuTop < menuRectPtr->top; + hasBottomScroll = globalsPtr->menuBottom > menuRectPtr->bottom; + scrollDirection = DONT_SCROLL; + if (hasTopScroll + && (hitPt.v < menuRectPtr->top + SICN_HEIGHT)) { + newItem = -1; + scrollDirection = DOWN_SCROLL; + } else if (hasBottomScroll + && (hitPt.v > menuRectPtr->bottom - SICN_HEIGHT)) { + newItem = -1; + scrollDirection = UP_SCROLL; + } + menuClipRect = *menuRectPtr; + if (hasTopScroll) { + menuClipRect.top += SICN_HEIGHT; + } + if (hasBottomScroll) { + menuClipRect.bottom -= SICN_HEIGHT; + } + if (MDEFScrollFlag) { + scrollDirection = DONT_SCROLL; + MDEFScrollFlag = 0; + } + GetClip(utilRgn); + ClipRect(&menuClipRect); + + if (oldItem != newItem) { + if (oldItem >= 0) { + mePtr = menuPtr->entries[oldItem]; + tkfont = mePtr->tkfont ? mePtr->tkfont : menuPtr->tkfont; + Tk_GetFontMetrics(tkfont, &fontMetrics); + TkpDrawMenuEntry(mePtr, (Drawable) &macMDEFDrawable, + tkfont, &fontMetrics, + menuRectPtr->left + mePtr->x, + globalsPtr->menuTop + mePtr->y, + (mePtr->entryFlags & ENTRY_LAST_COLUMN) + ? menuPtr->totalWidth - mePtr->x + : mePtr->width, mePtr->height, 0, 1); + } + if (newItem != -1) { + int oldActiveItem = menuPtr->active; + + mePtr = menuPtr->entries[newItem]; + if (mePtr->state != tkDisabledUid) { + TkActivateMenuEntry(menuPtr, newItem); + } + tkfont = mePtr->tkfont ? mePtr->tkfont : menuPtr->tkfont; + Tk_GetFontMetrics(tkfont, &fontMetrics); + TkpDrawMenuEntry(mePtr, (Drawable) &macMDEFDrawable, + tkfont, &fontMetrics, + menuRectPtr->left + mePtr->x, + globalsPtr->menuTop + mePtr->y, + (mePtr->entryFlags & ENTRY_LAST_COLUMN) + ? menuPtr->totalWidth - mePtr->x + : mePtr->width, mePtr->height, + 0, 1); + } + + tkUseMenuCascadeRgn = 1; + MenuSelectEvent(menuPtr); + Tcl_ServiceAll(); + tkUseMenuCascadeRgn = 0; + if (mePtr->state != tkDisabledUid) { + TkActivateMenuEntry(menuPtr, -1); + } + *whichItem = newItem + 1; + } + globalsPtr->menuDisable = ((*menu)->menuID << 16) | (newItem + 1); + + if (scrollDirection == UP_SCROLL) { + scrollAmt = menuClipRect.bottom - hitPt.v; + if (scrollAmt < menuRectPtr->bottom + - globalsPtr->menuBottom) { + scrollAmt = menuRectPtr->bottom - globalsPtr->menuBottom; + } + if (!hasTopScroll && ((globalsPtr->menuTop + scrollAmt) < menuRectPtr->top)) { + SetRect(&updateRect, menuRectPtr->left, + globalsPtr->menuTop, menuRectPtr->right, + globalsPtr->menuTop + SICN_HEIGHT); + EraseRect(&updateRect); + DrawSICN(SICN_RESOURCE_NUMBER, UP_ARROW, + (Drawable) &macMDEFDrawable, + menuPtr->textGC, menuRectPtr->left + + menuPtr->entries[1]->indicatorSpace, + menuRectPtr->top); + menuClipRect.top += SICN_HEIGHT; + } + } else if (scrollDirection == DOWN_SCROLL) { + scrollAmt = menuClipRect.top - hitPt.v; + if (scrollAmt > menuRectPtr->top - globalsPtr->menuTop) { + scrollAmt = menuRectPtr->top - globalsPtr->menuTop; + } + if (!hasBottomScroll && ((globalsPtr->menuBottom + scrollAmt) + > menuRectPtr->bottom)) { + SetRect(&updateRect, menuRectPtr->left, + globalsPtr->menuBottom - SICN_HEIGHT, + menuRectPtr->right, globalsPtr->menuBottom); + EraseRect(&updateRect); + DrawSICN(SICN_RESOURCE_NUMBER, DOWN_ARROW, + (Drawable) &macMDEFDrawable, + menuPtr->textGC, menuRectPtr->left + + menuPtr->entries[1]->indicatorSpace, + menuRectPtr->bottom - SICN_HEIGHT); + menuClipRect.bottom -= SICN_HEIGHT; + } + } + if (scrollDirection != DONT_SCROLL) { + RgnHandle updateRgn = NewRgn(); + ScrollRect(&menuClipRect, 0, scrollAmt, updateRgn); + updateRect = (*updateRgn)->rgnBBox; + DisposeRgn(updateRgn); + globalsPtr->menuTop += scrollAmt; + globalsPtr->menuBottom += scrollAmt; + if (globalsPtr->menuTop == menuRectPtr->top) { + updateRect.top -= SICN_HEIGHT; + } + if (globalsPtr->menuBottom == menuRectPtr->bottom) { + updateRect.bottom += SICN_HEIGHT; + } + ClipRect(&updateRect); + EraseRect(&updateRect); + Tk_GetFontMetrics(menuPtr->tkfont, &fontMetrics); + for (i = 0; i < menuPtr->numEntries; i++) { + mePtr = menuPtr->entries[i]; + if (globalsPtr->menuTop + mePtr->y + mePtr->height + < updateRect.top) { + continue; + } else if (globalsPtr->menuTop + mePtr->y + > updateRect.bottom) { + continue; + } + if (mePtr->tkfont == NULL) { + fmPtr = &fontMetrics; + tkfont = menuPtr->tkfont; + } else { + tkfont = mePtr->tkfont; + Tk_GetFontMetrics(tkfont, &entryMetrics); + fmPtr = &entryMetrics; + } + TkpDrawMenuEntry(mePtr, (Drawable) &macMDEFDrawable, + tkfont, fmPtr, menuRectPtr->left + mePtr->x, + globalsPtr->menuTop + mePtr->y, + (mePtr->entryFlags & ENTRY_LAST_COLUMN) ? + menuPtr->totalWidth - mePtr->x : mePtr->width, + menuPtr->entries[i]->height, 0, 1); + } + } + + SetClip(utilRgn); + SetEmptyRgn(utilRgn); + RGBForeColor(&origForeColor); + RGBBackColor(&origBackColor); + + /* + * If the menu is a tearoff, and the mouse is outside the menu, + * we need to draw the drag rectangle. + * + * In order for tearoffs to work properly, we need to set + * the active member of the containing menubar. + */ + + menuRefPtr = TkFindMenuReferences(menuPtr->interp, + Tk_PathName(menuPtr->tkwin)); + if ((menuRefPtr != NULL) && (menuRefPtr->parentEntryPtr != NULL)) { + for (parentEntryPtr = menuRefPtr->parentEntryPtr; + strcmp(parentEntryPtr->name, + Tk_PathName(menuPtr->tkwin)) == 0; + parentEntryPtr = parentEntryPtr->nextCascadePtr) { + } + if (parentEntryPtr != NULL) { + TkActivateMenuEntry(parentEntryPtr->menuPtr, + parentEntryPtr->index); + } + } + + if (menuPtr->tearOff) { + scratchRect = *menuRectPtr; + if (tearoffStruct.menuPtr == NULL) { + scratchRect.top -= 10; + scratchRect.bottom += 10; + scratchRect.left -= 10; + scratchRect.right += 10; + } + + windowPart = FindWindow(hitPt, &whichWindow); + if ((windowPart != inMenuBar) && (newItem == -1) + && (hitPt.v != 0) && (hitPt.h != 0) + && (!PtInRect(hitPt, &scratchRect)) + && (!PtInRect(hitPt, &tearoffStruct.excludeRect))) { +/* + * This is the second argument to the Toolbox Delay function. It changed + * from long to unsigned long between Universal Headers 2.0 & 3.0 + */ +#if !defined(UNIVERSAL_INTERFACES_VERSION) || (UNIVERSAL_INTERFACES_VERSION < 0x0300) + long dummy; +#else + unsigned long dummy; +#endif + oldClipRgn = NewRgn(); + GetClip(oldClipRgn); + GetForeColor(&origFgColor); + GetPenState(&origPenState); + GetForeColor(&fgColor); + GetBackColor(&bgColor); + GetGray(device, &bgColor, &fgColor); + RGBForeColor(&fgColor); + SetRect(&scratchRect, -32768, -32768, 32767, 32767); + ClipRect(&scratchRect); + + dragRect = *menuRectPtr; + tearoffStruct.menuPtr = menuPtr; + + PenMode(srcXor); + dragRect = *menuRectPtr; + OffsetRect(&dragRect, -dragRect.left, -dragRect.top); + OffsetRect(&dragRect, tearoffStruct.point.h, + tearoffStruct.point.v); + if ((dragRect.top != 0) && (dragRect.left != 0)) { + FrameRect(&dragRect); + Delay(1, &dummy); + FrameRect(&dragRect); + } + tearoffStruct.point = hitPt; + + SetClip(oldClipRgn); + DisposeRgn(oldClipRgn); + RGBForeColor(&origFgColor); + SetPenState(&origPenState); + } else { + tearoffStruct.menuPtr = NULL; + tearoffStruct.point.h = tearoffStruct.point.v = 0; + } + } else { + tearoffStruct.menuPtr = NULL; + tearoffStruct.point.h = tearoffStruct.point.v = 0; + } + + break; + } + + case mPopUpMsg: + + /* + * 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; + } + GetWMgrPort(&windowMgrPort); + maxMenuHeight = windowMgrPort->portRect.bottom + - windowMgrPort->portRect.top + - GetMBarHeight() - SCREEN_MARGIN; + if (menuPtr->totalHeight > maxMenuHeight) { + menuRectPtr->top = GetMBarHeight(); + } else { + menuRectPtr->top = hitPt.h; + if (oldItem >= 0) { + menuRectPtr->top -= menuPtr->entries[oldItem]->y; + } + if (menuRectPtr->top + menuPtr->totalHeight > maxMenuHeight) { + menuRectPtr->top -= maxMenuHeight - menuPtr->totalHeight; + } + } + menuRectPtr->left = hitPt.v; + menuRectPtr->right = menuRectPtr->left + menuPtr->totalWidth; + menuRectPtr->bottom = menuRectPtr->top + + ((maxMenuHeight < menuPtr->totalHeight) + ? maxMenuHeight : menuPtr->totalHeight); + if (menuRectPtr->top == GetMBarHeight()) { + *whichItem = hitPt.h; + } else { + *whichItem = menuRectPtr->top; + } + break; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacHandleTearoffMenu() -- + * + * 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 +TkMacHandleTearoffMenu(void) +{ + if (tearoffStruct.menuPtr != NULL) { + Tcl_DString tearoffCmdStr; + char intString[20]; + short windowPart; + WindowRef whichWindow; + + windowPart = FindWindow(tearoffStruct.point, &whichWindow); + + if (windowPart != inMenuBar) { + Tcl_DStringInit(&tearoffCmdStr); + Tcl_DStringAppendElement(&tearoffCmdStr, "tkTearOffMenu"); + Tcl_DStringAppendElement(&tearoffCmdStr, + Tk_PathName(tearoffStruct.menuPtr->tkwin)); + sprintf(intString, "%d", tearoffStruct.point.h); + Tcl_DStringAppendElement(&tearoffCmdStr, intString); + sprintf(intString, "%d", tearoffStruct.point.v); + Tcl_DStringAppendElement(&tearoffCmdStr, intString); + Tcl_Eval(tearoffStruct.menuPtr->interp, + Tcl_DStringValue(&tearoffCmdStr)); + Tcl_DStringFree(&tearoffCmdStr); + tearoffStruct.menuPtr = NULL; + } + } +} + +/* + *-------------------------------------------------------------- + * + * 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(interp, bindingTable) + 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(menuPtr) + TkMenu *menuPtr; /* Structure describing menu. */ +{ + TkpComputeStandardMenuGeometry(menuPtr); +} + +/* + *---------------------------------------------------------------------- + * + * DrawTearoffEntry -- + * + * This procedure draws the background part of a menu. + * + * 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; + + if ((menuPtr->menuType != MASTER_MENU) || (GetResource('MDEF', 591) != NULL)) { + return; + } + + margin = (fmPtr->ascent + fmPtr->descent)/2; + points[0].x = x; + points[0].y = y + height/2; + points[1].y = points[0].y; + segmentWidth = 6; + maxX = width - 1; + + 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, menuPtr->border, points, 2, 1, + TK_RELIEF_RAISED); + points[0].x += 2*segmentWidth; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacSetHelpMenuItemCount -- + * + * 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. + * + * Results: + * None. + * + * Side effects: + * Sets the global helpItemCount. + * + *---------------------------------------------------------------------- + */ + +void +TkMacSetHelpMenuItemCount() +{ + MenuHandle helpMenuHandle; + + if ((HMGetHelpMenuHandle(&helpMenuHandle) != noErr) + || (helpMenuHandle == NULL)) { + helpItemCount = -1; + } else { + helpItemCount = CountMItems(helpMenuHandle); + DeleteMenuItem(helpMenuHandle, helpItemCount); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacMenuClick -- + * + * Prepares a menubar for MenuSelect or MenuKey. + * + * Results: + * None. + * + * Side effects: + * Any pending configurations of the menubar are completed. + * + *---------------------------------------------------------------------- + */ + +void +TkMacMenuClick() +{ + 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, (ClientData *) NULL); + DrawMenuBarWhenIdle((ClientData *) 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, indicatorGC; + TkMenu *menuPtr = mePtr->menuPtr; + Tk_3DBorder bgBorder, activeBorder; + CONST Tk_FontMetrics *fmPtr; + Tk_FontMetrics entryMetrics; + int padY = (menuPtr->menuType == MENUBAR) ? 3 : 0; + int adjustedY = y + padY; + int adjustedHeight = height - 2 * padY; + + /* + * Choose the gc for drawing the foreground part of the entry. + */ + + if ((mePtr->state == tkActiveUid) + && !strictMotif) { + gc = mePtr->activeGC; + if (gc == NULL) { + gc = menuPtr->activeGC; + } + } else { + TkMenuEntry *cascadeEntryPtr; + int parentDisabled = 0; + + for (cascadeEntryPtr = menuPtr->menuRefPtr->parentEntryPtr; + cascadeEntryPtr != NULL; + cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr) { + if (strcmp(cascadeEntryPtr->name, + Tk_PathName(menuPtr->tkwin)) == 0) { + if (cascadeEntryPtr->state == tkDisabledUid) { + parentDisabled = 1; + } + break; + } + } + + if (((parentDisabled || (mePtr->state == tkDisabledUid))) + && (menuPtr->disabledFg != 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 = mePtr->border; + if (bgBorder == NULL) { + bgBorder = menuPtr->border; + } + if (strictMotif) { + activeBorder = bgBorder; + } else { + activeBorder = mePtr->activeBorder; + if (activeBorder == NULL) { + activeBorder = menuPtr->activeBorder; + } + } + + if (mePtr->tkfont == NULL) { + fmPtr = menuMetricsPtr; + } else { + tkfont = mePtr->tkfont; + 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; + 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; + TkMenuEntry *mePtr, *columnEntryPtr; + EntryGeometry *geometryPtr; + + if (menuPtr->tkwin == NULL) { + return; + } + + x = y = menuPtr->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. + */ + + Tk_GetFontMetrics(menuPtr->tkfont, &menuMetrics); + + for (i = 0; i < menuPtr->numEntries; i++) { + mePtr = menuPtr->entries[i]; + tkfont = mePtr->tkfont; + if (tkfont == NULL) { + tkfont = menuPtr->tkfont; + fmPtr = &menuMetrics; + } else { + 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 * menuPtr->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 * menuPtr->borderWidth; + windowWidth = x; + maxWidth = maxIndicatorSpace = maxAccelTextWidth = 0; + maxModifierWidth = maxNonAccelMargin = maxEntryWithAccelWidth = 0; + maxEntryWithoutAccelWidth = 0; + lastColumnBreak = i; + y = menuPtr->borderWidth; + } + + 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; + + if (mePtr->type == CASCADE_ENTRY) { + GetMenuAccelGeometry(menuPtr, mePtr, tkfont, fmPtr, + &modifierWidth, &accelWidth, &height); + nonAccelMargin = 0; + } else if (mePtr->accelLength == 0) { + nonAccelMargin = mePtr->hideMargin ? 0 + : Tk_TextWidth(tkfont, "m", 1); + accelWidth = modifierWidth = 0; + } else { + labelWidth += Tk_TextWidth(tkfont, "m", 1); + GetMenuAccelGeometry(menuPtr, mePtr, tkfont, + fmPtr, &modifierWidth, &accelWidth, &height); + if (height > mePtr->height) { + mePtr->height = height; + } + nonAccelMargin = 0; + } + + 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 * menuPtr->activeBorderWidth; + } + mePtr->y = y; + y += menuPtr->entries[i]->height + menuPtr->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 * menuPtr->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; + } + } + windowWidth = x + maxIndicatorSpace + maxWidth + + 2 * menuPtr->activeBorderWidth + menuPtr->borderWidth; + windowHeight += menuPtr->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. + * + *---------------------------------------------------------------------- + */ + +static 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 baseline; + int indicatorSpace = mePtr->indicatorSpace; + int leftEdge = x + indicatorSpace; + int imageHeight, imageWidth; + + /* + * Draw label or bitmap or image for entry. + */ + + baseline = y + (height + fmPtr->ascent - fmPtr->descent) / 2; + if (mePtr->image != NULL) { + Tk_SizeOfImage(mePtr->image, &imageWidth, &imageHeight); + if ((mePtr->selectImage != NULL) + && (mePtr->entryFlags & ENTRY_SELECTED)) { + Tk_RedrawImage(mePtr->selectImage, 0, 0, + imageWidth, imageHeight, d, leftEdge, + (int) (y + (mePtr->height - imageHeight)/2)); + } else { + Tk_RedrawImage(mePtr->image, 0, 0, imageWidth, + imageHeight, d, leftEdge, + (int) (y + (mePtr->height - imageHeight)/2)); + } + } else if (mePtr->bitmap != None) { + int width, height; + + Tk_SizeOfBitmap(menuPtr->display, + mePtr->bitmap, &width, &height); + XCopyPlane(menuPtr->display, + mePtr->bitmap, d, + gc, 0, 0, (unsigned) width, (unsigned) height, leftEdge, + (int) (y + (mePtr->height - height)/2), 1); + } else { + if (mePtr->labelLength > 0) { + Str255 itemText; + + GetEntryText(mePtr, itemText); + Tk_DrawChars(menuPtr->display, d, gc, + tkfont, (char *) itemText + 1, itemText[0], + leftEdge, baseline); +/* TkpDrawMenuUnderline(menuPtr, mePtr, d, gc, tkfont, fmPtr, x, y, + width, height);*/ + } + } + + if (mePtr->state == tkDisabledUid) { + if (menuPtr->disabledFg == NULL) { + XFillRectangle(menuPtr->display, d, menuPtr->disabledGC, x, y, + (unsigned) width, (unsigned) height); + } else if ((mePtr->image != NULL) + && (menuPtr->disabledImageGC != None)) { + XFillRectangle(menuPtr->display, d, menuPtr->disabledImageGC, + leftEdge, + (int) (y + (mePtr->height - imageHeight)/2), + (unsigned) imageWidth, (unsigned) imageHeight); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuEntryBackground -- + * + * This procedure draws the background part of a menu. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static 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 (mePtr->state == tkActiveUid) { + 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. + * + *---------------------------------------------------------------------- + */ + +static 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; + + if (mePtr->image != NULL) { + Tk_SizeOfImage(mePtr->image, widthPtr, heightPtr); + } else if (mePtr->bitmap != (Pixmap) NULL) { + Tk_SizeOfBitmap(menuPtr->display, mePtr->bitmap, widthPtr, heightPtr); + } else { + *heightPtr = fmPtr->linespace; + + if (mePtr->label != NULL) { + Str255 itemText; + + GetEntryText(mePtr, itemText); + *widthPtr = Tk_TextWidth(tkfont, (char *) itemText + 1, + itemText[0]); + } else { + *widthPtr = 0; + } + } + *heightPtr += 1; +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static void +MenuSelectEvent( + TkMenu *menuPtr) /* the menu we have selected. */ +{ + XVirtualEvent event; + Point where; + + 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(); + + GetMouse(&where); + event.x_root = where.h; + event.y_root = where.v; + event.state = TkMacButtonKeyState(); + event.same_screen = true; + event.name = Tk_GetUid("MenuSelect"); + Tk_QueueWindowEvent((XEvent *) &event, TCL_QUEUE_TAIL); +} + +/* + *---------------------------------------------------------------------- + * + * 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); + MenuSelectEvent(menuPtr); + 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); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * InvalidateMDEFRgns -- + * + * Invalidates the regions covered by menus that did redrawing and + * might be damaged. + * + * Results: + * None. + * + * Side effects: + * Generates Mac update events for affected windows. + * + *---------------------------------------------------------------------- + */ + +void +InvalidateMDEFRgns(void) { + GDHandle saveDevice; + GWorldPtr saveWorld, destPort; + Point scratch; + MacDrawable *macDraw; + TkMacWindowList *listPtr; + + if (totalMenuRgn == NULL) { + return; + } + + GetGWorld(&saveWorld, &saveDevice); + for (listPtr = tkMacWindowListPtr ; listPtr != NULL; + listPtr = listPtr->nextPtr) { + macDraw = (MacDrawable *) Tk_WindowId(listPtr->winPtr); + if (macDraw->flags & TK_DRAWN_UNDER_MENU) { + destPort = TkMacGetDrawablePort(Tk_WindowId(listPtr->winPtr)); + SetGWorld(destPort, NULL); + scratch.h = scratch.v = 0; + GlobalToLocal(&scratch); + OffsetRgn(totalMenuRgn, scratch.v, scratch.h); + InvalRgn(totalMenuRgn); + OffsetRgn(totalMenuRgn, -scratch.v, -scratch.h); + macDraw->flags &= ~TK_DRAWN_UNDER_MENU; + } + } + + SetGWorld(saveWorld, saveDevice); + SetEmptyRgn(totalMenuRgn); +} + +/* + *---------------------------------------------------------------------- + * + * TkMacClearMenubarActive -- + * + * Recursively clears the active entry in the current menubar hierarchy. + * + * Results: + * None. + * + * Side effects: + * Generates <<MenuSelect>> virtual events. + * + *---------------------------------------------------------------------- + */ + +void +TkMacClearMenubarActive(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); + } + } + } + } + InvalidateMDEFRgns(); + FixMDEF(); +} + +/* + *---------------------------------------------------------------------- + * + * 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. + */ +} + +/* + *---------------------------------------------------------------------- + * + * FixMDEF -- + * + * Loads the MDEF and blasts our routine descriptor into it. + * We have to set up the MDEF. This is pretty slimy. The real MDEF + * resource is 68K code. All this code does is call another procedure. + * When the application in launched, a dummy value for the procedure + * is compiled into the MDEF. We are going to replace that dummy + * value with a routine descriptor. When the routine descriptor + * is invoked, the globals and everything will be setup, and we + * can do what we need. This will not work from 68K or CFM 68k + * currently, so we will conditional compile this until we + * figure it out. + * + * Results: + * None. + * + * Side effects: + * Allcates a hash table. + * + *---------------------------------------------------------------------- + */ + +static void +FixMDEF(void) +{ +#ifdef GENERATINGCFM + Handle MDEFHandle = GetResource('MDEF', 591); + Handle SICNHandle = GetResource('SICN', SICN_RESOURCE_NUMBER); + if ((MDEFHandle != NULL) && (SICNHandle != NULL)) { + MoveHHi(MDEFHandle); + HLock(MDEFHandle); + menuDefProc = TkNewMenuDefProc(MenuDefProc); + memmove((void *) (((long) (*MDEFHandle)) + 0x24), &menuDefProc, 4); + } +#endif +} + +/* + *---------------------------------------------------------------------- + * + * TkpMenuInit -- + * + * Initializes Mac-specific menu data. + * + * Results: + * None. + * + * Side effects: + * Allcates a hash table. + * + *---------------------------------------------------------------------- + */ + +void +TkpMenuInit(void) +{ + lastMenuID = 256; + Tcl_InitHashTable(&commandTable, TCL_ONE_WORD_KEYS); + currentMenuBarOwner = NULL; + tearoffStruct.menuPtr = NULL; + currentAppleMenuID = 0; + currentHelpMenuID = 0; + currentMenuBarInterp = NULL; + currentMenuBarName = NULL; + windowListPtr = NULL; +} diff --git a/mac/tkMacMenu.r b/mac/tkMacMenu.r new file mode 100644 index 0000000..9952cea --- /dev/null +++ b/mac/tkMacMenu.r @@ -0,0 +1,47 @@ +/* + * tkMacMenu.r -- + * + * Resources needed by menus. + * + * This file also contains the icons 'SICN' used by the menu code + * in menu items. + * + * Copyright (c) 1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacMenu.r 1.1 97/07/11 18:06:27 + */ + +#include <Types.r> + +/* + * Icons used in menu items. + */ + +resource 'SICN' (128, preload) { + { /* array: 7 elements */ + /* [1] */ + $"0000 0000 8000 C000 E000 F000 F800 FC00" + $"F800 F000 E000 C000 80", + /* [2] */ + $"0000 0000 0000 0800 1400 2200 4100 8080" + $"E380 2200 2200 2200 3E", + /* [3] */ + $"0000 0000 0000 0000 0000 F8F0 C4F0 F270" + $"0900 0480 0270 0130 00F0", + /* [4] */ + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 E4E0 CE60 1B00 3180", + /* [5] */ + $"0000 0000 0000 0000 6300 9480 9480 7F00" + $"1400 7F00 9480 9480 63", + /* [6] */ + $"0000 0000 0000 0000 0000 3FF8 1FF0 0FE0" + $"07C0 0380 01", + /* [7] */ + $"0000 0000 0000 0000 0000 0100 0380 07C0" + $"0FE0 1FF0 3FF8" + } +}; diff --git a/mac/tkMacMenubutton.c b/mac/tkMacMenubutton.c new file mode 100644 index 0000000..42b8d2b --- /dev/null +++ b/mac/tkMacMenubutton.c @@ -0,0 +1,339 @@ +/* + * tkMacMenubutton.c -- + * + * This file implements the Macintosh specific portion of the + * menubutton widget. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacMenubutton.c 1.4 97/01/03 13:55:19 + */ + +#include "tkMenubutton.h" +#include "tkMacInt.h" +#include <Controls.h> + +#define kShadowOffset (3) /* amount to offset shadow from frame */ +#define kTriangleWidth (11) /* width of the triangle */ +#define kTriangleHeight (6) /* height of the triangle */ +#define kTriangleMargin (5) /* margin around triangle */ + +/* + * Declaration of Unix specific button structure. + */ + +typedef struct MacMenuButton { + TkMenuButton info; /* Generic button info. */ +} MacMenuButton; + +/* + * The structure below defines menubutton class behavior by means of + * procedures that can be invoked from generic window code. + */ + +TkClassProcs tkpMenubuttonClass = { + NULL, /* createProc. */ + TkMenuButtonWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + +/* + *---------------------------------------------------------------------- + * + * TkpCreateMenuButton -- + * + * Allocate a new TkMenuButton structure. + * + * Results: + * Returns a newly allocated TkMenuButton structure. + * + * Side effects: + * Registers an event handler for the widget. + * + *---------------------------------------------------------------------- + */ + +TkMenuButton * +TkpCreateMenuButton( + Tk_Window tkwin) +{ + MacMenuButton *butPtr = (MacMenuButton *)ckalloc(sizeof(MacMenuButton)); + + return (TkMenuButton *) butPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpDisplayMenuButton -- + * + * This procedure is invoked to display a menubutton widget. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menubutton in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +void +TkpDisplayMenuButton( + ClientData clientData) /* Information about widget. */ +{ + TkMenuButton *mbPtr = (TkMenuButton *) clientData; + GC gc; + Tk_3DBorder border; + int x = 0; /* Initialization needed only to stop + * compiler warning. */ + int y; + Tk_Window tkwin = mbPtr->tkwin; + int width, height; + MacMenuButton * macMBPtr = (MacMenuButton *) mbPtr; + GWorldPtr destPort; + CGrafPtr saveWorld; + GDHandle saveDevice; + MacDrawable *macDraw; + + mbPtr->flags &= ~REDRAW_PENDING; + if ((mbPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + return; + } + + GetGWorld(&saveWorld, &saveDevice); + destPort = TkMacGetDrawablePort(Tk_WindowId(tkwin)); + SetGWorld(destPort, NULL); + macDraw = (MacDrawable *) Tk_WindowId(tkwin); + + if ((mbPtr->state == tkDisabledUid) && (mbPtr->disabledFg != NULL)) { + gc = mbPtr->disabledGC; + } else if ((mbPtr->state == tkActiveUid) && !Tk_StrictMotif(mbPtr->tkwin)) { + gc = mbPtr->activeTextGC; + } else { + gc = mbPtr->normalTextGC; + } + border = mbPtr->normalBorder; + + /* + * In order to avoid screen flashes, this procedure redraws + * the menu button in a pixmap, then copies the pixmap to the + * screen in a single operation. This means that there's no + * point in time where the on-sreen image has been cleared. + */ + + Tk_Fill3DRectangle(tkwin, Tk_WindowId(tkwin), border, 0, 0, + Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); + + /* + * Display image or bitmap or text for button. + */ + + if (mbPtr->image != None) { + Tk_SizeOfImage(mbPtr->image, &width, &height); + + imageOrBitmap: + TkComputeAnchor(mbPtr->anchor, tkwin, 0, 0, + width + mbPtr->indicatorWidth, height, &x, &y); + if (mbPtr->image != NULL) { + Tk_RedrawImage(mbPtr->image, 0, 0, width, height, + Tk_WindowId(tkwin), x, y); + } else { + XCopyPlane(mbPtr->display, mbPtr->bitmap, Tk_WindowId(tkwin), + gc, 0, 0, (unsigned) width, (unsigned) height, x, y, 1); + } + } else if (mbPtr->bitmap != None) { + Tk_SizeOfBitmap(mbPtr->display, mbPtr->bitmap, &width, &height); + goto imageOrBitmap; + } else { + TkComputeAnchor(mbPtr->anchor, tkwin, mbPtr->padX, mbPtr->padY, + mbPtr->textWidth + mbPtr->indicatorWidth, mbPtr->textHeight, + &x, &y); + Tk_DrawTextLayout(mbPtr->display, Tk_WindowId(tkwin), gc, + mbPtr->textLayout, x, y, 0, -1); + } + + /* + * If the menu button is disabled with a stipple rather than a special + * foreground color, generate the stippled effect. + */ + + if ((mbPtr->state == tkDisabledUid) + && ((mbPtr->disabledFg == NULL) || (mbPtr->image != NULL))) { + XFillRectangle(mbPtr->display, Tk_WindowId(tkwin), mbPtr->disabledGC, + mbPtr->inset, mbPtr->inset, + (unsigned) (Tk_Width(tkwin) - 2*mbPtr->inset), + (unsigned) (Tk_Height(tkwin) - 2*mbPtr->inset)); + } + + /* + * Draw the cascade indicator for the menu button on the + * right side of the window, if desired. + */ + + if (mbPtr->indicatorOn) { + int w, h, i; + Rect r; + + r.left = macDraw->xOff + Tk_Width(tkwin) - mbPtr->inset + - mbPtr->indicatorWidth; + r.top = macDraw->yOff + Tk_Height(tkwin)/2 + - mbPtr->indicatorHeight/2; + r.right = macDraw->xOff + Tk_Width(tkwin) - mbPtr->inset + - kTriangleMargin; + r.bottom = macDraw->yOff + Tk_Height(tkwin)/2 + + mbPtr->indicatorHeight/2; + + h = mbPtr->indicatorHeight; + w = mbPtr->indicatorWidth - 1 - kTriangleMargin; + for (i = 0; i < h; i++) { + MoveTo(r.left + i, r.top + i); + LineTo(r.left + i + w, r.top + i); + w -= 2; + } + } + + /* + * Draw the border and traversal highlight last. This way, if the + * menu button's contents overflow onto the border they'll be covered + * up by the border. + */ + + TkMacSetUpClippingRgn(Tk_WindowId(tkwin)); + if (mbPtr->borderWidth > 0) { + Rect r; + + r.left = macDraw->xOff + mbPtr->highlightWidth + mbPtr->borderWidth; + r.top = macDraw->yOff + mbPtr->highlightWidth + mbPtr->borderWidth; + r.right = macDraw->xOff + Tk_Width(tkwin) - mbPtr->highlightWidth + - mbPtr->borderWidth; + r.bottom = macDraw->yOff + Tk_Height(tkwin) - mbPtr->highlightWidth + - mbPtr->borderWidth; + FrameRect(&r); + + PenSize(mbPtr->borderWidth - 1, mbPtr->borderWidth - 1); + MoveTo(r.right, r.top + kShadowOffset); + LineTo(r.right, r.bottom); + LineTo(r.left + kShadowOffset, r.bottom); + } + + if (mbPtr->state == tkDisabledUid) { + } + + if (mbPtr->highlightWidth != 0) { + GC gc; + + if (mbPtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(mbPtr->highlightColorPtr, Tk_WindowId(tkwin)); + } else { + gc = Tk_GCForColor(mbPtr->highlightBgColorPtr, Tk_WindowId(tkwin)); + } + Tk_DrawFocusHighlight(tkwin, gc, mbPtr->highlightWidth, + Tk_WindowId(tkwin)); + } + + SetGWorld(saveWorld, saveDevice); +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyMenuButton -- + * + * Free data structures associated with the menubutton control. + * + * Results: + * None. + * + * Side effects: + * Restores the default control state. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyMenuButton( + TkMenuButton *mbPtr) +{ +} + +/* + *---------------------------------------------------------------------- + * + * TkpComputeMenuButtonGeometry -- + * + * After changes in a menu button's text or bitmap, this procedure + * recomputes the menu button's geometry and passes this information + * along to the geometry manager for the window. + * + * Results: + * None. + * + * Side effects: + * The menu button's window may change size. + * + *---------------------------------------------------------------------- + */ + +void +TkpComputeMenuButtonGeometry(mbPtr) + register TkMenuButton *mbPtr; /* Widget record for menu button. */ +{ + int width, height, mm, pixels; + + mbPtr->inset = mbPtr->highlightWidth + mbPtr->borderWidth; + if (mbPtr->image != None) { + Tk_SizeOfImage(mbPtr->image, &width, &height); + if (mbPtr->width > 0) { + width = mbPtr->width; + } + if (mbPtr->height > 0) { + height = mbPtr->height; + } + } else if (mbPtr->bitmap != None) { + Tk_SizeOfBitmap(mbPtr->display, mbPtr->bitmap, &width, &height); + if (mbPtr->width > 0) { + width = mbPtr->width; + } + if (mbPtr->height > 0) { + height = mbPtr->height; + } + } else { + Tk_FreeTextLayout(mbPtr->textLayout); + mbPtr->textLayout = Tk_ComputeTextLayout(mbPtr->tkfont, mbPtr->text, + -1, mbPtr->wrapLength, mbPtr->justify, 0, &mbPtr->textWidth, + &mbPtr->textHeight); + width = mbPtr->textWidth; + height = mbPtr->textHeight; + if (mbPtr->width > 0) { + width = mbPtr->width * Tk_TextWidth(mbPtr->tkfont, "0", 1); + } + if (mbPtr->height > 0) { + Tk_FontMetrics fm; + + Tk_GetFontMetrics(mbPtr->tkfont, &fm); + height = mbPtr->height * fm.linespace; + } + width += 2*mbPtr->padX; + height += 2*mbPtr->padY; + } + + if (mbPtr->indicatorOn) { + mm = WidthMMOfScreen(Tk_Screen(mbPtr->tkwin)); + pixels = WidthOfScreen(Tk_Screen(mbPtr->tkwin)); + mbPtr->indicatorHeight= kTriangleHeight; + mbPtr->indicatorWidth = kTriangleWidth + kTriangleMargin; + width += mbPtr->indicatorWidth; + } else { + mbPtr->indicatorHeight = 0; + mbPtr->indicatorWidth = 0; + } + + Tk_GeometryRequest(mbPtr->tkwin, (int) (width + 2*mbPtr->inset), + (int) (height + 2*mbPtr->inset)); + Tk_SetInternalBorder(mbPtr->tkwin, mbPtr->inset); +} diff --git a/mac/tkMacMenus.c b/mac/tkMacMenus.c new file mode 100644 index 0000000..6eaf0ae --- /dev/null +++ b/mac/tkMacMenus.c @@ -0,0 +1,346 @@ +/* + * tkMacMenus.c -- + * + * These calls set up and manage the menubar for the + * Macintosh version of Tk. + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacMenus.c 1.38 97/10/31 17:37:03 + */ + +#include "tcl.h" +#include "tclMacInt.h" +#include "tk.h" +#include "tkInt.h" +#include "tkMacInt.h" + +/* + * The define Status defined by Xlib.h conflicts with the function Status + * defined by Devices.h. We undefine it here to compile. + */ +#undef Status +#include <Devices.h> +#include <Menus.h> +#include <Memory.h> +#include <SegLoad.h> +#include <StandardFile.h> +#include <ToolUtils.h> +#include <Balloons.h> + +#define kAppleMenu 256 +#define kAppleAboutItem 1 +#define kFileMenu 2 +#define kEditMenu 3 + +#define kSourceItem 1 +#define kCloseItem 2 +#define kQuitItem 4 + +#define EDIT_CUT 1 +#define EDIT_COPY 2 +#define EDIT_PASTE 3 +#define EDIT_CLEAR 4 + +MenuHandle tkAppleMenu; +MenuHandle tkFileMenu; +MenuHandle tkEditMenu; + +static Tcl_Interp * gInterp; /* Interpreter for this application. */ + +static void GenerateEditEvent _ANSI_ARGS_((int flag)); +static void SourceDialog _ANSI_ARGS_((void)); + +/* + *---------------------------------------------------------------------- + * + * TkMacHandleMenuSelect -- + * + * Handles events that occur in the Menu bar. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkMacHandleMenuSelect( + long mResult, + int optionKeyPressed) +{ + short theItem = LoWord(mResult); + short theMenu = HiWord(mResult); + Str255 name; + Tk_Window tkwin; + Window window; + + if (mResult == 0) { + TkMacHandleTearoffMenu(); + TkMacClearMenubarActive(); + return; + } + + switch (theMenu) { + + case kAppleMenu: + switch (theItem) { + case kAppleAboutItem: + { + Tcl_CmdInfo dummy; + + if (optionKeyPressed || gInterp == NULL || + Tcl_GetCommandInfo(gInterp, + "tkAboutDialog", &dummy) == 0) { + TkAboutDlg(); + } else { + Tcl_Eval(gInterp, "tkAboutDialog"); + } + break; + } + default: + GetItem(tkAppleMenu, theItem, name); + HiliteMenu(0); + OpenDeskAcc(name); + return; + } + break; + case kFileMenu: + switch (theItem) { + case kSourceItem: + /* TODO: source script */ + SourceDialog(); + break; + case kCloseItem: + /* Send close event */ + window = TkMacGetXWindow(FrontWindow()); + tkwin = Tk_IdToWindow(tkDisplayList->display, window); + TkGenWMDestroyEvent(tkwin); + break; + case kQuitItem: + /* Exit */ + if (optionKeyPressed || gInterp == NULL) { + Tcl_Exit(0); + } else { + Tcl_Eval(gInterp, "exit"); + } + break; + } + break; + case kEditMenu: + /* + * This implementation just send keysyms + * the Tk thinks are associated with function keys that + * do Cut, Copy & Paste on a Sun keyboard. + */ + GenerateEditEvent(theItem); + break; + default: + TkMacDispatchMenuEvent(theMenu, theItem); + TkMacClearMenubarActive(); + break; + } + + /* + * Finally we unhighlight the menu. + */ + HiliteMenu(0); +} /* TkMacHandleMenuSelect */ + +/* + *---------------------------------------------------------------------- + * + * TkMacInitMenus -- + * + * This procedure initializes the Macintosh menu bar. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkMacInitMenus( + Tcl_Interp *interp) +{ + gInterp = interp; + + /* + * At this point, InitMenus() should have already been called. + */ + + if (TkMacUseMenuID(256) != TCL_OK) { + panic("Menu ID 256 is already in use!"); + } + tkAppleMenu = NewMenu(256, "\p\024"); + if (tkAppleMenu == NULL) { + panic("memory - menus"); + } + InsertMenu(tkAppleMenu, 0); + AppendMenu(tkAppleMenu, "\pAbout Tcl & TkÉ"); + AppendMenu(tkAppleMenu, "\p(-"); + AddResMenu(tkAppleMenu, 'DRVR'); + + if (TkMacUseMenuID(kFileMenu) != TCL_OK) { + panic("Menu ID %d is already in use!", kFileMenu); + } + tkFileMenu = NewMenu(kFileMenu, "\pFile"); + if (tkFileMenu == NULL) { + panic("memory - menus"); + } + InsertMenu(tkFileMenu, 0); + AppendMenu(tkFileMenu, "\pSourceÉ"); + AppendMenu(tkFileMenu, "\pClose/W"); + AppendMenu(tkFileMenu, "\p(-"); + AppendMenu(tkFileMenu, "\pQuit/Q"); + + if (TkMacUseMenuID(kEditMenu) != TCL_OK) { + panic("Menu ID %d is already in use!", kEditMenu); + } + tkEditMenu = NewMenu(kEditMenu, "\pEdit"); + if (tkEditMenu == NULL) { + panic("memory - menus"); + } + InsertMenu(tkEditMenu, 0); + AppendMenu(tkEditMenu, "\pCut/X"); + AppendMenu(tkEditMenu, "\pCopy/C"); + AppendMenu(tkEditMenu, "\pPaste/V"); + AppendMenu(tkEditMenu, "\pClear"); + if (TkMacUseMenuID(kHMHelpMenuID) != TCL_OK) { + panic("Help menu ID %s is already in use!", kHMHelpMenuID); + } + + DrawMenuBar(); + TkMacSetHelpMenuItemCount(); + + return; +} + +/* + *---------------------------------------------------------------------- + * + * GenerateEditEvent -- + * + * Takes an edit menu item and posts the corasponding a virtual + * event to Tk's event queue. + * + * Results: + * None. + * + * Side effects: + * May place events of queue. + * + *---------------------------------------------------------------------- + */ + +static void +GenerateEditEvent( + int flag) +{ + XVirtualEvent event; + Point where; + Tk_Window tkwin; + Window window; + + window = TkMacGetXWindow(FrontWindow()); + tkwin = Tk_IdToWindow(tkDisplayList->display, window); + tkwin = (Tk_Window) ((TkWindow *) tkwin)->dispPtr->focusPtr; + if (tkwin == NULL) { + return; + } + + event.type = VirtualEvent; + event.serial = Tk_Display(tkwin)->request; + event.send_event = false; + event.display = Tk_Display(tkwin); + event.event = Tk_WindowId(tkwin); + event.root = XRootWindow(Tk_Display(tkwin), 0); + event.subwindow = None; + event.time = TkpGetMS(); + + GetMouse(&where); + tkwin = Tk_TopCoordsToWindow(tkwin, where.h, where.v, + &event.x, &event.y); + LocalToGlobal(&where); + event.x_root = where.h; + event.y_root = where.v; + event.state = TkMacButtonKeyState(); + event.same_screen = true; + + switch (flag) { + case EDIT_CUT: + event.name = Tk_GetUid("Cut"); + break; + + case EDIT_COPY: + event.name = Tk_GetUid("Copy"); + break; + + case EDIT_PASTE: + event.name = Tk_GetUid("Paste"); + break; + + case EDIT_CLEAR: + event.name = Tk_GetUid("Clear"); + break; + } + Tk_QueueWindowEvent((XEvent *) &event, TCL_QUEUE_TAIL); +} + +/* + *---------------------------------------------------------------------- + * + * SourceDialog -- + * + * Presents a dialog to the user for selecting a Tcl file. The + * selected file will be sourced into the main interpreter. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +SourceDialog() +{ + StandardFileReply reply; + OSType fileTypes[1]; + OSErr err; + int length, result; + Handle path; + + if (gInterp == NULL) { + return; + } + + fileTypes[0] = 'TEXT'; + StandardGetFile(NULL, 1, fileTypes, &reply); + if (reply.sfGood == false) { + return; + } + + err = FSpPathFromLocation(&reply.sfFile, &length, &path); + if (err == noErr) { + HLock(path); + result = Tcl_EvalFile(gInterp, *path); + HUnlock(path); + DisposeHandle(path); + } + if (result == TCL_ERROR) { + Tcl_BackgroundError(gInterp); + } +} diff --git a/mac/tkMacPort.h b/mac/tkMacPort.h new file mode 100644 index 0000000..733e745 --- /dev/null +++ b/mac/tkMacPort.h @@ -0,0 +1,145 @@ +/* + * tkMacPort.h -- + * + * This file is included by all of the Tk C files. It contains + * information that may be configuration-dependent, such as + * #includes for system include files and a few other things. + * + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacPort.h 1.52 97/07/28 11:18:59 + */ + +#ifndef _TKMACPORT +#define _TKMACPORT + +/* + * Macro to use instead of "void" for arguments that must have + * type "void *" in ANSI C; maps them to type "char *" in + * non-ANSI systems. This macro may be used in some of the include + * files below, which is why it is defined here. + */ + +#ifndef VOID +# ifdef __STDC__ +# define VOID void +# else +# define VOID char +# endif +#endif + +#ifndef _TCL +# include <tcl.h> +#endif + +#include <time.h> +#include <stdlib.h> +#include <string.h> +#include "tclMath.h" +#include <ctype.h> +#include <limits.h> + +#include <Xlib.h> +#include <cursorfont.h> +#include <keysym.h> +#include <Xatom.h> +#include <Xfuncproto.h> +#include <Xutil.h> + +/* + * Not all systems declare the errno variable in errno.h. so this + * file does it explicitly. + */ + +extern int errno; + +/* + * Define "NBBY" (number of bits per byte) if it's not already defined. + */ + +#ifndef NBBY +# define NBBY 8 +#endif + +/* + * Declarations for various library procedures that may not be declared + * in any other header file. + */ + +extern void panic _ANSI_ARGS_(TCL_VARARGS(char *, string)); +extern int strcasecmp _ANSI_ARGS_((CONST char *s1, + CONST char *s2)); +extern int strncasecmp _ANSI_ARGS_((CONST char *s1, + CONST char *s2, size_t n)); + +/* + * Defines for X functions that are used by Tk but are treated as + * no-op functions on the Macintosh. + */ + +#define XFlush(display) +#define XFree(data) {if ((data) != NULL) ckfree((char *) (data));} +#define XGrabServer(display) +#define XNoOp(display) {display->request++;} +#define XUngrabServer(display) +#define XSynchronize(display, bool) {display->request++;} +#define XSync(display, bool) {display->request++;} +#define XVisualIDFromVisual(visual) (visual->visualid) + +/* + * The following functions are not used on the Mac, so we stub it out. + */ + +#define TkFreeWindowId(dispPtr,w) +#define TkInitXId(dispPtr) +#define TkpCmapStressed(tkwin,colormap) (0) +#define TkpFreeColor(tkColPtr) +#define TkSetPixmapColormap(p,c) {} +#define Tk_FreeXId(display,xid) +#define TkpSync(display) + +/* + * The following macro returns the pixel value that corresponds to the + * RGB values in the given XColor structure. + */ + +#define PIXEL_MAGIC ((unsigned char) 0x69) +#define TkpGetPixel(p) ((((((PIXEL_MAGIC << 8) \ + | (((p)->red >> 8) & 0xff)) << 8) \ + | (((p)->green >> 8) & 0xff)) << 8) \ + | (((p)->blue >> 8) & 0xff)) + +/* + * This macro stores a representation of the window handle in a string. + */ + +#define TkpPrintWindowId(buf,w) \ + sprintf((buf), "0x%x", (unsigned int) (w)) + +/* + * TkpScanWindowId is just an alias for Tcl_GetInt on Unix. + */ + +#define TkpScanWindowId(i,s,wp) \ + Tcl_GetInt((i),(s),(wp)) + +/* + * Magic pixel values for dynamic (or active) colors. + */ + +#define HIGHLIGHT_PIXEL 31 +#define HIGHLIGHT_TEXT_PIXEL 33 +#define CONTROL_TEXT_PIXEL 35 +#define CONTROL_BODY_PIXEL 37 +#define CONTROL_FRAME_PIXEL 39 +#define WINDOW_BODY_PIXEL 41 +#define MENU_ACTIVE_PIXEL 43 +#define MENU_ACTIVE_TEXT_PIXEL 45 +#define MENU_BACKGROUND_PIXEL 47 +#define MENU_DISABLED_PIXEL 49 +#define MENU_TEXT_PIXEL 51 + +#endif /* _TKMACPORT */ diff --git a/mac/tkMacProlog.c b/mac/tkMacProlog.c new file mode 100644 index 0000000..21cf67c --- /dev/null +++ b/mac/tkMacProlog.c @@ -0,0 +1,61 @@ +/* + * tkMacProlog.c -- + * + * Implements a method on the Macintosh to get the prolog + * from the resource fork of our application (or the shared + * library). + * + * Copyright (c) 1996-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacProlog.c 1.6 97/05/21 10:01:07 + */ + +#include "tkInt.h" +#include "tclMacInt.h" +#include <Resources.h> + +/* + *-------------------------------------------------------------- + * + * TkGetNativeProlog -- + * + * Locate and load the postscript prolog from the resource + * fork of the application. If it can't be found then we + * will try looking for the file in the system folder. + * + * Results: + * A standard Tcl Result. If everything is OK the prolog + * will be located in the result string of the interpreter. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkGetNativeProlog( + Tcl_Interp *interp) /* Places the prolog in the result. */ +{ + Handle resource; + char *stringPtr; + int releaseIt; + + + resource = Tcl_MacFindResource(interp, 'TEXT', "prolog", -1, + NULL, &releaseIt); + + if (resource != NULL) { + stringPtr = Tcl_MacConvertTextResource(resource); + Tcl_SetResult(interp, stringPtr, TCL_DYNAMIC); + if (releaseIt) { + ReleaseResource(resource); + } + return TCL_OK; + } else { + return TkGetProlog(interp); + } +} diff --git a/mac/tkMacRegion.c b/mac/tkMacRegion.c new file mode 100644 index 0000000..534624c --- /dev/null +++ b/mac/tkMacRegion.c @@ -0,0 +1,217 @@ +/* + * tkMacRegion.c -- + * + * Implements X window calls for manipulating regions + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacRegion.c 1.9 96/12/03 11:46:50 + */ + +#include "tkInt.h" +#include "X.h" +#include "Xlib.h" + +#include <Windows.h> +#include <QDOffscreen.h> + +/* + * Temporary region that can be reused. + */ +static RgnHandle tmpRgn = NULL; + + +/* + *---------------------------------------------------------------------- + * + * TkCreateRegion -- + * + * Implements the equivelent of the X window function + * XCreateRegion. See X window documentation for more details. + * + * Results: + * Returns an allocated region handle. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkRegion +TkCreateRegion() +{ + RgnHandle rgn; + + rgn = NewRgn(); + return (TkRegion) rgn; +} + +/* + *---------------------------------------------------------------------- + * + * TkDestroyRegion -- + * + * Implements the equivelent of the X window function + * XDestroyRegion. See X window documentation for more details. + * + * Results: + * None. + * + * Side effects: + * Memory is freed. + * + *---------------------------------------------------------------------- + */ + +void +TkDestroyRegion( + TkRegion r) +{ + RgnHandle rgn = (RgnHandle) r; + + DisposeRgn(rgn); +} + +/* + *---------------------------------------------------------------------- + * + * TkIntersectRegion -- + * + * Implements the equivilent of the X window function + * XIntersectRegion. See X window documentation for more details. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkIntersectRegion( + TkRegion sra, + TkRegion srb, + TkRegion dr_return) +{ + RgnHandle srcRgnA = (RgnHandle) sra; + RgnHandle srcRgnB = (RgnHandle) srb; + RgnHandle destRgn = (RgnHandle) dr_return; + + SectRgn(srcRgnA, srcRgnB, destRgn); +} + +/* + *---------------------------------------------------------------------- + * + * TkUnionRectWithRegion -- + * + * Implements the equivelent of the X window function + * XUnionRectWithRegion. See X window documentation for more + * details. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkUnionRectWithRegion( + XRectangle* rectangle, + TkRegion src_region, + TkRegion dest_region_return) +{ + RgnHandle srcRgn = (RgnHandle) src_region; + RgnHandle destRgn = (RgnHandle) dest_region_return; + + if (tmpRgn == NULL) { + tmpRgn = NewRgn(); + } + SetRectRgn(tmpRgn, rectangle->x, rectangle->y, + rectangle->x + rectangle->width, rectangle->y + rectangle->height); + UnionRgn(srcRgn, tmpRgn, destRgn); +} + +/* + *---------------------------------------------------------------------- + * + * TkRectInRegion -- + * + * Implements the equivelent of the X window function + * XRectInRegion. See X window documentation for more details. + * + * Results: + * Returns one of: RectangleOut, RectangleIn, RectanglePart. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkRectInRegion( + TkRegion region, + int x, + int y, + unsigned int width, + unsigned int height) +{ + RgnHandle rgn = (RgnHandle) region; + RgnHandle rectRgn, destRgn; + int result; + + rectRgn = NewRgn(); + destRgn = NewRgn(); + SetRectRgn(rectRgn, x, y, x + width, y + height); + SectRgn(rgn, rectRgn, destRgn); + if (EmptyRgn(destRgn)) { + result = RectangleOut; + } else if (EqualRgn(rgn, destRgn)) { + result = RectangleIn; + } else { + result = RectanglePart; + } + DisposeRgn(rectRgn); + DisposeRgn(destRgn); + return result; +} + +/* + *---------------------------------------------------------------------- + * + * TkClipBox -- + * + * Implements the equivelent of the X window function XClipBox. + * See X window documentation for more details. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkClipBox( + TkRegion r, + XRectangle* rect_return) +{ + RgnHandle rgn = (RgnHandle) r; + + rect_return->x = (**rgn).rgnBBox.left; + rect_return->y = (**rgn).rgnBBox.top; + rect_return->width = (**rgn).rgnBBox.right - (**rgn).rgnBBox.left; + rect_return->height = (**rgn).rgnBBox.bottom - (**rgn).rgnBBox.top; +} diff --git a/mac/tkMacResource.r b/mac/tkMacResource.r new file mode 100644 index 0000000..23a2000 --- /dev/null +++ b/mac/tkMacResource.r @@ -0,0 +1,507 @@ +/* + * tkMacResources.r -- + * + * This file creates resources for use in a simple shell. + * This is designed to be an example of using the Tcl/Tk + * libraries in a Macintosh Application. + * + * Copyright (c) 1993-1994 Lockheed Missle & Space Company, AI Center + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacResource.r 1.35 97/11/03 17:16:34 + */ + +/* + * We define SystemSevenOrLater so that our dialogs may use the + * auto center feature. + */ +#define SystemSevenOrLater 1 + +#include <Types.r> +#include <SysTypes.r> + +/* + * The folowing include and defines help construct + * the version string for Tcl. + */ + +#define RESOURCE_INCLUDED +#include "tcl.h" +#include "tk.h" + +#if (TK_RELEASE_LEVEL == 0) +# define RELEASE_LEVEL alpha +#elif (TK_RELEASE_LEVEL == 1) +# define RELEASE_LEVEL beta +#elif (TK_RELEASE_LEVEL == 2) +# define RELEASE_LEVEL final +#endif + +#if (TK_RELEASE_LEVEL == 2) +# define MINOR_VERSION (TK_MINOR_VERSION * 16) + TK_RELEASE_SERIAL +#else +# define MINOR_VERSION TK_MINOR_VERSION * 16 +#endif + +resource 'vers' (1) { + TK_MAJOR_VERSION, MINOR_VERSION, + RELEASE_LEVEL, 0x00, verUS, + TK_PATCH_LEVEL, + TK_PATCH_LEVEL ", by Ray Johnson © 1993-1996" "\n" "Sun Microsystems Labratories" +}; + +resource 'vers' (2) { + TK_MAJOR_VERSION, MINOR_VERSION, + RELEASE_LEVEL, 0x00, verUS, + TK_PATCH_LEVEL, + "Wish " TK_PATCH_LEVEL " © 1993-1996" +}; + + +/* + * The mechanisim below loads Tcl source into the resource fork of the + * application. The example below creates a TEXT resource named + * "Init" from the file "init.tcl". This allows applications to use + * Tcl to define the behavior of the application without having to + * require some predetermined file structure - all needed Tcl "files" + * are located within the application. To source a file for the + * resource fork the source command has been modified to support + * sourcing from resources. In the below case "source -rsrc {Init}" + * will load the TEXT resource named "Init". + */ + +read 'TEXT' (0, "Init", purgeable, preload) + ":::tcl" TCL_VERSION ":library:init.tcl"; +read 'TEXT' (1, "History", purgeable, preload) + ":::tcl" TCL_VERSION ":library:history.tcl"; +read 'TEXT' (2, "Word", purgeable,preload) + ":::tcl" TCL_VERSION ":library:word.tcl"; + +read 'TEXT' (10, "tk", purgeable, preload) "::library:tk.tcl"; +read 'TEXT' (11, "button", purgeable, preload) "::library:button.tcl"; +read 'TEXT' (12, "dialog", purgeable, preload) "::library:dialog.tcl"; +read 'TEXT' (13, "entry", purgeable, preload) "::library:entry.tcl"; +read 'TEXT' (14, "focus", purgeable, preload) "::library:focus.tcl"; +read 'TEXT' (15, "listbox", purgeable, preload) "::library:listbox.tcl"; +read 'TEXT' (16, "menu", purgeable, preload) "::library:menu.tcl"; +read 'TEXT' (17, "optionMenu", purgeable, preload) "::library:optMenu.tcl"; +read 'TEXT' (18, "palette", purgeable, preload) "::library:palette.tcl"; +read 'TEXT' (19, "scale", purgeable, preload) "::library:scale.tcl"; +read 'TEXT' (20, "scrollbar", purgeable, preload) "::library:scrlbar.tcl"; +read 'TEXT' (21, "tearoff", purgeable, preload) "::library:tearoff.tcl"; +read 'TEXT' (22, "text", purgeable, preload) "::library:text.tcl"; +read 'TEXT' (23, "tkerror", purgeable, preload) "::library:bgerror.tcl"; +read 'TEXT' (24, "Console", purgeable, preload) "::library:console.tcl"; +read 'TEXT' (25, "msgbox", purgeable, preload) "::library:msgbox.tcl"; +read 'TEXT' (26, "comdlg", purgeable, preload) "::library:comdlg.tcl"; +read 'TEXT' (27, "prolog", purgeable, preload) "::library:prolog.ps"; + + +/* + * The following resource is used when creating the 'env' variable in + * the Macintosh environment. The creation mechanisim looks for the + * 'STR#' resource named "Tcl Environment Variables" rather than a + * specific resource number. (In other words, feel free to change the + * resource id if it conflicts with your application.) Each string in + * the resource must be of the form "KEYWORD=SOME STRING". See Tcl + * documentation for futher information about the env variable. + */ + +/* A good example of something you may want to set is: + * "TCL_LIBRARY=My disk:etc." + */ + +resource 'STR#' (128, "Tcl Environment Variables") { + { "SCHEDULE_NAME=Agent Controller Schedule", + "SCHEDULE_PATH=Lozoya:System Folder:Tcl Lib:Tcl-Scheduler" + }; +}; + +/* + * The following two resources define the default "About Box" for Mac Tk. + * This dialog appears if the "About Tk..." menu item is selected from + * the Apple menu. This dialog may be overridden by defining a Tcl procedure + * with the name of "tkAboutDialog". If this procedure is defined the + * default dialog will not be shown and the Tcl procedure is expected to + * create and manage an About Dialog box. + */ + +resource 'DLOG' (128, "Default About Box", purgeable) { + {85, 107, 243, 406}, dBoxProc, visible, goAway, 0, + 128, "", centerMainScreen +}; + +resource 'DITL' (128, "About Box", purgeable) { + { + {128, 128, 148, 186}, Button {enabled, "Ok"}, + { 14, 108, 117, 310}, StaticText {disabled, + "Wish - Windowing Shell" "\n" "based on Tcl " + TCL_PATCH_LEVEL " & Tk " TK_PATCH_LEVEL "\n\n" "Ray Johnson" "\n" + "Sun Microsystems Labs" "\n" "ray.johnson@eng.sun.com"}, + { 11, 24, 111, 92}, Picture {enabled, 128} + } +}; + +data 'PICT' (128) { + $"13A4 0000 0000 0064 0044 0011 02FF 0C00" + $"FFFE 0000 0048 0000 0048 0000 0000 0000" + $"0064 0044 0000 0000 0001 000A 0000 0000" + $"0064 0044 0099 8044 0000 0000 0064 0044" + $"0000 0000 0000 0000 0048 0000 0048 0000" + $"0000 0008 0001 0008 0000 0000 0108 00D8" + $"0000 0000 0001 5A5A 8000 00FF 3736 FF00" + $"FF00 FF00 3535 FF00 FF00 CC00 3434 FF00" + $"FF00 9900 3333 FF00 FF00 6600 3736 FF00" + $"FF00 3300 3535 FF00 FF00 0000 3434 FF00" + $"CC00 FF00 3333 FF00 CC00 CC00 3736 FF00" + $"CC00 9900 3535 FF00 CC00 6600 FAFA FF00" + $"CC00 3300 3333 FF00 CC00 0000 3130 FF00" + $"9900 FF00 2F2F FF00 9900 CC00 FAFA FF00" + $"9900 9900 F9F9 FF00 9900 6600 3130 FF00" + $"9900 3300 2F2F FF00 9900 0000 2E2E FF00" + $"6600 FF00 F9F9 FF00 6600 CC00 3130 FF00" + $"6600 9900 2F2F FF00 6600 6600 2E2E FF00" + $"6600 3300 2D2D FF00 6600 0000 3130 FF00" + $"3300 FF00 2F2F FF00 3300 CC00 2E2E FF00" + $"3300 9900 2D2D FF00 3300 6600 3130 FF00" + $"3300 3300 2F2F FF00 3300 0000 2E2E FF00" + $"0000 FF00 2D2D FF00 0000 CC00 3130 FF00" + $"0000 9900 2F2F FF00 0000 6600 2E2E FF00" + $"0000 3300 2DF8 FF00 0000 0000 2B2A CC00" + $"FF00 FF00 2929 CC00 FF00 CC00 2828 CC00" + $"FF00 9900 27F8 CC00 FF00 6600 2B2A CC00" + $"FF00 3300 2929 CC00 FF00 0000 2828 CC00" + $"CC00 FF00 2727 CC00 CC00 CC00 2B2A CC00" + $"CC00 9900 2929 CC00 CC00 6600 2828 CC00" + $"CC00 3300 2727 CC00 CC00 0000 2B2A CC00" + $"9900 FF00 2929 CC00 9900 CC00 2828 CC00" + $"9900 9900 2727 CC00 9900 6600 DBDB CC00" + $"9900 3300 4747 CC00 9900 0000 4646 CC00" + $"6600 FF00 4545 CC00 6600 CC00 DBDB CC00" + $"6600 9900 4747 CC00 6600 6600 4646 CC00" + $"6600 3300 4545 CC00 6600 0000 DBDB CC00" + $"3300 FF00 4747 CC00 3300 CC00 4646 CC00" + $"3300 9900 4545 CC00 3300 6600 DBDB CC00" + $"3300 3300 4141 CC00 3300 0000 4040 CC00" + $"0000 FF00 3F3F CC00 0000 CC00 4342 CC00" + $"0000 9900 4141 CC00 0000 6600 4040 CC00" + $"0000 3300 3F3F CC00 0000 0000 4342 9900" + $"FF00 FF00 4141 9900 FF00 CC00 4040 9900" + $"FF00 9900 3F3F 9900 FF00 6600 4342 9900" + $"FF00 3300 4141 9900 FF00 0000 4040 9900" + $"CC00 FF00 3F3F 9900 CC00 CC00 4342 9900" + $"CC00 9900 4141 9900 CC00 6600 4040 9900" + $"CC00 3300 3F3F 9900 CC00 0000 4342 9900" + $"9900 FF00 4141 9900 9900 CC00 4040 9900" + $"9900 9900 3F3F 9900 9900 6600 3D3C 9900" + $"9900 3300 3B3B 9900 9900 0000 3A3A 9900" + $"6600 FF00 3939 9900 6600 CC00 3D3C 9900" + $"6600 9900 3B3B 9900 6600 6600 3A3A 9900" + $"6600 3300 3939 9900 6600 0000 3D3C 9900" + $"3300 FF00 3B3B 9900 3300 CC00 3A3A 9900" + $"3300 9900 3939 9900 3300 6600 3D3C 9900" + $"3300 3300 3B3B 9900 3300 0000 3A3A 9900" + $"0000 FF00 3939 9900 0000 CC00 3D3C 9900" + $"0000 9900 3B3B 9900 0000 6600 3A3A 9900" + $"0000 3300 3939 9900 0000 0000 3D3C 6600" + $"FF00 FF00 3B3B 6600 FF00 CC00 3A3A 6600" + $"FF00 9900 3939 6600 FF00 6600 3D3C 6600" + $"FF00 3300 3B3B 6600 FF00 0000 3A3A 6600" + $"CC00 FF00 3939 6600 CC00 CC00 3736 6600" + $"CC00 9900 3535 6600 CC00 6600 3434 6600" + $"CC00 3300 3333 6600 CC00 0000 3736 6600" + $"9900 FF00 3535 6600 9900 CC00 3434 6600" + $"9900 9900 3333 6600 9900 6600 3736 6600" + $"9900 3300 3535 6600 9900 0000 3434 6600" + $"6600 FF00 3333 6600 6600 CC00 3736 6600" + $"6600 9900 3535 6600 6600 6600 3434 6600" + $"6600 3300 3333 6600 6600 0000 3736 6600" + $"3300 FF00 3535 6600 3300 CC00 3434 6600" + $"3300 9900 3333 6600 3300 6600 3736 6600" + $"3300 3300 3535 6600 3300 0000 3434 6600" + $"0000 FF00 3333 6600 0000 CC00 3130 6600" + $"0000 9900 2F2F 6600 0000 6600 2E2E 6600" + $"0000 3300 F9F9 6600 0000 0000 3130 3300" + $"FF00 FF00 2F2F 3300 FF00 CC00 2E2E 3300" + $"FF00 9900 F9F9 3300 FF00 6600 3130 3300" + $"FF00 3300 2F2F 3300 FF00 0000 2E2E 3300" + $"CC00 FF00 2D2D 3300 CC00 CC00 3130 3300" + $"CC00 9900 2F2F 3300 CC00 6600 2E2E 3300" + $"CC00 3300 2D2D 3300 CC00 0000 3130 3300" + $"9900 FF00 2F2F 3300 9900 CC00 2E2E 3300" + $"9900 9900 2D2D 3300 9900 6600 3130 3300" + $"9900 3300 2F2F 3300 9900 0000 2E2E 3300" + $"6600 FF00 2DF8 3300 6600 CC00 2B2A 3300" + $"6600 9900 2929 3300 6600 6600 2828 3300" + $"6600 3300 27F8 3300 6600 0000 2B2A 3300" + $"3300 FF00 2929 3300 3300 CC00 2828 3300" + $"3300 9900 2727 3300 3300 6600 2B2A 3300" + $"3300 3300 2929 3300 3300 0000 2828 3300" + $"0000 FF00 2727 3300 0000 CC00 2B2A 3300" + $"0000 9900 2929 3300 0000 6600 2828 3300" + $"0000 3300 2727 3300 0000 0000 4948 0000" + $"FF00 FF00 4747 0000 FF00 CC00 4646 0000" + $"FF00 9900 4545 0000 FF00 6600 4948 0000" + $"FF00 3300 4747 0000 FF00 0000 4646 0000" + $"CC00 FF00 4545 0000 CC00 CC00 4948 0000" + $"CC00 9900 4747 0000 CC00 6600 4646 0000" + $"CC00 3300 4545 0000 CC00 0000 4342 0000" + $"9900 FF00 4141 0000 9900 CC00 4040 0000" + $"9900 9900 3F3F 0000 9900 6600 4342 0000" + $"9900 3300 4141 0000 9900 0000 4040 0000" + $"6600 FF00 3F3F 0000 6600 CC00 4342 0000" + $"6600 9900 4141 0000 6600 6600 4040 0000" + $"6600 3300 3F3F 0000 6600 0000 4342 0000" + $"3300 FF00 4141 0000 3300 CC00 4040 0000" + $"3300 9900 3F3F 0000 3300 6600 4342 0000" + $"3300 3300 4141 0000 3300 0000 4040 0000" + $"0000 FF00 3F3F 0000 0000 CC00 4342 0000" + $"0000 9900 4141 0000 0000 6600 4040 0000" + $"0000 3300 3F3F EE00 0000 0000 3D3C DD00" + $"0000 0000 3B3B BB00 0000 0000 3A3A AA00" + $"0000 0000 3939 8800 0000 0000 3D3C 7700" + $"0000 0000 3B3B 5500 0000 0000 3A3A 4400" + $"0000 0000 3939 2200 0000 0000 3D3C 1100" + $"0000 0000 3B3B 0000 EE00 0000 3A3A 0000" + $"DD00 0000 3939 0000 BB00 0000 3D3C 0000" + $"AA00 0000 3B3B 0000 8800 0000 3A3A 0000" + $"7700 0000 3939 0000 5500 0000 3D3C 0000" + $"4400 0000 3B3B 0000 2200 0000 3A3A 0000" + $"1100 0000 3939 0000 0000 EE00 3D3C 0000" + $"0000 DD00 3B3B 0000 0000 BB00 3A3A 0000" + $"0000 AA00 3939 0000 0000 8800 3D3C 0000" + $"0000 7700 3B3B 0000 0000 5500 3A3A 0000" + $"0000 4400 3939 0000 0000 2200 3736 0000" + $"0000 1100 3535 EE00 EE00 EE00 3434 DD00" + $"DD00 DD00 3333 BB00 BB00 BB00 3736 AA00" + $"AA00 AA00 3535 8800 8800 8800 3434 7700" + $"7700 7700 3333 5500 5500 5500 3736 4400" + $"4400 4400 3535 2200 2200 2200 3434 1100" + $"1100 1100 3333 0000 0000 0000 0000 0000" + $"0064 0044 0000 0000 0064 0044 0000 000A" + $"0000 0000 0064 0044 02BD 0013 E800 01F5" + $"F6FE 07FE 0E02 3232 33FD 3900 0EE6 001D" + $"FC00 01F5 F5FE 0700 08FE 0E02 3232 33FE" + $"3900 3AFC 40F2 4102 4033 07E9 0017 0100" + $"0EFC 40DC 4102 390E F5F5 0002 F5F5 F6FE" + $"0702 0E07 0016 0100 32D5 4104 4039 0E32" + $"33FD 3900 3AFC 40FC 4101 3200 0801 000E" + $"C141 010E 0008 0100 0EC1 4101 0800 0801" + $"000E C141 0107 0008 0100 0EC1 4101 0700" + $"0901 0007 C241 0240 F500 0E01 0007 E841" + $"0147 47DD 4102 4000 0012 0100 07F0 4100" + $"47FA 4101 3B3B DD41 0240 0000 1901 0007" + $"F141 0C47 3B0B 3B47 4141 4711 0505 3B47" + $"DF41 023A 0000 1701 00F6 F041 010B 0BFE" + $"4105 473B 0505 113B DE41 0239 0000 1A02" + $"00F5 40F3 410C 473B 053B 4741 4741 0B0B" + $"3B47 47DE 4102 3900 0018 0200 F540 F341" + $"0247 110B FE41 0447 1105 4147 DC41 0233" + $"0000 1B02 0000 40F3 4103 4711 1147 FE41" + $"0205 3547 F741 FD47 E941 0232 0000 1E02" + $"0000 40F2 4106 113B 4741 4735 0BF7 4106" + $"4741 390E 0E40 47EA 4102 0E00 0021 0200" + $"0040 F241 0711 3B47 4141 0B35 47F9 4102" + $"4740 07FE 0002 F640 47EB 4102 0E00 0023" + $"0200 0040 F341 0847 3541 4147 3B05 4147" + $"FA41 0947 3AF6 00F5 4F55 F50E 47EB 4102" + $"0700 0022 0200 003A F341 0147 3BFE 4101" + $"0B0B F941 0547 3AF5 0055 C8FE CE01 5640" + $"EB41 0207 0000 1F02 0000 39F0 4104 4741" + $"053B 47FB 4104 4740 F5F5 A4FC CE01 C85D" + $"EB41 02F6 0000 1F02 0000 39F0 4104 473B" + $"0541 47FC 4104 4740 07F6 C8FA CE00 64EC" + $"4103 40F5 0000 1C02 0000 39F0 4102 4711" + $"0BFA 4103 4708 2AC8 FACE 0164 D8EC 4100" + $"40FE 0025 0200 0039 EF41 020B 3B47 FC41" + $"0347 0FF5 A4FB CE02 C887 D8FC 41FE 47FC" + $"4100 47F9 4100 3AFE 0028 0200 0039 EF41" + $"020B 3B47 FD41 0347 3900 A4FA CE00 ABFA" + $"4109 3B11 3B41 4147 3B0B 3B47 FA41 0039" + $"FE00 2402 0000 33F1 4102 4741 0BFA 4101" + $"0779 F9CE 0064 FA41 0235 050B FD41 010B" + $"0BF9 4100 39FE 0028 0200 0032 F141 0247" + $"3B0B FC41 0247 39F6 F9CE 0187 D8FB 4103" + $"4741 050B FE41 0247 110B F941 0039 FE00" + $"2C02 0000 32F1 4102 473B 11FB 4101 0879" + $"FACE 05AA 4041 4147 47FE 410A 4741 0511" + $"4741 4147 3511 47FA 4100 32FE 002F 0200" + $"000E F141 0347 3B11 47FE 4103 4740 F6C8" + $"FACE 0564 D841 4039 39FE 4104 473B 053B" + $"47FE 4102 3541 47FA 4100 0EFE 0027 0200" + $"000E F141 0347 3B3B 47FE 4102 470F 79FA" + $"CE0C 8741 4032 F500 003A 4741 473B 05F2" + $"4100 0EFE 0027 0200 000E F141 0347 3B3B" + $"47FD 4101 0EA4 FACE 01AB AAFE C808 7900" + $"3947 4147 110B 47F3 4100 07FE 001C 0200" + $"000E EA41 0240 2BC8 F5CE 0881 0033 4741" + $"410B 3B47 F341 0007 FE00 1A02 0000 08EB" + $"4102 473A 55F4 CE06 5D00 3947 4741 0BF1" + $"4100 F6FE 001C 0200 0007 EB41 0247 3979" + $"F4CE 0739 0039 4747 3511 47F3 4101 40F5" + $"FE00 1C02 0000 07EB 4102 4739 A4F5 CE08" + $"AB0E 0040 4741 1141 47F3 4100 40FD 001B" + $"0200 0007 EB41 0247 39A4 F5CE 0787 0707" + $"4147 4111 47F2 4100 40FD 001B 0200 0007" + $"EB41 0247 39C8 F5CE 0763 F532 4747 3B3B" + $"47F2 4100 3AFD 001A 0300 00F6 40EC 4102" + $"4739 C8F5 CE05 39F5 4047 413B F041 0039" + $"FD00 1C03 0000 F540 EB41 0140 C8FD CE01" + $"C8A4 FCCE 03AB 080E 47ED 4100 39FD 001A" + $"FE00 0040 EB41 0040 FCCE 01A4 C8FC CE03" + $"FA07 4047 ED41 0032 FD00 1AFE 0000 40EA" + $"4100 AAFE CE02 87F9 C8FC CE02 560F 47EC" + $"4100 32FD 0019 FE00 0040 EA41 00AB FECE" + $"0264 56C8 FDCE 01C8 32EA 4100 0EFD 001B" + $"FE00 0040 ED41 030E 4047 87FE CE01 4055" + $"FCCE 01FA 40EA 4100 08FD 001A FE00 003A" + $"ED41 0807 0740 FBCE CEAB 3979 FDCE 00AB" + $"E841 0007 FD00 1CFE 0000 3AED 4108 0700" + $"F6A4 CECE 8733 79FD CE02 4147 47EA 4100" + $"07FD 001E FE00 0039 ED41 0807 2AA4 C8CE" + $"CE88 0E9D FECE 0364 1C39 39EB 4101 40F5" + $"FD00 1CFE 0000 39ED 4101 074F FDCE 0264" + $"F7A4 FECE 03AB 80F6 07EB 4100 40FC 001C" + $"FE00 0039 ED41 0108 79FE CE03 AB40 2BA4" + $"FCCE 02F7 0E47 EC41 0040 FC00 1CFE 0000" + $"39ED 4101 0879 FECE 03AB 40F6 C8FC CE02" + $"F615 47EC 4100 40FC 001E FE00 003A EE41" + $"0247 0E79 FECE 03AB 40F5 C8FD CE03 A4F5" + $"3A47 EC41 0040 FC00 1EFE 0000 3AEE 4102" + $"470E 56FE CE03 FB3A F6C8 FDCE 0280 F540" + $"EB41 0140 F5FD 001E FE00 0040 EE41 0947" + $"0F56 CECE C888 39F6 C8FD CE02 5601 40EB" + $"4101 40F5 FD00 1CFE 0000 40EE 4109 4739" + $"32CE CEC8 8839 2AC8 FDCE 0156 07E9 4100" + $"F6FD 001B FE00 0040 EE41 0847 3A32 CECE" + $"C864 152A FCCE 0132 07E9 4100 07FD 001A" + $"FE00 0040 ED41 0740 32AB CEC8 6439 4EFC" + $"CE01 3A07 E941 0007 FD00 1D03 0000 F540" + $"ED41 0740 0EAB CECE 640F 4EFD CE03 AB40" + $"0840 EA41 0007 FD00 1B03 0000 F540 EC41" + $"060F 81CE CE64 334E FDCE 02AB 400E E941" + $"000E FD00 1C02 0000 F6EC 4107 4715 FACE" + $"CE64 334E FDCE 0387 0F0E 47EA 4100 0EFD" + $"001C 0200 0007 EC41 0747 16F9 CEC8 6433" + $"4EFD CE03 6308 4047 EA41 000E FD00 1A02" + $"0000 07EB 4106 40F9 CEC8 6439 4EFD CE02" + $"3940 47E9 4100 32FD 001B 0200 0007 EA41" + $"0539 CECE 8839 F6FE CE04 AB41 4139 40EA" + $"4100 32FD 001C 0200 0007 EB41 0E47 3AC8" + $"CE88 39F6 C8CE CE64 15F6 F540 EA41 0033" + $"FD00 1A02 0000 07EA 410C 40A4 CE87 392A" + $"C8CE AB41 40F8 F6E9 4100 39FD 001B 0200" + $"000E EB41 0D47 41AB C887 39F5 C8CE ABAB" + $"CEA4 07E9 4100 39FD 001C 0200 000E ED41" + $"0947 3939 4787 C8AB 40F5 C8FD CE01 A40E" + $"E941 0039 FD00 1D02 0000 0EED 4109 473A" + $"0007 80CE AB40 F5C8 FDCE 0255 0E47 EA41" + $"0039 FD00 1B02 0000 0EEB 4107 0779 C8CE" + $"CE40 F6A4 FDCE 022B 3947 EA41 003A FD00" + $"1C02 0000 0EEC 4102 4739 79FE CE02 6407" + $"A4FE CE02 A407 40E9 4100 40FD 001A 0200" + $"0032 EA41 0632 A4CE CE88 0879 FECE 02F9" + $"0F47 E941 0040 FD00 1A02 0000 32EB 4107" + $"4740 F7C8 CE87 0E79 FECE 0132 40E8 4100" + $"40FD 0019 0200 0033 EA41 0B47 40F8 C8AB" + $"0E55 CECE 8015 47E8 4100 40FD 0017 0200" + $"0033 E941 0847 40F9 A439 4FCE CE5D E641" + $"0140 F5FE 0014 0200 0039 E841 0647 64FB" + $"392B C8AB E441 00F6 FE00 1102 0000 39E5" + $"4103 40F6 8764 E441 0007 FE00 1E02 0000" + $"39EB 4102 3A0E 0EFD 4102 0740 47F6 4104" + $"400F 0839 47F4 4100 07FE 0027 0200 0039" + $"FB41 0147 47F2 4102 0800 40FE 4102 0839" + $"47FC 4101 4747 FC41 0339 0039 47F4 4100" + $"07FE 0029 0200 0039 FB41 0140 39F3 4109" + $"470E F540 4141 470E 3347 FC41 0139 3AFD" + $"4104 4739 0039 47F4 4100 08FE 0036 0200" + $"003A FC41 0347 0E00 40FC 4102 4741 40FC" + $"4109 470E F540 4141 4733 0E47 FE41 0447" + $"4000 0E47 FE41 0447 3900 3941 FE40 F741" + $"000E FE00 3A02 0000 3AFD 410E 4740 0700" + $"0E40 4741 4147 390E 390E 40FE 4108 470E" + $"F540 4141 4739 0EFC 4103 0F00 0739 FE41" + $"0747 3900 3940 080F 39F7 4100 0EFE 0035" + $"0200 0040 FB41 020E 0040 FE41 0D47 4000" + $"3941 0032 4741 4147 0EF5 40FE 4101 4008" + $"FC41 023A 000E FD41 0547 3900 3939 33F5" + $"4100 0EFE 0039 0200 0040 FC41 0347 0E00" + $"40FE 4106 4732 0040 4139 40FE 4103 470E" + $"F540 FD41 0108 40FE 4104 4740 000E 47FE" + $"4106 4739 0007 F540 47F6 4100 32FE 003A" + $"0200 0040 FC41 0C47 0E00 4047 4141 470E" + $"0040 4747 FD41 0347 0EF5 40FE 410A 470E" + $"3947 4141 4740 000E 47FE 4107 4739 000E" + $"0007 4147 F741 0032 FE00 3802 0000 40FC" + $"4102 470E 00FD 4106 4739 003A 4740 39FE" + $"4102 470E F5FD 410A 4733 3347 4141 4740" + $"000E 47FE 4106 4739 0039 3900 0EF6 4100" + $"33FE 003A 0200 F540 FC41 0447 3200 0E39" + $"FD41 0B0E 0E40 333A 4741 413A 07F5 39FE" + $"4102 473A 0EFD 410F 40F5 0733 4041 4140" + $"0E00 0E40 0700 0E40 F841 0039 FE00 2902" + $"00F5 40FA 4101 3939 FB41 023A 3A40 FD41" + $"FD40 FD41 0240 0E40 FD41 0240 3940 FD41" + $"FA40 F741 0039 FE00 2A01 00F6 F941 0147" + $"47FB 4101 4747 FB41 0147 47FB 4101 3940" + $"FD41 0147 47FB 4100 47FE 4100 47F6 4100" + $"39FE 000D 0100 07E1 4100 40E4 4100 3AFE" + $"0009 0100 07C3 4100 3AFE 0009 0100 07C3" + $"4100 40FE 0009 0100 07C3 4100 40FE 0009" + $"0100 07C3 4100 40FE 000A 0100 0EC3 4103" + $"40F5 0000 0901 000E C241 02F6 0000 0901" + $"000E C241 0207 0000 0901 000E C241 0207" + $"0000 1101 000E ED41 FE40 003A F940 E241" + $"0207 0000 2B01 0032 F941 FE40 FE39 0632" + $"0E0E 0707 F6F5 F800 02F5 F5F6 FB07 FB0E" + $"0332 3233 33FB 3901 3A3A FB40 0207 0000" + $"0E0A 000E 3939 320E 0E07 07F6 F5C8 0002" + $"BD00 00FF" +}; + +/* + * Here is the custom file open dialog. This dialog is used instead of + * the default file dialog if the -filetypes flag is specified. + */ + +resource 'DLOG' (130, purgeable) { + {0, 0, 195, 344}, dBoxProc, invisible, noGoAway, 0, + 130, "", noAutoCenter +}; + +resource 'DITL' (130, "File Open Box", purgeable) { + { + {135, 252, 155, 332}, Button {enabled, "Open"}, + {104, 252, 124, 332}, Button {enabled, "Cancel"}, + { 0, 0, 0, 0}, HelpItem {disabled, HMScanhdlg {130}}, + { 8, 235, 24, 337}, UserItem {enabled}, + { 32, 252, 52, 332}, Button {enabled, "Eject"}, + { 60, 252, 80, 332}, Button {enabled, "Desktop"}, + { 29, 12, 159, 230}, UserItem {enabled}, + { 6, 12, 25, 230}, UserItem {enabled}, + { 91, 251, 92, 333}, Picture {disabled, 11}, + {168, 20, 187, 300}, Control {enabled, 131} + } +}; + +resource 'CNTL' (131, "File Types menu", purgeable) { + {168, 20, 187, 300}, + popupTitleLeftJust, + visible, + 80, + 132, + popupMenuCDEFProc, + 0, + "File Type:" +}; + + +resource 'MENU' (132, preload) { + 132, + textMenuProc, + 0xFFFF, enabled, "", {} +}; diff --git a/mac/tkMacScale.c b/mac/tkMacScale.c new file mode 100644 index 0000000..292a064 --- /dev/null +++ b/mac/tkMacScale.c @@ -0,0 +1,603 @@ +/* + * tkMacScale.c -- + * + * This file implements the Macintosh specific portion of the + * scale widget. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacScale.c 1.3 96/10/17 13:16:18 + */ + +#include "tkScale.h" +#include "tkInt.h" +#include <Controls.h> +#include "tkMacInt.h" + +/* + * Defines used in this file. + */ +#define slider 1110 +#define inSlider 1 +#define inInc 2 +#define inDecr 3 + +/* + * Declaration of Macintosh specific scale structure. + */ + +typedef struct MacScale { + TkScale info; /* Generic scale info. */ + int flags; /* Flags. */ + ControlRef scaleHandle; /* Handle to the Scale control struct. */ +} MacScale; + +/* + * Globals uses locally in this file. + */ +static ControlActionUPP scaleActionProc = NULL; /* Pointer to func. */ + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void MacScaleEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static pascal void ScaleActionProc _ANSI_ARGS_((ControlRef theControl, + ControlPartCode partCode)); + +/* + *---------------------------------------------------------------------- + * + * TkpCreateScale -- + * + * Allocate a new TkScale structure. + * + * Results: + * Returns a newly allocated TkScale structure. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkScale * +TkpCreateScale(tkwin) + Tk_Window tkwin; +{ + MacScale *macScalePtr;; + + macScalePtr = (MacScale *) ckalloc(sizeof(MacScale)); + macScalePtr->scaleHandle = NULL; + if (scaleActionProc == NULL) { + scaleActionProc = NewControlActionProc(ScaleActionProc); + } + + Tk_CreateEventHandler(tkwin, ButtonPressMask, + MacScaleEventProc, (ClientData) macScalePtr); + + return (TkScale *) macScalePtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyScale -- + * + * Free Macintosh specific resources. + * + * Results: + * None + * + * Side effects: + * The slider control is destroyed. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyScale(scalePtr) + TkScale *scalePtr; +{ + MacScale *macScalePtr = (MacScale *) scalePtr; + + /* + * Free Macintosh control. + */ + if (macScalePtr->scaleHandle != NULL) { + DisposeControl(macScalePtr->scaleHandle); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpDisplayScale -- + * + * This procedure is invoked as an idle handler to redisplay + * the contents of a scale widget. + * + * Results: + * None. + * + * Side effects: + * The scale gets redisplayed. + * + *---------------------------------------------------------------------- + */ + +void +TkpDisplayScale(clientData) + ClientData clientData; /* Widget record for scale. */ +{ + TkScale *scalePtr = (TkScale *) clientData; + Tk_Window tkwin = scalePtr->tkwin; + Tcl_Interp *interp = scalePtr->interp; + int result; + char string[PRINT_CHARS]; + MacScale *macScalePtr = (MacScale *) clientData; + Rect r; + WindowRef windowRef; + GWorldPtr destPort; + CGrafPtr saveWorld; + GDHandle saveDevice; + MacDrawable *macDraw; + + if ((scalePtr->tkwin == NULL) || !Tk_IsMapped(scalePtr->tkwin)) { + goto done; + } + + /* + * Invoke the scale's command if needed. + */ + + Tcl_Preserve((ClientData) scalePtr); + if ((scalePtr->flags & INVOKE_COMMAND) && (scalePtr->command != NULL)) { + Tcl_Preserve((ClientData) interp); + sprintf(string, scalePtr->format, scalePtr->value); + result = Tcl_VarEval(interp, scalePtr->command, " ", string, + (char *) NULL); + if (result != TCL_OK) { + Tcl_AddErrorInfo(interp, "\n (command executed by scale)"); + Tcl_BackgroundError(interp); + } + Tcl_Release((ClientData) interp); + } + scalePtr->flags &= ~INVOKE_COMMAND; + if (scalePtr->tkwin == NULL) { + Tcl_Release((ClientData) scalePtr); + return; + } + Tcl_Release((ClientData) scalePtr); + + /* + * Now handle the part of redisplay that is the same for + * horizontal and vertical scales: border and traversal + * highlight. + */ + + if (scalePtr->highlightWidth != 0) { + GC gc; + + if (scalePtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(scalePtr->highlightColorPtr, Tk_WindowId(tkwin)); + } else { + gc = Tk_GCForColor(scalePtr->highlightBgColorPtr, Tk_WindowId(tkwin)); + } + Tk_DrawFocusHighlight(tkwin, gc, scalePtr->highlightWidth, Tk_WindowId(tkwin)); + } + Tk_Draw3DRectangle(tkwin, Tk_WindowId(tkwin), scalePtr->bgBorder, + scalePtr->highlightWidth, scalePtr->highlightWidth, + Tk_Width(tkwin) - 2*scalePtr->highlightWidth, + Tk_Height(tkwin) - 2*scalePtr->highlightWidth, + scalePtr->borderWidth, scalePtr->relief); + + /* + * Set up port for drawing Macintosh control. + */ + macDraw = (MacDrawable *) Tk_WindowId(tkwin); + destPort = TkMacGetDrawablePort(Tk_WindowId(tkwin)); + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + TkMacSetUpClippingRgn(Tk_WindowId(tkwin)); + + /* + * Create Macintosh control. + */ + if (macScalePtr->scaleHandle == NULL) { + r.left = r.top = 0; + r.right = r.bottom = 1; + /* TODO: initial value. */ + /* 16*slider+4 */ + macScalePtr->scaleHandle = NewControl((WindowRef) destPort, + &r, "\p", false, (short) 35, 0, 1000, + 16*slider, (SInt32) macScalePtr); + + /* + * If we are foremost than make us active. + */ + if ((WindowPtr) destPort == FrontWindow()) { + macScalePtr->flags |= ACTIVE; + } + } + windowRef = (**macScalePtr->scaleHandle).contrlOwner; + + /* + * We can't use the Macintosh commands SizeControl and MoveControl as these + * calls will also cause a redraw which in our case will also cause + * flicker. To avoid this we adjust the control record directly. The + * Draw1Control command appears to just draw where ever the control says to + * draw so this seems right. + * + * NOTE: changing the control record directly may not work when + * Apple releases the Copland version of the MacOS in late 1996. + */ + + (**macScalePtr->scaleHandle).contrlRect.left = macDraw->xOff + scalePtr->inset; + (**macScalePtr->scaleHandle).contrlRect.top = macDraw->yOff + scalePtr->inset; + (**macScalePtr->scaleHandle).contrlRect.right = macDraw->xOff + Tk_Width(tkwin) + - scalePtr->inset; + (**macScalePtr->scaleHandle).contrlRect.bottom = macDraw->yOff + + Tk_Height(tkwin) - scalePtr->inset; + + /* + * Set the thumb and resolution etc. + */ + (**macScalePtr->scaleHandle).contrlMin = (SInt16) scalePtr->toValue; + (**macScalePtr->scaleHandle).contrlMax = (SInt16) scalePtr->fromValue; + (**macScalePtr->scaleHandle).contrlValue = (SInt16) scalePtr->value; + + /* + * Finally draw the control. + */ + (**macScalePtr->scaleHandle).contrlVis = 255; + (**macScalePtr->scaleHandle).contrlHilite = 0; + Draw1Control(macScalePtr->scaleHandle); + + SetGWorld(saveWorld, saveDevice); + + done: + scalePtr->flags &= ~REDRAW_ALL; +} + +/* + *---------------------------------------------------------------------- + * + * TkpScaleElement -- + * + * Determine which part of a scale widget lies under a given + * point. + * + * Results: + * The return value is either TROUGH1, SLIDER, TROUGH2, or + * OTHER, depending on which of the scale's active elements + * (if any) is under the point at (x,y). + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpScaleElement(scalePtr, x, y) + TkScale *scalePtr; /* Widget record for scale. */ + int x, y; /* Coordinates within scalePtr's window. */ +{ + MacScale *macScalePtr = (MacScale *) scalePtr; + ControlPartCode part; + Point where; + Rect bounds; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + + destPort = TkMacGetDrawablePort(Tk_WindowId(scalePtr->tkwin)); + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + + /* + * All of the calculations in this procedure mirror those in + * DisplayScrollbar. Be sure to keep the two consistent. + */ + + TkMacWinBounds((TkWindow *) scalePtr->tkwin, &bounds); + where.h = x + bounds.left; + where.v = y + bounds.top; + part = TestControl(macScalePtr->scaleHandle, where); + + SetGWorld(saveWorld, saveDevice); + + switch (part) { + case inSlider: + return SLIDER; + case inInc: + if (scalePtr->vertical) { + return TROUGH1; + } else { + return TROUGH2; + } + case inDecr: + if (scalePtr->vertical) { + return TROUGH2; + } else { + return TROUGH1; + } + default: + return OTHER; + } +} + +/* + *-------------------------------------------------------------- + * + * TkpSetScaleValue -- + * + * This procedure changes the value of a scale and invokes + * a Tcl command to reflect the current position of a scale + * + * Results: + * None. + * + * Side effects: + * A Tcl command is invoked, and an additional error-processing + * command may also be invoked. The scale's slider is redrawn. + * + *-------------------------------------------------------------- + */ + +void +TkpSetScaleValue(scalePtr, value, setVar, invokeCommand) + register TkScale *scalePtr; /* Info about widget. */ + double value; /* New value for scale. Gets adjusted + * if it's off the scale. */ + int setVar; /* Non-zero means reflect new value through + * to associated variable, if any. */ + int invokeCommand; /* Non-zero means invoked -command option + * to notify of new value, 0 means don't. */ +{ + char string[PRINT_CHARS]; + + value = TkRoundToResolution(scalePtr, value); + if ((value < scalePtr->fromValue) + ^ (scalePtr->toValue < scalePtr->fromValue)) { + value = scalePtr->fromValue; + } + if ((value > scalePtr->toValue) + ^ (scalePtr->toValue < scalePtr->fromValue)) { + value = scalePtr->toValue; + } + if (scalePtr->flags & NEVER_SET) { + scalePtr->flags &= ~NEVER_SET; + } else if (scalePtr->value == value) { + return; + } + scalePtr->value = value; + if (invokeCommand) { + scalePtr->flags |= INVOKE_COMMAND; + } + TkEventuallyRedrawScale(scalePtr, REDRAW_SLIDER); + + if (setVar && (scalePtr->varName != NULL)) { + sprintf(string, scalePtr->format, scalePtr->value); + scalePtr->flags |= SETTING_VAR; + Tcl_SetVar(scalePtr->interp, scalePtr->varName, string, + TCL_GLOBAL_ONLY); + scalePtr->flags &= ~SETTING_VAR; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpPixelToValue -- + * + * Given a pixel within a scale window, return the scale + * reading corresponding to that pixel. + * + * Results: + * A double-precision scale reading. If the value is outside + * the legal range for the scale then it's rounded to the nearest + * end of the scale. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +double +TkpPixelToValue(scalePtr, x, y) + register TkScale *scalePtr; /* Information about widget. */ + int x, y; /* Coordinates of point within + * window. */ +{ + double value, pixelRange; + + if (scalePtr->vertical) { + pixelRange = Tk_Height(scalePtr->tkwin) - scalePtr->sliderLength + - 2*scalePtr->inset - 2*scalePtr->borderWidth; + value = y; + } else { + pixelRange = Tk_Width(scalePtr->tkwin) - scalePtr->sliderLength + - 2*scalePtr->inset - 2*scalePtr->borderWidth; + value = x; + } + + if (pixelRange <= 0) { + /* + * Not enough room for the slider to actually slide: just return + * the scale's current value. + */ + + return scalePtr->value; + } + value -= scalePtr->sliderLength/2 + scalePtr->inset + + scalePtr->borderWidth; + value /= pixelRange; + if (value < 0) { + value = 0; + } + if (value > 1) { + value = 1; + } + value = scalePtr->fromValue + + value * (scalePtr->toValue - scalePtr->fromValue); + return TkRoundToResolution(scalePtr, value); +} + +/* + *---------------------------------------------------------------------- + * + * TkpValueToPixel -- + * + * Given a reading of the scale, return the x-coordinate or + * y-coordinate corresponding to that reading, depending on + * whether the scale is vertical or horizontal, respectively. + * + * Results: + * An integer value giving the pixel location corresponding + * to reading. The value is restricted to lie within the + * defined range for the scale. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpValueToPixel(scalePtr, value) + register TkScale *scalePtr; /* Information about widget. */ + double value; /* Reading of the widget. */ +{ + int y, pixelRange; + double valueRange; + + valueRange = scalePtr->toValue - scalePtr->fromValue; + pixelRange = (scalePtr->vertical ? Tk_Height(scalePtr->tkwin) + : Tk_Width(scalePtr->tkwin)) - scalePtr->sliderLength + - 2*scalePtr->inset - 2*scalePtr->borderWidth; + if (valueRange == 0) { + y = 0; + } else { + y = (int) ((value - scalePtr->fromValue) * pixelRange + / valueRange + 0.5); + if (y < 0) { + y = 0; + } else if (y > pixelRange) { + y = pixelRange; + } + } + y += scalePtr->sliderLength/2 + scalePtr->inset + scalePtr->borderWidth; + return y; +} + +/* + *-------------------------------------------------------------- + * + * MacScaleEventProc -- + * + * This procedure is invoked by the Tk dispatcher for + * ButtonPress events on scales. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +MacScaleEventProc(clientData, eventPtr) + ClientData clientData; /* Information about window. */ + XEvent *eventPtr; /* Information about event. */ +{ + MacScale *macScalePtr = (MacScale *) clientData; + Point where; + Rect bounds; + int part, x, y, dummy; + unsigned int state; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + Window dummyWin; + + /* + * To call Macintosh control routines we must have the port + * set to the window containing the control. We will then test + * which part of the control was hit and act accordingly. + */ + destPort = TkMacGetDrawablePort(Tk_WindowId(macScalePtr->info.tkwin)); + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + TkMacSetUpClippingRgn(Tk_WindowId(macScalePtr->info.tkwin)); + + TkMacWinBounds((TkWindow *) macScalePtr->info.tkwin, &bounds); + where.h = eventPtr->xbutton.x + bounds.left; + where.v = eventPtr->xbutton.y + bounds.top; + part = TestControl(macScalePtr->scaleHandle, where); + if (part == 0) { + return; + } + + part = TrackControl(macScalePtr->scaleHandle, where, scaleActionProc); + + /* + * Update the value for the widget. + */ + macScalePtr->info.value = (**macScalePtr->scaleHandle).contrlValue; + /* TkpSetScaleValue(&macScalePtr->info, macScalePtr->info.value, 1, 0); */ + + /* + * The TrackControl call will "eat" the ButtonUp event. We now + * generate a ButtonUp event so Tk will unset implicit grabs etc. + */ + GetMouse(&where); + XQueryPointer(NULL, None, &dummyWin, &dummyWin, &x, + &y, &dummy, &dummy, &state); + TkGenerateButtonEvent(x, y, Tk_WindowId(macScalePtr->info.tkwin), state); + + SetGWorld(saveWorld, saveDevice); +} + +/* + *-------------------------------------------------------------- + * + * ScaleActionProc -- + * + * Callback procedure used by the Macintosh toolbox call + * TrackControl. This call will update the display while + * the scrollbar is being manipulated by the user. + * + * Results: + * None. + * + * Side effects: + * May change the display. + * + *-------------------------------------------------------------- + */ + +static pascal void +ScaleActionProc(ControlRef theControl, ControlPartCode partCode) + /* ControlRef theControl; /* Handle to scrollbat control */ + /* ControlPartCode partCode; /* Part of scrollbar that was "hit" */ +{ + register int value; + register TkScale *scalePtr = (TkScale *) GetCRefCon(theControl); + + value = (**theControl).contrlValue; + TkpSetScaleValue(scalePtr, value, 1, 1); + Tcl_Preserve((ClientData) scalePtr); + Tcl_DoOneEvent(TCL_IDLE_EVENTS); + Tcl_Release((ClientData) scalePtr); +} + diff --git a/mac/tkMacScrlbr.c b/mac/tkMacScrlbr.c new file mode 100644 index 0000000..c76daec --- /dev/null +++ b/mac/tkMacScrlbr.c @@ -0,0 +1,1057 @@ +/* + * tkMacScrollbar.c -- + * + * This file implements the Macintosh specific portion of the scrollbar + * widget. The Macintosh scrollbar may also draw a windows grow + * region under certain cases. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacScrlbr.c 1.9 96/12/10 20:04:39 + */ + +#include "tkScrollbar.h" +#include "tkMacInt.h" +#include <Controls.h> + +/* + * The following definitions should really be in MacOS + * header files. They are included here as this is the only + * file that needs the declarations. + */ +typedef pascal void (*ThumbActionFunc)(void); + +#if GENERATINGCFM +typedef UniversalProcPtr ThumbActionUPP; +#else +typedef ThumbActionFunc ThumbActionUPP; +#endif + +enum { + uppThumbActionProcInfo = kPascalStackBased +}; + +#if GENERATINGCFM +#define NewThumbActionProc(userRoutine) \ + (ThumbActionUPP) NewRoutineDescriptor((ProcPtr)(userRoutine), uppThumbActionProcInfo, GetCurrentArchitecture()) +#else +#define NewThumbActionProc(userRoutine) \ + ((ThumbActionUPP) (userRoutine)) +#endif + +/* + * Minimum slider length, in pixels (designed to make sure that the slider + * is always easy to grab with the mouse). + */ + +#define MIN_SLIDER_LENGTH 5 + +/* + * Declaration of Windows specific scrollbar structure. + */ + +typedef struct MacScrollbar { + TkScrollbar info; /* Generic scrollbar info. */ + ControlRef sbHandle; /* Handle to the Scrollbar control struct. */ + int macFlags; /* Various flags; see below. */ +} MacScrollbar; + +/* + * Flag bits for scrollbars on the Mac: + * + * ALREADY_DEAD: Non-zero means this scrollbar has been + * destroyed, but has not been cleaned up. + * IN_MODAL_LOOP: Non-zero means this scrollbar is in the middle + * of a modal loop. + * ACTIVE: Non-zero means this window is currently + * active (in the foreground). + * FLUSH_TOP: Flush with top of Mac window. + * FLUSH_BOTTOM: Flush with bottom of Mac window. + * FLUSH_RIGHT: Flush with right of Mac window. + * FLUSH_LEFT: Flush with left of Mac window. + * SCROLLBAR_GROW: Non-zero means this window draws the grow + * region for the toplevel window. + * AUTO_ADJUST: Non-zero means we automatically adjust + * the size of the widget to align correctly + * along a Mac window. + * DRAW_GROW: Non-zero means we draw the grow region. + */ + +#define ALREADY_DEAD 1 +#define IN_MODAL_LOOP 2 +#define ACTIVE 4 +#define FLUSH_TOP 8 +#define FLUSH_BOTTOM 16 +#define FLUSH_RIGHT 32 +#define FLUSH_LEFT 64 +#define SCROLLBAR_GROW 128 +#define AUTO_ADJUST 256 +#define DRAW_GROW 512 + +/* + * Globals uses locally in this file. + */ +static ControlActionUPP scrollActionProc = NULL; /* Pointer to func. */ +static ThumbActionUPP thumbActionProc = NULL; /* Pointer to func. */ +static TkScrollbar *activeScrollPtr = NULL; /* Non-null when in thumb */ + /* proc. */ +/* + * Forward declarations for procedures defined later in this file: + */ + +static pascal void ScrollbarActionProc _ANSI_ARGS_((ControlRef theControl, + ControlPartCode partCode)); +static int ScrollbarBindProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, XEvent *eventPtr, + Tk_Window tkwin, KeySym keySym)); +static void ScrollbarEventProc _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +static pascal void ThumbActionProc _ANSI_ARGS_((void)); +static void UpdateControlValues _ANSI_ARGS_((MacScrollbar *macScrollPtr)); + +/* + * The class procedure table for the scrollbar widget. + */ + +TkClassProcs tkpScrollbarProcs = { + NULL, /* createProc. */ + NULL, /* geometryProc. */ + NULL /* modalProc */ +}; + +/* + *---------------------------------------------------------------------- + * + * TkpCreateScrollbar -- + * + * Allocate a new TkScrollbar structure. + * + * Results: + * Returns a newly allocated TkScrollbar structure. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkScrollbar * +TkpCreateScrollbar( + Tk_Window tkwin) /* New Tk Window. */ +{ + MacScrollbar * macScrollPtr; + TkWindow *winPtr = (TkWindow *)tkwin; + + if (scrollActionProc == NULL) { + scrollActionProc = NewControlActionProc(ScrollbarActionProc); + thumbActionProc = NewThumbActionProc(ThumbActionProc); + } + + macScrollPtr = (MacScrollbar *) ckalloc(sizeof(MacScrollbar)); + macScrollPtr->sbHandle = NULL; + macScrollPtr->macFlags = 0; + + Tk_CreateEventHandler(tkwin, ActivateMask|ExposureMask| + StructureNotifyMask|FocusChangeMask, + ScrollbarEventProc, (ClientData) macScrollPtr); + + if (!Tcl_GetAssocData(winPtr->mainPtr->interp, "TkScrollbar", NULL)) { + Tcl_SetAssocData(winPtr->mainPtr->interp, "TkScrollbar", NULL, + (ClientData)1); + TkCreateBindingProcedure(winPtr->mainPtr->interp, + winPtr->mainPtr->bindingTable, + (ClientData)Tk_GetUid("Scrollbar"), "<ButtonPress>", + ScrollbarBindProc, NULL, NULL); + } + + return (TkScrollbar *) macScrollPtr; +} + +/* + *-------------------------------------------------------------- + * + * TkpDisplayScrollbar -- + * + * This procedure redraws the contents of a scrollbar window. + * It is invoked as a do-when-idle handler, so it only runs + * when there's nothing else for the application to do. + * + * Results: + * None. + * + * Side effects: + * Information appears on the screen. + * + *-------------------------------------------------------------- + */ + +void +TkpDisplayScrollbar( + ClientData clientData) /* Information about window. */ +{ + register TkScrollbar *scrollPtr = (TkScrollbar *) clientData; + register MacScrollbar *macScrollPtr = (MacScrollbar *) clientData; + register Tk_Window tkwin = scrollPtr->tkwin; + + MacDrawable *macDraw; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + WindowRef windowRef; + + if ((scrollPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + goto done; + } + + /* + * Draw the focus or any 3D relief we may have. + */ + if (scrollPtr->highlightWidth != 0) { + GC gc; + + if (scrollPtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(scrollPtr->highlightColorPtr, + Tk_WindowId(tkwin)); + } else { + gc = Tk_GCForColor(scrollPtr->highlightBgColorPtr, + Tk_WindowId(tkwin)); + } + Tk_DrawFocusHighlight(tkwin, gc, scrollPtr->highlightWidth, + Tk_WindowId(tkwin)); + } + Tk_Draw3DRectangle(tkwin, Tk_WindowId(tkwin), scrollPtr->bgBorder, + scrollPtr->highlightWidth, scrollPtr->highlightWidth, + Tk_Width(tkwin) - 2*scrollPtr->highlightWidth, + Tk_Height(tkwin) - 2*scrollPtr->highlightWidth, + scrollPtr->borderWidth, scrollPtr->relief); + + /* + * Set up port for drawing Macintosh control. + */ + macDraw = (MacDrawable *) Tk_WindowId(tkwin); + destPort = TkMacGetDrawablePort(Tk_WindowId(tkwin)); + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + TkMacSetUpClippingRgn(Tk_WindowId(tkwin)); + + if (macScrollPtr->sbHandle == NULL) { + Rect r; + + r.left = r.top = 0; + r.right = r.bottom = 1; + macScrollPtr->sbHandle = NewControl((WindowRef) destPort, &r, "\p", + false, (short) 500, 0, 1000, + scrollBarProc, (SInt32) scrollPtr); + + /* + * If we are foremost than make us active. + */ + if ((WindowPtr) destPort == FrontWindow()) { + macScrollPtr->macFlags |= ACTIVE; + } + } + + /* + * Update the control values before we draw. + */ + windowRef = (**macScrollPtr->sbHandle).contrlOwner; + UpdateControlValues(macScrollPtr); + + if (macScrollPtr->macFlags & ACTIVE) { + Draw1Control(macScrollPtr->sbHandle); + if (macScrollPtr->macFlags & DRAW_GROW) { + DrawGrowIcon(windowRef); + } + } else { + (**macScrollPtr->sbHandle).contrlHilite = 255; + Draw1Control(macScrollPtr->sbHandle); + if (macScrollPtr->macFlags & DRAW_GROW) { + DrawGrowIcon(windowRef); + Tk_Fill3DRectangle(tkwin, Tk_WindowId(tkwin), scrollPtr->bgBorder, + Tk_Width(tkwin) - 13, Tk_Height(tkwin) - 13, + Tk_Width(tkwin), Tk_Height(tkwin), + 0, TK_RELIEF_FLAT); + } + } + + SetGWorld(saveWorld, saveDevice); + + done: + scrollPtr->flags &= ~REDRAW_PENDING; +} + +/* + *---------------------------------------------------------------------- + * + * TkpConfigureScrollbar -- + * + * This procedure is called after the generic code has finished + * processing configuration options, in order to configure + * platform specific options. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpConfigureScrollbar(scrollPtr) + register TkScrollbar *scrollPtr; /* Information about widget; may or + * may not already have values for + * some fields. */ +{ +} + +/* + *---------------------------------------------------------------------- + * + * TkpComputeScrollbarGeometry -- + * + * After changes in a scrollbar's size or configuration, this + * procedure recomputes various geometry information used in + * displaying the scrollbar. + * + * Results: + * None. + * + * Side effects: + * The scrollbar will be displayed differently. + * + *---------------------------------------------------------------------- + */ + +void +TkpComputeScrollbarGeometry( + register TkScrollbar *scrollPtr) /* Scrollbar whose geometry may + * have changed. */ +{ + MacScrollbar *macScrollPtr = (MacScrollbar *) scrollPtr; + int width, fieldLength, adjust = 0; + + if (scrollPtr->highlightWidth < 0) { + scrollPtr->highlightWidth = 0; + } + scrollPtr->inset = scrollPtr->highlightWidth + scrollPtr->borderWidth; + width = (scrollPtr->vertical) ? Tk_Width(scrollPtr->tkwin) + : Tk_Height(scrollPtr->tkwin); + scrollPtr->arrowLength = width - 2*scrollPtr->inset + 1; + fieldLength = (scrollPtr->vertical ? Tk_Height(scrollPtr->tkwin) + : Tk_Width(scrollPtr->tkwin)) + - 2*(scrollPtr->arrowLength + scrollPtr->inset); + if (fieldLength < 0) { + fieldLength = 0; + } + scrollPtr->sliderFirst = fieldLength*scrollPtr->firstFraction; + scrollPtr->sliderLast = fieldLength*scrollPtr->lastFraction; + + /* + * Adjust the slider so that some piece of it is always + * displayed in the scrollbar and so that it has at least + * a minimal width (so it can be grabbed with the mouse). + */ + + if (scrollPtr->sliderFirst > (fieldLength - 2*scrollPtr->borderWidth)) { + scrollPtr->sliderFirst = fieldLength - 2*scrollPtr->borderWidth; + } + if (scrollPtr->sliderFirst < 0) { + scrollPtr->sliderFirst = 0; + } + if (scrollPtr->sliderLast < (scrollPtr->sliderFirst + + MIN_SLIDER_LENGTH)) { + scrollPtr->sliderLast = scrollPtr->sliderFirst + MIN_SLIDER_LENGTH; + } + if (scrollPtr->sliderLast > fieldLength) { + scrollPtr->sliderLast = fieldLength; + } + scrollPtr->sliderFirst += scrollPtr->arrowLength + scrollPtr->inset; + scrollPtr->sliderLast += scrollPtr->arrowLength + scrollPtr->inset; + + /* + * Register the desired geometry for the window (leave enough space + * for the two arrows plus a minimum-size slider, plus border around + * the whole window, if any). Then arrange for the window to be + * redisplayed. + */ + + if (scrollPtr->vertical) { + if ((macScrollPtr->macFlags & AUTO_ADJUST) && + (macScrollPtr->macFlags & (FLUSH_RIGHT|FLUSH_LEFT))) { + adjust--; + } + Tk_GeometryRequest(scrollPtr->tkwin, + scrollPtr->width + 2*scrollPtr->inset + adjust, + 2*(scrollPtr->arrowLength + scrollPtr->borderWidth + + scrollPtr->inset)); + } else { + if ((macScrollPtr->macFlags & AUTO_ADJUST) && + (macScrollPtr->macFlags & (FLUSH_TOP|FLUSH_BOTTOM))) { + adjust--; + } + Tk_GeometryRequest(scrollPtr->tkwin, + 2*(scrollPtr->arrowLength + scrollPtr->borderWidth + + scrollPtr->inset), scrollPtr->width + 2*scrollPtr->inset + adjust); + } + Tk_SetInternalBorder(scrollPtr->tkwin, scrollPtr->inset); +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyScrollbar -- + * + * Free data structures associated with the scrollbar control. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyScrollbar( + TkScrollbar *scrollPtr) /* Scrollbar to destroy. */ +{ + MacScrollbar *macScrollPtr = (MacScrollbar *)scrollPtr; + + if (macScrollPtr->sbHandle != NULL) { + if (!(macScrollPtr->macFlags & IN_MODAL_LOOP)) { + DisposeControl(macScrollPtr->sbHandle); + macScrollPtr->sbHandle = NULL; + } + } + macScrollPtr->macFlags |= ALREADY_DEAD; +} + +/* + *-------------------------------------------------------------- + * + * TkpScrollbarPosition -- + * + * Determine the scrollbar element corresponding to a + * given position. + * + * Results: + * One of TOP_ARROW, TOP_GAP, etc., indicating which element + * of the scrollbar covers the position given by (x, y). If + * (x,y) is outside the scrollbar entirely, then OUTSIDE is + * returned. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkpScrollbarPosition( + TkScrollbar *scrollPtr, /* Scrollbar widget record. */ + int x, int y) /* Coordinates within scrollPtr's + * window. */ +{ + MacScrollbar *macScrollPtr = (MacScrollbar *) scrollPtr; + GWorldPtr destPort; + int length, width, tmp, inactive = false; + ControlPartCode part; + Point where; + Rect bounds; + + if (scrollPtr->vertical) { + length = Tk_Height(scrollPtr->tkwin); + width = Tk_Width(scrollPtr->tkwin); + } else { + tmp = x; + x = y; + y = tmp; + length = Tk_Width(scrollPtr->tkwin); + width = Tk_Height(scrollPtr->tkwin); + } + + if ((x < scrollPtr->inset) || (x >= (width - scrollPtr->inset)) + || (y < scrollPtr->inset) || (y >= (length - scrollPtr->inset))) { + return OUTSIDE; + } + + /* + * All of the calculations in this procedure mirror those in + * DisplayScrollbar. Be sure to keep the two consistent. On the + * Macintosh we use the OS call TestControl to do this mapping. + * For TestControl to work, the scrollbar must be active and must + * be in the current port. + */ + + destPort = TkMacGetDrawablePort(Tk_WindowId(scrollPtr->tkwin)); + SetGWorld(destPort, NULL); + UpdateControlValues(macScrollPtr); + if ((**macScrollPtr->sbHandle).contrlHilite == 255) { + inactive = true; + (**macScrollPtr->sbHandle).contrlHilite = 0; + } + + TkMacWinBounds((TkWindow *) scrollPtr->tkwin, &bounds); + where.h = x + bounds.left; + where.v = y + bounds.top; + part = TestControl(((MacScrollbar *) scrollPtr)->sbHandle, where); + if (inactive) { + (**macScrollPtr->sbHandle).contrlHilite = 255; + } + switch (part) { + case inUpButton: + return TOP_ARROW; + case inPageUp: + return TOP_GAP; + case inThumb: + return SLIDER; + case inPageDown: + return BOTTOM_GAP; + case inDownButton: + return BOTTOM_ARROW; + default: + return OUTSIDE; + } +} + +/* + *-------------------------------------------------------------- + * + * ThumbActionProc -- + * + * Callback procedure used by the Macintosh toolbox call + * TrackControl. This call is used to track the thumb of + * the scrollbar. Unlike the ScrollbarActionProc function + * this function is called once and basically takes over + * tracking the scrollbar from the control. This is done + * to avoid conflicts with what the control plans to draw. + * + * Results: + * None. + * + * Side effects: + * May change the display. + * + *-------------------------------------------------------------- + */ + +static pascal void +ThumbActionProc() +{ + register TkScrollbar *scrollPtr = activeScrollPtr; + register MacScrollbar *macScrollPtr = (MacScrollbar *) activeScrollPtr; + Tcl_DString cmdString; + Rect nullRect = {0,0,0,0}; + int origValue, trackBarPin; + double thumbWidth, newFirstFraction, trackBarSize; + char vauleString[40]; + Point currentPoint = { 0, 0 }; + Point lastPoint = { 0, 0 }; + Rect trackRect; + Tcl_Interp *interp; + + if (scrollPtr == NULL) { + return; + } + + Tcl_DStringInit(&cmdString); + + /* + * First compute values that will remain constant during the tracking + * of the thumb. The variable trackBarSize is the length of the scrollbar + * minus the 2 arrows and half the width of the thumb on both sides + * (3 * arrowLength). The variable trackBarPin is the lower starting point + * of the drag region. + * + * Note: the arrowLength is equal to the thumb width of a Mac scrollbar. + */ + origValue = GetControlValue(macScrollPtr->sbHandle); + trackRect = (**macScrollPtr->sbHandle).contrlRect; + if (scrollPtr->vertical == true) { + trackBarSize = (double) (trackRect.bottom - trackRect.top + - (scrollPtr->arrowLength * 3)); + trackBarPin = trackRect.top + scrollPtr->arrowLength + + (scrollPtr->arrowLength / 2); + InsetRect(&trackRect, -25, -113); + + } else { + trackBarSize = (double) (trackRect.right - trackRect.left + - (scrollPtr->arrowLength * 3)); + trackBarPin = trackRect.left + scrollPtr->arrowLength + + (scrollPtr->arrowLength / 2); + InsetRect(&trackRect, -113, -25); + } + + /* + * Track the mouse while the button is held down. If the mouse is moved, + * we calculate the value that should be passed to the "command" part of + * the scrollbar. + */ + while (StillDown()) { + GetMouse(¤tPoint); + if (EqualPt(currentPoint, lastPoint)) { + continue; + } + lastPoint = currentPoint; + + /* + * Calculating this value is a little tricky. We need to calculate a + * value for where the thumb would be in a Motif widget (variable + * thumb). This value is what the "command" expects and is what will + * be resent to the scrollbar to update its value. + */ + thumbWidth = scrollPtr->lastFraction - scrollPtr->firstFraction; + if (PtInRect(currentPoint, &trackRect)) { + if (scrollPtr->vertical == true) { + newFirstFraction = (1.0 - thumbWidth) * + ((double) (currentPoint.v - trackBarPin) / trackBarSize); + } else { + newFirstFraction = (1.0 - thumbWidth) * + ((double) (currentPoint.h - trackBarPin) / trackBarSize); + } + } else { + newFirstFraction = ((double) origValue / 1000.0) + * (1.0 - thumbWidth); + } + + sprintf(vauleString, "%g", newFirstFraction); + + Tcl_DStringSetLength(&cmdString, 0); + Tcl_DStringAppend(&cmdString, scrollPtr->command, + scrollPtr->commandSize); + Tcl_DStringAppendElement(&cmdString, "moveto"); + Tcl_DStringAppendElement(&cmdString, vauleString); + + interp = scrollPtr->interp; + Tcl_Preserve((ClientData) interp); + Tcl_GlobalEval(interp, cmdString.string); + Tcl_Release((ClientData) interp); + + Tcl_DStringSetLength(&cmdString, 0); + Tcl_DStringAppend(&cmdString, "update idletasks", + strlen("update idletasks")); + Tcl_Preserve((ClientData) interp); + Tcl_GlobalEval(interp, cmdString.string); + Tcl_Release((ClientData) interp); + } + + /* + * This next bit of code is a bit of a hack - but needed. The problem is + * that the control wants to draw the drag outline if the control value + * changes during the drag (which it does). What we do here is change the + * clip region to hide this drawing from the user. + */ + ClipRect(&nullRect); + + Tcl_DStringFree(&cmdString); + return; +} + +/* + *-------------------------------------------------------------- + * + * ScrollbarActionProc -- + * + * Callback procedure used by the Macintosh toolbox call + * TrackControl. This call will update the display while + * the scrollbar is being manipulated by the user. + * + * Results: + * None. + * + * Side effects: + * May change the display. + * + *-------------------------------------------------------------- + */ + +static pascal void +ScrollbarActionProc( + ControlRef theControl, /* Handle to scrollbat control */ + ControlPartCode partCode) /* Part of scrollbar that was "hit" */ +{ + register TkScrollbar *scrollPtr = (TkScrollbar *) GetCRefCon(theControl); + Tcl_DString cmdString; + + Tcl_DStringInit(&cmdString); + Tcl_DStringAppend(&cmdString, scrollPtr->command, + scrollPtr->commandSize); + + if (partCode == inUpButton || partCode == inDownButton) { + Tcl_DStringAppendElement(&cmdString, "scroll"); + Tcl_DStringAppendElement(&cmdString, + (partCode == inUpButton ) ? "-1" : "1"); + Tcl_DStringAppendElement(&cmdString, "unit"); + } else if (partCode == inPageUp || partCode == inPageDown) { + Tcl_DStringAppendElement(&cmdString, "scroll"); + Tcl_DStringAppendElement(&cmdString, + (partCode == inPageUp ) ? "-1" : "1"); + Tcl_DStringAppendElement(&cmdString, "page"); + } + Tcl_Preserve((ClientData) scrollPtr->interp); + Tcl_DStringAppend(&cmdString, "; update idletasks", + strlen("; update idletasks")); + Tcl_GlobalEval(scrollPtr->interp, cmdString.string); + Tcl_Release((ClientData) scrollPtr->interp); + + Tcl_DStringFree(&cmdString); +} + +/* + *-------------------------------------------------------------- + * + * ScrollbarBindProc -- + * + * This procedure is invoked when the default <ButtonPress> + * binding on the Scrollbar bind tag fires. + * + * Results: + * None. + * + * Side effects: + * The event enters a modal loop. + * + *-------------------------------------------------------------- + */ + +static int +ScrollbarBindProc( + ClientData clientData, /* Not used. */ + Tcl_Interp *interp, /* Interp with binding. */ + XEvent *eventPtr, /* X event that triggered binding. */ + Tk_Window tkwin, /* Target window for event. */ + KeySym keySym) /* The KeySym if a key event. */ +{ + TkWindow *winPtr = (TkWindow*)tkwin; + TkScrollbar *scrollPtr = (TkScrollbar *) winPtr->instanceData; + MacScrollbar *macScrollPtr = (MacScrollbar *) winPtr->instanceData; + + Tcl_Preserve((ClientData)scrollPtr); + macScrollPtr->macFlags |= IN_MODAL_LOOP; + + if (eventPtr->type == ButtonPress) { + Point where; + Rect bounds; + int part, x, y, dummy; + unsigned int state; + CGrafPtr saveWorld; + GDHandle saveDevice; + GWorldPtr destPort; + Window window; + + /* + * To call Macintosh control routines we must have the port + * set to the window containing the control. We will then test + * which part of the control was hit and act accordingly. + */ + destPort = TkMacGetDrawablePort(Tk_WindowId(scrollPtr->tkwin)); + GetGWorld(&saveWorld, &saveDevice); + SetGWorld(destPort, NULL); + TkMacSetUpClippingRgn(Tk_WindowId(scrollPtr->tkwin)); + + TkMacWinBounds((TkWindow *) scrollPtr->tkwin, &bounds); + where.h = eventPtr->xbutton.x + bounds.left; + where.v = eventPtr->xbutton.y + bounds.top; + part = TestControl(macScrollPtr->sbHandle, where); + if (part == inThumb && scrollPtr->jump == false) { + /* + * Case 1: In thumb, no jump scrolling. Call track control + * with the thumb action proc which will do most of the work. + * Set the global activeScrollPtr to the current control + * so the callback may have access to it. + */ + activeScrollPtr = scrollPtr; + part = TrackControl(macScrollPtr->sbHandle, where, + (ControlActionUPP) thumbActionProc); + activeScrollPtr = NULL; + } else if (part == inThumb) { + /* + * Case 2: in thumb with jump scrolling. Call TrackControl + * with a NULL action proc. Use the new value of the control + * to set update the control. + */ + part = TrackControl(macScrollPtr->sbHandle, where, NULL); + if (part == inThumb) { + double newFirstFraction, thumbWidth; + Tcl_DString cmdString; + char vauleString[TCL_DOUBLE_SPACE]; + + /* + * The following calculation takes the new control + * value and maps it to what Tk needs for its variable + * thumb size representation. + */ + thumbWidth = scrollPtr->lastFraction + - scrollPtr->firstFraction; + newFirstFraction = (1.0 - thumbWidth) * + ((double) GetControlValue(macScrollPtr->sbHandle) / 1000.0); + sprintf(vauleString, "%g", newFirstFraction); + + Tcl_DStringInit(&cmdString); + Tcl_DStringAppend(&cmdString, scrollPtr->command, + strlen(scrollPtr->command)); + Tcl_DStringAppendElement(&cmdString, "moveto"); + Tcl_DStringAppendElement(&cmdString, vauleString); + Tcl_DStringAppend(&cmdString, "; update idletasks", + strlen("; update idletasks")); + + interp = scrollPtr->interp; + Tcl_Preserve((ClientData) interp); + Tcl_GlobalEval(interp, cmdString.string); + Tcl_Release((ClientData) interp); + Tcl_DStringFree(&cmdString); + } + } else if (part != 0) { + /* + * Case 3: in any other part of the scrollbar. We call + * TrackControl with the scrollActionProc which will do + * most all the work. + */ + TrackControl(macScrollPtr->sbHandle, where, scrollActionProc); + HiliteControl(macScrollPtr->sbHandle, 0); + } + + /* + * The TrackControl call will "eat" the ButtonUp event. We now + * generate a ButtonUp event so Tk will unset implicit grabs etc. + */ + GetMouse(&where); + XQueryPointer(NULL, None, &window, &window, &x, + &y, &dummy, &dummy, &state); + window = Tk_WindowId(scrollPtr->tkwin); + TkGenerateButtonEvent(x, y, window, state); + + SetGWorld(saveWorld, saveDevice); + } + + if (macScrollPtr->sbHandle && (macScrollPtr->macFlags & ALREADY_DEAD)) { + DisposeControl(macScrollPtr->sbHandle); + macScrollPtr->sbHandle = NULL; + } + macScrollPtr->macFlags &= ~IN_MODAL_LOOP; + Tcl_Release((ClientData)scrollPtr); + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * ScrollbarEventProc -- + * + * This procedure is invoked by the Tk dispatcher for various + * events on scrollbars. + * + * Results: + * None. + * + * Side effects: + * When the window gets deleted, internal structures get + * cleaned up. When it gets exposed, it is redisplayed. + * + *-------------------------------------------------------------- + */ + +static void +ScrollbarEventProc( + ClientData clientData, /* Information about window. */ + XEvent *eventPtr) /* Information about event. */ +{ + TkScrollbar *scrollPtr = (TkScrollbar *) clientData; + MacScrollbar *macScrollPtr = (MacScrollbar *) clientData; + + if (eventPtr->type == UnmapNotify) { + TkMacSetScrollbarGrow((TkWindow *) scrollPtr->tkwin, false); + } else if (eventPtr->type == ActivateNotify) { + macScrollPtr->macFlags |= ACTIVE; + TkScrollbarEventuallyRedraw((ClientData) scrollPtr); + } else if (eventPtr->type == DeactivateNotify) { + macScrollPtr->macFlags &= ~ACTIVE; + TkScrollbarEventuallyRedraw((ClientData) scrollPtr); + } else { + TkScrollbarEventProc(clientData, eventPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * UpdateControlValues -- + * + * This procedure updates the Macintosh scrollbar control + * to display the values defined by the Tk scrollbar. + * + * Results: + * None. + * + * Side effects: + * The Macintosh control is updated. + * + *-------------------------------------------------------------- + */ + +static void +UpdateControlValues( + MacScrollbar *macScrollPtr) /* Scrollbar data struct. */ +{ + TkScrollbar *scrollPtr = (TkScrollbar *) macScrollPtr; + Tk_Window tkwin = scrollPtr->tkwin; + MacDrawable * macDraw = (MacDrawable *) Tk_WindowId(scrollPtr->tkwin); + WindowRef windowRef = (**macScrollPtr->sbHandle).contrlOwner; + double middle; + int drawGrowRgn = false; + int flushRight = false; + int flushBottom = false; + + /* + * We can't use the Macintosh commands SizeControl and MoveControl as these + * calls will also cause a redraw which in our case will also cause + * flicker. To avoid this we adjust the control record directly. The + * Draw1Control command appears to just draw where ever the control says to + * draw so this seems right. + * + * NOTE: changing the control record directly may not work when + * Apple releases the Copland version of the MacOS (or when hell is cold). + */ + + (**macScrollPtr->sbHandle).contrlRect.left = macDraw->xOff + scrollPtr->inset; + (**macScrollPtr->sbHandle).contrlRect.top = macDraw->yOff + scrollPtr->inset; + (**macScrollPtr->sbHandle).contrlRect.right = macDraw->xOff + Tk_Width(tkwin) + - scrollPtr->inset; + (**macScrollPtr->sbHandle).contrlRect.bottom = macDraw->yOff + + Tk_Height(tkwin) - scrollPtr->inset; + + /* + * To make Tk applications look more like Macintosh applications without + * requiring additional work by the Tk developer we do some cute tricks. + * The first trick plays with the size of the widget to get it to overlap + * with the side of the window by one pixel (we don't do this if the placer + * is the geometry manager). The second trick shrinks the scrollbar if it + * it covers the area of the grow region ao the scrollbar can also draw + * the grow region if need be. + */ + if (!strcmp(macDraw->winPtr->geomMgrPtr->name, "place")) { + macScrollPtr->macFlags &= AUTO_ADJUST; + } else { + macScrollPtr->macFlags |= AUTO_ADJUST; + } + /* TODO: use accessor function!!! */ + if (windowRef->portRect.left == (**macScrollPtr->sbHandle).contrlRect.left) { + if (macScrollPtr->macFlags & AUTO_ADJUST) { + (**macScrollPtr->sbHandle).contrlRect.left--; + } + if (!(macScrollPtr->macFlags & FLUSH_LEFT)) { + macScrollPtr->macFlags |= FLUSH_LEFT; + if (scrollPtr->vertical) { + TkpComputeScrollbarGeometry(scrollPtr); + } + } + } else if (macScrollPtr->macFlags & FLUSH_LEFT) { + macScrollPtr->macFlags &= ~FLUSH_LEFT; + if (scrollPtr->vertical) { + TkpComputeScrollbarGeometry(scrollPtr); + } + } + + if (windowRef->portRect.top == (**macScrollPtr->sbHandle).contrlRect.top) { + if (macScrollPtr->macFlags & AUTO_ADJUST) { + (**macScrollPtr->sbHandle).contrlRect.top--; + } + if (!(macScrollPtr->macFlags & FLUSH_TOP)) { + macScrollPtr->macFlags |= FLUSH_TOP; + if (! scrollPtr->vertical) { + TkpComputeScrollbarGeometry(scrollPtr); + } + } + } else if (macScrollPtr->macFlags & FLUSH_TOP) { + macScrollPtr->macFlags &= ~FLUSH_TOP; + if (! scrollPtr->vertical) { + TkpComputeScrollbarGeometry(scrollPtr); + } + } + + if (windowRef->portRect.right == (**macScrollPtr->sbHandle).contrlRect.right) { + flushRight = true; + if (macScrollPtr->macFlags & AUTO_ADJUST) { + (**macScrollPtr->sbHandle).contrlRect.right++; + } + if (!(macScrollPtr->macFlags & FLUSH_RIGHT)) { + macScrollPtr->macFlags |= FLUSH_RIGHT; + if (scrollPtr->vertical) { + TkpComputeScrollbarGeometry(scrollPtr); + } + } + } else if (macScrollPtr->macFlags & FLUSH_RIGHT) { + macScrollPtr->macFlags &= ~FLUSH_RIGHT; + if (scrollPtr->vertical) { + TkpComputeScrollbarGeometry(scrollPtr); + } + } + + if (windowRef->portRect.bottom == (**macScrollPtr->sbHandle).contrlRect.bottom) { + flushBottom = true; + if (macScrollPtr->macFlags & AUTO_ADJUST) { + (**macScrollPtr->sbHandle).contrlRect.bottom++; + } + if (!(macScrollPtr->macFlags & FLUSH_BOTTOM)) { + macScrollPtr->macFlags |= FLUSH_BOTTOM; + if (! scrollPtr->vertical) { + TkpComputeScrollbarGeometry(scrollPtr); + } + } + } else if (macScrollPtr->macFlags & FLUSH_BOTTOM) { + macScrollPtr->macFlags &= ~FLUSH_BOTTOM; + if (! scrollPtr->vertical) { + TkpComputeScrollbarGeometry(scrollPtr); + } + } + + /* + * If the scrollbar is flush against the bottom right hand coner then + * it may need to draw the grow region for the window so we let the + * wm code know about this scrollbar. We don't actually draw the grow + * region, however, unless we are currently resizable. + */ + macScrollPtr->macFlags &= ~DRAW_GROW; + if (flushBottom && flushRight) { + TkMacSetScrollbarGrow((TkWindow *) tkwin, true); + if (TkMacResizable(macDraw->toplevel->winPtr)) { + if (scrollPtr->vertical) { + (**macScrollPtr->sbHandle).contrlRect.bottom -= 14; + } else { + (**macScrollPtr->sbHandle).contrlRect.right -= 14; + } + macScrollPtr->macFlags |= DRAW_GROW; + } + } else { + TkMacSetScrollbarGrow((TkWindow *) tkwin, false); + } + + /* + * Given the Tk parameters for the fractions of the start and + * end of the thumb, the following calculation determines the + * location for the fixed sized Macintosh thumb. + */ + middle = scrollPtr->firstFraction / (scrollPtr->firstFraction + + (1.0 - scrollPtr->lastFraction)); + + (**macScrollPtr->sbHandle).contrlValue = (short) (middle * 1000); + if ((**macScrollPtr->sbHandle).contrlHilite == 0 || + (**macScrollPtr->sbHandle).contrlHilite == 255) { + if (scrollPtr->firstFraction == 0.0 && + scrollPtr->lastFraction == 1.0) { + (**macScrollPtr->sbHandle).contrlHilite = 255; + } else { + (**macScrollPtr->sbHandle).contrlHilite = 0; + } + } + if ((**macScrollPtr->sbHandle).contrlVis != 255) { + (**macScrollPtr->sbHandle).contrlVis = 255; + } +} diff --git a/mac/tkMacSend.c b/mac/tkMacSend.c new file mode 100644 index 0000000..85065ac --- /dev/null +++ b/mac/tkMacSend.c @@ -0,0 +1,358 @@ +/* + * tkMacSend.c -- + * + * This file provides procedures that implement the "send" + * command, allowing commands to be passed from interpreter + * to interpreter. This current implementation for the Mac + * has most functionality stubed out. + * + * Copyright (c) 1989-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacSend.c 1.7 96/12/03 11:48:27 + */ + +#include "tkPort.h" +#include "tkInt.h" + + /* + * The following structure is used to keep track of the + * interpreters registered by this process. + */ + +typedef struct RegisteredInterp { + char *name; /* Interpreter's name (malloc-ed). */ + Tcl_Interp *interp; /* Interpreter associated with + * name. */ + TkWindow *winPtr; /* Main window for the application. */ + struct RegisteredInterp *nextPtr; + /* Next in list of names associated + * with interps in this process. + * NULL means end of list. */ +} RegisteredInterp; + +static RegisteredInterp *registry = NULL; +/* List of all interpreters + * registered by this process. */ + +/* + * A registry of all interpreters for a display is kept in a + * property "InterpRegistry" on the root window of the display. + * It is organized as a series of zero or more concatenated strings + * (in no particular order), each of the form + * window space name '\0' + * where "window" is the hex id of the comm. window to use to talk + * to an interpreter named "name". + * + * When the registry is being manipulated by an application (e.g. to + * add or remove an entry), it is loaded into memory using a structure + * of the following type: + */ + +typedef struct NameRegistry { + TkDisplay *dispPtr; /* Display from which the registry was + * read. */ + int locked; /* Non-zero means that the display was + * locked when the property was read in. */ + int modified; /* Non-zero means that the property has + * been modified, so it needs to be written + * out when the NameRegistry is closed. */ + unsigned long propLength; /* Length of the property, in bytes. */ + char *property; /* The contents of the property. See format + * above; this is *not* terminated by the + * first null character. Dynamically + * allocated. */ + int allocedByX; /* Non-zero means must free property with + * XFree; zero means use ckfree. */ +} NameRegistry; + + /* + * When a result is being awaited from a sent command, one of + * the following structures is present on a list of all outstanding + * sent commands. The information in the structure is used to + * process the result when it arrives. You're probably wondering + * how there could ever be multiple outstanding sent commands. + * This could happen if interpreters invoke each other recursively. + * It's unlikely, but possible. + */ + +typedef struct PendingCommand { + int serial; /* Serial number expected in + * result. */ + TkDisplay *dispPtr; /* Display being used for communication. */ + char *target; /* Name of interpreter command is + * being sent to. */ + Window commWindow; /* Target's communication window. */ + Tk_TimerToken timeout; /* Token for timer handler used to check + * up on target during long sends. */ + Tcl_Interp *interp; /* Interpreter from which the send + * was invoked. */ + int code; /* Tcl return code for command + * will be stored here. */ + char *result; /* String result for command (malloc'ed), + * or NULL. */ + char *errorInfo; /* Information for "errorInfo" variable, + * or NULL (malloc'ed). */ + char *errorCode; /* Information for "errorCode" variable, + * or NULL (malloc'ed). */ + int gotResponse; /* 1 means a response has been received, + * 0 means the command is still outstanding. */ + struct PendingCommand *nextPtr; + /* Next in list of all outstanding + * commands. NULL means end of + * list. */ +} PendingCommand; + +static PendingCommand *pendingCommands = NULL; +/* List of all commands currently + * being waited for. */ + + /* + * The information below is used for communication between processes + * during "send" commands. Each process keeps a private window, never + * even mapped, with one property, "Comm". When a command is sent to + * an interpreter, the command is appended to the comm property of the + * communication window associated with the interp's process. Similarly, + * when a result is returned from a sent command, it is also appended + * to the comm property. + * + * Each command and each result takes the form of ASCII text. For a + * command, the text consists of a zero character followed by several + * null-terminated ASCII strings. The first string consists of the + * single letter "c". Subsequent strings have the form "option value" + * where the following options are supported: + * + * -r commWindow serial + * + * This option means that a response should be sent to the window + * whose X identifier is "commWindow" (in hex), and the response should + * be identified with the serial number given by "serial" (in decimal). + * If this option isn't specified then the send is asynchronous and + * no response is sent. + * + * -n name + * "Name" gives the name of the application for which the command is + * intended. This option must be present. + * + * -s script + * + * "Script" is the script to be executed. This option must be present. + * + * The options may appear in any order. The -n and -s options must be + * present, but -r may be omitted for asynchronous RPCs. For compatibility + * with future releases that may add new features, there may be additional + * options present; as long as they start with a "-" character, they will + * be ignored. + * + * A result also consists of a zero character followed by several null- + * terminated ASCII strings. The first string consists of the single + * letter "r". Subsequent strings have the form "option value" where + * the following options are supported: + * + * -s serial + * + * Identifies the command for which this is the result. It is the + * same as the "serial" field from the -s option in the command. This + * option must be present. + * + * -c code + * + * "Code" is the completion code for the script, in decimal. If the + * code is omitted it defaults to TCL_OK. + * + * -r result + * + * "Result" is the result string for the script, which may be either + * a result or an error message. If this field is omitted then it + * defaults to an empty string. + * + * -i errorInfo + * + * "ErrorInfo" gives a string with which to initialize the errorInfo + * variable. This option may be omitted; it is ignored unless the + * completion code is TCL_ERROR. + * + * -e errorCode + * + * "ErrorCode" gives a string with with to initialize the errorCode + * variable. This option may be omitted; it is ignored unless the + * completion code is TCL_ERROR. + * + * Options may appear in any order, and only the -s option must be + * present. As with commands, there may be additional options besides + * these; unknown options are ignored. + */ + + /* + * The following variable is the serial number that was used in the + * last "send" command. It is exported only for testing purposes. + */ + +int tkSendSerial = 0; + + /* + * Maximum size property that can be read at one time by + * this module: + */ + +#define MAX_PROP_WORDS 100000 + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int AppendErrorProc _ANSI_ARGS_((ClientData clientData, + XErrorEvent *errorPtr)); +static void AppendPropCarefully _ANSI_ARGS_((Display *display, + Window window, Atom property, char *value, + int length, PendingCommand *pendingPtr)); +static void DeleteProc _ANSI_ARGS_((ClientData clientData)); +static void RegAddName _ANSI_ARGS_((NameRegistry *regPtr, + char *name, Window commWindow)); +static void RegClose _ANSI_ARGS_((NameRegistry *regPtr)); +static void RegDeleteName _ANSI_ARGS_((NameRegistry *regPtr, + char *name)); +static Window RegFindName _ANSI_ARGS_((NameRegistry *regPtr, + char *name)); +static NameRegistry * RegOpen _ANSI_ARGS_((Tcl_Interp *interp, + TkWindow *winPtr, int lock)); +static void SendEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int SendInit _ANSI_ARGS_((Tcl_Interp *interp, + TkWindow *winPtr)); +static Bool SendRestrictProc _ANSI_ARGS_((Display *display, + XEvent *eventPtr, char *arg)); +static int ServerSecure _ANSI_ARGS_((TkDisplay *dispPtr)); +static void TimeoutProc _ANSI_ARGS_((ClientData clientData)); +static int ValidateName _ANSI_ARGS_((TkDisplay *dispPtr, + char *name, Window commWindow, int oldOK)); + +/* + *-------------------------------------------------------------- + * + * Tk_SetAppName -- + * + * This procedure is called to associate an ASCII name with a Tk + * application. If the application has already been named, the + * name replaces the old one. + * + * Results: + * The return value is the name actually given to the application. + * This will normally be the same as name, but if name was already + * in use for an application then a name of the form "name #2" will + * be chosen, with a high enough number to make the name unique. + * + * Side effects: + * Registration info is saved, thereby allowing the "send" command + * to be used later to invoke commands in the application. In + * addition, the "send" command is created in the application's + * interpreter. The registration will be removed automatically + * if the interpreter is deleted or the "send" command is removed. + * + *-------------------------------------------------------------- + */ + +char * +Tk_SetAppName( + Tk_Window tkwin, /* Token for any window in the application + * to be named: it is just used to identify + * the application and the display. */ + char *name) /* The name that will be used to + * refer to the interpreter in later + * "send" commands. Must be globally + * unique. */ +{ + return name; +} + +/* + *-------------------------------------------------------------- + * + * Tk_SendCmd -- + * + * This procedure is invoked to process the "send" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_SendCmd( + ClientData clientData, /* Information about sender (only + * dispPtr field is used). */ + Tcl_Interp *interp, /* Current interpreter. */ + int argc, /* Number of arguments. */ + char **argv) /* Argument strings. */ +{ + Tcl_SetResult(interp, "Send not yet implemented", TCL_STATIC); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * TkGetInterpNames -- + * + * This procedure is invoked to fetch a list of all the + * interpreter names currently registered for the display + * of a particular window. + * + * Results: + * A standard Tcl return value. Interp->result will be set + * to hold a list of all the interpreter names defined for + * tkwin's display. If an error occurs, then TCL_ERROR + * is returned and interp->result will hold an error message. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkGetInterpNames( + Tcl_Interp *interp, /* Interpreter for returning a result. */ + Tk_Window tkwin) /* Window whose display is to be used + * for the lookup. */ +{ + Tcl_SetResult(interp, "Send not yet implemented", TCL_STATIC); + return TCL_ERROR; +} + +/* + *-------------------------------------------------------------- + * + * SendInit -- + * + * This procedure is called to initialize the + * communication channels for sending commands and + * receiving results. + * + * Results: + * None. + * + * Side effects: + * Sets up various data structures and windows. + * + *-------------------------------------------------------------- + */ + +static int +SendInit( + Tcl_Interp *interp, /* Interpreter to use for error reporting + * (no errors are ever returned, but the + * interpreter is needed anyway). */ + TkWindow *winPtr) /* Window that identifies the display to + * initialize. */ +{ + return TCL_OK; +} diff --git a/mac/tkMacShLib.exp b/mac/tkMacShLib.exp new file mode 100644 index 0000000..0c28a4c --- /dev/null +++ b/mac/tkMacShLib.exp @@ -0,0 +1,766 @@ +MacMoveWindow +TkAboutDlg +TkActivateMenuEntry +TkAllocWindow +TkBTreeCharTagged +TkBTreeCharsInLine +TkBTreeCheck +TkBTreeCreate +TkBTreeDeleteChars +TkBTreeDestroy +TkBTreeFindLine +TkBTreeGetTags +TkBTreeInsertChars +TkBTreeLineIndex +TkBTreeLinkSegment +TkBTreeNextLine +TkBTreeNextTag +TkBTreeNumLines +TkBTreePrevTag +TkBTreePreviousLine +TkBTreeStartSearch +TkBTreeStartSearchBack +TkBTreeTag +TkBTreeUnlinkSegment +TkBezierPoints +TkBezierScreenPoints +TkBindDeadWindow +TkBindEventProc +TkBindFree +TkBindInit +TkButtonWorldChanged +TkCanvPostscriptCmd +TkChangeEventWindow +TkClipBox +TkClipInit +TkComputeAnchor +TkConsoleCreate +TkConsoleInit +TkConsolePrint +TkCopyAndGlobalEval +TkCreateBindingProcedure +TkCreateCursorFromData +TkCreateFrame +TkCreateMainWindow +TkCreateMenuReferences +TkCreateNamedFont +TkCreateRegion +TkCurrentTime +TkDeadAppCmd +TkDeleteAllImages +TkDestroyMenu +TkDestroyRegion +TkDoConfigureNotify +TkEventDeadWindow +TkEventuallyRecomputeMenu +TkEventuallyRedrawMenu +TkEventuallyRedrawScale +TkFillPolygon +TkFindMenuReferences +TkFindStateNum +TkFindStateString +TkFocusDeadWindow +TkFocusFilterEvent +TkFocusKeyEvent +TkFontPkgFree +TkFontPkgInit +TkFreeBindingTags +TkFreeCursor +TkFreeFileFilters +TkFreeMenuReferences +TkGenWMConfigureEvent +TkGenWMDestroyEvent +TkGenerateActivateEvents +TkGenerateButtonEvent +TkGetBitmapData +TkGetButtPoints +TkGetCursorByName +TkGetDefaultScreenName +TkGetDisplay +TkGetDisplayOf +TkGetFileFilters +TkGetInterpNames +TkGetMenuHashTable +TkGetMenuIndex +TkGetMiterPoints +TkGetNativeProlog +TkGetPointerCoords +TkGetProlog +TkGetServerInfo +TkGetTransientMaster +TkGrabDeadWindow +TkGrabState +TkInOutEvents +TkIncludePoint +TkInitFileFilters +TkInitFontAttributes +TkIntersectRegion +TkInvokeButton +TkInvokeMenu +TkKeysymToString +TkLineToArea +TkLineToPoint +TkMacButtonKeyState +TkMacClearMenubarActive +TkMacConvertEvent +TkMacConvertTkEvent +TkMacDispatchMenuEvent +TkMacDoHLEvent +TkMacGenerateTime +TkMacGetDrawablePort +TkMacGetScrollbarGrowWindow +TkMacGetXWindow +TkMacGrowToplevel +TkMacHandleMenuSelect +TkMacHandleTearoffMenu +TkMacInitAppleEvents +TkMacInitMenus +TkMacInstallCursor +TkMacInvalClipRgns +TkMacInvalidateWindow +TkMacIsCharacterMissing +TkMacMakeRealWindowExist +TkMacMakeStippleMap +TkMacMenuClick +TkMacRegisterOffScreenWindow +TkMacResizable +TkMacSetEmbedRgn +TkMacSetHelpMenuItemCount +TkMacSetScrollbarGrow +TkMacSetUpClippingRgn +TkMacSetUpGraphicsPort +TkMacUnregisterMacWindow +TkMacUpdateClipRgn +TkMacUseMenuID +TkMacVisableClipRgn +TkMacWinBounds +TkMacWindowOffset +TkMacXAddPixel +TkMacXDestroyImage +TkMacXGetPixel +TkMacXPutPixel +TkMacXSubImage +TkMacZoomToplevel +TkMakeBezierCurve +TkMakeBezierPostscript +TkMakeMenuWindow +TkMenuButtonWorldChanged +TkMenuConfigureDrawOptions +TkMenuConfigureEntryDrawOptions +TkMenuEntryFreeDrawOptions +TkMenuEventProc +TkMenuFreeDrawOptions +TkMenuImageProc +TkMenuInit +TkMenuInitializeDrawingFields +TkMenuInitializeEntryDrawingFields +TkMenuSelectImageProc +TkNewMenuName +TkOptionClassChanged +TkOptionDeadWindow +TkOvalToArea +TkOvalToPoint +TkParseXLFD +TkPointerDeadWindow +TkPointerEvent +TkPolygonToArea +TkPolygonToPoint +TkPositionInTree +TkPostCommand +TkPostSubmenu +TkPostTearoffMenu +TkPreprocessMenu +TkPutImage +TkQueueEventForAllChildren +TkRecomputeMenu +TkRectInRegion +TkRoundToResolution +TkScrollWindow +TkScrollbarEventProc +TkScrollbarEventuallyRedraw +TkSelClearSelection +TkSelDeadWindow +TkSelDefaultSelection +TkSelEventProc +TkSelGetSelection +TkSelInit +TkSelPropProc +TkSelUpdateClipboard +TkSetClassProcs +TkSetMacColor +TkSetRegion +TkSetWMName +TkSetWindowMenuBar +TkStringToKeysym +TkSuspendClipboard +TkTextBindProc +TkTextChanged +TkTextCharBbox +TkTextCharLayoutProc +TkTextCreateDInfo +TkTextCreateTag +TkTextDLineInfo +TkTextEventuallyRepick +TkTextFreeDInfo +TkTextFreeTag +TkTextGetIndex +TkTextGetTabs +TkTextImageCmd +TkTextImageIndex +TkTextIndexBackChars +TkTextIndexCmp +TkTextIndexForwChars +TkTextIndexToSeg +TkTextInsertDisplayProc +TkTextLostSelection +TkTextMakeIndex +TkTextMarkCmd +TkTextMarkNameToIndex +TkTextMarkSegToIndex +TkTextPickCurrent +TkTextPixelIndex +TkTextPrintIndex +TkTextRedrawRegion +TkTextRedrawTag +TkTextRelayoutWindow +TkTextScanCmd +TkTextSeeCmd +TkTextSegToOffset +TkTextSetMark +TkTextSetYView +TkTextTagCmd +TkTextWindowCmd +TkTextWindowIndex +TkTextXviewCmd +TkTextYviewCmd +TkThickPolyLineToArea +TkUnionRectWithRegion +TkUnsupported1Cmd +TkWmAddToColormapWindows +TkWmDeadWindow +TkWmFocusToplevel +TkWmMapWindow +TkWmNewWindow +TkWmProtocolEventProc +TkWmRemoveFromColormapWindows +TkWmRestackToplevel +TkWmSetClass +TkWmUnmapWindow +Tk_3DBorderColor +Tk_3DBorderGC +Tk_3DHorizontalBevel +Tk_3DVerticalBevel +Tk_AddOption +Tk_BellCmd +Tk_BindCmd +Tk_BindEvent +Tk_BindtagsCmd +Tk_ButtonCmd +Tk_CanvasCmd +Tk_CanvasDrawableCoords +Tk_CanvasEventuallyRedraw +Tk_CanvasGetCoord +Tk_CanvasGetTextInfo +Tk_CanvasPsBitmap +Tk_CanvasPsColor +Tk_CanvasPsFont +Tk_CanvasPsPath +Tk_CanvasPsStipple +Tk_CanvasPsY +Tk_CanvasSetStippleOrigin +Tk_CanvasTagsParseProc +Tk_CanvasTagsPrintProc +Tk_CanvasTkwin +Tk_CanvasWindowCoords +Tk_ChangeWindowAttributes +Tk_CharBbox +Tk_CheckbuttonCmd +Tk_ChooseColorCmd +Tk_ClearSelection +Tk_ClipboardAppend +Tk_ClipboardClear +Tk_ClipboardCmd +Tk_ComputeTextLayout +Tk_ConfigureInfo +Tk_ConfigureValue +Tk_ConfigureWidget +Tk_ConfigureWindow +Tk_CoordsToWindow +Tk_CreateBinding +Tk_CreateBindingTable +Tk_CreateErrorHandler +Tk_CreateEventHandler +Tk_CreateGenericHandler +Tk_CreateImageType +Tk_CreateItemType +Tk_CreatePhotoImageFormat +Tk_CreateSelHandler +Tk_CreateWindow +Tk_CreateWindowFromPath +Tk_DefineBitmap +Tk_DefineCursor +Tk_DeleteAllBindings +Tk_DeleteBinding +Tk_DeleteBindingTable +Tk_DeleteErrorHandler +Tk_DeleteEventHandler +Tk_DeleteGenericHandler +Tk_DeleteImage +Tk_DeleteSelHandler +Tk_DestroyCmd +Tk_DestroyWindow +Tk_DisplayName +Tk_DistanceToTextLayout +Tk_Draw3DPolygon +Tk_Draw3DRectangle +Tk_DrawChars +Tk_DrawFocusHighlight +Tk_DrawTextLayout +Tk_EntryCmd +Tk_EventCmd +Tk_Fill3DPolygon +Tk_Fill3DRectangle +Tk_FindPhoto +Tk_FocusCmd +Tk_FontId +Tk_FontObjCmd +Tk_FrameCmd +Tk_Free3DBorder +Tk_FreeBitmap +Tk_FreeColor +Tk_FreeColormap +Tk_FreeCursor +Tk_FreeFont +Tk_FreeGC +Tk_FreeImage +Tk_FreeOptions +Tk_FreePixmap +Tk_FreeTextLayout +Tk_GCForColor +Tk_GeometryRequest +Tk_Get3DBorder +Tk_GetAllBindings +Tk_GetAnchor +Tk_GetAtomName +Tk_GetBinding +Tk_GetBitmap +Tk_GetBitmapFromData +Tk_GetCapStyle +Tk_GetColor +Tk_GetColorByValue +Tk_GetColormap +Tk_GetCursor +Tk_GetCursorFromData +Tk_GetFont +Tk_GetFontFromObj +Tk_GetFontMetrics +Tk_GetGC +Tk_GetImage +Tk_GetItemTypes +Tk_GetJoinStyle +Tk_GetJustify +Tk_GetNumMainWindows +Tk_GetOpenFileCmd +Tk_GetOption +Tk_GetPixels +Tk_GetPixmap +Tk_GetRelief +Tk_GetRootCoords +Tk_GetSaveFileCmd +Tk_GetScreenMM +Tk_GetScrollInfo +Tk_GetSelection +Tk_GetUid +Tk_GetVRootGeometry +Tk_GetVisual +Tk_Grab +Tk_GrabCmd +Tk_GridCmd +Tk_HandleEvent +Tk_IdToWindow +Tk_ImageChanged +Tk_ImageCmd +Tk_Init +Tk_InternAtom +Tk_IntersectTextLayout +Tk_LabelCmd +Tk_ListboxCmd +Tk_LowerCmd +Tk_Main +Tk_MainLoop +Tk_MainWindow +Tk_MaintainGeometry +Tk_MakeWindowExist +Tk_ManageGeometry +Tk_MapWindow +Tk_MeasureChars +Tk_MenuCmd +Tk_MenubuttonCmd +Tk_MessageBoxCmd +Tk_MessageCmd +Tk_MoveResizeWindow +Tk_MoveToplevelWindow +Tk_MoveWindow +Tk_NameOf3DBorder +Tk_NameOfAnchor +Tk_NameOfBitmap +Tk_NameOfCapStyle +Tk_NameOfColor +Tk_NameOfCursor +Tk_NameOfFont +Tk_NameOfImage +Tk_NameOfJoinStyle +Tk_NameOfJustify +Tk_NameOfRelief +Tk_NameToWindow +Tk_OptionCmd +Tk_OwnSelection +Tk_PackCmd +Tk_ParseArgv +Tk_PhotoBlank +Tk_PhotoExpand +Tk_PhotoGetImage +Tk_PhotoGetSize +Tk_PhotoPutBlock +Tk_PhotoPutZoomedBlock +Tk_PhotoSetSize +Tk_PlaceCmd +Tk_PointToChar +Tk_PostscriptFontName +Tk_PreserveColormap +Tk_QueueWindowEvent +Tk_RadiobuttonCmd +Tk_RaiseCmd +Tk_RedrawImage +Tk_ResizeWindow +Tk_RestackWindow +Tk_RestrictEvents +Tk_SafeInit +Tk_ScaleCmd +Tk_ScrollbarCmd +Tk_SelectionCmd +Tk_SendCmd +Tk_SetAppName +Tk_SetBackgroundFromBorder +Tk_SetClass +Tk_SetGrid +Tk_SetInternalBorder +Tk_SetWindowBackground +Tk_SetWindowBackgroundPixmap +Tk_SetWindowBorder +Tk_SetWindowBorderPixmap +Tk_SetWindowBorderWidth +Tk_SetWindowColormap +Tk_SetWindowVisual +Tk_SizeOfBitmap +Tk_SizeOfImage +Tk_StrictMotif +Tk_TextCmd +Tk_TextLayoutToPostscript +Tk_TextWidth +Tk_TkObjCmd +Tk_TkwaitCmd +Tk_TopCoordsToWindow +Tk_ToplevelCmd +Tk_UndefineCursor +Tk_UnderlineChars +Tk_UnderlineTextLayout +Tk_Ungrab +Tk_UnmaintainGeometry +Tk_UnmapWindow +Tk_UnsetGrid +Tk_UpdateCmd +Tk_UpdatePointer +Tk_WinfoObjCmd +Tk_WmCmd +TkpChangeFocus +TkpClaimFocus +TkpCloseDisplay +TkpComputeButtonGeometry +TkpComputeMenuButtonGeometry +TkpComputeMenubarGeometry +TkpComputeScrollbarGeometry +TkpComputeStandardMenuGeometry +TkpConfigureMenuEntry +TkpConfigureScrollbar +TkpCreateButton +TkpCreateMenuButton +TkpCreateNativeBitmap +TkpCreateScale +TkpCreateScrollbar +TkpDefineNativeBitmaps +TkpDeleteFont +TkpDestroyButton +TkpDestroyMenu +TkpDestroyMenuButton +TkpDestroyMenuEntry +TkpDestroyScale +TkpDestroyScrollbar +TkpDisplayButton +TkpDisplayMenuButton +TkpDisplayScale +TkpDisplayScrollbar +TkpDisplayWarning +TkpDrawMenuEntry +TkpFindWindow +TkpFreeBorder +TkpGetAppName +TkpGetBorder +TkpGetColor +TkpGetColorByValue +TkpGetFontFamilies +TkpGetFontFromAttributes +TkpGetMS +TkpGetNativeAppBitmap +TkpGetNativeFont +TkpGetOtherWindow +TkpGetShadows +TkpInit +TkpInitializeMenuBindings +TkpMakeContainer +TkpMakeWindow +TkpMenuInit +TkpMenuNewEntry +TkpNewMenu +TkpOpenDisplay +TkpPixelToValue +TkpPostMenu +TkpRedirectKeyEvent +TkpScaleElement +TkpScrollbarPosition +TkpSetCapture +TkpSetCursor +TkpSetMainMenubar +TkpSetScaleValue +TkpSetWindowMenuBar +TkpTestembedCmd +TkpUseWindow +TkpValueToPixel +TkpWindowWasRecentlyDeleted +XAllocColor +XAllocSizeHints +XBell +XChangeGC +XChangeProperty +XChangeWindowAttributes +XConfigureWindow +XCopyArea +XCopyPlane +XCreateBitmapFromData +XCreateColormap +XCreateGC +XCreateImage +XDefineCursor +XDestroyWindow +XDrawArc +XDrawLine +XDrawLines +XDrawRectangle +XFillArc +XFillPolygon +XFillRectangle +XFillRectangles +XForceScreenSaver +XFreeColormap +XFreeColors +XFreeGC +XFreeModifiermap +XGContextFromGC +XGetAtomName +XGetGeometry +XGetImage +XGetModifierMapping +XGetVisualInfo +XGetWindowProperty +XGrabKeyboard +XGrabPointer +XInternAtom +XKeycodeToKeysym +XKeysymToKeycode +XKeysymToString +XLookupString +XMapWindow +XMoveResizeWindow +XMoveWindow +XParseColor +XQueryPointer +XRaiseWindow +XReadBitmapFile +XRefreshKeyboardMapping +XResizeWindow +XRootWindow +XSelectInput +XSendEvent +XSetArcMode +XSetBackground +XSetClipMask +XSetClipOrigin +XSetErrorHandler +XSetFillRule +XSetFillStyle +XSetFont +XSetForeground +XSetFunction +XSetIconName +XSetInputFocus +XSetLineAttributes +XSetSelectionOwner +XSetStipple +XSetTSOrigin +XSetWMNormalHints +XSetWindowBackground +XSetWindowBackgroundPixmap +XSetWindowBorder +XSetWindowBorderPixmap +XSetWindowBorderWidth +XSetWindowColormap +XStringToKeysym +XUngrabKeyboard +XUngrabPointer +XUnmapWindow +_Aldata +_Assert +_Atcount +_Atfuns +_Clocale +_Closreg +_Costate +_Daysto +_Dbl +_Defloc +_Environ +_Environ1 +_Fgpos +_Files +_Flt +_Fopen +_Foprep +_Fread +_Freeloc +_Frprep +_Fspos +_Fwprep +_Fwrite +_Genld +_Gentime +_Getdst +_Getfld +_Getfloat +_Getint +_Getloc +_Getmem +_Getstr +_Gettime +_Getzone +_Isdst +_Ldbl +_Ldtob +_Litob +_Locale +_Locsum +_Loctab +_Locterm +_Locvar +_MWERKS_Atcount +_MWERKS_Atfuns +_Makeloc +_Makestab +_Makewct +_Mbcurmax +_Mbstate +_Mbtowc +_Nnl +_PJP_C_Copyright +_Printf +_Putfld +_Putstr +_Puttxt +_Randseed +_Readloc +_Scanf +_Setloc +_Skip +_Stdin +_Stdout +_Stod +_Stof +_Stoflt +_Stold +_Strerror +_Strftime +_Strxfrm +_Times +_Tolower +_Toupper +_Ttotm +_WCostate +_Wcstate +_Wctob +_Wctomb +_Wctrans +_Wctype +_XInitImageFuncPtrs +__CheckForSystem7 +__RemoveConsoleHandler__ +__aborting +__ctopstring +__getcreator +__gettype +__myraise +__system7present +_atexit +_exit +_fcreator +_ftype +pendingPtr +tclFocusDebug +tcl_macQdPtr +tkActiveUid +tkAppleMenu +tkArcType +tkBTreeDebug +tkBitmapImageType +tkBitmapType +tkDisabledUid +tkDisplayList +tkEditMenu +tkFileMenu +tkImageType +tkImgFmtGIF +tkImgFmtPPM +tkLineType +tkMacAppInFront +tkMacFocusWin +tkMainWindowList +tkMenuConfigSpecs +tkMenuEntryConfigSpecs +tkNormalUid +tkOvalType +tkPhotoImageType +tkPolygonType +tkPredefBitmapTable +tkRectangleType +tkSendSerial +tkTextCharType +tkTextCharUid +tkTextDebug +tkTextDisabledUid +tkTextLeftMarkType +tkTextNoneUid +tkTextNormalUid +tkTextRightMarkType +tkTextToggleOffType +tkTextToggleOnType +tkTextType +tkTextWordUid +tkWindowType +tkpButtonConfigSpecs +tkpButtonProcs +tkpMenubuttonClass +tkpScrollbarConfigSpecs +tkpScrollbarProcs +#TclMacInitializeFragment +#TclMacTerminateFragment +#__initialize +#__ptmf_null +#__terminate diff --git a/mac/tkMacSubwindows.c b/mac/tkMacSubwindows.c new file mode 100644 index 0000000..65c1a7e --- /dev/null +++ b/mac/tkMacSubwindows.c @@ -0,0 +1,1227 @@ +/* + * tkMacSubwindows.c -- + * + * Implements subwindows for the macintosh version of Tk. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacSubwindows.c 1.81 97/10/29 11:46:54 + */ + +#include "tkInt.h" +#include "X.h" +#include "Xlib.h" +#include <stdio.h> + +#include <Windows.h> +#include <QDOffscreen.h> +#include "tkMacInt.h" + +/* + * Temporary region that can be reused. + */ +static RgnHandle tmpRgn = NULL; + +static void UpdateOffsets _ANSI_ARGS_((TkWindow *winPtr, int deltaX, int deltaY)); + +void MacMoveWindow _ANSI_ARGS_((WindowRef window, int x, int y)); + +/* + *---------------------------------------------------------------------- + * + * XDestroyWindow -- + * + * Dealocates the given X Window. + * + * Results: + * The window id is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +XDestroyWindow( + Display* display, /* Display. */ + Window window) /* Window. */ +{ + MacDrawable *macWin = (MacDrawable *) window; + GWorldPtr destPort; + + /* + * Remove any dangling pointers that may exist if + * the window we are deleting is being tracked by + * the grab code. + */ + + TkPointerDeadWindow(macWin->winPtr); + macWin->toplevel->referenceCount--; + + + if (Tk_IsTopLevel(macWin->winPtr)) { + DisposeRgn(macWin->clipRgn); + DisposeRgn(macWin->aboveClipRgn); + + /* + * Delete the Mac window and remove it from the windowTable. + * The window could be NULL if the window was never mapped. + * However, we don't do this for embedded windows, they don't + * go in the window list, and they do not own their portPtr's. + */ + + if (!(Tk_IsEmbedded(macWin->winPtr))) { + destPort = TkMacGetDrawablePort(window); + if (destPort != NULL) { + TkMacWindowList *listPtr, *prevPtr; + + TkMacUnregisterMacWindow(destPort); + DisposeWindow((WindowRef) destPort); + + for (listPtr = tkMacWindowListPtr, prevPtr = NULL; + tkMacWindowListPtr != NULL; + prevPtr = listPtr, listPtr = listPtr->nextPtr) { + if (listPtr->winPtr == macWin->winPtr) { + if (prevPtr == NULL) { + tkMacWindowListPtr = listPtr->nextPtr; + } else { + prevPtr->nextPtr = listPtr->nextPtr; + } + ckfree((char *) listPtr); + break; + } + } + } + } + + macWin->portPtr = NULL; + + /* + * Delay deletion of a toplevel data structure untill all + * children have been deleted. + */ + if (macWin->toplevel->referenceCount == 0) { + ckfree((char *) macWin->toplevel); + } + } else { + destPort = TkMacGetDrawablePort(window); + if (destPort != NULL) { + SetGWorld(destPort, NULL); + TkMacInvalidateWindow(macWin, TK_PARENT_WINDOW); + } + if (macWin->winPtr->parentPtr != NULL) { + TkMacInvalClipRgns(macWin->winPtr->parentPtr); + } + DisposeRgn(macWin->clipRgn); + DisposeRgn(macWin->aboveClipRgn); + + if (macWin->toplevel->referenceCount == 0) { + ckfree((char *) macWin->toplevel); + } + ckfree((char *) macWin); + } +} + +/* + *---------------------------------------------------------------------- + * + * XMapWindow -- + * + * Map the given X Window to the screen. See X window documentation + * for more details. + * + * Results: + * None. + * + * Side effects: + * The subwindow or toplevel may appear on the screen. + * + *---------------------------------------------------------------------- + */ + +void +XMapWindow( + Display* display, /* Display. */ + Window window) /* Window. */ +{ + MacDrawable *macWin = (MacDrawable *) window; + XEvent event; + GWorldPtr destPort; + + /* + * Under certain situations it's possible for this function to be + * called before the toplevel window it's associated with has actually + * been mapped. In that case we need to create the real Macintosh + * window now as this function as well as other X functions assume that + * the portPtr is valid. + */ + if (!TkMacHostToplevelExists(macWin->toplevel->winPtr)) { + TkMacMakeRealWindowExist(macWin->toplevel->winPtr); + } + destPort = TkMacGetDrawablePort(window); + + display->request++; + macWin->winPtr->flags |= TK_MAPPED; + if (Tk_IsTopLevel(macWin->winPtr)) { + if (!Tk_IsEmbedded(macWin->winPtr)) { + ShowWindow((WindowRef) destPort); + } + + /* + * We only need to send the MapNotify event + * for toplevel windows. + */ + event.xany.serial = display->request; + event.xany.send_event = False; + event.xany.display = display; + + event.xmap.window = window; + event.xmap.type = MapNotify; + event.xmap.event = window; + event.xmap.override_redirect = macWin->winPtr->atts.override_redirect; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + } else { + TkMacInvalClipRgns(macWin->winPtr->parentPtr); + } + + /* + * Generate damage for that area of the window + */ + SetGWorld(destPort, NULL); + TkMacUpdateClipRgn(macWin->winPtr); + TkMacInvalidateWindow(macWin, TK_PARENT_WINDOW); +} + +/* + *---------------------------------------------------------------------- + * + * XUnmapWindow -- + * + * Unmap the given X Window to the screen. See X window + * documentation for more details. + * + * Results: + * None. + * + * Side effects: + * The subwindow or toplevel may be removed from the screen. + * + *---------------------------------------------------------------------- + */ + +void +XUnmapWindow( + Display* display, /* Display. */ + Window window) /* Window. */ +{ + MacDrawable *macWin = (MacDrawable *) window; + XEvent event; + GWorldPtr destPort; + + destPort = TkMacGetDrawablePort(window); + + display->request++; + macWin->winPtr->flags &= ~TK_MAPPED; + if (Tk_IsTopLevel(macWin->winPtr)) { + if (!Tk_IsEmbedded(macWin->winPtr)) { + HideWindow((WindowRef) destPort); + } + + /* + * We only need to send the UnmapNotify event + * for toplevel windows. + */ + event.xany.serial = display->request; + event.xany.send_event = False; + event.xany.display = display; + + event.xunmap.type = UnmapNotify; + event.xunmap.window = window; + event.xunmap.event = window; + event.xunmap.from_configure = false; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + } else { + /* + * Generate damage for that area of the window. + */ + SetGWorld(destPort, NULL); + TkMacInvalidateWindow(macWin, TK_PARENT_WINDOW); /* TODO: may not be valid */ + TkMacInvalClipRgns(macWin->winPtr->parentPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * XResizeWindow -- + * + * Resize a given X window. See X windows documentation for + * further details. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +XResizeWindow( + Display* display, /* Display. */ + Window window, /* Window. */ + unsigned int width, + unsigned int height) +{ + MacDrawable *macWin = (MacDrawable *) window; + GWorldPtr destPort; + + destPort = TkMacGetDrawablePort(window); + if (destPort == NULL) { + return; + } + + display->request++; + SetPort((GrafPtr) destPort); + if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { + /* + * NOTE: we are not adding the new space to the update + * region. It is currently assumed that Tk will need + * to completely redraw anway. + */ + SizeWindow((WindowRef) destPort, + (short) width, (short) height, false); + TkMacInvalidateWindow(macWin, TK_WINDOW_ONLY); + TkMacInvalClipRgns(macWin->winPtr); + } else { + /* TODO: update all xOff & yOffs */ + int deltaX, deltaY, parentBorderwidth; + MacDrawable *macParent = macWin->winPtr->parentPtr->privatePtr; + + /* + * Find the Parent window - + * For an embedded window this will be its container. + */ + + if (Tk_IsEmbedded(macWin->winPtr)) { + TkWindow *contWinPtr; + + contWinPtr = TkpGetOtherWindow(macWin->winPtr); + if (contWinPtr == NULL) { + panic("XMoveResizeWindow could not find container"); + } + macParent = contWinPtr->privatePtr; + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } else { + macParent = macWin->winPtr->parentPtr->privatePtr; + if (macParent == NULL) { + return; /* TODO: Probably should be a panic */ + } + } + + TkMacInvalClipRgns(macParent->winPtr); + TkMacInvalidateWindow(macWin, TK_PARENT_WINDOW); + + deltaX = - macWin->xOff; + deltaY = - macWin->yOff; + + /* + * If macWin->winPtr is an embedded window, don't offset by its + * parent's borderwidth... + */ + + if (!Tk_IsEmbedded(macWin->winPtr)) { + parentBorderwidth = macWin->winPtr->parentPtr->changes.border_width; + } else { + parentBorderwidth = 0; + } + deltaX += macParent->xOff + parentBorderwidth + + macWin->winPtr->changes.x; + deltaY += macParent->yOff + parentBorderwidth + + macWin->winPtr->changes.y; + + UpdateOffsets(macWin->winPtr, deltaX, deltaY); + } +} + +/* + *---------------------------------------------------------------------- + * + * XMoveResizeWindow -- + * + * Move or resize a given X window. See X windows documentation + * for further details. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +XMoveResizeWindow( + Display* display, /* Display. */ + Window window, /* Window. */ + int x, int y, + unsigned int width, + unsigned int height) +{ + MacDrawable *macWin = (MacDrawable *) window; + GWorldPtr destPort; + + destPort = TkMacGetDrawablePort(window); + if (destPort == NULL) { + return; + } + + SetPort((GrafPtr) destPort); + if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { + /* + * NOTE: we are not adding the new space to the update + * region. It is currently assumed that Tk will need + * to completely redraw anway. + */ + + SizeWindow((WindowRef) destPort, + (short) width, (short) height, false); + MacMoveWindow((WindowRef) destPort, x, y); + + /* TODO: is the following right? */ + TkMacInvalidateWindow(macWin, TK_WINDOW_ONLY); + TkMacInvalClipRgns(macWin->winPtr); + } else { + int deltaX, deltaY, parentBorderwidth; + Rect bounds; + MacDrawable *macParent; + + /* + * Find the Parent window - + * For an embedded window this will be its container. + */ + + if (Tk_IsEmbedded(macWin->winPtr)) { + TkWindow *contWinPtr; + + contWinPtr = TkpGetOtherWindow(macWin->winPtr); + if (contWinPtr == NULL) { + panic("XMoveResizeWindow could not find container"); + } + macParent = contWinPtr->privatePtr; + + /* + * NOTE: Here we should handle out of process embedding. + */ + + + } else { + macParent = macWin->winPtr->parentPtr->privatePtr; + if (macParent == NULL) { + return; /* TODO: Probably should be a panic */ + } + } + + TkMacInvalClipRgns(macParent->winPtr); + TkMacInvalidateWindow(macWin, TK_PARENT_WINDOW); + + deltaX = - macWin->xOff; + deltaY = - macWin->yOff; + + /* + * If macWin->winPtr is an embedded window, don't offset by its + * parent's borderwidth... + */ + + if (!Tk_IsEmbedded(macWin->winPtr)) { + parentBorderwidth = macWin->winPtr->parentPtr->changes.border_width; + } else { + parentBorderwidth = 0; + } + deltaX += macParent->xOff + parentBorderwidth + + macWin->winPtr->changes.x; + deltaY += macParent->yOff + parentBorderwidth + + macWin->winPtr->changes.y; + + UpdateOffsets(macWin->winPtr, deltaX, deltaY); + TkMacWinBounds(macWin->winPtr, &bounds); + InvalRect(&bounds); + } +} + +/* + *---------------------------------------------------------------------- + * + * XMoveWindow -- + * + * Move a given X window. See X windows documentation for further + * details. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +XMoveWindow( + Display* display, /* Display. */ + Window window, /* Window. */ + int x, + int y) +{ + MacDrawable *macWin = (MacDrawable *) window; + GWorldPtr destPort; + + destPort = TkMacGetDrawablePort(window); + if (destPort == NULL) { + return; + } + + SetPort((GrafPtr) destPort); + if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { + /* + * NOTE: we are not adding the new space to the update + * region. It is currently assumed that Tk will need + * to completely redraw anway. + */ + MacMoveWindow((WindowRef) destPort, x, y); + + /* TODO: is the following right? */ + TkMacInvalidateWindow(macWin, TK_WINDOW_ONLY); + TkMacInvalClipRgns(macWin->winPtr); + } else { + int deltaX, deltaY, parentBorderwidth; + Rect bounds; + MacDrawable *macParent; + + /* + * Find the Parent window - + * For an embedded window this will be its container. + */ + + if (Tk_IsEmbedded(macWin->winPtr)) { + TkWindow *contWinPtr; + + contWinPtr = TkpGetOtherWindow(macWin->winPtr); + if (contWinPtr == NULL) { + panic("XMoveWindow could not find container"); + } + macParent = contWinPtr->privatePtr; + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } else { + macParent = macWin->winPtr->parentPtr->privatePtr; + if (macParent == NULL) { + return; /* TODO: Probably should be a panic */ + } + } + + TkMacInvalClipRgns(macParent->winPtr); + TkMacInvalidateWindow(macWin, TK_PARENT_WINDOW); + + deltaX = - macWin->xOff; + deltaY = - macWin->yOff; + + /* + * If macWin->winPtr is an embedded window, don't offset by its + * parent's borderwidth... + */ + + if (!Tk_IsEmbedded(macWin->winPtr)) { + parentBorderwidth = macWin->winPtr->parentPtr->changes.border_width; + } else { + parentBorderwidth = 0; + } + deltaX += macParent->xOff + parentBorderwidth + + macWin->winPtr->changes.x; + deltaY += macParent->yOff + parentBorderwidth + + macWin->winPtr->changes.y; + + UpdateOffsets(macWin->winPtr, deltaX, deltaY); + TkMacWinBounds(macWin->winPtr, &bounds); + InvalRect(&bounds); + } +} + +/* + *---------------------------------------------------------------------- + * + * XRaiseWindow -- + * + * Change the stacking order of a window. + * + * Results: + * None. + * + * Side effects: + * Changes the stacking order of the specified window. + * + *---------------------------------------------------------------------- + */ + +void +XRaiseWindow( + Display* display, /* Display. */ + Window window) /* Window. */ +{ + MacDrawable *macWin = (MacDrawable *) window; + + display->request++; + if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { + TkWmRestackToplevel(macWin->winPtr, Above, NULL); + } else { + /* TODO: this should generate damage */ + } +} + +/* + *---------------------------------------------------------------------- + * + * XConfigureWindow -- + * + * Change the size, position, stacking, or border of the specified + * window. + * + * Results: + * None. + * + * Side effects: + * Changes the attributes of the specified window. Note that we + * ignore the passed in values and use the values stored in the + * TkWindow data structure. + * + *---------------------------------------------------------------------- + */ + +void +XConfigureWindow( + Display* display, /* Display. */ + Window w, /* Window. */ + unsigned int value_mask, + XWindowChanges* values) +{ + MacDrawable *macWin = (MacDrawable *) w; + TkWindow *winPtr = macWin->winPtr; + + display->request++; + + /* + * Change the shape and/or position of the window. + */ + + if (value_mask & (CWX|CWY|CWWidth|CWHeight)) { + XMoveResizeWindow(display, w, winPtr->changes.x, winPtr->changes.y, + winPtr->changes.width, winPtr->changes.height); + } + + /* + * Change the stacking order of the window. Tk actuall keeps all + * the information we need for stacking order. All we need to do + * is make sure the clipping regions get updated and generate damage + * that will ensure things get drawn correctly. + */ + + if (value_mask & CWStackMode) { + Rect bounds; + GWorldPtr destPort; + + destPort = TkMacGetDrawablePort(w); + if (destPort != NULL) { + SetPort((GrafPtr) destPort); + TkMacInvalClipRgns(winPtr->parentPtr); + TkMacWinBounds(winPtr, &bounds); + InvalRect(&bounds); + } + } + + /* TkGenWMMoveRequestEvent(macWin->winPtr, + macWin->winPtr->changes.x, macWin->winPtr->changes.y); */ +} + +/* + *---------------------------------------------------------------------- + * + * TkMacUpdateClipRgn -- + * + * This function updates the cliping regions for a given window + * and all of its children. Once updated the TK_CLIP_INVALID flag + * in the subwindow data structure is unset. The TK_CLIP_INVALID + * flag should always be unset before any drawing is attempted. + * + * Results: + * None. + * + * Side effects: + * The clip regions for the window and its children are updated. + * + *---------------------------------------------------------------------- + */ + +void +TkMacUpdateClipRgn( + TkWindow *winPtr) +{ + RgnHandle rgn; + int x, y; + TkWindow *win2Ptr; + + if (winPtr == NULL) { + return; + } + + if (winPtr->privatePtr->flags & TK_CLIP_INVALID) { + rgn = winPtr->privatePtr->aboveClipRgn; + if (tmpRgn == NULL) { + tmpRgn = NewRgn(); + } + + /* + * Start with a region defined by the window bounds. + */ + + x = winPtr->privatePtr->xOff; + y = winPtr->privatePtr->yOff; + SetRectRgn(rgn, (short) x, (short) y, + (short) (winPtr->changes.width + x), + (short) (winPtr->changes.height + y)); + + /* + * Clip away the area of any windows that may obscure this + * window. + * For a non-toplevel window, first, clip to the parents visable + * clip region. + * Second, clip away any siblings that are higher in the + * stacking order. + * For an embedded toplevel, just clip to the container's visible + * clip region. Remember, we only allow one contained window + * in a frame, and don't support any other widgets in the frame either. + * This is not currently enforced, however. + */ + + if (!Tk_IsTopLevel(winPtr)) { + TkMacUpdateClipRgn(winPtr->parentPtr); + SectRgn(rgn, + winPtr->parentPtr->privatePtr->aboveClipRgn, rgn); + + win2Ptr = winPtr->nextPtr; + while (win2Ptr != NULL) { + if (Tk_IsTopLevel(win2Ptr) || !Tk_IsMapped(win2Ptr)) { + win2Ptr = win2Ptr->nextPtr; + continue; + } + x = win2Ptr->privatePtr->xOff; + y = win2Ptr->privatePtr->yOff; + SetRectRgn(tmpRgn, (short) x, (short) y, + (short) (win2Ptr->changes.width + x), + (short) (win2Ptr->changes.height + y)); + DiffRgn(rgn, tmpRgn, rgn); + + win2Ptr = win2Ptr->nextPtr; + } + } else if (Tk_IsEmbedded(winPtr)) { + TkWindow *contWinPtr; + + contWinPtr = TkpGetOtherWindow(winPtr); + + if (contWinPtr != NULL) { + TkMacUpdateClipRgn(contWinPtr); + SectRgn(rgn, + contWinPtr->privatePtr->aboveClipRgn, rgn); + } + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } + + /* + * The final clip region is the aboveClip region (or visable + * region) minus all the children of this window. + * Alternatively, if the window is a container, we must also + * subtract the region of the embedded window. + */ + + rgn = winPtr->privatePtr->clipRgn; + CopyRgn(winPtr->privatePtr->aboveClipRgn, rgn); + + win2Ptr = winPtr->childList; + while (win2Ptr != NULL) { + if (Tk_IsTopLevel(win2Ptr) || !Tk_IsMapped(win2Ptr)) { + win2Ptr = win2Ptr->nextPtr; + continue; + } + x = win2Ptr->privatePtr->xOff; + y = win2Ptr->privatePtr->yOff; + SetRectRgn(tmpRgn, (short) x, (short) y, + (short) (win2Ptr->changes.width + x), + (short) (win2Ptr->changes.height + y)); + DiffRgn(rgn, tmpRgn, rgn); + + win2Ptr = win2Ptr->nextPtr; + } + + if (Tk_IsContainer(winPtr)) { + win2Ptr = TkpGetOtherWindow(winPtr); + if (win2Ptr != NULL) { + if (Tk_IsMapped(win2Ptr)) { + x = win2Ptr->privatePtr->xOff; + y = win2Ptr->privatePtr->yOff; + SetRectRgn(tmpRgn, (short) x, (short) y, + (short) (win2Ptr->changes.width + x), + (short) (win2Ptr->changes.height + y)); + DiffRgn(rgn, tmpRgn, rgn); + } + } + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } + + winPtr->privatePtr->flags &= ~TK_CLIP_INVALID; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacVisableClipRgn -- + * + * This function returnd the Macintosh cliping region for the + * given window. A NULL Rgn means the window is not visable. + * + * Results: + * The region. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +RgnHandle +TkMacVisableClipRgn( + TkWindow *winPtr) +{ + if (winPtr->privatePtr->flags & TK_CLIP_INVALID) { + TkMacUpdateClipRgn(winPtr); + } + + return winPtr->privatePtr->clipRgn; +} + +/* + *---------------------------------------------------------------------- + * + * TkMacInvalidateWindow -- + * + * This function makes the window as invalid will generate damage + * for the window. + * + * Results: + * None. + * + * Side effects: + * Damage is created. + * + *---------------------------------------------------------------------- + */ + +void +TkMacInvalidateWindow( + MacDrawable *macWin, /* Make window that's causing damage. */ + int flag) /* Should be TK_WINDOW_ONLY or + * TK_PARENT_WINDOW */ +{ + + if (flag == TK_WINDOW_ONLY) { + InvalRgn(macWin->clipRgn); + } else { + if (!EmptyRgn(macWin->aboveClipRgn)) { + InvalRgn(macWin->aboveClipRgn); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacGetDrawablePort -- + * + * This function returns the Graphics Port for a given X drawable. + * + * Results: + * A GWorld pointer. Either an off screen pixmap or a Window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +GWorldPtr +TkMacGetDrawablePort( + Drawable drawable) +{ + MacDrawable *macWin = (MacDrawable *) drawable; + + if (macWin == NULL) { + return NULL; + } + + /* + * This is NULL for off-screen pixmaps. Then the portPtr + * always points to the off-screen port, and we don't + * have to worry about containment + */ + + if (macWin->clipRgn == NULL) { + return macWin->portPtr; + } + + /* + * If the Drawable is in an embedded window, use the Port of its container. + * + * TRICKY POINT: we can have cases when a toplevel is being destroyed + * where the winPtr for the toplevel has been freed, but the children + * are not all the way destroyed. The children will call this function + * as they are being destroyed, but Tk_IsEmbedded will return garbage. + * So we check the copy of the TK_EMBEDDED flag we put into the + * toplevel's macWin flags. + */ + + if (!(macWin->toplevel->flags & TK_EMBEDDED)) { + return macWin->toplevel->portPtr; + } else { + TkWindow *contWinPtr; + + contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr); + + if (contWinPtr != NULL) { + return TkMacGetDrawablePort((Drawable) contWinPtr->privatePtr); + } else { + panic("TkMacGetDrawablePort couldn't find container"); + return NULL; + } + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } + +} + +/* + *---------------------------------------------------------------------- + * + * TkMacInvalClipRgns -- + * + * This function invalidates the clipping regions for a given + * window and all of its children. This function should be + * called whenever changes are made to subwindows that would + * effect the size or position of windows. + * + * Results: + * None. + * + * Side effects: + * The cliping regions for the window and its children are + * mark invalid. (Make sure they are valid before drawing.) + * + *---------------------------------------------------------------------- + */ + +void +TkMacInvalClipRgns( + TkWindow *winPtr) +{ + TkWindow *childPtr; + + /* + * If already marked we can stop because all + * decendants will also already be marked. + */ + if (winPtr->privatePtr->flags & TK_CLIP_INVALID) { + return; + } + + winPtr->privatePtr->flags |= TK_CLIP_INVALID; + + /* + * Invalidate clip regions for all children & + * their decendants - unless the child is a toplevel. + */ + childPtr = winPtr->childList; + while (childPtr != NULL) { + if (!Tk_IsTopLevel(childPtr) && Tk_IsMapped(childPtr)) { + TkMacInvalClipRgns(childPtr); + } + childPtr = childPtr->nextPtr; + } + + /* + * Also, if the window is a container, mark its embedded window + */ + + if (Tk_IsContainer(winPtr)) { + childPtr = TkpGetOtherWindow(winPtr); + + if (childPtr != NULL && Tk_IsMapped(childPtr)) { + TkMacInvalClipRgns(childPtr); + } + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacWinBounds -- + * + * Given a Tk window this function determines the windows + * bounds in relation to the Macintosh window's coordinate + * system. This is also the same coordinate system as the + * Tk toplevel window in which this window is contained. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkMacWinBounds( + TkWindow *winPtr, + Rect *bounds) +{ + bounds->left = (short) winPtr->privatePtr->xOff; + bounds->top = (short) winPtr->privatePtr->yOff; + bounds->right = (short) (winPtr->privatePtr->xOff + + winPtr->changes.width); + bounds->bottom = (short) (winPtr->privatePtr->yOff + + winPtr->changes.height); +} + +/* + *---------------------------------------------------------------------- + * + * MacMoveWindow -- + * + * A replacement for the Macintosh MoveWindow function. This + * function adjusts the inputs to MoveWindow to offset the root of + * the window system. This has the effect of making the coords + * refer to the window dressing rather than the top of the content. + * + * Results: + * None. + * + * Side effects: + * Moves the Macintosh window. + * + *---------------------------------------------------------------------- + */ + +void +MacMoveWindow( + WindowRef window, + int x, + int y) +{ + int xOffset, yOffset; + + TkMacWindowOffset(window, &xOffset, &yOffset); + MoveWindow((WindowRef) window, + (short) (x + xOffset), (short) (y + yOffset), false); +} + +/* + *---------------------------------------------------------------------- + * + * UpdateOffsets -- + * + * Updates the X & Y offsets of the given TkWindow from the + * TopLevel it is a decendant of. + * + * Results: + * None. + * + * Side effects: + * The xOff & yOff fields for the Mac window datastructure + * is updated to the proper offset. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateOffsets( + TkWindow *winPtr, + int deltaX, + int deltaY) +{ + TkWindow *childPtr; + + if (winPtr->privatePtr == NULL) { + /* + * We havn't called Tk_MakeWindowExist for this window yet. The + * offset information will be postponed and calulated at that + * time. (This will usually only happen when a mapped parent is + * being moved but has child windows that have yet to be mapped.) + */ + return; + } + + winPtr->privatePtr->xOff += deltaX; + winPtr->privatePtr->yOff += deltaY; + + childPtr = winPtr->childList; + while (childPtr != NULL) { + if (!Tk_IsTopLevel(childPtr)) { + UpdateOffsets(childPtr, deltaX, deltaY); + } + childPtr = childPtr->nextPtr; + } + + if (Tk_IsContainer(winPtr)) { + childPtr = TkpGetOtherWindow(winPtr); + if (childPtr != NULL) { + UpdateOffsets(childPtr,deltaX,deltaY); + } + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetPixmap -- + * + * Creates an in memory drawing surface. + * + * Results: + * Returns a handle to a new pixmap. + * + * Side effects: + * Allocates a new Macintosh GWorld. + * + *---------------------------------------------------------------------- + */ + +Pixmap +Tk_GetPixmap( + Display *display, /* Display for new pixmap (can be null). */ + Drawable d, /* Drawable where pixmap will be used (ignored). */ + int width, /* Dimensions of pixmap. */ + int height, + int depth) /* Bits per pixel for pixmap. */ +{ + QDErr err; + GWorldPtr gWorld; + Rect bounds; + MacDrawable *macPix; + PixMapHandle pixels; + + if (display != NULL) { + display->request++; + } + macPix = (MacDrawable *) ckalloc(sizeof(MacDrawable)); + macPix->winPtr = NULL; + macPix->xOff = 0; + macPix->yOff = 0; + macPix->clipRgn = NULL; + macPix->aboveClipRgn = NULL; + macPix->referenceCount = 0; + macPix->toplevel = NULL; + macPix->flags = 0; + + bounds.top = bounds.left = 0; + bounds.right = (short) width; + bounds.bottom = (short) height; + if (depth != 1) { + depth = 0; + } + + /* + * Allocate memory for the off screen pixmap. If we fail + * try again from system memory. Eventually, we may have + * to panic. + */ + err = NewGWorld(&gWorld, depth, &bounds, NULL, NULL, 0); + if (err != noErr) { + err = NewGWorld(&gWorld, depth, &bounds, NULL, NULL, useTempMem); + } + if (err != noErr) { + panic("Out of memory: NewGWorld failed in Tk_GetPixmap"); + } + + /* + * Lock down the pixels so they don't move out from under us. + */ + pixels = GetGWorldPixMap(gWorld); + LockPixels(pixels); + macPix->portPtr = gWorld; + + return (Pixmap) macPix; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreePixmap -- + * + * Release the resources associated with a pixmap. + * + * Results: + * None. + * + * Side effects: + * Deletes the Macintosh GWorld created by Tk_GetPixmap. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreePixmap( + Display *display, /* Display. */ + Pixmap pixmap) /* Pixmap to destroy */ +{ + MacDrawable *macPix = (MacDrawable *) pixmap; + PixMapHandle pixels; + + display->request++; + pixels = GetGWorldPixMap(macPix->portPtr); + UnlockPixels(pixels); + DisposeGWorld(macPix->portPtr); + ckfree((char *) macPix); +} + diff --git a/mac/tkMacTest.c b/mac/tkMacTest.c new file mode 100644 index 0000000..46a7bb1 --- /dev/null +++ b/mac/tkMacTest.c @@ -0,0 +1,81 @@ +/* + * tkMacTest.c -- + * + * Contains commands for platform specific tests for + * the Macintosh platform. + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacTest.c 1.2 96/12/15 14:34:00 + */ + +#include <Types.h> + +/* + * Forward declarations of procedures defined later in this file: + */ + +int TkplatformtestInit _ANSI_ARGS_((Tcl_Interp *interp)); +static int DebuggerCmd _ANSI_ARGS_((ClientData dummy, + Tcl_Interp *interp, int argc, char **argv)); + +/* + *---------------------------------------------------------------------- + * + * TkplatformtestInit -- + * + * Defines commands that test platform specific functionality for + * Unix platforms. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * Defines new commands. + * + *---------------------------------------------------------------------- + */ + +int +TkplatformtestInit( + Tcl_Interp *interp) /* Interpreter to add commands to. */ +{ + /* + * Add commands for platform specific tests on MacOS here. + */ + + Tcl_CreateCommand(interp, "debugger", DebuggerCmd, + (ClientData) 0, (Tcl_CmdDeleteProc *) NULL); + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * DebuggerCmd -- + * + * This procedure simply calls the low level debugger. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +DebuggerCmd( + ClientData clientData, /* Not used. */ + Tcl_Interp *interp, /* Not used. */ + int argc, /* Not used. */ + char **argv) /* Not used. */ +{ + Debugger(); + return TCL_OK; +} diff --git a/mac/tkMacWindowMgr.c b/mac/tkMacWindowMgr.c new file mode 100644 index 0000000..7c8206c --- /dev/null +++ b/mac/tkMacWindowMgr.c @@ -0,0 +1,1591 @@ +/* + * tkMacWindowMgr.c -- + * + * Implements common window manager functions for the Macintosh. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacWindowMgr.c 1.59 97/11/20 18:56:39 + */ + +#include <Events.h> +#include <Dialogs.h> +#include <EPPC.h> +#include <Windows.h> +#include <ToolUtils.h> +#include <DiskInit.h> +#include <LowMem.h> +#include <Timer.h> +#include <Sound.h> + +#include "tkInt.h" +#include "tkPort.h" +#include "tkMacInt.h" + +#define TK_DEFAULT_ABOUT 128 + +/* + * Declarations of global variables defined in this file. + */ + +int tkMacAppInFront = true; /* Boolean variable for determining + * if we are the frontmost app. */ + +/* + * Non-standard event types that can be passed to HandleEvent. + * These are defined and used by Netscape's plugin architecture. + */ +#define getFocusEvent (osEvt + 16) +#define loseFocusEvent (osEvt + 17) +#define adjustCursorEvent (osEvt + 18) + +/* + * Declarations of static variables used in this file. + */ + +static int gEatButtonUp = 0; /* 1 if we need to eat the next + * up event */ +static Tk_Window gGrabWinPtr = NULL; /* Current grab window, NULL if no grab. */ +static Tk_Window gKeyboardWinPtr = NULL; /* Current keyboard grab window. */ +static RgnHandle gDamageRgn = NULL; /* Damage region used for handling + * screen updates. */ +/* + * Forward declarations of procedures used in this file. + */ + +static void BringWindowForward _ANSI_ARGS_((WindowRef wRef)); +static int CheckEventsAvail _ANSI_ARGS_((void)); +static int GenerateActivateEvents _ANSI_ARGS_((EventRecord *eventPtr, + Window window)); +static int GenerateFocusEvent _ANSI_ARGS_((EventRecord *eventPtr, + Window window)); +static int GenerateKeyEvent _ANSI_ARGS_((EventRecord *eventPtr, + Window window)); +static int GenerateUpdateEvent _ANSI_ARGS_((EventRecord *eventPtr, + Window window)); +static void GenerateUpdates _ANSI_ARGS_((RgnHandle updateRgn, + TkWindow *winPtr)); +static int GeneratePollingEvents _ANSI_ARGS_((void)); +static int GeneratePollingEvents2 _ANSI_ARGS_((Window window)); +static OSErr TellWindowDefProcToCalcRegions _ANSI_ARGS_((WindowRef wRef)); +static int WindowManagerMouse _ANSI_ARGS_((EventRecord *theEvent, + Window window)); + + +/* + *---------------------------------------------------------------------- + * + * WindowManagerMouse -- + * + * This function determines if a button event is a "Window Manager" + * function or an event that should be passed to Tk's event + * queue. + * + * Results: + * Return true if event was placed on Tk's event queue. + * + * Side effects: + * Depends on where the button event occurs. + * + *---------------------------------------------------------------------- + */ + +static int +WindowManagerMouse( + EventRecord *eventPtr, /* Macintosh event record. */ + Window window) /* Window pointer. */ +{ + WindowRef whichWindow, frontWindow; + Tk_Window tkwin; + Point where, where2; + int xOffset, yOffset; + short windowPart; + + frontWindow = FrontWindow(); + + /* + * The window manager only needs to know about mouse down events + * and sometimes we need to "eat" the mouse up. Otherwise, we + * just pass the event to Tk. + */ + if (eventPtr->what == mouseUp) { + if (gEatButtonUp) { + gEatButtonUp = false; + return false; + } + return TkGenerateButtonEvent(eventPtr->where.h, eventPtr->where.v, + window, TkMacButtonKeyState()); + } + + windowPart = FindWindow(eventPtr->where, &whichWindow); + tkwin = Tk_IdToWindow(tkDisplayList->display, window); + switch (windowPart) { + case inSysWindow: + SystemClick(eventPtr, (GrafPort *) whichWindow); + return false; + case inDrag: + if (whichWindow != frontWindow) { + if (!(eventPtr->modifiers & cmdKey)) { + if ((gGrabWinPtr != NULL) && (gGrabWinPtr != tkwin)) { + SysBeep(1); + return false; + } + } + } + + /* + * Call DragWindow to move the window around. It will + * also eat the mouse up event. + */ + SetPort((GrafPort *) whichWindow); + where.h = where.v = 0; + LocalToGlobal(&where); + DragWindow(whichWindow, eventPtr->where, + &tcl_macQdPtr->screenBits.bounds); + gEatButtonUp = false; + + where2.h = where2.v = 0; + LocalToGlobal(&where2); + if (EqualPt(where, where2)) { + return false; + } + + TkMacWindowOffset(whichWindow, &xOffset, &yOffset); + where2.h -= xOffset; + where2.v -= yOffset; + TkGenWMConfigureEvent(tkwin, where2.h, where2.v, + -1, -1, TK_LOCATION_CHANGED); + return true; + case inGrow: + case inContent: + if (whichWindow != frontWindow ) { + /* + * This click moves the window forward. We don't want + * the corasponding mouse-up to be reported to the application + * or else it will mess up some Tk scripts. + */ + if ((gGrabWinPtr != NULL) && (gGrabWinPtr != tkwin)) { + SysBeep(1); + return false; + } + BringWindowForward(whichWindow); + gEatButtonUp = true; + SetPort((GrafPort *) whichWindow); + return false; + } else { + /* + * Generally the content region is the domain of Tk + * sub-windows. However, one exception is the grow + * region. A button down in this area will be handled + * by the window manager. Note: this means that Tk + * may not get button down events in this area! + */ + + if (TkMacGrowToplevel(whichWindow, eventPtr->where) == true) { + return true; + } else { + return TkGenerateButtonEvent(eventPtr->where.h, + eventPtr->where.v, window, TkMacButtonKeyState()); + } + } + case inGoAway: + if (TrackGoAway( whichWindow, eventPtr->where)) { + if (tkwin == NULL) { + return false; + } + TkGenWMDestroyEvent(tkwin); + return true; + } + return false; + case inMenuBar: + { + int oldMode; + KeyMap theKeys; + + GetKeys(theKeys); + oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); + TkMacClearMenubarActive(); + TkMacHandleMenuSelect(MenuSelect(eventPtr->where), + theKeys[1] & 4); + Tcl_SetServiceMode(oldMode); + return true; /* TODO: may not be on event on queue. */ + } + case inZoomIn: + case inZoomOut: + if (TkMacZoomToplevel(whichWindow, eventPtr->where, windowPart) + == true) { + return true; + } else { + return false; + } + default: + return false; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkAboutDlg -- + * + * Displays the default Tk About box. This code uses Macintosh + * resources to define the content of the About Box. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkAboutDlg() +{ + DialogPtr aboutDlog; + short itemHit = -9; + + aboutDlog = GetNewDialog(128, NULL, (void*)(-1)); + + if (!aboutDlog) { + return; + } + + SelectWindow((WindowRef) aboutDlog); + + while (itemHit != 1) { + ModalDialog( NULL, &itemHit); + } + DisposDialog(aboutDlog); + aboutDlog = NULL; + + SelectWindow(FrontWindow()); + + return; +} + +/* + *---------------------------------------------------------------------- + * + * GenerateUpdateEvent -- + * + * Given a Macintosh update event this function generates all the + * X update events needed by Tk. + * + * Results: + * True if event(s) are generated - false otherwise. + * + * Side effects: + * Additional events may be place on the Tk event queue. + * + *---------------------------------------------------------------------- + */ + +static int +GenerateUpdateEvent( + EventRecord *eventPtr, /* Incoming Mac event */ + Window window) /* Root X window for event. */ +{ + WindowRef macWindow; + register TkWindow *winPtr; + + winPtr = (TkWindow *) Tk_IdToWindow(tkDisplayList->display, window); + + if (winPtr == NULL) { + return false; + } + + if (gDamageRgn == NULL) { + gDamageRgn = NewRgn(); + } + + /* + * After the call to BeginUpdate the visable region (visRgn) of the + * window is equal to the intersection of the real visable region and + * the update region for this event. We use this region in all of our + * calculations. + */ + + if (eventPtr->message != NULL) { + macWindow = (WindowRef) TkMacGetDrawablePort(window); + BeginUpdate(macWindow); + GenerateUpdates(macWindow->visRgn, winPtr); + EndUpdate(macWindow); + return true; + } else { + /* + * This event didn't come from the system. This might + * occur if we are running from inside of Netscape. + * In this we shouldn't call BeginUpdate as the vis region + * may be NULL. + */ + RgnHandle rgn; + Rect bounds; + + rgn = NewRgn(); + TkMacWinBounds(winPtr, &bounds); + RectRgn(rgn, &bounds); + GenerateUpdates(rgn, winPtr); + DisposeRgn(rgn); + return true; + } +} + +/* + *---------------------------------------------------------------------- + * + * GenerateUpdates -- + * + * Given a Macintosh update region and a Tk window this function + * geneates a X damage event for the window if it is within the + * update region. The function will then recursivly have each + * damaged window generate damage events for its child windows. + * + * Results: + * None. + * + * Side effects: + * Additional events may be place on the Tk event queue. + * + *---------------------------------------------------------------------- + */ + +static void +GenerateUpdates( + RgnHandle updateRgn, + TkWindow *winPtr) +{ + TkWindow *childPtr; + XEvent event; + Rect bounds; + + TkMacWinBounds(winPtr, &bounds); + + if (bounds.top > (*updateRgn)->rgnBBox.bottom || + (*updateRgn)->rgnBBox.top > bounds.bottom || + bounds.left > (*updateRgn)->rgnBBox.right || + (*updateRgn)->rgnBBox.left > bounds.right || + !RectInRgn(&bounds, updateRgn)) { + return; + } + + event.xany.serial = Tk_Display(winPtr)->request; + event.xany.send_event = false; + event.xany.window = Tk_WindowId(winPtr); + event.xany.display = Tk_Display(winPtr); + + event.type = Expose; + + /* + * Compute the bounding box of the area that the damage occured in. + */ + + /* + * CopyRgn(TkMacVisableClipRgn(winPtr), rgn); + * TODO: this call doesn't work doing resizes!!! + */ + RectRgn(gDamageRgn, &bounds); + SectRgn(gDamageRgn, updateRgn, gDamageRgn); + OffsetRgn(gDamageRgn, -bounds.left, -bounds.top); + event.xexpose.x = (**gDamageRgn).rgnBBox.left; + event.xexpose.y = (**gDamageRgn).rgnBBox.top; + event.xexpose.width = (**gDamageRgn).rgnBBox.right - + (**gDamageRgn).rgnBBox.left; + event.xexpose.height = (**gDamageRgn).rgnBBox.bottom - + (**gDamageRgn).rgnBBox.top; + event.xexpose.count = 0; + + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + + /* + * Generate updates for the children of this window + */ + + for (childPtr = winPtr->childList; childPtr != NULL; + childPtr = childPtr->nextPtr) { + if (!Tk_IsMapped(childPtr) || Tk_IsTopLevel(childPtr)) { + continue; + } + + GenerateUpdates(updateRgn, childPtr); + } + + /* + * Generate updates for any contained windows + */ + + if (Tk_IsContainer(winPtr)) { + childPtr = TkpGetOtherWindow(winPtr); + if (childPtr != NULL && Tk_IsMapped(childPtr)) { + GenerateUpdates(updateRgn, childPtr); + } + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } + + return; +} + +/* + *---------------------------------------------------------------------- + * + * TkGenerateButtonEvent -- + * + * Given a global x & y position and the button key status this + * procedure generates the appropiate X button event. It also + * handles the state changes needed to implement implicit grabs. + * + * Results: + * True if event(s) are generated - false otherwise. + * + * Side effects: + * Additional events may be place on the Tk event queue. + * Grab state may also change. + * + *---------------------------------------------------------------------- + */ + +int +TkGenerateButtonEvent( + int x, /* X location of mouse */ + int y, /* Y location of mouse */ + Window window, /* X Window containing button event. */ + unsigned int state) /* Button Key state suitable for X event */ +{ + WindowRef whichWin, frontWin; + Point where; + Tk_Window tkwin; + int dummy; + + /* + * ButtonDown events will always occur in the front + * window. ButtonUp events, however, may occur anywhere + * on the screen. ButtonUp events should only be sent + * to Tk if in the front window or during an implicit grab. + */ + where.h = x; + where.v = y; + FindWindow(where, &whichWin); + frontWin = FrontWindow(); + + if ((frontWin == NULL) || (frontWin != whichWin && gGrabWinPtr == NULL)) { + return false; + } + + tkwin = Tk_IdToWindow(tkDisplayList->display, window); + + GlobalToLocal(&where); + if (tkwin != NULL) { + tkwin = Tk_TopCoordsToWindow(tkwin, where.h, where.v, &dummy, &dummy); + } + + Tk_UpdatePointer(tkwin, x, y, state); + + return true; +} + +/* + *---------------------------------------------------------------------- + * + * GenerateActivateEvents -- + * + * Generate Activate/Deactivate events from a Macintosh Activate + * event. Note, the activate-on-foreground bit must be set in the + * SIZE flags to ensure we get Activate/Deactivate in addition to + * Susspend/Resume events. + * + * Results: + * Returns true if events were generate. + * + * Side effects: + * Queue events on Tk's event queue. + * + *---------------------------------------------------------------------- + */ + +static int +GenerateActivateEvents( + EventRecord *eventPtr, /* Incoming Mac event */ + Window window) /* Root X window for event. */ +{ + TkWindow *winPtr; + + winPtr = (TkWindow *) Tk_IdToWindow(tkDisplayList->display, window); + if (winPtr == NULL || winPtr->window == None) { + return false; + } + + TkGenerateActivateEvents(winPtr, + (eventPtr->modifiers & activeFlag) ? 1 : 0); + return true; +} + +/* + *---------------------------------------------------------------------- + * + * XSetInputFocus -- + * + * Change the focus window for the application. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +XSetInputFocus( + Display* display, + Window focus, + int revert_to, + Time time) +{ + /* + * Don't need to do a thing. Tk manages the focus for us. + */ +} + +/* + *---------------------------------------------------------------------- + * + * TkpChangeFocus -- + * + * This procedure is a stub on the Mac because we always own the + * focus if we are a front most application. + * + * Results: + * The return value is the serial number of the command that + * changed the focus. It may be needed by the caller to filter + * out focus change events that were queued before the command. + * If the procedure doesn't actually change the focus then + * it returns 0. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpChangeFocus(winPtr, force) + TkWindow *winPtr; /* Window that is to receive the X focus. */ + int force; /* Non-zero means claim the focus even + * if it didn't originally belong to + * topLevelPtr's application. */ +{ + /* + * We don't really need to do anything on the Mac. Tk will + * keep all this state for us. + */ + + if (winPtr->atts.override_redirect) { + return 0; + } + + /* + * Remember the current serial number for the X server and issue + * a dummy server request. This marks the position at which we + * changed the focus, so we can distinguish FocusIn and FocusOut + * events on either side of the mark. + */ + + return NextRequest(winPtr->display); +} + +/* + *---------------------------------------------------------------------- + * + * GenerateFocusEvent -- + * + * Generate FocusIn/FocusOut events from a Macintosh Activate + * event. Note, the activate-on-foreground bit must be set in + * the SIZE flags to ensure we get Activate/Deactivate in addition + * to Susspend/Resume events. + * + * Results: + * Returns true if events were generate. + * + * Side effects: + * Queue events on Tk's event queue. + * + *---------------------------------------------------------------------- + */ + +static int +GenerateFocusEvent( + EventRecord *eventPtr, /* Incoming Mac event */ + Window window) /* Root X window for event. */ +{ + XEvent event; + Tk_Window tkwin; + + tkwin = Tk_IdToWindow(tkDisplayList->display, window); + if (tkwin == NULL) { + return false; + } + + /* + * Generate FocusIn and FocusOut events. This event + * is only sent to the toplevel window. + */ + + if (eventPtr->modifiers & activeFlag) { + event.xany.type = FocusIn; + } else { + event.xany.type = FocusOut; + } + + event.xany.serial = tkDisplayList->display->request; + event.xany.send_event = False; + event.xfocus.display = tkDisplayList->display; + event.xfocus.window = window; + event.xfocus.mode = NotifyNormal; + event.xfocus.detail = NotifyDetailNone; + + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + return true; +} + +/* + *---------------------------------------------------------------------- + * + * GenerateKeyEvent -- + * + * Given Macintosh keyUp, keyDown & autoKey events this function + * generates the appropiate X key events. The window that is passed + * should represent the frontmost window - which will recieve the + * event. + * + * Results: + * True if event(s) are generated - false otherwise. + * + * Side effects: + * Additional events may be place on the Tk event queue. + * + *---------------------------------------------------------------------- + */ + +static int +GenerateKeyEvent( + EventRecord *eventPtr, /* Incoming Mac event */ + Window window) /* Root X window for event. */ +{ + Point where; + Tk_Window tkwin; + XEvent event; + + /* + * The focus must be in the FrontWindow on the Macintosh. + * We then query Tk to determine the exact Tk window + * that owns the focus. + */ + + tkwin = Tk_IdToWindow(tkDisplayList->display, window); + tkwin = (Tk_Window) ((TkWindow *) tkwin)->dispPtr->focusPtr; + if (tkwin == NULL) { + return false; + } + + where.v = eventPtr->where.v; + where.h = eventPtr->where.h; + + event.xany.send_event = False; + event.xkey.same_screen = true; + event.xkey.subwindow = None; + event.xkey.time = TkpGetMS(); + + event.xkey.x_root = where.h; + event.xkey.y_root = where.v; + GlobalToLocal(&where); + Tk_TopCoordsToWindow(tkwin, where.h, where.v, + &event.xkey.x, &event.xkey.y); + event.xkey.keycode = eventPtr->message; + + event.xany.serial = Tk_Display(tkwin)->request; + event.xkey.window = Tk_WindowId(tkwin); + event.xkey.display = Tk_Display(tkwin); + event.xkey.root = XRootWindow(Tk_Display(tkwin), 0); + event.xkey.state = TkMacButtonKeyState(); + + if (eventPtr->what == keyDown) { + event.xany.type = KeyPress; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + } else if (eventPtr->what == keyUp) { + event.xany.type = KeyRelease; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + } else { + /* + * Autokey events send multiple XKey events. + * + * Note: the last KeyRelease will always be missed with + * this scheme. However, most Tk scripts don't look for + * KeyUp events so we should be OK. + */ + event.xany.type = KeyRelease; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + event.xany.type = KeyPress; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + } + return true; +} + +/* + *---------------------------------------------------------------------- + * + * GeneratePollingEvents -- + * + * This function polls the mouse position and generates X Motion, + * Enter & Leave events. The cursor is also updated at this + * time. + * + * Results: + * True if event(s) are generated - false otherwise. + * + * Side effects: + * Additional events may be place on the Tk event queue. + * The cursor may be changed. + * + *---------------------------------------------------------------------- + */ + +static int +GeneratePollingEvents() +{ + Tk_Window tkwin, rootwin; + Window window; + WindowRef whichwindow, frontWin; + Point whereLocal, whereGlobal; + Boolean inContentRgn; + short part; + int local_x, local_y; + int generatedEvents = false; + + /* + * First we get the current mouse position and determine + * what Tk window the mouse is over (if any). + */ + frontWin = FrontWindow(); + if (frontWin == NULL) { + return false; + } + SetPort((GrafPort *) frontWin); + + GetMouse(&whereLocal); + whereGlobal = whereLocal; + LocalToGlobal(&whereGlobal); + + part = FindWindow(whereGlobal, &whichwindow); + inContentRgn = (part == inContent || part == inGrow); + + if ((frontWin != whichwindow) || !inContentRgn) { + tkwin = NULL; + } else { + window = TkMacGetXWindow(whichwindow); + rootwin = Tk_IdToWindow(tkDisplayList->display, window); + if (rootwin == NULL) { + tkwin = NULL; + } else { + tkwin = Tk_TopCoordsToWindow(rootwin, whereLocal.h, whereLocal.v, + &local_x, &local_y); + } + } + + /* + * The following call will generate the appropiate X events and + * adjust any state that Tk must remember. + */ + + if ((tkwin == NULL) && (gGrabWinPtr != NULL)) { + tkwin = gGrabWinPtr; + } + Tk_UpdatePointer(tkwin, whereGlobal.h, whereGlobal.v, + TkMacButtonKeyState()); + + /* + * Finally, we make sure the proper cursor is installed. The installation + * is polled to 1) make our resize hack work, and 2) make sure we have the + * proper cursor even if someone else changed the cursor out from under + * us. + */ + if ((gGrabWinPtr == NULL) && (part == inGrow) && + TkMacResizable((TkWindow *) tkwin) && + (TkMacGetScrollbarGrowWindow((TkWindow *) tkwin) == NULL)) { + TkMacInstallCursor(1); + } else { + TkMacInstallCursor(0); + } + + return true; +} + +/* + *---------------------------------------------------------------------- + * + * GeneratePollingEvents2 -- + * + * This function polls the mouse position and generates X Motion, + * Enter & Leave events. The cursor is also updated at this + * time. NOTE: this version is for Netscape!!! + * + * Results: + * True if event(s) are generated - false otherwise. + * + * Side effects: + * Additional events may be place on the Tk event queue. + * The cursor may be changed. + * + *---------------------------------------------------------------------- + */ + +static int +GeneratePollingEvents2( + Window window) +{ + Tk_Window tkwin, rootwin; + WindowRef whichwindow, frontWin; + Point whereLocal, whereGlobal; + int local_x, local_y; + int generatedEvents = false; + Rect bounds; + + /* + * First we get the current mouse position and determine + * what Tk window the mouse is over (if any). + */ + frontWin = FrontWindow(); + if (frontWin == NULL) { + return false; + } + SetPort((GrafPort *) frontWin); + + GetMouse(&whereLocal); + whereGlobal = whereLocal; + LocalToGlobal(&whereGlobal); + + /* + * Determine if we are in a Tk window or not. + */ + whichwindow = (WindowRef) TkMacGetDrawablePort(window); + if (whichwindow != frontWin) { + tkwin = NULL; + } else { + rootwin = Tk_IdToWindow(tkDisplayList->display, window); + TkMacWinBounds((TkWindow *) rootwin, &bounds); + if (!PtInRect(whereLocal, &bounds)) { + tkwin = NULL; + } else { + tkwin = Tk_TopCoordsToWindow(rootwin, whereLocal.h, whereLocal.v, + &local_x, &local_y); + } + } + + /* + * The following call will generate the appropiate X events and + * adjust any state that Tk must remember. + */ + + if ((tkwin == NULL) && (gGrabWinPtr != NULL)) { + tkwin = gGrabWinPtr; + } + Tk_UpdatePointer(tkwin, whereGlobal.h, whereGlobal.v, + TkMacButtonKeyState()); + + /* + * Finally, we make sure the proper cursor is installed. The installation + * is polled to 1) make our resize hack work, and 2) make sure we have the + * proper cursor even if someone else changed the cursor out from under + * us. + */ + TkMacInstallCursor(0); + + return true; +} + +/* + *---------------------------------------------------------------------- + * + * TkMacButtonKeyState -- + * + * Returns the current state of the button & modifier keys. + * + * Results: + * A bitwise inclusive OR of a subset of the following: + * Button1Mask, ShiftMask, LockMask, ControlMask, Mod?Mask, + * Mod?Mask. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +unsigned int +TkMacButtonKeyState() +{ + unsigned int state = 0; + KeyMap theKeys; + + if (Button() & !gEatButtonUp) { + state |= Button1Mask; + } + + GetKeys(theKeys); + + if (theKeys[1] & 2) { + state |= LockMask; + } + + if (theKeys[1] & 1) { + state |= ShiftMask; + } + + if (theKeys[1] & 8) { + state |= ControlMask; + } + + if (theKeys[1] & 32768) { + state |= Mod1Mask; /* command key */ + } + + if (theKeys[1] & 4) { + state |= Mod2Mask; /* option key */ + } + + return state; +} + +/* + *---------------------------------------------------------------------- + * + * XGrabKeyboard -- + * + * Simulates a keyboard grab by setting the focus. + * + * Results: + * Always returns GrabSuccess. + * + * Side effects: + * Sets the keyboard focus to the specified window. + * + *---------------------------------------------------------------------- + */ + +int +XGrabKeyboard( + Display* display, + Window grab_window, + Bool owner_events, + int pointer_mode, + int keyboard_mode, + Time time) +{ + gKeyboardWinPtr = Tk_IdToWindow(display, grab_window); + return GrabSuccess; +} + +/* + *---------------------------------------------------------------------- + * + * XUngrabKeyboard -- + * + * Releases the simulated keyboard grab. + * + * Results: + * None. + * + * Side effects: + * Sets the keyboard focus back to the value before the grab. + * + *---------------------------------------------------------------------- + */ + +void +XUngrabKeyboard( + Display* display, + Time time) +{ + gKeyboardWinPtr = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * XQueryPointer -- + * + * Check the current state of the mouse. This is not a complete + * implementation of this function. It only computes the root + * coordinates and the current mask. + * + * Results: + * Sets root_x_return, root_y_return, and mask_return. Returns + * true on success. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Bool +XQueryPointer( + Display* display, + Window w, + Window* root_return, + Window* child_return, + int* root_x_return, + int* root_y_return, + int* win_x_return, + int* win_y_return, + unsigned int* mask_return) +{ + Point where; + + GetMouse(&where); + LocalToGlobal(&where); + *root_x_return = where.h; + *root_y_return = where.v; + *mask_return = TkMacButtonKeyState(); + return True; +} + +/* + *---------------------------------------------------------------------- + * + * TkMacGenerateTime -- + * + * Returns the total number of ticks from startup This function + * is used to generate the time of generated X events. + * + * Results: + * Returns the current time (ticks from startup). + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Time +TkMacGenerateTime() +{ + return (Time) LMGetTicks(); +} + +/* + *---------------------------------------------------------------------- + * + * TkMacConvertEvent -- + * + * This function converts a Macintosh event into zero or more + * Tcl events. + * + * Results: + * Returns 1 if event added to Tcl queue, 0 otherwse. + * + * Side effects: + * May add events to Tcl's event queue. + * + *---------------------------------------------------------------------- + */ + +int +TkMacConvertEvent( + EventRecord *eventPtr) +{ + WindowRef whichWindow; + Window window; + int eventFound = false; + + switch (eventPtr->what) { + case nullEvent: + case adjustCursorEvent: + if (GeneratePollingEvents()) { + eventFound = true; + } + break; + case updateEvt: + whichWindow = (WindowRef)eventPtr->message; + window = TkMacGetXWindow(whichWindow); + if (GenerateUpdateEvent(eventPtr, window)) { + eventFound = true; + } + break; + case mouseDown: + case mouseUp: + FindWindow(eventPtr->where, &whichWindow); + window = TkMacGetXWindow(whichWindow); + if (WindowManagerMouse(eventPtr, window)) { + eventFound = true; + } + break; + case autoKey: + case keyDown: + /* + * Handle menu-key events here. If it is *not* + * a menu key - just fall through to handle as a + * normal key event. + */ + if ((eventPtr->modifiers & cmdKey) == cmdKey) { + long menuResult; + int oldMode; + + oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); + menuResult = MenuKey(eventPtr->message & charCodeMask); + Tcl_SetServiceMode(oldMode); + + if (HiWord(menuResult) != 0) { + TkMacHandleMenuSelect(menuResult, false); + break; + } + } + case keyUp: + whichWindow = FrontWindow(); + window = TkMacGetXWindow(whichWindow); + eventFound |= GenerateKeyEvent(eventPtr, window); + break; + case activateEvt: + window = TkMacGetXWindow((WindowRef) eventPtr->message); + eventFound |= GenerateActivateEvents(eventPtr, window); + eventFound |= GenerateFocusEvent(eventPtr, window); + break; + case getFocusEvent: + eventPtr->modifiers |= activeFlag; + window = TkMacGetXWindow((WindowRef) eventPtr->message); + eventFound |= GenerateFocusEvent(eventPtr, window); + break; + case loseFocusEvent: + eventPtr->modifiers &= ~activeFlag; + window = TkMacGetXWindow((WindowRef) eventPtr->message); + eventFound |= GenerateFocusEvent(eventPtr, window); + break; + case kHighLevelEvent: + TkMacDoHLEvent(eventPtr); + /* TODO: should return true if events were placed on event queue. */ + break; + case osEvt: + /* + * Do clipboard conversion. + */ + switch ((eventPtr->message & osEvtMessageMask) >> 24) { + case mouseMovedMessage: + if (GeneratePollingEvents()) { + eventFound = true; + } + break; + case suspendResumeMessage: + if (!(eventPtr->message & resumeFlag)) { + TkSuspendClipboard(); + } + tkMacAppInFront = (eventPtr->message & resumeFlag); + break; + } + break; + case diskEvt: + /* + * Disk insertion. + */ + if (HiWord(eventPtr->message) != noErr) { + Point pt; + + DILoad(); + pt.v = pt.h = 120; /* parameter ignored in sys 7 */ + DIBadMount(pt, eventPtr->message); + DIUnload(); + } + break; + } + + return eventFound; +} + +/* + *---------------------------------------------------------------------- + * + * TkMacConvertTkEvent -- + * + * This function converts a Macintosh event into zero or more + * Tcl events. + * + * Results: + * Returns 1 if event added to Tcl queue, 0 otherwse. + * + * Side effects: + * May add events to Tcl's event queue. + * + *---------------------------------------------------------------------- + */ + +int +TkMacConvertTkEvent( + EventRecord *eventPtr, + Window window) +{ + int eventFound = false; + Point where; + + switch (eventPtr->what) { + case nullEvent: + case adjustCursorEvent: + if (GeneratePollingEvents2(window)) { + eventFound = true; + } + break; + case updateEvt: + if (GenerateUpdateEvent(eventPtr, window)) { + eventFound = true; + } + break; + case mouseDown: + case mouseUp: + GetMouse(&where); + LocalToGlobal(&where); + eventFound |= TkGenerateButtonEvent(where.h, where.v, + window, TkMacButtonKeyState()); + break; + case autoKey: + case keyDown: + /* + * Handle menu-key events here. If it is *not* + * a menu key - just fall through to handle as a + * normal key event. + */ + if ((eventPtr->modifiers & cmdKey) == cmdKey) { + long menuResult = MenuKey(eventPtr->message & charCodeMask); + + if (HiWord(menuResult) != 0) { + TkMacHandleMenuSelect(menuResult, false); + break; + } + } + case keyUp: + eventFound |= GenerateKeyEvent(eventPtr, window); + break; + case activateEvt: + eventFound |= GenerateActivateEvents(eventPtr, window); + eventFound |= GenerateFocusEvent(eventPtr, window); + break; + case getFocusEvent: + eventPtr->modifiers |= activeFlag; + eventFound |= GenerateFocusEvent(eventPtr, window); + break; + case loseFocusEvent: + eventPtr->modifiers &= ~activeFlag; + eventFound |= GenerateFocusEvent(eventPtr, window); + break; + case kHighLevelEvent: + TkMacDoHLEvent(eventPtr); + /* TODO: should return true if events were placed on event queue. */ + break; + case osEvt: + /* + * Do clipboard conversion. + */ + switch ((eventPtr->message & osEvtMessageMask) >> 24) { + case mouseMovedMessage: + if (GeneratePollingEvents2(window)) { + eventFound = true; + } + break; + case suspendResumeMessage: + if (!(eventPtr->message & resumeFlag)) { + TkSuspendClipboard(); + } + tkMacAppInFront = (eventPtr->message & resumeFlag); + break; + } + break; + case diskEvt: + /* + * Disk insertion. + */ + if (HiWord(eventPtr->message) != noErr) { + Point pt; + + DILoad(); + pt.v = pt.h = 120; /* parameter ignored in sys 7 */ + DIBadMount(pt, eventPtr->message); + DIUnload(); + } + break; + } + + return eventFound; +} + +/* + *---------------------------------------------------------------------- + * + * CheckEventsAvail -- + * + * Checks to see if events are available on the Macintosh queue. + * This function looks for both queued events (eg. key & button) + * and generated events (update). + * + * Results: + * True is events exist, false otherwise. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +CheckEventsAvail() +{ + QHdrPtr evPtr; + WindowPeek macWinPtr; + + evPtr = GetEvQHdr(); + if (evPtr->qHead != NULL) { + return true; + } + + macWinPtr = (WindowPeek) FrontWindow(); + while (macWinPtr != NULL) { + if (!EmptyRgn(macWinPtr->updateRgn)) { + return true; + } + macWinPtr = macWinPtr->nextWindow; + } + return false; +} + +/* + *---------------------------------------------------------------------- + * + * TkpSetCapture -- + * + * This function captures the mouse so that all future events + * will be reported to this window, even if the mouse is outside + * the window. If the specified window is NULL, then the mouse + * is released. + * + * Results: + * None. + * + * Side effects: + * Sets the capture flag and captures the mouse. + * + *---------------------------------------------------------------------- + */ + +void +TkpSetCapture( + TkWindow *winPtr) /* Capture window, or NULL. */ +{ + while ((winPtr != NULL) && !Tk_IsTopLevel(winPtr)) { + winPtr = winPtr->parentPtr; + } + gGrabWinPtr = (Tk_Window) winPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkMacWindowOffset -- + * + * Determines the x and y offset from the orgin of the toplevel + * window dressing (the structure region, ie. title bar) and the + * orgin of the content area. + * + * Results: + * The x & y offset in pixels. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkMacWindowOffset( + WindowRef wRef, + int *xOffset, + int *yOffset) +{ + OSErr err = noErr; + WindowPeek wPeek = (WindowPeek) wRef; + RgnHandle strucRgn = wPeek->strucRgn; + RgnHandle contRgn = wPeek->contRgn; + Rect strucRect, contRect; + + if (!EmptyRgn(strucRgn) && !EmptyRgn(contRgn)) { + strucRect = (**strucRgn).rgnBBox; + contRect = (**contRgn).rgnBBox; + } else { + /* + * The current window's regions are not up to date. + * Probably because the window isn't visable. What we + * will do is save the old regions, have the window calculate + * what the regions should be, and then restore it self. + */ + strucRgn = NewRgn( ); + contRgn = NewRgn( ); + + if (!strucRgn || !contRgn) { + err = MemError( ); + } else { + CopyRgn(wPeek->strucRgn, strucRgn); + CopyRgn(wPeek->contRgn, contRgn); + + if (!(err = TellWindowDefProcToCalcRegions(wRef))) { + strucRect = (**(wPeek->strucRgn)).rgnBBox; + contRect = (**(wPeek->contRgn)).rgnBBox; + } + + CopyRgn(strucRgn, wPeek->strucRgn); + CopyRgn(contRgn, wPeek->contRgn); + } + + if (contRgn) { + DisposeRgn(contRgn); + } + + if (strucRgn) { + DisposeRgn(strucRgn); + } + } + + if (!err) { + *xOffset = contRect.left - strucRect.left; + *yOffset = contRect.top - strucRect.top; + } else { + *xOffset = 0; + *yOffset = 0; + } + + return; +} + +/* + *---------------------------------------------------------------------- + * + * TellWindowDefProcToCalcRegions -- + * + * Force a Macintosh window to recalculate it's content and + * structure regions. + * + * Results: + * An OS error. + * + * Side effects: + * The windows content and structure regions may be updated. + * + *---------------------------------------------------------------------- + */ + +static OSErr +TellWindowDefProcToCalcRegions( + WindowRef wRef) +{ + OSErr err = noErr; + SInt8 hState; + Handle wdef = ((WindowPeek) wRef)->windowDefProc; + + /* + * Load and lock the window definition procedure for + * the window. + */ + hState = HGetState(wdef); + if (!(err = MemError())) { + LoadResource(wdef); + if (!(err = ResError())) { + MoveHHi(wdef); + err = MemError(); + if (err == memLockedErr) { + err = noErr; + } else if (!err) { + HLock(wdef); + err = MemError(); + } + } + } + + /* + * Assuming there are no errors we now call the window definition + * procedure to tell it to calculate the regions for the window. + */ + + if (err == noErr) { + (void) CallWindowDefProc((UniversalProcPtr) *wdef, + GetWVariant(wRef), wRef, wCalcRgns, 0); + + HSetState(wdef, hState); + if (!err) { + err = MemError(); + } + } + + return err; +} + +/* + *---------------------------------------------------------------------- + * + * BringWindowForward -- + * + * Bring this background window to the front. We also set state + * so Tk thinks the button is currently up. + * + * Results: + * None. + * + * Side effects: + * The window is brought forward. + * + *---------------------------------------------------------------------- + */ + +static void +BringWindowForward( + WindowRef wRef) +{ + SelectWindow(wRef); +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetMS -- + * + * Return a relative time in milliseconds. It doesn't matter + * when the epoch was. + * + * Results: + * Number of milliseconds. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +unsigned long +TkpGetMS() +{ + long long * int64Ptr; + UnsignedWide micros; + + Microseconds(µs); + int64Ptr = (long long *) µs; + + /* + * We need 64 bit math to do this. This is available in CW 11 + * and on. Other's will need to use a different scheme. + */ + + *int64Ptr /= 1000; + + return (long) *int64Ptr; +} diff --git a/mac/tkMacWm.c b/mac/tkMacWm.c new file mode 100644 index 0000000..56c4b8a --- /dev/null +++ b/mac/tkMacWm.c @@ -0,0 +1,4213 @@ +/* + * tkMacWm.c -- + * + * This module takes care of the interactions between a Tk-based + * application and the window manager. Among other things, it + * implements the "wm" command and passes geometry information + * to the window manager. + * + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacWm.c 1.72 97/10/29 13:27:30 + */ + +#include <Gestalt.h> +#include <QDOffscreen.h> +#include <Windows.h> +#include <ToolUtils.h> + +#include "tkPort.h" +#include "tkInt.h" +#include "tkMacInt.h" +#include <errno.h> +#include "tkScrollbar.h" + +/* + * If HAVE_APPEARANCE is defined in MW_TkHeader.pch then we must have the + * Appearance manager header & library. If so we can use these new API's to + * have the iconify code do the right thing. + */ + +#ifdef HAVE_APPEARANCE +# include <Appearance.h> +#endif + +/* + * A data structure of the following type holds information for + * each window manager protocol (such as WM_DELETE_WINDOW) for + * which a handler (i.e. a Tcl command) has been defined for a + * particular top-level window. + */ + +typedef struct ProtocolHandler { + Atom protocol; /* Identifies the protocol. */ + struct ProtocolHandler *nextPtr; + /* Next in list of protocol handlers for + * the same top-level window, or NULL for + * end of list. */ + Tcl_Interp *interp; /* Interpreter in which to invoke command. */ + char command[4]; /* Tcl command to invoke when a client + * message for this protocol arrives. + * The actual size of the structure varies + * to accommodate the needs of the actual + * command. THIS MUST BE THE LAST FIELD OF + * THE STRUCTURE. */ +} ProtocolHandler; + +#define HANDLER_SIZE(cmdLength) \ +((unsigned) (sizeof(ProtocolHandler) - 3 + cmdLength)) + +/* + * A data structure of the following type holds window-manager-related + * information for each top-level window in an application. + */ + +typedef struct TkWmInfo { + TkWindow *winPtr; /* Pointer to main Tk information for + * this window. */ + Window reparent; /* If the window has been reparented, this + * gives the ID of the ancestor of the window + * that is a child of the root window (may + * not be window's immediate parent). If + * the window isn't reparented, this has the + * value None. */ + Tk_Uid titleUid; /* Title to display in window caption. If + * NULL, use name of widget. */ + Tk_Uid iconName; /* Name to display in icon. */ + Window master; /* Master window for TRANSIENT_FOR property, + * or None. */ + XWMHints hints; /* Various pieces of information for + * window manager. */ + char *leaderName; /* Path name of leader of window group + * (corresponds to hints.window_group). + * Malloc-ed. Note: this field doesn't + * get updated if leader is destroyed. */ + char *masterWindowName; /* Path name of window specified as master + * in "wm transient" command, or NULL. + * Malloc-ed. Note: this field doesn't + * get updated if masterWindowName is + * destroyed. */ + Tk_Window icon; /* Window to use as icon for this window, + * or NULL. */ + Tk_Window iconFor; /* Window for which this window is icon, or + * NULL if this isn't an icon for anyone. */ + + /* + * Information used to construct an XSizeHints structure for + * the window manager: + */ + + int sizeHintsFlags; /* Flags word for XSizeHints structure. + * If the PBaseSize flag is set then the + * window is gridded; otherwise it isn't + * gridded. */ + int minWidth, minHeight; /* Minimum dimensions of window, in + * grid units, not pixels. */ + int maxWidth, maxHeight; /* Maximum dimensions of window, in + * grid units, not pixels. */ + Tk_Window gridWin; /* Identifies the window that controls + * gridding for this top-level, or NULL if + * the top-level isn't currently gridded. */ + int widthInc, heightInc; /* Increments for size changes (# pixels + * per step). */ + struct { + int x; /* numerator */ + int y; /* denominator */ + } minAspect, maxAspect; /* Min/max aspect ratios for window. */ + int reqGridWidth, reqGridHeight; + /* The dimensions of the window (in + * grid units) requested through + * the geometry manager. */ + int gravity; /* Desired window gravity. */ + + /* + * Information used to manage the size and location of a window. + */ + + int width, height; /* Desired dimensions of window, specified + * in grid units. These values are + * set by the "wm geometry" command and by + * ConfigureNotify events (for when wm + * resizes window). -1 means user hasn't + * requested dimensions. */ + int x, y; /* Desired X and Y coordinates for window. + * These values are set by "wm geometry", + * plus by ConfigureNotify events (when wm + * moves window). These numbers are + * different than the numbers stored in + * winPtr->changes because (a) they could be + * measured from the right or bottom edge + * of the screen (see WM_NEGATIVE_X and + * WM_NEGATIVE_Y flags) and (b) if the window + * has been reparented then they refer to the + * parent rather than the window itself. */ + int parentWidth, parentHeight; + /* Width and height of reparent, in pixels + * *including border*. If window hasn't been + * reparented then these will be the outer + * dimensions of the window, including + * border. */ + int xInParent, yInParent; /* Offset of window within reparent, measured + * from upper-left outer corner of parent's + * border to upper-left outer corner of child's + * border. If not reparented then these are + * zero. */ + int configWidth, configHeight; + /* Dimensions passed to last request that we + * issued to change geometry of window. Used + * to eliminate redundant resize operations. */ + + /* + * Information about the virtual root window for this top-level, + * if there is one. + */ + + Window vRoot; /* Virtual root window for this top-level, + * or None if there is no virtual root + * window (i.e. just use the screen's root). */ + int vRootX, vRootY; /* Position of the virtual root inside the + * root window. If the WM_VROOT_OFFSET_STALE + * flag is set then this information may be + * incorrect and needs to be refreshed from + * the X server. If vRoot is None then these + * values are both 0. */ + unsigned int vRootWidth, vRootHeight; + /* Dimensions of the virtual root window. + * If vRoot is None, gives the dimensions + * of the containing screen. This information + * is never stale, even though vRootX and + * vRootY can be. */ + + /* + * List of children of the toplevel which have private colormaps. + */ + + TkWindow **cmapList; /* Array of window with private colormaps. */ + int cmapCount; /* Number of windows in array. */ + + /* + * Miscellaneous information. + */ + + ProtocolHandler *protPtr; /* First in list of protocol handlers for + * this window (NULL means none). */ + int cmdArgc; /* Number of elements in cmdArgv below. */ + char **cmdArgv; /* Array of strings to store in the + * WM_COMMAND property. NULL means nothing + * available. */ + char *clientMachine; /* String to store in WM_CLIENT_MACHINE + * property, or NULL. */ + int flags; /* Miscellaneous flags, defined below. */ + + /* + * Macintosh information. + */ + int style; /* Native window style. */ + TkWindow *scrollWinPtr; /* Ptr to scrollbar handling grow widget. */ +} WmInfo; + + +/* + * Flag values for WmInfo structures: + * + * WM_NEVER_MAPPED - non-zero means window has never been + * mapped; need to update all info when + * window is first mapped. + * WM_UPDATE_PENDING - non-zero means a call to UpdateGeometryInfo + * has already been scheduled for this + * window; no need to schedule another one. + * WM_NEGATIVE_X - non-zero means x-coordinate is measured in + * pixels from right edge of screen, rather + * than from left edge. + * WM_NEGATIVE_Y - non-zero means y-coordinate is measured in + * pixels up from bottom of screen, rather than + * down from top. + * WM_UPDATE_SIZE_HINTS - non-zero means that new size hints need to be + * propagated to window manager. + * WM_SYNC_PENDING - set to non-zero while waiting for the window + * manager to respond to some state change. + * WM_VROOT_OFFSET_STALE - non-zero means that (x,y) offset information + * about the virtual root window is stale and + * needs to be fetched fresh from the X server. + * WM_ABOUT_TO_MAP - non-zero means that the window is about to + * be mapped by TkWmMapWindow. This is used + * by UpdateGeometryInfo to modify its behavior. + * WM_MOVE_PENDING - non-zero means the application has requested + * a new position for the window, but it hasn't + * been reflected through the window manager + * yet. + * WM_COLORMAPS_EXPLICIT - non-zero means the colormap windows were + * set explicitly via "wm colormapwindows". + * WM_ADDED_TOPLEVEL_COLORMAP - non-zero means that when "wm colormapwindows" + * was called the top-level itself wasn't + * specified, so we added it implicitly at + * the end of the list. + * WM_WIDTH_NOT_RESIZABLE - non-zero means that we're not supposed to + * allow the user to change the width of the + * window (controlled by "wm resizable" + * command). + * WM_HEIGHT_NOT_RESIZABLE - non-zero means that we're not supposed to + * allow the user to change the height of the + * window (controlled by "wm resizable" + * command). + */ + +#define WM_NEVER_MAPPED 1 +#define WM_UPDATE_PENDING 2 +#define WM_NEGATIVE_X 4 +#define WM_NEGATIVE_Y 8 +#define WM_UPDATE_SIZE_HINTS 0x10 +#define WM_SYNC_PENDING 0x20 +#define WM_VROOT_OFFSET_STALE 0x40 +#define WM_ABOUT_TO_MAP 0x100 +#define WM_MOVE_PENDING 0x200 +#define WM_COLORMAPS_EXPLICIT 0x400 +#define WM_ADDED_TOPLEVEL_COLORMAP 0x800 +#define WM_WIDTH_NOT_RESIZABLE 0x1000 +#define WM_HEIGHT_NOT_RESIZABLE 0x2000 + +/* + * This is a list of all of the toplevels that have been mapped so far. It is + * used by the menu code to inval windows that were damaged by menus, and will + * eventually also be used to keep track of floating windows. + */ + +TkMacWindowList *tkMacWindowListPtr = NULL; + +/* + * The variable below is used to enable or disable tracing in this + * module. If tracing is enabled, then information is printed on + * standard output about interesting interactions with the window + * manager. + */ + +static int wmTracing = 0; + +/* + * The following structure is the official type record for geometry + * management of top-level windows. + */ + +static void TopLevelReqProc _ANSI_ARGS_((ClientData dummy, + Tk_Window tkwin)); + +static Tk_GeomMgr wmMgrType = { + "wm", /* name */ + TopLevelReqProc, /* requestProc */ + (Tk_GeomLostSlaveProc *) NULL, /* lostSlaveProc */ +}; + +/* + * Hash table for Mac Window -> TkWindow mapping. + */ + +static Tcl_HashTable windowTable; +static int windowHashInit = false; + +void MacMoveWindow(WindowRef window, int x, int y); + +/* + * Forward declarations for procedures defined in this file: + */ + +static int HaveAppearance _ANSI_ARGS_((void)); +static void InitialWindowBounds _ANSI_ARGS_((TkWindow *winPtr, + Rect *geometry)); +static int ParseGeometry _ANSI_ARGS_((Tcl_Interp *interp, + char *string, TkWindow *winPtr)); +static void TopLevelEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void TopLevelReqProc _ANSI_ARGS_((ClientData dummy, + Tk_Window tkwin)); +static void UpdateGeometryInfo _ANSI_ARGS_(( + ClientData clientData)); +static void UpdateSizeHints _ANSI_ARGS_((TkWindow *winPtr)); +static void UpdateVRootGeometry _ANSI_ARGS_((WmInfo *wmPtr)); + +/* + *-------------------------------------------------------------- + * + * TkWmNewWindow -- + * + * This procedure is invoked whenever a new top-level + * window is created. Its job is to initialize the WmInfo + * structure for the window. + * + * Results: + * None. + * + * Side effects: + * A WmInfo structure gets allocated and initialized. + * + *-------------------------------------------------------------- + */ + +void +TkWmNewWindow( + TkWindow *winPtr) /* Newly-created top-level window. */ +{ + register WmInfo *wmPtr; + + wmPtr = (WmInfo *) ckalloc(sizeof(WmInfo)); + wmPtr->winPtr = winPtr; + wmPtr->reparent = None; + wmPtr->titleUid = NULL; + wmPtr->iconName = NULL; + wmPtr->master = None; + wmPtr->hints.flags = InputHint | StateHint; + wmPtr->hints.input = True; + wmPtr->hints.initial_state = NormalState; + wmPtr->hints.icon_pixmap = None; + wmPtr->hints.icon_window = None; + wmPtr->hints.icon_x = wmPtr->hints.icon_y = 0; + wmPtr->hints.icon_mask = None; + wmPtr->hints.window_group = None; + wmPtr->leaderName = NULL; + wmPtr->masterWindowName = NULL; + wmPtr->icon = NULL; + wmPtr->iconFor = NULL; + wmPtr->sizeHintsFlags = 0; + wmPtr->minWidth = wmPtr->minHeight = 1; + + /* + * Default the maximum dimensions to the size of the display, minus + * a guess about how space is needed for window manager decorations. + */ + + wmPtr->maxWidth = DisplayWidth(winPtr->display, winPtr->screenNum) - 15; + wmPtr->maxHeight = DisplayHeight(winPtr->display, winPtr->screenNum) - 30; + wmPtr->gridWin = NULL; + wmPtr->widthInc = wmPtr->heightInc = 1; + wmPtr->minAspect.x = wmPtr->minAspect.y = 1; + wmPtr->maxAspect.x = wmPtr->maxAspect.y = 1; + wmPtr->reqGridWidth = wmPtr->reqGridHeight = -1; + wmPtr->gravity = NorthWestGravity; + wmPtr->width = -1; + wmPtr->height = -1; + wmPtr->x = winPtr->changes.x; + wmPtr->y = winPtr->changes.y; + wmPtr->parentWidth = winPtr->changes.width + + 2*winPtr->changes.border_width; + wmPtr->parentHeight = winPtr->changes.height + + 2*winPtr->changes.border_width; + wmPtr->xInParent = 0; + wmPtr->yInParent = 0; + wmPtr->cmapList = NULL; + wmPtr->cmapCount = 0; + wmPtr->configWidth = -1; + wmPtr->configHeight = -1; + wmPtr->vRoot = None; + wmPtr->protPtr = NULL; + wmPtr->cmdArgv = NULL; + wmPtr->clientMachine = NULL; + wmPtr->flags = WM_NEVER_MAPPED; + wmPtr->style = zoomDocProc; + wmPtr->scrollWinPtr = NULL; + winPtr->wmInfoPtr = wmPtr; + + UpdateVRootGeometry(wmPtr); + + /* + * Tk must monitor structure events for top-level windows, in order + * to detect size and position changes caused by window managers. + */ + + Tk_CreateEventHandler((Tk_Window) winPtr, StructureNotifyMask, + TopLevelEventProc, (ClientData) winPtr); + + /* + * Arrange for geometry requests to be reflected from the window + * to the window manager. + */ + + Tk_ManageGeometry((Tk_Window) winPtr, &wmMgrType, (ClientData) 0); +} + +/* + *-------------------------------------------------------------- + * + * TkWmMapWindow -- + * + * This procedure is invoked to map a top-level window. This + * module gets a chance to update all window-manager-related + * information in properties before the window manager sees + * the map event and checks the properties. It also gets to + * decide whether or not to even map the window after all. + * + * Results: + * None. + * + * Side effects: + * Properties of winPtr may get updated to provide up-to-date + * information to the window manager. The window may also get + * mapped, but it may not be if this procedure decides that + * isn't appropriate (e.g. because the window is withdrawn). + * + *-------------------------------------------------------------- + */ + +void +TkWmMapWindow( + TkWindow *winPtr) /* Top-level window that's about to + * be mapped. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + Point where = {0, 0}; + int xOffset, yOffset; + int firstMap = false; + MacDrawable *macWin; + + if (wmPtr->flags & WM_NEVER_MAPPED) { + wmPtr->flags &= ~WM_NEVER_MAPPED; + firstMap = true; + + /* + * Create the underlying Mac window for this Tk window. + */ + macWin = (MacDrawable *) winPtr->window; + if (!TkMacHostToplevelExists(winPtr)) { + TkMacMakeRealWindowExist(winPtr); + } + + /* + * Generate configure event when we first map the window. + */ + LocalToGlobal(&where); + TkMacWindowOffset((WindowRef) TkMacGetDrawablePort((Drawable) macWin), + &xOffset, &yOffset); + where.h -= xOffset; + where.v -= yOffset; + TkGenWMConfigureEvent((Tk_Window) winPtr, + where.h, where.v, -1, -1, TK_LOCATION_CHANGED); + + /* + * This is the first time this window has ever been mapped. + * Store all the window-manager-related information for the + * window. + */ + + if (wmPtr->titleUid == NULL) { + wmPtr->titleUid = winPtr->nameUid; + } + + if (!Tk_IsEmbedded(winPtr)) { + TkSetWMName(winPtr, wmPtr->titleUid); + } + + TkWmSetClass(winPtr); + + if (wmPtr->iconName != NULL) { + XSetIconName(winPtr->display, winPtr->window, wmPtr->iconName); + } + + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + } + if (wmPtr->hints.initial_state == WithdrawnState) { + return; + } + + /* + * TODO: we need to display a window if it's iconic on creation. + */ + + if (wmPtr->hints.initial_state == IconicState) { + return; + } + + /* + * Update geometry information. + */ + wmPtr->flags |= WM_ABOUT_TO_MAP; + if (wmPtr->flags & WM_UPDATE_PENDING) { + Tk_CancelIdleCall(UpdateGeometryInfo, (ClientData) winPtr); + } + UpdateGeometryInfo((ClientData) winPtr); + wmPtr->flags &= ~WM_ABOUT_TO_MAP; + + /* + * Map the window. + */ + + XMapWindow(winPtr->display, winPtr->window); + + /* + * Now that the window is visable we can determine the offset + * from the window's content orgin to the window's decorative + * orgin (structure orgin). + */ + TkMacWindowOffset((WindowRef) TkMacGetDrawablePort(Tk_WindowId(winPtr)), + &wmPtr->xInParent, &wmPtr->yInParent); +} + +/* + *-------------------------------------------------------------- + * + * TkWmUnmapWindow -- + * + * This procedure is invoked to unmap a top-level window. + * On the Macintosh all we do is call XUnmapWindow. + * + * Results: + * None. + * + * Side effects: + * Unmaps the window. + * + *-------------------------------------------------------------- + */ + +void +TkWmUnmapWindow( + TkWindow *winPtr) /* Top-level window that's about to + * be mapped. */ +{ + XUnmapWindow(winPtr->display, winPtr->window); +} + +/* + *-------------------------------------------------------------- + * + * TkWmDeadWindow -- + * + * This procedure is invoked when a top-level window is + * about to be deleted. It cleans up the wm-related data + * structures for the window. + * + * Results: + * None. + * + * Side effects: + * The WmInfo structure for winPtr gets freed up. + * + *-------------------------------------------------------------- + */ + +void +TkWmDeadWindow(winPtr) + TkWindow *winPtr; /* Top-level window that's being deleted. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + WmInfo *wmPtr2; + + if (wmPtr == NULL) { + return; + } + if (wmPtr->hints.flags & IconPixmapHint) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_pixmap); + } + if (wmPtr->hints.flags & IconMaskHint) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_mask); + } + if (wmPtr->leaderName != NULL) { + ckfree(wmPtr->leaderName); + } + if (wmPtr->masterWindowName != NULL) { + ckfree(wmPtr->masterWindowName); + } + if (wmPtr->icon != NULL) { + wmPtr2 = ((TkWindow *) wmPtr->icon)->wmInfoPtr; + wmPtr2->iconFor = NULL; + } + if (wmPtr->iconFor != NULL) { + wmPtr2 = ((TkWindow *) wmPtr->iconFor)->wmInfoPtr; + wmPtr2->icon = NULL; + wmPtr2->hints.flags &= ~IconWindowHint; + } + while (wmPtr->protPtr != NULL) { + ProtocolHandler *protPtr; + + protPtr = wmPtr->protPtr; + wmPtr->protPtr = protPtr->nextPtr; + Tcl_EventuallyFree((ClientData) protPtr, TCL_DYNAMIC); + } + if (wmPtr->cmdArgv != NULL) { + ckfree((char *) wmPtr->cmdArgv); + } + if (wmPtr->clientMachine != NULL) { + ckfree((char *) wmPtr->clientMachine); + } + if (wmPtr->flags & WM_UPDATE_PENDING) { + Tk_CancelIdleCall(UpdateGeometryInfo, (ClientData) winPtr); + } + ckfree((char *) wmPtr); + winPtr->wmInfoPtr = NULL; +} + +/* + *-------------------------------------------------------------- + * + * TkWmSetClass -- + * + * This procedure is invoked whenever a top-level window's + * class is changed. If the window has been mapped then this + * procedure updates the window manager property for the + * class. If the window hasn't been mapped, the update is + * deferred until just before the first mapping. + * + * Results: + * None. + * + * Side effects: + * A window property may get updated. + * + *-------------------------------------------------------------- + */ + +void +TkWmSetClass( + TkWindow *winPtr) /* Newly-created top-level window. */ +{ + return; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_WmCmd -- + * + * This procedure is invoked to process the "wm" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +Tk_WmCmd( + ClientData clientData, /* Main window associated with + * interpreter. */ + Tcl_Interp *interp, /* Current interpreter. */ + int argc, /* Number of arguments. */ + char **argv) /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + TkWindow *winPtr; + register WmInfo *wmPtr; + int c; + size_t length; + + if (argc < 2) { + wrongNumArgs: + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option window ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 't') && (strncmp(argv[1], "tracing", length) == 0) + && (length >= 3)) { + if ((argc != 2) && (argc != 3)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " tracing ?boolean?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 2) { + interp->result = (wmTracing) ? "on" : "off"; + return TCL_OK; + } + return Tcl_GetBoolean(interp, argv[2], &wmTracing); + } + + if (argc < 3) { + goto wrongNumArgs; + } + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[2], tkwin); + if (winPtr == NULL) { + return TCL_ERROR; + } + if (!(winPtr->flags & TK_TOP_LEVEL)) { + Tcl_AppendResult(interp, "window \"", winPtr->pathName, + "\" isn't a top-level window", (char *) NULL); + return TCL_ERROR; + } + wmPtr = winPtr->wmInfoPtr; + if ((c == 'a') && (strncmp(argv[1], "aspect", length) == 0)) { + int numer1, denom1, numer2, denom2; + + if ((argc != 3) && (argc != 7)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " aspect window ?minNumer minDenom ", + "maxNumer maxDenom?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & PAspect) { + sprintf(interp->result, "%d %d %d %d", wmPtr->minAspect.x, + wmPtr->minAspect.y, wmPtr->maxAspect.x, + wmPtr->maxAspect.y); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->sizeHintsFlags &= ~PAspect; + } else { + if ((Tcl_GetInt(interp, argv[3], &numer1) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &denom1) != TCL_OK) + || (Tcl_GetInt(interp, argv[5], &numer2) != TCL_OK) + || (Tcl_GetInt(interp, argv[6], &denom2) != TCL_OK)) { + return TCL_ERROR; + } + if ((numer1 <= 0) || (denom1 <= 0) || (numer2 <= 0) || + (denom2 <= 0)) { + interp->result = "aspect number can't be <= 0"; + return TCL_ERROR; + } + wmPtr->minAspect.x = numer1; + wmPtr->minAspect.y = denom1; + wmPtr->maxAspect.x = numer2; + wmPtr->maxAspect.y = denom2; + wmPtr->sizeHintsFlags |= PAspect; + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 'c') && (strncmp(argv[1], "client", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " client window ?name?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->clientMachine != NULL) { + interp->result = wmPtr->clientMachine; + } + return TCL_OK; + } + if (argv[3][0] == 0) { + if (wmPtr->clientMachine != NULL) { + ckfree((char *) wmPtr->clientMachine); + wmPtr->clientMachine = NULL; + } + return TCL_OK; + } + if (wmPtr->clientMachine != NULL) { + ckfree((char *) wmPtr->clientMachine); + } + wmPtr->clientMachine = (char *) + ckalloc((unsigned) (strlen(argv[3]) + 1)); + strcpy(wmPtr->clientMachine, argv[3]); + } else if ((c == 'c') && (strncmp(argv[1], "colormapwindows", length) == 0) + && (length >= 3)) { + TkWindow **cmapList; + TkWindow *winPtr2; + int i, windowArgc, gotToplevel; + char **windowArgv; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " colormapwindows window ?windowList?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + Tk_MakeWindowExist((Tk_Window) winPtr); + for (i = 0; i < wmPtr->cmapCount; i++) { + if ((i == (wmPtr->cmapCount-1)) + && (wmPtr->flags & WM_ADDED_TOPLEVEL_COLORMAP)) { + break; + } + Tcl_AppendElement(interp, wmPtr->cmapList[i]->pathName); + } + return TCL_OK; + } + if (Tcl_SplitList(interp, argv[3], &windowArgc, &windowArgv) + != TCL_OK) { + return TCL_ERROR; + } + cmapList = (TkWindow **) ckalloc((unsigned) + ((windowArgc+1)*sizeof(TkWindow*))); + for (i = 0; i < windowArgc; i++) { + winPtr2 = (TkWindow *) Tk_NameToWindow(interp, windowArgv[i], + tkwin); + if (winPtr2 == NULL) { + ckfree((char *) cmapList); + ckfree((char *) windowArgv); + return TCL_ERROR; + } + if (winPtr2 == winPtr) { + gotToplevel = 1; + } + if (winPtr2->window == None) { + Tk_MakeWindowExist((Tk_Window) winPtr2); + } + cmapList[i] = winPtr2; + } + if (!gotToplevel) { + wmPtr->flags |= WM_ADDED_TOPLEVEL_COLORMAP; + cmapList[windowArgc] = winPtr; + windowArgc++; + } else { + wmPtr->flags &= ~WM_ADDED_TOPLEVEL_COLORMAP; + } + wmPtr->flags |= WM_COLORMAPS_EXPLICIT; + if (wmPtr->cmapList != NULL) { + ckfree((char *)wmPtr->cmapList); + } + wmPtr->cmapList = cmapList; + wmPtr->cmapCount = windowArgc; + ckfree((char *) windowArgv); + + /* + * On the Macintosh all of this is just an excercise + * in compatability as we don't support colormaps. If + * we did they would be installed here. + */ + + return TCL_OK; + } else if ((c == 'c') && (strncmp(argv[1], "command", length) == 0) + && (length >= 3)) { + int cmdArgc; + char **cmdArgv; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " command window ?value?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->cmdArgv != NULL) { + interp->result = Tcl_Merge(wmPtr->cmdArgc, wmPtr->cmdArgv); + interp->freeProc = (Tcl_FreeProc *) free; + } + return TCL_OK; + } + if (argv[3][0] == 0) { + if (wmPtr->cmdArgv != NULL) { + ckfree((char *) wmPtr->cmdArgv); + wmPtr->cmdArgv = NULL; + } + return TCL_OK; + } + if (Tcl_SplitList(interp, argv[3], &cmdArgc, &cmdArgv) != TCL_OK) { + return TCL_ERROR; + } + if (wmPtr->cmdArgv != NULL) { + ckfree((char *) wmPtr->cmdArgv); + } + wmPtr->cmdArgc = cmdArgc; + wmPtr->cmdArgv = cmdArgv; + } else if ((c == 'd') && (strncmp(argv[1], "deiconify", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " deiconify window\"", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + Tcl_AppendResult(interp, "can't deiconify ", argv[2], + ": it is an icon for ", winPtr->pathName, (char *) NULL); + return TCL_ERROR; + } + if (winPtr->flags & TK_EMBEDDED) { + Tcl_AppendResult(interp, "can't deiconify ", winPtr->pathName, + ": it is an embedded window", (char *) NULL); + return TCL_ERROR; + } + + /* + * TODO: may not want to call this function - look at Map events gened. + */ + + TkpWmSetState(winPtr, NormalState); + } else if ((c == 'f') && (strncmp(argv[1], "focusmodel", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " focusmodel window ?active|passive?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + interp->result = wmPtr->hints.input ? "passive" : "active"; + return TCL_OK; + } + c = argv[3][0]; + length = strlen(argv[3]); + if ((c == 'a') && (strncmp(argv[3], "active", length) == 0)) { + wmPtr->hints.input = False; + } else if ((c == 'p') && (strncmp(argv[3], "passive", length) == 0)) { + wmPtr->hints.input = True; + } else { + Tcl_AppendResult(interp, "bad argument \"", argv[3], + "\": must be active or passive", (char *) NULL); + return TCL_ERROR; + } + } else if ((c == 'f') && (strncmp(argv[1], "frame", length) == 0) + && (length >= 2)) { + Window window; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " frame window\"", (char *) NULL); + return TCL_ERROR; + } + window = wmPtr->reparent; + if (window == None) { + window = Tk_WindowId((Tk_Window) winPtr); + } + sprintf(interp->result, "0x%x", (unsigned int) window); + } else if ((c == 'g') && (strncmp(argv[1], "geometry", length) == 0) + && (length >= 2)) { + char xSign, ySign; + int width, height; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " geometry window ?newGeometry?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + xSign = (wmPtr->flags & WM_NEGATIVE_X) ? '-' : '+'; + ySign = (wmPtr->flags & WM_NEGATIVE_Y) ? '-' : '+'; + if (wmPtr->gridWin != NULL) { + width = wmPtr->reqGridWidth + (winPtr->changes.width + - winPtr->reqWidth)/wmPtr->widthInc; + height = wmPtr->reqGridHeight + (winPtr->changes.height + - winPtr->reqHeight)/wmPtr->heightInc; + } else { + width = winPtr->changes.width; + height = winPtr->changes.height; + } + sprintf(interp->result, "%dx%d%c%d%c%d", width, height, + xSign, wmPtr->x, ySign, wmPtr->y); + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->width = -1; + wmPtr->height = -1; + goto updateGeom; + } + return ParseGeometry(interp, argv[3], winPtr); + } else if ((c == 'g') && (strncmp(argv[1], "grid", length) == 0) + && (length >= 3)) { + int reqWidth, reqHeight, widthInc, heightInc; + + if ((argc != 3) && (argc != 7)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " grid window ?baseWidth baseHeight ", + "widthInc heightInc?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & PBaseSize) { + sprintf(interp->result, "%d %d %d %d", wmPtr->reqGridWidth, + wmPtr->reqGridHeight, wmPtr->widthInc, + wmPtr->heightInc); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + /* + * Turn off gridding and reset the width and height + * to make sense as ungridded numbers. + */ + + wmPtr->sizeHintsFlags &= ~(PBaseSize|PResizeInc); + if (wmPtr->width != -1) { + wmPtr->width = winPtr->reqWidth + (wmPtr->width + - wmPtr->reqGridWidth)*wmPtr->widthInc; + wmPtr->height = winPtr->reqHeight + (wmPtr->height + - wmPtr->reqGridHeight)*wmPtr->heightInc; + } + wmPtr->widthInc = 1; + wmPtr->heightInc = 1; + } else { + if ((Tcl_GetInt(interp, argv[3], &reqWidth) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &reqHeight) != TCL_OK) + || (Tcl_GetInt(interp, argv[5], &widthInc) != TCL_OK) + || (Tcl_GetInt(interp, argv[6], &heightInc) != TCL_OK)) { + return TCL_ERROR; + } + if (reqWidth < 0) { + interp->result = "baseWidth can't be < 0"; + return TCL_ERROR; + } + if (reqHeight < 0) { + interp->result = "baseHeight can't be < 0"; + return TCL_ERROR; + } + if (widthInc < 0) { + interp->result = "widthInc can't be < 0"; + return TCL_ERROR; + } + if (heightInc < 0) { + interp->result = "heightInc can't be < 0"; + return TCL_ERROR; + } + Tk_SetGrid((Tk_Window) winPtr, reqWidth, reqHeight, widthInc, + heightInc); + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 'g') && (strncmp(argv[1], "group", length) == 0) + && (length >= 3)) { + Tk_Window tkwin2; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " group window ?pathName?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & WindowGroupHint) { + interp->result = wmPtr->leaderName; + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->hints.flags &= ~WindowGroupHint; + if (wmPtr->leaderName != NULL) { + ckfree(wmPtr->leaderName); + } + wmPtr->leaderName = NULL; + } else { + tkwin2 = Tk_NameToWindow(interp, argv[3], tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + Tk_MakeWindowExist(tkwin2); + wmPtr->hints.window_group = Tk_WindowId(tkwin2); + wmPtr->hints.flags |= WindowGroupHint; + wmPtr->leaderName = ckalloc((unsigned) (strlen(argv[3])+1)); + strcpy(wmPtr->leaderName, argv[3]); + } + } else if ((c == 'i') && (strncmp(argv[1], "iconbitmap", length) == 0) + && (length >= 5)) { + Pixmap pixmap; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconbitmap window ?bitmap?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & IconPixmapHint) { + interp->result = Tk_NameOfBitmap(winPtr->display, + wmPtr->hints.icon_pixmap); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + if (wmPtr->hints.icon_pixmap != None) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_pixmap); + } + wmPtr->hints.flags &= ~IconPixmapHint; + } else { + pixmap = Tk_GetBitmap(interp, (Tk_Window) winPtr, + Tk_GetUid(argv[3])); + if (pixmap == None) { + return TCL_ERROR; + } + wmPtr->hints.icon_pixmap = pixmap; + wmPtr->hints.flags |= IconPixmapHint; + } + } else if ((c == 'i') && (strncmp(argv[1], "iconify", length) == 0) + && (length >= 5)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconify window\"", (char *) NULL); + return TCL_ERROR; + } + if (Tk_Attributes((Tk_Window) winPtr)->override_redirect) { + Tcl_AppendResult(interp, "can't iconify \"", winPtr->pathName, + "\": override-redirect flag is set", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->master != None) { + Tcl_AppendResult(interp, "can't iconify \"", winPtr->pathName, + "\": it is a transient", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + Tcl_AppendResult(interp, "can't iconify ", argv[2], + ": it is an icon for ", Tk_PathName(wmPtr->iconFor), + (char *) NULL); + return TCL_ERROR; + } + if (winPtr->flags & TK_EMBEDDED) { + Tcl_AppendResult(interp, "can't iconify ", winPtr->pathName, + ": it is an embedded window", (char *) NULL); + return TCL_ERROR; + } + TkpWmSetState(winPtr, IconicState); + } else if ((c == 'i') && (strncmp(argv[1], "iconmask", length) == 0) + && (length >= 5)) { + Pixmap pixmap; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconmask window ?bitmap?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & IconMaskHint) { + interp->result = Tk_NameOfBitmap(winPtr->display, + wmPtr->hints.icon_mask); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + if (wmPtr->hints.icon_mask != None) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_mask); + } + wmPtr->hints.flags &= ~IconMaskHint; + } else { + pixmap = Tk_GetBitmap(interp, tkwin, Tk_GetUid(argv[3])); + if (pixmap == None) { + return TCL_ERROR; + } + wmPtr->hints.icon_mask = pixmap; + wmPtr->hints.flags |= IconMaskHint; + } + } else if ((c == 'i') && (strncmp(argv[1], "iconname", length) == 0) + && (length >= 5)) { + if (argc > 4) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconname window ?newName?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + interp->result = (wmPtr->iconName != NULL) ? wmPtr->iconName : ""; + return TCL_OK; + } else { + wmPtr->iconName = Tk_GetUid(argv[3]); + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XSetIconName(winPtr->display, winPtr->window, wmPtr->iconName); + } + } + } else if ((c == 'i') && (strncmp(argv[1], "iconposition", length) == 0) + && (length >= 5)) { + int x, y; + + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconposition window ?x y?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & IconPositionHint) { + sprintf(interp->result, "%d %d", wmPtr->hints.icon_x, + wmPtr->hints.icon_y); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->hints.flags &= ~IconPositionHint; + } else { + if ((Tcl_GetInt(interp, argv[3], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &y) != TCL_OK)){ + return TCL_ERROR; + } + wmPtr->hints.icon_x = x; + wmPtr->hints.icon_y = y; + wmPtr->hints.flags |= IconPositionHint; + } + } else if ((c == 'i') && (strncmp(argv[1], "iconwindow", length) == 0) + && (length >= 5)) { + Tk_Window tkwin2; + WmInfo *wmPtr2; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconwindow window ?pathName?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->icon != NULL) { + interp->result = Tk_PathName(wmPtr->icon); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->hints.flags &= ~IconWindowHint; + if (wmPtr->icon != NULL) { + wmPtr2 = ((TkWindow *) wmPtr->icon)->wmInfoPtr; + wmPtr2->iconFor = NULL; + wmPtr2->hints.initial_state = WithdrawnState; + } + wmPtr->icon = NULL; + } else { + tkwin2 = Tk_NameToWindow(interp, argv[3], tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + if (!Tk_IsTopLevel(tkwin2)) { + Tcl_AppendResult(interp, "can't use ", argv[3], + " as icon window: not at top level", (char *) NULL); + return TCL_ERROR; + } + wmPtr2 = ((TkWindow *) tkwin2)->wmInfoPtr; + if (wmPtr2->iconFor != NULL) { + Tcl_AppendResult(interp, argv[3], " is already an icon for ", + Tk_PathName(wmPtr2->iconFor), (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->icon != NULL) { + WmInfo *wmPtr3 = ((TkWindow *) wmPtr->icon)->wmInfoPtr; + wmPtr3->iconFor = NULL; + } + Tk_MakeWindowExist(tkwin2); + wmPtr->hints.icon_window = Tk_WindowId(tkwin2); + wmPtr->hints.flags |= IconWindowHint; + wmPtr->icon = tkwin2; + wmPtr2->iconFor = (Tk_Window) winPtr; + if (!(wmPtr2->flags & WM_NEVER_MAPPED)) { + /* + * Don't have iconwindows on the Mac. We just withdraw. + */ + + Tk_UnmapWindow(tkwin2); + } + } + } else if ((c == 'm') && (strncmp(argv[1], "maxsize", length) == 0) + && (length >= 2)) { + int width, height; + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " maxsize window ?width height?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + sprintf(interp->result, "%d %d", wmPtr->maxWidth, + wmPtr->maxHeight); + return TCL_OK; + } + if ((Tcl_GetInt(interp, argv[3], &width) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &height) != TCL_OK)) { + return TCL_ERROR; + } + wmPtr->maxWidth = width; + wmPtr->maxHeight = height; + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 'm') && (strncmp(argv[1], "minsize", length) == 0) + && (length >= 2)) { + int width, height; + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " minsize window ?width height?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + sprintf(interp->result, "%d %d", wmPtr->minWidth, + wmPtr->minHeight); + return TCL_OK; + } + if ((Tcl_GetInt(interp, argv[3], &width) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &height) != TCL_OK)) { + return TCL_ERROR; + } + wmPtr->minWidth = width; + wmPtr->minHeight = height; + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 'o') + && (strncmp(argv[1], "overrideredirect", length) == 0)) { + int boolean; + XSetWindowAttributes atts; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " overrideredirect window ?boolean?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (Tk_Attributes((Tk_Window) winPtr)->override_redirect) { + interp->result = "1"; + } else { + interp->result = "0"; + } + return TCL_OK; + } + if (Tcl_GetBoolean(interp, argv[3], &boolean) != TCL_OK) { + return TCL_ERROR; + } + atts.override_redirect = (boolean) ? True : False; + Tk_ChangeWindowAttributes((Tk_Window) winPtr, CWOverrideRedirect, + &atts); + wmPtr->style = (boolean) ? plainDBox : documentProc; + } else if ((c == 'p') && (strncmp(argv[1], "positionfrom", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " positionfrom window ?user/program?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & USPosition) { + interp->result = "user"; + } else if (wmPtr->sizeHintsFlags & PPosition) { + interp->result = "program"; + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->sizeHintsFlags &= ~(USPosition|PPosition); + } else { + c = argv[3][0]; + length = strlen(argv[3]); + if ((c == 'u') && (strncmp(argv[3], "user", length) == 0)) { + wmPtr->sizeHintsFlags &= ~PPosition; + wmPtr->sizeHintsFlags |= USPosition; + } else if ((c == 'p') && + (strncmp(argv[3], "program", length) == 0)) { + wmPtr->sizeHintsFlags &= ~USPosition; + wmPtr->sizeHintsFlags |= PPosition; + } else { + Tcl_AppendResult(interp, "bad argument \"", argv[3], + "\": must be program or user", (char *) NULL); + return TCL_ERROR; + } + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 'p') && (strncmp(argv[1], "protocol", length) == 0) + && (length >= 2)) { + register ProtocolHandler *protPtr, *prevPtr; + Atom protocol; + int cmdLength; + + if ((argc < 3) || (argc > 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " protocol window ?name? ?command?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + /* + * Return a list of all defined protocols for the window. + */ + for (protPtr = wmPtr->protPtr; protPtr != NULL; + protPtr = protPtr->nextPtr) { + Tcl_AppendElement(interp, + Tk_GetAtomName((Tk_Window) winPtr, protPtr->protocol)); + } + return TCL_OK; + } + protocol = Tk_InternAtom((Tk_Window) winPtr, argv[3]); + if (argc == 4) { + /* + * Return the command to handle a given protocol. + */ + for (protPtr = wmPtr->protPtr; protPtr != NULL; + protPtr = protPtr->nextPtr) { + if (protPtr->protocol == protocol) { + interp->result = protPtr->command; + return TCL_OK; + } + } + return TCL_OK; + } + + /* + * Delete any current protocol handler, then create a new + * one with the specified command, unless the command is + * empty. + */ + + for (protPtr = wmPtr->protPtr, prevPtr = NULL; protPtr != NULL; + prevPtr = protPtr, protPtr = protPtr->nextPtr) { + if (protPtr->protocol == protocol) { + if (prevPtr == NULL) { + wmPtr->protPtr = protPtr->nextPtr; + } else { + prevPtr->nextPtr = protPtr->nextPtr; + } + Tcl_EventuallyFree((ClientData) protPtr, TCL_DYNAMIC); + break; + } + } + cmdLength = strlen(argv[4]); + if (cmdLength > 0) { + protPtr = (ProtocolHandler *) ckalloc(HANDLER_SIZE(cmdLength)); + protPtr->protocol = protocol; + protPtr->nextPtr = wmPtr->protPtr; + wmPtr->protPtr = protPtr; + protPtr->interp = interp; + strcpy(protPtr->command, argv[4]); + } + } else if ((c == 'r') && (strncmp(argv[1], "resizable", length) == 0)) { + int width, height; + + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " resizable window ?width height?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + sprintf(interp->result, "%d %d", + (wmPtr->flags & WM_WIDTH_NOT_RESIZABLE) ? 0 : 1, + (wmPtr->flags & WM_HEIGHT_NOT_RESIZABLE) ? 0 : 1); + return TCL_OK; + } + if ((Tcl_GetBoolean(interp, argv[3], &width) != TCL_OK) + || (Tcl_GetBoolean(interp, argv[4], &height) != TCL_OK)) { + return TCL_ERROR; + } + if (width) { + wmPtr->flags &= ~WM_WIDTH_NOT_RESIZABLE; + } else { + wmPtr->flags |= WM_WIDTH_NOT_RESIZABLE; + } + if (height) { + wmPtr->flags &= ~WM_HEIGHT_NOT_RESIZABLE; + } else { + wmPtr->flags |= WM_HEIGHT_NOT_RESIZABLE; + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + if (wmPtr->scrollWinPtr != NULL) { + TkScrollbarEventuallyRedraw( + (TkScrollbar *) wmPtr->scrollWinPtr->instanceData); + } + goto updateGeom; + } else if ((c == 's') && (strncmp(argv[1], "sizefrom", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " sizefrom window ?user|program?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & USSize) { + interp->result = "user"; + } else if (wmPtr->sizeHintsFlags & PSize) { + interp->result = "program"; + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->sizeHintsFlags &= ~(USSize|PSize); + } else { + c = argv[3][0]; + length = strlen(argv[3]); + if ((c == 'u') && (strncmp(argv[3], "user", length) == 0)) { + wmPtr->sizeHintsFlags &= ~PSize; + wmPtr->sizeHintsFlags |= USSize; + } else if ((c == 'p') + && (strncmp(argv[3], "program", length) == 0)) { + wmPtr->sizeHintsFlags &= ~USSize; + wmPtr->sizeHintsFlags |= PSize; + } else { + Tcl_AppendResult(interp, "bad argument \"", argv[3], + "\": must be program or user", (char *) NULL); + return TCL_ERROR; + } + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 's') && (strncmp(argv[1], "state", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " state window\"", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + interp->result = "icon"; + } else { + switch (wmPtr->hints.initial_state) { + case NormalState: + interp->result = "normal"; + break; + case IconicState: + interp->result = "iconic"; + break; + case WithdrawnState: + interp->result = "withdrawn"; + break; + case ZoomState: + interp->result = "zoomed"; + break; + } + } + } else if ((c == 't') && (strncmp(argv[1], "title", length) == 0) + && (length >= 2)) { + if (argc > 4) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " title window ?newTitle?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + interp->result = (wmPtr->titleUid != NULL) ? wmPtr->titleUid + : winPtr->nameUid; + return TCL_OK; + } else { + wmPtr->titleUid = Tk_GetUid(argv[3]); + if (!(wmPtr->flags & WM_NEVER_MAPPED) && !Tk_IsEmbedded(winPtr)) { + TkSetWMName(winPtr, wmPtr->titleUid); + } + } + } else if ((c == 't') && (strncmp(argv[1], "transient", length) == 0) + && (length >= 3)) { + Tk_Window master; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " transient window ?master?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->master != None) { + interp->result = wmPtr->masterWindowName; + } + return TCL_OK; + } + if (argv[3][0] == '\0') { + wmPtr->master = None; + if (wmPtr->masterWindowName != NULL) { + ckfree(wmPtr->masterWindowName); + } + wmPtr->masterWindowName = NULL; + wmPtr->style = documentProc; + } else { + master = Tk_NameToWindow(interp, argv[3], tkwin); + if (master == NULL) { + return TCL_ERROR; + } + Tk_MakeWindowExist(master); + wmPtr->master = Tk_WindowId(master); + wmPtr->masterWindowName = ckalloc((unsigned) (strlen(argv[3])+1)); + strcpy(wmPtr->masterWindowName, argv[3]); + wmPtr->style = plainDBox; + } + } else if ((c == 'w') && (strncmp(argv[1], "withdraw", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " withdraw window\"", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + Tcl_AppendResult(interp, "can't withdraw ", argv[2], + ": it is an icon for ", Tk_PathName(wmPtr->iconFor), + (char *) NULL); + return TCL_ERROR; + } + TkpWmSetState(winPtr, WithdrawnState); + } else { + Tcl_AppendResult(interp, "unknown or ambiguous option \"", argv[1], + "\": must be aspect, client, command, deiconify, ", + "focusmodel, frame, geometry, grid, group, iconbitmap, ", + "iconify, iconmask, iconname, iconposition, ", + "iconwindow, maxsize, minsize, overrideredirect, ", + "positionfrom, protocol, resizable, sizefrom, state, title, ", + "transient, or withdraw", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; + + updateGeom: + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tk_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_SetGrid -- + * + * This procedure is invoked by a widget when it wishes to set a grid + * coordinate system that controls the size of a top-level window. + * It provides a C interface equivalent to the "wm grid" command and + * is usually asscoiated with the -setgrid option. + * + * Results: + * None. + * + * Side effects: + * Grid-related information will be passed to the window manager, so + * that the top-level window associated with tkwin will resize on + * even grid units. If some other window already controls gridding + * for the top-level window then this procedure call has no effect. + * + *---------------------------------------------------------------------- + */ + +void +Tk_SetGrid( + Tk_Window tkwin, /* Token for window. New window mgr info + * will be posted for the top-level window + * associated with this window. */ + int reqWidth, /* Width (in grid units) corresponding to + * the requested geometry for tkwin. */ + int reqHeight, /* Height (in grid units) corresponding to + * the requested geometry for tkwin. */ + int widthInc, int heightInc)/* Pixel increments corresponding to a + * change of one grid unit. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + register WmInfo *wmPtr; + + /* + * Find the top-level window for tkwin, plus the window manager + * information. + */ + + while (!(winPtr->flags & TK_TOP_LEVEL)) { + winPtr = winPtr->parentPtr; + } + wmPtr = winPtr->wmInfoPtr; + + if ((wmPtr->gridWin != NULL) && (wmPtr->gridWin != tkwin)) { + return; + } + + if ((wmPtr->reqGridWidth == reqWidth) + && (wmPtr->reqGridHeight == reqHeight) + && (wmPtr->widthInc == widthInc) + && (wmPtr->heightInc == heightInc) + && ((wmPtr->sizeHintsFlags & (PBaseSize|PResizeInc)) + == PBaseSize|PResizeInc)) { + return; + } + + /* + * If gridding was previously off, then forget about any window + * size requests made by the user or via "wm geometry": these are + * in pixel units and there's no easy way to translate them to + * grid units since the new requested size of the top-level window in + * pixels may not yet have been registered yet (it may filter up + * the hierarchy in DoWhenIdle handlers). However, if the window + * has never been mapped yet then just leave the window size alone: + * assume that it is intended to be in grid units but just happened + * to have been specified before this procedure was called. + */ + + if ((wmPtr->gridWin == NULL) && !(wmPtr->flags & WM_NEVER_MAPPED)) { + wmPtr->width = -1; + wmPtr->height = -1; + } + + /* + * Set the new gridding information, and start the process of passing + * all of this information to the window manager. + */ + + wmPtr->gridWin = tkwin; + wmPtr->reqGridWidth = reqWidth; + wmPtr->reqGridHeight = reqHeight; + wmPtr->widthInc = widthInc; + wmPtr->heightInc = heightInc; + wmPtr->sizeHintsFlags |= PBaseSize|PResizeInc; + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tk_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_UnsetGrid -- + * + * This procedure cancels the effect of a previous call + * to Tk_SetGrid. + * + * Results: + * None. + * + * Side effects: + * If tkwin currently controls gridding for its top-level window, + * gridding is cancelled for that top-level window; if some other + * window controls gridding then this procedure has no effect. + * + *---------------------------------------------------------------------- + */ + +void +Tk_UnsetGrid( + Tk_Window tkwin) /* Token for window that is currently + * controlling gridding. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + register WmInfo *wmPtr; + + /* + * Find the top-level window for tkwin, plus the window manager + * information. + */ + + while (!(winPtr->flags & TK_TOP_LEVEL)) { + winPtr = winPtr->parentPtr; + } + wmPtr = winPtr->wmInfoPtr; + if (tkwin != wmPtr->gridWin) { + return; + } + + wmPtr->gridWin = NULL; + wmPtr->sizeHintsFlags &= ~(PBaseSize|PResizeInc); + if (wmPtr->width != -1) { + wmPtr->width = winPtr->reqWidth + (wmPtr->width + - wmPtr->reqGridWidth)*wmPtr->widthInc; + wmPtr->height = winPtr->reqHeight + (wmPtr->height + - wmPtr->reqGridHeight)*wmPtr->heightInc; + } + wmPtr->widthInc = 1; + wmPtr->heightInc = 1; + + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tk_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * TopLevelEventProc -- + * + * This procedure is invoked when a top-level (or other externally- + * managed window) is restructured in any way. + * + * Results: + * None. + * + * Side effects: + * Tk's internal data structures for the window get modified to + * reflect the structural change. + * + *---------------------------------------------------------------------- + */ + +static void +TopLevelEventProc( + ClientData clientData, /* Window for which event occurred. */ + XEvent *eventPtr) /* Event that just happened. */ +{ + register TkWindow *winPtr = (TkWindow *) clientData; + + winPtr->wmInfoPtr->flags |= WM_VROOT_OFFSET_STALE; + if (eventPtr->type == DestroyNotify) { + Tk_ErrorHandler handler; + + if (!(winPtr->flags & TK_ALREADY_DEAD)) { + /* + * A top-level window was deleted externally (e.g., by the window + * manager). This is probably not a good thing, but cleanup as + * best we can. The error handler is needed because + * Tk_DestroyWindow will try to destroy the window, but of course + * it's already gone. + */ + + handler = Tk_CreateErrorHandler(winPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + Tk_DestroyWindow((Tk_Window) winPtr); + Tk_DeleteErrorHandler(handler); + } + if (wmTracing) { + printf("TopLevelEventProc: %s deleted\n", winPtr->pathName); + } + } else if (eventPtr->type == ReparentNotify) { + panic("recieved unwanted reparent event"); + } +} + +/* + *---------------------------------------------------------------------- + * + * TopLevelReqProc -- + * + * This procedure is invoked by the geometry manager whenever + * the requested size for a top-level window is changed. + * + * Results: + * None. + * + * Side effects: + * Arrange for the window to be resized to satisfy the request + * (this happens as a when-idle action). + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +TopLevelReqProc( + ClientData dummy, /* Not used. */ + Tk_Window tkwin) /* Information about window. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + WmInfo *wmPtr; + + wmPtr = winPtr->wmInfoPtr; + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tk_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * UpdateGeometryInfo -- + * + * This procedure is invoked when a top-level window is first + * mapped, and also as a when-idle procedure, to bring the + * geometry and/or position of a top-level window back into + * line with what has been requested by the user and/or widgets. + * This procedure doesn't return until the window manager has + * responded to the geometry change. + * + * Results: + * None. + * + * Side effects: + * The window's size and location may change, unless the WM prevents + * that from happening. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateGeometryInfo( + ClientData clientData) /* Pointer to the window's record. */ +{ + register TkWindow *winPtr = (TkWindow *) clientData; + register WmInfo *wmPtr = winPtr->wmInfoPtr; + int x, y, width, height; + unsigned long serial; + + wmPtr->flags &= ~WM_UPDATE_PENDING; + + /* + * Compute the new size for the top-level window. See the + * user documentation for details on this, but the size + * requested depends on (a) the size requested internally + * by the window's widgets, (b) the size requested by the + * user in a "wm geometry" command or via wm-based interactive + * resizing (if any), and (c) whether or not the window is + * gridded. Don't permit sizes <= 0 because this upsets + * the X server. + */ + + if (wmPtr->width == -1) { + width = winPtr->reqWidth; + } else if (wmPtr->gridWin != NULL) { + width = winPtr->reqWidth + + (wmPtr->width - wmPtr->reqGridWidth)*wmPtr->widthInc; + } else { + width = wmPtr->width; + } + if (width <= 0) { + width = 1; + } + if (wmPtr->height == -1) { + height = winPtr->reqHeight; + } else if (wmPtr->gridWin != NULL) { + height = winPtr->reqHeight + + (wmPtr->height - wmPtr->reqGridHeight)*wmPtr->heightInc; + } else { + height = wmPtr->height; + } + if (height <= 0) { + height = 1; + } + + /* + * Compute the new position for the upper-left pixel of the window's + * decorative frame. This is tricky, because we need to include the + * border widths supplied by a reparented parent in this calculation, + * but can't use the parent's current overall size since that may + * change as a result of this code. + */ + + if (wmPtr->flags & WM_NEGATIVE_X) { + x = wmPtr->vRootWidth - wmPtr->x + - (width + (wmPtr->parentWidth - winPtr->changes.width)); + } else { + x = wmPtr->x; + } + if (wmPtr->flags & WM_NEGATIVE_Y) { + y = wmPtr->vRootHeight - wmPtr->y + - (height + (wmPtr->parentHeight - winPtr->changes.height)); + } else { + y = wmPtr->y; + } + + /* + * If the window's size is going to change and the window is + * supposed to not be resizable by the user, then we have to + * update the size hints. There may also be a size-hint-update + * request pending from somewhere else, too. + */ + + if (((width != winPtr->changes.width) + || (height != winPtr->changes.height)) + && (wmPtr->gridWin == NULL) + && ((wmPtr->sizeHintsFlags & (PMinSize|PMaxSize)) == 0)) { + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + } + if (wmPtr->flags & WM_UPDATE_SIZE_HINTS) { + UpdateSizeHints(winPtr); + } + + /* + * Reconfigure the window if it isn't already configured correctly. + * A few tricky points: + * + * 1. If the window is embedded and the container is also in this + * process, don't actually reconfigure the window; just pass the + * desired size on to the container. Also, zero out any position + * information, since embedded windows are not allowed to move. + * 2. Sometimes the window manager will give us a different size + * than we asked for (e.g. mwm has a minimum size for windows), so + * base the size check on what we *asked for* last time, not what we + * got. + * 3. Don't move window unless a new position has been requested for + * it. This is because of "features" in some window managers (e.g. + * twm, as of 4/24/91) where they don't interpret coordinates + * according to ICCCM. Moving a window to its current location may + * cause it to shift position on the screen. + */ + + if (Tk_IsEmbedded(winPtr)) { + TkWindow *contWinPtr; + + contWinPtr = TkpGetOtherWindow(winPtr); + + /* + * NOTE: Here we should handle out of process embedding. + */ + + if (contWinPtr != NULL) { + /* + * This window is embedded and the container is also in this + * process, so we don't need to do anything special about the + * geometry, except to make sure that the desired size is known + * by the container. Also, zero out any position information, + * since embedded windows are not allowed to move. + */ + + wmPtr->x = wmPtr->y = 0; + wmPtr->flags &= ~(WM_NEGATIVE_X|WM_NEGATIVE_Y); + Tk_GeometryRequest((Tk_Window) contWinPtr, width, height); + } + return; + } + serial = NextRequest(winPtr->display); + if (wmPtr->flags & WM_MOVE_PENDING) { + wmPtr->configWidth = width; + wmPtr->configHeight = height; + if (wmTracing) { + printf( + "UpdateGeometryInfo moving to %d %d, resizing to %d x %d,\n", + x, y, width, height); + } + Tk_MoveResizeWindow((Tk_Window) winPtr, x, y, (unsigned) width, + (unsigned) height); + } else if ((width != wmPtr->configWidth) + || (height != wmPtr->configHeight)) { + wmPtr->configWidth = width; + wmPtr->configHeight = height; + if (wmTracing) { + printf("UpdateGeometryInfo resizing to %d x %d\n", width, height); + } + Tk_ResizeWindow((Tk_Window) winPtr, (unsigned) width, + (unsigned) height); + } else { + return; + } +} + +/* + *-------------------------------------------------------------- + * + * UpdateSizeHints -- + * + * This procedure is called to update the window manager's + * size hints information from the information in a WmInfo + * structure. + * + * Results: + * None. + * + * Side effects: + * Properties get changed for winPtr. + * + *-------------------------------------------------------------- + */ + +static void +UpdateSizeHints( + TkWindow *winPtr) +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + XSizeHints *hintsPtr; + + wmPtr->flags &= ~WM_UPDATE_SIZE_HINTS; + + hintsPtr = XAllocSizeHints(); + if (hintsPtr == NULL) { + return; + } + + /* + * Compute the pixel-based sizes for the various fields in the + * size hints structure, based on the grid-based sizes in + * our structure. + */ + + if (wmPtr->gridWin != NULL) { + hintsPtr->base_width = winPtr->reqWidth + - (wmPtr->reqGridWidth * wmPtr->widthInc); + if (hintsPtr->base_width < 0) { + hintsPtr->base_width = 0; + } + hintsPtr->base_height = winPtr->reqHeight + - (wmPtr->reqGridHeight * wmPtr->heightInc); + if (hintsPtr->base_height < 0) { + hintsPtr->base_height = 0; + } + hintsPtr->min_width = hintsPtr->base_width + + (wmPtr->minWidth * wmPtr->widthInc); + hintsPtr->min_height = hintsPtr->base_height + + (wmPtr->minHeight * wmPtr->heightInc); + hintsPtr->max_width = hintsPtr->base_width + + (wmPtr->maxWidth * wmPtr->widthInc); + hintsPtr->max_height = hintsPtr->base_height + + (wmPtr->maxHeight * wmPtr->heightInc); + } else { + hintsPtr->min_width = wmPtr->minWidth; + hintsPtr->min_height = wmPtr->minHeight; + hintsPtr->max_width = wmPtr->maxWidth; + hintsPtr->max_height = wmPtr->maxHeight; + hintsPtr->base_width = 0; + hintsPtr->base_height = 0; + } + hintsPtr->width_inc = wmPtr->widthInc; + hintsPtr->height_inc = wmPtr->heightInc; + hintsPtr->min_aspect.x = wmPtr->minAspect.x; + hintsPtr->min_aspect.y = wmPtr->minAspect.y; + hintsPtr->max_aspect.x = wmPtr->maxAspect.x; + hintsPtr->max_aspect.y = wmPtr->maxAspect.y; + hintsPtr->win_gravity = wmPtr->gravity; + hintsPtr->flags = wmPtr->sizeHintsFlags | PMinSize | PMaxSize; + + /* + * If the window isn't supposed to be resizable, then set the + * minimum and maximum dimensions to be the same. + */ + + if (wmPtr->flags & WM_WIDTH_NOT_RESIZABLE) { + if (wmPtr->width >= 0) { + hintsPtr->min_width = wmPtr->width; + } else { + hintsPtr->min_width = winPtr->reqWidth; + } + hintsPtr->max_width = hintsPtr->min_width; + } + if (wmPtr->flags & WM_HEIGHT_NOT_RESIZABLE) { + if (wmPtr->height >= 0) { + hintsPtr->min_height = wmPtr->height; + } else { + hintsPtr->min_height = winPtr->reqHeight; + } + hintsPtr->max_height = hintsPtr->min_height; + } + + XSetWMNormalHints(winPtr->display, winPtr->window, hintsPtr); + + XFree((char *) hintsPtr); +} + +/* + *-------------------------------------------------------------- + * + * ParseGeometry -- + * + * This procedure parses a geometry string and updates + * information used to control the geometry of a top-level + * window. + * + * Results: + * A standard Tcl return value, plus an error message in + * interp->result if an error occurs. + * + * Side effects: + * The size and/or location of winPtr may change. + * + *-------------------------------------------------------------- + */ + +static int +ParseGeometry( + Tcl_Interp *interp, /* Used for error reporting. */ + char *string, /* String containing new geometry. Has the + * standard form "=wxh+x+y". */ + TkWindow *winPtr) /* Pointer to top-level window whose + * geometry is to be changed. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + int x, y, width, height, flags; + char *end; + register char *p = string; + + /* + * The leading "=" is optional. + */ + + if (*p == '=') { + p++; + } + + /* + * Parse the width and height, if they are present. Don't + * actually update any of the fields of wmPtr until we've + * successfully parsed the entire geometry string. + */ + + width = wmPtr->width; + height = wmPtr->height; + x = wmPtr->x; + y = wmPtr->y; + flags = wmPtr->flags; + if (isdigit(UCHAR(*p))) { + width = strtoul(p, &end, 10); + p = end; + if (*p != 'x') { + goto error; + } + p++; + if (!isdigit(UCHAR(*p))) { + goto error; + } + height = strtoul(p, &end, 10); + p = end; + } + + /* + * Parse the X and Y coordinates, if they are present. + */ + + if (*p != '\0') { + flags &= ~(WM_NEGATIVE_X | WM_NEGATIVE_Y); + if (*p == '-') { + flags |= WM_NEGATIVE_X; + } else if (*p != '+') { + goto error; + } + x = strtol(p+1, &end, 10); + p = end; + if (*p == '-') { + flags |= WM_NEGATIVE_Y; + } else if (*p != '+') { + goto error; + } + y = strtol(p+1, &end, 10); + if (*end != '\0') { + goto error; + } + + /* + * Assume that the geometry information came from the user, + * unless an explicit source has been specified. Otherwise + * most window managers assume that the size hints were + * program-specified and they ignore them. + */ + + if ((wmPtr->sizeHintsFlags & (USPosition|PPosition)) == 0) { + wmPtr->sizeHintsFlags |= USPosition; + flags |= WM_UPDATE_SIZE_HINTS; + } + } + + /* + * Everything was parsed OK. Update the fields of *wmPtr and + * arrange for the appropriate information to be percolated out + * to the window manager at the next idle moment. + */ + + wmPtr->width = width; + wmPtr->height = height; + if ((x != wmPtr->x) || (y != wmPtr->y) + || ((flags & (WM_NEGATIVE_X|WM_NEGATIVE_Y)) + != (wmPtr->flags & (WM_NEGATIVE_X|WM_NEGATIVE_Y)))) { + wmPtr->x = x; + wmPtr->y = y; + flags |= WM_MOVE_PENDING; + } + wmPtr->flags = flags; + + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tk_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } + return TCL_OK; + + error: + Tcl_AppendResult(interp, "bad geometry specifier \"", + string, "\"", (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetRootCoords -- + * + * Given a token for a window, this procedure traces through the + * window's lineage to find the (virtual) root-window coordinates + * corresponding to point (0,0) in the window. + * + * Results: + * The locations pointed to by xPtr and yPtr are filled in with + * the root coordinates of the (0,0) point in tkwin. If a virtual + * root window is in effect for the window, then the coordinates + * in the virtual root are returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +Tk_GetRootCoords( + Tk_Window tkwin, /* Token for window. */ + int *xPtr, /* Where to store x-displacement of (0,0). */ + int *yPtr) /* Where to store y-displacement of (0,0). */ +{ + int x, y; + register TkWindow *winPtr = (TkWindow *) tkwin; + + /* + * Search back through this window's parents all the way to a + * top-level window, combining the offsets of each window within + * its parent. + */ + + x = y = 0; + while (1) { + x += winPtr->changes.x + winPtr->changes.border_width; + y += winPtr->changes.y + winPtr->changes.border_width; + if (winPtr->flags & TK_TOP_LEVEL) { + if (!(Tk_IsEmbedded(winPtr))) { + x += winPtr->wmInfoPtr->xInParent; + y += winPtr->wmInfoPtr->yInParent; + break; + } else { + TkWindow *otherPtr; + + otherPtr = TkpGetOtherWindow(winPtr); + if (otherPtr != NULL) { + /* + * The container window is in the same application. + * Query its coordinates. + */ + winPtr = otherPtr; + + /* + * Remember to offset by the container window here, + * since at the end of this if branch, we will + * pop out to the container's parent... + */ + + x += winPtr->changes.x + winPtr->changes.border_width; + y += winPtr->changes.y + winPtr->changes.border_width; + + } else { + + /* + * NOTE: Here we should handle + * out of process embedding. + */ + + break; + } + } + } + winPtr = winPtr->parentPtr; + } + *xPtr = x; + *yPtr = y; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_CoordsToWindow -- + * + * This is a Macintosh specific implementation of this function. + * Given the root coordinates of a point, this procedure returns + * the token for the top-most window covering that point, if + * there exists such a window in this application. + * + * Results: + * The return result is either a token for the window corresponding + * to rootX and rootY, or else NULL to indicate that there is no such + * window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +Tk_CoordsToWindow( + int rootX, int rootY, /* Coordinates of point in root window. If + * a virtual-root window manager is in use, + * these coordinates refer to the virtual + * root, not the real root. */ + Tk_Window tkwin) /* Token for any window in application; + * used to identify the display. */ +{ + WindowPtr whichWin; + Point where; + Window rootChild; + register TkWindow *winPtr, *childPtr; + TkWindow *nextPtr; /* Coordinates of highest child found so + * far that contains point. */ + int x, y; /* Coordinates in winPtr. */ + int tmpx, tmpy, bd; + + /* + * Step 1: find the top-level window that contains the desired point. + */ + + where.h = rootX; + where.v = rootY; + FindWindow(where, &whichWin); + if (whichWin == NULL) { + return NULL; + } + rootChild = TkMacGetXWindow(whichWin); + winPtr = (TkWindow *) Tk_IdToWindow(tkDisplayList->display, rootChild); + if (winPtr == NULL) { + return NULL; + } + + /* + * Step 2: work down through the hierarchy underneath this window. + * At each level, scan through all the children to find the highest + * one in the stacking order that contains the point. Then repeat + * the whole process on that child. + */ + + x = rootX - winPtr->wmInfoPtr->xInParent; + y = rootY - winPtr->wmInfoPtr->yInParent; + while (1) { + x -= winPtr->changes.x; + y -= winPtr->changes.y; + nextPtr = NULL; + + /* + * Container windows cannot have children. So if it is a container, + * look there, otherwise inspect the children. + */ + + if (Tk_IsContainer(winPtr)) { + childPtr = TkpGetOtherWindow(winPtr); + if (childPtr != NULL) { + if (Tk_IsMapped(childPtr)) { + tmpx = x - childPtr->changes.x; + tmpy = y - childPtr->changes.y; + bd = childPtr->changes.border_width; + + if ((tmpx >= -bd) && (tmpy >= -bd) + && (tmpx < (childPtr->changes.width + bd)) + && (tmpy < (childPtr->changes.height + bd))) { + nextPtr = childPtr; + } + } + } + + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } else { + for (childPtr = winPtr->childList; childPtr != NULL; + childPtr = childPtr->nextPtr) { + if (!Tk_IsMapped(childPtr) || + (childPtr->flags & TK_TOP_LEVEL)) { + continue; + } + tmpx = x - childPtr->changes.x; + tmpy = y - childPtr->changes.y; + bd = childPtr->changes.border_width; + if ((tmpx >= -bd) && (tmpy >= -bd) + && (tmpx < (childPtr->changes.width + bd)) + && (tmpy < (childPtr->changes.height + bd))) { + nextPtr = childPtr; + } + } + } + if (nextPtr == NULL) { + break; + } + winPtr = nextPtr; + } + return (Tk_Window) winPtr; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_TopCoordsToWindow -- + * + * Given a Tk Window, and coordinates of a point relative to that window + * this procedure returns the top-most child of the window (excluding + * toplevels) covering that point, if there exists such a window in this + * application. + * It also sets newX, and newY to the coords of the point relative to the + * window returned. + * + * Results: + * The return result is either a token for the window corresponding + * to rootX and rootY, or else NULL to indicate that there is no such + * window. newX and newY are also set to the coords of the point relative + * to the returned window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +Tk_TopCoordsToWindow( + Tk_Window tkwin, /* Token for a Tk Window which defines the; + * coordinates for rootX & rootY */ + int rootX, int rootY, /* Coordinates of a point in tkWin. */ + int *newX, int *newY) /* Coordinates of point in the upperMost child of + * tkWin containing (rootX,rootY) */ +{ + register TkWindow *winPtr, *childPtr; + TkWindow *nextPtr; /* Coordinates of highest child found so + * far that contains point. */ + int x, y; /* Coordinates in winPtr. */ + Window *children; /* Children of winPtr, or NULL. */ + + winPtr = (TkWindow *) tkwin; + x = rootX; + y = rootY; + while (1) { + nextPtr = NULL; + children = NULL; + + /* + * Container windows cannot have children. So if it is a container, + * look there, otherwise inspect the children. + */ + + if (Tk_IsContainer(winPtr)) { + childPtr = TkpGetOtherWindow(winPtr); + if (childPtr != NULL) { + if (Tk_IsMapped(childPtr) && + (x > childPtr->changes.x && + x < childPtr->changes.x + + childPtr->changes.width) && + (y > childPtr->changes.y && + y < childPtr->changes.y + + childPtr->changes.height)) { + nextPtr = childPtr; + } + } + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } else { + + for (childPtr = winPtr->childList; childPtr != NULL; + childPtr = childPtr->nextPtr) { + if (!Tk_IsMapped(childPtr) || + (childPtr->flags & TK_TOP_LEVEL)) { + continue; + } + if (x < childPtr->changes.x || y < childPtr->changes.y) { + continue; + } + if (x > childPtr->changes.x + childPtr->changes.width || + y > childPtr->changes.y + childPtr->changes.height) { + continue; + } + nextPtr = childPtr; + } + } + if (nextPtr == NULL) { + break; + } + winPtr = nextPtr; + x -= winPtr->changes.x; + y -= winPtr->changes.y; + } + *newX = x; + *newY = y; + return (Tk_Window) winPtr; +} + +/* + *---------------------------------------------------------------------- + * + * UpdateVRootGeometry -- + * + * This procedure is called to update all the virtual root + * geometry information in wmPtr. + * + * Results: + * None. + * + * Side effects: + * The vRootX, vRootY, vRootWidth, and vRootHeight fields in + * wmPtr are filled with the most up-to-date information. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateVRootGeometry( + WmInfo *wmPtr) /* Window manager information to be + * updated. The wmPtr->vRoot field must + * be valid. */ +{ + TkWindow *winPtr = wmPtr->winPtr; + unsigned int bd, dummy; + Window dummy2; + Status status; + Tk_ErrorHandler handler; + + /* + * If this isn't a virtual-root window manager, just return information + * about the screen. + */ + + wmPtr->flags &= ~WM_VROOT_OFFSET_STALE; + if (wmPtr->vRoot == None) { + noVRoot: + wmPtr->vRootX = wmPtr->vRootY = 0; + wmPtr->vRootWidth = DisplayWidth(winPtr->display, winPtr->screenNum); + wmPtr->vRootHeight = DisplayHeight(winPtr->display, winPtr->screenNum); + return; + } + + /* + * Refresh the virtual root information if it's out of date. + */ + + handler = Tk_CreateErrorHandler(winPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + status = XGetGeometry(winPtr->display, wmPtr->vRoot, + &dummy2, &wmPtr->vRootX, &wmPtr->vRootY, + &wmPtr->vRootWidth, &wmPtr->vRootHeight, &bd, &dummy); + if (wmTracing) { + printf("UpdateVRootGeometry: x = %d, y = %d, width = %d, ", + wmPtr->vRootX, wmPtr->vRootY, wmPtr->vRootWidth); + printf("height = %d, status = %d\n", wmPtr->vRootHeight, status); + } + Tk_DeleteErrorHandler(handler); + if (status == 0) { + /* + * The virtual root is gone! Pretend that it never existed. + */ + + wmPtr->vRoot = None; + goto noVRoot; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetVRootGeometry -- + * + * This procedure returns information about the virtual root + * window corresponding to a particular Tk window. + * + * Results: + * The values at xPtr, yPtr, widthPtr, and heightPtr are set + * with the offset and dimensions of the root window corresponding + * to tkwin. If tkwin is being managed by a virtual root window + * manager these values correspond to the virtual root window being + * used for tkwin; otherwise the offsets will be 0 and the + * dimensions will be those of the screen. + * + * Side effects: + * Vroot window information is refreshed if it is out of date. + * + *---------------------------------------------------------------------- + */ + +void +Tk_GetVRootGeometry( + Tk_Window tkwin, /* Window whose virtual root is to be + * queried. */ + int *xPtr, int *yPtr, /* Store x and y offsets of virtual root + * here. */ + int *widthPtr, /* Store dimensions of virtual root here. */ + int *heightPtr) +{ + WmInfo *wmPtr; + TkWindow *winPtr = (TkWindow *) tkwin; + + /* + * Find the top-level window for tkwin, and locate the window manager + * information for that window. + */ + + while (!(winPtr->flags & TK_TOP_LEVEL)) { + winPtr = winPtr->parentPtr; + } + wmPtr = winPtr->wmInfoPtr; + + /* + * Make sure that the geometry information is up-to-date, then copy + * it out to the caller. + */ + + if (wmPtr->flags & WM_VROOT_OFFSET_STALE) { + UpdateVRootGeometry(wmPtr); + } + *xPtr = wmPtr->vRootX; + *yPtr = wmPtr->vRootY; + *widthPtr = wmPtr->vRootWidth; + *heightPtr = wmPtr->vRootHeight; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_MoveToplevelWindow -- + * + * This procedure is called instead of Tk_MoveWindow to adjust + * the x-y location of a top-level window. It delays the actual + * move to a later time and keeps window-manager information + * up-to-date with the move + * + * Results: + * None. + * + * Side effects: + * The window is eventually moved so that its upper-left corner + * (actually, the upper-left corner of the window's decorative + * frame, if there is one) is at (x,y). + * + *---------------------------------------------------------------------- + */ + +void +Tk_MoveToplevelWindow( + Tk_Window tkwin, /* Window to move. */ + int x, int y) /* New location for window (within + * parent). */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + register WmInfo *wmPtr = winPtr->wmInfoPtr; + + if (!(winPtr->flags & TK_TOP_LEVEL)) { + panic("Tk_MoveToplevelWindow called with non-toplevel window"); + } + wmPtr->x = x; + wmPtr->y = y; + wmPtr->flags |= WM_MOVE_PENDING; + wmPtr->flags &= ~(WM_NEGATIVE_X|WM_NEGATIVE_Y); + if ((wmPtr->sizeHintsFlags & (USPosition|PPosition)) == 0) { + wmPtr->sizeHintsFlags |= USPosition; + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + } + + /* + * If the window has already been mapped, must bring its geometry + * up-to-date immediately, otherwise an event might arrive from the + * server that would overwrite wmPtr->x and wmPtr->y and lose the + * new position. + */ + + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + if (wmPtr->flags & WM_UPDATE_PENDING) { + Tk_CancelIdleCall(UpdateGeometryInfo, (ClientData) winPtr); + } + UpdateGeometryInfo((ClientData) winPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWmProtocolEventProc -- + * + * This procedure is called by the Tk_HandleEvent whenever a + * ClientMessage event arrives whose type is "WM_PROTOCOLS". + * This procedure handles the message from the window manager + * in an appropriate fashion. + * + * Results: + * None. + * + * Side effects: + * Depends on what sort of handler, if any, was set up for the + * protocol. + * + *---------------------------------------------------------------------- + */ + +void +TkWmProtocolEventProc( + TkWindow *winPtr, /* Window to which the event was sent. */ + XEvent *eventPtr) /* X event. */ +{ + WmInfo *wmPtr; + register ProtocolHandler *protPtr; + Tcl_Interp *interp; + Atom protocol; + int result; + + wmPtr = winPtr->wmInfoPtr; + if (wmPtr == NULL) { + return; + } + protocol = (Atom) eventPtr->xclient.data.l[0]; + for (protPtr = wmPtr->protPtr; protPtr != NULL; + protPtr = protPtr->nextPtr) { + if (protocol == protPtr->protocol) { + Tcl_Preserve((ClientData) protPtr); + interp = protPtr->interp; + Tcl_Preserve((ClientData) interp); + result = Tcl_GlobalEval(interp, protPtr->command); + if (result != TCL_OK) { + Tcl_AddErrorInfo(interp, "\n (command for \""); + Tcl_AddErrorInfo(interp, + Tk_GetAtomName((Tk_Window) winPtr, protocol)); + Tcl_AddErrorInfo(interp, "\" window manager protocol)"); + Tk_BackgroundError(interp); + } + Tcl_Release((ClientData) interp); + Tcl_Release((ClientData) protPtr); + return; + } + } + + /* + * No handler was present for this protocol. If this is a + * WM_DELETE_WINDOW message then just destroy the window. + */ + + if (protocol == Tk_InternAtom((Tk_Window) winPtr, "WM_DELETE_WINDOW")) { + Tk_DestroyWindow((Tk_Window) winPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWmRestackToplevel -- + * + * This procedure restacks a top-level window. + * + * Results: + * None. + * + * Side effects: + * WinPtr gets restacked as specified by aboveBelow and otherPtr. + * This procedure doesn't return until the restack has taken + * effect and the ConfigureNotify event for it has been received. + * + *---------------------------------------------------------------------- + */ + +void +TkWmRestackToplevel( + TkWindow *winPtr, /* Window to restack. */ + int aboveBelow, /* Gives relative position for restacking; + * must be Above or Below. */ + TkWindow *otherPtr) /* Window relative to which to restack; + * if NULL, then winPtr gets restacked + * above or below *all* siblings. */ +{ + WmInfo *wmPtr; + WindowPeek macWindow, otherMacWindow, frontWindow; + + wmPtr = winPtr->wmInfoPtr; + + /* + * Get the mac window. Make sure it exists & is mapped. + */ + + if (winPtr->window == None) { + Tk_MakeWindowExist((Tk_Window) winPtr); + } + if (winPtr->wmInfoPtr->flags & WM_NEVER_MAPPED) { + + /* + * Can't set stacking order properly until the window is on the + * screen (mapping it may give it a reparent window), so make sure + * it's on the screen. + */ + + TkWmMapWindow(winPtr); + } + macWindow = (WindowPeek) TkMacGetDrawablePort(winPtr->window); + + /* + * Get the window in which a raise or lower is in relation to. + */ + if (otherPtr != NULL) { + if (otherPtr->window == None) { + Tk_MakeWindowExist((Tk_Window) otherPtr); + } + if (otherPtr->wmInfoPtr->flags & WM_NEVER_MAPPED) { + TkWmMapWindow(otherPtr); + } + otherMacWindow = (WindowPeek) TkMacGetDrawablePort(otherPtr->window); + } else { + otherMacWindow = NULL; + } + + frontWindow = (WindowPeek) FrontWindow(); + if (aboveBelow == Above) { + if (macWindow == frontWindow) { + /* + * Do nothing - it's already at the top. + */ + } else if (otherMacWindow == frontWindow || otherMacWindow == NULL) { + /* + * Raise the window to the top. If the window is visable then + * we also make it the active window. + */ + + if (wmPtr->hints.initial_state == WithdrawnState) { + BringToFront((WindowPtr) macWindow); + } else { + SelectWindow((WindowPtr) macWindow); + } + } else { + /* + * Find the window to be above. (Front window will actually be the + * window to be behind.) Front window is NULL if no other windows. + */ + while (frontWindow != NULL && + frontWindow->nextWindow != otherMacWindow) { + frontWindow = frontWindow->nextWindow; + } + if (frontWindow != NULL) { + SendBehind((WindowPtr) macWindow, (WindowPtr) frontWindow); + } + } + } else { + /* + * Send behind. If it was in front find another window to make active. + */ + if (macWindow == frontWindow) { + if (macWindow->nextWindow != NULL) { + SelectWindow((WindowPtr) macWindow->nextWindow); + } + } + SendBehind((WindowPtr) macWindow, (WindowPtr) otherMacWindow); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWmAddToColormapWindows -- + * + * This procedure is called to add a given window to the + * WM_COLORMAP_WINDOWS property for its top-level, if it + * isn't already there. It is invoked by the Tk code that + * creates a new colormap, in order to make sure that colormap + * information is propagated to the window manager by default. + * + * Results: + * None. + * + * Side effects: + * WinPtr's window gets added to the WM_COLORMAP_WINDOWS + * property of its nearest top-level ancestor, unless the + * colormaps have been set explicitly with the + * "wm colormapwindows" command. + * + *---------------------------------------------------------------------- + */ + +void +TkWmAddToColormapWindows( + TkWindow *winPtr) /* Window with a non-default colormap. + * Should not be a top-level window. */ +{ + TkWindow *topPtr; + TkWindow **oldPtr, **newPtr; + int count, i; + + if (winPtr->window == None) { + return; + } + + for (topPtr = winPtr->parentPtr; ; topPtr = topPtr->parentPtr) { + if (topPtr == NULL) { + /* + * Window is being deleted. Skip the whole operation. + */ + + return; + } + if (topPtr->flags & TK_TOP_LEVEL) { + break; + } + } + if (topPtr->wmInfoPtr->flags & WM_COLORMAPS_EXPLICIT) { + return; + } + + /* + * Make sure that the window isn't already in the list. + */ + + count = topPtr->wmInfoPtr->cmapCount; + oldPtr = topPtr->wmInfoPtr->cmapList; + + for (i = 0; i < count; i++) { + if (oldPtr[i] == winPtr) { + return; + } + } + + /* + * Make a new bigger array and use it to reset the property. + * Automatically add the toplevel itself as the last element + * of the list. + */ + + newPtr = (TkWindow **) ckalloc((unsigned) ((count+2)*sizeof(TkWindow*))); + if (count > 0) { + memcpy(newPtr, oldPtr, count * sizeof(TkWindow*)); + } + if (count == 0) { + count++; + } + newPtr[count-1] = winPtr; + newPtr[count] = topPtr; + if (oldPtr != NULL) { + ckfree((char *) oldPtr); + } + + topPtr->wmInfoPtr->cmapList = newPtr; + topPtr->wmInfoPtr->cmapCount = count+1; + + /* + * On the Macintosh all of this is just an excercise + * in compatability as we don't support colormaps. If + * we did they would be installed here. + */ +} + +/* + *---------------------------------------------------------------------- + * + * TkWmRemoveFromColormapWindows -- + * + * This procedure is called to remove a given window from the + * WM_COLORMAP_WINDOWS property for its top-level. It is invoked + * when windows are deleted. + * + * Results: + * None. + * + * Side effects: + * WinPtr's window gets removed from the WM_COLORMAP_WINDOWS + * property of its nearest top-level ancestor, unless the + * top-level itself is being deleted too. + * + *---------------------------------------------------------------------- + */ + +void +TkWmRemoveFromColormapWindows( + TkWindow *winPtr) /* Window that may be present in + * WM_COLORMAP_WINDOWS property for its + * top-level. Should not be a top-level + * window. */ +{ + TkWindow *topPtr; + TkWindow **oldPtr; + int count, i, j; + + for (topPtr = winPtr->parentPtr; ; topPtr = topPtr->parentPtr) { + if (topPtr == NULL) { + /* + * Ancestors have been deleted, so skip the whole operation. + * Seems like this can't ever happen? + */ + + return; + } + if (topPtr->flags & TK_TOP_LEVEL) { + break; + } + } + if (topPtr->flags & TK_ALREADY_DEAD) { + /* + * Top-level is being deleted, so there's no need to cleanup + * the WM_COLORMAP_WINDOWS property. + */ + + return; + } + + /* + * Find the window and slide the following ones down to cover + * it up. + */ + + count = topPtr->wmInfoPtr->cmapCount; + oldPtr = topPtr->wmInfoPtr->cmapList; + for (i = 0; i < count; i++) { + if (oldPtr[i] == winPtr) { + for (j = i ; j < count-1; j++) { + oldPtr[j] = oldPtr[j+1]; + } + topPtr->wmInfoPtr->cmapCount = count - 1; + break; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkGetPointerCoords -- + * + * Fetch the position of the mouse pointer. + * + * Results: + * *xPtr and *yPtr are filled in with the (virtual) root coordinates + * of the mouse pointer for tkwin's display. If the pointer isn't + * on tkwin's screen, then -1 values are returned for both + * coordinates. The argument tkwin must be a toplevel window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkGetPointerCoords( + Tk_Window tkwin, /* Toplevel window that identifies screen + * on which lookup is to be done. */ + int *xPtr, int *yPtr) /* Store pointer coordinates here. */ +{ + Point where; + + GetMouse(&where); + LocalToGlobal(&where); + *xPtr = where.h; + *yPtr = where.v; +} + +/* + *---------------------------------------------------------------------- + * + * InitialWindowBounds -- + * + * This function calculates the initial bounds for a new Mac + * toplevel window. Unless the geometry is specified by the user + * this code will auto place the windows in a cascade diagonially + * across the main monitor of the Mac. + * + * Results: + * The bounds are returned in geometry. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +InitialWindowBounds( + TkWindow *winPtr, /* Window to get initial bounds for. */ + Rect *geometry) /* On return the initial bounds. */ +{ + int x, y; + static int defaultX = 5; + static int defaultY = 45; + + if (!(winPtr->wmInfoPtr->sizeHintsFlags & (USPosition | PPosition))) { + /* + * We will override the program & hopefully place the + * window in a "better" location. + */ + + if (((tcl_macQdPtr->screenBits.bounds.right - defaultX) < 30) || + ((tcl_macQdPtr->screenBits.bounds.bottom - defaultY) < 30)) { + defaultX = 5; + defaultY = 45; + } + x = defaultX; + y = defaultY; + defaultX += 20; + defaultY += 20; + } else { + x = winPtr->wmInfoPtr->x; + y = winPtr->wmInfoPtr->y; + } + + geometry->left = x; + geometry->top = y; + geometry->right = x + winPtr->changes.width; + geometry->bottom = y + winPtr->changes.height; +} + +/* + *---------------------------------------------------------------------- + * + * TkMacResizable -- + * + * This function determines if the passed in window is part of + * a toplevel window that is resizable. If the window is + * resizable in the x, y or both directions, true is returned. + * + * Results: + * True if resizable, false otherwise. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkMacResizable( + TkWindow *winPtr) /* Tk window or NULL. */ +{ + WmInfo *wmPtr; + + if (winPtr == NULL) { + return false; + } + while (winPtr->wmInfoPtr == NULL) { + winPtr = winPtr->parentPtr; + } + + wmPtr = winPtr->wmInfoPtr; + if ((wmPtr->flags & WM_WIDTH_NOT_RESIZABLE) && + (wmPtr->flags & WM_HEIGHT_NOT_RESIZABLE)) { + return false; + } else { + return true; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacGrowToplevel -- + * + * The function is invoked when the user clicks in the grow region + * of a Tk window. The function will handle the dragging + * procedure and not return until completed. Finally, the function + * may place information Tk's event queue is the window was resized. + * + * Results: + * True if events were placed on event queue, false otherwise. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkMacGrowToplevel( + WindowPtr whichWindow, + Point start) +{ + Point where = start; + + GlobalToLocal(&where); + if (where.h > (whichWindow->portRect.right - 16) && + where.v > (whichWindow->portRect.bottom - 16)) { + + Window window; + TkWindow *winPtr; + WmInfo *wmPtr; + Rect bounds; + long growResult; + + window = TkMacGetXWindow(whichWindow); + winPtr = (TkWindow *) Tk_IdToWindow(tkDisplayList->display, window); + wmPtr = winPtr->wmInfoPtr; + + /* TODO: handle grid size options. */ + if ((wmPtr->flags & WM_WIDTH_NOT_RESIZABLE) && + (wmPtr->flags & WM_HEIGHT_NOT_RESIZABLE)) { + return false; + } + if (wmPtr->flags & WM_WIDTH_NOT_RESIZABLE) { + bounds.left = bounds.right = winPtr->changes.width; + } else { + bounds.left = (wmPtr->minWidth < 64) ? 64 : wmPtr->minWidth; + bounds.right = (wmPtr->maxWidth < 64) ? 64 : wmPtr->maxWidth; + } + if (wmPtr->flags & WM_HEIGHT_NOT_RESIZABLE) { + bounds.top = bounds.bottom = winPtr->changes.height; + } else { + bounds.top = (wmPtr->minHeight < 64) ? 64 : wmPtr->minHeight; + bounds.bottom = (wmPtr->maxHeight < 64) ? 64 : wmPtr->maxHeight; + } + + growResult = GrowWindow(whichWindow, start, &bounds); + + if (growResult != 0) { + SizeWindow(whichWindow, + LoWord(growResult), HiWord(growResult), true); + SetPort(whichWindow); + InvalRect(&whichWindow->portRect); /* TODO: may not be needed */ + TkMacInvalClipRgns(winPtr); + TkGenWMConfigureEvent((Tk_Window) winPtr, -1, -1, + (int) LoWord(growResult), (int) HiWord(growResult), + TK_SIZE_CHANGED); + return true; + } + return false; + } + return false; +} + +/* + *---------------------------------------------------------------------- + * + * TkSetWMName -- + * + * Set the title for a toplevel window. If the window is embedded, + * do not change the window title. + * + * Results: + * None. + * + * Side effects: + * The title of the window is changed. + * + *---------------------------------------------------------------------- + */ + +void +TkSetWMName( + TkWindow *winPtr, + Tk_Uid titleUid) +{ + Str255 pTitle; + GWorldPtr macWin; + + if (Tk_IsEmbedded(winPtr)) { + return; + } + + macWin = TkMacGetDrawablePort(winPtr->window); + + strcpy((char *) pTitle + 1, titleUid); + pTitle[0] = strlen(titleUid); + SetWTitle((WindowPtr) macWin, pTitle); +} + +void +TkGenWMDestroyEvent( + Tk_Window tkwin) +{ + XEvent event; + + event.xany.serial = Tk_Display(tkwin)->request; + event.xany.send_event = False; + event.xany.display = Tk_Display(tkwin); + + event.xclient.window = Tk_WindowId(tkwin); + event.xclient.type = ClientMessage; + event.xclient.message_type = Tk_InternAtom(tkwin, "WM_PROTOCOLS"); + event.xclient.format = 32; + event.xclient.data.l[0] = Tk_InternAtom(tkwin, "WM_DELETE_WINDOW"); + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); +} + +/* + *---------------------------------------------------------------------- + * + * TkGenWMConfigureEvent -- + * + * Generate a ConfigureNotify event for Tk. Depending on the + * value of flag the values of width/height, x/y, or both may + * be changed. + * + * Results: + * None. + * + * Side effects: + * A ConfigureNotify event is sent to Tk. + * + *---------------------------------------------------------------------- + */ + +void +TkGenWMConfigureEvent( + Tk_Window tkwin, + int x, + int y, + int width, + int height, + int flags) +{ + XEvent event; + WmInfo *wmPtr; + TkWindow *winPtr = (TkWindow *) tkwin; + + if (tkwin == NULL) { + return; + } + + event.type = ConfigureNotify; + event.xconfigure.serial = Tk_Display(tkwin)->request; + event.xconfigure.send_event = False; + event.xconfigure.display = Tk_Display(tkwin); + event.xconfigure.event = Tk_WindowId(tkwin); + event.xconfigure.window = Tk_WindowId(tkwin); + event.xconfigure.border_width = winPtr->changes.border_width; + event.xconfigure.override_redirect = winPtr->atts.override_redirect; + if (winPtr->changes.stack_mode == Above) { + event.xconfigure.above = winPtr->changes.sibling; + } else { + event.xconfigure.above = None; + } + + if (flags & TK_LOCATION_CHANGED) { + event.xconfigure.x = x; + event.xconfigure.y = y; + } else { + event.xconfigure.x = Tk_X(tkwin); + event.xconfigure.y = Tk_Y(tkwin); + x = Tk_X(tkwin); + y = Tk_Y(tkwin); + } + if (flags & TK_SIZE_CHANGED) { + event.xconfigure.width = width; + event.xconfigure.height = height; + } else { + event.xconfigure.width = Tk_Width(tkwin); + event.xconfigure.height = Tk_Height(tkwin); + width = Tk_Width(tkwin); + height = Tk_Height(tkwin); + } + + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + + /* + * Update window manager information. + */ + if (Tk_IsTopLevel(winPtr)) { + wmPtr = winPtr->wmInfoPtr; + if (flags & TK_LOCATION_CHANGED) { + wmPtr->x = x; + wmPtr->y = y; + wmPtr->flags &= ~(WM_NEGATIVE_X | WM_NEGATIVE_Y); + } + if ((flags & TK_SIZE_CHANGED) && + ((width != Tk_Width(tkwin)) || (height != Tk_Height(tkwin)))) { + if ((wmPtr->width == -1) && (width == winPtr->reqWidth)) { + /* + * Don't set external width, since the user didn't change it + * from what the widgets asked for. + */ + } else { + if (wmPtr->gridWin != NULL) { + wmPtr->width = wmPtr->reqGridWidth + + (width - winPtr->reqWidth)/wmPtr->widthInc; + if (wmPtr->width < 0) { + wmPtr->width = 0; + } + } else { + wmPtr->width = width; + } + } + if ((wmPtr->height == -1) && (height == winPtr->reqHeight)) { + /* + * Don't set external height, since the user didn't change it + * from what the widgets asked for. + */ + } else { + if (wmPtr->gridWin != NULL) { + wmPtr->height = wmPtr->reqGridHeight + + (height - winPtr->reqHeight)/wmPtr->heightInc; + if (wmPtr->height < 0) { + wmPtr->height = 0; + } + } else { + wmPtr->height = height; + } + } + wmPtr->configWidth = width; + wmPtr->configHeight = height; + } + } + + /* + * Now set up the changes structure. Under X we wait for the + * ConfigureNotify to set these values. On the Mac we know imediatly that + * this is what we want - so we just set them. However, we need to + * make sure the windows clipping region is marked invalid so the + * change is visable to the subwindow. + */ + winPtr->changes.x = x; + winPtr->changes.y = y; + winPtr->changes.width = width; + winPtr->changes.height = height; + TkMacInvalClipRgns(winPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TkGetTransientMaster -- + * + * If the passed window has the TRANSIENT_FOR property set this + * will return the master window. Otherwise it will return None. + * + * Results: + * The master window or None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Window +TkGetTransientMaster( + TkWindow *winPtr) +{ + if (winPtr->wmInfoPtr != NULL) { + return winPtr->wmInfoPtr->master; + } + return None; +} + +/* + *---------------------------------------------------------------------- + * + * TkMacGetXWindow -- + * + * Returns the X window Id associated with the given WindowRef. + * + * Results: + * The window id is returned. None is returned if not a Tk window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Window +TkMacGetXWindow( + WindowRef macWinPtr) +{ + register Tcl_HashEntry *hPtr; + + if ((macWinPtr == NULL) || !windowHashInit) { + return None; + } + hPtr = Tcl_FindHashEntry(&windowTable, (char *) macWinPtr); + if (hPtr == NULL) { + return None; + } + return (Window) Tcl_GetHashValue(hPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TkMacZoomToplevel -- + * + * The function is invoked when the user clicks in the zoom region + * of a Tk window. The function will handle the mouse tracking + * for the interaction. If the window is to be zoomed the window + * size is changed and events are generated to let Tk know what + * happened. + * + * Results: + * True if events were placed on event queue, false otherwise. + * + * Side effects: + * The window may be resized & events placed on Tk's queue. + * + *---------------------------------------------------------------------- + */ + +int +TkMacZoomToplevel( + WindowPtr whichWindow, /* The Macintosh window to zoom. */ + Point where, /* The current mouse position. */ + short zoomPart) /* Either inZoomIn or inZoomOut */ +{ + Window window; + Tk_Window tkwin; + Point location = {0, 0}; + int xOffset, yOffset; + WmInfo *wmPtr; + + SetPort(whichWindow); + if (!TrackBox(whichWindow, where, zoomPart)) { + return false; + } + + /* + * We should now zoom the window (as long as it's one of ours). We + * also need to generate an event to let Tk know that the window size + * has changed. + */ + window = TkMacGetXWindow(whichWindow); + tkwin = Tk_IdToWindow(tkDisplayList->display, window); + if (tkwin == NULL) { + return false; + } + + /* + * The following block of code works around a bug in the window + * definition for Apple's floating windows. The zoom behavior is + * broken - we must manually set the standard state (by default + * it's something like 1x1) and we must swap the zoomPart manually + * otherwise we always get the same zoomPart and nothing happens. + */ + wmPtr = ((TkWindow *) tkwin)->wmInfoPtr; + if (wmPtr->style >= floatProc && wmPtr->style <= floatSideZoomGrowProc) { + if (zoomPart == inZoomIn) { + Rect zoomRect = tcl_macQdPtr->screenBits.bounds; + InsetRect(&zoomRect, 60, 60); + SetWindowStandardState(whichWindow, &zoomRect); + zoomPart = inZoomOut; + } else { + zoomPart = inZoomIn; + } + } + + ZoomWindow(whichWindow, zoomPart, false); + InvalRect(&whichWindow->portRect); + TkMacInvalClipRgns((TkWindow *) tkwin); + + LocalToGlobal(&location); + TkMacWindowOffset(whichWindow, &xOffset, &yOffset); + location.h -= xOffset; + location.v -= yOffset; + TkGenWMConfigureEvent(tkwin, location.h, location.v, + whichWindow->portRect.right - whichWindow->portRect.left, + whichWindow->portRect.bottom - whichWindow->portRect.top, + TK_BOTH_CHANGED); + return true; +} + +/* + *---------------------------------------------------------------------- + * + * TkUnsupported1Cmd -- + * + * This procedure is invoked to process the "unsupported1" Tcl + * command. This command allows you to set the style of decoration + * for a Macintosh window. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * Changes the style of a new Mac window. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +TkUnsupported1Cmd( + ClientData clientData, /* Main window associated with + * interpreter. */ + Tcl_Interp *interp, /* Current interpreter. */ + int argc, /* Number of arguments. */ + char **argv) /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + TkWindow *winPtr; + register WmInfo *wmPtr; + int c; + size_t length; + + if (argc < 3) { + wrongNumArgs: + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option window ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[2], tkwin); + if (winPtr == NULL) { + return TCL_ERROR; + } + if (!(winPtr->flags & TK_TOP_LEVEL)) { + Tcl_AppendResult(interp, "window \"", winPtr->pathName, + "\" isn't a top-level window", (char *) NULL); + return TCL_ERROR; + } + wmPtr = winPtr->wmInfoPtr; + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 's') && (strncmp(argv[1], "style", length) == 0)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " style window ?windowStyle?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + switch (wmPtr->style) { + case noGrowDocProc: + case documentProc: + interp->result = "documentProc"; + break; + case dBoxProc: + interp->result = "dBoxProc"; + break; + case plainDBox: + interp->result = "plainDBox"; + break; + case altDBoxProc: + interp->result = "altDBoxProc"; + break; + case movableDBoxProc: + interp->result = "movableDBoxProc"; + break; + case zoomDocProc: + case zoomNoGrow: + interp->result = "zoomDocProc"; + break; + case rDocProc: + interp->result = "rDocProc"; + break; + case floatProc: + case floatGrowProc: + interp->result = "floatProc"; + break; + case floatZoomProc: + case floatZoomGrowProc: + interp->result = "floatZoomProc"; + break; + case floatSideProc: + case floatSideGrowProc: + interp->result = "floatSideProc"; + break; + case floatSideZoomProc: + case floatSideZoomGrowProc: + interp->result = "floatSideZoomProc"; + break; + default: + panic("invalid style"); + } + return TCL_OK; + } + if (strcmp(argv[3], "documentProc") == 0) { + wmPtr->style = documentProc; + } else if (strcmp(argv[3], "noGrowDocProc") == 0) { + wmPtr->style = documentProc; + } else if (strcmp(argv[3], "dBoxProc") == 0) { + wmPtr->style = dBoxProc; + } else if (strcmp(argv[3], "plainDBox") == 0) { + wmPtr->style = plainDBox; + } else if (strcmp(argv[3], "altDBoxProc") == 0) { + wmPtr->style = altDBoxProc; + } else if (strcmp(argv[3], "movableDBoxProc") == 0) { + wmPtr->style = movableDBoxProc; + } else if (strcmp(argv[3], "zoomDocProc") == 0) { + wmPtr->style = zoomDocProc; + } else if (strcmp(argv[3], "zoomNoGrow") == 0) { + wmPtr->style = zoomNoGrow; + } else if (strcmp(argv[3], "rDocProc") == 0) { + wmPtr->style = rDocProc; + } else if (strcmp(argv[3], "floatProc") == 0) { + wmPtr->style = floatGrowProc; + } else if (strcmp(argv[3], "floatGrowProc") == 0) { + wmPtr->style = floatGrowProc; + } else if (strcmp(argv[3], "floatZoomProc") == 0) { + wmPtr->style = floatZoomGrowProc; + } else if (strcmp(argv[3], "floatZoomGrowProc") == 0) { + wmPtr->style = floatZoomGrowProc; + } else if (strcmp(argv[3], "floatSideProc") == 0) { + wmPtr->style = floatSideGrowProc; + } else if (strcmp(argv[3], "floatSideGrowProc") == 0) { + wmPtr->style = floatSideGrowProc; + } else if (strcmp(argv[3], "floatSideZoomProc") == 0) { + wmPtr->style = floatSideZoomGrowProc; + } else if (strcmp(argv[3], "floatSideZoomGrowProc") == 0) { + wmPtr->style = floatSideZoomGrowProc; + } else { + Tcl_AppendResult(interp, "bad style: should be documentProc, ", + "dBoxProc, plainDBox, altDBoxProc, movableDBoxProc, ", + "zoomDocProc, rDocProc, floatProc, floatZoomProc, ", + "floatSideProc, or floatSideZoomProc", + (char *) NULL); + return TCL_ERROR; + } + } else { + Tcl_AppendResult(interp, "unknown or ambiguous option \"", argv[1], + "\": must be style", + (char *) NULL); + return TCL_ERROR; + } + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpMakeMenuWindow -- + * + * Configure the window to be either a undecorated pull-down + * (or pop-up) menu, or as a toplevel floating menu (palette). + * + * Results: + * None. + * + * Side effects: + * Changes the style bit used to create a new Mac toplevel. + * + *---------------------------------------------------------------------- + */ + +void +TkpMakeMenuWindow( + Tk_Window tkwin, /* New window. */ + int transient) /* 1 means menu is only posted briefly as + * a popup or pulldown or cascade. 0 means + * menu is always visible, e.g. as a + * floating menu. */ +{ + if (transient) { + ((TkWindow *) tkwin)->wmInfoPtr->style = plainDBox; + } else { + ((TkWindow *) tkwin)->wmInfoPtr->style = floatProc; + ((TkWindow *) tkwin)->wmInfoPtr->flags |= WM_WIDTH_NOT_RESIZABLE; + ((TkWindow *) tkwin)->wmInfoPtr->flags |= WM_HEIGHT_NOT_RESIZABLE; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacMakeRealWindowExist -- + * + * This function finally creates the real Macintosh window that + * the Mac actually understands. + * + * Results: + * None. + * + * Side effects: + * A new Macintosh toplevel is created. + * + *---------------------------------------------------------------------- + */ + +void +TkMacMakeRealWindowExist( + TkWindow *winPtr) /* Tk window. */ +{ + WmInfo *wmPtr = winPtr->wmInfoPtr; + WindowRef newWindow = NULL; + MacDrawable *macWin; + Rect geometry; + Tcl_HashEntry *valueHashPtr; + int new; + TkMacWindowList *listPtr; + + if (TkMacHostToplevelExists(winPtr)) { + return; + } + + macWin = (MacDrawable *) winPtr->window; + + /* + * If this is embedded, make sure its container's toplevel exists, + * then return... + */ + + if (Tk_IsEmbedded(winPtr)) { + TkWindow *contWinPtr; + + contWinPtr = TkpGetOtherWindow(winPtr); + if (contWinPtr != NULL) { + TkMacMakeRealWindowExist(contWinPtr->privatePtr->toplevel->winPtr); + macWin->flags |= TK_HOST_EXISTS; + return; + } else { + panic("TkMacMakeRealWindowExist could not find container"); + } + + /* + * NOTE: Here we should handle out of process embedding. + */ + + } + + InitialWindowBounds(winPtr, &geometry); + + newWindow = NewCWindow(NULL, &geometry, "\ptemp", false, + (short) wmPtr->style, (WindowRef) -1, true, 0); + if (newWindow == NULL) { + panic("couldn't allocate new Mac window"); + } + + /* + * Add this window to the list of toplevel windows. + */ + + listPtr = (TkMacWindowList *) ckalloc(sizeof(TkMacWindowList)); + listPtr->nextPtr = tkMacWindowListPtr; + listPtr->winPtr = winPtr; + tkMacWindowListPtr = listPtr; + + macWin->portPtr = (GWorldPtr) newWindow; + MacMoveWindow(newWindow, (int) geometry.left, (int) geometry.top); + SetPort((GrafPtr) newWindow); + + if (!windowHashInit) { + Tcl_InitHashTable(&windowTable, TCL_ONE_WORD_KEYS); + windowHashInit = true; + } + valueHashPtr = Tcl_CreateHashEntry(&windowTable, + (char *) newWindow, &new); + if (!new) { + panic("same macintosh window allocated twice!"); + } + Tcl_SetHashValue(valueHashPtr, macWin); + + macWin->flags |= TK_HOST_EXISTS; +} + +/* + *---------------------------------------------------------------------- + * + * TkMacRegisterOffScreenWindow -- + * + * This function adds the passed in Off Screen Port to the + * hash table that maps Mac windows to root X windows. + * + * Results: + * None. + * + * Side effects: + * An entry is added to the windowTable hash table. + * + *---------------------------------------------------------------------- + */ + +void +TkMacRegisterOffScreenWindow( + Window window, /* Window structure. */ + GWorldPtr portPtr) /* Pointer to a Mac GWorld. */ +{ + WindowRef newWindow = NULL; + MacDrawable *macWin; + Tcl_HashEntry *valueHashPtr; + int new; + + macWin = (MacDrawable *) window; + if (!windowHashInit) { + Tcl_InitHashTable(&windowTable, TCL_ONE_WORD_KEYS); + windowHashInit = true; + } + valueHashPtr = Tcl_CreateHashEntry(&windowTable, + (char *) portPtr, &new); + if (!new) { + panic("same macintosh window allocated twice!"); + } + Tcl_SetHashValue(valueHashPtr, macWin); +} + +/* + *---------------------------------------------------------------------- + * + * TkMacUnregisterMacWindow -- + * + * Given a macintosh port window, this function removes the + * association between this window and the root X window that + * Tk cares about. + * + * Results: + * None. + * + * Side effects: + * An entry is removed from the windowTable hash table. + * + *---------------------------------------------------------------------- + */ + +void +TkMacUnregisterMacWindow( + GWorldPtr portPtr) /* Pointer to a Mac GWorld. */ +{ + if (!windowHashInit) { + panic("TkMacUnregisterMacWindow: unmapping before inited");; + } + Tcl_DeleteHashEntry(Tcl_FindHashEntry(&windowTable, + (char *) portPtr)); +} + +/* + *---------------------------------------------------------------------- + * + * TkMacSetScrollbarGrow -- + * + * Sets a flag for a toplevel window indicating that the passed + * Tk scrollbar window will display the grow region for the + * toplevel window. + * + * Results: + * None. + * + * Side effects: + * A flag is set int windows toplevel parent. + * + *---------------------------------------------------------------------- + */ + +void +TkMacSetScrollbarGrow( + TkWindow *winPtr, /* Tk scrollbar window. */ + int flag) /* Boolean value true or false. */ +{ + if (flag) { + winPtr->privatePtr->toplevel->flags |= TK_SCROLLBAR_GROW; + winPtr->privatePtr->toplevel->winPtr->wmInfoPtr->scrollWinPtr = winPtr; + } else if (winPtr->privatePtr->toplevel->winPtr->wmInfoPtr->scrollWinPtr + == winPtr) { + winPtr->privatePtr->toplevel->flags &= ~TK_SCROLLBAR_GROW; + winPtr->privatePtr->toplevel->winPtr->wmInfoPtr->scrollWinPtr = NULL; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkMacGetScrollbarGrowWindow -- + * + * Tests to see if a given window's toplevel window contains a + * scrollbar that will draw the GrowIcon for the window. + * + * Results: + * Boolean value. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkMacGetScrollbarGrowWindow( + TkWindow *winPtr) /* Tk window. */ +{ + TkWindow *scrollWinPtr; + + if (winPtr == NULL) { + return NULL; + } + scrollWinPtr = + winPtr->privatePtr->toplevel->winPtr->wmInfoPtr->scrollWinPtr; + if (winPtr != NULL) { + /* + * We need to confirm the window exists. + */ + if ((Tk_Window) scrollWinPtr != + Tk_IdToWindow(winPtr->display, winPtr->window)) { + scrollWinPtr = NULL; + } + } + return scrollWinPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkWmFocusToplevel -- + * + * This is a utility procedure invoked by focus-management code. It + * exists because of the extra wrapper windows that exist under + * Unix; its job is to map from wrapper windows to the + * corresponding toplevel windows. On PCs and Macs there are no + * wrapper windows so no mapping is necessary; this procedure just + * determines whether a window is a toplevel or not. + * + * Results: + * If winPtr is a toplevel window, returns the pointer to the + * window; otherwise returns NULL. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkWmFocusToplevel( + TkWindow *winPtr) /* Window that received a focus-related + * event. */ +{ + if (!(winPtr->flags & TK_TOP_LEVEL)) { + return NULL; + } + return winPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetWrapperWindow -- + * + * This is a utility procedure invoked by focus-management code. It + * maps to the wrapper for a top-level, which is just the same + * as the top-level on Macs and PCs. + * + * Results: + * If winPtr is a toplevel window, returns the pointer to the + * window; otherwise returns NULL. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkpGetWrapperWindow( + TkWindow *winPtr) /* Window that received a focus-related + * event. */ +{ + if (!(winPtr->flags & TK_TOP_LEVEL)) { + return NULL; + } + return winPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpWmSetState -- + * + * Sets the window manager state for the wrapper window of a + * given toplevel window. + * + * Results: + * None. + * + * Side effects: + * May maximize, minimize, restore, or withdraw a window. + * + *---------------------------------------------------------------------- + */ + +void +TkpWmSetState(winPtr, state) + TkWindow *winPtr; /* Toplevel window to operate on. */ + int state; /* One of IconicState, ZoomState, NormalState, + * or WithdrawnState. */ +{ + WmInfo *wmPtr = winPtr->wmInfoPtr; + GWorldPtr macWin; + + wmPtr->hints.initial_state = state; + if (wmPtr->flags & WM_NEVER_MAPPED) { + return; + } + + macWin = TkMacGetDrawablePort(winPtr->window); + + if (state == WithdrawnState) { + Tk_UnmapWindow((Tk_Window) winPtr); + } else if (state == IconicState) { + Tk_UnmapWindow((Tk_Window) winPtr); +#ifdef HAVE_APPEARANCE + if (HaveAppearance()) { + /* + * The window always gets unmapped. However, if we can show the + * icon version of the window (collapsed) we make the window visable + * and then collapse it. + * + * TODO: This approach causes flashing! + */ + + if (IsWindowCollapsable((WindowRef) macWin)) { + ShowWindow((WindowRef) macWin); + CollapseWindow((WindowPtr) macWin, true); + } + } +#endif + } else if (state == NormalState) { + Tk_MapWindow((Tk_Window) winPtr); +#ifdef HAVE_APPEARANCE + if (HaveAppearance()) { + CollapseWindow((WindowPtr) macWin, false); + } +#endif + } else if (state == ZoomState) { + /* TODO: need to support zoomed windows */ + } +} +/* + *---------------------------------------------------------------------- + * + * HaveAppearance -- + * + * Determine if the appearance manager is available on this Mac. + * We cache the result so future calls are fast. + * + * Results: + * True if the appearance manager is present, false otherwise. + * + * Side effects: + * Calls Gestalt to query system values. + * + *---------------------------------------------------------------------- + */ + +static int +HaveAppearance() +{ + static initialized = false; + static int haveAppearance = false; + long response = 0; + OSErr err = noErr; + +#ifdef HAVE_APPEARANCE + if (!initialized) { + err = Gestalt(gestaltAppearanceAttr, &response); + if (err == noErr) { + haveAppearance = true; + } + } +#endif + + return haveAppearance; +} diff --git a/mac/tkMacXCursors.r b/mac/tkMacXCursors.r new file mode 100644 index 0000000..29ddc3e --- /dev/null +++ b/mac/tkMacXCursors.r @@ -0,0 +1,961 @@ +/* + * tkMacXCursors.r -- + * + * This file defines a set of Macintosh cursor resources that + * emulate the X cursor set. All of these cursors were + * constructed and donated by Grant Neufeld. (gneufeld@ccs.carleton.ca) + * + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacXCursors.r 1.4 96/01/11 13:18:22 + */ + +/* + * All of the X cursors are defined as 'CURS' resources. However, a + * subset of the X cursors are also defined as 'crsr' resources. Tk + * will attempt to first use the color cursors ('crsr') if it doesn't + * exist it will attempt to use the black & white cursor ('CURS'). + */ + +data 'CURS' (3000, "X_cursor") { + $"E007 F00F F81F 7C3E 3E7C 1FF8 0FF0 07E0" + $"07E0 0FF0 1FF8 3E7C 7C3E F81F F00F E007" + $"0000 6006 700E 381C 1C38 0E70 07E0 03C0" + $"03C0 07E0 0E70 1C38 381C 700E 6006 0000" + $"0007 0007" +}; + +data 'CURS' (3001, "arrow") { + $"0000 0006 001E 007C 01FC 07F8 00F8 01F0" + $"03B0 0720 0E20 1C00 3800 7000 2000 0000" + $"0007 001F 007F 01FE 07FE 1FFC 7FFC 03F8" + $"07F8 0FF0 1F70 3E60 7C60 F840 7040 2000" + $"0001 000E" +}; + +data 'CURS' (3002, "based_arrow_down") { + $"0000 0000 0000 1FE0 0000 1FE0 0300 0300" + $"0300 0B40 0780 0300 0000 0000 0000 0000" + $"0000 0000 0000 1FE0 0000 1FE0 0780 0780" + $"3FF0 1FE0 0FC0 0780 0300 0000 0000 0000" + $"000B 0006" +}; + +data 'CURS' (3003, "based_arrow_up") { + $"0000 0000 0000 0000 0300 0780 0B40 0300" + $"0300 0300 1FE0 0000 1FE0 0000 0000 0000" + $"0000 0000 0000 0300 0780 0FC0 1FE0 3FF0" + $"0780 0780 1FE0 0000 1FE0 0000 0000 0000" + $"0004 0006" +}; + +data 'CURS' (3004, "boat") { + $"0000 0000 0000 0000 0100 03C0 8460 FFFF" + $"0018 0020 0040 FFC0 0000 0000 0000 0000" + $"0000 0000 0000 0000 0100 03C0 87E0 FFFF" + $"FFF8 FFE0 FFC0 FFC0 0000 0000 0000 0000" + $"0007 000F" +}; + +data 'CURS' (3005, "bogosity") { + $"0000 711C 1110 1110 1110 7FFC 5114 5114" + $"5114 5114 7FFC 1110 1110 1110 711C 0000" + $"0000 0000 0000 0000 0000 7FFC 7FFC 7FFC" + $"7FFC 7FFC 7FFC 0000 0000 0000 0000 0000" + $"0001 0007" +}; + +data 'CURS' (3006, "bottom_left_corner") { + $"0000 0000 0000 0000 C000 C020 C840 C880" + $"C900 CA00 CC00 CFC0 C000 C000 FFF0 FFF0" + $"0000 0000 0000 0000 0000 0020 0840 0880" + $"0900 0A00 0C00 0FC0 0000 0000 0000 0000" + $"000F 0000" +}; + +data 'CURS' (3007, "bottom_right_corner") { + $"0000 0000 0000 0000 0003 0403 0213 0113" + $"0093 0053 0033 03F3 0003 0003 0FFF 0FFF" + $"0000 0000 0000 0000 0000 0400 0210 0110" + $"0090 0050 0030 03F0 0000 0000 0000 0000" + $"000F 000F" +}; + +data 'CURS' (3008, "bottom_side") { + $"0000 0000 0100 0100 0100 0100 0100 1110" + $"0920 0540 0380 0100 0000 7FFC 7FFC 0000" + $"0000 0000 0100 0100 0100 0100 0100 1110" + $"0920 0540 0380 0100 0000 0000 0000 0000" + $"000B 0007" +}; + +data 'CURS' (3009, "bottom_tee") { + $"0000 0000 0000 0180 0180 0180 0180 0180" + $"0180 0180 7FFE 7FFE 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"000B 0007" +}; + +data 'CURS' (3010, "box_spiral") { + $"FFFE 8000 BFFE A002 AFFA A80A ABEA AA2A" + $"AAAA ABAA A82A AFEA A00A BFFA 8002 FFFE" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0008 0008" +}; + +data 'CURS' (3011, "center_ptr") { + $"0000 0300 0300 0780 0780 0FC0 0FC0 1FE0" + $"1FE0 3330 2310 0300 0300 0300 0300 0000" + $"0300 0780 0780 0FC0 0FC0 1FE0 1FE0 3FF0" + $"3FF0 7FF8 77B8 6798 0780 0780 0780 0780" + $"0001 0006" +}; + +data 'CURS' (3012, "circle") { + $"0000 03C0 0FF0 1FF8 3C3C 381C 700E 700E" + $"700E 700E 381C 3C3C 1FF8 0FF0 03C0 0000" + $"03C0 0FF0 1FF8 3FFC 7FFE 7C3E F81F F81F" + $"F81F F81F 7C3E 7FFE 3FFC 1FF8 0FF0 03C0" + $"0007 0007" +}; + +data 'CURS' (3013, "clock") { + $"1FF8 33CC 6466 4992 4F12 4422 63C6 3FFC" + $"2994 2994 2994 2BD4 6996 781E 7FFE 7FFE" + $"1FF8 3FFC 7FFE 7FFE 7FFE 7FFE 7FFE 3FFC" + $"3FFC 3FFC 3FFC 3FFC 7FFE 7FFE 7FFE 7FFE" + $"0004 0008" +}; + +data 'CURS' (3014, "coffee_mug") { + $"03F8 0C06 1001 1C07 33F9 7001 D001 9001" + $"960D DA55 7A55 36ED 10A1 1001 0802 07FC" + $"03F8 0FFE 1FFF 1FFF 3FFF 7FFF FFFF FFFF" + $"FFFF FFFF 7FFF 3FFF 1FFF 1FFF 0FFE 07FC" + $"0004 0003" +}; + +data 'CURS' (3015, "cross") { + $"0280 0280 0280 0280 0280 0280 FEFE 0000" + $"FEFE 0280 0280 0280 0280 0280 0280 0000" + $"0380 0380 0380 0380 0380 0380 FFFE FFFE" + $"FFFE 0380 0380 0380 0380 0380 0380 0000" + $"0007 0007" +}; + +data 'CURS' (3016, "cross_reverse") { + $"4284 A28A 5294 2AA8 16D0 0AA0 FD7E 0280" + $"FD7E 0AA0 16D0 2AA8 5294 A28A 4284 0000" + $"4384 E38E 739C 3BB8 1FF0 0FE0 FFFE FFFE" + $"FFFE 0FE0 1FF0 3BB8 739C E38E 4384 0000" + $"0007 0007" +}; + +data 'CURS' (3017, "crosshair") { + $"0100 0100 0100 0100 0100 0100 0100 FEFE" + $"0100 0100 0100 0100 0100 0100 0100 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0007 0007" +}; + +data 'CURS' (3018, "diamond_cross") { + $"0280 06C0 0AA0 1290 2288 4284 FEFE 0000" + $"FEFE 4284 2288 1290 0AA0 06C0 0280 0000" + $"0280 06C0 0EE0 1EF0 3EF8 7EFC FEFE 0000" + $"FEFE 7EFC 3EF8 1EF0 0EE0 06C0 0280 0000" + $"0007 0007" +}; + +data 'CURS' (3019, "dot") { + $"0000 0000 0780 1FE0 1FE0 3FF0 3FF0 3FF0" + $"3FF0 1FE0 1FE0 0780 0000 0000 0000 0000" + $"0000 0780 1FE0 3FF0 3FF0 7FF8 7FF8 7FF8" + $"7FF8 3FF0 3FF0 1FE0 0780 0000 0000 0000" + $"0006 0006" +}; + +data 'CURS' (3020, "dotbox") { + $"0000 0000 3FFC 2004 2004 2004 2004 2184" + $"2184 2004 2004 2004 2004 3FFC 0000 0000" + $"0000 0000 3FFC 3FFC 300C 300C 318C 33CC" + $"33CC 318C 300C 300C 3FFC 3FFC 0000 0000" + $"0007 0007" +}; + +data 'CURS' (3021, "double_arrow") { + $"0000 0180 03C0 07E0 0DB0 1998 0180 0180" + $"0180 0180 1998 0DB0 07E0 03C0 0180 0000" + $"0180 03C0 07E0 0FF0 1FF8 3FFC 3BDC 03C0" + $"03C0 3BDC 3FFC 1FF8 0FF0 07E0 03C0 0180" + $"0007 0007" +}; + +data 'CURS' (3022, "draft_large") { + $"0000 0002 000C 003C 00F8 03F8 0FF0 00F0" + $"0160 0260 0440 0840 1000 2000 4000 0000" + $"0003 000F 003E 00FE 03FC 0FFC 3FF8 FFF8" + $"03F0 07F0 0EE0 1CE0 38C0 70C0 E080 4080" + $"0001 000E" +}; + +data 'CURS' (3023, "draft_small") { + $"0000 0002 000C 003C 00F8 03F8 0070 00B0" + $"0120 0220 0400 0800 1000 2000 4000 0000" + $"0003 000F 003E 00FE 03FC 0FFC 3FF8 01F8" + $"03F0 0770 0E60 1C60 3840 7040 E000 4000" + $"0001 000E" +}; + +data 'CURS' (3024, "draped_box") { + $"0000 0000 3FFC 2244 2664 2C34 381C 2184" + $"2184 381C 2C34 2664 2244 3FFC 0000 0000" + $"0000 0000 3FFC 3E7C 3E7C 3C3C 399C 23C4" + $"23C4 399C 3C3C 3E7C 3E7C 3FFC 0000 0000" + $"0007 0007" +}; + +data 'CURS' (3025, "exchange") { + $"0000 47C0 6FE0 7C30 4810 4C00 7E00 0000" + $"0000 00FC 0064 1024 187C 0FEC 07C4 0000" + $"C7C0 EFE0 FFF0 FFF8 FC38 FE10 FF00 FF80" + $"03FE 01FE 10FE 387E 3FFE 1FFE 0FEE 07C6" + $"0007 0007" +}; + +data 'CURS' (3026, "fleur") { + $"0000 0180 03C0 07E0 0180 1188 318C 7FFE" + $"7FFE 318C 1188 0180 07E0 03C0 0180 0000" + $"0180 03C0 07E0 0FF0 17E8 3BDC 7FFE FFFF" + $"FFFF 7FFE 3BDC 17E8 0FF0 07E0 03C0 0180" + $"0007 0007" +}; + +data 'CURS' (3027, "gobbler") { + $"0000 0078 0070 4036 4FB0 7FF0 7E30 7C30" + $"3038 00F0 0FE0 0400 0400 0400 0F00 0000" + $"00FC 00FC E0FF FFFF FFFF FFF8 FFF8 FFF8" + $"FFFC 7FFC 3FF8 1FF0 0E00 1F80 1F80 1F80" + $"0003 000E" +}; + +data 'CURS' (3028, "gumby") { + $"3F00 10C0 C820 EAA0 C820 CBA0 F838 383E" + $"0826 0826 092E 0926 0920 1110 2108 3EF8" + $"3F00 1FC0 CFE0 EFE0 CFE0 CFE0 FFF8 3FFE" + $"0FE6 0FE6 0FEE 0FE6 0FE0 1FF0 3FF8 3EF8" + $"0000 0002" +}; + +data 'CURS' (3029, "hand1") { + $"000C 003C 00F0 01E0 03C0 07E0 0FF0 2FE0" + $"7FF0 5FF0 07E0 07C0 4A00 6200 3400 1800" + $"000C 003C 00F0 01E0 03C0 07E0 0FF0 2FE0" + $"7FF0 7FF0 7FE0 7FC0 7E00 7E00 3C00 1800" + $"0000 000D" +}; + +data 'CURS' (3030, "hand2") { + $"0000 3FC0 4020 3F10 0808 0708 0808 0714" + $"0822 0641 0182 0124 0088 0050 0020 0000" + $"0000 3FC0 7FE0 3FF0 0FF8 07F8 0FF8 07FC" + $"0FFE 07FF 01FE 01FC 00F8 0070 0020 0000" + $"0002 0001" +}; + +data 'CURS' (3031, "heart") { + $"0000 3EF8 638C C106 8002 8002 8002 8002" + $"C006 600C 3018 1830 0C60 06C0 0380 0000" + $"0000 3EF8 7FFC FFFE FFFE FFFE FFFE FFFE" + $"FFFE 7FFC 3FF8 1FF0 0FE0 07C0 0380 0000" + $"0003 0007" +}; + +data 'CURS' (3032, "icon") { + $"FFFF D555 AAAB D555 A00B D005 A00B D005" + $"A00B D005 A00B D005 AAAB D555 AAAB FFFF" + $"FFFF FFFF FFFF FFFF F00F F00F F00F F00F" + $"F00F F00F F00F F00F FFFF FFFF FFFF FFFF" + $"0007 0007" +}; + +data 'CURS' (3033, "iron_cross") { + $"0000 3FFC 1FF8 4FF2 67E6 73CE 799E 7FFE" + $"7FFE 799E 73CE 67E6 4FF2 1FF8 3FFC 0000" + $"7FFE 7FFE FFFF FFFF FFFF FFFF FFFF FFFF" + $"FFFF FFFF FFFF FFFF FFFF FFFF 7FFE 7FFE" + $"0007 0006" +}; + +data 'CURS' (3034, "left_ptr") { + $"0000 0800 0C00 0E00 0F00 0F80 0FC0 0FE0" + $"0FF0 0F80 0D80 08C0 00C0 0060 0060 0000" + $"1800 1C00 1E00 1F00 1F80 1FC0 1FE0 1FF0" + $"1FF8 1FFC 1FC0 1DE0 19E0 10F0 00F0 0070" + $"0001 0004" +}; + +data 'CURS' (3035, "left_side") { + $"0000 6000 6000 6080 6100 6200 6400 6FFC" + $"6400 6200 6100 6080 6000 6000 0000 0000" + $"0000 0000 0000 0080 0100 0200 0400 0FFC" + $"0400 0200 0100 0080 0000 0000 0000 0000" + $"0007 0004" +}; + +data 'CURS' (3036, "left_tee") { + $"0000 0C00 0C00 0C00 0C00 0C00 0C00 0FF8" + $"0FF8 0C00 0C00 0C00 0C00 0C00 0C00 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0007 0004" +}; + +data 'CURS' (3037, "leftbutton") { + $"8002 7FFC 7FFC 4444 4554 4554 4554 4554" + $"4444 7FFC 7FFC 7FFC 7FFC 7FFC 7FFC 8002" + $"FFFE FFFE FFFE FFFE FFFE FFFE FFFE FFFE" + $"FFFE FFFE FFFE FFFE FFFE FFFE FFFE FFFE" + $"0004 0003" +}; + +data 'CURS' (3038, "ll_angle") { + $"0000 0000 0000 0C00 0C00 0C00 0C00 0C00" + $"0C00 0C00 0FF8 0FF8 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"000B 0004" +}; + +data 'CURS' (3039, "lr_angle") { + $"0000 0000 0000 0030 0030 0030 0030 0030" + $"0030 0030 1FF0 1FF0 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"000B 000B" +}; + +data 'CURS' (3040, "man") { + $"0380 1EF0 0280 8100 4387 244B 1D70 0540" + $"0440 0280 0440 0920 1290 1450 783C F83F" + $"0380 1FF0 0380 8100 4387 27CB 1FF0 07C0" + $"07C0 0380 07C0 0FE0 1EF0 1C70 783C F83F" + $"0001 0007" +}; + +data 'CURS' (3041, "middlebutton") { + $"8002 7FFC 7FFC 4444 5454 5454 5454 5454" + $"4444 7FFC 7FFC 7FFC 7FFC 7FFC 7FFC 8002" + $"FFFE FFFE FFFE FFFE FFFE FFFE FFFE FFFE" + $"FFFE FFFE FFFE FFFE FFFE FFFE FFFE FFFE" + $"0004 0007" +}; + +data 'CURS' (3042, "mouse") { + $"0600 0100 0180 0FF0 1008 17E8 1428 1428" + $"17E8 1008 1008 1008 1008 1008 1008 0FF0" + $"0600 0100 0180 0FF0 1FF8 1FF8 1FF8 1FF8" + $"1FF8 1FF8 1FF8 1FF8 1FF8 1FF8 1FF8 0FF0" + $"0000 0000" +}; + +data 'CURS' (3043, "pencil") { + $"0000 00F0 0088 0108 0190 0270 0220 0440" + $"0440 0880 0880 1100 1E00 1C00 1800 1000" + $"0000 00F0 00F8 01F8 01F0 03F0 03E0 07C0" + $"07C0 0F80 0F80 1F00 1E00 1C00 1800 1000" + $"000F 0003" +}; + +data 'CURS' (3044, "pirate") { + $"03C0 07E0 0FF0 1998 1998 0FF0 07E0 03C0" + $"43C2 43C3 2184 1C38 03C0 0FF1 781F 4002" + $"07E0 0FF0 1FF8 3FFC 3FFC 1FF8 0FF0 47E2" + $"E7E7 E7E7 7FFF 3FFC 1FF9 7FFF FFFF F81F" + $"000A 0007" +}; + +data 'CURS' (3045, "plus") { + $"0000 0000 0000 0180 0180 0180 0180 1FF8" + $"1FF8 0180 0180 0180 0180 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0007 0007" +}; + +data 'CURS' (3046, "question_arrow") { + $"07C0 0FE0 1C70 1830 1C30 0C70 00E0 03C0" + $"0380 0280 0280 0EE0 06C0 0380 0100 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 3FF8 1FF0 0FE0 07C0 0380 0100" + $"000E 0007" +}; + +data 'CURS' (3047, "right_ptr") { + $"0000 0010 0030 0070 00F0 01F0 03F0 07F0" + $"0FF0 01F0 01B0 0310 0300 0600 0600 0000" + $"0018 0038 0078 00F8 01F8 03F8 07F8 0FF8" + $"1FF8 3FF8 03F8 07B8 0798 0F08 0F00 0E00" + $"0001 000B" +}; + +data 'CURS' (3048, "right_side") { + $"0000 0000 0006 0006 0106 0086 0046 0026" + $"3FF6 0026 0046 0086 0106 0006 0006 0000" + $"0000 0000 0000 0000 0100 0080 0040 0020" + $"3FF0 0020 0040 0080 0100 0000 0000 0000" + $"0008 000B" +}; + +data 'CURS' (3049, "right_tee") { + $"0000 0030 0030 0030 0030 0030 0030 1FF0" + $"1FF0 0030 0030 0030 0030 0030 0030 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0007 000A" +}; + +data 'CURS' (3050, "rightbutton") { + $"8002 7FFC 7FFC 4444 5544 5544 5544 5544" + $"4444 7FFC 7FFC 7FFC 7FFC 7FFC 7FFC 8002" + $"FFFE FFFE FFFE FFFE FFFE FFFE FFFE FFFE" + $"FFFE FFFE FFFE FFFE FFFE FFFE FFFE FFFE" + $"0004 0003" +}; + +data 'CURS' (3051, "rtl_logo") { + $"0000 7FFE 4022 4022 4022 7FE2 4422 4422" + $"4422 4422 47FE 4402 4402 4402 7FFE 0000" + $"0000 7FFE 7FFE 6076 7FF6 7FF6 7C36 6C36" + $"6C36 6C3E 6FFE 6FFE 6E06 7FFE 7FFE 0000" + $"0007 0007" +}; + +data 'CURS' (3052, "sailboat") { + $"0000 0040 0040 0160 0160 0360 0370 0770" + $"0770 0F78 0F78 1F78 1F7C 3E38 0000 0000" + $"0040 00E0 01E0 03F0 03F0 07F0 07F8 0FF8" + $"0FF8 1FFC 1FFC 3FFC 3FFE 7F7C 7E38 0000" + $"000C 0008" +}; + +data 'CURS' (3053, "sb_down_arrow") { + $"0280 0280 0280 0280 0280 0280 0280 0280" + $"0280 0280 0280 0FE0 07C0 0380 0100 0000" + $"0380 0380 0380 0380 0380 0380 0380 0380" + $"0380 0380 0380 1FF0 0FE0 07C0 0380 0100" + $"000E 0007" +}; + +data 'CURS' (3054, "sb_h_double_arrow") { + $"0000 0000 0000 0000 0810 1818 3FFC 781E" + $"3FFC 1818 0810 0000 0000 0000 0000 0000" + $"0000 0000 0000 0810 1818 381C 7FFE FFFF" + $"7FFE 381C 1818 0810 0000 0000 0000 0000" + $"0007 0007" +}; + +data 'CURS' (3055, "sb_left_arrow") { + $"0000 0000 0000 0000 0800 1800 3FFF 7800" + $"3FFF 1800 0800 0000 0000 0000 0000 0000" + $"0000 0000 0000 0800 1800 3800 7FFF FFFF" + $"7FFF 3800 1800 0800 0000 0000 0000 0000" + $"0007 0001" +}; + +data 'CURS' (3056, "sb_right_arrow") { + $"0000 0000 0000 0000 0000 0010 0018 FFFC" + $"001E FFFC 0018 0010 0000 0000 0000 0000" + $"0000 0000 0000 0000 0010 0018 001C FFFE" + $"FFFF FFFE 001C 0018 0010 0000 0000 0000" + $"0008 000E" +}; + +data 'CURS' (3057, "sb_up_arrow") { + $"0000 0080 01C0 03E0 07F0 0140 0140 0140" + $"0140 0140 0140 0140 0140 0140 0140 0140" + $"0080 01C0 03E0 07F0 0FF8 01C0 01C0 01C0" + $"01C0 01C0 01C0 01C0 01C0 01C0 01C0 01C0" + $"0001 0008" +}; + +data 'CURS' (3058, "sb_v_double_arrow") { + $"0000 0100 0380 07C0 0FE0 0280 0280 0280" + $"0280 0280 0280 0FE0 07C0 0380 0100 0000" + $"0100 0380 07C0 0FE0 1FF0 0380 0380 0380" + $"0380 0380 0380 1FF0 0FE0 07C0 0380 0100" + $"0007 0007" +}; + +data 'CURS' (3059, "shuttle") { + $"0020 0070 00F8 01DE 05DE 09DE 11DE 11DE" + $"11DE 11DE 31DE 71DE FDDE 1888 0078 0030" + $"0020 0070 00F8 01FE 07FE 0FFE 1FFE 1FFE" + $"1FFE 1FFE 3FFE 7FFE FFFE 18F8 0078 0030" + $"0000 000A" +}; + +data 'CURS' (3060, "sizing") { + $"0000 7F80 4000 4000 4000 47E0 4420 4422" + $"4422 0422 07E2 0012 000A 0006 01FE 0000" + $"FFC0 FFC0 FFC0 E000 EFF0 EFF0 EC37 EC37" + $"EC37 EC37 0FF7 0FFF 001F 03FF 03FF 03FF" + $"000E 000E" +}; + +data 'CURS' (3061, "spider") { + $"2010 1020 1020 0840 0840 8787 6798 1FE0" + $"1FE0 6798 8787 0840 0840 1020 1020 2010" + $"7038 3870 3870 1CE0 9FE7 EFDF FFFF 7FF8" + $"7FF8 FFFF EFDF 9FE7 1CE0 3870 3870 7038" + $"0007 0007" +}; + +data 'CURS' (3062, "spraycan") { + $"0018 0040 0D18 1E40 1A18 3F00 2100 3900" + $"2900 3900 2900 3900 3900 2100 2100 3F00" + $"0000 0000 0C00 1E00 1E00 3F00 3F00 3F00" + $"3F00 3F00 3F00 3F00 3F00 3F00 3F00 3F00" + $"0002 0007" +}; + +data 'CURS' (3063, "star") { + $"0100 0280 0280 0280 0440 0440 0440 3938" + $"C006 3838 0920 1290 2448 2828 3018 2008" + $"0100 0380 0380 0380 07C0 07C0 07C0 3FF8" + $"FFFE 3FF8 0FE0 1EF0 3C78 3838 3018 2008" + $"0007 0007" +}; + +data 'CURS' (3064, "target") { + $"0000 0380 0FE0 1C70 3018 600C C106 C286" + $"C106 600C 3018 1C70 0FE0 0380 0000 0000" + $"0000 0380 0FE0 1FF0 3C78 701C E38E E38E" + $"E38E 701C 3C78 1FF0 0FE0 0380 0000 0000" + $"0007 0007" +}; + +data 'CURS' (3065, "tcross") { + $"0100 0100 0100 0100 0100 0100 0100 FFFE" + $"0100 0100 0100 0100 0100 0100 0100 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0007 0007" +}; + +data 'CURS' (3066, "top_left_arrow") { + $"0000 6000 7800 3E00 3F80 1FE0 1E00 0D00" + $"0C80 0440 0420 0010 0008 0004 0000 0000" + $"E000 F800 FE00 7F80 7FE0 3FF8 3FFE 1F80" + $"1FC0 0EE0 0E70 0638 061C 020E 0204 0000" + $"0001 0001" +}; + +data 'CURS' (3067, "top_left_corner") { + $"FFF0 FFF0 C000 C000 CFC0 CC00 CA00 C900" + $"C880 C840 C020 C000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0FC0 0C00 0A00 0900" + $"0880 0840 0020 0000 0000 0000 0000 0000" + $"0000 0000" +}; + +data 'CURS' (3068, "top_right_corner") { + $"0FFF 0FFF 0003 0003 03F3 0033 0053 0093" + $"0113 0213 0403 0003 0000 0000 0000 0000" + $"0000 0000 0000 0000 03F0 0030 0050 0090" + $"0110 0210 0400 0000 0000 0000 0000 0000" + $"0000 000F" +}; + +data 'CURS' (3069, "top_side") { + $"0000 7FFC 7FFC 0000 0100 0380 0540 0920" + $"1110 0100 0100 0100 0100 0100 0000 0000" + $"0000 0000 0000 0000 0100 0380 0540 0920" + $"1110 0100 0100 0100 0100 0100 0000 0000" + $"0004 0007" +}; + +data 'CURS' (3070, "top_tee") { + $"0000 0000 0000 0000 7FFE 7FFE 0180 0180" + $"0180 0180 0180 0180 0180 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0004 0007" +}; + +data 'CURS' (3071, "trek") { + $"0100 0000 0380 07C0 0FE0 0EE0 0FE0 07C0" + $"0380 0100 0BA0 0D60 0920 0820 0820 0000" + $"0000 0380 07C0 0FE0 1FF0 1FF0 1FF0 0FE0" + $"07C0 0BA0 1FF0 1FF0 1FF0 1D70 1C70 0820" + $"0000 0007" +}; + +data 'CURS' (3072, "ul_angle") { + $"0000 0000 0000 0FF8 0FF8 0C00 0C00 0C00" + $"0C00 0C00 0C00 0C00 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0003 0004" +}; + +data 'CURS' (3073, "umbrella") { + $"0000 0890 0228 49A6 27C8 1930 610C 0100" + $"0100 0100 0100 0100 0140 0140 0080 0000" + $"0000 0FF0 1FF8 7FFE 7FFC FFFE FBBE E38E" + $"0380 0380 0380 03C0 03E0 03E0 01C0 0080" + $"0004 0007" +}; + +data 'CURS' (3074, "ur_angle") { + $"0000 0000 0000 0000 1FF0 1FF0 0030 0030" + $"0030 0030 0030 0030 0030 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0004 000B" +}; + +data 'CURS' (3075, "watch") { + $"07E0 07E0 07E0 07E0 0810 1088 1088 108C" + $"138C 1008 1008 0810 07E0 07E0 07E0 07E0" + $"07E0 07E0 07E0 07E0 0FF0 1FF8 1FF8 1FFC" + $"1FFC 1FF8 1FF8 0FF0 07E0 07E0 07E0 07E0" + $"0008 000D" +}; + +data 'CURS' (3076, "xterm") { + $"0C60 0280 0100 0100 0100 0100 0100 0100" + $"0100 0100 0100 0100 0100 0100 0280 0C60" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"000B 0007" +}; + +/* + * The following are color versions of some of the + * cursors defined above. The color cursors will be + * used if the exist in preference to the black & white + * cursors. + */ + +data 'crsr' (3004, "boat", purgeable) { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0100 03C0" + $"8460 FFFF 0018 0020 0040 FFC0 0000 0000" + $"0000 0000 0000 0000 0000 0000 0100 03C0" + $"87E0 FFFF FFF8 FFE0 FFC0 FFC0 0000 0000" + $"0000 0000 0007 000F 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 000F 0000 0000 0000 00FF FF00" + $"0000 F000 0F32 25F0 0000 6FFF FFFF FFFF" + $"FFFF 2222 2222 221F F000 2222 2222 21F0" + $"0000 3333 3333 4F00 0000 FFFF FFFF FF00" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0007 0000 FFFF FFFF" + $"FFFF 0001 BBBB BBBB BBBB 0002 EEEE EEEE" + $"EEEE 0003 DDDD DDDD DDDD 0004 CCCC CCCC" + $"CCCC 0005 4444 4444 4444 0006 1111 1111" + $"1111 000F 0000 0000 0000" +}; + +data 'crsr' (3013, "clock") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 1FF8 33CC 6466 4992 4F12 4422" + $"63C6 3FFC 2994 2994 2994 2BD4 6996 781E" + $"7FFE 7FFE 1FF8 3FFC 7FFE 7FFE 7FFE 7FFE" + $"7FFE 3FFC 3FFC 3FFC 3FFC 3FFC 7FFE 7FFE" + $"7FFE 7FFE 0004 0008 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 000F FFFF FFFF F000 00F6 05FF FF50" + $"6F00 0F60 5F00 56F5 06F0 0F00 F021 F30F" + $"00F0 0F00 F6F1 000F 00F0 0F00 5F00 00F5" + $"00F0 0F60 05FF FF50 06F0 00FF FFFF FFFF" + $"FF00 00F0 F001 100F 0F00 00F0 F001 100F" + $"0F00 00F0 F021 120F 0F00 00F0 F01F F10F" + $"0F00 0FF0 F021 120F 0FF0 0FF4 F500 005F" + $"4FF0 0FFF FFFF FFFF FFF0 0FFF FFFF FFFF" + $"FFF0 0000 0000 0000 0007 0000 FFFF FFFF" + $"FFFF 0001 4444 4444 4444 0002 AAAA AAAA" + $"AAAA 0003 EEEE EEEE EEEE 0004 5555 5555" + $"5555 0005 DDDD DDDD DDDD 0006 7777 7777" + $"7777 000F 0000 0000 0000" +}; + +data 'crsr' (3014, "coffee_mug") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 03F8 0C06 1001 1C07 33F9 7001" + $"D001 9001 960D DA55 7A55 36ED 10A1 1001" + $"0802 07FC 03F8 0FFE 1FFF 1FFF 3FFF 7FFF" + $"FFFF FFFF FFFF FFFF 7FFF 3FFF 1FFF 1FFF" + $"0FFE 07FC 0004 0003 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 0000 00FF FFFF F000 0000 FF42 2222" + $"4FF0 000F 4221 1111 224F 000F FF11 1111" + $"1FFF 00FF 24FF FFFF F42F 0F5F 2222 2222" + $"222F F52F 2222 2222 222F F40F 2222 2222" + $"222F F40F 4FF2 2224 FF2F F52F F2F2 2F2F" + $"2F2F 0F5F F2F2 535F 2F2F 00FF 4FF2 F3F4" + $"FF2F 000F 2222 F2F2 222F 000F 4222 2222" + $"224F 0000 F422 2222 24F0 0000 0FFF FFFF" + $"FF00 0000 0000 0000 0006 0000 FFFF FFFF" + $"FFFF 0001 CCCC 9999 6666 0002 CCCC CCCC" + $"FFFF 0003 3333 3333 6666 0004 9999 9999" + $"FFFF 0005 6666 6666 CCCC 000F 0000 0000" + $"0000" +}; + +data 'crsr' (3027, "gobbler") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 0000 0078 0070 4036 4FB0 7FF0" + $"7E30 7C30 3038 00F0 0FE0 0400 0400 0400" + $"0F00 0000 00FC 00FC E0FF FFFF FFFF FFF8" + $"FFF8 FFF8 FFFC 7FFC 3FF8 1FF0 0E00 1F80" + $"1F80 1F80 0003 000E 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 0000 0000 0000 0000 0000 0000 0222" + $"2000 0000 0000 0111 0000 0300 0000 0011" + $"0220 0100 1616 1011 0000 0361 6111 1111" + $"0000 0111 1114 4415 0000 0311 1144 4451" + $"0000 0011 4444 4415 1000 0004 4444 5151" + $"0000 0000 1515 1510 0000 0000 0200 0000" + $"0000 0000 0300 0000 0000 0000 0200 0000" + $"0000 0000 2323 0000 0000 0000 0000 0000" + $"0000 0000 0000 0000 0006 0000 FFFF FFFF" + $"FFFF 0001 CCCC 9999 6666 0002 DDDD 0000" + $"0000 0003 FFFF 6666 3333 0004 CCCC CCCC" + $"CCCC 0005 8888 8888 8888 0006 FFFF CCCC" + $"9999" +}; + +data 'crsr' (3028, "gumby") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 3F00 10C0 C820 EAA0 C820 CBA0" + $"F838 383E 0826 0826 092E 0926 0920 1110" + $"2108 3EF8 3F00 1FC0 CFE0 EFE0 CFE0 CFE0" + $"FFF8 3FFE 0FE6 0FE6 0FEE 0FE6 0FE0 1FF0" + $"3FF8 3EF8 0000 0002 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 00FF FFFF 0000 0000 000F 1212 FF00" + $"0000 FF00 F131 31F0 0000 FFF0 F3F3 F3F0" + $"0000 FF00 F131 31F0 0000 FF00 F2FF F2F0" + $"0000 4FFF F121 21FF F000 00FF F212 12FF" + $"FF40 0000 F121 21F0 0FF0 0000 F212 12F0" + $"0FF0 0000 F12F 21F0 FFF0 0000 F21F 12F0" + $"0FF0 0000 F12F 21F0 0000 000F 121F 121F" + $"0000 00F1 212F 2121 F000 00FF FFF0 FFFF" + $"F000 0000 0000 0000 0005 0000 FFFF FFFF" + $"FFFF 0001 0000 BBBB 0000 0002 CCCC CCCC" + $"CCCC 0003 AAAA AAAA AAAA 0004 4444 4444" + $"4444 000F 0000 0000 0000" +}; + +data 'crsr' (3031, "heart") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 0000 3EF8 638C C106 8002 8002" + $"8002 8002 C006 600C 3018 1830 0C60 06C0" + $"0380 0000 0000 3EF8 7FFC FFFE FFFE FFFE" + $"FFFE FFFE FFFE 7FFC 3FF8 1FF0 0FE0 07C0" + $"0380 0000 0003 0007 0000 0000 0000 0000" + $"0000 0000 8004 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0002 0001 0002 0000 0000 0000 00D2 0000" + $"0000 0000 0000 0FFC FFC0 3AAB AA70 E99B" + $"999C E665 A65C E999 999C E666 665C E999" + $"999C D666 665C 3599 9970 0D66 65C0 0359" + $"9700 00D6 5C00 0035 7000 000F C000 0000" + $"0000 0000 0000 0000 0003 0000 FFFF FFFF" + $"FFFF 0001 DDDD 0000 0000 0002 FFFF 6666" + $"CCCC 0003 0000 0000 0000" +}; + +data 'crsr' (3042, "mouse", purgeable) { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 BE00 0100 0180 0FF0 1008 17E8" + $"1428 1428 17E8 1008 1008 1008 1008 1008" + $"1008 0FF0 FE00 0100 0180 0FF0 1FF8 1FF8" + $"1FF8 1FF8 1FF8 1FF8 1FF8 1FF8 1FF8 1FF8" + $"1FF8 0FF0 0001 0007 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 1379 4AF0 0000 0000 0000 000F 0000" + $"0000 0000 000F F000 0000 0000 FFFF FFFF" + $"0000 000F 2111 1112 F000 000F 3655 5563" + $"F000 000F 3513 1351 F000 000F 3533 3351" + $"F000 000F 3655 5561 F000 000F 3311 1111" + $"F000 000F 3333 3333 F000 000F 3333 3333" + $"F000 000F 2222 2222 F000 000F 8888 8888" + $"F000 000F 7888 8887 F000 0000 FFFF FFFF" + $"0000 0000 0000 0000 000B 0000 FFFF FFFF" + $"FFFF 0001 EEEE EEEE EEEE 0002 CCCC CCCC" + $"CCCC 0003 DDDD DDDD DDDD 0004 4444 4444" + $"4444 0005 2222 2222 2222 0006 5555 5555" + $"5555 0007 AAAA AAAA AAAA 0008 BBBB BBBB" + $"BBBB 0009 7777 7777 7777 000A 1111 1111" + $"1111 000F 0000 0000 0000" +}; + +data 'crsr' (3043, "pencil", purgeable) { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 0000 00F0 0088 0108 0190 0270" + $"0220 0440 0440 0880 0880 1100 1E00 1C00" + $"1800 1000 0000 00F0 00F8 01F8 01F0 03F0" + $"03E0 07C0 07C0 0F80 0F80 1F00 1E00 1C00" + $"1800 1000 000F 0003 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 0000 0000 0000 0000 0000 0000 FFFF" + $"0000 0000 0000 F404 F000 0000 000F 4042" + $"F000 0000 000F F42F 0000 0000 00F5 3FFF" + $"0000 0000 00F3 52F0 0000 0000 0F35 1F00" + $"0000 0000 0F53 2F00 0000 0000 F532 F000" + $"0000 0000 F312 F000 0000 000F 352F 0000" + $"0000 000F FFF0 0000 0000 000F FF00 0000" + $"0000 000F F000 0000 0000 000F 0000 0000" + $"0000 0000 0000 0000 0006 0000 FFFF FFFF" + $"FFFF 0001 CCCC CCCC CCCC 0002 8888 8888" + $"8888 0003 FFFF FFFF 0000 0004 DDDD 0000" + $"0000 0005 FFFF 6666 3333 000F 0000 0000" + $"0000" +}; + +data 'crsr' (3059, "shuttle") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 0020 0070 00F8 01DE 05DE 09DE" + $"11DE 11DE 11DE 11DE 31DE 71DE FDDE 1888" + $"0078 0030 0020 0070 00F8 01FE 07FE 0FFE" + $"1FFE 1FFE 1FFE 1FFE 3FFE 7FFE FFFE 18F8" + $"0078 0030 0000 000A 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 0000 0000 00F0 0000 0000 0000 0F3F" + $"0000 0000 0000 F343 F000 0000 000F 3404" + $"3FF0 0000 0F4F 3404 3FF0 0000 F55F 3404" + $"3FF0 000F 505F 3404 3FF0 000F 005F 3404" + $"3FF0 000F 005F 3404 3FF0 000F 005F 3404" + $"3FF0 00F3 005F 3404 3FF0 0F33 505F 3404" + $"3FF0 FFF3 3F4F 3404 3FF0 000F F000 1222" + $"1000 0000 0000 0111 1000 0000 0000 0011" + $"0000 0000 0000 0000 0006 0000 FFFF FFFF" + $"FFFF 0001 FFFF 6666 3333 0002 DDDD 0000" + $"0000 0003 4444 4444 4444 0004 8888 8888" + $"8888 0005 DDDD DDDD DDDD 000F 0000 0000" + $"0000" +}; + +data 'crsr' (3062, "spraycan") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 0018 0040 0D18 1E40 1A18 3F00" + $"2100 3900 2900 3900 2900 3900 3900 2100" + $"2100 3F00 0000 0000 0C00 1E00 1E00 3F00" + $"3F00 3F00 3F00 3F00 3F00 3F00 3F00 3F00" + $"3F00 3F00 0002 0007 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 0000 0000 0005 2000 0000 0000 0460" + $"0000 0000 FF1F 6005 2000 000F 33F0 0460" + $"0000 000F 10F0 0005 2000 00FF FFFF 0000" + $"0000 00F8 170F 0000 0000 00F5 F70F 0000" + $"0000 00FA F70F 0000 0000 00F9 F70F 0000" + $"0000 00FA F70F 0000 0000 00F9 F70F 0000" + $"0000 00F5 F70F 0000 0000 00F8 170F 0000" + $"0000 00F8 170F 0000 0000 00FF FFFF 0000" + $"0000 0000 0000 0000 000B 0000 FFFF FFFF" + $"FFFF 0001 AAAA AAAA AAAA 0002 7777 7777" + $"7777 0003 5555 5555 5555 0004 2222 2222" + $"2222 0005 4444 4444 4444 0006 BBBB BBBB" + $"BBBB 0007 DDDD DDDD DDDD 0008 EEEE EEEE" + $"EEEE 0009 6666 6666 CCCC 000A CCCC CCCC" + $"FFFF 000F 0000 0000 0000" +}; + +data 'crsr' (3063, "star") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 0100 0280 0280 0280 0440 0440" + $"0440 3938 C006 3838 0920 1290 2448 2828" + $"3018 2008 0100 0380 0380 0380 07C0 07C0" + $"07C0 3FF8 FFFE 3FF8 0FE0 1EF0 3C78 3838" + $"3018 2008 0007 0007 0000 0000 0000 0000" + $"0000 0000 8004 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0002 0001 0002 0000 0000 0000 00D2 0000" + $"0000 0003 0000 000D C000 000D C000 000D" + $"C000 0035 7000 0035 7000 0035 7000 0FD7" + $"5FC0 F555 557C 0FD5 5FC0 00D7 5C00 035C" + $"D700 0D70 35C0 0DC0 0DC0 0F00 03C0 0C00" + $"00C0 0000 0000 0000 0002 0000 FFFF FFFF" + $"FFFF 0001 FFFF FFFF 0000 0003 0000 0000" + $"0000" +}; + +data 'crsr' (3071, "trek") { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 0100 0000 0380 07C0 0FE0 0EE0" + $"0FE0 07C0 0380 0100 0BA0 0D60 0920 0820" + $"0820 0000 0000 0380 07C0 0FE0 1FF0 1FF0" + $"1FF0 0FE0 07C0 0BA0 1FF0 1FF0 1FF0 1D70" + $"1C70 0820 0000 0007 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 0000 0005 0000 0000 0000 0005 0000" + $"0000 0000 00FF F000 0000 0000 0F31 3F00" + $"0000 0000 F322 23F0 0000 0000 F110 11F0" + $"0000 0000 F311 13F0 0000 0000 0F31 3F00" + $"0000 0000 00FF F000 0000 0000 000F 0000" + $"0000 0000 F0FF F0F0 0000 0000 FF0F 0FF0" + $"0000 0000 400F 0040 0000 0000 4000 0040" + $"0000 0000 4000 0040 0000 0000 0000 0000" + $"0000 0000 0000 0000 0006 0000 FFFF FFFF" + $"FFFF 0001 EEEE EEEE EEEE 0002 9999 9999" + $"FFFF 0003 DDDD DDDD DDDD 0004 3333 3333" + $"6666 0005 DDDD 0000 0000 000F 0000 0000" + $"0000" +}; + +data 'crsr' (3075, "watch", purgeable) { + $"8001 0000 0060 0000 0092 0000 0000 0000" + $"0000 0000 07E0 07E0 07E0 07E0 0810 1088" + $"1088 108C 138C 1008 1008 0810 07E0 07E0" + $"07E0 07E0 07E0 07E0 07E0 07E0 0FF0 1FF8" + $"1FF8 1FF8 1FF8 1FF8 1FF8 0FF0 07E0 07E0" + $"07E0 07E0 0008 000D 0000 0000 0000 0000" + $"0000 0000 8008 0000 0000 0010 0010 0000" + $"0000 0000 0000 0048 0000 0048 0000 0000" + $"0004 0001 0004 0000 0000 0000 0112 0000" + $"0000 0000 0FFF FFF0 0000 0000 0FFF FFF0" + $"0000 0000 0FFF FFF0 0000 0000 0FFF FFF0" + $"0000 0000 F020 202F 0000 000F 0222 F221" + $"F000 000F 2222 F123 F000 000F 0222 F121" + $"FF00 000F 22FF F123 FF00 000F 0222 2221" + $"F000 000F 2222 2213 F000 0000 F131 313F" + $"0000 0000 0FFF FFF0 0000 0000 0FFF FFF0" + $"0000 0000 0FFF FFF0 0000 0000 0FFF FFF0" + $"0000 0000 0000 0000 0004 0000 FFFF FFFF" + $"FFFF 0001 CCCC CCCC CCCC 0002 EEEE EEEE" + $"EEEE 0003 BBBB BBBB BBBB 000F 0000 0000" + $"0000" +}; + diff --git a/mac/tkMacXStubs.c b/mac/tkMacXStubs.c new file mode 100644 index 0000000..f1042c2 --- /dev/null +++ b/mac/tkMacXStubs.c @@ -0,0 +1,709 @@ +/* + * tkMacXStubs.c -- + * + * This file contains most of the X calls called by Tk. Many of + * these calls are just stubs and either don't make sense on the + * Macintosh or thier implamentation just doesn't do anything. Other + * calls will eventually be moved into other files. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkMacXStubs.c 1.87 97/11/20 18:35:29 + */ + +#include "tkInt.h" +#include <X.h> +#include <Xlib.h> +#include <stdio.h> +#include <tcl.h> + +#include <Xatom.h> + +#include <Windows.h> +#include <Fonts.h> +#include <QDOffscreen.h> +#include <ToolUtils.h> +#include <Sound.h> +#include "tkMacInt.h" + +/* + * Because this file is still under major development Debugger statements are + * used through out this file. The define TCL_DEBUG will decide whether + * the debugger statements actually call the debugger or not. + */ + +#ifndef TCL_DEBUG +# define Debugger() +#endif + +#define ROOT_ID 10 + +/* + * Declarations of static variables used in this file. + */ + +static TkDisplay *gMacDisplay = NULL; /* Macintosh display. */ +static char *macScreenName = "Macintosh:0"; + /* Default name of macintosh display. */ + +/* + * Forward declarations of procedures used in this file. + */ + +static XID MacXIdAlloc _ANSI_ARGS_((Display *display)); +static int DefaultErrorHandler _ANSI_ARGS_((Display* display, + XErrorEvent* err_evt)); + +/* + * Other declrations + */ + +int TkMacXDestroyImage _ANSI_ARGS_((XImage *image)); +unsigned long TkMacXGetPixel _ANSI_ARGS_((XImage *image, int x, int y)); +int TkMacXPutPixel _ANSI_ARGS_((XImage *image, int x, int y, + unsigned long pixel)); +XImage *TkMacXSubImage _ANSI_ARGS_((XImage *image, int x, int y, + unsigned int width, unsigned int height)); +int TkMacXAddPixel _ANSI_ARGS_((XImage *image, long value)); +int _XInitImageFuncPtrs _ANSI_ARGS_((XImage *image)); + +/* + *---------------------------------------------------------------------- + * + * TkpOpenDisplay -- + * + * Create the Display structure and fill it with device + * specific information. + * + * Results: + * Returns a Display structure on success or NULL on failure. + * + * Side effects: + * Allocates a new Display structure. + * + *---------------------------------------------------------------------- + */ + +TkDisplay * +TkpOpenDisplay( + char *display_name) +{ + Display *display; + Screen *screen; + GDHandle graphicsDevice; + + if (gMacDisplay != NULL) { + if (strcmp(gMacDisplay->display->display_name, display_name) == 0) { + return gMacDisplay; + } else { + return NULL; + } + } + + graphicsDevice = GetMainDevice(); + display = (Display *) ckalloc(sizeof(Display)); + display->resource_alloc = MacXIdAlloc; + screen = (Screen *) ckalloc(sizeof(Screen) * 2); + display->default_screen = 0; + display->request = 0; + display->nscreens = 1; + display->screens = screen; + display->display_name = macScreenName; + display->qlen = 0; + + screen->root = ROOT_ID; + screen->display = display; + screen->root_depth = (*(*graphicsDevice)->gdPMap)->cmpSize * + (*(*graphicsDevice)->gdPMap)->cmpCount; + screen->height = (*graphicsDevice)->gdRect.bottom - + (*graphicsDevice)->gdRect.top; + screen->width = (*graphicsDevice)->gdRect.right - + (*graphicsDevice)->gdRect.left; + + screen->mwidth = (screen->width * 254 + 360) / 720; + screen->mheight = (screen->height * 254 + 360) / 720; + screen->black_pixel = 0x00000000; + screen->white_pixel = 0x00FFFFFF; + screen->root_visual = (Visual *) ckalloc(sizeof(Visual)); + screen->root_visual->visualid = 0; + screen->root_visual->class = TrueColor; + screen->root_visual->red_mask = 0x00FF0000; + screen->root_visual->green_mask = 0x0000FF00; + screen->root_visual->blue_mask = 0x000000FF; + screen->root_visual->bits_per_rgb = 24; + screen->root_visual->map_entries = 2 ^ 8; + + gMacDisplay = (TkDisplay *) ckalloc(sizeof(TkDisplay)); + gMacDisplay->display = display; + return gMacDisplay; +} + +/* + *---------------------------------------------------------------------- + * + * TkpCloseDisplay -- + * + * Deallocates a display structure created by TkpOpenDisplay. + * + * Results: + * None. + * + * Side effects: + * Frees memory. + * + *---------------------------------------------------------------------- + */ + +void +TkpCloseDisplay( + TkDisplay *displayPtr) +{ + Display *display = displayPtr->display; + if (gMacDisplay != displayPtr) { + panic("TkpCloseDisplay: tried to call TkpCloseDisplay on bad display"); + } + + /* + * Make sure that the local scrap is transfered to the global + * scrap if needed. + */ + + TkSuspendClipboard(); + + gMacDisplay = NULL; + if (display->screens != (Screen *) NULL) { + if (display->screens->root_visual != (Visual *) NULL) { + ckfree((char *) display->screens->root_visual); + } + ckfree((char *) display->screens); + } + ckfree((char *) display); + ckfree((char *) displayPtr); +} + +/* + *---------------------------------------------------------------------- + * + * MacXIdAlloc -- + * + * This procedure is invoked by Xlib as the resource allocator + * for a display. + * + * Results: + * The return value is an X resource identifier that isn't currently + * in use. + * + * Side effects: + * The identifier is removed from the stack of free identifiers, + * if it was previously on the stack. + * + *---------------------------------------------------------------------- + */ + +static XID +MacXIdAlloc( + Display *display) /* Display for which to allocate. */ +{ + static long int cur_id = 100; + /* + * Some special XIds are reserved + * - this is why we start at 100 + */ + + return ++cur_id; +} + +/* + *---------------------------------------------------------------------- + * + * TkpWindowWasRecentlyDeleted -- + * + * Tries to determine whether the given window was recently deleted. + * Called from the generic code error handler to attempt to deal with + * async BadWindow errors under some circumstances. + * + * Results: + * Always 0, we do not keep this information on the Mac, so we do not + * know whether the window was destroyed. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpWindowWasRecentlyDeleted( + Window win, + TkDisplay *dispPtr) +{ + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * DefaultErrorHandler -- + * + * This procedure is the default X error handler. Tk uses it's + * own error handler so this call should never be called. + * + * Results: + * None. + * + * Side effects: + * This function will call panic and exit. + * + *---------------------------------------------------------------------- + */ + +static int +DefaultErrorHandler( + Display* display, + XErrorEvent* err_evt) +{ + /* + * This call should never be called. Tk replaces + * it with its own error handler. + */ + panic("Warning hit bogus error handler!"); + return 0; +} + + +char * +XGetAtomName( + Display * display, + Atom atom) +{ + display->request++; + return NULL; +} + +int +_XInitImageFuncPtrs(XImage *image) +{ + return 0; +} + +XErrorHandler +XSetErrorHandler( + XErrorHandler handler) +{ + return DefaultErrorHandler; +} + +Window +XRootWindow(Display *display, int screen_number) +{ + display->request++; + return ROOT_ID; +} + +XImage * +XGetImage(display, d, x, y, width, height, plane_mask, format) + Display *display; + Drawable d; + int x; + int y; + unsigned int width; + unsigned int height; + unsigned long plane_mask; + int format; +{ + Debugger(); + return NULL; +} + +int +XGetGeometry(display, d, root_return, x_return, y_return, width_return, + height_return, border_width_return, depth_return) + Display* display; + Drawable d; + Window* root_return; + int* x_return; + int* y_return; + unsigned int* width_return; + unsigned int* height_return; + unsigned int* border_width_return; + unsigned int* depth_return; +{ + /* Used in tkCanvPs.c & wm code */ + Debugger(); + return 0; +} + +void +XChangeProperty( + Display* display, + Window w, + Atom property, + Atom type, + int format, + int mode, + _Xconst unsigned char* data, + int nelements) +{ + Debugger(); +} + +void +XSelectInput( + Display* display, + Window w, + long event_mask) +{ + Debugger(); +} + +void +XBell( + Display* display, + int percent) +{ + SysBeep(percent); +} + +void +XSetWMNormalHints( + Display* display, + Window w, + XSizeHints* hints) +{ + /* + * Do nothing. Shouldn't even be called. + */ +} + +XSizeHints * +XAllocSizeHints() +{ + /* + * Always return NULL. Tk code checks to see if NULL + * is returned & does nothing if it is. + */ + + return NULL; +} + +XImage * +XCreateImage( + Display* display, + Visual* visual, + unsigned int depth, + int format, + int offset, + char* data, + unsigned int width, + unsigned int height, + int bitmap_pad, + int bytes_per_line) +{ + XImage *ximage; + + display->request++; + ximage = (XImage *) ckalloc(sizeof(XImage)); + + ximage->height = height; + ximage->width = width; + ximage->depth = depth; + ximage->xoffset = offset; + ximage->format = format; + ximage->data = data; + ximage->bitmap_pad = bitmap_pad; + if (bytes_per_line == 0) { + ximage->bytes_per_line = width * 4; /* assuming 32 bits per pixel */ + } else { + ximage->bytes_per_line = bytes_per_line; + } + + if (format == ZPixmap) { + ximage->bits_per_pixel = 32; + ximage->bitmap_unit = 32; + } else { + ximage->bits_per_pixel = 1; + ximage->bitmap_unit = 8; + } + ximage->byte_order = LSBFirst; + ximage->bitmap_bit_order = LSBFirst; + ximage->red_mask = 0x00FF0000; + ximage->green_mask = 0x0000FF00; + ximage->blue_mask = 0x000000FF; + + ximage->f.destroy_image = TkMacXDestroyImage; + ximage->f.get_pixel = TkMacXGetPixel; + ximage->f.put_pixel = TkMacXPutPixel; + ximage->f.sub_image = TkMacXSubImage; + ximage->f.add_pixel = TkMacXAddPixel; + + return ximage; +} + +GContext +XGContextFromGC( + GC gc) +{ + /* TODO - currently a no-op */ + return 0; +} + +Status +XSendEvent( + Display* display, + Window w, + Bool propagate, + long event_mask, + XEvent* event_send) +{ + Debugger(); + return 0; +} + +int +XGetWindowProperty( + Display *display, + Window w, + Atom property, + long long_offset, + long long_length, + Bool delete, + Atom req_type, + Atom *actual_type_return, + int *actual_format_return, + unsigned long *nitems_return, + unsigned long *bytes_after_return, + unsigned char ** prop_return) +{ + display->request++; + *actual_type_return = None; + *actual_format_return = *bytes_after_return = 0; + *nitems_return = 0; + return 0; +} + +void +XRefreshKeyboardMapping() +{ + /* used by tkXEvent.c */ + Debugger(); +} + +void +XSetIconName( + Display* display, + Window w, + const char *icon_name) +{ + /* + * This is a no-op, no icon name for Macs. + */ + display->request++; +} + +void +XForceScreenSaver( + Display* display, + int mode) +{ + /* + * This function is just a no-op. It is defined to + * reset the screen saver. However, there is no real + * way to do this on a Mac. Let me know if there is! + */ + display->request++; +} + +/* + *---------------------------------------------------------------------- + * + * TkGetServerInfo -- + * + * Given a window, this procedure returns information about + * the window server for that window. This procedure provides + * the guts of the "winfo server" command. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkGetServerInfo( + Tcl_Interp *interp, /* The server information is returned in + * this interpreter's result. */ + Tk_Window tkwin) /* Token for window; this selects a + * particular display and server. */ +{ + char buffer[50], buffer2[50]; + + sprintf(buffer, "X%dR%d ", ProtocolVersion(Tk_Display(tkwin)), + ProtocolRevision(Tk_Display(tkwin))); + sprintf(buffer2, " %d", VendorRelease(Tk_Display(tkwin))); + Tcl_AppendResult(interp, buffer, ServerVendor(Tk_Display(tkwin)), + buffer2, (char *) NULL); +} +/* + * Image stuff + */ + +int +TkMacXDestroyImage( + XImage *image) +{ + Debugger(); + return 0; +} + +unsigned long +TkMacXGetPixel( + XImage *image, + int x, + int y) +{ + Debugger(); + return 0; +} + +int +TkMacXPutPixel( + XImage *image, + int x, + int y, + unsigned long pixel) +{ + /* Debugger(); */ + return 0; +} + +XImage * +TkMacXSubImage( + XImage *image, + int x, + int y, + unsigned int width, + unsigned int height) +{ + Debugger(); + return NULL; +} + +int +TkMacXAddPixel( + XImage *image, + long value) +{ + Debugger(); + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * XChangeWindowAttributes, XSetWindowBackground, + * XSetWindowBackgroundPixmap, XSetWindowBorder, XSetWindowBorderPixmap, + * XSetWindowBorderWidth, XSetWindowColormap + * + * These functions are all no-ops. They all have equivilent + * Tk calls that should always be used instead. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +XChangeWindowAttributes( + Display* display, + Window w, + unsigned long value_mask, + XSetWindowAttributes* attributes) +{ +} + +void +XSetWindowBackground( + Display *display, + Window window, + unsigned long value) +{ +} + +void +XSetWindowBackgroundPixmap( + Display* display, + Window w, + Pixmap background_pixmap) +{ +} + +void +XSetWindowBorder( + Display* display, + Window w, + unsigned long border_pixel) +{ +} + +void +XSetWindowBorderPixmap( + Display* display, + Window w, + Pixmap border_pixmap) +{ +} + +void +XSetWindowBorderWidth( + Display* display, + Window w, + unsigned int width) +{ +} + +void +XSetWindowColormap( + Display* display, + Window w, + Colormap colormap) +{ + Debugger(); +} + +/* + *---------------------------------------------------------------------- + * + * TkGetDefaultScreenName -- + * + * Returns the name of the screen that Tk should use during + * initialization. + * + * Results: + * Returns a statically allocated string. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +char * +TkGetDefaultScreenName( + Tcl_Interp *interp, /* Not used. */ + char *screenName) /* If NULL, use default string. */ +{ + if ((screenName == NULL) || (screenName[0] == '\0')) { + screenName = macScreenName; + } + return screenName; +} diff --git a/tests/README b/tests/README new file mode 100644 index 0000000..2ae2a44 --- /dev/null +++ b/tests/README @@ -0,0 +1,30 @@ +Tk Test Suite +-------------- + +SCCS: @(#) README 1.2 96/03/27 08:52:21 + +This directory contains a set of validation tests for Tk. +Each of the files whose name ends in ".test" is intended to +fully exercise one or a few Tk features. The features +tested by a given file are listed in the first line of the +file. The test suite is nowhere near complete yet. Contributions +of additional tests would be most welcome. + +You can run the tests in two ways: + (a) type "make test" in the directory ../unix; this will run all of + the tests. + (b) start up tktest in this directory, then "source" the test + file (for example, type "source pack.test"). To run all + of the tests, type "source all". +In either case no output will be generated if all goes well, except +for a listing of the tests. If there are errors then additional +messages will appear. + +For more details on the testing environment, see the README +file in the Tcl test directory. + +You can also run a set of visual tests, which create various screens +that you can verify visually for appropriate behavior. The visual +tests are available through the "visual" script: if you invoke this +script, it creates a main window with a bunch of menus. Each menu +runs a particular test. diff --git a/tests/all b/tests/all new file mode 100644 index 0000000..38d2ca0 --- /dev/null +++ b/tests/all @@ -0,0 +1,57 @@ +# This file contains a top-level script to run all of the Tcl +# tests. Execute it by invoking "source all" when running tclTest +# in this directory. +# +# SCCS: @(#) all 1.23 97/08/06 18:50:18 + +switch $tcl_platform(platform) { + "windows" { + # Tests that cause tk to crash under windows. + set crash {} + + # Tests that fail under windows. + + set fail { grid.test } + + if {! [info exist exclude] } { + set exclude [string tolower "$crash $fail"] + } + } + "macintosh" { + set x [pwd] + cd $tk_library + set tk_library [pwd] + cd $x + + # Tests that cause tk to crash under mac. + set crash {} + + # Tests that fail under mac. + set fail {bind.test entry.test send.test textDisp.test} + + set exclude [string tolower "$crash $fail"] + } + "unix" { + set exclude "" + } +} + +if {$tcl_platform(os) == "Win32s"} { + set tests [lsort [glob *.tes]] +} else { + set tests [lsort [glob *.test]] +} + +foreach i $tests { + if [string match l.*.test $i] { + # This is an SCCS lock file; ignore it. + continue + } + if [lsearch $exclude [string tolower $i]]>=0 { + # Do not source this file; it exercises a known bug at this time. + puts stdout "Skipping $i" + continue + } + puts stdout $i + source $i +} diff --git a/tests/arc.tcl b/tests/arc.tcl new file mode 100644 index 0000000..62ea96d --- /dev/null +++ b/tests/arc.tcl @@ -0,0 +1,140 @@ +# This file creates a visual test for arcs. It is part of the Tk +# visual test suite, which is invoked via the "visual" script. +# +# SCCS: @(#) arc.tcl 1.5 96/02/16 10:55:40 + +catch {destroy .t} +toplevel .t +wm title .t "Visual Tests for Canvas Arcs" +wm iconname .t "Arcs" +wm geom .t +0+0 +wm minsize .t 1 1 + +canvas .t.c -width 650 -height 600 -relief raised +pack .t.c -expand yes -fill both +button .t.quit -text Quit -command {destroy .t} +pack .t.quit -side bottom -pady 3 -ipadx 4 -ipady 2 + +puts "depth is [winfo depth .t]" +if {[winfo depth .t] > 1} { + set fill1 aquamarine3 + set fill2 aquamarine3 + set fill3 IndianRed1 + set outline2 IndianRed3 +} else { + set fill1 black + set fill2 white + set fill3 Black + set outline2 white +} +set outline black + +.t.c create arc 20 20 220 120 -start 30 -extent 270 -outline $fill1 -width 14 \ + -style arc +.t.c create arc 260 20 460 120 -start 30 -extent 270 -fill $fill2 -width 14 \ + -style chord -outline $outline +.t.c create arc 500 20 620 160 -start 30 -extent 270 -fill {} -width 14 \ + -style chord -outline $outline -outlinestipple gray50 +.t.c create arc 20 260 140 460 -start 45 -extent 90 -fill $fill2 -width 14 \ + -style pieslice -outline $outline +.t.c create arc 180 260 300 460 -start 45 -extent 90 -fill {} -width 14 \ + -style pieslice -outline $outline +.t.c create arc 340 260 460 460 -start 30 -extent 150 -fill $fill2 -width 14 \ + -style chord -outline $outline -stipple gray50 -outlinestipple gray25 +.t.c create arc 500 260 620 460 -start 30 -extent 150 -fill {} -width 14 \ + -style chord -outline $outline +.t.c create arc 20 450 140 570 -start 135 -extent 270 -fill $fill1 -width 14 \ + -style pieslice -outline {} +.t.c create arc 180 450 300 570 -start 30 -extent -90 -fill $fill1 -width 14 \ + -style pieslice -outline {} +.t.c create arc 340 450 460 570 -start 320 -extent 270 -fill $fill1 -width 14 \ + -style chord -outline {} +.t.c create arc 500 450 620 570 -start 350 -extent -110 -fill $fill1 -width 14 \ + -style chord -outline {} +.t.c addtag arc withtag all +.t.c addtag circle withtag [.t.c create oval 320 200 340 220 -fill MistyRose3] + +.t.c bind arc <Any-Enter> { + set prevFill [lindex [.t.c itemconf current -fill] 4] + set prevOutline [lindex [.t.c itemconf current -outline] 4] + if {($prevFill != "") || ($prevOutline == "")} { + .t.c itemconf current -fill $fill3 + } + if {$prevOutline != ""} { + .t.c itemconf current -outline $outline2 + } +} +.t.c bind arc <Any-Leave> {.t.c itemconf current -fill $prevFill -outline $prevOutline} + +bind .t.c <1> {markarea %x %y} +bind .t.c <B1-Motion> {strokearea %x %y} + +proc markarea {x y} { + global areaX1 areaY1 + set areaX1 $x + set areaY1 $y +} + +proc strokearea {x y} { + global areaX1 areaY1 areaX2 areaY2 + if {($areaX1 != $x) && ($areaY1 != $y)} { + .t.c delete area + .t.c addtag area withtag [.t.c create rect $areaX1 $areaY1 $x $y \ + -outline black] + set areaX2 $x + set areaY2 $y + } +} + +bind .t.c <Control-f> { + puts stdout "Enclosed: [.t.c find enclosed $areaX1 $areaY1 $areaX2 $areaY2]" + puts stdout "Overlapping: [.t.c find overl $areaX1 $areaY1 $areaX2 $areaY2]" +} + +bind .t.c <3> {puts stdout "%x %y"} + +# The code below allows the circle to be move by shift-dragging. + +bind .t.c <Shift-1> { + set curx %x + set cury %y +} + +bind .t.c <Shift-B1-Motion> { + .t.c move circle [expr %x-$curx] [expr %y-$cury] + set curx %x + set cury %y +} + +# The binding below flashes the closest item to the mouse. + +bind .t.c <Control-c> { + set closest [.t.c find closest %x %y] + set oldfill [lindex [.t.c itemconf $closest -fill] 4] + .t.c itemconf $closest -fill IndianRed1 + after 200 [list .t.c itemconfig $closest -fill $oldfill] +} + +proc c {option value} {.t.c itemconf 2 $option $value} + +bind .t.c a { + set go 1 + set i 1 + while {$go} { + if {$i >= 50} { + set delta -5 + } + if {$i <= 5} { + set delta 5 + } + incr i $delta + c -start $i + c -extent [expr 360-2*$i] + after 20 + update + } +} + +bind .t.c b {set go 0} + +bind .t.c <Control-x> {.t.c delete current} diff --git a/tests/bell.test b/tests/bell.test new file mode 100644 index 0000000..97d015e --- /dev/null +++ b/tests/bell.test @@ -0,0 +1,34 @@ +# This file is a Tcl script to test out Tk's "bell" command. +# It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) bell.test 1.5 96/04/09 23:47:12 + +if {[string compare test [info procs test]] == 1} { + source defs +} + +test bell-1.1 {bell command} { + list [catch {bell a} msg] $msg +} {1 {wrong # args: should be "bell ?-displayof window?"}} +test bell-1.2 {bell command} { + list [catch {bell a b} msg] $msg +} {1 {bad option "a": must be -displayof}} +test bell-1.3 {bell command} { + list [catch {bell -displayof gorp} msg] $msg +} {1 {bad window path name "gorp"}} +test bell-1.4 {bell command} { + puts "Bell should ring now ..." + flush stdout + after 500 + bell -displayof . + after 200 + bell + after 200 + bell +} {} diff --git a/tests/bevel.tcl b/tests/bevel.tcl new file mode 100644 index 0000000..60c913a --- /dev/null +++ b/tests/bevel.tcl @@ -0,0 +1,128 @@ +# This file creates a visual test for bevels drawn around text in text +# widgets. It is part of the Tk visual test suite, which is invoked +# via the "visual" script. +# +# SCCS: @(#) bevel.tcl 1.4 96/06/24 16:48:14 + +catch {destroy .t} +toplevel .t +wm title .t "Visual Tests for Borders in Text Widgets" +wm iconname .t "Text Borders" +wm geom .t +0+0 + +text .t.t -width 60 -height 30 -setgrid true -xscrollcommand {.t.h set} \ + -font {Courier 12} \ + -yscrollcommand {.t.v set} -wrap none -relief raised -bd 2 +scrollbar .t.v -orient vertical -command ".t.t yview" +scrollbar .t.h -orient horizontal -command ".t.t xview" +button .t.quit -text Quit -command {destroy .t} +pack .t.quit -side bottom -pady 3 -ipadx 4 -ipady 2 +pack .t.h -side bottom -fill x +pack .t.v -side right -fill y +pack .t.t -expand yes -fill both +wm minsize .t 1 1 + +if {[winfo depth .t] > 1} { + .t.t tag configure r1 -relief raised -borderwidth 2 -background #b2dfee + .t.t tag configure r2 -relief raised -borderwidth 2 -background #b2dfee \ + -offset 2 + .t.t tag configure s1 -relief sunken -borderwidth 2 -background #b2dfee +} else { + .t.t tag configure r1 -relief raised -borderwidth 2 -background white + .t.t tag configure r2 -relief raised -borderwidth 2 -background white \ + -offset 2 + .t.t tag configure s1 -relief sunken -borderwidth 2 -background white +} +.t.t tag configure indent1 -lmargin1 100 +.t.t tag configure indent2 -lmargin1 200 + +.t.t insert end {This display contains a bunch of raised and sunken +regions to exercise the bevel-drawing facilities of +DisplayLineBackground. The letters have the following +significance: + +r - should appear raised +u - should appear raised and also slightly offset vertically +s - should appear sunken +n - preceding relief should extend right to end of line. +* - should appear "normal" +x - extra long lines to allow horizontal scrolling. + +Try scrolling the text both vertically and horizontally to +be sure that the bevels are still drawn correctly. + +xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + +Pass 1 (side bevels): + +} +.t.t insert end **** +.t.t insert end rrrrrrr r1 +.t.t insert end uuuu r2 +.t.t insert end ************ +.t.t insert end ssssssssssssssssss s1 +.t.t insert end \n\n**************** +.t.t insert end rrrrrrrrrrrrrrn\n r1 + +.t.t insert end "\nPass 2 (top bevels):\n\n" +.t.t insert end rrrrrrrrrrrrrr r1 +.t.t insert end rrrrr {r1 dummy} +.t.t insert end rrrrrrrrrrrrrrrrrrr r1 +.t.t insert end \n************ +.t.t insert end rrrrrrrrrrrrrrrrr r1 +.t.t insert end ***********\n +.t.t insert end rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr r1 +.t.t insert end \n\n*** +.t.t insert end rrrrrrrrrrrrrrrrrrr r1 +.t.t insert end ***********\n* +.t.t insert end rrrrrrrrr r1 +.t.t insert end ******** +.t.t insert end rrrrrrrrrrrrrrrrrrrrrrrrr r1 +.t.t insert end \n\n* +.t.t insert end *** dummy +.t.t insert end rrrrrrrrrrrrrrrrrrrrrrrrr r1 +.t.t insert end n\nrrrrrrrrrrrrrrr {r1 indent1} +.t.t insert end \n\n*** +.t.t insert end rrr r1 +.t.t insert end \n +.t.t insert end rrrr {r1 indent1} + +.t.t insert end \n\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n +.t.t insert end "Pass 3 (bottom bevels):\n\n" +.t.t insert end ******* +.t.t insert end ********** dummy +.t.t insert end rrrrrrrrrrrrrrrr r1 +.t.t insert end **********\n +.t.t insert end rrrrrrrrr r1 +.t.t insert end uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu r2 +.t.t insert end \n******************** +.t.t insert end rrrrrrrrrrrrrrr r1 +.t.t insert end ************\n\n* +.t.t insert end rrrrrrrrrrrr r1 +.t.t insert end ******** +.t.t insert end rrrrrrrrrrrrrrrrrrrrrrrrr r1 +.t.t insert end \n***** +.t.t insert end rrrrrrrrrrrrrrrrrrrr r1 +.t.t insert end **********\n\n +.t.t insert end rrrrrrrrrrrrrrr {r1 indent1} +.t.t insert end \n** dummy +.t.t insert end ** +.t.t insert end rrrrrrrrrrrrrrrrrrrrn\n r1 +.t.t insert end \n +.t.t insert end rrrr {r1 indent1} +.t.t insert end \n*** +.t.t insert end rrr r1 + +.t.t insert end \n\nMiscellaneous:\n\n +.t.t insert end rrr r1 +.t.t insert end ***** +.t.t insert end rrr r1 +foreach i {1 2 3} { + .t.t insert end \n + .t.t insert end *** + .t.t insert end rrrrr r1 +} +.t.t insert end \n +.t.t insert end rrr r1 +.t.t insert end ***** +.t.t insert end rrr r1 diff --git a/tests/bgerror.test b/tests/bgerror.test new file mode 100644 index 0000000..72b5400 --- /dev/null +++ b/tests/bgerror.test @@ -0,0 +1,59 @@ +# This file is a Tcl script to test the bgerror command. +# It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) bgerror.test 1.1 97/08/06 09:28:30 + +if {[info commands test] == ""} { + source defs +} + + +test bgerror-1.1 {bgerror / tkerror compat} { + set errRes {} + proc tkerror {err} { + global errRes; + set errRes $err; + } + after 0 {error err1} + vwait errRes; + set errRes; +} err1 + +test bgerror-1.2 {bgerror / tkerror compat / accumulation} { + set errRes {} + proc tkerror {err} { + global errRes; + lappend errRes $err; + } + after 0 {error err1} + after 0 {error err2} + after 0 {error err3} + update + set errRes; +} {err1 err2 err3} + +test bgerror-1.3 {bgerror / tkerror compat / accumulation / break} { + set errRes {} + proc tkerror {err} { + global errRes; + lappend errRes $err; + return -code break "skip!"; + } + after 0 {error err1} + after 0 {error err2} + after 0 {error err3} + update + set errRes; +} err1 + +catch {rename tkerror {}} + +# some testing of the default error dialog +# would be needed too, but that's not easy at all +# to emulate. + diff --git a/tests/bind.test b/tests/bind.test new file mode 100644 index 0000000..18de465 --- /dev/null +++ b/tests/bind.test @@ -0,0 +1,2530 @@ +# This file is a Tcl script to test out Tk's "bind" and "bindtags" +# commands plus the procedures in tkBind.c. It is organized in the +# standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) bind.test 1.39 97/07/01 18:01:05 + +if {[string compare test [info procs test]] != 0} { + source defs +} + +catch {destroy .b} +toplevel .b -width 100 -height 50 +wm geom .b +0+0 +update idletasks + +proc setup {} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + pack .b.f + focus -force .b.f + foreach p [event info] {event delete $p} + update +} +setup + +foreach i [bind Test] { + bind Test $i {} +} +foreach i [bind all] { + bind all $i {} +} + +test bind-1.1 {bind command} { + list [catch {bind} msg] $msg +} {1 {wrong # args: should be "bind window ?pattern? ?command?"}} +test bind-1.2 {bind command} { + list [catch {bind a b c d} msg] $msg +} {1 {wrong # args: should be "bind window ?pattern? ?command?"}} +test bind-1.3 {bind command} { + list [catch {bind .gorp} msg] $msg +} {1 {bad window path name ".gorp"}} +test bind-1.4 {bind command} { + list [catch {bind foo} msg] $msg +} {0 {}} +test bind-1.5 {bind command} { + list [catch {bind .b <gorp-> {}} msg] $msg +} {0 {}} +test bind-1.6 {bind command} { + catch {destroy .b.f} + frame .b.f + bind .b.f <Enter> {test script} + set result [bind .b.f <Enter>] + bind .b.f <Enter> {} + list $result [bind .b.f <Enter>] +} {{test script} {}} +test bind-1.7 {bind command} { + catch {destroy .b.f} + frame .b.f + bind .b.f <Enter> {test script} + bind .b.f <Enter> {+more text} + bind .b.f <Enter> +} {test script +more text} +test bind-1.8 {bind command} { + list [catch {bind .b <gorp-> {test script}} msg] $msg [bind .b] +} {1 {bad event type or keysym "gorp"} {}} +test bind-1.9 {bind command} { + list [catch {bind .b <gorp->} msg] $msg +} {0 {}} +test bind-1.10 {bind command} { + catch {destroy .b.f} + frame .b.f + bind .b.f <Enter> {script 1} + bind .b.f <Leave> {script 2} + bind .b.f a {script for a} + bind .b.f b {script for b} + lsort [bind .b.f] +} {<Enter> <Leave> a b} + +test bind-2.1 {bindtags command} { + list [catch {bindtags} msg] $msg +} {1 {wrong # args: should be "bindtags window ?tags?"}} +test bind-2.2 {bindtags command} { + list [catch {bindtags a b c} msg] $msg +} {1 {wrong # args: should be "bindtags window ?tags?"}} +test bind-2.3 {bindtags command} { + list [catch {bindtags .foo} msg] $msg +} {1 {bad window path name ".foo"}} +test bind-2.4 {bindtags command} { + bindtags .b +} {.b Toplevel all} +test bind-2.5 {bindtags command} { + catch {destroy .b.f} + frame .b.f + bindtags .b.f +} {.b.f Frame .b all} +test bind-2.6 {bindtags command} { + catch {destroy .b.f} + frame .b.f + bindtags .b.f {{x y z} b c d} + bindtags .b.f +} {{x y z} b c d} +test bind-2.7 {bindtags command} { + catch {destroy .b.f} + frame .b.f + bindtags .b.f {x y z} + bindtags .b.f {} + bindtags .b.f +} {.b.f Frame .b all} +test bind-2.8 {bindtags command} { + catch {destroy .b.f} + frame .b.f + bindtags .b.f {x y z} + bindtags .b.f {a b c d} + bindtags .b.f +} {a b c d} +test bind-2.9 {bindtags command} { + catch {destroy .b.f} + frame .b.f + bindtags .b.f {a b c} + list [catch {bindtags .b.f "\{"} msg] $msg [bindtags .b.f] +} {1 {unmatched open brace in list} {.b.f Frame .b all}} +test bind-2.10 {bindtags command} { + catch {destroy .b.f} + frame .b.f + bindtags .b.f {a b c} + list [catch {bindtags .b.f "a .gorp b"} msg] $msg [bindtags .b.f] +} {0 {} {a .gorp b}} +test bind-3.1 {TkFreeBindingTags procedure} { + catch {destroy .b.f} + frame .b.f + bindtags .b.f "a b c d" + destroy .b.f +} {} +test bind-3.2 {TkFreeBindingTags procedure} { + catch {destroy .b.f} + frame .b.f + catch {bindtags .b.f "a .gorp b .b.f"} + destroy .b.f +} {} + +bind all <Enter> {lappend x "%W enter all"} +bind Test <Enter> {lappend x "%W enter frame"} +bind Toplevel <Enter> {lappend x "%W enter toplevel"} +bind xyz <Enter> {lappend x "%W enter xyz"} +bind {a b} <Enter> {lappend x "%W enter {a b}"} +bind .b <Enter> {lappend x "%W enter .b"} +test bind-4.1 {TkBindEventProc procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + pack .b.f + update + bind .b.f <Enter> {lappend x "%W enter .b.f"} + set x {} + event gen .b.f <Enter> + set x +} {{.b.f enter .b.f} {.b.f enter frame} {.b.f enter .b} {.b.f enter all}} +test bind-4.2 {TkBindEventProc procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + pack .b.f + update + bind .b.f <Enter> {lappend x "%W enter .b.f"} + bindtags .b.f {.b.f {a b} xyz} + set x {} + event gen .b.f <Enter> + set x +} {{.b.f enter .b.f} {.b.f enter {a b}} {.b.f enter xyz}} +test bind-4.3 {TkBindEventProc procedure} { + set x {} + event gen .b <Enter> + set x +} {{.b enter .b} {.b enter toplevel} {.b enter all}} +test bind-4.4 {TkBindEventProc procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + pack .b.f + update + bindtags .b.f {.b.f .b.f2 .b.f3} + frame .b.f3 -width 50 -height 50 + pack .b.f3 + bind .b.f <Enter> {lappend x "%W enter .b.f"} + bind .b.f3 <Enter> {lappend x "%W enter .b.f3"} + set x {} + event gen .b.f <Enter> + destroy .b.f3 + set x +} {{.b.f enter .b.f} {.b.f enter .b.f3}} +test bind-4.5 {TkBindEventProc procedure} { + # This tests memory allocation for objPtr; it won't serve any useful + # purpose unless run with some sort of allocation checker turned on. + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + pack .b.f + update + bindtags .b.f {a b c d e f g h i j k l m n o p q r s t u v w x y z} + event gen .b.f <Enter> +} {} +bind all <Enter> {} +bind Test <Enter> {} +bind Toplevel <Enter> {} +bind xyz <Enter> {} +bind {a b} <Enter> {} +bind .b <Enter> {} + +test bind-5.1 {Tk_CreateBindingTable procedure} { + catch {destroy .b.c} + canvas .b.c + .b.c bind foo +} {} + + +test bind-6.1 {Tk_DeleteBindTable procedure} { + catch {destroy .b.c} + canvas .b.c + .b.c bind foo <1> {string 1} + .b.c create rectangle 0 0 100 100 + .b.c bind 1 <2> {string 2} + destroy .b.c +} {} +test bind-6.2 {Tk_DeleteBindTable procedure: pending bindings deleted later} { + catch {interp delete foo} + interp create foo + foo eval { + load {} Tk + load {} Tktest + wm geometry . +0+0 + frame .t -width 50 -height 50 + bindtags .t {a b c d} + pack .t + update + set x {} + testcbind a <1> "lappend x a1; destroy ." "lappend x bye.a1" + bind b <1> "lappend x b1" + testcbind c <1> "lappend x c1" "lappend x bye.c1" + testcbind c <2> "lappend x all2" "lappend x bye.all2" + event gen .t <1> + } + set x [foo eval set x] + interp delete foo + set x +} {a1 bye.all2 bye.a1 b1 bye.c1} + +test bind-7.1 {Tk_CreateBinding procedure: error} { + catch {destroy .b.c} + canvas .b.c + list [catch {.b.c bind foo <} msg] $msg +} {1 {no event type or button # or keysym}} +test bind-7.2 {Tk_CreateBinding procedure: replace existing C binding} { + catch {destroy .b.f} + frame .b.f + testcbind .b.f <1> "xyz" "lappend x bye.1" + set x {} + bind .b.f <1> "abc" + destroy .b.f + set x +} {bye.1} +test bind-7.3 {Tk_CreateBinding procedure: append} { + catch {destroy .b.c} + canvas .b.c + .b.c bind foo <1> "button 1" + .b.c bind foo <1> "+more button 1" + .b.c bind foo <1> +} {button 1 +more button 1} +test bind-7.4 {Tk_CreateBinding procedure: append to non-existing} { + catch {destroy .b.c} + canvas .b.c + .b.c bind foo <1> "+button 1" + .b.c bind foo <1> +} {button 1} + +test bind-8.1 {TkCreateBindingProcedure: error} { + list [catch {testcbind . <xyz> "xyz"} msg] $msg +} {1 {bad event type or keysym "xyz"}} +test bind-8.2 {TkCreateBindingProcedure: new binding} { + catch {destroy .b.f} + frame .b.f + testcbind .b.f <1> "lappend x 1" "lappend x bye.1" + set x {} + event gen .b.f <1> + destroy .b.f + set x +} {bye.1} +test bind-8.3 {TkCreateBindingProcedure: replace existing} { + catch {destroy .b.f} + frame .b.f + pack .b.f + set x {} + testcbind .b.f <1> "lappend x old1" "lappend x bye.old1" + testcbind .b.f <1> "lappend x new1" "lappend x bye.new1" + set x +} {bye.old1} +test bind-8.4 {TkCreateBindingProcedure: replace existing while pending} { + catch {destroy .b.f} + frame .b.f + pack .b.f + update + testcbind .b.f <1> "lappend x .b.f; testcbind Frame <1> {lappend x Frame}" + testcbind Frame <1> "lappend x never" + set x {} + event gen .b.f <1> + bind .b.f <1> {} + set x +} {.b.f Frame} + +test bind-9.1 {Tk_DeleteBinding procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + list [catch {bind .b.f <} msg] $msg +} {0 {}} +test bind-9.2 {Tk_DeleteBinding procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + foreach i {a b c d} { + bind .b.f $i "binding for $i" + } + set result {} + foreach i {b d a c} { + bind .b.f $i {} + lappend result [lsort [bind .b.f]] + } + set result +} {{a c d} {a c} c {}} +test bind-9.3 {Tk_DeleteBinding procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + foreach i {<1> <Meta-1> <Control-1> <Double-Alt-1>} { + bind .b.f $i "binding for $i" + } + set result {} + foreach i {<Control-1> <Double-Alt-1> <1> <Meta-1>} { + bind .b.f $i {} + lappend result [lsort [bind .b.f]] + } + set result +} {{<Button-1> <Double-Alt-Button-1> <Meta-Button-1>} {<Button-1> <Meta-Button-1>} <Meta-Button-1> {}} +test bind-9.4 {Tk_DeleteBinding procedure: pending bindings delete later} { + catch {destroy .b.f} + frame .b.f + pack .b.f + update + bindtags .b.f {a b c} + testcbind a <1> {lappend x a1; bind c <1> {}; bind c <2> {}} {lappend x bye.a1} + bind b <1> {lappend x b1} + testcbind c <1> {lappend x c1} {lappend x bye.c1} + testcbind c <2> {lappend x c2} {lappend x bye.c2} + set x {} + event gen .b.f <1> + bind a <1> {} + bind b <1> {} + set x +} {a1 bye.c2 b1 bye.c1 bye.a1} + +test bind-10.1 {Tk_GetBinding procedure} { + catch {destroy .b.c} + canvas .b.c + list [catch {.b.c bind foo <} msg] $msg +} {1 {no event type or button # or keysym}} +test bind-10.2 {Tk_GetBinding procedure} { + catch {destroy .b.c} + canvas .b.c + .b.c bind foo a Test + .b.c bind foo a +} {Test} +test bind-10.3 {Tk_GetBinding procedure: C binding} { + catch {destroy .b.f} + frame .b.f + testcbind .b.f <1> "foo" + list [bind .b.f] [bind .b.f <1>] +} {<Button-1> {}} + +test bind-11.1 {Tk_GetAllBindings procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + foreach i "! a \\\{ ~ <Delete> <space> <<Paste>> <Tab> <Linefeed> <less> <Meta-a> <Acircumflex>" { + bind .b.f $i Test + } + lsort [bind .b.f] +} {! <<Paste>> <Key-Acircumflex> <Key-Delete> <Key-Linefeed> <Key-Tab> <Key-less> <Key-space> <Meta-Key-a> a \{ ~} +test bind-11.2 {Tk_GetAllBindings procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + foreach i "<Double-1> <Triple-1> <Meta-Control-a> <Double-Alt-Enter> <1>" { + bind .b.f $i Test + } + lsort [bind .b.f] +} {<Button-1> <Control-Meta-Key-a> <Double-Alt-Enter> <Double-Button-1> <Triple-Button-1>} +test bind-11.3 {Tk_GetAllBindings procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + foreach i "<Double-Triple-1> abcd a<Leave>b" { + bind .b.f $i Test + } + lsort [bind .b.f] +} {<Triple-Button-1> a<Leave>b abcd} + + +test bind-12.1 {Tk_DeleteAllBindings procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + destroy .b.f +} {} +test bind-12.2 {Tk_DeleteAllBindings procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + foreach i "a b c <Meta-1> <Alt-a> <Control-a>" { + bind .b.f $i x + } + destroy .b.f +} {} +test bind-12.3 {Tk_DeleteAllBindings procedure: pending bindings deleted later} { + catch {destroy .b.f} + frame .b.f + pack .b.f + update + testcbind .b.f <1> {lappend x before; event gen .b.f <2>; lappend x after} {lappend x bye.f1} + testcbind .b.f <2> {destroy .b.f} {lappend x bye.f2} + bind .b.f <Destroy> {lappend x fDestroy} + testcbind .b.f <3> {foo} {lappend x bye.f3} + set x {} + event gen .b.f <1> + set x +} {before fDestroy bye.f3 bye.f2 after bye.f1} + +bind Test <KeyPress> {lappend x "%W %K Test press any"} +bind all <KeyPress> {lappend x "%W %K all press any"} +bind Test a {lappend x "%W %K Test press a"} +bind all x {lappend x "%W %K all press x"} + +test bind-13.1 {Tk_BindEvent procedure} { + setup + bind .b.f a {lappend x "%W %K .b.f press a"} + set x {} + event gen .b.f <Key-a> + event gen .b.f <Key-b> + event gen .b.f <Key-x> + set x +} {{.b.f a .b.f press a} {.b.f a Test press a} {.b.f a all press any} {.b.f b Test press any} {.b.f b all press any} {.b.f x Test press any} {.b.f x all press x}} + +bind Test <KeyPress> {lappend x "%W %K Test press any"; break} +bind all <KeyPress> {continue; lappend x "%W %K all press any"} + +test bind-13.2 {Tk_BindEvent procedure} { + setup + bind .b.f b {lappend x "%W %K .b.f press a"} + set x {} + event gen .b.f <Key-b> + set x +} {{.b.f b .b.f press a} {.b.f b Test press any}} +if {[info procs bgerror] == "bgerror"} { + rename bgerror {} +} +proc bgerror args {} +bind Test <KeyPress> {lappend x "%W %K Test press any"; error Test} +test bind-13.3 {Tk_BindEvent procedure} { + setup + bind .b.f b {lappend x "%W %K .b.f press a"} + set x {} + event gen .b.f <Key-b> + update + list $x $errorInfo +} {{{.b.f b .b.f press a} {.b.f b Test press any}} {Test + while executing +"error Test" + (command bound to event)}} +rename bgerror {} +test bind-13.4 {Tk_BindEvent procedure} { + proc foo {} { + set x 44 + event gen .b.f <Key-a> + } + setup + bind .b.f a {lappend x "%W %K .b.f press a"} + set x {} + foo + set x +} {{.b.f a .b.f press a} {.b.f a Test press a}} +test bind-13.5 {Tk_BindEvent procedure} { + bind all <Destroy> {lappend x "%W destroyed"} + set x {} + list [catch {frame .b.g -gorp foo} msg] $msg $x +} {1 {unknown option "-gorp"} {{.b.g destroyed}}} +foreach i [bind all] { + bind all $i {} +} +foreach i [bind Test] { + bind Test $i {} +} +test bind-13.6 {Tk_BindEvent procedure} { + setup + bind .b.f z {lappend x "%W z (.b.f binding)"} + bind Test z {lappend x "%W z (.b.f binding)"} + bind all z {bind .b.f z {}; lappend x "%W z (.b.f binding)"} + set x {} + event gen .b.f <Key-z> + bind Test z {} + bind all z {} + set x +} {{.b.f z (.b.f binding)} {.b.f z (.b.f binding)} {.b.f z (.b.f binding)}} +test bind-13.7 {Tk_BindEvent procedure} { + setup + bind .b.f z {lappend x "%W z (.b.f binding)"} + bind Test z {lappend x "%W z (.b.f binding)"} + bind all z {destroy .b.f; lappend x "%W z (.b.f binding)"} + set x {} + event gen .b.f <Key-z> + bind Test z {} + bind all z {} + set x +} {{.b.f z (.b.f binding)} {.b.f z (.b.f binding)} {.b.f z (.b.f binding)}} +test bind-13.8 {Tk_BindEvent procedure} { + setup + bind .b.f <1> {lappend x "%W z (.b.f <1> binding)"} + bind .b.f <ButtonPress> {lappend x "%W z (.b.f <ButtonPress> binding)"} + set x {} + event gen .b.f <Button-1> + event gen .b.f <Button-2> + set x +} {{.b.f z (.b.f <1> binding)} {.b.f z (.b.f <ButtonPress> binding)}} +test bind-13.9 {Tk_BindEvent procedure: ignore NotifyInferior} { + setup + bind .b.f <Enter> "lappend x Enter%#" + bind .b.f <Leave> "lappend x Leave%#" + set x {} + event gen .b.f <Enter> -serial 100 -detail NotifyAncestor + event gen .b.f <Enter> -serial 101 -detail NotifyInferior + event gen .b.f <Leave> -serial 102 -detail NotifyAncestor + event gen .b.f <Leave> -serial 103 -detail NotifyInferior + set x +} {Enter100 Leave102} +test bind-13.10 {Tk_BindEvent procedure: collapse Motions} { + setup + bind .b.f <Motion> "lappend x Motion%#(%x,%y)" + set x {} + event gen .b.f <Motion> -serial 100 -x 100 -y 200 -when tail + update + event gen .b.f <Motion> -serial 101 -x 200 -y 300 -when tail + event gen .b.f <Motion> -serial 102 -x 300 -y 400 -when tail + update + set x +} {Motion100(100,200) Motion102(300,400)} +test bind-13.11 {Tk_BindEvent procedure: collapse repeating modifiers} { + setup + bind .b.f <Key> "lappend x %K%#" + bind .b.f <KeyRelease> "lappend x %K%#" + event gen .b.f <Key-Shift_L> -serial 100 -when tail + event gen .b.f <KeyRelease-Shift_L> -serial 101 -when tail + event gen .b.f <Key-Shift_L> -serial 102 -when tail + event gen .b.f <KeyRelease-Shift_L> -serial 103 -when tail + update +} {} +test bind-13.12 {Tk_BindEvent procedure: valid key detail} { + setup + bind .b.f <Key> "lappend x Key%K" + bind .b.f <KeyRelease> "lappend x Release%K" + set x {} + event gen .b.f <Key> -keysym a + event gen .b.f <KeyRelease> -keysym a + set x +} {Keya Releasea} +test bind-13.13 {Tk_BindEvent procedure: invalid key detail} { + setup + bind .b.f <Key> "lappend x Key%K" + bind .b.f <KeyRelease> "lappend x Release%K" + set x {} + event gen .b.f <Key> -keycode 0 + event gen .b.f <KeyRelease> -keycode 0 + set x +} {Key?? Release??} +test bind-13.14 {Tk_BindEvent procedure: button detail} { + setup + bind .b.f <Button> "lappend x Button%b" + bind .b.f <ButtonRelease> "lappend x Release%b" + set x {} + event gen .b.f <Button> -button 1 + event gen .b.f <ButtonRelease> -button 3 + set x +} {Button1 Release3} +test bind-13.15 {Tk_BindEvent procedure: virtual detail} { + setup + bind .b.f <<Paste>> "lappend x Paste" + set x {} + event gen .b.f <<Paste>> + set x +} {Paste} +test bind-13.16 {Tk_BindEvent procedure: virtual event in event stream} { + setup + bind .b.f <<Paste>> "lappend x Paste" + set x {} + event gen .b.f <<Paste>> + set x +} {Paste} +test bind-13.17 {Tk_BindEvent procedure: match detail physical} { + setup + bind .b.f <Button-2> {set x Button-2} + event add <<Paste>> <Button-2> + bind .b.f <<Paste>> {set x Paste} + set x {} + event gen .b.f <Button-2> + set x +} {Button-2} +test bind-13.18 {Tk_BindEvent procedure: no match detail physical} { + setup + event add <<Paste>> <Button-2> + bind .b.f <<Paste>> {set x Paste} + set x {} + event gen .b.f <Button-2> + set x +} {Paste} +test bind-13.19 {Tk_BindEvent procedure: match detail virtual} { + setup + event add <<Paste>> <Button-2> + bind .b.f <<Paste>> "lappend x Paste" + set x {} + event gen .b.f <Button-2> + set x +} {Paste} +test bind-13.20 {Tk_BindEvent procedure: no match detail virtual} { + setup + event add <<Paste>> <Button-2> + bind .b.f <<Paste>> "lappend x Paste" + set x {} + event gen .b.f <Button> + set x +} {} +test bind-13.21 {Tk_BindEvent procedure: match no-detail physical} { + setup + bind .b.f <Button> {set x Button} + event add <<Paste>> <Button> + bind .b.f <<Paste>> {set x Paste} + set x {} + event gen .b.f <Button-2> + set x +} {Button} +test bind-13.22 {Tk_BindEvent procedure: no match no-detail physical} { + setup + event add <<Paste>> <Button> + bind .b.f <<Paste>> {set x Paste} + set x {} + event gen .b.f <Button-2> + set x +} {Paste} +test bind-13.23 {Tk_BindEvent procedure: match no-detail virtual} { + setup + event add <<Paste>> <Button> + bind .b.f <<Paste>> "lappend x Paste" + set x {} + event gen .b.f <Button-2> + set x +} {Paste} +test bind-13.24 {Tk_BindEvent procedure: no match no-detail virtual} { + setup + event add <<Paste>> <Key> + bind .b.f <<Paste>> "lappend x Paste" + set x {} + event gen .b.f <Button> + set x +} {} +test bind-13.25 {Tk_BindEvent procedure: precedence} { + setup + event add <<Paste>> <Button-2> + event add <<Copy>> <Button> + bind .b.f <Button-2> "lappend x Button-2" + bind .b.f <<Paste>> "lappend x Paste" + bind .b.f <Button> "lappend x Button" + bind .b.f <<Copy>> "lappend x Copy" + + set x {} + event gen .b.f <Button-2> + bind .b.f <Button-2> {} + event gen .b.f <Button-2> + bind .b.f <<Paste>> {} + event gen .b.f <Button-2> + bind .b.f <Button> {} + event gen .b.f <Button-2> + bind .b.f <<Copy>> {} + event gen .b.f <Button-2> + set x +} {Button-2 Paste Button Copy} +test bind-13.26 {Tk_BindEvent procedure: no detail virtual pattern list} { + setup + bind .b.f <Button-2> {set x Button-2} + set x {} + event gen .b.f <Button-2> + set x +} {Button-2} +test bind-13.27 {Tk_BindEvent procedure: detail virtual pattern list} { + setup + event add <<Paste>> <Button-2> + bind .b.f <<Paste>> {set x Paste} + set x {} + event gen .b.f <Button-2> + set x +} {Paste} +test bind-13.28 {Tk_BindEvent procedure: no no-detail virtual pattern list} { + setup + bind .b.f <Button> {set x Button} + set x {} + event gen .b.f <Button-2> + set x +} {Button} +test bind-13.29 {Tk_BindEvent procedure: no-detail virtual pattern list} { + setup + event add <<Paste>> <Button> + bind .b.f <<Paste>> {set x Paste} + set x {} + event gen .b.f <Button-2> + set x +} {Paste} +test bind-13.30 {Tk_BindEvent procedure: no match} { + setup + event gen .b.f <Button-2> +} {} +test bind-13.31 {Tk_BindEvent procedure: match} { + setup + bind .b.f <Button-2> {set x Button-2} + set x {} + event gen .b.f <Button-2> + set x +} {Button-2} +test bind-13.32 {Tk_BindEvent procedure: many C bindings cause realloc} { + setup + bindtags .b.f {a b c d e f g h i j k l m n o p} + foreach p [bindtags .b.f] { + testcbind $p <1> "lappend x $p" + } + set x {} + event gen .b.f <1> + foreach p [bindtags .b.f] { + bind $p <1> {} + } + set x +} {a b c d e f g h i j k l m n o p} +test bind-13.33 {Tk_BindEvent procedure: multiple tags} { + setup + bind .b.f <Button-2> {lappend x .b.f} + bind Test <Button-2> {lappend x Button} + set x {} + event gen .b.f <Button-2> + bind Test <Button-2> {} + set x +} {.b.f Button} +test bind-13.34 {Tk_BindEvent procedure: execute C binding} { + setup + testcbind .b.f <1> {lappend x 1} + set x {} + event gen .b.f <1> + set x +} {1} +test bind-13.35 {Tk_BindEvent procedure: pending list marked deleted} { + setup + testcbind Test <1> {lappend x Test} {lappend x Deleted} + bind .b.f <1> {lappend x .b.f; destroy .b.f} + set x {} + event gen .b.f <1> + set y [list $x [bind Test]] + bind Test <1> {} + set y +} {.b.f <Button-1>} +test bind-13.36 {Tk_BindEvent procedure: C binding marked deleted} { + setup + testcbind Test <1> {lappend x Test} {lappend x Deleted} + bind .b.f <1> {lappend x .b.f; bind Test <1> {}; lappend x after} + set x {} + event gen .b.f <1> + set x +} {.b.f after Deleted} +test bind-13.37 {Tk_BindEvent procedure: C binding gets to run} { + setup + testcbind Test <1> {lappend x Test} + bind .b.f <1> {lappend x .b.f} + set x {} + event gen .b.f <1> + bind Test <1> {} + set x +} {.b.f Test} +test bind-13.38 {Tk_BindEvent procedure: C binding deleted, refcount == 0} { + setup + testcbind .b.f <1> {lappend x hi; bind .b.f <1> {}} {lappend x bye} + set x {} + event gen .b.f <1> + set x +} {hi bye} +test bind-13.39 {Tk_BindEvent procedure: C binding deleted, refcount != 0} { + setup + testcbind .b.f <1> { + lappend x before$n + if {$n==0} { + bind .b.f <1> {} + } else { + set n [expr $n-1] + event gen .b.f <1> + } + lappend x after$n + } {lappend x Deleted} + set n 3 + set x {} + event gen .b.f <1> + set x +} {before3 before2 before1 before0 after0 after0 after0 after0 Deleted} +test bind-13.40 {Tk_BindEvent procedure: continue in script} { + setup + bind .b.f <Button-2> {lappend x b1; continue; lappend x b2} + bind Test <Button-2> {lappend x B1; continue; lappend x B2} + set x {} + event gen .b.f <Button-2> + bind Test <Button-2> {} + set x +} {b1 B1} +test bind-13.41 {Tk_BindEvent procedure: continue in script} { + setup + testcbind .b.f <Button-2> {lappend x b1; continue; lappend x b2} + testcbind Test <Button-2> {lappend x B1; continue; lappend x B2} + set x {} + event gen .b.f <Button-2> + bind Test <Button-2> {} + set x +} {b1 B1} +test bind-13.42 {Tk_BindEvent procedure: break in script} { + setup + bind .b.f <Button-2> {lappend x b1; break; lappend x b2} + bind Test <Button-2> {lappend x B1; break; lappend x B2} + set x {} + event gen .b.f <Button-2> + bind Test <Button-2> {} + set x +} {b1} +test bind-13.43 {Tk_BindEvent procedure: break in script} { + setup + testcbind .b.f <Button-2> {lappend x b1; break; lappend x b2} + testcbind Test <Button-2> {lappend x B1; break; lappend x B2} + set x {} + event gen .b.f <Button-2> + bind Test <Button-2> {} + set x +} {b1} + +proc bgerror msg { + global x + lappend x $msg +} +test bind-13.44 {Tk_BindEvent procedure: error in script} { + setup + bind .b.f <Button-2> {lappend x b1; blap} + bind Test <Button-2> {lappend x B1} + set x {} + event gen .b.f <Button-2> + update + bind Test <Button-2> {} + set x +} {b1 {invalid command name "blap"}} +test bind-13.45 {Tk_BindEvent procedure: error in script} { + setup + testcbind .b.f <Button-2> {lappend x b1; blap} + testcbind Test <Button-2> {lappend x B1} + set x {} + event gen .b.f <Button-2> + update + bind Test <Button-2> {} + set x +} {b1 {invalid command name "blap"}} + +test bind-14.1 {TkBindDeadWindow: no C bindings pending} { + setup + bind .b.f <1> x + testcbind .b.f <2> y + destroy .b.f +} {} +test bind-14.2 {TkBindDeadWindow: is called after <Destroy>} { + setup + testcbind .b.f <Destroy> "lappend x .b.f" + testcbind Test <Destroy> "lappend x Test" + set x {} + destroy .b.f + bind Test <Destroy> {} + set x +} {.b.f Test} +test bind-14.3 {TkBindDeadWindow: pending C bindings} { + setup + bindtags .b.f {a b c d} + testcbind a <1> "lappend x a1" "lappend x bye.a1" + testcbind b <1> "destroy .b.f; lappend x b1" "lappend x bye.b1" + testcbind c <1> "lappend x c1" "lappend x bye.c1" + testcbind d <1> "lappend x d1" "lappend x bye.d1" + bind a <2> "event gen .b.f <1>" + testcbind b <2> "lappend x b2" "lappend x bye.b2" + testcbind c <2> "lappend x c2" "lappend x bye.d2" + bind d <2> "lappend x d2" + testcbind a <3> "event gen .b.f <2>" + set x {} + event gen .b.f <3> + set y $x + foreach tag {a b c d} { + foreach event {<1> <2> <3>} { + bind $tag $event {} + } + } + set y +} {a1 b1 d2} + +test bind-15.1 {MatchPatterns procedure, ignoring type mismatches} { + setup + bind .b.f ab {set x 1} + set x 0 + event gen .b.f <Key-a> + event gen .b.f <KeyRelease-a> + event gen .b.f <Key-b> + event gen .b.f <KeyRelease-b> + set x +} 1 +test bind-15.2 {MatchPatterns procedure, ignoring type mismatches} { + setup + bind .b.f ab {set x 1} + set x 0 + event gen .b.f <Key-a> + event gen .b.f <Enter> + event gen .b.f <KeyRelease-a> + event gen .b.f <Leave> + event gen .b.f <Key-b> + event gen .b.f <KeyRelease-b> + set x +} 1 +test bind-15.3 {MatchPatterns procedure, ignoring type mismatches} { + setup + bind .b.f ab {set x 1} + set x 0 + event gen .b.f <Key-a> + event gen .b.f <Button-1> + event gen .b.f <Key-b> + set x +} 0 +test bind-15.4 {MatchPatterns procedure, ignoring type mismatches} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-1> + event gen .b.f <ButtonRelease-1> + event gen .b.f <Button-1> + event gen .b.f <ButtonRelease-1> + set x +} 1 +test bind-15.5 {MatchPatterns procedure, ignoring type mismatches} { + setup + bind .b.f <Double-ButtonRelease> {set x 1} + set x 0 + event gen .b.f <Button-1> + event gen .b.f <ButtonRelease-1> + event gen .b.f <Button-2> + event gen .b.f <ButtonRelease-2> + set x +} 1 +test bind-15.6 {MatchPatterns procedure, ignoring type mismatches} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-1> + event gen .b.f <Key-a> + event gen .b.f <ButtonRelease-1> + event gen .b.f <Button-1> + event gen .b.f <ButtonRelease-1> + set x +} 0 +test bind-15.7 {MatchPatterns procedure, ignoring type mismatches} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-1> + event gen .b.f <Key-Shift_L> + event gen .b.f <ButtonRelease-1> + event gen .b.f <Button-1> + event gen .b.f <ButtonRelease-1> + set x +} 1 +test bind-15.8 {MatchPatterns procedure, ignoring type mismatches} { + setup + bind .b.f ab {set x 1} + set x 0 + event gen .b.f <Key-a> + event gen .b.f <Key-c> + event gen .b.f <Key-b> + set x +} 0 +test bind-15.9 {MatchPatterns procedure, modifier checks} { + setup + bind .b.f <M1-M2-Key> {set x 1} + set x 0 + event gen .b.f <Key-a> -state 0x18 + set x +} 1 +test bind-15.10 {MatchPatterns procedure, modifier checks} { + setup + bind .b.f <M1-M2-Key> {set x 1} + set x 0 + event gen .b.f <Key-a> -state 0xfc + set x +} 1 +test bind-15.11 {MatchPatterns procedure, modifier checks} { + setup + bind .b.f <M1-M2-Key> {set x 1} + set x 0 + event gen .b.f <Key-a> -state 0x8 + set x +} 0 +test bind-15.12 {MatchPatterns procedure, ignore modifier presses and releases} {nonPortable} { + # This test is non-portable because the Shift_L keysym may behave + # differently on some platforms. + setup + bind .b.f aB {set x 1} + set x 0 + event gen .b.f <Key-a> + event gen .b.f <Key-Shift_L> + event gen .b.f <Key-b> -state 1 + set x +} 1 +test bind-15.13 {MatchPatterns procedure, checking detail} { + setup + bind .b.f ab {set x 1} + set x 0 + event gen .b.f <Key-a> + event gen .b.f <Key-c> + set x +} 0 +test bind-15.14 {MatchPatterns procedure, checking "nearby"} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-2> + event gen .b.f <Button-1> -x 30 -y 40 + event gen .b.f <Button-1> -x 31 -y 39 + set x +} 1 +test bind-15.15 {MatchPatterns procedure, checking "nearby"} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-2> + event gen .b.f <Button-1> -x 30 -y 40 + event gen .b.f <Button-1> -x 29 -y 41 + set x +} 1 +test bind-15.16 {MatchPatterns procedure, checking "nearby"} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-2> + event gen .b.f <Button-1> -x 30 -y 40 + event gen .b.f <Button-1> -x 40 -y 40 + set x +} 0 +test bind-15.17 {MatchPatterns procedure, checking "nearby"} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-2> + event gen .b.f <Button-1> -x 30 -y 40 + event gen .b.f <Button-1> -x 20 -y 40 + set x +} 0 +test bind-15.18 {MatchPatterns procedure, checking "nearby"} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-2> + event gen .b.f <Button-1> -x 30 -y 40 + event gen .b.f <Button-1> -x 30 -y 30 + set x +} 0 +test bind-15.19 {MatchPatterns procedure, checking "nearby"} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-2> + event gen .b.f <Button-1> -x 30 -y 40 + event gen .b.f <Button-1> -x 30 -y 50 + set x +} 0 +test bind-15.20 {MatchPatterns procedure, checking "nearby"} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-2> + event gen .b.f <Button-1> -time 300 + event gen .b.f <Button-1> -time 700 + set x +} 1 +test bind-15.21 {MatchPatterns procedure, checking "nearby"} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-2> + event gen .b.f <Button-1> -time 300 + event gen .b.f <Button-1> -time 900 + set x +} 0 +test bind-15.22 {MatchPatterns procedure, time wrap-around} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-1> -time [expr -100] + event gen .b.f <Button-1> -time 200 + set x +} 1 +test bind-15.23 {MatchPatterns procedure, time wrap-around} { + setup + bind .b.f <Double-1> {set x 1} + set x 0 + event gen .b.f <Button-1> -time -100 + event gen .b.f <Button-1> -time 500 + set x +} 0 +test bind-15.24 {MatchPatterns procedure, virtual event} { + setup + event add <<Paste>> <Button-1> + bind .b.f <<Paste>> {lappend x paste} + set x {} + event gen .b.f <Button-1> + set x +} {paste} +test bind-15.25 {MatchPatterns procedure, reject a virtual event} { + setup + event add <<Paste>> <Shift-Button-1> + bind .b.f <<Paste>> {lappend x paste} + set x {} + event gen .b.f <Button-1> + set x +} {} +test bind-15.26 {MatchPatterns procedure, reject a virtual event} { + setup + event add <<V1>> <Button> + event add <<V2>> <Button-1> + event add <<V3>> <Shift-Button-1> + bind .b.f <<V2>> "lappend x V2%#" + set x {} + event gen .b.f <Button> -serial 101 + event gen .b.f <Button-1> -serial 102 + event gen .b.f <Shift-Button-1> -serial 103 + bind .b.f <Shift-Button-1> "lappend x Shift-Button-1" + event gen .b.f <Button> -serial 104 + event gen .b.f <Button-1> -serial 105 + event gen .b.f <Shift-Button-1> -serial 106 + set x +} {V2102 V2103 V2105 Shift-Button-1} +test bind-15.27 {MatchPatterns procedure, conflict resolution} { + setup + bind .b.f <KeyPress> {set x 0} + bind .b.f a {set x 1} + set x none + event gen .b.f <Key-a> + set x +} 1 +test bind-15.28 {MatchPatterns procedure, conflict resolution} { + setup + bind .b.f <KeyPress> {set x 0} + bind .b.f a {set x 1} + set x none + event gen .b.f <Key-b> + set x +} 0 +test bind-15.29 {MatchPatterns procedure, conflict resolution} { + setup + bind .b.f <KeyPress> {lappend x 0} + bind .b.f a {lappend x 1} + bind .b.f ba {lappend x 2} + set x none + event gen .b.f <Key-b> + event gen .b.f <KeyRelease-b> + event gen .b.f <Key-a> + set x +} {none 0 2} +test bind-15.30 {MatchPatterns procedure, conflict resolution} { + setup + bind .b.f <ButtonPress> {set x 0} + bind .b.f <1> {set x 1} + set x none + event gen .b.f <Button-1> + set x +} 1 +test bind-15.31 {MatchPatterns procedure, conflict resolution} { + setup + bind .b.f <M1-Key> {set x 0} + bind .b.f <M2-Key> {set x 1} + set x none + event gen .b.f <Key-a> -state 0x18 + set x +} 1 +test bind-15.32 {MatchPatterns procedure, conflict resolution} { + setup + bind .b.f <M2-Key> {set x 0} + bind .b.f <M1-Key> {set x 1} + set x none + event gen .b.f <Key-a> -state 0x18 + set x +} 1 +test bind-15.33 {MatchPatterns procedure, conflict resolution} { + setup + bind .b.f <1> {lappend x single} + bind Test <1> {lappend x single(Test)} + bind Test <Double-1> {lappend x double(Test)} + set x {} + event gen .b.f <Button-1> + event gen .b.f <Button-1> + event gen .b.f <Button-1> + set x +} {single single(Test) single double(Test) single double(Test)} +foreach i [bind Test] { + bind Test $i {} +} +test bind-16.1 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x abcd} + set x none + event gen .b.f <Enter> + set x +} abcd +test bind-16.2 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x %#} + set x none + event gen .b.f <Enter> -serial 1234 + set x +} 1234 +test bind-16.3 {ExpandPercents procedure} { + setup + bind .b.f <Configure> {set x %a} + set x none + event gen .b.f <Configure> -above .b -window .b.f + set x +} [winfo id .b] +test bind-16.4 {ExpandPercents procedure} { + setup + bind .b.f <Button> {set x %b} + set x none + event gen .b.f <Button-3> + set x +} 3 +test bind-16.5 {ExpandPercents procedure} { + setup + bind .b.f <Expose> {set x %c} + set x none + event gen .b.f <Expose> -count 47 + set x +} 47 +test bind-16.6 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x %d} + set x none + event gen .b.f <Enter> -detail NotifyAncestor + set x +} NotifyAncestor +test bind-16.7 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x %d} + set x none + event gen .b.f <Enter> -detail NotifyVirtual + set x +} NotifyVirtual +test bind-16.8 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x %d} + set x none + event gen .b.f <Enter> -detail NotifyNonlinear + set x +} NotifyNonlinear +test bind-16.9 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x %d} + set x none + event gen .b.f <Enter> -detail NotifyNonlinearVirtual + set x +} NotifyNonlinearVirtual +test bind-16.10 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x %d} + set x none + event gen .b.f <Enter> -detail NotifyPointer + set x +} NotifyPointer +test bind-16.11 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x %d} + set x none + event gen .b.f <Enter> -detail NotifyPointerRoot + set x +} NotifyPointerRoot +test bind-16.12 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x %d} + set x none + event gen .b.f <Enter> -detail NotifyDetailNone + set x +} NotifyDetailNone +test bind-16.13 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x %f} + set x none + event gen .b.f <Enter> -focus 1 + set x +} 1 +test bind-16.14 {ExpandPercents procedure} { + setup + bind .b.f <Expose> {set x "%x %y %w %h"} + set x none + event gen .b.f <Expose> -x 24 -y 18 -width 147 -height 61 + set x +} {24 18 147 61} +test bind-16.15 {ExpandPercents procedure} { + setup + bind .b.f <Configure> {set x "%x %y %w %h"} + set x none + event gen .b.f <Configure> -x 24 -y 18 -width 147 -height 61 -window .b.f + set x +} {24 18 147 61} +test bind-16.16 {ExpandPercents procedure} { + setup + bind .b.f <Key> {set x "%k"} + set x none + event gen .b.f <Key> -keycode 146 + set x +} 146 +test bind-16.17 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x "%m"} + set x none + event gen .b.f <Enter> -mode NotifyNormal + set x +} NotifyNormal +test bind-16.18 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x "%m"} + set x none + event gen .b.f <Enter> -mode NotifyGrab + set x +} NotifyGrab +test bind-16.19 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x "%m"} + set x none + event gen .b.f <Enter> -mode NotifyUngrab + set x +} NotifyUngrab +test bind-16.20 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x "%m"} + set x none + event gen .b.f <Enter> -mode NotifyWhileGrabbed + set x +} NotifyWhileGrabbed +test bind-16.21 {ExpandPercents procedure} { + setup + bind .b.f <Map> {set x "%o"} + set x none + event gen .b.f <Map> -override 1 -window .b.f + set x +} 1 +test bind-16.22 {ExpandPercents procedure} { + setup + bind .b.f <Reparent> {set x "%o"} + set x none + event gen .b.f <Reparent> -override true -window .b.f + set x +} 1 +test bind-16.23 {ExpandPercents procedure} { + setup + bind .b.f <Configure> {set x "%o"} + set x none + event gen .b.f <Configure> -override 1 -window .b.f + set x +} 1 +test bind-16.24 {ExpandPercents procedure} { + setup + bind .b.f <Circulate> {set x "%p"} + set x none + event gen .b.f <Circulate> -place PlaceOnTop -window .b.f + set x +} PlaceOnTop +test bind-16.25 {ExpandPercents procedure} { + setup + bind .b.f <Circulate> {set x "%p"} + set x none + event gen .b.f <Circulate> -place PlaceOnBottom -window .b.f + set x +} PlaceOnBottom +test bind-16.26 {ExpandPercents procedure} { + setup + bind .b.f <1> {set x "%s"} + set x none + event gen .b.f <Button-1> -state 122 + set x +} 122 +test bind-16.27 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x "%s"} + set x none + event gen .b.f <Enter> -state 0x3ff + set x +} 1023 +test bind-16.28 {ExpandPercents procedure} { + setup + bind .b.f <Visibility> {set x "%s"} + set x none + event gen .b.f <Visibility> -state VisibilityPartiallyObscured + set x +} VisibilityPartiallyObscured +test bind-16.29 {ExpandPercents procedure} { + setup + bind .b.f <Visibility> {set x "%s"} + set x none + event gen .b.f <Visibility> -state VisibilityUnobscured + set x +} VisibilityUnobscured +test bind-16.30 {ExpandPercents procedure} { + setup + bind .b.f <Visibility> {set x "%s"} + set x none + event gen .b.f <Visibility> -state VisibilityFullyObscured + set x +} VisibilityFullyObscured +test bind-16.31 {ExpandPercents procedure} { + setup + bind .b.f <Button> {set x "%t"} + set x none + event gen .b.f <Button> -time 4294 + set x +} 4294 +test bind-16.32 {ExpandPercents procedure} { + setup + bind .b.f <Button> {set x "%x %y"} + set x none + event gen .b.f <Button> -x 881 -y 432 + set x +} {881 432} +test bind-16.33 {ExpandPercents procedure} { + setup + bind .b.f <Reparent> {set x "%x %y"} + set x none + event gen .b.f <Reparent> -x 882 -y 431 -window .b.f + set x +} {882 431} +test bind-16.34 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x "%x %y"} + set x none + event gen .b.f <Enter> -x 781 -y 632 + set x +} {781 632} +test bind-16.35 {ExpandPercents procedure} {nonPortable} { + setup + bind .b.f <Key> {lappend x "%A"} + set x {} + event gen .b.f <Key-a> + event gen .b.f <Key-A> -state 1 + event gen .b.f <Key-Tab> + event gen .b.f <Key-Return> + event gen .b.f <Key-F1> + event gen .b.f <Key-Shift_L> + event gen .b.f <Key-space> + event gen .b.f <Key-dollar> -state 1 + event gen .b.f <Key-braceleft> -state 1 + set x +} "a A { } {\r} {{}} {{}} { } {\$} \\\{" +test bind-16.36 {ExpandPercents procedure} { + setup + bind .b.f <Configure> {set x "%B"} + set x none + event gen .b.f <Configure> -borderwidth 24 -window .b.f + set x +} 24 +test bind-16.37 {ExpandPercents procedure} { + setup + bind .b.f <Enter> {set x "%E"} + set x none + event gen .b.f <Enter> -sendevent 1 + set x +} 1 +test bind-16.38 {ExpandPercents procedure} {nonPortable} { + setup + bind .b.f <Key> {lappend x %K} + set x {} + event gen .b.f <Key-a> + event gen .b.f <Key-A> -state 1 + event gen .b.f <Key-Tab> + event gen .b.f <Key-F1> + event gen .b.f <Key-Shift_L> + event gen .b.f <Key-space> + event gen .b.f <Key-dollar> -state 1 + event gen .b.f <Key-braceleft> -state 1 + set x +} {a A Tab F1 Shift_L space dollar braceleft} +test bind-16.39 {ExpandPercents procedure} { + setup + bind .b.f <Key> {set x "%N"} + set x none + event gen .b.f <Key-a> + set x +} 97 +test bind-16.40 {ExpandPercents procedure} { + setup + bind .b.f <Key> {set x "%S"} + set x none + event gen .b.f <Key-a> -subwindow .b + set x +} [winfo id .b] +test bind-16.41 {ExpandPercents procedure} { + setup + bind .b.f <Key> {set x "%T"} + set x none + event gen .b.f <Key> + set x +} 2 +test bind-16.42 {ExpandPercents procedure} { + setup + bind .b.f <Key> {set x "%W"} + set x none + event gen .b.f <Key> + set x +} .b.f +test bind-16.43 {ExpandPercents procedure} { + setup + bind .b.f <Button> {set x "%X %Y"} + set x none + event gen .b.f <Button> -rootx 422 -rooty 13 + set x +} {422 13} + + +test bind-17.1 {event command} { + list [catch {event} msg] $msg +} {1 {wrong # args: should be "event option ?arg1?"}} +test bind-17.2 {event command} { + list [catch {event {}} msg] $msg +} {1 {bad option "": should be add, delete, generate, info}} +test bind-17.3 {event command: add} { + list [catch {event add} msg] $msg +} {1 {wrong # args: should be "event add virtual sequence ?sequence ...?"}} +test bind-17.4 {event command: add 1} { + setup + event add <<Paste>> <Control-v> + event info <<Paste>> +} {<Control-Key-v>} +test bind-17.5 {event command: add 2} { + setup + event add <<Paste>> <Control-v> <Button-2> + lsort [event info <<Paste>>] +} {<Button-2> <Control-Key-v>} +test bind-17.6 {event command: add with error} { + setup + list [catch {event add <<Paste>> <Control-v> <Button-2> abc <xyz> <1>} \ + msg] $msg [lsort [event info <<Paste>>]] +} {1 {bad event type or keysym "xyz"} {<Button-2> <Control-Key-v> abc}} +test bind-17.7 {event command: delete} { + list [catch {event delete} msg] $msg +} {1 {wrong # args: should be "event delete virtual ?sequence sequence ...?"}} +test bind-17.8 {event command: delete many} { + setup + event add <<Paste>> <3> <1> <2> t + event delete <<Paste>> <1> <2> + lsort [event info <<Paste>>] +} {<Button-3> t} +test bind-17.9 {event command: delete all} { + setup + event add <<Paste>> a b + event delete <<Paste>> + event info <<Paste>> +} {} +test bind-17.10 {event command: delete 1} { + setup + event add <<Paste>> a b c + event delete <<Paste>> b + lsort [event info <<Paste>>] +} {a c} +test bind-17.11 {event command: info name} { + setup + event add <<Paste>> a b c + lsort [event info <<Paste>>] +} {a b c} +test bind-17.12 {event command: info all} { + setup + event add <<Paste>> a + event add <<Alive>> b + lsort [event info] +} {<<Alive>> <<Paste>>} +test bind-17.13 {event command: info error} { + list [catch {event info <<Paste>> <Control-v>} msg] $msg +} {1 {wrong # args: should be "event info ?virtual?"}} +test bind-17.14 {event command: generate} { + list [catch {event generate} msg] $msg +} {1 {wrong # args: should be "event generate window event ?options?"}} +test bind-17.15 {event command: generate} { + setup + bind .b.f <1> "lappend x 1" + set x {} + event generate .b.f <1> + set x +} {1} +test bind-17.16 {event command: generate} { + list [catch {event generate .b.f <xyz>} msg] $msg +} {1 {bad event type or keysym "xyz"}} +test bind-17.17 {event command} { + list [catch {event foo} msg] $msg +} {1 {bad option "foo": should be add, delete, generate, info}} + + +test bind-18.1 {CreateVirtualEvent procedure: GetVirtualEventUid} { + list [catch {event add asd <Ctrl-v>} msg] $msg +} {1 {virtual event "asd" is badly formed}} +test bind-18.2 {CreateVirtualEvent procedure: FindSequence} { + list [catch {event add <<asd>> <Ctrl-v>} msg] $msg +} {1 {bad event type or keysym "Ctrl"}} +test bind-18.3 {CreateVirtualEvent procedure: new physical} { + setup + event add <<xyz>> <Control-v> + event info <<xyz>> +} {<Control-Key-v>} +test bind-18.4 {CreateVirtualEvent procedure: duplicate physical} { + setup + event add <<xyz>> <Control-v> + event add <<xyz>> <Control-v> + event info <<xyz>> +} {<Control-Key-v>} +test bind-18.5 {CreateVirtualEvent procedure: existing physical} { + setup + event add <<xyz>> <Control-v> + event add <<abc>> <Control-v> + list [lsort [event info]] [event info <<xyz>>] [event info <<abc>>] +} {{<<abc>> <<xyz>>} <Control-Key-v> <Control-Key-v>} +test bind-18.6 {CreateVirtualEvent procedure: new virtual} { + setup + event add <<xyz>> <Control-v> + list [event info] [event info <<xyz>>] +} {<<xyz>> <Control-Key-v>} +test bind-18.7 {CreateVirtualEvent procedure: existing virtual} { + setup + event add <<xyz>> <Control-v> + event add <<xyz>> <Button-2> + list [event info] [lsort [event info <<xyz>>]] +} {<<xyz>> {<Button-2> <Control-Key-v>}} + + +test bind-19.1 {DeleteVirtualEvent procedure: GetVirtualEventUid} { + list [catch {event add xyz {}} msg] $msg +} {1 {virtual event "xyz" is badly formed}} +test bind-19.2 {DeleteVirtualEvent procedure: non-existent virtual} { + setup + event delete <<xyz>> + event info +} {} +test bind-19.3 {DeleteVirtualEvent procedure: delete 1} { + setup + event add <<xyz>> <Control-v> + event delete <<xyz>> <Control-v> + event info <<xyz>> +} {} +test bind-19.4 {DeleteVirtualEvent procedure: delete 1, not owned} { + setup + event add <<xyz>> <Control-v> + event delete <<xyz>> <Button-1> + event info <<xyz>> +} {<Control-Key-v>} +test bind-19.5 {DeleteVirtualEvent procedure: delete 1, badly formed} { + setup + event add <<xyz>> <Control-v> + list [catch {event delete <<xyz>> <xyz>} msg] $msg +} {1 {bad event type or keysym "xyz"}} +test bind-19.6 {DeleteVirtualEvent procedure: delete 1, badly formed} { + setup + event add <<xyz>> <Control-v> + list [catch {event delete <<xyz>> <<Paste>>} msg] $msg +} {1 {virtual event not allowed in definition of another virtual event}} +test bind-19.7 {DeleteVirtualEvent procedure: owns 1, delete all} { + setup + event add <<xyz>> <Control-v> + event delete <<xyz>> + event info +} {} +test bind-19.8 {DeleteVirtualEvent procedure: owns 1, delete 1} { + setup + event add <<xyz>> <Control-v> + event delete <<xyz>> <Control-v> + event info +} {} +test bind-19.9 {DeleteVirtualEvent procedure: owns many, delete all} { + setup + event add <<xyz>> <Control-v> <Control-w> <Control-x> + event delete <<xyz>> + event info +} {} +test bind-19.10 {DeleteVirtualEvent procedure: owns many, delete 1} { + setup + event add <<xyz>> <Control-v> <Control-w> <Control-x> + event delete <<xyz>> <Control-w> + lsort [event info <<xyz>>] +} {<Control-Key-v> <Control-Key-x>} +test bind-19.11 {DeleteVirtualEvent procedure: owned by 1, only} { + setup + event add <<xyz>> <Button-2> + bind .b.f <<xyz>> {lappend x %#} + set x {} + event gen .b.f <Button-2> -serial 101 + event delete <<xyz>> + event gen .b.f <Button-2> -serial 102 + set x +} {101} +test bind-19.12 {DeleteVirtualEvent procedure: owned by 1, first in chain} { + setup + event add <<abc>> <Control-Button-2> + event add <<xyz>> <Button-2> + bind .b.f <<xyz>> {lappend x xyz} + bind .b.f <<abc>> {lappend x abc} + set x {} + event gen .b.f <Button-2> + event gen .b.f <Control-Button-2> + event delete <<xyz>> + event gen .b.f <Button-2> + event gen .b.f <Control-Button-2> + list $x [event info <<abc>>] +} {{xyz abc abc} <Control-Button-2>} +test bind-19.13 {DeleteVirtualEvent procedure: owned by 1, second in chain} { + setup + event add <<def>> <Shift-Button-2> + event add <<xyz>> <Button-2> + event add <<abc>> <Control-Button-2> + bind .b.f <<xyz>> {lappend x xyz} + bind .b.f <<abc>> {lappend x abc} + bind .b.f <<def>> {lappend x def} + set x {} + event gen .b.f <Button-2> + event gen .b.f <Control-Button-2> + event gen .b.f <Shift-Button-2> + event delete <<xyz>> + event gen .b.f <Button-2> + event gen .b.f <Control-Button-2> + event gen .b.f <Shift-Button-2> + list $x [event info <<def>>] [event info <<xyz>>] [event info <<abc>>] +} {{xyz abc def abc def} <Shift-Button-2> {} <Control-Button-2>} +test bind-19.14 {DeleteVirtualEvent procedure: owned by 1, last in chain} { + setup + event add <<xyz>> <Button-2> + event add <<abc>> <Control-Button-2> + event add <<def>> <Shift-Button-2> + bind .b.f <<xyz>> {lappend x xyz} + bind .b.f <<abc>> {lappend x abc} + bind .b.f <<def>> {lappend x def} + set x {} + event gen .b.f <Button-2> + event gen .b.f <Control-Button-2> + event gen .b.f <Shift-Button-2> + event delete <<xyz>> + event gen .b.f <Button-2> + event gen .b.f <Control-Button-2> + event gen .b.f <Shift-Button-2> + list $x [event info <<xyz>>] [event info <<abc>>] [event info <<def>>] +} {{xyz abc def abc def} {} <Control-Button-2> <Shift-Button-2>} +test bind-19.15 {DeleteVirtualEvent procedure: owned by many, first} { + setup + pack [frame .b.g -class Test -width 150 -height 100] + pack [frame .b.h -class Test -width 150 -height 100] + update + event add <<xyz>> <Button-2> + event add <<abc>> <Button-2> + event add <<def>> <Button-2> + bind .b.f <<xyz>> {lappend x xyz} + bind .b.g <<abc>> {lappend x abc} + bind .b.h <<def>> {lappend x def} + set x {} + event gen .b.f <Button-2> + event gen .b.g <Button-2> + event gen .b.h <Button-2> + event delete <<xyz>> + event gen .b.f <Button-2> + event gen .b.g <Button-2> + event gen .b.h <Button-2> + destroy .b.g + destroy .b.h + list $x [event info <<xyz>>] [event info <<abc>>] [event info <<def>>] +} {{xyz abc def abc def} {} <Button-2> <Button-2>} +test bind-19.16 {DeleteVirtualEvent procedure: owned by many, middle} { + setup + pack [frame .b.g -class Test -width 150 -height 100] + pack [frame .b.h -class Test -width 150 -height 100] + update + event add <<xyz>> <Button-2> + event add <<abc>> <Button-2> + event add <<def>> <Button-2> + bind .b.f <<xyz>> {lappend x xyz} + bind .b.g <<abc>> {lappend x abc} + bind .b.h <<def>> {lappend x def} + set x {} + event gen .b.f <Button-2> + event gen .b.g <Button-2> + event gen .b.h <Button-2> + event delete <<abc>> + event gen .b.f <Button-2> + event gen .b.g <Button-2> + event gen .b.h <Button-2> + destroy .b.g + destroy .b.h + list $x [event info <<xyz>>] [event info <<abc>>] [event info <<def>>] +} {{xyz abc def xyz def} <Button-2> {} <Button-2>} +test bind-19.17 {DeleteVirtualEvent procedure: owned by many, last} { + setup + pack [frame .b.g -class Test -width 150 -height 100] + pack [frame .b.h -class Test -width 150 -height 100] + update + event add <<xyz>> <Button-2> + event add <<abc>> <Button-2> + event add <<def>> <Button-2> + bind .b.f <<xyz>> {lappend x xyz} + bind .b.g <<abc>> {lappend x abc} + bind .b.h <<def>> {lappend x def} + set x {} + event gen .b.f <Button-2> + event gen .b.g <Button-2> + event gen .b.h <Button-2> + event delete <<def>> + event gen .b.f <Button-2> + event gen .b.g <Button-2> + event gen .b.h <Button-2> + destroy .b.g + destroy .b.h + list $x [event info <<xyz>>] [event info <<abc>>] [event info <<def>>] +} {{xyz abc def xyz abc} <Button-2> <Button-2> {}} + + +test bind-20.1 {GetVirtualEvent procedure: GetVirtualEventUid} { + list [catch {event info asd} msg] $msg +} {1 {virtual event "asd" is badly formed}} +test bind-20.2 {GetVirtualEvent procedure: non-existent event} { + event info <<asd>> +} {} +test bind-20.3 {GetVirtualEvent procedure: owns 1} { + setup + event add <<xyz>> <Control-Key-v> + event info <<xyz>> +} {<Control-Key-v>} +test bind-20.4 {GetVirtualEvent procedure: owns many} { + setup + event add <<xyz>> <Control-v> <Button-2> spack + event info <<xyz>> +} {<Control-Key-v> <Button-2> spack} + + +test bind-21.1 {GetAllVirtualEvents procedure: no events} { + setup + event info +} {} +test bind-21.2 {GetAllVirtualEvents procedure: 1 event} { + setup + event add <<xyz>> <Control-v> + event info +} {<<xyz>>} +test bind-21.3 {GetAllVirtualEvents procedure: many events} { + setup + event add <<xyz>> <Control-v> + event add <<xyz>> <Button-2> + event add <<abc>> <Control-v> + event add <<def>> <Key-F6> + lsort [event info] +} {<<abc>> <<def>> <<xyz>>} + +test bind-22.1 {HandleEventGenerate} { + list [catch {event gen .xyz <Control-v>} msg] $msg +} {1 {bad window path name ".xyz"}} +test bind-22.2 {HandleEventGenerate} { + list [catch {event gen zzz <Control-v>} msg] $msg +} {1 {bad window name/identifier "zzz"}} +test bind-22.3 {HandleEventGenerate} { + list [catch {event gen 47 <Control-v>} msg] $msg +} {1 {window id "47" doesn't exist in this application}} +test bind-22.4 {HandleEventGenerate} { + setup + bind .b.f <Button> {set x "%s %b"} + set x {} + event gen [winfo id .b.f] <Control-Button-1> + set x +} {4 1} +test bind-22.5 {HandleEventGenerate} { + list [catch {event gen . <xyz>} msg] $msg +} {1 {bad event type or keysym "xyz"}} +test bind-22.6 {HandleEventGenerate} { + list [catch {event gen . <Double-Button-1>} msg] $msg +} {1 {Double or Triple modifier not allowed}} +test bind-22.7 {HandleEventGenerate} { + list [catch {event gen . xyz} msg] $msg +} {1 {only one event specification allowed}} +test bind-22.8 {HandleEventGenerate} { + list [catch {event gen . <Button> -button} msg] $msg +} {1 {value for "-button" missing}} +test bind-22.9 {HandleEventGenerate} { + setup + bind .b.f <Button> {set x "%s %b"} + set x {} + event gen .b.f <Control-Button-1> + set x +} {4 1} +test bind-22.10 {HandleEventGenerate} { + setup + bind .b.f <Key> {set x "%s %K"} + set x {} + event gen .b.f <Control-Key-1> + set x +} {4 1} +test bind-22.11 {HandleEventGenerate} { + setup + bind .b.f <<Paste>> {set x "%s"} + set x {} + event gen .b.f <<Paste>> -state 1 + set x +} {1} +test bind-22.12 {HandleEventGenerate} { + setup + bind .b.f <Motion> {set x "%s"} + set x {} + event gen .b.f <Control-Motion> + set x +} {4} +test bind-22.13 {HandleEventGenerate} { + setup + bind .b.f <Button> {lappend x %#} + set x {} + event gen .b.f <Button> -when now -serial 100 + set x +} {100} +test bind-22.14 {HandleEventGenerate} { + setup + bind .b.f <Button> {lappend x %#} + set x {} + event gen .b.f <Button> -when head -serial 100 + event gen .b.f <Button> -when head -serial 101 + event gen .b.f <Button> -when head -serial 102 + lappend x foo + update + set x +} {foo 102 101 100} +test bind-22.15 {HandleEventGenerate} { + setup + bind .b.f <Button> {lappend x %#} + set x {} + event gen .b.f <Button> -when head -serial 99 + event gen .b.f <Button> -when mark -serial 100 + event gen .b.f <Button> -when mark -serial 101 + event gen .b.f <Button> -when mark -serial 102 + lappend x foo + update + set x +} {foo 100 101 102 99} +test bind-22.16 {HandleEventGenerate} { + setup + bind .b.f <Button> {lappend x %#} + set x {} + event gen .b.f <Button> -when head -serial 99 + event gen .b.f <Button> -when tail -serial 100 + event gen .b.f <Button> -when tail -serial 101 + event gen .b.f <Button> -when tail -serial 102 + lappend x foo + update + set x +} {foo 99 100 101 102} +test bind-22.17 {HandleEventGenerate} { + list [catch {event gen . <Button> -when xyz} msg] $msg +} {1 {bad position "xyz": should be now, head, mark, tail}} +set i 14 +foreach check { + {<Configure> %a {-above .xyz} {{1 {bad window path name ".xyz"}}}} + {<Configure> %a {-above .b} {[winfo id .b]}} + {<Configure> %a {-above xyz} {{1 {expected integer but got "xyz"}}}} + {<Configure> %a {-above [winfo id .b]} {[winfo id .b]}} + {<Key> %b {-above .} {{1 {bad option to <Key> event: "-above"}}}} + + {<Configure> %B {-borderwidth xyz} {{1 {bad screen distance "xyz"}}}} + {<Configure> %B {-borderwidth 2i} {[winfo pixels .b.f 2i]}} + {<Key> %k {-borderwidth 2i} {{1 {bad option to <Key> event: "-borderwidth"}}}} + + {<Button> %b {-button xyz} {{1 {expected integer but got "xyz"}}}} + {<Button> %b {-button 1} 1} + {<Key> %k {-button 1} {{1 {bad option to <Key> event: "-button"}}}} + + {<Expose> %c {-count xyz} {{1 {expected integer but got "xyz"}}}} + {<Expose> %c {-count 20} 20} + {<Key> %b {-count 20} {{1 {bad option to <Key> event: "-count"}}}} + + {<Enter> %d {-detail xyz} {{1 {bad -detail value "xyz": must be NotifyAncestor, NotifyVirtual, NotifyInferior, NotifyNonlinear, NotifyNonlinearVirtual, NotifyPointer, NotifyPointerRoot, NotifyDetailNone}}}} + {<FocusIn> %d {-detail NotifyVirtual} {{}}} + {<Enter> %d {-detail NotifyVirtual} NotifyVirtual} + {<Key> %k {-detail NotifyVirtual} {{1 {bad option to <Key> event: "-detail"}}}} + + {<Enter> %f {-focus xyz} {{1 {expected boolean value but got "xyz"}}}} + {<Enter> %f {-focus 1} 1} + {<Key> %k {-focus 1} {{1 {bad option to <Key> event: "-focus"}}}} + + {<Expose> %h {-height xyz} {{1 {bad screen distance "xyz"}}}} + {<Expose> %h {-height 2i} {[winfo pixels .b.f 2i]}} + {<Configure> %h {-height 2i} {[winfo pixels .b.f 2i]}} + {<Key> %k {-height 2i} {{1 {bad option to <Key> event: "-height"}}}} + + {<Key> %k {-keycode xyz} {{1 {expected integer but got "xyz"}}}} + {<Key> %k {-keycode 20} 20} + {<Button> %b {-keycode 20} {{1 {bad option to <Button> event: "-keycode"}}}} + + {<Key> %K {-keysym xyz} {{1 {unknown keysym "xyz"}}}} + {<Key> %K {-keysym a} a} + {<Button> %b {-keysym a} {{1 {bad option to <Button> event: "-keysym"}}}} + + {<Enter> %m {-mode xyz} {{1 {bad -mode value "xyz": must be NotifyNormal, NotifyGrab, NotifyUngrab, NotifyWhileGrabbed}}}} + {<Enter> %m {-mode NotifyNormal} NotifyNormal} + {<FocusIn> %m {-mode NotifyNormal} {{}}} + {<Key> %k {-mode NotifyNormal} {{1 {bad option to <Key> event: "-mode"}}}} + + {<Map> %o {-override xyz} {{1 {expected boolean value but got "xyz"}}}} + {<Map> %o {-override 1} 1} + {<Reparent> %o {-override 1} 1} + {<Configure> %o {-override 1} 1} + {<Key> %k {-override 1} {{1 {bad option to <Key> event: "-override"}}}} + + {<Circulate> %p {-place xyz} {{1 {bad -place value "xyz": must be PlaceOnTop, PlaceOnBottom}}}} + {<Circulate> %p {-place PlaceOnTop} PlaceOnTop} + {<Key> %k {-place PlaceOnTop} {{1 {bad option to <Key> event: "-place"}}}} + + {<Key> %R {-root .xyz} {{1 {bad window path name ".xyz"}}}} + {<Key> %R {-root .b} {[winfo id .b]}} + {<Key> %R {-root xyz} {{1 {expected integer but got "xyz"}}}} + {<Key> %R {-root [winfo id .b]} {[winfo id .b]}} + {<Button> %R {-root .b} {[winfo id .b]}} + {<Motion> %R {-root .b} {[winfo id .b]}} + {<<Paste>> %R {-root .b} {[winfo id .b]}} + {<Enter> %R {-root .b} {[winfo id .b]}} + {<Configure> %R {-root .b} {{1 {bad option to <Configure> event: "-root"}}}} + + {<Key> %X {-rootx xyz} {{1 {bad screen distance "xyz"}}}} + {<Key> %X {-rootx 2i} {[winfo pixels .b.f 2i]}} + {<Button> %X {-rootx 2i} {[winfo pixels .b.f 2i]}} + {<Motion> %X {-rootx 2i} {[winfo pixels .b.f 2i]}} + {<<Paste>> %X {-rootx 2i} {[winfo pixels .b.f 2i]}} + {<Enter> %X {-rootx 2i} {[winfo pixels .b.f 2i]}} + {<Configure> %X {-rootx 2i} {{1 {bad option to <Configure> event: "-rootx"}}}} + + {<Key> %Y {-rooty xyz} {{1 {bad screen distance "xyz"}}}} + {<Key> %Y {-rooty 2i} {[winfo pixels .b.f 2i]}} + {<Button> %Y {-rooty 2i} {[winfo pixels .b.f 2i]}} + {<Motion> %Y {-rooty 2i} {[winfo pixels .b.f 2i]}} + {<<Paste>> %Y {-rooty 2i} {[winfo pixels .b.f 2i]}} + {<Enter> %Y {-rooty 2i} {[winfo pixels .b.f 2i]}} + {<Configure> %Y {-rooty 2i} {{1 {bad option to <Configure> event: "-rooty"}}}} + + {<Key> %E {-sendevent xyz} {{1 {expected boolean value but got "xyz"}}}} + {<Key> %E {-sendevent 1} 1} + {<Key> %E {-sendevent yes} 1} + {<Key> %E {-sendevent 43} 43} + + {<Key> %# {-serial xyz} {{1 {expected integer but got "xyz"}}}} + {<Key> %# {-serial 100} 100} + + {<Key> %s {-state xyz} {{1 {expected integer but got "xyz"}}}} + {<Key> %s {-state 1} 1} + {<Button> %s {-state 1} 1} + {<Motion> %s {-state 1} 1} + {<<Paste>> %s {-state 1} 1} + {<Enter> %s {-state 1} 1} + {<Visibility> %s {-state xyz} {{1 {bad -state value "xyz": must be VisibilityUnobscured, VisibilityPartiallyObscured, VisibilityFullyObscured}}}} + {<Visibility> %s {-state VisibilityUnobscured} VisibilityUnobscured} + {<Configure> %s {-state xyz} {{1 {bad option to <Configure> event: "-state"}}}} + + {<Key> %S {-subwindow .xyz} {{1 {bad window path name ".xyz"}}}} + {<Key> %S {-subwindow .b} {[winfo id .b]}} + {<Key> %S {-subwindow xyz} {{1 {expected integer but got "xyz"}}}} + {<Key> %S {-subwindow [winfo id .b]} {[winfo id .b]}} + {<Button> %S {-subwindow .b} {[winfo id .b]}} + {<Motion> %S {-subwindow .b} {[winfo id .b]}} + {<<Paste>> %S {-subwindow .b} {[winfo id .b]}} + {<Enter> %S {-subwindow .b} {[winfo id .b]}} + {<Configure> %S {-subwindow .b} {{1 {bad option to <Configure> event: "-subwindow"}}}} + + {<Key> %t {-time xyz} {{1 {expected integer but got "xyz"}}}} + {<Key> %t {-time 100} 100} + {<Button> %t {-time 100} 100} + {<Motion> %t {-time 100} 100} + {<<Paste>> %t {-time 100} 100} + {<Enter> %t {-time 100} 100} + {<Property> %t {-time 100} 100} + {<Configure> %t {-time 100} {{1 {bad option to <Configure> event: "-time"}}}} + + {<Expose> %w {-width xyz} {{1 {bad screen distance "xyz"}}}} + {<Expose> %w {-width 2i} {[winfo pixels .b.f 2i]}} + {<Configure> %w {-width 2i} {[winfo pixels .b.f 2i]}} + {<Key> %k {-width 2i} {{1 {bad option to <Key> event: "-width"}}}} + + {<Unmap> %W {-window .xyz} {{1 {bad window path name ".xyz"}}}} + {<Unmap> %W {-window .b.f} .b.f} + {<Unmap> %W {-window xyz} {{1 {expected integer but got "xyz"}}}} + {<Unmap> %W {-window [winfo id .b.f]} .b.f} + {<Unmap> %W {-window .b.f} .b.f} + {<Map> %W {-window .b.f} .b.f} + {<Reparent> %W {-window .b.f} .b.f} + {<Configure> %W {-window .b.f} .b.f} + {<Gravity> %W {-window .b.f} .b.f} + {<Circulate> %W {-window .b.f} .b.f} + {<Key> %W {-window .b.f} {{1 {bad option to <Key> event: "-window"}}}} + + {<Key> %x {-x xyz} {{1 {bad screen distance "xyz"}}}} + {<Key> %x {-x 2i} {[winfo pixels .b.f 2i]}} + {<Button> %x {-x 2i} {[winfo pixels .b.f 2i]}} + {<Motion> %x {-x 2i} {[winfo pixels .b.f 2i]}} + {<<Paste>> %x {-x 2i} {[winfo pixels .b.f 2i]}} + {<Enter> %x {-x 2i} {[winfo pixels .b.f 2i]}} + {<Expose> %x {-x 2i} {[winfo pixels .b.f 2i]}} + {<Configure> %x {-x 2i} {[winfo pixels .b.f 2i]}} + {<Gravity> %x {-x 2i} {[winfo pixels .b.f 2i]}} + {<Reparent> %x {-x 2i} {[winfo pixels .b.f 2i]}} + {<Map> %x {-x 2i} {{1 {bad option to <Map> event: "-x"}}}} + + {<Key> %y {-y xyz} {{1 {bad screen distance "xyz"}}}} + {<Key> %y {-y 2i} {[winfo pixels .b.f 2i]}} + {<Button> %y {-y 2i} {[winfo pixels .b.f 2i]}} + {<Motion> %y {-y 2i} {[winfo pixels .b.f 2i]}} + {<<Paste>> %y {-y 2i} {[winfo pixels .b.f 2i]}} + {<Enter> %y {-y 2i} {[winfo pixels .b.f 2i]}} + {<Expose> %y {-y 2i} {[winfo pixels .b.f 2i]}} + {<Configure> %y {-y 2i} {[winfo pixels .b.f 2i]}} + {<Gravity> %y {-y 2i} {[winfo pixels .b.f 2i]}} + {<Reparent> %y {-y 2i} {[winfo pixels .b.f 2i]}} + {<Map> %y {-y 2i} {{1 {bad option to <Map> event: "-y"}}}} + + {<Key> %k {-xyz 1} {{1 {bad option to <Key> event: "-xyz"}}}} +} { + set event [lindex $check 0] + test bind-22.$i "HandleEventGenerate: options $event [lindex $check 2]" { + setup + bind .b.f $event "lappend x [lindex $check 1]" + set x {} + if [catch {eval event gen .b.f $event [lindex $check 2]} msg] { + set x [list 1 $msg] + } + set x + } [eval set x [lindex $check 3]] + incr i +} +test bind-23.1 {GetVirtualEventUid procedure} { + list [catch {event info <<asd} msg] $msg +} {1 {virtual event "<<asd" is badly formed}} +test bind-23.2 {GetVirtualEventUid procedure} { + list [catch {event info <<>>} msg] $msg +} {1 {virtual event "<<>>" is badly formed}} +test bind-23.3 {GetVirtualEventUid procedure} { + list [catch {event info <<asd>} msg] $msg +} {1 {virtual event "<<asd>" is badly formed}} +test bind-23.4 {GetVirtualEventUid procedure} { + event info <<asd>> +} {} + + +test bind-24.1 {FindSequence procedure: no event} { + list [catch {bind .b {} test} msg] $msg +} {1 {no events specified in binding}} +test bind-24.2 {FindSequence procedure: bad event} { + list [catch {bind .b <xyz> test} msg] $msg +} {1 {bad event type or keysym "xyz"}} +test bind-24.3 {FindSequence procedure: virtual allowed} { + bind .b.f <<Paste>> test +} {} +test bind-24.4 {FindSequence procedure: virtual not allowed} { + list [catch {event add <<Paste>> <<Alive>>} msg] $msg +} {1 {virtual event not allowed in definition of another virtual event}} +test bind-24.5 {FindSequence procedure, multiple bindings} { + setup + bind .b.f <1> {lappend x single} + bind .b.f <Double-1> {lappend x double} + bind .b.f <Triple-1> {lappend x triple} + set x press + event gen .b.f <Button-1> + lappend x press + event gen .b.f <Button-1> + lappend x press + event gen .b.f <Button-1> + lappend x press + event gen .b.f <Button-1> + set x +} {press single press double press triple press triple} +test bind-24.6 {FindSequence procedure: virtual composed} { + list [catch {bind .b <Control-b><<Paste>> "puts hi"} msg] $msg +} {1 {virtual events may not be composed}} +test bind-24.7 {FindSequence procedure: new pattern sequence} { + setup + bind .b.f <Button-1><Button-2> {lappend x 1-2} + set x {} + event gen .b.f <Button-1> + event gen .b.f <Button-2> + set x +} {1-2} +test bind-24.8 {FindSequence procedure: similar pattern sequence} { + setup + bind .b.f <Button-1><Button-2> {lappend x 1-2} + bind .b.f <Button-2> {lappend x 2} + set x {} + event gen .b.f <Button-3> + event gen .b.f <Button-2> + event gen .b.f <Button-1> + event gen .b.f <Button-2> + set x +} {2 1-2} +test bind-24.9 {FindSequence procedure: similar pattern sequence} { + setup + bind .b.f <Button-1><Button-2> {lappend x 1-2} + bind .b.f <Button-2><Button-2> {lappend x 2-2} + set x {} + event gen .b.f <Button-3> + event gen .b.f <Button-2> + event gen .b.f <Button-2> + event gen .b.f <Button-1> + event gen .b.f <Button-2> + set x +} {2-2 1-2} +test bind-24.10 {FindSequence procedure: similar pattern sequence} { + setup + bind .b.f <Button-2><Button-2> {lappend x 2-2} + bind .b.f <Double-Button-2> {lappend x d-2} + set x {} + event gen .b.f <Button-3> + event gen .b.f <Button-2> + event gen .b.f <Button-2> + event gen .b.f <Button-1> + event gen .b.f <Button-2> -x 100 + event gen .b.f <Button-2> -x 200 + set x +} {d-2 2-2} +test bind-24.11 {FindSequence procedure: new sequence, don't create} { + setup + bind .b.f <Button-2> +} {} +test bind-24.12 {FindSequence procedure: not new sequence, don't create} { + setup + bind .b.f <Control-Button-2> "foo" + bind .b.f <Button-2> +} {} + + +test bind-25.1 {ParseEventDescription procedure} { + list [catch {bind .b \x7 test} msg] $msg +} {1 {bad ASCII character 0x7}} +test bind-25.2 {ParseEventDescription procedure} { + list [catch {bind .b "\x7f" test} msg] $msg +} {1 {bad ASCII character 0x7f}} +test bind-25.3 {ParseEventDescription procedure} { + list [catch {bind .b "\x4" test} msg] $msg +} {1 {bad ASCII character 0x4}} +test bind-25.4 {ParseEventDescription procedure} { + setup + bind .b.f a test + bind .b.f a +} {test} +test bind-25.5 {ParseEventDescription procedure: virtual} { + list [catch {bind .b <<>> foo} msg] $msg +} {1 {virtual event "<<>>" is badly formed}} +test bind-25.6 {ParseEventDescription procedure: virtual} { + list [catch {bind .b <<Paste foo} msg] $msg +} {1 {missing ">" in virtual binding}} +test bind-25.7 {ParseEventDescription procedure: virtual} { + list [catch {bind .b <<Paste> foo} msg] $msg +} {1 {missing ">" in virtual binding}} +test bind-25.8 {ParseEventDescription procedure: correctly terminate virtual} { + list [catch {bind .b <<Paste>>h foo} msg] $msg +} {1 {virtual events may not be composed}} +test bind-25.9 {ParseEventDescription procedure} { + list [catch {bind .b <> test} msg] $msg +} {1 {no event type or button # or keysym}} +test bind-25.10 {ParseEventDescription procedure: misinterpreted modifier} { + button .x + bind .x <Control-M> a + bind .x <M-M> b + set x [lsort [bind .x]] + destroy .x + set x +} {<Control-Key-M> <Meta-Key-M>} +test bind-25.11 {ParseEventDescription procedure} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + bind .b.f <a---> {nothing} + bind .b.f +} a +test bind-25.12 {ParseEventDescription procedure} { + list [catch {bind .b <a-- test} msg] $msg +} {1 {missing ">" in binding}} +test bind-25.13 {ParseEventDescription procedure} { + list [catch {bind .b <a-b> test} msg] $msg +} {1 {extra characters after detail in binding}} +test bind-25.14 {ParseEventDescription} { + setup + list [catch {bind .b <<abc {puts hi}} msg] $msg +} {1 {missing ">" in virtual binding}} +test bind-25.15 {ParseEventDescription} { + setup + list [catch {bind .b <<abc> {puts hi}} msg] $msg +} {1 {missing ">" in virtual binding}} +test bind-25.16 {ParseEventDescription} { + setup + bind .b <<Shift-Paste>> {puts hi} + bind .b +} {<<Shift-Paste>>} +test bind-25.17 {ParseEventDescription} { + setup + list [catch {event add <<xyz>> <<abc>>} msg] $msg +} {1 {virtual event not allowed in definition of another virtual event}} +set i 1 +foreach check { + {{<Control- a>} <Control-Key-a>} + {<Shift-a> <Shift-Key-a>} + {<Lock-a> <Lock-Key-a>} + {<Meta---a> <Meta-Key-a>} + {<M-a> <Meta-Key-a>} + {<Alt-a> <Alt-Key-a>} + {<B1-a> <B1-Key-a>} + {<B2-a> <B2-Key-a>} + {<B3-a> <B3-Key-a>} + {<B4-a> <B4-Key-a>} + {<B5-a> <B5-Key-a>} + {<Button1-a> <B1-Key-a>} + {<Button2-a> <B2-Key-a>} + {<Button3-a> <B3-Key-a>} + {<Button4-a> <B4-Key-a>} + {<Button5-a> <B5-Key-a>} + {<M1-a> <Mod1-Key-a>} + {<M2-a> <Mod2-Key-a>} + {<M3-a> <Mod3-Key-a>} + {<M4-a> <Mod4-Key-a>} + {<M5-a> <Mod5-Key-a>} + {<Mod1-a> <Mod1-Key-a>} + {<Mod2-a> <Mod2-Key-a>} + {<Mod3-a> <Mod3-Key-a>} + {<Mod4-a> <Mod4-Key-a>} + {<Mod5-a> <Mod5-Key-a>} + {<Double-a> <Double-Key-a>} + {<Triple-a> <Triple-Key-a>} + {{<Double 1>} <Double-Button-1>} + {<Triple-1> <Triple-Button-1>} + {{<M1-M2 M3-M4 B1-Control-a>} <Control-B1-Mod1-Mod2-Mod3-Mod4-Key-a>} +} { + test bind-25.$i {modifier names} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + bind .b.f [lindex $check 0] foo + bind .b.f + } [lindex $check 1] + bind .b.f [lindex $check 1] {} + incr i +} + +foreach event [bind Test] { + bind Test $event {} +} +foreach event [bind all] { + bind all $event {} +} +test bind-26.1 {event names} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + bind .b.f <FocusIn> {nothing} + bind .b.f +} <FocusIn> +test bind-26.2 {event names} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + bind .b.f <FocusOut> {nothing} + bind .b.f +} <FocusOut> +test bind-26.3 {event names} { + setup + bind .b.f <Destroy> {lappend x "destroyed"} + set x [bind .b.f] + destroy .b.f + set x +} {<Destroy> destroyed} +set i 4 +foreach check { + {Motion Motion} + {Button Button} + {ButtonPress Button} + {ButtonRelease ButtonRelease} + {Colormap Colormap} + {Enter Enter} + {Leave Leave} + {Expose Expose} + {Key Key} + {KeyPress Key} + {KeyRelease KeyRelease} + {Property Property} + {Visibility Visibility} + {Activate Activate} + {Deactivate Deactivate} +} { + set event [lindex $check 0] + test bind-26.$i {event names} { + setup + bind .b.f <$event> "set x {event $event}" + set x xyzzy + event gen .b.f <$event> + list $x [bind .b.f] + } [list "event $event" <[lindex $check 1]>] + incr i +} +foreach check { + {Circulate Circulate} + {Configure Configure} + {Gravity Gravity} + {Map Map} + {Reparent Reparent} + {Unmap Unmap} +} { + set event [lindex $check 0] + test bind-26.$i {event names} { + setup + bind .b.f <$event> "set x {event $event}" + set x xyzzy + event gen .b.f <$event> -window .b.f + list $x [bind .b.f] + } [list "event $event" <[lindex $check 1]>] + incr i +} + + +test bind-27.1 {button names} { + list [catch {bind .b <Expose-1> foo} msg] $msg +} {1 {specified button "1" for non-button event}} +test bind-27.2 {button names} { + list [catch {bind .b <Button-6> foo} msg] $msg +} {1 {specified keysym "6" for non-key event}} +set i 3 +foreach button {1 2 3 4 5} { + test bind-27.$i {button names} { + setup + bind .b.f <Button-$button> "lappend x \"button $button\"" + set x [bind .b.f] + event gen .b.f <Button-$button> + set x + } [list <Button-$button> "button $button"] + incr i +} + +test bind-28.1 {keysym names} { + list [catch {bind .b <Expose-a> foo} msg] $msg +} {1 {specified keysym "a" for non-key event}} +test bind-28.2 {keysym names} { + list [catch {bind .b <Gorp> foo} msg] $msg +} {1 {bad event type or keysym "Gorp"}} +test bind-28.3 {keysym names} { + list [catch {bind .b <Key-Stupid> foo} msg] $msg +} {1 {bad event type or keysym "Stupid"}} +test bind-28.4 {keysym names} { + catch {destroy .b.f} + frame .b.f -class Test -width 150 -height 100 + bind .b.f <a> foo + bind .b.f +} a +set i 5 +foreach check { + {a 0 a} + {space 0 <Key-space>} + {Return 0 <Key-Return>} + {X 1 X} +} { + set keysym [lindex $check 0] + test bind-28.$i {keysym names} { + setup + bind .b.f <Key-$keysym> "lappend x \"keysym $keysym\"" + bind .b.f <Key-x> "lappend x {bad binding match}" + set x [lsort [bind .b.f]] + event gen .b.f <Key-$keysym> -state [lindex $check 1] + set x + } [concat [lsort "x [lindex $check 2]"] "{keysym $keysym}"] + incr i +} + +test bind-29.1 {dummy test to help ensure proper numbering} {} {} +setup +bind .b.f <KeyPress> {set x %K} +set i 2 +foreach check { + {a 0 a} + {x 1 X} + {x 2 X} + {space 0 space} + {F1 1 F1} +} { + test bind-29.$i {GetKeySym procedure} {nonPortable} { + set x nothing + event gen .b.f <KeyPress> -keysym [lindex $check 0] \ + -state [lindex $check 1] + set x + } [lindex $check 2] + incr i +} + + +proc bgerror msg { + global x errorInfo + set x [list $msg $errorInfo] +} +test bind-30.1 {Tk_BackgroundError procedure} { + setup + bind .b.f <Button> {error "This is a test"} + set x none + event gen .b.f <Button> + update + set x +} {{This is a test} {This is a test + while executing +"error "This is a test"" + (command bound to event)}} +test bind-30.2 {Tk_BackgroundError procedure} { + proc do {} { + event gen .b.f <Button> + } + setup + bind .b.f <Button> {error Message2} + set x none + do + update + set x +} {Message2 {Message2 + while executing +"error Message2" + (command bound to event)}} +rename bgerror {} + + +destroy .b diff --git a/tests/bugs.tcl b/tests/bugs.tcl new file mode 100644 index 0000000..1f4e5b7 --- /dev/null +++ b/tests/bugs.tcl @@ -0,0 +1,30 @@ +# This file is a Tcl script to test out various known bugs that will +# cause Tk to crash. This file ends with .tcl instead of .test to make +# sure it isn't run when you type "source all". We currently are not +# shipping this file with the rest of the source release. +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) bugs.tcl 1.1 96/07/25 15:49:45 + +if {[info procs test] != "test"} { + source defs +} + +test crash-1.0 {imgPhoto} { + image create photo p1 + image create photo p2 + catch {image create photo p2 -file bogus} + p1 copy p2 + label .l -image p1 + destroy .l + set foo "" +} {} + +test crash-1.1 {color} { + . configure -bg rgb:345 + set foo "" +} {} diff --git a/tests/butGeom.tcl b/tests/butGeom.tcl new file mode 100644 index 0000000..352712b --- /dev/null +++ b/tests/butGeom.tcl @@ -0,0 +1,115 @@ +# This file creates a visual test for button layout. It is part of +# the Tk visual test suite, which is invoked via the "visual" script. +# +# SCCS: @(#) butGeom.tcl 1.3 97/06/13 13:46:57 + +catch {destroy .t} +toplevel .t +wm title .t "Visual Tests for Button Geometry" +wm iconname .t "Button Geometry" +wm geom .t +0+0 +wm minsize .t 1 1 + +label .t.l -text {This screen exercises the layout mechanisms for various flavors of buttons. Select display options below, and they will be applied to all of the button widgets. In order to see the effects of different anchor positions, expand the window so that there is extra space in the buttons. The letter "o" in "automatically" should be underlined in the right column of widgets.} -wraplength 5i +pack .t.l -side top -fill both + +button .t.quit -text Quit -command {destroy .t} +pack .t.quit -side bottom -pady 2m + +set sepId 1 +proc sep {} { + global sepId + frame .t.sep$sepId -height 2 -bd 1 -relief sunken + pack .t.sep$sepId -side top -padx 2m -pady 2m -fill x + incr sepId +} + +# Create buttons that control configuration options. + +frame .t.control +pack .t.control -side top -fill x -pady 3m +frame .t.control.left +frame .t.control.right +pack .t.control.left .t.control.right -side left -expand 1 -fill x +label .t.anchorLabel -text "Anchor:" +frame .t.control.left.f -width 6c -height 3c +pack .t.anchorLabel .t.control.left.f -in .t.control.left -side top +foreach anchor {nw n ne w center e sw s se} { + button .t.anchor-$anchor -text $anchor -command "config -anchor $anchor" +} +place .t.anchor-nw -in .t.control.left.f -relx 0 -relwidth 0.333 \ + -rely 0 -relheight 0.333 +place .t.anchor-n -in .t.control.left.f -relx 0.333 -relwidth 0.333 \ + -rely 0 -relheight 0.333 +place .t.anchor-ne -in .t.control.left.f -relx 0.666 -relwidth 0.333 \ + -rely 0 -relheight 0.333 +place .t.anchor-w -in .t.control.left.f -relx 0 -relwidth 0.333 \ + -rely 0.333 -relheight 0.333 +place .t.anchor-center -in .t.control.left.f -relx 0.333 -relwidth 0.333 \ + -rely 0.333 -relheight 0.333 +place .t.anchor-e -in .t.control.left.f -relx 0.666 -relwidth 0.333 \ + -rely 0.333 -relheight 0.333 +place .t.anchor-sw -in .t.control.left.f -relx 0 -relwidth 0.333 \ + -rely 0.666 -relheight 0.333 +place .t.anchor-s -in .t.control.left.f -relx 0.333 -relwidth 0.333 \ + -rely 0.666 -relheight 0.333 +place .t.anchor-se -in .t.control.left.f -relx 0.666 -relwidth 0.333 \ + -rely 0.666 -relheight 0.333 + +set justify center +radiobutton .t.justify-left -text "Justify Left" -relief flat \ + -command "config -justify left" -variable justify \ + -value left +radiobutton .t.justify-center -text "Justify Center" -relief flat \ + -command "config -justify center" -variable justify \ + -value center +radiobutton .t.justify-right -text "Justify Right" -relief flat \ + -command "config -justify right" -variable justify \ + -value right +pack .t.justify-left .t.justify-center .t.justify-right \ + -in .t.control.right -anchor w + +sep +frame .t.f1 +pack .t.f1 -side top -expand 1 -fill both +sep +frame .t.f2 +pack .t.f2 -side top -expand 1 -fill both +sep +frame .t.f3 +pack .t.f3 -side top -expand 1 -fill both +sep +frame .t.f4 +pack .t.f4 -side top -expand 1 -fill both +sep + +label .t.l1 -text Label -bd 2 -relief sunken +label .t.l2 -text "Explicit\nnewlines\n\nin the text" -bd 2 -relief sunken +label .t.l3 -text "This text is quite long, so it must be wrapped automatically by Tk" -wraplength 2i -bd 2 -relief sunken -underline 50 +pack .t.l1 .t.l2 .t.l3 -in .t.f1 -side left -padx 5m -pady 3m \ + -expand y -fill both + +button .t.b1 -text Button +button .t.b2 -text "Explicit\nnewlines\n\nin the text" +button .t.b3 -text "This text is quite long, so it must be wrapped automatically by Tk" -wraplength 2i -underline 50 +pack .t.b1 .t.b2 .t.b3 -in .t.f2 -side left -padx 5m -pady 3m \ + -expand y -fill both + +checkbutton .t.c1 -text Checkbutton -variable a +checkbutton .t.c2 -text "Explicit\nnewlines\n\nin the text" -variable b +checkbutton .t.c3 -text "This text is quite long, so it must be wrapped automatically by Tk" -wraplength 2i -variable c -underline 50 +pack .t.c1 .t.c2 .t.c3 -in .t.f3 -side left -padx 5m -pady 3m \ + -expand y -fill both + +radiobutton .t.r1 -text Radiobutton -value a +radiobutton .t.r2 -text "Explicit\nnewlines\n\nin the text" -value b +radiobutton .t.r3 -text "This text is quite long, so it must be wrapped automatically by Tk" -wraplength 2i -value c -underline 50 +pack .t.r1 .t.r2 .t.r3 -in .t.f4 -side left -padx 5m -pady 3m \ + -expand y -fill both + +proc config {option value} { + foreach w {.t.l1 .t.l2 .t.l3 .t.b1 .t.b2 .t.b3 .t.c1 .t.c2 .t.c3 + .t.r1 .t.r2 .t.r3} { + $w configure $option $value + } +} diff --git a/tests/butGeom2.tcl b/tests/butGeom2.tcl new file mode 100644 index 0000000..f1293a0 --- /dev/null +++ b/tests/butGeom2.tcl @@ -0,0 +1,113 @@ +# This file creates a visual test for button layout. It is part of +# the Tk visual test suite, which is invoked via the "visual" script. +# +# SCCS: @(#) butGeom2.tcl 1.3 97/06/13 17:00:32 + +catch {destroy .t} +toplevel .t +wm title .t "Visual Tests for Button Geometry" +wm iconname .t "Button Geometry" +wm geom .t +0+0 +wm minsize .t 1 1 + +label .t.l -text {This screen exercises the color options for various flavors of buttons. Select display options below, and they will be applied to the appropiate button widgets.} -wraplength 5i +pack .t.l -side top -fill both + +button .t.quit -text Quit -command {destroy .t} +pack .t.quit -side bottom -pady 2m + +set sepId 1 +proc sep {} { + global sepId + frame .t.sep$sepId -height 2 -bd 1 -relief sunken + pack .t.sep$sepId -side top -padx 2m -pady 2m -fill x + incr sepId +} + +# Create buttons that control configuration options. + +frame .t.control +pack .t.control -side top -fill x -pady 3m +frame .t.control.left +frame .t.control.right +pack .t.control.left .t.control.right -side left -expand 1 -fill x +label .t.anchorLabel -text "Color:" +frame .t.control.left.f -width 6c -height 3c +pack .t.anchorLabel .t.control.left.f -in .t.control.left -side top -anchor w +foreach opt {activebackground activeforeground background disabledforeground foreground highlightbackground highlightcolor } { + #button .t.color-$opt -text $opt -command "config -$opt \[tk_chooseColor]" + menubutton .t.color-$opt -text $opt -menu .t.color-$opt.m -indicatoron 1 \ + -relief raised -bd 2 + menu .t.color-$opt.m -tearoff 0 + .t.color-$opt.m add command -label Red -command "config -$opt red" + .t.color-$opt.m add command -label Green -command "config -$opt green" + .t.color-$opt.m add command -label Blue -command "config -$opt blue" + .t.color-$opt.m add command -label Other... \ + -command "config -$opt \[tk_chooseColor]" + pack .t.color-$opt -in .t.control.left.f -fill x +} + +set default disabled +label .t.default -text Default: +radiobutton .t.default-normal -text "Default normal" -relief flat \ + -command "config-but -default normal" -variable default \ + -value normal +radiobutton .t.default-active -text "Default active" -relief flat \ + -command "config-but -default active" -variable default \ + -value active +radiobutton .t.default-disabled -text "Default disabled" -relief flat \ + -command "config-but -default disabled" -variable default \ + -value disabled +pack .t.default .t.default-normal .t.default-active .t.default-disabled \ + -in .t.control.right -anchor w + +sep +frame .t.f1 +pack .t.f1 -side top -expand 1 -fill both +sep +frame .t.f2 +pack .t.f2 -side top -expand 1 -fill both +sep +frame .t.f3 +pack .t.f3 -side top -expand 1 -fill both +sep +frame .t.f4 +pack .t.f4 -side top -expand 1 -fill both +sep + +label .t.l1 -text Label -bd 2 -relief sunken +label .t.l2 -text "Explicit\nnewlines\n\nin the text" -bd 2 -relief sunken +label .t.l3 -text "This text is quite long, so it must be wrapped automatically by Tk" -wraplength 2i -bd 2 -relief sunken -underline 50 +pack .t.l1 .t.l2 .t.l3 -in .t.f1 -side left -padx 5m -pady 3m \ + -expand y -fill both + +button .t.b1 -text Button +button .t.b2 -text "Explicit\nnewlines\n\nin the text" +button .t.b3 -text "This text is quite long, so it must be wrapped automatically by Tk" -wraplength 2i -underline 50 +pack .t.b1 .t.b2 .t.b3 -in .t.f2 -side left -padx 5m -pady 3m \ + -expand y -fill both + +checkbutton .t.c1 -text Checkbutton -variable a +checkbutton .t.c2 -text "Explicit\nnewlines\n\nin the text" -variable b +checkbutton .t.c3 -text "This text is quite long, so it must be wrapped automatically by Tk" -wraplength 2i -variable c -underline 50 +pack .t.c1 .t.c2 .t.c3 -in .t.f3 -side left -padx 5m -pady 3m \ + -expand y -fill both + +radiobutton .t.r1 -text Radiobutton -value a +radiobutton .t.r2 -text "Explicit\nnewlines\n\nin the text" -value b +radiobutton .t.r3 -text "This text is quite long, so it must be wrapped automatically by Tk" -wraplength 2i -value c -underline 50 +pack .t.r1 .t.r2 .t.r3 -in .t.f4 -side left -padx 5m -pady 3m \ + -expand y -fill both + +proc config {option value} { + foreach w {.t.l1 .t.l2 .t.l3 .t.b1 .t.b2 .t.b3 .t.c1 .t.c2 .t.c3 + .t.r1 .t.r2 .t.r3} { + catch {$w configure $option $value} + } +} + +proc config-but {option value} { + foreach w {.t.b1 .t.b2 .t.b3} { + $w configure $option $value + } +} diff --git a/tests/button.test b/tests/button.test new file mode 100644 index 0000000..2c6d082 --- /dev/null +++ b/tests/button.test @@ -0,0 +1,822 @@ +# This file is a Tcl script to test labels, buttons, checkbuttons, and +# radiobuttons in Tk (i.e., all the widgets defined in tkButton.c). It is +# organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) button.test 1.39 97/07/31 10:19:02 + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\"" + puts "image, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +proc bogusTrace args { + error "trace aborted" +} +catch {unset value} +catch {unset value2} + +# Create entries in the option database to be sure that geometry options +# like border width have predictable values. + +option add *Button.borderWidth 2 +option add *Button.highlightThickness 2 +option add *Button.font {Helvetica -12 bold} + +eval image delete [image names] +image create test image1 +label .l -text Label +button .b -text Button +checkbutton .c -text Checkbutton +radiobutton .r -text Radiobutton +pack .l .b .c .r +update +set i 1 +foreach test { + {-activebackground #012345 #012345 non-existent + {unknown color name "non-existent"}} + {-activeforeground #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-anchor nw nw bogus {bad anchor position "bogus": must be n, ne, e, se, s, sw, w, nw, or center}} + {-background #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-bg #ff0000 #ff0000 non-existent {unknown color name "non-existent"}} + {-bd 4 4 badValue {bad screen distance "badValue"}} + {-bitmap questhead questhead badValue {bitmap "badValue" not defined}} + {-borderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-command "set x" {set x} {} {}} + {-cursor arrow arrow badValue {bad cursor spec "badValue"}} + {-disabledforeground #00ff00 #00ff00 xyzzy {unknown color name "xyzzy"}} + {-fg #110022 #110022 bogus {unknown color name "bogus"}} + {-font {Helvetica 12} {Helvetica 12} {} {font "" doesn't exist}} + {-foreground #110022 #110022 bogus {unknown color name "bogus"}} + {-height 18 18 20.0 {expected integer but got "20.0"}} + {-highlightbackground #112233 #112233 ugly {unknown color name "ugly"}} + {-highlightcolor #110022 #110022 bogus {unknown color name "bogus"}} + {-highlightthickness 18 18 badValue {bad screen distance "badValue"}} + {-image image1 image1 bogus {image "bogus" doesn't exist}} + {-indicatoron yes 1 no_way {expected boolean value but got "no_way"}} + {-justify right right bogus {bad justification "bogus": must be left, right, or center}} + {-offvalue lousy lousy {} {}} + {-offvalue fantastic fantastic {} {}} + {-padx 12 12 420x {bad screen distance "420x"}} + {-pady 12 12 420x {bad screen distance "420x"}} + {-relief groove groove 1.5 {bad relief type "1.5": must be flat, groove, raised, ridge, solid, or sunken}} + {-selectcolor #110022 #110022 bogus {unknown color name "bogus"}} + {-selectimage image1 image1 bogus {image "bogus" doesn't exist}} + {-state normal normal bogus {bad state value "bogus": must be normal, active, or disabled}} + {-takefocus "any string" "any string" {} {}} + {-text "Sample text" {Sample text} {} {}} + {-textvariable i i {} {}} + {-underline 5 5 3p {expected integer but got "3p"}} + {-width 402 402 3p {expected integer but got "3p"}} + {-wraplength 100 100 6x {bad screen distance "6x"}} +} { + set name [lindex $test 0] + test button-1.$i {configuration options} { + .c configure $name [lindex $test 1] + lindex [.c configure $name] 4 + } [lindex $test 2] + incr i + if {[lindex $test 3] != ""} { + test button-1.$i {configuration options} { + list [catch {.c configure $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .c configure $name [lindex [.c configure $name] 3] + incr i +} +test button-1.$i {configuration options} { + .c configure -selectcolor {} +} {} +incr i +# the following tests only work on buttons, not checkbuttons +test button-1.$i {configuration options} { + .b configure -default active + lindex [.b configure -default] 4 +} active +incr i +test button-1.$i {configuration options} { + .b configure -default normal + lindex [.b configure -default] 4 +} normal +incr i +test button-1.$i {configuration options} { + .b configure -default disabled + lindex [.b configure -default] 4 +} disabled +incr i +test button-1.$i {configuration options} { + .b configure -default active + lindex [.b configure -default] 3 +} disabled +incr i +test button-1.$i {configuration options} { + list [catch {.b configure -default no_way} msg] $msg +} {1 {bad -default value "no_way": must be normal, active, or disabled}} + +set i 1 +foreach check { + {-activebackground 1 0 0 0} + {-activeforeground 1 0 0 0} + {-anchor 0 0 0 0} + {-background 0 0 0 0} + {-bd 0 0 0 0} + {-bg 0 0 0 0} + {-bitmap 0 0 0 0} + {-borderwidth 0 0 0 0} + {-command 1 0 0 0} + {-cursor 0 0 0 0} + {-default 1 0 1 1} + {-disabledforeground 1 0 0 0} + {-fg 0 0 0 0} + {-font 0 0 0 0} + {-foreground 0 0 0 0} + {-height 0 0 0 0} + {-image 0 0 0 0} + {-indicatoron 1 1 0 0} + {-offvalue 1 1 0 1} + {-onvalue 1 1 0 1} + {-padx 0 0 0 0} + {-pady 0 0 0 0} + {-relief 0 0 0 0} + {-selectcolor 1 1 0 0} + {-selectimage 1 1 0 0} + {-state 1 0 0 0} + {-text 0 0 0 0} + {-textvariable 0 0 0 0} + {-value 1 1 1 0} + {-variable 1 1 0 0} + {-width 0 0 0 0} +} { + test button-2.$i {label-specific options} " + catch {.l configure [lindex $check 0]} + " [lindex $check 1] + incr i + test button-2.$i {button-specific options} " + catch {.b configure [lindex $check 0]} + " [lindex $check 2] + incr i + test button-2.$i {checkbutton-specific options} " + catch {.c configure [lindex $check 0]} + " [lindex $check 3] + incr i + test button-2.$i {radiobutton-specific options} " + catch {.r configure [lindex $check 0]} + " [lindex $check 4] + incr i +} + +test button-3.1 {ButtonCreate procedure} { + list [catch {button} msg] $msg +} {1 {wrong # args: should be "button pathName ?options?"}} +test button-3.2 {ButtonCreate procedure} { + catch {destroy .x} + label .x + winfo class .x +} {Label} +test button-3.3 {ButtonCreate procedure} { + catch {destroy .x} + button .x + winfo class .x +} {Button} +test button-3.4 {ButtonCreate procedure} { + catch {destroy .x} + checkbutton .x + winfo class .x +} {Checkbutton} +test button-3.5 {ButtonCreate procedure} { + catch {destroy .x} + radiobutton .x + winfo class .x +} {Radiobutton} +rename button gorp +test button-3.6 {ButtonCreate procedure} { + catch {destroy .x} + gorp .x + winfo class .x +} {Button} +rename gorp button +test button-3.7 {ButtonCreate procedure} { + list [catch {button foo} msg] $msg +} {1 {bad window path name "foo"}} +test button-3.8 {ButtonCreate procedure} { + catch {destroy .x} + list [catch {button .x -gorp foo} msg] $msg [winfo exists .x] +} {1 {unknown option "-gorp"} 0} + +test button-4.1 {ButtonWidgetCmd procedure} { + list [catch {.b} msg] $msg +} {1 {wrong # args: should be ".b option ?arg arg ...?"}} +test button-4.2 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.b c} msg] $msg +} {1 {bad option "c": must be cget, configure, flash, or invoke}} +test button-4.3 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.b cget a b} msg] $msg +} {1 {wrong # args: should be ".b cget option"}} +test button-4.4 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.b cget -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test button-4.5 {ButtonWidgetCmd procedure, "cget" option} { + .b configure -highlightthickness 3 + .b cget -highlightthickness +} {3} +test button-4.6 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.l cget -disabledforeground} msg] $msg +} {1 {unknown option "-disabledforeground"}} +test button-4.7 {ButtonWidgetCmd procedure, "cget" option} { + catch {.b cget -disabledforeground} +} {0} +test button-4.8 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.b cget -variable} msg] $msg +} {1 {unknown option "-variable"}} +test button-4.9 {ButtonWidgetCmd procedure, "cget" option} { + catch {.c cget -variable} +} {0} +test button-4.10 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.c cget -value} msg] $msg +} {1 {unknown option "-value"}} +test button-4.11 {ButtonWidgetCmd procedure, "cget" option} { + catch {.r cget -value} +} {0} +test button-4.12 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.r cget -onvalue} msg] $msg +} {1 {unknown option "-onvalue"}} +test button-4.13 {ButtonWidgetCmd procedure, "configure" option} { + llength [.c configure] +} {36} +test button-4.14 {ButtonWidgetCmd procedure, "configure" option} { + list [catch {.b configure -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test button-4.15 {ButtonWidgetCmd procedure, "configure" option} { + list [catch {.b co -bg #ffffff -fg} msg] $msg +} {1 {value for "-fg" missing}} +test button-4.16 {ButtonWidgetCmd procedure, "configure" option} { + .b configure -fg #123456 + .b configure -bg #654321 + lindex [.b configure -fg] 4 +} {#123456} +.c configure -variable value -onvalue 1 -offvalue 0 +.r configure -variable value2 -value red +test button-4.17 {ButtonWidgetCmd procedure, "deselect" option} { + list [catch {.c deselect foo} msg] $msg +} {1 {wrong # args: should be ".c deselect"}} +test button-4.18 {ButtonWidgetCmd procedure, "deselect" option} { + list [catch {.l deselect} msg] $msg +} {1 {bad option "deselect": must be cget or configure}} +test button-4.19 {ButtonWidgetCmd procedure, "deselect" option} { + list [catch {.b deselect} msg] $msg +} {1 {bad option "deselect": must be cget, configure, flash, or invoke}} +test button-4.20 {ButtonWidgetCmd procedure, "deselect" option} { + set value 1 + .c d + set value +} {0} +test button-4.21 {ButtonWidgetCmd procedure, "deselect" option} { + set value2 green + .r deselect + set value2 +} {green} +test button-4.22 {ButtonWidgetCmd procedure, "deselect" option} { + set value2 red + .r deselect + set value2 +} {} +test button-4.23 {ButtonWidgetCmd procedure, "deselect" option} { + set value 1 + trace variable value w bogusTrace + set result [list [catch {.c deselect} msg] $msg $errorInfo $value] + trace vdelete value w bogusTrace + set result +} {1 {can't set "value": trace aborted} {can't set "value": trace aborted + while executing +".c deselect"} 0} +test button-4.24 {ButtonWidgetCmd procedure, "deselect" option} { + set value2 red + trace variable value2 w bogusTrace + set result [list [catch {.r deselect} msg] $msg $errorInfo $value2] + trace vdelete value2 w bogusTrace + set result +} {1 {can't set "value2": trace aborted} {can't set "value2": trace aborted + while executing +".r deselect"} {}} +test button-4.25 {ButtonWidgetCmd procedure, "flash" option} { + list [catch {.b flash foo} msg] $msg +} {1 {wrong # args: should be ".b flash"}} +test button-4.26 {ButtonWidgetCmd procedure, "flash" option} { + list [catch {.l flash} msg] $msg +} {1 {bad option "flash": must be cget or configure}} +test button-4.27 {ButtonWidgetCmd procedure, "flash" option} { + list [catch {.b flash} msg] $msg +} {0 {}} +test button-4.28 {ButtonWidgetCmd procedure, "flash" option} { + list [catch {.c flash} msg] $msg +} {0 {}} +test button-4.29 {ButtonWidgetCmd procedure, "flash" option} { + list [catch {.r f} msg] $msg +} {0 {}} +test button-4.30 {ButtonWidgetCmd procedure, "invoke" option} { + list [catch {.b invoke foo} msg] $msg +} {1 {wrong # args: should be ".b invoke"}} +test button-4.31 {ButtonWidgetCmd procedure, "invoke" option} { + list [catch {.l invoke} msg] $msg +} {1 {bad option "invoke": must be cget or configure}} +test button-4.32 {ButtonWidgetCmd procedure, "invoke" option} { + .b configure -command {set x invoked} + set x "not invoked" + .b invoke + set x +} {invoked} +test button-4.33 {ButtonWidgetCmd procedure, "invoke" option} { + .b configure -command {set x invoked} -state disabled + set x "not invoked" + .b invoke + set x +} {not invoked} +test button-4.34 {ButtonWidgetCmd procedure, "invoke" option} { + set value bogus + .c configure -command {set x invoked} -variable value -onvalue 1 \ + -offvalue 0 + set x "not invoked" + .c invoke + list $x $value +} {invoked 1} +test button-4.35 {ButtonWidgetCmd procedure, "invoke" option} { + set value2 green + .r configure -command {set x invoked} -variable value2 -value red + set x "not invoked" + .r i + list $x $value2 +} {invoked red} +test button-4.36 {ButtonWidgetCmd procedure, "select" option} { + list [catch {.l select} msg] $msg +} {1 {bad option "select": must be cget or configure}} +test button-4.37 {ButtonWidgetCmd procedure, "select" option} { + list [catch {.b select} msg] $msg +} {1 {bad option "select": must be cget, configure, flash, or invoke}} +test button-4.38 {ButtonWidgetCmd procedure, "select" option} { + list [catch {.c select foo} msg] $msg +} {1 {wrong # args: should be ".c select"}} +test button-4.39 {ButtonWidgetCmd procedure, "select" option} { + set value bogus + .c configure -command {} -variable value -onvalue lovely -offvalue 0 + .c s + set value +} {lovely} +test button-4.40 {ButtonWidgetCmd procedure, "select" option} { + set value2 green + .r configure -command {} -variable value2 -value red + .r select + set value2 +} {red} +test button-4.41 {ButtonWidgetCmd procedure, "select" option} { + set value2 yellow + trace variable value2 w bogusTrace + set result [list [catch {.r select} msg] $msg $errorInfo $value2] + trace vdelete value2 w bogusTrace + set result +} {1 {can't set "value2": trace aborted} {can't set "value2": trace aborted + while executing +".r select"} red} +test button-4.42 {ButtonWidgetCmd procedure, "toggle" option} { + list [catch {.l toggle} msg] $msg +} {1 {bad option "toggle": must be cget or configure}} +test button-4.43 {ButtonWidgetCmd procedure, "toggle" option} { + list [catch {.b toggle} msg] $msg +} {1 {bad option "toggle": must be cget, configure, flash, or invoke}} +test button-4.44 {ButtonWidgetCmd procedure, "toggle" option} { + list [catch {.r toggle} msg] $msg +} {1 {bad option "toggle": must be cget, configure, deselect, flash, invoke, or select}} +test button-4.45 {ButtonWidgetCmd procedure, "toggle" option} { + list [catch {.c toggle foo} msg] $msg +} {1 {wrong # args: should be ".c toggle"}} +test button-4.46 {ButtonWidgetCmd procedure, "toggle" option} { + set value bogus + .c configure -command {} -variable value -onvalue sunshine -offvalue rain + .c toggle + set result $value + .c toggle + lappend result $value + .c toggle + lappend result $value +} {sunshine rain sunshine} +test button-4.47 {ButtonWidgetCmd procedure, "toggle" option} { + .c configure -onvalue xyz -offvalue abc + set value xyz + trace variable value w bogusTrace + set result [list [catch {.c toggle} msg] $msg $errorInfo $value] + trace vdelete value w bogusTrace + set result +} {1 {can't set "value": trace aborted} {can't set "value": trace aborted + while executing +".c toggle"} abc} +test button-4.48 {ButtonWidgetCmd procedure, "toggle" option} { + .c configure -onvalue xyz -offvalue abc + set value abc + trace variable value w bogusTrace + set result [list [catch {.c toggle} msg] $msg $errorInfo $value] + trace vdelete value w bogusTrace + set result +} {1 {can't set "value": trace aborted} {can't set "value": trace aborted + while executing +".c toggle"} xyz} +test button-4.49 {ButtonWidgetCmd procedure} { + list [catch {.c bad_option} msg] $msg +} {1 {bad option "bad_option": must be cget, configure, deselect, flash, invoke, select, or toggle}} +test button-4.50 {ButtonWidgetCmd procedure, "toggle" option} { + catch {unset value}; set value(1) 1; + set result [list [catch {.c toggle} msg] $msg $errorInfo] + unset value; + set result +} {1 {can't set "value": variable is array} {can't set "value": variable is array + while executing +".c toggle"}} + +test button-5.1 {DestroyButton procedure} { + image create test image1 + button .b1 -image image1 + button .b2 -fg #ff0000 -text "Button 2" + button .b3 -state active -text "Button 3" + button .b4 -disabledforeground #0000ff -state disabled -text "Button 4" + checkbutton .b5 -variable x -text "Checkbutton 5" + set x 1 + pack .b1 .b2 .b3 .b4 .b5 + update + eval destroy [winfo children .] +} {} + +test button-6.1 {ConfigureButton procedure} { + catch {destroy .b1} + set x From-x + set y From-y + button .b1 -textvariable x + .b1 configure -textvariable y + set x New + lindex [.b1 configure -text] 4 +} {From-y} +test button-6.2 {ConfigureButton procedure} { + catch {destroy .b1} + catch {unset x} + checkbutton .b1 -variable x + set x 1 + set y 1 + .b1 configure -textvariable y + set x 0 + .b1 toggle + set y +} {1} +test button-6.3 {ConfigureButton procedure} { + catch {destroy .b1} + eval image delete [image names] + image create test image1 + image create test image2 + button .b1 -image image1 + image delete image1 + .b1 configure -image image2 + image names +} {image2} +test button-6.4 {ConfigureButton procedure} { + catch {destroy .b1} + button .b1 -text "Test" -state disabled + list [catch {.b1 configure -state bogus} msg] $msg \ + [lindex [.b1 configure -state] 4] +} {1 {bad state value "bogus": must be normal, active, or disabled} normal} +test button-6.5 {ConfigureButton procedure} { + catch {destroy .b1} + checkbutton .b1 + .b1 cget -variable +} {b1} +test button-6.6 {ConfigureButton procedure} { + catch {destroy .b1} + set x 0 + set y Shiny + checkbutton .b1 -variable x + .b1 configure -variable y -onvalue Shiny + .b1 toggle + set y +} 0 +test button-6.7 {ConfigureButton procedure} { + catch {destroy .b1} + catch {unset x} + checkbutton .b1 -variable x -offvalue Bogus + set x +} Bogus +test button-6.8 {ConfigureButton procedure} { + catch {destroy .b1} + catch {unset x} + radiobutton .b1 -variable x + set x +} {} +test button-6.9 {ConfigureButton procedure} { + catch {destroy .b1} + catch {unset x} + trace variable x w bogusTrace + set result [list [catch {radiobutton .b1 -variable x} msg] $msg] + trace vdelete x w bogusTrace + set result +} {1 {can't set "x": trace aborted}} +test button-6.10 {ConfigureButton procedure} { + catch {destroy .b1} + list [catch {button .b1 -image bogus} msg] $msg +} {1 {image "bogus" doesn't exist}} +test button-6.11 {ConfigureButton procedure} { + catch {destroy .b1} + catch {unset x} + button .b1 -textvariable x -text "Button 1" + set x +} {Button 1} +test button-6.12 {ConfigureButton procedure} { + catch {destroy .b1} + set x Override + button .b1 -textvariable x -text "Button 1" + set x +} {Override} +test button-6.13 {ConfigureButton procedure} { + catch {destroy .b1} + catch {unset x} + trace variable x w bogusTrace + set result [list [catch {radiobutton .b1 -text foo -textvariable x} msg] \ + $msg $x] + trace vdelete x w bogusTrace + set result +} {1 {can't set "x": trace aborted} foo} +test button-6.14 {ConfigureButton procedure} { + catch {destroy .b1} + button .b1 -text "Button 1" + list [catch {.b1 configure -width 1i} msg] $msg $errorInfo +} {1 {expected integer but got "1i"} {expected integer but got "1i" + (processing -width option) + invoked from within +".b1 configure -width 1i"}} +test button-6.15 {ConfigureButton procedure} { + catch {destroy .b1} + button .b1 -text "Button 1" + list [catch {.b1 configure -height 0.5c} msg] $msg $errorInfo +} {1 {expected integer but got "0.5c"} {expected integer but got "0.5c" + (processing -height option) + invoked from within +".b1 configure -height 0.5c"}} +test button-6.16 {ConfigureButton procedure} { + catch {destroy .b1} + button .b1 -bitmap questhead + list [catch {.b1 configure -width abc} msg] $msg $errorInfo +} {1 {bad screen distance "abc"} {bad screen distance "abc" + (processing -width option) + invoked from within +".b1 configure -width abc"}} +test button-6.17 {ConfigureButton procedure} { + catch {destroy .b1} + eval image delete [image names] + image create test image1 + button .b1 -image image1 + list [catch {.b1 configure -height 0.5x} msg] $msg $errorInfo +} {1 {bad screen distance "0.5x"} {bad screen distance "0.5x" + (processing -height option) + invoked from within +".b1 configure -height 0.5x"}} +test button-6.18 {ConfigureButton procedure} {nonPortable fonts} { + catch {destroy .b1} + button .b1 -text "Sample text" -width 10 -height 2 + pack .b1 + set result "[winfo reqwidth .b1] [winfo reqheight .b1]" + .b1 configure -bitmap questhead + lappend result [winfo reqwidth .b1] [winfo reqheight .b1] +} {102 46 20 12} +test button-6.19 {ConfigureButton procedure} { + catch {destroy .b1} + button .b1 -text "Button 1" + set old [winfo reqwidth .b1] + .b1 configure -text "Much longer text" + set new [winfo reqwidth .b1] + expr $old == $new +} {0} + +test button-7.1 {ButtonEventProc procedure} { + catch {destroy .b1} + button .b1 -text "Test Button" -command { + destroy .b1 + set x [list [winfo exists .b1] [info commands .b1]] + } + .b1 invoke + set x +} {0 {}} +test button-7.2 {ButtonEventProc procedure} { + eval destroy [winfo children .] + button .b1 -bg #543210 + rename .b1 .b2 + set x {} + lappend x [winfo children .] + lappend x [.b2 cget -bg] + destroy .b1 + lappend x [info command .b*] [winfo children .] +} {.b1 #543210 {} {}} + +test button-8.1 {ButtonCmdDeletedProc procedure} { + eval destroy [winfo children .] + button .b1 + rename .b1 {} + list [info command .b*] [winfo children .] +} {{} {}} + +test button-9.1 {TkInvokeButton procedure} { + catch {destroy .b1} + set x 0 + checkbutton .b1 -variable x + set result $x + .b1 invoke + lappend result $x + .b1 invoke + lappend result $x +} {0 1 0} +test button-9.2 {TkInvokeButton procedure} { + catch {destroy .b1} + set x 0 + checkbutton .b1 -variable x + trace variable x w bogusTrace + set result [list [catch {.b1 invoke} msg] $msg $x] + trace vdelete x w bogusTrace + set result +} {1 {can't set "x": trace aborted} 1} +test button-9.3 {TkInvokeButton procedure} { + catch {destroy .b1} + set x 1 + checkbutton .b1 -variable x + trace variable x w bogusTrace + set result [list [catch {.b1 invoke} msg] $msg $x] + trace vdelete x w bogusTrace + set result +} {1 {can't set "x": trace aborted} 0} +test button-9.4 {TkInvokeButton procedure} { + catch {destroy .b1} + set x 0 + radiobutton .b1 -variable x -value red + set result $x + .b1 invoke + lappend result $x + .b1 invoke + lappend result $x +} {0 red red} +test button-9.5 {TkInvokeButton procedure} { + catch {destroy .b1} + radiobutton .b1 -variable x -value red + set x green + trace variable x w bogusTrace + set result [list [catch {.b1 invoke} msg] $msg $errorInfo $x] + trace vdelete x w bogusTrace + set result +} {1 {can't set "x": trace aborted} {can't set "x": trace aborted + while executing +".b1 invoke"} red} +test button-9.6 {TkInvokeButton procedure} { + eval destroy [winfo children .] + set result untouched + button .b1 -command {set result invoked} + list [catch {.b1 invoke} msg] $msg $result +} {0 invoked invoked} +test button-9.7 {TkInvokeButton procedure} { + eval destroy [winfo children .] + set result untouched + set x 0 + checkbutton .b1 -variable x -command {set result "invoked $x"} + list [catch {.b1 invoke} msg] $msg $result +} {0 {invoked 1} {invoked 1}} +test button-9.8 {TkInvokeButton procedure} { + eval destroy [winfo children .] + set result untouched + set x 0 + radiobutton .b1 -variable x -value red -command {set result "invoked $x"} + list [catch {.b1 invoke} msg] $msg $result +} {0 {invoked red} {invoked red}} + +test button-10.1 {ButtonVarProc procedure} { + eval destroy [winfo children .] + set x 1 + checkbutton .b1 -variable x + unset x + set result [info exists x] + .b1 toggle + lappend result $x + set x 0 + .b1 toggle + lappend result $x +} {0 1 1} +test button-10.2 {ButtonVarProc procedure} { + eval destroy [winfo children .] + set x 0 + checkbutton .b1 -variable x + set x 44 + .b1 toggle + set x +} {1} +test button-10.3 {ButtonVarProc procedure} { + eval destroy [winfo children .] + set x 1 + checkbutton .b1 -variable x + set x 44 + .b1 toggle + set x +} {1} +test button-10.4 {ButtonVarProc procedure} { + eval destroy [winfo children .] + set x 0 + checkbutton .b1 -variable x + set x 1 + .b1 toggle + set x +} {0} +test button-10.5 {ButtonVarProc procedure} { + eval destroy [winfo children .] + set x 1 + checkbutton .b1 -variable x + set x 1 + .b1 toggle + set x +} {0} +test button-10.6 {ButtonVarProc procedure} { + eval destroy [winfo children .] + set x 0 + checkbutton .b1 -variable x + set x 0 + .b1 toggle + set x +} {1} +test button-10.7 {ButtonVarProc procedure} { + eval destroy [winfo children .] + set x 1 + checkbutton .b1 -variable x + set x 0 + .b1 toggle + set x +} {1} +test button-10.8 {ButtonVarProc procedure, can't read variable} { + # This test does nothing but produce a core dump if there's a prbblem. + eval destroy [winfo children .] + catch {unset a} + checkbutton .b1 -variable a + unset a + set a(32) 0 + unset a +} {} + +test button-11.1 {ButtonTextVarProc procedure} { + eval destroy [winfo children .] + set x Label + button .b1 -textvariable x + unset x + set result [list $x [lindex [.b1 configure -text] 4]] + set x New + lappend result [lindex [.b1 configure -text] 4] +} {Label Label New} +test button-11.2 {ButtonTextVarProc procedure} { + eval destroy [winfo children .] + set x Label + button .b1 -textvariable x + set old [winfo reqwidth .b1] + set x New + set new [winfo reqwidth .b1] + list [lindex [.b1 configure -text] 4] [expr $old == $new] +} {New 0} + +test button-12.1 {ButtonImageProc procedure} { + eval destroy [winfo children .] + eval image delete [image names] + image create test image1 + label .b1 -image image1 -padx 0 -pady 0 -bd 0 + pack .b1 + set result "[winfo reqwidth .b1] [winfo reqheight .b1]" + image1 changed 0 0 0 0 80 100 + lappend result [winfo reqwidth .b1] [winfo reqheight .b1] +} {30 15 80 100} + +eval destroy [winfo children .] +set l [interp hidden] + +test button-13.1 {button widget vs hidden commands} { + catch {destroy .b} + button .b -text hello + interp hide {} .b + destroy .b + list [winfo children .] [interp hidden] +} [list {} $l] + +eval destroy [winfo children .] + +option clear + diff --git a/tests/canvImg.test b/tests/canvImg.test new file mode 100644 index 0000000..59ceaa2 --- /dev/null +++ b/tests/canvImg.test @@ -0,0 +1,397 @@ +# This file is a Tcl script to test out the procedures in tkCanvImg.c, +# which implement canvas "image" items. It is organized in the standard +# fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) canvImg.test 1.17 97/07/02 11:28:26 + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\" image" + puts "type, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +eval image delete [image names] +canvas .c +pack .c +update +image create test foo -variable x +image create test foo2 -variable y +foo2 changed 0 0 0 0 80 60 +test canvImg-1.1 {options for image items} { + .c delete all + .c create image 50 50 -anchor nw -tags i1 + .c itemconfigure i1 -anchor +} {-anchor {} {} center nw} +test canvImg-1.2 {options for image items} { + .c delete all + list [catch {.c create image 50 50 -anchor gorp -tags i1} msg] $msg +} {1 {bad anchor position "gorp": must be n, ne, e, se, s, sw, w, nw, or center}} +test canvImg-1.3 {options for image items} { + .c delete all + .c create image 50 50 -image foo -tags i1 + .c itemconfigure i1 -image +} {-image {} {} {} foo} +test canvImg-1.4 {options for image items} { + .c delete all + list [catch {.c create image 50 50 -image unknown -tags i1} msg] $msg +} {1 {image "unknown" doesn't exist}} +test canvImg-1.5 {options for image items} { + .c delete all + .c create image 50 50 -image foo -tags {i1 foo} + .c itemconfigure i1 -tags +} {-tags {} {} {} {i1 foo}} + +test canvImg-2.1 {CreateImage procedure} { + list [catch {.c create image 40} msg] $msg +} {1 {wrong # args: should be ".c create image x y ?options?"}} +test canvImg-2.2 {CreateImage procedure} { + list [catch {.c create image 40 50 60} msg] $msg +} {1 {unknown option "60"}} +test canvImg-2.3 {CreateImage procedure} { + .c delete all + set i [.c create image 50 50] + list [lindex [.c itemconf $i -anchor] 4] \ + [lindex [.c itemconf $i -image] 4] \ + [lindex [.c itemconf $i -tags] 4] +} {center {} {}} +test canvImg-2.4 {CreateImage procedure} { + list [catch {.c create image xyz 40} msg] $msg +} {1 {bad screen distance "xyz"}} +test canvImg-2.5 {CreateImage procedure} { + list [catch {.c create image 50 qrs} msg] $msg +} {1 {bad screen distance "qrs"}} +test canvImg-2.6 {CreateImage procedure} { + list [catch {.c create image 50 50 -gorp foo} msg] $msg +} {1 {unknown option "-gorp"}} + +test canvImg-3.1 {ImageCoords procedure} { + .c delete all + .c create image 50 100 -image foo -tags i1 + .c coords i1 +} {50.0 100.0} +test canvImg-3.2 {ImageCoords procedure} { + .c delete all + .c create image 50 100 -image foo -tags i1 + list [catch {.c coords i1 dumb 100} msg] $msg +} {1 {bad screen distance "dumb"}} +test canvImg-3.3 {ImageCoords procedure} { + .c delete all + .c create image 50 100 -image foo -tags i1 + list [catch {.c coords i1 250 dumb0} msg] $msg +} {1 {bad screen distance "dumb0"}} +test canvImg-3.4 {ImageCoords procedure} { + .c delete all + .c create image 50 100 -image foo -tags i1 + list [catch {.c coords i1 250} msg] $msg +} {1 {wrong # coordinates: expected 0 or 2, got 1}} +test canvImg-3.5 {ImageCoords procedure} { + .c delete all + .c create image 50 100 -image foo -tags i1 + list [catch {.c coords i1 250 300 400} msg] $msg +} {1 {wrong # coordinates: expected 0 or 2, got 3}} + +test canvImg-4.1 {ConfiugreImage procedure} { + .c delete all + .c create image 50 100 -image foo -tags i1 + update + set x {} + .c itemconfigure i1 -image {} + update + list $x [.c bbox i1] +} {{{foo free}} {}} +test canvImg-4.2 {ConfiugreImage procedure} { + .c delete all + .c create image 50 100 -image foo -tags i1 -anchor nw + update + set x {} + set y {} + .c itemconfigure i1 -image foo2 + update + list $x $y [.c bbox i1] +} {{{foo free}} {{foo2 get} {foo2 display 0 0 80 60 30 30}} {50 100 130 160}} +test canvImg-4.3 {ConfiugreImage procedure} { + .c delete all + .c create image 50 100 -image foo -tags i1 -anchor nw + update + set x {} + set y {} + list [catch {.c itemconfigure i1 -image lousy} msg] $msg +} {1 {image "lousy" doesn't exist}} + +test canvImg-5.1 {DeleteImage procedure} { + image create test xyzzy -variable z + .c delete all + .c create image 50 100 -image xyzzy -tags i1 + update + image delete xyzzy + set z {} + set names [lsort [image names]] + .c delete i1 + update + list $names $z [lsort [image names]] +} {{foo foo2 xyzzy} {} {foo foo2}} +test canvImg-5.2 {DeleteImage procedure (don't delete non-existent image)} { + .c delete all + .c create image 50 100 -tags i1 + update + .c delete i1 + update +} {} + +test canvImg-6.1 {ComputeImageBbox procedure} { + .c delete all + .c create image 15.51 17.51 -image foo -tags i1 -anchor nw + .c bbox i1 +} {16 18 46 33} +test canvImg-6.2 {ComputeImageBbox procedure} { + .c delete all + .c create image 15.49 17.49 -image foo -tags i1 -anchor nw + .c bbox i1 +} {15 17 45 32} +test canvImg-6.3 {ComputeImageBbox procedure} { + .c delete all + .c create image 20 30 -tags i1 -anchor nw + .c bbox i1 +} {} +test canvImg-6.4 {ComputeImageBbox procedure} { + .c delete all + .c create image 20 30 -image foo -tags i1 -anchor nw + .c bbox i1 +} {20 30 50 45} +test canvImg-6.5 {ComputeImageBbox procedure} { + .c delete all + .c create image 20 30 -image foo -tags i1 -anchor n + .c bbox i1 +} {5 30 35 45} +test canvImg-6.6 {ComputeImageBbox procedure} { + .c delete all + .c create image 20 30 -image foo -tags i1 -anchor ne + .c bbox i1 +} {-10 30 20 45} +test canvImg-6.7 {ComputeImageBbox procedure} { + .c delete all + .c create image 20 30 -image foo -tags i1 -anchor e + .c bbox i1 +} {-10 23 20 38} +test canvImg-6.8 {ComputeImageBbox procedure} { + .c delete all + .c create image 20 30 -image foo -tags i1 -anchor se + .c bbox i1 +} {-10 15 20 30} +test canvImg-6.9 {ComputeImageBbox procedure} { + .c delete all + .c create image 20 30 -image foo -tags i1 -anchor s + .c bbox i1 +} {5 15 35 30} +test canvImg-6.10 {ComputeImageBbox procedure} { + .c delete all + .c create image 20 30 -image foo -tags i1 -anchor sw + .c bbox i1 +} {20 15 50 30} +test canvImg-6.11 {ComputeImageBbox procedure} { + .c delete all + .c create image 20 30 -image foo -tags i1 -anchor w + .c bbox i1 +} {20 23 50 38} +test canvImg-6.12 {ComputeImageBbox procedure} { + .c delete all + .c create image 20 30 -image foo -tags i1 -anchor center + .c bbox i1 +} {5 23 35 38} + +# The following test is non-portable because of differences in +# coordinate rounding on some machines (does 0.5 round up?). + +test canvImg-7.1 {DisplayImage procedure} {nonPortable} { + .c delete all + .c create image 50 100 -image foo -tags i1 -anchor nw + update + set x {} + .c create rect 55 110 65 115 -width 1 -outline black -fill white + update + set x +} {{foo display 4 9 12 6 30 30}} +test canvImg-7.2 {DisplayImage procedure, no image} { + .c delete all + .c create image 50 100 -tags i1 + update + .c create rect 55 110 65 115 -width 1 -outline black -fill white + update +} {} + +set i 1 +.c delete all +.c create image 50 100 -image foo -tags image -anchor nw +.c create rect 10 10 20 20 -tags rect -fill black -width 0 -outline {} +foreach check { + {{50 70 80 81} {70 90} {rect}} + {{50 70 80 79} {70 90} {image}} + {{99 70 110 81} {90 90} {rect}} + {{101 70 110 79} {90 90} {image}} + {{99 100 110 115} {90 110} {rect}} + {{101 100 110 115} {90 110} {image}} + {{99 134 110 145} {90 125} {rect}} + {{101 136 110 145} {90 125} {image}} + {{50 134 80 145} {70 125} {rect}} + {{50 136 80 145} {70 125} {image}} + {{20 134 31 145} {40 125} {rect}} + {{20 136 29 145} {40 125} {image}} + {{20 100 31 115} {40 110} {rect}} + {{20 100 29 115} {40 110} {image}} + {{20 70 31 80} {40 90} {rect}} + {{20 70 29 79} {40 90} {image}} + {{60 70 69 109} {70 110} {image}} + {{60 70 71 111} {70 110} {rect}} +} { + test canvImg-8.$i {ImageToPoint procedure} { + eval .c coords rect [lindex $check 0] + .c gettags [eval .c find closest [lindex $check 1]] + } [lindex $check 2] + incr i +} + +.c delete all +.c create image 50 100 -image foo -tags image -anchor nw +test canvImg-8.19 {ImageToArea procedure} { + .c gettags [.c find overlapping 60 0 70 99] +} {} +test canvImg-8.20 {ImageToArea procedure} { + .c gettags [.c find overlapping 60 0 70 99.999] +} {} +test canvImg-8.21 {ImageToArea procedure} { + .c gettags [.c find overlapping 60 0 70 101] +} {image} +test canvImg-8.22 {ImageToArea procedure} { + .c gettags [.c find overlapping 81 105 120 115] +} {} +test canvImg-8.23 {ImageToArea procedure} { + .c gettags [.c find overlapping 80.001 105 120 115] +} {} +test canvImg-8.24 {ImageToArea procedure} { + .c gettags [.c find overlapping 79 105 120 115] +} {image} +test canvImg-8.25 {ImageToArea procedure} { + .c gettags [.c find overlapping 60 116 70 150] +} {} +test canvImg-8.26 {ImageToArea procedure} { + .c gettags [.c find overlapping 60 115.001 70 150] +} {} +test canvImg-8.27 {ImageToArea procedure} { + .c gettags [.c find overlapping 60 114 70 150] +} {image} +test canvImg-8.28 {ImageToArea procedure} { + .c gettags [.c find overlapping 0 105 49 115] +} {} +test canvImg-8.29 {ImageToArea procedure} { + .c gettags [.c find overlapping 0 105 50 114.999] +} {} +test canvImg-8.30 {ImageToArea procedure} { + .c gettags [.c find overlapping 0 105 51 115] +} {image} +test canvImg-8.31 {ImageToArea procedure} { + .c gettags [.c find overlapping 0 0 49.999 99.999] +} {} +test canvImg-8.32 {ImageToArea procedure} { + .c gettags [.c find overlapping 0 0 51 101] +} {image} +test canvImg-8.33 {ImageToArea procedure} { + .c gettags [.c find overlapping 80 0 150 100] +} {} +test canvImg-8.34 {ImageToArea procedure} { + .c gettags [.c find overlapping 79 0 150 101] +} {image} +test canvImg-8.35 {ImageToArea procedure} { + .c gettags [.c find overlapping 80.001 115.001 150 180] +} {} +test canvImg-8.36 {ImageToArea procedure} { + .c gettags [.c find overlapping 79 114 150 180] +} {image} +test canvImg-8.37 {ImageToArea procedure} { + .c gettags [.c find overlapping 0 115 50 180] +} {} +test canvImg-8.38 {ImageToArea procedure} { + .c gettags [.c find overlapping 0 114 51 180] +} {image} +test canvImg-8.39 {ImageToArea procedure} { + .c gettags [.c find enclosed 0 0 200 200] +} {image} +test canvImg-8.40 {ImageToArea procedure} { + .c gettags [.c find enclosed 49.999 99.999 80.001 115.001] +} {image} +test canvImg-8.41 {ImageToArea procedure} { + .c gettags [.c find enclosed 51 100 80 115] +} {} +test canvImg-8.42 {ImageToArea procedure} { + .c gettags [.c find enclosed 50 101 80 115] +} {} +test canvImg-8.43 {ImageToArea procedure} { + .c gettags [.c find enclosed 50 100 79 115] +} {} +test canvImg-8.44 {ImageToArea procedure} { + .c gettags [.c find enclosed 50 100 80 114] +} {} + +test canvImg-9.1 {DisplayImage procedure} { + .c delete all + .c create image 50 100 -image foo -tags image -anchor nw + .c scale image 25 0 2.0 1.5 + .c bbox image +} {75 150 105 165} + +test canvImg-10.1 {TranslateImage procedure} { + .c delete all + .c create image 50 100 -image foo -tags image -anchor nw + update + set x {} + foo changed 2 4 6 8 30 15 + update + set x +} {{foo display 2 4 6 8 30 30}} + +test canvImg-11.1 {TranslateImage procedure} { + .c delete all + .c create image 50 100 -image foo -tags image -anchor nw + update + set x {} + foo changed 2 4 6 8 40 50 + update + set x +} {{foo display 0 0 40 50 30 30}} +test canvImg-11.2 {ImageChangedProc procedure} { + .c delete all + image create test foo -variable x + .c create image 50 100 -image foo -tags image -anchor center + update + set x {} + foo changed 0 0 0 0 40 50 + .c bbox image +} {30 75 70 125} +test canvImg-11.3 {ImageChangedProc procedure} { + .c delete all + image create test foo -variable x + foo changed 0 0 0 0 40 50 + .c create image 50 100 -image foo -tags image -anchor nw + .c create image 70 110 -image foo2 -anchor nw + update + set y {} + image create test foo -variable x + update + set y +} {{foo2 display 0 0 20 40 50 40}} diff --git a/tests/canvPs.test b/tests/canvPs.test new file mode 100644 index 0000000..5ee56b9 --- /dev/null +++ b/tests/canvPs.test @@ -0,0 +1,105 @@ +# This file is a Tcl script to test out procedures to write postscript +# for canvases to files and channels. It exercises the procedure +# TkCanvPostscriptCmd in generic/tkCanvPs.c +# +# Copyright (c) 1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) canvPs.test 1.5 97/06/10 15:49:35 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +canvas .c -width 400 -height 300 -bd 2 -relief sunken +.c create rectangle 20 20 80 80 -fill red +pack .c +update + +test canvPs-1.1 {test writing to a file} {unixOrPc} { + removeFile foo.ps + .c postscript -file foo.ps + file exists foo.ps +} 1 +test canvPs-1.2 {test writing to a file, idempotency} {unixOrPc} { + removeFile foo.ps + removeFile bar.ps + .c postscript -file foo.ps + .c postscript -file bar.ps + set status ok + if {[file size bar.ps] != [file size foo.ps]} { + set status broken + } + set status +} ok + +test canvPs-2.1 {test writing to a channel} {unixOrPc} { + removeFile foo.ps + set chan [open foo.ps w] + fconfigure $chan -translation lf + .c postscript -channel $chan + close $chan + file exists foo.ps +} 1 +test canvPs-2.2 {test writing to channel, idempotency} {unixOrPc} { + removeFile foo.ps + removeFile bar.ps + set c1 [open foo.ps w] + set c2 [open bar.ps w] + fconfigure $c1 -translation lf + fconfigure $c2 -translation lf + .c postscript -channel $c1 + .c postscript -channel $c2 + close $c1 + close $c2 + set status ok + if {[file size bar.ps] != [file size foo.ps]} { + set status broken + } + set status +} ok +test canvPs-2.3 {test writing to channel and file, same output} {unixOnly} { + removeFile foo.ps + removeFile bar.ps + set c1 [open foo.ps w] + fconfigure $c1 -translation lf + .c postscript -channel $c1 + close $c1 + .c postscript -file bar.ps + set status ok + if {[file size foo.ps] != [file size bar.ps]} { + set status broken + } + set status +} ok +test canvPs-2.4 {test writing to channel and file, same output} {pcOnly} { + removeFile foo.ps + removeFile bar.ps + set c1 [open foo.ps w] + fconfigure $c1 -translation crlf + .c postscript -channel $c1 + close $c1 + .c postscript -file bar.ps + set status ok + if {[file size foo.ps] != [file size bar.ps]} { + set status broken + } + set status +} ok + +# Clean-up + +removeFile foo.ps +removeFile bar.ps + +foreach i [winfo children .] { + destroy $i +} diff --git a/tests/canvPsArc.tcl b/tests/canvPsArc.tcl new file mode 100644 index 0000000..333765a --- /dev/null +++ b/tests/canvPsArc.tcl @@ -0,0 +1,45 @@ +# This file creates a screen to exercise Postscript generation +# for bitmaps in canvases. It is part of the Tk visual test suite, +# which is invoked via the "visual" script. +# +# SCCS: @(#) canvPsArc.tcl 1.3 96/02/16 10:55:43 + +catch {destroy .t} +toplevel .t +wm title .t "Postscript Tests for Canvases" +wm iconname .t "Postscript" +wm geom .t +0+0 +wm minsize .t 1 1 + +set c .t.c + +message .t.m -text {This screen exercises the Postscript-generation abilities of Tk canvas widgets for arcs. Click on "Print" to print the canvas to your default printer. You can click on items in the canvas to delete them.} -width 6i +pack .t.m -side top -fill both + +frame .t.bot +pack .t.bot -side bottom -fill both +button .t.bot.quit -text Quit -command {destroy .t} +button .t.bot.print -text Print -command "lpr $c" +pack .t.bot.print .t.bot.quit -side left -pady 1m -expand 1 + +canvas $c -width 6i -height 6i -bd 2 -relief sunken +pack $c -expand yes -fill both -padx 2m -pady 2m + +$c create arc .5i .5i 2i 2i -style pieslice -start 20 -extent 90 \ + -fill black -outline {} +$c create arc 2.5i 0 4.5i 1i -style pieslice -start -45 -extent -135 \ + -fill {} -outline black -outlinestipple gray50 -width 3m +$c create arc 5.0i .5i 6.5i 2i -style pieslice -start 45 -extent 315 \ + -fill black -stipple gray25 -outline black -width 1m + +$c create arc -.5i 2.5i 2.0i 3.5i -style chord -start 90 -extent 270 \ + -fill black -outline {} +$c create arc 2.5i 2i 4i 6i -style chord -start 20 -extent 140 \ + -fill black -stipple gray50 -outline black -width 2m +$c create arc 4i 2.5i 8i 4.5i -style chord -start 60 -extent 60 \ + -fill {} -outline black + +$c create arc .5i 4.5i 2i 6i -style arc -start 135 -extent 315 -width 3m \ + -outline black -outlinestipple gray25 +$c create arc 3.5i 4.5i 5.5i 5.5i -style arc -start 45 -extent -90 -width 1m \ + -outline black diff --git a/tests/canvPsBmap.tcl b/tests/canvPsBmap.tcl new file mode 100644 index 0000000..385e998 --- /dev/null +++ b/tests/canvPsBmap.tcl @@ -0,0 +1,71 @@ +# This file creates a screen to exercise Postscript generation +# for bitmaps in canvases. It is part of the Tk visual test suite, +# which is invoked via the "visual" script. +# +# SCCS: @(#) canvPsBmap.tcl 1.5 96/07/25 15:54:14 + +catch {destroy .t} +toplevel .t +wm title .t "Postscript Tests for Canvases" +wm iconname .t "Postscript" +wm geom .t +0+0 +wm minsize .t 1 1 + +set c .t.c + +message .t.m -text {This screen exercises the Postscript-generation abilities of Tk canvas widgets for bitmaps. Click on "Print" to print the canvas to your default printer. You can click on items in the canvas to delete them.} -width 6i +pack .t.m -side top -fill both + +frame .t.bot +pack .t.bot -side bottom -fill both +button .t.bot.quit -text Quit -command {destroy .t} +button .t.bot.print -text Print -command "lpr $c" +pack .t.bot.print .t.bot.quit -side left -pady 1m -expand 1 + +canvas $c -width 6i -height 6i -bd 2 -relief sunken +pack $c -expand yes -fill both -padx 2m -pady 2m + +$c create bitmap 0.5i 0.5i \ + -bitmap @[file join $tk_library demos/images/flagdown.bmp] \ + -background {} -foreground black -anchor nw +$c create rect 0.47i 0.47i 0.53i 0.53i -fill {} -outline black + +$c create bitmap 3.0i 0.5i \ + -bitmap @[file join $tk_library demos/images/flagdown.bmp] \ + -background {} -foreground black -anchor n +$c create rect 2.97i 0.47i 3.03i 0.53i -fill {} -outline black + +$c create bitmap 5.5i 0.5i \ + -bitmap @[file join $tk_library demos/images/flagdown.bmp] \ + -background black -foreground white -anchor ne +$c create rect 5.47i 0.47i 5.53i 0.53i -fill {} -outline black + +$c create bitmap 0.5i 3.0i \ + -bitmap @[file join $tk_library demos/images/face.bmp] \ + -background {} -foreground black -anchor w +$c create rect 0.47i 2.97i 0.53i 3.03i -fill {} -outline black + +$c create bitmap 3.0i 3.0i \ + -bitmap @[file join $tk_library demos/images/face.bmp] \ + -background {} -foreground black -anchor center +$c create rect 2.97i 2.97i 3.03i 3.03i -fill {} -outline black + +$c create bitmap 5.5i 3.0i \ + -bitmap @[file join $tk_library demos/images/face.bmp] \ + -background blue -foreground black -anchor e +$c create rect 5.47i 2.97i 5.53i 3.03i -fill {} -outline black + +$c create bitmap 0.5i 5.5i \ + -bitmap @[file join $tk_library demos/images/flagup.bmp] \ + -background black -foreground white -anchor sw +$c create rect 0.47i 5.47i 0.53i 5.53i -fill {} -outline black + +$c create bitmap 3.0i 5.5i \ + -bitmap @[file join $tk_library demos/images/flagup.bmp] \ + -background green -foreground white -anchor s +$c create rect 2.97i 5.47i 3.03i 5.53i -fill {} -outline black + +$c create bitmap 5.5i 5.5i \ + -bitmap @[file join $tk_library demos/images/flagup.bmp] \ + -background {} -foreground black -anchor se +$c create rect 5.47i 5.47i 5.53i 5.53i -fill {} -outline black diff --git a/tests/canvPsGrph.tcl b/tests/canvPsGrph.tcl new file mode 100644 index 0000000..55b90d7 --- /dev/null +++ b/tests/canvPsGrph.tcl @@ -0,0 +1,87 @@ +# This file creates a screen to exercise Postscript generation +# for some of the graphical objects in canvases. It is part of the Tk +# visual test suite, which is invoked via the "visual" script. +# +# SCCS: @(#) canvPsGrph.tcl 1.3 96/02/16 10:56:07 + +catch {destroy .t} +toplevel .t +wm title .t "Postscript Tests for Canvases" +wm iconname .t "Postscript" +wm geom .t +0+0 +wm minsize .t 1 1 + +set c .t.mid.c + +message .t.m -text {This screen exercises the Postscript-generation abilities of Tk canvas widgets. Select what you want to display with the buttons below, then click on "Print" to print it to your default printer. You can click on items in the canvas to delete them.} -width 4i +pack .t.m -side top -fill both + +frame .t.top +pack .t.top -side top -fill both +set what rect +radiobutton .t.top.rect -text Rectangles -variable what -value rect \ + -command "mkObjs $c" -relief flat +radiobutton .t.top.oval -text Ovals -variable what -value oval \ + -command "mkObjs $c" -relief flat +radiobutton .t.top.poly -text Polygons -variable what -value poly \ + -command "mkObjs $c" -relief flat +radiobutton .t.top.line -text Lines -variable what -value line \ + -command "mkObjs $c" -relief flat +pack .t.top.rect .t.top.oval .t.top.poly .t.top.line \ + -side left -pady 2m -ipadx 2m -ipady 1m -expand 1 + +frame .t.bot +pack .t.bot -side bottom -fill both +button .t.bot.quit -text Quit -command {destroy .t} +button .t.bot.print -text Print -command "lpr $c" +pack .t.bot.print .t.bot.quit -side left -pady 1m -expand 1 + +frame .t.mid -relief sunken -bd 2 +pack .t.mid -side top -expand yes -fill both -padx 2m -pady 2m +canvas $c -width 400 -height 350 -bd 0 -relief sunken +pack $c -expand yes -fill both -padx 1 -pady 1 + +proc mkObjs c { + global what + $c delete all + if {$what == "rect"} { + $c create rect 0 0 400 350 -outline black + $c create rect 2 2 100 50 -fill black -stipple gray25 + $c create rect -20 180 80 320 -fill black -stipple gray50 -width .5c + $c create rect 200 -20 240 20 -fill black + $c create rect 380 200 420 240 -fill black + $c create rect 200 330 240 370 -fill black + } + + if {$what == "oval"} { + $c create oval 50 10 150 80 -fill black -stipple gray25 -outline {} + $c create oval 100 100 200 150 -outline {} -fill black -stipple gray50 + $c create oval 250 100 400 300 -width .5c + } + + if {$what == "poly"} { + $c create poly 100 200 200 50 300 200 -smooth yes -stipple gray25 \ + -outline black -width 4 + $c create poly 100 300 100 250 350 250 350 300 350 300 100 300 100 300 \ + -fill red -smooth yes + $c create poly 20 10 40 10 40 60 80 60 80 25 30 25 30 \ + 35 50 35 50 45 20 45 + $c create poly 300 20 300 120 380 80 320 100 -fill blue -outline black + $c create poly 20 200 100 220 90 100 40 250 \ + -fill {} -outline brown -width 3 + } + + if {$what == "line"} { + $c create line 20 20 120 20 -arrow both -width 5 + $c create line 20 80 150 80 20 200 150 200 -smooth yes + $c create line 150 20 150 150 250 150 -width .5c -smooth yes \ + -arrow both -arrowshape {.75c 1.0c .5c} -stipple gray25 + $c create line 50 340 100 250 150 340 -join round -cap round -width 10 + $c create line 200 340 250 250 300 340 -join bevel -cap project \ + -width 10 + $c create line 300 20 380 20 300 150 380 150 -join miter -cap butt \ + -width 10 -stipple gray25 + } +} + +mkObjs $c diff --git a/tests/canvPsText.tcl b/tests/canvPsText.tcl new file mode 100644 index 0000000..8bcc713 --- /dev/null +++ b/tests/canvPsText.tcl @@ -0,0 +1,83 @@ +# This file creates a screen to exercise Postscript generation +# for text in canvases. It is part of the Tk visual test suite, +# which is invoked via the "visual" script. +# +# SCCS: @(#) canvPsText.tcl 1.3 96/06/24 16:49:12 + +catch {destroy .t} +toplevel .t +wm title .t "Postscript Tests for Canvases" +wm iconname .t "Postscript" +wm geom .t +0+0 +wm minsize .t 1 1 + +set c .t.c + +message .t.m -text {This screen exercises the Postscript-generation abilities of Tk canvas widgets for text. Click on "Print" to print the canvas to your default printer. The "Stipple" button can be used to turn stippling on and off for the text, but beware: many Postscript printers cannot handle stippled text. You can click on items in the canvas to delete them.} -width 6i +pack .t.m -side top -fill both + +set stipple {} +checkbutton .t.stipple -text Stippling -variable stipple -onvalue gray50 \ + -offvalue {} -command "setStipple $c" -relief flat +pack .t.stipple -side top -pady 2m -expand 1 -anchor w + +frame .t.bot +pack .t.bot -side bottom -fill both +button .t.bot.quit -text Quit -command {destroy .t} +button .t.bot.print -text Print -command "lpr $c" +pack .t.bot.print .t.bot.quit -side left -pady 1m -expand 1 + +canvas $c -width 6i -height 7i -bd 2 -relief sunken +pack $c -expand yes -fill both -padx 2m -pady 2m + +$c create rect 2.95i 0.45i 3.05i 0.55i -fill {} -outline black +$c create text 3.0i 0.5i -text "Center Courier Oblique 24" \ + -anchor center -tags text -font {Courier 24 italic} -stipple $stipple +$c create rect 2.95i 0.95i 3.05i 1.05i -fill {} -outline black +$c create text 3.0i 1.0i -text "Northwest Helvetica 24" \ + -anchor nw -tags text -font {Helvetica 24} -stipple $stipple +$c create rect 2.95i 1.45i 3.05i 1.55i -fill {} -outline black +$c create text 3.0i 1.5i -text "North Helvetica Oblique 12 " \ + -anchor n -tags text -font {Helvetica 12 italic} -stipple $stipple +$c create rect 2.95i 1.95i 3.05i 2.05i -fill {} -outline blue +$c create text 3.0i 2.0i -text "Northeast Helvetica Bold 24" \ + -anchor ne -tags text -font {Helvetica 24 bold} -stipple $stipple +$c create rect 2.95i 2.45i 3.05i 2.55i -fill {} -outline black +$c create text 3.0i 2.5i -text "East Helvetica Bold Oblique 18" \ + -anchor e -tags text -font {Helvetica 18 {bold italic}} -stipple $stipple +$c create rect 2.95i 2.95i 3.05i 3.05i -fill {} -outline black +$c create text 3.0i 3.0i -text "Southeast Times 10" \ + -anchor se -tags text -font {Times 10} -stipple $stipple +$c create rect 2.95i 3.45i 3.05i 3.55i -fill {} -outline black +$c create text 3.0i 3.5i -text "South Times Italic 24" \ + -anchor s -tags text -font {Times 24 italic} -stipple $stipple +$c create rect 2.95i 3.95i 3.05i 4.05i -fill {} -outline black +$c create text 3.0i 4.0i -text "Southwest Times Bold 18" \ + -anchor sw -tags text -font {Times 18 bold} -stipple $stipple +$c create rect 2.95i 4.45i 3.05i 4.55i -fill {} -outline black +$c create text 3.0i 4.5i -text "West Times Bold Italic 24"\ + -anchor w -tags text -font {Times 24 {bold italic}} -stipple $stipple + +$c create rect 0.95i 5.20i 1.05i 5.30i -fill {} -outline black +$c create text 1.0i 5.25i -width 1.9i -anchor c -justify left -tags text \ + -font {Times 18 bold} -stipple $stipple \ + -text "This is a sample text item to see how left justification works" +$c create rect 2.95i 5.20i 3.05i 5.30i -fill {} -outline black +$c create text 3.0i 5.25i -width 1.8i -anchor c -justify center -tags text \ + -font {Times 18 bold} -stipple $stipple \ + -text "This is a sample text item to see how center justification works" +$c create rect 4.95i 5.20i 5.05i 5.30i -fill {} -outline black +$c create text 5.0i 5.25i -width 1.8i -anchor c -justify right -tags text \ + -font {Times 18 bold} -stipple $stipple \ + -text "This is a sample text item to see how right justification works" + +$c create text 3.0i 6.0i -width 5.0i -anchor n -justify right -tags text \ + -text "This text is\nright justified\nwith a line length equal to\n\ + the size of the enclosing rectangle.\nMake sure it prints right\ + justified as well." +$c create rect 0.5i 6.0i 5.5i 6.9i -fill {} -outline black + +proc setStipple c { + global stipple + $c itemconfigure text -stipple $stipple +} diff --git a/tests/canvRect.test b/tests/canvRect.test new file mode 100644 index 0000000..e910906 --- /dev/null +++ b/tests/canvRect.test @@ -0,0 +1,329 @@ +# This file is a Tcl script to test out the procedures in tkRectOval.c, +# which implement canvas "rectangle" and "oval" items. It is organized +# in the standard fashion for Tcl tests. +# +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) canvRect.test 1.18 97/08/06 15:33:39 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +canvas .c -width 400 -height 300 -bd 2 -relief sunken +pack .c +bind .c <1> { + puts "button down at (%x,%y)" +} +update + +set i 1 +.c create rectangle 20 20 80 80 -tag test +foreach test { + {-fill #ff0000 #ff0000 non-existent {unknown color name "non-existent"}} + {-outline #123456 #123456 bad_color {unknown color name "bad_color"}} + {-stipple gray50 gray50 bogus {bitmap "bogus" not defined}} + {-tags {test a b c} {test a b c} {} {}} + {-width 6 6 abc {bad screen distance "abc"}} +} { + set name [lindex $test 0] + test canvRect-1.$i {configuration options} { + .c itemconfigure test $name [lindex $test 1] + list [lindex [.c itemconfigure test $name] 4] [.c itemcget test $name] + } [list [lindex $test 2] [lindex $test 2]] + incr i + if {[lindex $test 3] != ""} { + test canvRect-1.$i {configuration options} { + list [catch {.c itemconfigure test $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + incr i +} +test canvRect-1.$i {configuration options} { + .c itemconfigure test -tags {test xyz} + .c itemcget xyz -tags +} {test xyz} + +test canvRect-2.1 {CreateRectOval procedure} { + list [catch {.c create rect} msg] $msg +} {1 {wrong # args: should be ".c create rectangle x1 y1 x2 y2 ?options?"}} +test canvRect-2.2 {CreateRectOval procedure} { + list [catch {.c create oval x y z} msg] $msg +} {1 {wrong # args: should be ".c create oval x1 y1 x2 y2 ?options?"}} +test canvRect-2.3 {CreateRectOval procedure} { + list [catch {.c create rectangle x 2 3 4} msg] $msg +} {1 {bad screen distance "x"}} +test canvRect-2.4 {CreateRectOval procedure} { + list [catch {.c create rectangle 1 y 3 4} msg] $msg +} {1 {bad screen distance "y"}} +test canvRect-2.5 {CreateRectOval procedure} { + list [catch {.c create rectangle 1 2 z 4} msg] $msg +} {1 {bad screen distance "z"}} +test canvRect-2.6 {CreateRectOval procedure} { + list [catch {.c create rectangle 1 2 3 q} msg] $msg +} {1 {bad screen distance "q"}} +test canvRect-2.7 {CreateRectOval procedure} { + .c create rectangle 1 2 3 4 -tags x + set result {} + foreach element [.c coords x] { + lappend result [format %.1f $element] + } + set result +} {1.0 2.0 3.0 4.0} +test canvRect-2.8 {CreateRectOval procedure} { + list [catch {.c create rectangle 1 2 3 4 -gorp foo} msg] $msg +} {1 {unknown option "-gorp"}} + +.c delete withtag all +.c create rectangle 10 20 30 40 -tags x +test canvRect-3.1 {RectOvalCoords procedure} { + set result {} + foreach element [.c coords x] { + lappend result [format %.1f $element] + } + set result +} {10.0 20.0 30.0 40.0} +test canvRect-3.2 {RectOvalCoords procedure} { + list [catch {.c coords x a 2 3 4} msg] $msg +} {1 {bad screen distance "a"}} +test canvRect-3.3 {RectOvalCoords procedure} { + list [catch {.c coords x 1 b 3 4} msg] $msg +} {1 {bad screen distance "b"}} +test canvRect-3.4 {RectOvalCoords procedure} { + list [catch {.c coords x 1 2 c 4} msg] $msg +} {1 {bad screen distance "c"}} +test canvRect-3.5 {RectOvalCoords procedure} { + list [catch {.c coords x 1 2 3 d} msg] $msg +} {1 {bad screen distance "d"}} +test canvRect-3.6 {RectOvalCoords procedure} {nonPortable} { + # Non-portable due to rounding differences. + .c coords x 10 25 15 40 + .c bbox x +} {9 24 16 41} +test canvRect-3.7 {RectOvalCoords procedure} { + list [catch {.c coords x 1 2 3 4 5} msg] $msg +} {1 {wrong # coordinates: expected 0 or 4, got 5}} + +.c delete withtag all +.c create rectangle 10 20 30 40 -tags x -width 1 +test canvRect-4.1 {ConfigureRectOval procedure} { + list [catch {.c itemconfigure x -width abc} msg] $msg \ + [.c itemcget x -width] +} {1 {bad screen distance "abc"} 1} +test canvRect-4.2 {ConfigureRectOval procedure} { + .c itemconfigure x -width -5 + .c itemcget x -width +} {1} +test canvRect-4.3 {ConfigureRectOval procedure} {nonPortable} { + # Non-portable due to rounding differences. + .c itemconfigure x -width 10 + .c bbox x +} {5 15 35 45} +# I can't come up with any good tests for DeleteRectOval. + +.c delete withtag all +.c create rectangle 10 20 30 40 -tags x -width 1 -outline {} +test canvRect-5.1 {ComputeRectOvalBbox procedure} {nonPortable} { + # Non-portable due to rounding differences: + .c coords x 20 15 10 5 + .c bbox x +} {10 5 20 15} +test canvRect-5.2 {ComputeRectOvalBbox procedure} {nonPortable} { + # Non-portable due to rounding differences: + .c coords x 10 20 30 10 + .c itemconfigure x -width 1 -outline red + .c bbox x +} {9 9 31 21} +test canvRect-5.3 {ComputeRectOvalBbox procedure} {nonPortable} { + # Non-portable due to rounding differences: + .c coords x 10 20 30 10 + .c itemconfigure x -width 2 -outline red + .c bbox x +} {9 9 31 21} +test canvRect-5.4 {ComputeRectOvalBbox procedure} {nonPortable} { + # Non-portable due to rounding differences: + .c coords x 10 20 30 10 + .c itemconfigure x -width 3 -outline red + .c bbox x +} {8 8 32 22} + +# I can't come up with any good tests for DisplayRectOval. + +.c delete withtag all +set x [.c create rectangle 10 20 30 35 -tags x -fill green] +set y [.c create rectangle 15 25 25 30 -tags y -fill red] +test canvRect-6.1 {RectToPoint procedure} { + .c itemconfigure y -outline {} + list [.c find closest 14.9 28] [.c find closest 15.1 28] \ + [.c find closest 24.9 28] [.c find closest 25.1 28] +} "$x $y $y $x" +test canvRect-6.2 {RectToPoint procedure} { + .c itemconfigure y -outline {} + list [.c find closest 20 24.9] [.c find closest 20 25.1] \ + [.c find closest 20 29.9] [.c find closest 20 30.1] +} "$x $y $y $x" +test canvRect-6.3 {RectToPoint procedure} { + .c itemconfigure y -width 1 -outline black + list [.c find closest 14.4 28] [.c find closest 14.6 28] \ + [.c find closest 25.4 28] [.c find closest 25.6 28] +} "$x $y $y $x" +test canvRect-6.4 {RectToPoint procedure} { + .c itemconfigure y -width 1 -outline black + list [.c find closest 20 24.4] [.c find closest 20 24.6] \ + [.c find closest 20 30.4] [.c find closest 20 30.6] +} "$x $y $y $x" +.c itemconfigure x -fill {} -outline black -width 3 +.c itemconfigure y -outline {} +test canvRect-6.5 {RectToPoint procedure} { + list [.c find closest 13.2 28] [.c find closest 13.3 28] \ + [.c find closest 26.7 28] [.c find closest 26.8 28] +} "$x $y $y $x" +test canvRect-6.6 {RectToPoint procedure} { + list [.c find closest 20 23.2] [.c find closest 20 23.3] \ + [.c find closest 20 31.7] [.c find closest 20 31.8] +} "$x $y $y $x" +.c delete withtag all +set x [.c create rectangle 10 20 30 40 -outline {} -fill black] +set y [.c create rectangle 40 40 50 50 -outline {} -fill black] +test canvRect-6.7 {RectToPoint procedure} { + list [.c find closest 35 35] [.c find closest 36 36] \ + [.c find closest 37 37] [.c find closest 38 38] +} "$x $y $y $y" + +.c delete withtag all +set x [.c create rectangle 10 20 30 35 -fill green -outline {}] +set y [.c create rectangle 40 45 60 70 -fill red -outline black -width 3] +set z [.c create rectangle 100 150 120 170 -fill {} -outline black -width 3] +test canvRect-7.1 {RectToArea procedure} { + list [.c find overlapping 20 50 38 60] \ + [.c find overlapping 20 50 39 60] \ + [.c find overlapping 20 50 70 60] \ + [.c find overlapping 61 50 70 60] \ + [.c find overlapping 62 50 70 60] +} "{} $y $y $y {}" +test canvRect-7.2 {RectToArea procedure} { + list [.c find overlapping 45 20 55 43] \ + [.c find overlapping 45 20 55 44] \ + [.c find overlapping 45 20 55 80] \ + [.c find overlapping 45 71 55 80] \ + [.c find overlapping 45 72 55 80] +} "{} $y $y $y {}" +test canvRect-7.3 {RectToArea procedure} { + list [.c find overlapping 5 25 9.9 30] [.c find overlapping 5 25 10.1 30] +} "{} $x" +test canvRect-7.4 {RectToArea procedure} { + list [.c find overlapping 102 152 118 168] \ + [.c find overlapping 101 152 118 168] \ + [.c find overlapping 102 151 118 168] \ + [.c find overlapping 102 152 119 168] \ + [.c find overlapping 102 152 118 169] +} "{} $z $z $z $z" +test canvRect-7.5 {RectToArea procedure} { + list [.c find enclosed 20 40 38 80] \ + [.c find enclosed 20 40 39 80] \ + [.c find enclosed 20 40 70 80] \ + [.c find enclosed 61 40 70 80] \ + [.c find enclosed 62 40 70 80] +} "{} {} $y {} {}" +test canvRect-7.6 {RectToArea procedure} { + list [.c find enclosed 20 20 65 43] \ + [.c find enclosed 20 20 65 44] \ + [.c find enclosed 20 20 65 80] \ + [.c find enclosed 20 71 65 80] \ + [.c find enclosed 20 72 65 80] +} "{} {} $y {} {}" + +.c delete withtag all +set x [.c create oval 50 100 200 150 -fill green -outline {}] +set y [.c create oval 50 100 200 150 -fill red -outline black -width 3] +set z [.c create oval 50 100 200 150 -fill {} -outline black -width 3] +test canvRect-8.1 {OvalToArea procedure} { + list [.c find overlapping 20 120 48 130] \ + [.c find overlapping 20 120 49 130] \ + [.c find overlapping 20 120 50.2 130] \ + [.c find overlapping 20 120 300 130] \ + [.c find overlapping 60 120 190 130] \ + [.c find overlapping 199.9 120 300 130] \ + [.c find overlapping 201 120 300 130] \ + [.c find overlapping 202 120 300 130] +} "{} {$y $z} {$x $y $z} {$x $y $z} {$x $y} {$x $y $z} {$y $z} {}" +test canvRect-8.2 {OvalToArea procedure} { + list [.c find overlapping 100 50 150 98] \ + [.c find overlapping 100 50 150 99] \ + [.c find overlapping 100 50 150 100.1] \ + [.c find overlapping 100 50 150 200] \ + [.c find overlapping 100 110 150 140] \ + [.c find overlapping 100 149.9 150 200] \ + [.c find overlapping 100 151 150 200] \ + [.c find overlapping 100 152 150 200] +} "{} {$y $z} {$x $y $z} {$x $y $z} {$x $y} {$x $y $z} {$y $z} {}" +test canvRect-8.3 {OvalToArea procedure} { + list [.c find overlapping 176 104 177 105] \ + [.c find overlapping 187 116 188 117] \ + [.c find overlapping 192 142 193 143] \ + [.c find overlapping 180 138 181 139] \ + [.c find overlapping 61 142 62 143] \ + [.c find overlapping 65 137 66 136] \ + [.c find overlapping 62 108 63 109] \ + [.c find overlapping 68 115 69 116] +} "{} {$x $y} {} {$x $y} {} {$x $y} {} {$x $y}" + +test canvRect-9.1 {ScaleRectOval procedure} { + .c delete withtag all + .c create rect 100 300 200 350 -tags x + .c scale x 50 100 2 4 + .c coords x +} {150.0 900.0 350.0 1100.0} + +test canvRect-10.1 {TranslateRectOval procedure} { + .c delete withtag all + .c create rect 100 300 200 350 -tags x + .c move x 100 -10 + .c coords x +} {200.0 290.0 300.0 340.0} + +# This test is non-portable because different color information +# will get generated on different displays (e.g. mono displays +# vs. color). +test canvRect-11.1 {RectOvalToPostscript procedure} {nonPortable win32sCrash macCrash} { + # Crashes on Mac because the XGetImage() call isn't implemented, causing a + # dereference of NULL. + + .c configure -bd 0 -highlightthickness 0 + .c delete withtag all + .c create rect 50 60 90 80 -fill black -stipple gray50 -outline {} + .c create oval 100 150 200 200 -fill {} -outline #ff0000 -width 5 + update + set x [.c postscript] + string range $x [string first "-200 -150 translate" $x] end +} {-200 -150 translate +0 300 moveto 400 300 lineto 400 0 lineto 0 0 lineto closepath clip newpath +gsave +50 240 moveto 40 0 rlineto 0 -20 rlineto -40 0 rlineto closepath +0.000 0.000 0.000 setrgbcolor AdjustColor +clip 16 16 <5555aaaa5555aaaa5555aaaa5555aaaa5555aaaa5555aaaa5555aaaa5555 +aaaa> StippleFill +grestore +gsave +matrix currentmatrix +150 125 translate 50 25 scale 1 0 moveto 0 0 1 0 360 arc +setmatrix +5 setlinewidth 0 setlinejoin 2 setlinecap +1.000 0.000 0.000 setrgbcolor AdjustColor +stroke +grestore +restore showpage + +%%Trailer +end +%%EOF +} diff --git a/tests/canvText.test b/tests/canvText.test new file mode 100644 index 0000000..b121c25 --- /dev/null +++ b/tests/canvText.test @@ -0,0 +1,492 @@ +# This file is a Tcl script to test out the procedures in tkCanvText.c, +# which implement canvas "text" items. It is organized in the standard +# fashion for Tcl tests. +# +# Copyright (c) 1996-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) canvText.test 1.8 97/06/24 13:34:16 + +if {"[info procs test]" != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +canvas .c -width 400 -height 300 -bd 2 -relief sunken +pack .c +update + +set i 1 +.c create text 20 20 -tag test + +set font "-adobe-times-medium-r-normal--*-200-*-*-*-*-*-*" +set ay [font metrics $font -linespace] +set ax [font measure $font 0] + + +foreach test { + {-anchor nw nw xyz {bad anchor position "xyz": must be n, ne, e, se, s, sw, w, nw, or center}} + {-fill #ff0000 #ff0000 xyz {unknown color name "xyz"}} + {-font {Times 40} {Times 40} {} {font "" doesn't exist}} + {-justify left left xyz {bad justification "xyz": must be left, right, or center}} + {-stipple gray50 gray50 xyz {bitmap "xyz" not defined}} + {-tags {test a b c} {test a b c} {} {}} + {-text xyz xyz {} {}} + {-width 6 6 xyz {bad screen distance "xyz"}} +} { + set name [lindex $test 0] + test canvText-1.$i {configuration options} { + .c itemconfigure test $name [lindex $test 1] + list [lindex [.c itemconfigure test $name] 4] [.c itemcget test $name] + } [list [lindex $test 2] [lindex $test 2]] + incr i + if {[lindex $test 3] != ""} { + test canvText-1.$i {configuration options} { + list [catch {.c itemconfigure test $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + incr i +} +test canvText-1.$i {configuration options} { + .c itemconfigure test -tags {test xyz} + .c itemcget xyz -tags +} {test xyz} + +.c delete test +.c create text 20 20 -tag test + +test canvText-2.1 {CreateText procedure: args} { + list [catch {.c create text} msg] $msg +} {1 {wrong # args: should be ".c create text x y ?options?"}} +test canvText-2.2 {CreateText procedure: args} { + list [catch {.c create text xyz 0} msg] $msg +} {1 {bad screen distance "xyz"}} +test canvText-2.3 {CreateText procedure: args} { + list [catch {.c create text 0 xyz} msg] $msg +} {1 {bad screen distance "xyz"}} +test canvText-2.4 {CreateText procedure: args} { + list [catch {.c create text 0 0 -xyz xyz} msg] $msg +} {1 {unknown option "-xyz"}} +test canvText-2.5 {CreateText procedure} { + .c create text 0 0 -tags x + set x [.c coords x] + .c delete x + set x +} {0.0 0.0} + +focus -force .c +.c focus test +.c coords test 0 0 +update + +test canvText-3.1 {TextCoords procedure} { + .c coords test +} {0.0 0.0} +test canvText-3.2 {TextCoords procedure} { + list [catch {.c coords test xyz 0} msg] $msg +} {1 {bad screen distance "xyz"}} +test canvText-3.3 {TextCoords procedure} { + list [catch {.c coords test 0 xyz} msg] $msg +} {1 {bad screen distance "xyz"}} +test canvText-3.4 {TextCoords procedure} { + .c coords test 10 10 + set result {} + foreach element [.c coords test] { + lappend result [format %.1f $element] + } + set result +} {10.0 10.0} +test canvText-3.5 {TextCoords procedure} { + list [catch {.c coords test 10} msg] $msg +} {1 {wrong # coordinates: expected 0 or 2, got 1}} +test canvText-3.6 {TextCoords procedure} { + list [catch {.c coords test 10 10 10} msg] $msg +} {1 {wrong # coordinates: expected 0 or 2, got 3}} + +test canvText-4.1 {ConfigureText procedure} { + list [catch {.c itemconfig test -fill xyz} msg] $msg +} {1 {unknown color name "xyz"}} +test canvText-4.2 {ConfigureText procedure} { + .c itemconfig test -fill blue + .c itemcget test -fill +} {blue} +test canvText-4.3 {ConfigureText procedure: construct font gcs} { + .c itemconfig test -font "times 20" -fill black -stipple gray50 + list [.c itemcget test -font] [.c itemcget test -fill] [.c itemcget test -stipple] +} {{times 20} black gray50} +test canvText-4.4 {ConfigureText procedure: construct cursor gc} { + .c itemconfig test -text "abcdefg" + .c select from test 2 + .c select to test 4 + .c icursor test 3 + + # Both black -> cursor becomes white. + .c config -insertbackground black + .c config -selectbackground black + .c itemconfig test -just left + update + + # Both same color (and not black) -> cursor becomes black. + .c config -insertbackground red + .c config -selectbackground red + .c itemconfig test -just left + update +} {} +test canvText-4.5 {ConfigureText procedure: adjust selection} { + set x {} + .c itemconfig test -text "abcdefghi" + .c select from test 2 + .c select to test 6 + lappend x [selection get] + .c dchars test 1 end + lappend x [catch {selection get}] + .c insert test end "bcdefghi" + .c select from test 2 + .c select to test 6 + lappend x [selection get] + .c dchars test 4 end + lappend x [selection get] + .c insert test end "efghi" + .c select from test 6 + .c select to test 2 + lappend x [selection get] + .c dchars test 4 end + lappend x [selection get] +} {cdefg 1 cdefg cd cdef cd} +test canvText-4.6 {ConfigureText procedure: adjust cursor} { + .c itemconfig test -text "abcdefghi" + set x {} + .c icursor test 6 + .c dchars test 4 end + .c index test insert +} {4} + +test canvText-5.1 {ConfigureText procedure: adjust cursor} { + .c create text 10 10 -tag x -fill blue -font "times 40" -stipple gray50 -text "xyz" + .c delete x +} {} + +test canvText-6.1 {ComputeTextBbox procedure} {fonts} { + .c itemconfig test -font $font -text 0 + .c coords test 0 0 + set x {} + lappend x [.c itemconfig test -anchor n; .c bbox test] + lappend x [.c itemconfig test -anchor nw; .c bbox test] + lappend x [.c itemconfig test -anchor w; .c bbox test] + lappend x [.c itemconfig test -anchor sw; .c bbox test] + lappend x [.c itemconfig test -anchor s; .c bbox test] + lappend x [.c itemconfig test -anchor se; .c bbox test] + lappend x [.c itemconfig test -anchor e; .c bbox test] + lappend x [.c itemconfig test -anchor ne; .c bbox test] + lappend x [.c itemconfig test -anchor center; .c bbox test] +} "{[expr -$ax/2-1] 0 [expr $ax/2+1] $ay}\ +{-1 0 [expr $ax+1] $ay}\ +{-1 [expr -$ay/2] [expr $ax+1] [expr $ay/2]}\ +{-1 -$ay [expr $ax+1] 0}\ +{[expr -$ax/2-1] -$ay [expr $ax/2+1] 0}\ +{[expr -$ax-1] -$ay 1 0}\ +{[expr -$ax-1] [expr -$ay/2] 1 [expr $ay/2]}\ +{[expr -$ax-1] 0 1 $ay}\ +{[expr -$ax/2-1] [expr -$ay/2] [expr $ax/2+1] [expr $ay/2]}" + +focus .c +.c focus test +.c itemconfig test -text "abcd\nefghi\njklmnopq" +test canvText-7.1 {DisplayText procedure: stippling} { + .c itemconfig test -stipple gray50 + update + .c itemconfig test -stipple {} + update +} {} +test canvText-7.2 {DisplayText procedure: draw selection} { + .c select from test 0 + .c select to test end + update + selection get +} "abcd\nefghi\njklmnopq" +test canvText-7.3 {DisplayText procedure: selection} { + .c select from test 0 + .c select to test end + update + selection get +} "abcd\nefghi\njklmnopq" +test canvText-7.4 {DisplayText procedure: one line selection} { + .c select from test 2 + .c select to test 3 + update +} {} +test canvText-7.5 {DisplayText procedure: multi-line selection} { + .c select from test 2 + .c select to test 12 + update +} {} +test canvText-7.6 {DisplayText procedure: draw cursor} { + .c icursor test 3 + update +} {} +test canvText-7.7 {DisplayText procedure: selected text different color} { + .c config -selectforeground blue + .c itemconfig test -anchor n + update +} {} +test canvText-7.8 {DisplayText procedure: not selected} { + .c select clear + update +} {} + +test canvText-8.1 {TextInsert procedure: 0 length insert} { + .c insert test end {} +} {} +test canvText-8.2 {TextInsert procedure: before beginning/after end} { + # Can't test this because GetTextIndex filters out those numbers. +} {} +test canvText-8.3 {TextInsert procedure: inserting in a selected item} { + .c itemconfig test -text "abcdefg" + .c select from test 2 + .c select to test 4 + .c insert test 1 "xyz" + .c itemcget test -text +} {axyzbcdefg} +test canvText-8.4 {TextInsert procedure: inserting before selection} { + .c itemconfig test -text "abcdefg" + .c select from test 2 + .c select to test 4 + .c insert test 1 "xyz" + list [.c index test sel.first] [.c index test sel.last] +} {5 7} +test canvText-8.5 {TextInsert procedure: inserting in selection} { + .c itemconfig test -text "abcdefg" + .c select from test 2 + .c select to test 4 + .c insert test 3 "xyz" + list [.c index test sel.first] [.c index test sel.last] +} {2 7} +test canvText-8.6 {TextInsert procedure: inserting after selection} { + .c itemconfig test -text "abcdefg" + .c select from test 2 + .c select to test 4 + .c insert test 5 "xyz" + list [.c index test sel.first] [.c index test sel.last] +} {2 4} +test canvText-8.7 {TextInsert procedure: inserting in unselected item} { + .c itemconfig test -text "abcdefg" + .c select clear + .c insert test 5 "xyz" + .c itemcget test -text +} {abcdexyzfg} +test canvText-8.8 {TextInsert procedure: inserting before cursor} { + .c itemconfig test -text "abcdefg" + .c icursor test 3 + .c insert test 2 "xyz" + .c index test insert +} {6} +test canvText-8.9 {TextInsert procedure: inserting after cursor} { + .c itemconfig test -text "abcdefg" + .c icursor test 3 + .c insert test 4 "xyz" + .c index test insert +} {3} + +test canvText-9.1 {TextInsert procedure: before beginning/after end} { + # Can't test this because GetTextIndex filters out those numbers. +} {} +test canvText-9.2 {TextInsert procedure: start > end} { + .c itemconfig test -text "abcdefg" + .c dchars test 4 2 + .c itemcget test -text +} {abcdefg} +test canvText-9.3 {TextInsert procedure: deleting from a selected item} { + .c itemconfig test -text "abcdefg" + .c select from test 2 + .c select to test 4 + .c dchars test 3 5 + .c itemcget test -text +} {abcg} +test canvText-9.4 {TextInsert procedure: deleting before start} { + .c itemconfig test -text "abcdefghijk" + .c select from test 4 + .c select to test 8 + .c dchars test 1 1 + list [.c index test sel.first] [.c index test sel.last] +} {3 7} +test canvText-9.5 {TextInsert procedure: keep start > first char deleted} { + .c itemconfig test -text "abcdefghijk" + .c select from test 4 + .c select to test 8 + .c dchars test 2 6 + list [.c index test sel.first] [.c index test sel.last] +} {2 3} +test canvText-9.6 {TextInsert procedure: deleting inside selection} { + .c itemconfig test -text "abcdefghijk" + .c select from test 4 + .c select to test 8 + .c dchars test 6 6 + list [.c index test sel.first] [.c index test sel.last] +} {4 7} +test canvText-9.7 {TextInsert procedure: keep end > first char deleted} { + .c itemconfig test -text "abcdefghijk" + .c select from test 4 + .c select to test 8 + .c dchars test 6 10 + list [.c index test sel.first] [.c index test sel.last] +} {4 5} +test canvText-9.8 {TextInsert procedure: selectFirst > selectLast: deselect} { + .c itemconfig test -text "abcdefghijk" + .c select from test 4 + .c select to test 8 + .c dchars test 3 10 + list [catch {.c index test sel.first} msg] $msg +} {1 {selection isn't in item}} +test canvText-9.9 {TextInsert procedure: selectFirst <= selectLast} { + .c itemconfig test -text "abcdefghijk" + .c select from test 4 + .c select to test 8 + .c dchars test 4 7 + list [.c index test sel.first] [.c index test sel.last] +} {4 4} +test canvText-9.10 {TextInsert procedure: move anchor} { + .c itemconfig test -text "abcdefghijk" + .c select from test 6 + .c select to test 8 + .c dchars test 2 4 + .c select to test 1 + list [.c index test sel.first] [.c index test sel.last] +} {1 2} +test canvText-9.11 {TextInsert procedure: keep anchor >= first} { + .c itemconfig test -text "abcdefghijk" + .c select from test 6 + .c select to test 8 + .c dchars test 5 7 + .c select to test 1 + list [.c index test sel.first] [.c index test sel.last] +} {1 4} +test canvText-9.12 {TextInsert procedure: anchor doesn't move} { + .c itemconfig test -text "abcdefghijk" + .c select from test 2 + .c select to test 5 + .c dchars test 6 8 + .c select to test 8 + list [.c index test sel.first] [.c index test sel.last] +} {2 8} +test canvText-9.13 {TextInsert procedure: move cursor} { + .c itemconfig test -text "abcdefghijk" + .c icursor test 6 + .c dchars test 2 4 + .c index test insert +} {3} +test canvText-9.14 {TextInsert procedure: keep cursor >= first} { + .c itemconfig test -text "abcdefghijk" + .c icursor test 6 + .c dchars test 2 10 + .c index test insert +} {2} +test canvText-9.15 {TextInsert procedure: cursor doesn't move} { + .c itemconfig test -text "abcdefghijk" + .c icursor test 5 + .c dchars test 7 9 + .c index test insert +} {5} + +test canvText-10.1 {TextToPoint procedure} { + .c coords test 0 0 + .c itemconfig test -text 0 -anchor center + .c index test @0,0 +} {0} + +test canvText-11.1 {TextToArea procedure} { + .c coords test 0 0 + .c itemconfig test -text 0 -anchor center + .c find overlapping 0 0 1 1 +} [.c find withtag test] +test canvText-11.2 {TextToArea procedure} { + .c coords test 0 0 + .c itemconfig test -text 0 -anchor center + .c find overlapping 1000 1000 1001 1001 +} {} + +test canvText-12.1 {ScaleText procedure} { + .c coords test 100 100 + .c scale all 50 50 2 2 + .c coords test +} {150.0 150.0} + +test canvText-13.1 {TranslateText procedure} { + .c coords test 100 100 + .c move all 10 10 + .c coords test +} {110.0 110.0} + +.c itemconfig test -text "abcdefghijklmno" -anchor nw +.c select from test 5 +.c select to test 8 +.c icursor test 12 +.c coords test 0 0 +test canvText-14.1 {GetTextIndex procedure} { + list [.c index test end] [.c index test insert] \ + [.c index test sel.first] [.c index test sel.last] \ + [.c index test @0,0] \ + [.c index test -1] [.c index test 10] [.c index test 100] +} {15 12 5 8 0 0 10 15} +test canvText-14.2 {GetTextIndex procedure: select error} { + .c select clear + list [catch {.c index test sel.first} msg] $msg +} {1 {selection isn't in item}} +test canvText-14.3 {GetTextIndex procedure: select error} { + .c select clear + list [catch {.c index test sel.last} msg] $msg +} {1 {selection isn't in item}} +test canvText-14.4 {GetTextIndex procedure: select error} { + .c select clear + list [catch {.c index test sel.} msg] $msg +} {1 {bad index "sel."}} +test canvText-14.5 {GetTextIndex procedure: bad int or unknown index} { + list [catch {.c index test xyz} msg] $msg +} {1 {bad index "xyz"}} + +test canvText-15.1 {SetTextCursor procedure} { + .c itemconfig -text "abcdefg" + .c icursor test 3 + .c index test insert +} {3} + +test canvText-16.1 {GetSelText procedure} { + .c itemconfig test -text "abcdefghijklmno" -anchor nw + .c select from test 5 + .c select to test 8 + selection get +} {fghi} + +set font {Courier 12 italic} +set ax [font measure $font 0] +set ay [font metrics $font -linespace] + +test canvText-17.1 {TextToPostscript procedure} { + .c delete all + .c config -height 300 -highlightthickness 0 -bd 0 + update + .c create text 100 100 -tags test + .c itemconfig test -font $font -text "00000000" -width [expr 3*$ax] + .c itemconfig test -anchor n -fill black + set x [.c postscript] + set x [string range $x [string first "/Courier-Oblique" $x] end] +} "/Courier-Oblique findfont [font actual $font -size] scalefont ISOEncode setfont +0.000 0.000 0.000 setrgbcolor AdjustColor +100 200 \[ +(000) +(000) +(00) +] $ay -0.5 0 0 false DrawText +grestore +restore showpage + +%%Trailer +end +%%EOF +" diff --git a/tests/canvWind.test b/tests/canvWind.test new file mode 100644 index 0000000..d8c6835 --- /dev/null +++ b/tests/canvWind.test @@ -0,0 +1,133 @@ +# This file is a Tcl script to test out the procedures in tkCanvWind.c, +# which implement canvas "window" items. It is organized in the standard +# fashion for Tcl tests. +# +# Copyright (c) 1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) canvWind.test 1.2 97/11/06 13:49:14 + +if {"[info procs test]" != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +test canvWind-1.1 {DisplayWinItem, windows off-screen vertically} { + catch {destroy .t} + toplevel .t + canvas .t.c -scrollregion {0 0 1000 800} -width 250 -height 200 -bd 2 \ + -relief sunken -xscrollincrement 1 -yscrollincrement 1 \ + -highlightthickness 1 + pack .t.c -fill both -expand 1 -padx 20 -pady 20 + wm geometry .t +0+0 + set f .t.f + frame $f -width 80 -height 50 -bg red + .t.c create window 300 400 -window $f -anchor nw + .t.c xview moveto .3 + .t.c yview moveto .50 + update + set x [list [list [winfo ismapped $f] [winfo y $f]]] + .t.c yview scroll 52 units + update + lappend x [list [winfo ismapped $f] [winfo y $f]] + .t.c yview scroll 1 units + update + lappend x [list [winfo ismapped $f] [winfo y $f]] + .t.c yview scroll -255 units + update + lappend x [list [winfo ismapped $f] [winfo y $f]] + .t.c yview scroll -1 units + update + lappend x [list [winfo ismapped $f] [winfo y $f]] +} {{1 23} {1 -29} {0 -29} {1 225} {0 225}} +test canvWind-1.2 {DisplayWinItem, windows off-screen vertically} { + catch {destroy .t} + toplevel .t + canvas .t.c -scrollregion {0 0 1000 800} -width 250 -height 200 -bd 2 \ + -relief sunken -xscrollincrement 1 -yscrollincrement 1 \ + -highlightthickness 1 + pack .t.c -fill both -expand 1 -padx 20 -pady 20 + wm geometry .t +0+0 + set f .t.c.f + frame $f -width 80 -height 50 -bg red + .t.c create window 300 400 -window $f -anchor nw + .t.c xview moveto .3 + .t.c yview moveto .50 + update + set x [list [list [winfo ismapped $f] [winfo y $f]]] + .t.c yview scroll 52 units + update + lappend x [list [winfo ismapped $f] [winfo y $f]] + .t.c yview scroll 1 units + update + lappend x [list [winfo ismapped $f] [winfo y $f]] + .t.c yview scroll -255 units + update + lappend x [list [winfo ismapped $f] [winfo y $f]] + .t.c yview scroll -1 units + update + lappend x [list [winfo ismapped $f] [winfo y $f]] +} {{1 3} {1 -49} {0 -49} {1 205} {0 205}} +test canvWind-1.3 {DisplayWinItem, windows off-screen horizontally} { + catch {destroy .t} + toplevel .t + canvas .t.c -scrollregion {0 0 1000 800} -width 250 -height 200 -bd 2 \ + -relief sunken -xscrollincrement 1 -yscrollincrement 1 \ + -highlightthickness 1 + pack .t.c -fill both -expand 1 -padx 20 -pady 20 + wm geometry .t +0+0 + set f .t.f + frame $f -width 80 -height 50 -bg red + .t.c create window 300 400 -window $f -anchor nw + .t.c xview moveto .3 + .t.c yview moveto .50 + update + set x [list [list [winfo ismapped $f] [winfo x $f]]] + .t.c xview scroll 82 units + update + lappend x [list [winfo ismapped $f] [winfo x $f]] + .t.c xview scroll 1 units + update + lappend x [list [winfo ismapped $f] [winfo x $f]] + .t.c xview scroll -335 units + update + lappend x [list [winfo ismapped $f] [winfo x $f]] + .t.c xview scroll -1 units + update + lappend x [list [winfo ismapped $f] [winfo x $f]] +} {{1 23} {1 -59} {0 -59} {1 275} {0 275}} +test canvWind-1.4 {DisplayWinItem, windows off-screen horizontally} { + catch {destroy .t} + toplevel .t + canvas .t.c -scrollregion {0 0 1000 800} -width 250 -height 200 -bd 2 \ + -relief sunken -xscrollincrement 1 -yscrollincrement 1 \ + -highlightthickness 1 + pack .t.c -fill both -expand 1 -padx 20 -pady 20 + wm geometry .t +0+0 + set f .t.c.f + frame $f -width 80 -height 50 -bg red + .t.c create window 300 400 -window $f -anchor nw + .t.c xview moveto .3 + .t.c yview moveto .50 + update + set x [list [list [winfo ismapped $f] [winfo x $f]]] + .t.c xview scroll 82 units + update + lappend x [list [winfo ismapped $f] [winfo x $f]] + .t.c xview scroll 1 units + update + lappend x [list [winfo ismapped $f] [winfo x $f]] + .t.c xview scroll -335 units + update + lappend x [list [winfo ismapped $f] [winfo x $f]] + .t.c xview scroll -1 units + update + lappend x [list [winfo ismapped $f] [winfo x $f]] +} {{1 3} {1 -79} {0 -79} {1 255} {0 255}} diff --git a/tests/canvas.test b/tests/canvas.test new file mode 100644 index 0000000..786a29a --- /dev/null +++ b/tests/canvas.test @@ -0,0 +1,192 @@ +# This file is a Tcl script to test out the procedures in tkCanvas.c, +# which implements generic code for canvases. It is organized in the +# standard fashion for Tcl tests. +# +# Copyright (c) 1995-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) canvas.test 1.10 97/07/31 10:22:48 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +# XXX - This test file is woefully incomplete. At present, only a +# few of the features are tested. + +canvas .c +pack .c +update +set i 1 +foreach test { + {-background #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-bg #ff0000 #ff0000 non-existent {unknown color name "non-existent"}} + {-bd 4 4 badValue {bad screen distance "badValue"}} + {-borderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-closeenough 24 24.0 bogus {expected floating-point number but got "bogus"}} + {-confine true 1 silly {expected boolean value but got "silly"}} + {-cursor arrow arrow badValue {bad cursor spec "badValue"}} + {-height 2.1 2 x42 {bad screen distance "x42"}} + {-highlightbackground #112233 #112233 ugly {unknown color name "ugly"}} + {-highlightcolor #110022 #110022 bogus {unknown color name "bogus"}} + {-highlightthickness 18 18 badValue {bad screen distance "badValue"}} + {-insertbackground #110022 #110022 bogus {unknown color name "bogus"}} + {-insertborderwidth 1.3 1 2.6x {bad screen distance "2.6x"}} + {-insertofftime 100 100 3.2 {expected integer but got "3.2"}} + {-insertontime 100 100 3.2 {expected integer but got "3.2"}} + {-insertwidth 1.3 1 6x {bad screen distance "6x"}} + {-relief groove groove 1.5 {bad relief type "1.5": must be flat, groove, raised, ridge, solid, or sunken}} + {-selectbackground #110022 #110022 bogus {unknown color name "bogus"}} + {-selectborderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-selectforeground #654321 #654321 bogus {unknown color name "bogus"}} + {-takefocus "any string" "any string" {} {}} + {-width 402 402 xyz {bad screen distance "xyz"}} + {-xscrollcommand {Some command} {Some command} {} {}} + {-yscrollcommand {Another command} {Another command} {} {}} +} { + set name [lindex $test 0] + test canvas-1.$i {configuration options} { + .c configure $name [lindex $test 1] + lindex [.c configure $name] 4 + } [lindex $test 2] + incr i + if {[lindex $test 3] != ""} { + test canvas-1.$i {configuration options} { + list [catch {.c configure $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .c configure $name [lindex [.c configure $name] 3] + incr i +} + + +catch {destroy .c} +canvas .c -width 60 -height 40 -scrollregion {0 0 200 150} -bd 0 \ + -highlightthickness 0 +pack .c +update +test canvas-2.1 {CanvasWidgetCmd, xview option} { + .c configure -xscrollincrement 40 -yscrollincrement 5 + .c xview moveto 0 + update + set x [list [.c xview]] + .c xview scroll 2 units + update + lappend x [.c xview] +} {{0 0.3} {0.4 0.7}} +test canvas-2.2 {CanvasWidgetCmd, xview option} {nonPortable} { + # This test gives slightly different results on platforms such + # as NetBSD. I don't know why... + .c configure -xscrollincrement 0 -yscrollincrement 5 + .c xview moveto 0.6 + update + set x [list [.c xview]] + .c xview scroll 2 units + update + lappend x [.c xview] +} {{0.6 0.9} {0.66 0.96}} + +catch {destroy .c} +canvas .c -width 60 -height 40 -scrollregion {0 0 200 80} \ + -borderwidth 0 -highlightthickness 0 +pack .c +update +test canvas-3.1 {CanvasWidgetCmd, yview option} { + .c configure -xscrollincrement 40 -yscrollincrement 5 + .c yview moveto 0 + update + set x [list [.c yview]] + .c yview scroll 3 units + update + lappend x [.c yview] +} {{0 0.5} {0.1875 0.6875}} +test canvas-3.2 {CanvasWidgetCmd, yview option} { + .c configure -xscrollincrement 40 -yscrollincrement 0 + .c yview moveto 0 + update + set x [list [.c yview]] + .c yview scroll 2 units + update + lappend x [.c yview] +} {{0 0.5} {0.1 0.6}} + +test canvas-4.1 {ButtonEventProc procedure} { + eval destroy [winfo children .] + canvas .c1 -bg #543210 + rename .c1 .c2 + set x {} + lappend x [winfo children .] + lappend x [.c2 cget -bg] + destroy .c1 + lappend x [info command .c*] [winfo children .] +} {.c1 #543210 {} {}} + +test canvas-5.1 {ButtonCmdDeletedProc procedure} { + eval destroy [winfo children .] + canvas .c1 + rename .c1 {} + list [info command .c*] [winfo children .] +} {{} {}} + +catch {destroy .c} +canvas .c -width 100 -height 50 -scrollregion {-200 -100 305 102} \ + -borderwidth 2 -highlightthickness 3 +pack .c +update +test canvas-6.1 {CanvasSetOrigin procedure} { + .c configure -xscrollincrement 0 -yscrollincrement 0 + .c xview moveto 0 + .c yview moveto 0 + update + list [.c canvasx 0] [.c canvasy 0] +} {-205.0 -105.0} +test canvas-6.2 {CanvasSetOrigin procedure} { + .c configure -xscrollincrement 20 -yscrollincrement 10 + set x "" + foreach i {.08 .10 .48 .50} { + .c xview moveto $i + update + lappend x [.c canvasx 0] + } + set x +} {-165.0 -145.0 35.0 55.0} +test canvas-6.3 {CanvasSetOrigin procedure} { + .c configure -xscrollincrement 20 -yscrollincrement 10 + set x "" + foreach i {.06 .08 .70 .72} { + .c yview moveto $i + update + lappend x [.c canvasy 0] + } + set x +} {-95.0 -85.0 35.0 45.0} +test canvas-6.4 {CanvasSetOrigin procedure} { + .c configure -xscrollincrement 20 -yscrollincrement 10 + .c xview moveto 1.0 + .c canvasx 0 +} {215.0} +test canvas-6.5 {CanvasSetOrigin procedure} { + .c configure -xscrollincrement 20 -yscrollincrement 10 + .c yview moveto 1.0 + .c canvasy 0 +} {55.0} + +set l [interp hidden] +eval destroy [winfo children .] + +test canvas-7.1 {canvas widget vs hidden commands} { + catch {destroy .c} + canvas .c + interp hide {} .c + destroy .c + list [winfo children .] [interp hidden] +} [list {} $l] diff --git a/tests/clipboard.test b/tests/clipboard.test new file mode 100644 index 0000000..90f4ecb --- /dev/null +++ b/tests/clipboard.test @@ -0,0 +1,234 @@ +# This file is a Tcl script to test out Tk's clipboard management code, +# especially the "clipboard" command. It is organized in the standard +# fashion for Tcl tests. +# +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) clipboard.test 1.15 96/12/09 17:26:02 + +# +# Note: Multiple display clipboard handling will only be tested if the +# environment variable TK_ALT_DISPLAY is set to an alternate display. +# + +if {[string compare test [info procs test]] == 1} { + source defs +} + +eval destroy [winfo child .] + +# set up a very large buffer to test INCR retrievals +set longValue "" +foreach i {a b c d e f g j h i j k l m o p q r s t u v w x y z} { + set j $i.1$i.2$i.3$i.4$i.5$i.6$i.7$i.8$i.9$i.10$i.11$i.12$i.13$i.14 + append longValue A$j B$j C$j D$j E$j F$j G$j H$j I$j K$j L$j M$j N$j +} + +# Now we start the main body of the test code + +test clipboard-1.1 {ClipboardHandler procedure} { + clipboard clear + clipboard append "test" + selection get -s CLIPBOARD +} {test} +test clipboard-1.2 {ClipboardHandler procedure} { + clipboard clear + clipboard append "test" + clipboard append "ing" + selection get -s CLIPBOARD +} {testing} +test clipboard-1.3 {ClipboardHandler procedure} { + clipboard clear + clipboard append "t" + clipboard append "e" + clipboard append "s" + clipboard append "t" + selection get -s CLIPBOARD +} {test} +test clipboard-1.4 {ClipboardHandler procedure} { + clipboard clear + clipboard append $longValue + selection get -s CLIPBOARD +} "$longValue" +test clipboard-1.5 {ClipboardHandler procedure} { + clipboard clear + clipboard append $longValue + clipboard append "test" + selection get -s CLIPBOARD +} "${longValue}test" +test clipboard-1.6 {ClipboardHandler procedure} { + clipboard clear + clipboard append -t TEST $longValue + clipboard append -t STRING "test" + list [selection get -s CLIPBOARD -t STRING] \ + [selection get -s CLIPBOARD -t TEST] +} [list test $longValue] +test clipboard-1.7 {ClipboardHandler procedure} { + clipboard clear + clipboard append -t TEST [string range $longValue 1 4000] + clipboard append -t STRING "test" + list [selection get -s CLIPBOARD -t STRING] \ + [selection get -s CLIPBOARD -t TEST] +} [list test [string range $longValue 1 4000]] +test clipboard-1.8 {ClipboardHandler procedure} { + clipboard clear + clipboard append "" + selection get -s CLIPBOARD +} {} +test clipboard-1.9 {ClipboardHandler procedure} { + clipboard clear + clipboard append "" + clipboard append "Test" + selection get -s CLIPBOARD +} {Test} + +############################################################################## + +test clipboard-2.1 {ClipboardAppHandler procedure} { + set oldAppName [tk appname] + tk appname UnexpectedName + clipboard clear + clipboard append -type NEW_TYPE Data + set result [selection get -selection CLIPBOARD -type TK_APPLICATION] + tk appname $oldAppName + set result +} {UnexpectedName} + +############################################################################## + +test clipboard-3.1 {ClipboardWindowHandler procedure} { + set oldAppName [tk appname] + tk appname UnexpectedName + clipboard clear + clipboard append -type NEW_TYPE Data + set result [selection get -selection CLIPBOARD -type TK_WINDOW] + tk appname $oldAppName + set result +} {.} + +############################################################################## + +test clipboard-4.1 {ClipboardLostSel procedure} { + clipboard clear + clipboard append "Test" + selection clear -s CLIPBOARD + list [catch {selection get -s CLIPBOARD} msg] $msg +} {1 {CLIPBOARD selection doesn't exist or form "STRING" not defined}} +test clipboard-4.2 {ClipboardLostSel procedure} { + clipboard clear + clipboard append "Test" + clipboard append -t TEST "Test2" + selection clear -s CLIPBOARD + list [catch {selection get -s CLIPBOARD} msg] $msg \ + [catch {selection get -s CLIPBOARD -t TEST} msg] $msg +} {1 {CLIPBOARD selection doesn't exist or form "STRING" not defined} 1 {CLIPBOARD selection doesn't exist or form "TEST" not defined}} +test clipboard-4.3 {ClipboardLostSel procedure} { + clipboard clear + clipboard append "Test" + clipboard append -t TEST "Test2" + clipboard append "Test3" + selection clear -s CLIPBOARD + list [catch {selection get -s CLIPBOARD} msg] $msg \ + [catch {selection get -s CLIPBOARD -t TEST} msg] $msg +} {1 {CLIPBOARD selection doesn't exist or form "STRING" not defined} 1 {CLIPBOARD selection doesn't exist or form "TEST" not defined}} + +############################################################################## + +test clipboard-5.1 {Tk_ClipboardClear procedure} { + clipboard clear + clipboard append -t TEST "test" + set result [lsort [selection get -s CLIPBOARD TARGETS]] + clipboard clear + list $result [lsort [selection get -s CLIPBOARD TARGETS]] +} {{MULTIPLE TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW} {MULTIPLE TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW}} +test clipboard-5.2 {Tk_ClipboardClear procedure} { + clipboard clear + clipboard append -t TEST "test" + set result [lsort [selection get -s CLIPBOARD TARGETS]] + selection own -s CLIPBOARD . + lappend result [lsort [selection get -s CLIPBOARD TARGETS]] + clipboard clear + clipboard append -t TEST "test" + lappend result [lsort [selection get -s CLIPBOARD TARGETS]] +} {MULTIPLE TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW {MULTIPLE TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW} {MULTIPLE TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW}} + +############################################################################## + +test clipboard-6.1 {Tk_ClipboardAppend procedure} { + clipboard clear + clipboard append "first chunk" + selection own -s CLIPBOARD . + list [catch { + clipboard append " second chunk" + selection get -s CLIPBOARD + } msg] $msg +} {0 {first chunk second chunk}} +test clipboard-6.2 {Tk_ClipboardAppend procedure} {unixOnly} { + setupbg + clipboard clear + clipboard append -f INTEGER -t TEST "16" + set result [dobg {selection get -s CLIPBOARD TEST}] + cleanupbg + set result +} {0x10} +test clipboard-6.3 {Tk_ClipboardAppend procedure} { + clipboard clear + clipboard append -f INTEGER -t TEST "16" + list [catch {clipboard append -t TEST "test"} msg] $msg +} {1 {format "STRING" does not match current format "INTEGER" for TEST}} + +############################################################################## + +test clipboard-7.1 {Tk_ClipboardCmd procedure} { + list [catch {clipboard} msg] $msg +} {1 {wrong # args: should be "clipboard option ?arg arg ...?"}} +test clipboard-7.2 {Tk_ClipboardCmd procedure} { + clipboard clear + list [catch {clipboard append --} msg] $msg \ + [selection get -selection CLIPBOARD] +} {0 {} --} +test clipboard-7.3 {Tk_ClipboardCmd procedure} { + clipboard clear + list [catch {clipboard append -- information} msg] $msg \ + [selection get -selection CLIPBOARD] +} {0 {} information} +test clipboard-7.4 {Tk_ClipboardCmd procedure} { + list [catch {clipboard append --x a b} msg] $msg +} {1 {unknown option "--x"}} +test clipboard-7.5 {Tk_ClipboardCmd procedure} { + list [catch {clipboard append -- a b} msg] $msg +} {1 {wrong # args: should be "clipboard append ?options? data"}} +test clipboard-7.6 {Tk_ClipboardCmd procedure} { + clipboard clear + list [catch {clipboard append -format} msg] $msg \ + [selection get -selection CLIPBOARD] +} {0 {} -format} +test clipboard-7.7 {Tk_ClipboardCmd procedure} { + list [catch {clipboard append -displayofoo f} msg] $msg +} {1 {unknown option "-displayofoo"}} +test clipboard-7.8 {Tk_ClipboardCmd procedure} { + list [catch {clipboard append -type TEST} msg] $msg +} {1 {wrong # args: should be "clipboard append ?options? data"}} +test clipboard-7.9 {Tk_ClipboardCmd procedure} { + list [catch {clipboard append -displayof foo "test"} msg] $msg +} {1 {bad window path name "foo"}} + +test clipboard-7.10 {Tk_ClipboardCmd procedure} { + list [catch {clipboard clear -displayof} msg] $msg +} {1 {value for "-displayof" missing}} +test clipboard-7.11 {Tk_ClipboardCmd procedure} { + list [catch {clipboard clear -displayofoo f} msg] $msg +} {1 {unknown option "-displayofoo"}} +test clipboard-7.12 {Tk_ClipboardCmd procedure} { + list [catch {clipboard clear foo} msg] $msg +} {1 {wrong # args: should be "clipboard clear ?options?"}} +test clipboard-7.13 {Tk_ClipboardCmd procedure} { + list [catch {clipboard clear -displayof foo} msg] $msg +} {1 {bad window path name "foo"}} + +test clipboard-7.14 {Tk_ClipboardCmd procedure} { + list [catch {clipboard error} msg] $msg +} {1 {bad option "error": must be clear or append}} diff --git a/tests/clrpick.test b/tests/clrpick.test new file mode 100644 index 0000000..d267224 --- /dev/null +++ b/tests/clrpick.test @@ -0,0 +1,215 @@ +# This file is a Tcl script to test out Tk's "tk_chooseColor" command. +# It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# @(#) clrpick.test 1.9 97/10/21 11:29:53 +# + +if {[string compare test [info procs test]] == 1} { + source defs +} + +test clrpick-1.1 {tk_chooseColor command} { + list [catch {tk_chooseColor -foo} msg] $msg +} {1 {unknown option "-foo", must be -initialcolor, -parent or -title}} + +catch {tk_chooseColor -foo} msg +regsub -all , $msg "" options +regsub \"-foo\" $options "" options + +foreach option $options { + if {[string index $option 0] == "-"} { + test clrpick-1.2 {tk_chooseColor command} { + list [catch {tk_chooseColor $option} msg] $msg + } [list 1 "value for \"$option\" missing"] + } +} + +test clrpick-1.3 {tk_chooseColor command} { + list [catch {tk_chooseColor -foo bar} msg] $msg +} {1 {unknown option "-foo", must be -initialcolor, -parent or -title}} + +test clrpick-1.4 {tk_chooseColor command} { + list [catch {tk_chooseColor -initialcolor} msg] $msg +} {1 {value for "-initialcolor" missing}} + +test clrpick-1.5 {tk_chooseColor command} { + list [catch {tk_chooseColor -parent foo.bar} msg] $msg +} {1 {bad window path name "foo.bar"}} + +test clrpick-1.6 {tk_chooseColor command} { + list [catch {tk_chooseColor -initialcolor badbadbaadcolor} msg] $msg +} {1 {unknown color name "badbadbaadcolor"}} + +test clrpick-1.7 {tk_chooseColor command} { + list [catch {tk_chooseColor -initialcolor ##badbadbaadcolor} msg] $msg +} {1 {invalid color name "##badbadbaadcolor"}} + +if {[info commands tkColorDialog] == ""} { + set isNative 1 +} else { + set isNative 0 +} + +if {$isNative && ![info exists INTERACTIVE]} { + puts " Some tests were skipped because they could not be performed" + puts " automatically on this platform. If you wish to execute them" + puts " interactively, set the TCL variable INTERACTIVE and re-run" + puts " the test." + return +} + +proc ToPressButton {parent btn} { + global isNative + if {!$isNative} { + after 200 "SendButtonPress $parent $btn mouse" + } +} + +proc ToChooseColorByKey {parent r g b} { + global isNative + if {!$isNative} { + after 200 ChooseColorByKey $parent $r $g $b + } +} + +proc PressButton {btn} { + event generate $btn <Enter> + event generate $btn <1> -x 5 -y 5 + event generate $btn <ButtonRelease-1> -x 5 -y 5 +} + +proc ChooseColorByKey {parent r g b} { + set w .__tk__color + upvar #0 $w data + + update + $data(red,entry) delete 0 end + $data(green,entry) delete 0 end + $data(blue,entry) delete 0 end + + $data(red,entry) insert 0 $r + $data(green,entry) insert 0 $g + $data(blue,entry) insert 0 $b + + # Manually force the refresh of the color values instead + # of counting on the timing of the event stream to change + # the values for us. + tkColorDialog_HandleRGBEntry $w + + SendButtonPress $parent ok mouse +} + +proc SendButtonPress {parent btn type} { + set w .__tk__color + upvar #0 $w data + + set button $data($btn\Btn) + if ![winfo ismapped $button] { + update + } + + if {$type == "mouse"} { + PressButton $button + } else { + event generate $w <Enter> + focus $w + event generate $button <Enter> + event generate $w <KeyPress> -keysym Return + } +} + +set parent . + +set verylongstring longstring: +set verylongstring $verylongstring$verylongstring +set verylongstring $verylongstring$verylongstring +set verylongstring $verylongstring$verylongstring +set verylongstring $verylongstring$verylongstring +#set verylongstring $verylongstring$verylongstring +# Interesting thing...when this is too long, the +# delay caused in processing it kills the automated testing, +# and makes a lot of the test cases fail. +#set verylongstring $verylongstring$verylongstring +#set verylongstring $verylongstring$verylongstring +#set verylongstring $verylongstring$verylongstring +#set verylongstring $verylongstring$verylongstring + +# let's soak up a bunch of colors...so that +# machines with small color palettes still fail. +set numcolors 32 +set nomorecolors 0 +set i 0 +canvas .c +pack .c -expand 1 -fill both +while {$i<$numcolors} { + set color \#[format "%02x%02x%02x" $i [expr $i+1] [expr $i+3]] + .c create rectangle [expr 10+$i] [expr 10+$i] [expr 50+$i] [expr 50+$i] -fill $color -outline $color + incr i +} +set i 0 +while {$i<$numcolors} { + set color [.c itemcget $i -fill] + if {$color != ""} { + foreach {r g b} [winfo rgb . $color] {} + set r [expr $r/256] + set g [expr $g/256] + set b [expr $b/256] + if {"$color" != "#[format %02x%02x%02x $r $g $b]"} { + set nomorecolors 1 + } + } + .c delete $i + incr i +} + +destroy .c + +if {!$nomorecolors} { + set color #404040 + test clrpick-2.1 {tk_chooseColor command} { + ToPressButton $parent ok + tk_chooseColor -title "Press Ok $verylongstring" -initialcolor $color -parent $parent + } "$color" + + set color #808040 + test clrpick-2.2 {tk_chooseColor command} { + if {$tcl_platform(platform) == "macintosh"} { + set colors "32768 32768 16384" + } else { + set colors "128 128 64" + } + ToChooseColorByKey $parent 128 128 64 + tk_chooseColor -parent $parent -title "choose $colors" + } "$color" + + test clrpick-2.3 {tk_chooseColor command} { + ToPressButton $parent ok + tk_chooseColor -parent $parent -title "Press OK" + } "$color" +} else { + puts "Skipped tests clrpick2.1, clrpick2.2 and clrpick2.3 because" + puts "you ran out of colors in your color palette, and this would" + puts "have caused the tests to generate errors." +} + +test clrpick-2.4 {tk_chooseColor command} { + ToPressButton $parent cancel + tk_chooseColor -parent $parent -title "Press Cancel" +} "" + +set color #000000 +test clrpick-3.1 {tk_chooseColor: background events} { + after 1 {set x 53} + ToPressButton $parent ok + tk_chooseColor -parent $parent -title "Press OK" -initialcolor $color +} "#000000" +test clrpick-3.2 {tk_chooseColor: background events} { + after 1 {set x 53} + ToPressButton $parent cancel + tk_chooseColor -parent $parent -title "Press Cancel" +} "" diff --git a/tests/cmap.tcl b/tests/cmap.tcl new file mode 100644 index 0000000..13c350d --- /dev/null +++ b/tests/cmap.tcl @@ -0,0 +1,61 @@ +# This file creates a visual test for colormaps and the WM_COLORMAP_WINDOWS +# property. It is part of the Tk visual test suite, which is invoked +# via the "visual" script. +# +# SCCS: @(#) cmap.tcl 1.2 96/02/16 10:55:47 + +catch {destroy .t} +toplevel .t -colormap new +wm title .t "Visual Test for Colormaps" +wm iconname .t "Colormaps" +wm geom .t +0+0 + +# The following procedure creates a whole bunch of frames within a +# window, in order to eat up all the colors in a colormap. + +proc colors {w redInc greenInc blueInc} { + set red 0 + set green 0 + set blue 0 + for {set y 0} {$y < 8} {incr y} { + for {set x 0} {$x < 8} {incr x} { + frame $w.f$x,$y -width 40 -height 40 -bd 2 -relief raised \ + -bg [format #%02x%02x%02x $red $green $blue] + place $w.f$x,$y -x [expr 40*$x] -y [expr 40*$y] + incr red $redInc + incr green $greenInc + incr blue $blueInc + } + } +} + +message .t.m -width 6i -text {This window displays two nested frames, each with a whole bunch of subwindows that eat up a lot of colors. The toplevel window has its own colormap, which is inherited by the outer frame. The inner frame has its own colormap. As you move the mouse around, the colors in the frames should change back and forth.} +pack .t.m -side top -fill x + +button .t.quit -text Quit -command {destroy .t} +pack .t.quit -side bottom -pady 3 -ipadx 4 -ipady 2 + +frame .t.f -width 700 -height 450 -relief raised -bd 2 +pack .t.f -side top -padx 1c -pady 1c +colors .t.f 4 0 0 +frame .t.f.f -width 350 -height 350 -colormap new -bd 2 -relief raised +place .t.f.f -relx 1.0 -rely 0 -anchor ne +colors .t.f.f 0 4 0 +bind .t.f.f <Enter> {wm colormapwindows .t {.t.f.f .t}} +bind .t.f.f <Leave> {wm colormapwindows .t {.t .t.f.f}} + +catch {destroy .t2} +toplevel .t2 +wm title .t2 "Visual Test for Colormaps" +wm iconname .t2 "Colormaps" +wm geom .t2 +0-0 + +message .t2.m -width 6i -text {This window just eats up most of the colors in the default colormap.} +pack .t2.m -side top -fill x + +button .t2.quit -text Quit -command {destroy .t2} +pack .t2.quit -side bottom -pady 3 -ipadx 4 -ipady 2 + +frame .t2.f -height 320 -width 320 +pack .t2.f -side bottom +colors .t2.f 0 0 4 diff --git a/tests/cmds.test b/tests/cmds.test new file mode 100644 index 0000000..71b14f4 --- /dev/null +++ b/tests/cmds.test @@ -0,0 +1,43 @@ +# This file is a Tcl script to test the procedures in the file +# tkCmds.c. It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) cmds.test 1.1 96/03/14 13:25:24 + +if {[string compare test [info procs test]] == 1} { + source defs +} + +eval destroy [winfo child .] +wm geometry . {} +update + +test cmds-1.1 {tkwait visibility, argument errors} { + list [catch {tkwait visibility} msg] $msg +} {1 {wrong # args: should be "tkwait variable|visibility|window name"}} +test cmds-1.2 {tkwait visibility, argument errors} { + list [catch {tkwait visibility foo bar} msg] $msg +} {1 {wrong # args: should be "tkwait variable|visibility|window name"}} +test cmds-1.3 {tkwait visibility, argument errors} { + list [catch {tkwait visibility bad_window} msg] $msg +} {1 {bad window path name "bad_window"}} +test cmds-1.4 {tkwait visibility, waiting for window to be mapped} { + button .b -text "Test" + set x init + after 100 {set x delay; place .b -x 0 -y 0} + tkwait visibility .b + destroy .b + set x +} {delay} +test cmds-1.5 {tkwait visibility, window gets deleted} { + frame .f + button .f.b -text "Test" + pack .f.b + set x init + after 100 {set x deleted; destroy .f} + list [catch {tkwait visibility .f.b} msg] $msg $x +} {1 {window ".f.b" was deleted before its visibility changed} deleted} diff --git a/tests/color.test b/tests/color.test new file mode 100644 index 0000000..030efa0 --- /dev/null +++ b/tests/color.test @@ -0,0 +1,167 @@ +# This file is a Tcl script to test out the procedures in the file +# tkColor.c. It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) color.test 1.5 96/02/16 10:56:05 + +if {[info procs test] != "test"} { + source defs +} + +eval destroy [winfo children .] +wm geometry . {} +raise . + +# cname -- +# Returns a proper name for a color, given its intensities. +# +# Arguments: +# r, g, b - Intensities on a 0-255 scale. + +proc cname {r g b} { + format #%02x%02x%02x $r $g $b +} +proc cname4 {r g b} { + format #%04x%04x%04x $r $g $b +} + +# mkColors -- +# Creates a canvas and fills it with a 2-D array of squares, each of a +# different color. +# +# Arguments: +# c - Name of canvas window to create. +# width - Number of squares in each row. +# height - Number of squares in each column. +# r, g, b - Initial value for red, green, and blue intensities. +# rx, gx, bx - Change in intensities between adjacent elements in row. +# ry, gy, by - Change in intensities between adjacent elements in column. + +proc mkColors {c width height r g b rx gx bx ry gy by} { + catch {destroy $c} + canvas $c -width 400 -height 200 -bd 0 + for {set y 0} {$y < $height} {incr y} { + for {set x 0} {$x < $width} {incr x} { + set color [format #%02x%02x%02x [expr $r + $y*$ry + $x*$rx] \ + [expr $g + $y*$gy + $x*$gx] [expr $b + $y*$by + $x*$bx]] + $c create rectangle [expr 10*$x] [expr 20*$y] \ + [expr 10*$x + 10] [expr 20*$y + 20] -outline {} \ + -fill $color + } + } +} + +# closest - +# Given intensities between 0 and 255, return the closest intensities +# that the server can provide. +# +# Arguments: +# w - Window in which to lookup color +# r, g, b - Desired intensities, between 0 and 255. + +proc closest {w r g b} { + set vals [winfo rgb $w [cname $r $g $b]] + list [expr [lindex $vals 0]/256] [expr [lindex $vals 1]/256] \ + [expr [lindex $vals 2]/256] +} + +# c255 - +# Given a list of red, green, and blue intensities, scale them +# down to a 0-255 range. +# +# Arguments: +# vals - List of intensities. + +proc c255 {vals} { + list [expr [lindex $vals 0]/256] [expr [lindex $vals 1]/256] \ + [expr [lindex $vals 2]/256] +} + +# colorsFree -- +# +# Returns 1 if there appear to be free colormap entries in a window, +# 0 otherwise. +# +# Arguments: +# w - Name of window in which to check. +# red, green, blue - Intensities to use in a trial color allocation +# to see if there are colormap entries free. + +proc colorsFree {w {red 31} {green 245} {blue 192}} { + set vals [winfo rgb $w [format #%02x%02x%02x $red $green $blue]] + expr ([lindex $vals 0]/256 == $red) && ([lindex $vals 1]/256 == $green) \ + && ([lindex $vals 2]/256 == $blue) +} + +# Create a top-level with its own colormap (so we can test under +# controlled conditions), then check to make sure that the visual +# is color-mapped with 256 colors. If not, just skip this whole +# test file. + +if [catch {toplevel .t -visual {pseudocolor 8} -colormap new}] { + return +} +wm geom .t +0+0 +if {[winfo depth .t] != 8} { + destroy .t + return +} +mkColors .t.c 40 6 0 0 0 0 6 0 0 0 40 +pack .t.c +update +if ![colorsFree .t.c 101 233 17] { + destroy .t + return +} +mkColors .t.c2 20 1 250 0 0 -10 0 0 0 0 0 +pack .t.c2 +if [colorsFree .t.c] { + destroy .t + return +} +destroy .t.c .t.c2 + +test color-1.1 {Tk_GetColor procedure} { + c255 [winfo rgb .t red] +} {255 0 0} +test color-1.2 {Tk_GetColor procedure} { + list [catch {winfo rgb .t noname} msg] $msg +} {1 {unknown color name "noname"}} + +test color-1.3 {Tk_GetColor procedure} { + c255 [winfo rgb .t #123456] +} {18 52 86} +test color-1.4 {Tk_GetColor procedure} { + list [catch {winfo rgb .t #xyz} msg] $msg +} {1 {invalid color name "#xyz"}} + +test color-2.1 {Tk_FreeColor procedure, reference counting} { + eval destroy [winfo child .t] + mkColors .t.c 40 6 0 240 240 0 -6 0 0 0 -40 + pack .t.c + mkColors .t.c2 20 1 250 0 0 -10 0 0 0 0 0 + pack .t.c2 + update + set last [.t.c2 create rectangle 50 50 70 60 -outline {} \ + -fill [cname 0 240 240]] + .t.c delete 1 + set result [colorsFree .t] + .t.c2 delete $last + lappend result [colorsFree .t] +} {0 1} +test color-2.2 {Tk_FreeColor procedure, flushing stressed cmap information} { + eval destroy [winfo child .t] + mkColors .t.c 40 6 0 240 240 0 -6 0 0 0 -40 + pack .t.c + mkColors .t.c2 20 1 250 0 0 -10 0 0 0 0 0 + mkColors .t.c2 20 1 250 250 0 -10 -10 0 0 0 0 + pack .t.c2 + update + closest .t 241 241 1 +} {240 240 0} + +destroy .t diff --git a/tests/defs b/tests/defs new file mode 100644 index 0000000..df518da --- /dev/null +++ b/tests/defs @@ -0,0 +1,367 @@ +# This file contains support code for the Tcl test suite. It is +# normally sourced by the individual files in the test suite before +# they run their tests. This improved approach to testing was designed +# and initially implemented by Mary Ann May-Pumphrey of Sun Microsystems. +# +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) defs 1.39 97/08/06 15:32:02 + +if ![info exists VERBOSE] { + set VERBOSE 0 +} +if ![info exists TESTS] { + set TESTS {} +} + +tk appname tktest +wm title . tktest + +# Check configuration information that will determine which tests +# to run. To do this, create an array testConfig. Each element +# has a 0 or 1 value, and the following elements are defined: +# unixOnly - 1 means this is a UNIX platform, so it's OK +# to run tests that only work under UNIX. +# macOnly - 1 means this is a Mac platform, so it's OK +# to run tests that only work on Macs. +# pcOnly - 1 means this is a PC platform, so it's OK to +# run tests that only work on PCs. +# unixOrPc - 1 means this is a UNIX or PC platform. +# macOrPc - 1 means this is a Mac or PC platform. +# macOrUnix - 1 means this is a Mac or UNIX platform. +# nonPortable - 1 means this the tests are being running in +# the master Tcl/Tk development environment; +# Some tests are inherently non-portable because +# they depend on things like word length, file system +# configuration, window manager, etc. These tests +# are only run in the main Tcl development directory +# where the configuration is well known. The presence +# of the file "doAllTests" in this directory indicates +# that it is safe to run non-portable tests. +# fonts - 1 means that this platform uses fonts with +# well-know geometries, so it is safe to run +# tests that depend on particular font sizes. + +catch {unset testConfig} + +set testConfig(unixOnly) [expr {$tcl_platform(platform) == "unix"}] +set testConfig(macOnly) [expr {$tcl_platform(platform) == "macintosh"}] +set testConfig(pcOnly) [expr {$tcl_platform(platform) == "windows"}] + +set testConfig(unix) $testConfig(unixOnly) +set testConfig(mac) $testConfig(macOnly) +set testConfig(pc) $testConfig(pcOnly) + +set testConfig(unixOrPc) [expr $testConfig(unixOnly) || $testConfig(pcOnly)] +set testConfig(macOrPc) [expr $testConfig(macOnly) || $testConfig(pcOnly)] +set testConfig(macOrUnix) [expr $testConfig(macOnly) || $testConfig(unixOnly)] + +set testConfig(nonPortable) [expr [file exists doAllTests] || [file exists DOALLT~1]] + +set testConfig(nt) [expr {$tcl_platform(os) == "Windows NT"}] +set testConfig(95) [expr {$tcl_platform(os) == "Windows 95"}] +set testConfig(win32s) [expr {$tcl_platform(os) == "Win32s"}] + +# The following config switches are used to mark tests that should work, +# but have been temporarily disabled on certain platforms because they don't. + +set testConfig(tempNotPc) [expr !$testConfig(pc)] +set testConfig(tempNotMac) [expr !$testConfig(mac)] +set testConfig(tempNotUnix) [expr !$testConfig(unix)] + +# The following config switches are used to mark tests that crash on +# certain platforms, so that they can be reactivated again when the +# underlying problem is fixed. + +set testConfig(pcCrash) [expr !$testConfig(pc)] +set testConfig(win32sCrash) [expr !$testConfig(win32s)] +set testConfig(macCrash) [expr !$testConfig(mac)] +set testConfig(unixCrash) [expr !$testConfig(unix)] + +set testConfig(fonts) 1 +catch {destroy .e} +entry .e -width 0 -font {Helvetica -12} -bd 1 +.e insert end "a.bcd" +if {([winfo reqwidth .e] != 37) || ([winfo reqheight .e] != 20)} { + set testConfig(fonts) 0 +} +destroy .e .t +text .t -width 80 -height 20 -font {Times -14} -bd 1 +pack .t +.t insert end "This is\na dot." +update +set x [list [.t bbox 1.3] [.t bbox 2.5]] +destroy .t +if {[string match {{22 3 6 15} {31 18 [34] 15}} $x] == 0} { + set testConfig(fonts) 0 +} + +if {$testConfig(nonPortable) == 0} { + puts "(will skip non-portable tests)" +} +if {$testConfig(fonts) == 0} { + puts "(will skip font-sensitive tests: this system has unexpected font geometries)" +} + +trace variable testConfig r safeFetch + +proc safeFetch {n1 n2 op} { + global testConfig + + if {($n2 != {}) && ([info exists testConfig($n2)] == 0)} { + set testConfig($n2) 0 + } +} + +# If there is no "memory" command (because memory debugging isn't +# enabled), generate a dummy command that does nothing. + +if {[info commands memory] == ""} { + proc memory args {} +} + +proc print_verbose {name description script code answer} { + puts stdout "\n" + puts stdout "==== $name $description" + puts stdout "==== Contents of test case:" + puts stdout "$script" + if {$code != 0} { + if {$code == 1} { + puts stdout "==== Test generated error:" + puts stdout $answer + } elseif {$code == 2} { + puts stdout "==== Test generated return exception; result was:" + puts stdout $answer + } elseif {$code == 3} { + puts stdout "==== Test generated break exception" + } elseif {$code == 4} { + puts stdout "==== Test generated continue exception" + } else { + puts stdout "==== Test generated exception $code; message was:" + puts stdout $answer + } + } else { + puts stdout "==== Result was:" + puts stdout "$answer" + } +} + +# test -- +# This procedure runs a test and prints an error message if the +# test fails. If VERBOSE has been set, it also prints a message +# even if the test succeeds. The test will be skipped if it +# doesn't match the TESTS variable, or if one of the elements +# of "constraints" turns out not to be true. +# +# Arguments: +# name - Name of test, in the form foo-1.2. +# description - Short textual description of the test, to +# help humans understand what it does. +# constraints - A list of one or more keywords, each of +# which must be the name of an element in +# the array "testConfig". If any of these +# elements is zero, the test is skipped. +# This argument may be omitted. +# script - Script to run to carry out the test. It must +# return a result that can be checked for +# correctness. +# answer - Expected result from script. + +proc test {name description script answer args} { + global VERBOSE TESTS testConfig + if {[string compare $TESTS ""] != 0} { + set ok 0 + foreach test $TESTS { + if {[string match $test $name]} { + set ok 1 + break + } + } + if {!$ok} { + return + } + } + set i [llength $args] + if {$i == 0} { + # Empty body + } elseif {$i == 1} { + # "constraints" argument exists; shuffle arguments down, then + # make sure that the constraints are satisfied. + + set constraints $script + set script $answer + set answer [lindex $args 0] + set doTest 0 + if {[string match {*[$\[]*} $constraints] != 0} { + # full expression, e.g. {$foo > [info tclversion]} + + catch {set doTest [uplevel #0 expr $constraints]} + } elseif {[regexp {[^.a-zA-Z0-9 ]+} $constraints] != 0} { + # something like {a || b} should be turned into + # $testConfig(a) || $testConfig(b). + + regsub -all {[.a-zA-Z0-9]+} $constraints {$testConfig(&)} c + catch {set doTest [eval expr $c]} + } else { + # just simple constraints such as {unixOnly fonts}. + + set doTest 1 + foreach constraint $constraints { + if {![info exists testConfig($constraint)] + || !$testConfig($constraint)} { + set doTest 0 + break + } + } + } + if {$doTest == 0} { + if {$VERBOSE} { + puts stdout "++++ $name SKIPPED: $constraints" + } + return + } + } else { + error "wrong # args: must be \"test name description ?constraints? script answer\"" + } + memory tag $name + set code [catch {uplevel $script} result] + if {$code != 0} { + print_verbose $name $description $script $code $result + } elseif {[string compare $result $answer] == 0} { + if {$VERBOSE} then { + if {$VERBOSE > 0} { + print_verbose $name $description $script $code $result + } + if {$VERBOSE != -2} { + puts stdout "++++ $name PASSED" + } + } + } else { + print_verbose $name $description $script $code $result + puts stdout "---- Result should have been:" + puts stdout "$answer" + puts stdout "---- $name FAILED" + } +} + +proc dotests {file args} { + global TESTS + set savedTests $TESTS + set TESTS $args + source $file + set TESTS $savedTests +} + +# If the main window isn't already mapped (e.g. because the tests are +# being run automatically) , specify a precise size for it so that the +# user won't have to position it manually. + +if {![winfo ismapped .]} { + wm geometry . +0+0 + update +} + +# The following code can be used to perform tests involving a second +# process running in the background. + +# Locate tktest executable + +set tktest [info nameofexecutable] +if {$tktest == "{}"} { + set tktest {} + puts "Unable to find tktest executable, skipping multiple process tests." +} + +# Create background process + +proc setupbg {{args ""}} { + global tktest fd bgData + if {$tktest == ""} { + error "you're not running tktest so setupbg should not have been called" + } + if {[info exists fd] && ($fd != "")} { + cleanupbg + } + set fd [open "|[list $tktest -geometry +0+0 -name tktest] $args" r+] + puts $fd "puts foo; flush stdout" + flush $fd + if {[gets $fd data] < 0} { + error "unexpected EOF from \"$tktest\"" + } + if [string compare $data foo] { + error "unexpected output from background process \"$data\"" + } + fileevent $fd readable bgReady +} + +# Send a command to the background process, catching errors and +# flushing I/O channels +proc dobg {command} { + global fd bgData bgDone + puts $fd "catch [list $command] msg; update; puts \$msg; puts **DONE**; flush stdout" + flush $fd + set bgDone 0 + set bgData {} + tkwait variable bgDone + set bgData +} + +# Data arrived from background process. Check for special marker +# indicating end of data for this command, and make data available +# to dobg procedure. +proc bgReady {} { + global fd bgData bgDone + set x [gets $fd] + if [eof $fd] { + fileevent $fd readable {} + set bgDone 1 + } elseif {$x == "**DONE**"} { + set bgDone 1 + } else { + append bgData $x + } +} + +# Exit the background process, and close the pipes +proc cleanupbg {} { + global fd + catch { + puts $fd "exit" + close $fd + } + set fd "" +} + +# Clean up focus after using generate event, which +# can leave the window manager with the wrong impression +# about who thinks they have the focus. (BW) + +proc fixfocus {} { + catch {destroy .focus} + toplevel .focus + wm geometry .focus +0+0 + entry .focus.e + .focus.e insert 0 "fixfocus" + pack .focus.e + update + focus -force .focus.e + destroy .focus +} + +proc makeFile {contents name} { + set fd [open $name w] + fconfigure $fd -translation lf + if {[string index $contents [expr [string length $contents] - 1]] == "\n"} { + puts -nonewline $fd $contents + } else { + puts $fd $contents + } + close $fd +} + +proc removeFile {name} { + file delete -- $name +} diff --git a/tests/entry.test b/tests/entry.test new file mode 100644 index 0000000..950d278 --- /dev/null +++ b/tests/entry.test @@ -0,0 +1,1269 @@ +# This file is a Tcl script to test entry widgets in Tk. It is +# organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) entry.test 1.49 97/11/07 09:34:31 + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\"" + puts "image, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +proc scroll args { + global scrollInfo + set scrollInfo $args +} + +# Create additional widget that's used to hold the selection at times. + +entry .sel +.sel insert end "This is some sample text" + +# Font names + +set big -adobe-helvetica-medium-r-normal--24-240-75-75-p-*-iso8859-1 +set fixed -adobe-courier-medium-r-normal--12-120-75-75-m-*-iso8859-1 + +# Create entries in the option database to be sure that geometry options +# like border width have predictable values. + +option add *Entry.borderWidth 2 +option add *Entry.highlightThickness 2 +option add *Entry.font {Helvetica -12} + +entry .e -bd 2 -relief sunken +pack .e +update +set i 1 +foreach test { + {-background #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-bd 4 4 badValue {bad screen distance "badValue"}} + {-bg #ff0000 #ff0000 non-existent {unknown color name "non-existent"}} + {-borderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-cursor arrow arrow badValue {bad cursor spec "badValue"}} + {-exportselection yes 1 xyzzy {expected boolean value but got "xyzzy"}} + {-fg #110022 #110022 bogus {unknown color name "bogus"}} + {-font -Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* + -Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* {} + {font "" doesn't exist}} + {-foreground #110022 #110022 bogus {unknown color name "bogus"}} + {-highlightbackground #123456 #123456 ugly {unknown color name "ugly"}} + {-highlightcolor #123456 #123456 bogus {unknown color name "bogus"}} + {-highlightthickness 6 6 bogus {bad screen distance "bogus"}} + {-highlightthickness -2 0 {} {}} + {-insertbackground #110022 #110022 bogus {unknown color name "bogus"}} + {-insertborderwidth 1.3 1 2.6x {bad screen distance "2.6x"}} + {-insertofftime 100 100 3.2 {expected integer but got "3.2"}} + {-insertontime 100 100 3.2 {expected integer but got "3.2"}} + {-justify right right bogus {bad justification "bogus": must be left, right, or center}} + {-relief groove groove 1.5 {bad relief type "1.5": must be flat, groove, raised, ridge, solid, or sunken}} + {-selectbackground #110022 #110022 bogus {unknown color name "bogus"}} + {-selectborderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-selectforeground #654321 #654321 bogus {unknown color name "bogus"}} + {-show * * {} {}} + {-state normal normal bogus {bad state value "bogus": must be normal or disabled}} + {-takefocus "any string" "any string" {} {}} + {-textvariable i i {} {}} + {-width 402 402 3p {expected integer but got "3p"}} + {-xscrollcommand {Some command} {Some command} {} {}} +} { + set name [lindex $test 0] + test entry-1.1 {configuration options} { + .e configure $name [lindex $test 1] + list [lindex [.e configure $name] 4] [.e cget $name] + } [list [lindex $test 2] [lindex $test 2]] + incr i + if {[lindex $test 3] != ""} { + test entry-1.2 {configuration options} { + list [catch {.e configure $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .e configure $name [lindex [.e configure $name] 3] + incr i +} + +test entry-2.1 {Tk_EntryCmd procedure} { + list [catch {entry} msg] $msg +} {1 {wrong # args: should be "entry pathName ?options?"}} +test entry-2.2 {Tk_EntryCmd procedure} { + list [catch {entry gorp} msg] $msg +} {1 {bad window path name "gorp"}} +test entry-2.3 {Tk_EntryCmd procedure} { + catch {destroy .e} + entry .e + list [winfo exists .e] [winfo class .e] [info commands .e] +} {1 Entry .e} +test entry-2.4 {Tk_EntryCmd procedure} { + catch {destroy .e} + list [catch {entry .e -gorp foo} msg] $msg [winfo exists .e] \ + [info commands .e] +} {1 {unknown option "-gorp"} 0 {}} +test entry-2.5 {Tk_EntryCmd procedure} { + catch {destroy .e} + entry .e +} {.e} + +catch {destroy .e} +entry .e -font $fixed +pack .e +update + +set cx [font measure $fixed a] +set cy [font metrics $fixed -linespace] + +test entry-3.1 {EntryWidgetCmd procedure} { + list [catch {.e} msg] $msg +} {1 {wrong # args: should be ".e option ?arg arg ...?"}} +test entry-3.2 {EntryWidgetCmd procedure, "bbox" widget command} { + list [catch {.e bbox} msg] $msg +} {1 {wrong # args: should be ".e bbox index"}} +test entry-3.3 {EntryWidgetCmd procedure, "bbox" widget command} { + list [catch {.e bbox a b} msg] $msg +} {1 {wrong # args: should be ".e bbox index"}} +test entry-3.4 {EntryWidgetCmd procedure, "bbox" widget command} { + list [catch {.e bbox bogus} msg] $msg +} {1 {bad entry index "bogus"}} +test entry-3.5 {EntryWidgetCmd procedure, "bbox" widget command} { + .e delete 0 end + .e bbox 0 +} [list 5 5 0 $cy] +test entry-3.6 {EntryWidgetCmd procedure, "bbox" widget command} {fonts} { + .e delete 0 end + .e insert 0 "abcdefghijklmnop" + list [.e bbox 0] [.e bbox 1] [.e bbox end] +} [list "5 5 $cx $cy" "[expr 5+$cx] 5 $cx $cy" "[expr 5+15*$cx] 5 $cx $cy"] +test entry-3.7 {EntryWidgetCmd procedure, "cget" widget command} { + list [catch {.e cget} msg] $msg +} {1 {wrong # args: should be ".e cget option"}} +test entry-3.8 {EntryWidgetCmd procedure, "cget" widget command} { + list [catch {.e cget a b} msg] $msg +} {1 {wrong # args: should be ".e cget option"}} +test entry-3.9 {EntryWidgetCmd procedure, "cget" widget command} { + list [catch {.e cget -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test entry-3.10 {EntryWidgetCmd procedure, "cget" widget command} { + .e configure -bd 4 + .e cget -bd +} {4} +test entry-3.11 {EntryWidgetCmd procedure, "configure" widget command} { + llength [.e configure] +} {28} +test entry-3.12 {EntryWidgetCmd procedure, "configure" widget command} { + list [catch {.e configure -foo} msg] $msg +} {1 {unknown option "-foo"}} +test entry-3.13 {EntryWidgetCmd procedure, "configure" widget command} { + .e configure -bd 4 + .e configure -bg #ffffff + lindex [.e configure -bd] 4 +} {4} +test entry-3.14 {EntryWidgetCmd procedure, "delete" widget command} { + list [catch {.e delete} msg] $msg +} {1 {wrong # args: should be ".e delete firstIndex ?lastIndex?"}} +test entry-3.15 {EntryWidgetCmd procedure, "delete" widget command} { + list [catch {.e delete a b c} msg] $msg +} {1 {wrong # args: should be ".e delete firstIndex ?lastIndex?"}} +test entry-3.16 {EntryWidgetCmd procedure, "delete" widget command} { + list [catch {.e delete foo} msg] $msg +} {1 {bad entry index "foo"}} +test entry-3.17 {EntryWidgetCmd procedure, "delete" widget command} { + list [catch {.e delete 0 bar} msg] $msg +} {1 {bad entry index "bar"}} +test entry-3.18 {EntryWidgetCmd procedure, "delete" widget command} { + .e delete 0 end + .e insert end "01234567890" + .e delete 2 4 + .e get +} {014567890} +test entry-3.19 {EntryWidgetCmd procedure, "delete" widget command} { + .e delete 0 end + .e insert end "01234567890" + .e delete 6 + .e get +} {0123457890} +test entry-3.20 {EntryWidgetCmd procedure, "delete" widget command} { + .e delete 0 end + .e insert end "01234567890" + .e delete 6 5 + .e get +} {01234567890} +test entry-3.21 {EntryWidgetCmd procedure, "delete" widget command} { + .e delete 0 end + .e insert end "01234567890" + .e configure -state disabled + .e delete 2 8 + .e configure -state normal + .e get +} {01234567890} +test entry-3.22 {EntryWidgetCmd procedure, "get" widget command} { + list [catch {.e get foo} msg] $msg +} {1 {wrong # args: should be ".e get"}} +test entry-3.23 {EntryWidgetCmd procedure, "icursor" widget command} { + list [catch {.e icursor} msg] $msg +} {1 {wrong # args: should be ".e icursor pos"}} +test entry-3.24 {EntryWidgetCmd procedure, "icursor" widget command} { + list [catch {.e icursor foo} msg] $msg +} {1 {bad entry index "foo"}} +test entry-3.25 {EntryWidgetCmd procedure, "icursor" widget command} { + .e delete 0 end + .e insert end "01234567890" + .e icursor 4 + .e index insert +} {4} +test entry-3.26 {EntryWidgetCmd procedure, "index" widget command} { + list [catch {.e in} msg] $msg +} {1 {bad option "in": must be bbox, cget, configure, delete, get, icursor, index, insert, scan, selection, or xview}} +test entry-3.27 {EntryWidgetCmd procedure, "index" widget command} { + list [catch {.e index} msg] $msg +} {1 {wrong # args: should be ".e index string"}} +test entry-3.28 {EntryWidgetCmd procedure, "index" widget command} { + list [catch {.e index foo} msg] $msg +} {1 {bad entry index "foo"}} +test entry-3.29 {EntryWidgetCmd procedure, "index" widget command} { + list [catch {.e index 0} msg] $msg +} {0 0} +test entry-3.30 {EntryWidgetCmd procedure, "insert" widget command} { + list [catch {.e insert a} msg] $msg +} {1 {wrong # args: should be ".e insert index text"}} +test entry-3.31 {EntryWidgetCmd procedure, "insert" widget command} { + list [catch {.e insert a b c} msg] $msg +} {1 {wrong # args: should be ".e insert index text"}} +test entry-3.32 {EntryWidgetCmd procedure, "insert" widget command} { + list [catch {.e insert foo Text} msg] $msg +} {1 {bad entry index "foo"}} +test entry-3.33 {EntryWidgetCmd procedure, "insert" widget command} { + .e delete 0 end + .e insert end "01234567890" + .e insert 3 xxx + .e get +} {012xxx34567890} +test entry-3.34 {EntryWidgetCmd procedure, "insert" widget command} { + .e delete 0 end + .e insert end "01234567890" + .e configure -state disabled + .e insert 3 xxx + .e configure -state normal + .e get +} {01234567890} +test entry-3.35 {EntryWidgetCmd procedure, "insert" widget command} { + list [catch {.e insert a b c} msg] $msg +} {1 {wrong # args: should be ".e insert index text"}} +test entry-3.36 {EntryWidgetCmd procedure, "scan" widget command} { + list [catch {.e scan a} msg] $msg +} {1 {wrong # args: should be ".e scan mark|dragto x"}} +test entry-3.37 {EntryWidgetCmd procedure, "scan" widget command} { + list [catch {.e scan a b c} msg] $msg +} {1 {wrong # args: should be ".e scan mark|dragto x"}} +test entry-3.38 {EntryWidgetCmd procedure, "scan" widget command} { + list [catch {.e scan foobar 20} msg] $msg +} {1 {bad scan option "foobar": must be mark or dragto}} +test entry-3.39 {EntryWidgetCmd procedure, "scan" widget command} { + list [catch {.e scan mark 20.1} msg] $msg +} {1 {expected integer but got "20.1"}} +# This test is non-portable because character sizes vary. + +test entry-3.40 {EntryWidgetCmd procedure, "scan" widget command} {fonts} { + .e delete 0 end + update + .e insert end "This is quite a long string, in fact a " + .e insert end "very very long string" + .e scan mark 30 + .e scan dragto 28 + .e index @0 +} {2} +test entry-3.41 {EntryWidgetCmd procedure, "select" widget command} { + list [catch {.e select} msg] $msg +} {1 {wrong # args: should be ".e select option ?index?"}} +test entry-3.42 {EntryWidgetCmd procedure, "select" widget command} { + list [catch {.e select foo} msg] $msg +} {1 {bad selection option "foo": must be adjust, clear, from, present, range, or to}} +test entry-3.43 {EntryWidgetCmd procedure, "select clear" widget command} { + list [catch {.e select clear gorp} msg] $msg +} {1 {wrong # args: should be ".e selection clear"}} +test entry-3.44 {EntryWidgetCmd procedure, "select clear" widget command} { + .e delete 0 end + .e insert end "0123456789" + .e select from 1 + .e select to 4 + update + .e select clear + list [catch {selection get} msg] $msg [selection own] +} {1 {PRIMARY selection doesn't exist or form "STRING" not defined} .e} +test entry-3.45 {EntryWidgetCmd procedure, "selection present" widget command} { + list [catch {.e selection present foo} msg] $msg +} {1 {wrong # args: should be ".e selection present"}} +test entry-3.46 {EntryWidgetCmd procedure, "selection present" widget command} { + .e delete 0 end + .e insert end 0123456789 + .e select from 3 + .e select to 6 + .e selection present +} {1} +test entry-3.47 {EntryWidgetCmd procedure, "selection present" widget command} { + .e delete 0 end + .e insert end 0123456789 + .e select from 3 + .e select to 6 + .e configure -exportselection false + .e selection present +} {1} +.e configure -exportselection true +test entry-3.48 {EntryWidgetCmd procedure, "selection present" widget command} { + .e delete 0 end + .e insert end 0123456789 + .e select from 3 + .e select to 6 + .e delete 0 end + .e selection present +} {0} +test entry-3.49 {EntryWidgetCmd procedure, "selection adjust" widget command} { + list [catch {.e select adjust x} msg] $msg +} {1 {bad entry index "x"}} +test entry-3.50 {EntryWidgetCmd procedure, "selection adjust" widget command} { + list [catch {.e select adjust 2 3} msg] $msg +} {1 {wrong # args: should be ".e selection adjust index"}} +test entry-3.51 {EntryWidgetCmd procedure, "selection adjust" widget command} { + .e delete 0 end + .e insert end "0123456789" + .e select from 1 + .e select to 5 + update + .e select adjust 4 + selection get +} {123} +test entry-3.52 {EntryWidgetCmd procedure, "selection adjust" widget command} { + .e delete 0 end + .e insert end "0123456789" + .e select from 1 + .e select to 5 + update + .e select adjust 2 + selection get +} {234} +test entry-3.53 {EntryWidgetCmd procedure, "selection from" widget command} { + list [catch {.e select from 2 3} msg] $msg +} {1 {wrong # args: should be ".e selection from index"}} +test entry-3.54 {EntryWidgetCmd procedure, "selection range" widget command} { + list [catch {.e select range 2} msg] $msg +} {1 {wrong # args: should be ".e selection range start end"}} +test entry-3.55 {EntryWidgetCmd procedure, "selection range" widget command} { + list [catch {.e selection range 2 3 4} msg] $msg +} {1 {wrong # args: should be ".e selection range start end"}} +test entry-3.56 {EntryWidgetCmd procedure, "selection range" widget command} { + .e delete 0 end + .e insert end 0123456789 + .e select from 1 + .e select to 5 + .e select range 4 4 + list [catch {.e index sel.first} msg] $msg +} {1 {selection isn't in entry}} +test entry-3.57 {EntryWidgetCmd procedure, "selection range" widget command} { + .e delete 0 end + .e insert end 0123456789 + .e select from 3 + .e select to 7 + .e select range 2 9 + list [.e index sel.first] [.e index sel.last] [.e index anchor] +} {2 9 3} +.e delete 0 end +.e insert end "This is quite a long text string, so long that it " +.e insert end "runs off the end of the window quite a bit." +test entry-3.58 {EntryWidgetCmd procedure, "selection to" widget command} { + list [catch {.e select to 2 3} msg] $msg +} {1 {wrong # args: should be ".e selection to index"}} +test entry-3.59 {EntryWidgetCmd procedure, "xview" widget command} { + .e xview 5 + .e xview +} {0.0537634 0.268817} +test entry-3.60 {EntryWidgetCmd procedure, "xview" widget command} { + list [catch {.e xview gorp} msg] $msg +} {1 {bad entry index "gorp"}} +test entry-3.61 {EntryWidgetCmd procedure, "xview" widget command} { + .e xview 0 + .e icursor 10 + .e xview insert + .e xview +} {0.107527 0.322581} +test entry-3.62 {EntryWidgetCmd procedure, "xview" widget command} { + list [catch {.e xview moveto foo bar} msg] $msg +} {1 {wrong # args: should be ".e xview moveto fraction"}} +test entry-3.63 {EntryWidgetCmd procedure, "xview" widget command} { + list [catch {.e xview moveto foo} msg] $msg +} {1 {expected floating-point number but got "foo"}} +test entry-3.64 {EntryWidgetCmd procedure, "xview" widget command} { + .e xview moveto 0.5 + .e xview +} {0.505376 0.72043} +test entry-3.65 {EntryWidgetCmd procedure, "xview" widget command} { + list [catch {.e xview scroll 24} msg] $msg +} {1 {wrong # args: should be ".e xview scroll number units|pages"}} +test entry-3.66 {EntryWidgetCmd procedure, "xview" widget command} { + list [catch {.e xview scroll gorp units} msg] $msg +} {1 {expected integer but got "gorp"}} +test entry-3.67 {EntryWidgetCmd procedure, "xview" widget command} { + .e xview moveto 0 + .e xview scroll 1 pages + .e xview +} {0.193548 0.408602} +test entry-3.68 {EntryWidgetCmd procedure, "xview" widget command} { + .e xview moveto .9 + update + .e xview scroll -2 p + .e xview +} {0.397849 0.612903} +test entry-3.69 {EntryWidgetCmd procedure, "xview" widget command} { + .e xview 30 + update + .e xview scroll 2 units + .e index @0 +} {32} +test entry-3.70 {EntryWidgetCmd procedure, "xview" widget command} { + .e xview 30 + update + .e xview scroll -1 units + .e index @0 +} {29} +test entry-3.71 {EntryWidgetCmd procedure, "xview" widget command} { + list [catch {.e xview scroll 23 foobars} msg] $msg +} {1 {bad argument "foobars": must be units or pages}} +test entry-3.72 {EntryWidgetCmd procedure, "xview" widget command} { + list [catch {.e xview eat 23 hamburgers} msg] $msg +} {1 {unknown option "eat": must be moveto or scroll}} +test entry-3.73 {EntryWidgetCmd procedure, "xview" widget command} { + .e xview 0 + update + .e xview -4 + .e index @0 +} {0} +test entry-3.74 {EntryWidgetCmd procedure, "xview" widget command} { + .e xview 300 + .e index @0 +} {73} +test entry-3.75 {EntryWidgetCmd procedure} { + list [catch {.e gorp} msg] $msg +} {1 {bad option "gorp": must be bbox, cget, configure, delete, get, icursor, index, insert, scan, selection, or xview}} + +# The test below doesn't actually check anything directly, but if run +# with Purify or some other memory-allocation-checking program it will +# ensure that resources get properly freed. + +test entry-4.1 {DestroyEntry procedure} { + catch {destroy .e} + entry .e -textvariable x -show * + pack .e + .e insert end "Sample text" + update + destroy .e +} {} + +frame .f -width 200 -height 50 -relief raised -bd 2 +pack .f -side right +test entry-5.1 {ConfigureEntry procedure, -textvariable} { + catch {destroy .e} + set x 12345 + entry .e -textvariable x + .e get +} {12345} +test entry-5.2 {ConfigureEntry procedure, -textvariable} { + catch {destroy .e} + set x 12345 + entry .e -textvariable x + set y abcde + .e configure -textvariable y + set x 54321 + .e get +} {abcde} +test entry-5.3 {ConfigureEntry procedure, -textvariable} { + catch {destroy .e} + catch {unset x} + entry .e + .e insert 0 "Some text" + .e configure -textvariable x + set x +} {Some text} +test entry-5.4 {ConfigureEntry procedure, -textvariable} { + proc override args { + global x + set x 12345 + } + catch {destroy .e} + catch {unset x} + trace variable x w override + entry .e + .e insert 0 "Some text" + .e configure -textvariable x + set result [list $x [.e get]] + unset x; rename override {} + set result +} {12345 12345} +test entry-5.5 {ConfigureEntry procedure} { + catch {destroy .e} + entry .e -exportselection false + pack .e + .e insert end "0123456789" + .sel select from 0 + .sel select to 10 + set x {} + lappend x [selection get] + .e select from 1 + .e select to 5 + lappend x [selection get] + .e configure -exportselection 1 + lappend x [selection get] + set x +} {{This is so} {This is so} 1234} +test entry-5.6 {ConfigureEntry procedure} { + catch {destroy .e} + entry .e + pack .e + .e insert end "0123456789" + .e select from 1 + .e select to 5 + .e configure -exportselection 0 + list [catch {selection get} msg] $msg [.e index sel.first] \ + [.e index sel.last] +} {1 {PRIMARY selection doesn't exist or form "STRING" not defined} 1 5} +test entry-5.7 {ConfigureEntry procedure} { + catch {destroy .e} + entry .e -font $fixed -width 4 -xscrollcommand scroll + pack .e + .e insert end "01234567890" + update + .e configure -width 5 + set scrollInfo +} {0 0.363636} +test entry-5.8 {ConfigureEntry procedure} {fonts} { + catch {destroy .e} + entry .e -width 0 + pack .e + .e insert end "0123" + update + .e configure -font $big + update + winfo geom .e +} {62x37+0+0} +test entry-5.9 {ConfigureEntry procedure} {fonts} { + catch {destroy .e} + entry .e -font $fixed -bd 2 -relief raised + pack .e + .e insert end "0123" + update + list [.e index @10] [.e index @11] [.e index @12] [.e index @13] +} {0 0 1 1} +test entry-5.10 {ConfigureEntry procedure} {fonts} { + catch {destroy .e} + entry .e -font $fixed -bd 2 -relief flat + pack .e + .e insert end "0123" + update + list [.e index @10] [.e index @11] [.e index @12] [.e index @13] +} {0 0 1 1} +test entry-5.11 {ConfigureEntry procedure} { + # If "0" in selected font had 0 width, caused divide-by-zero error. + + catch {destroy .e} + pack [entry .e -font {{open look glyph}}] + .e scan dragto 30 + update +} {} + +# No tests for DisplayEntry. + +test entry-6.1 {EntryComputeGeometry procedure} {fonts} { + catch {destroy .e} + entry .e -font $fixed -bd 2 -relief raised -width 20 -highlightthickness 3 + pack .e + .e insert end 012\t45 + update + list [.e index @61] [.e index @62] +} {3 4} +test entry-6.2 {EntryComputeGeometry procedure} {fonts} { + catch {destroy .e} + entry .e -font $fixed -bd 2 -relief raised -width 20 -justify center \ + -highlightthickness 3 + pack .e + .e insert end 012\t45 + update + list [.e index @96] [.e index @97] +} {3 4} +test entry-6.3 {EntryComputeGeometry procedure} {fonts} { + catch {destroy .e} + entry .e -font $fixed -bd 2 -relief raised -width 20 -justify right \ + -highlightthickness 3 + pack .e + .e insert end 012\t45 + update + list [.e index @131] [.e index @132] +} {3 4} +test entry-6.4 {EntryComputeGeometry procedure} { + catch {destroy .e} + entry .e -font $fixed -bd 2 -relief raised -width 5 + pack .e + .e insert end "01234567890" + update + .e xview 6 + .e index @0 +} {6} +test entry-6.5 {EntryComputeGeometry procedure} { + catch {destroy .e} + entry .e -font $fixed -bd 2 -relief raised -width 5 + pack .e + .e insert end "01234567890" + update + .e xview 7 + .e index @0 +} {6} +test entry-6.6 {EntryComputeGeometry procedure} {fonts} { + catch {destroy .e} + entry .e -font $fixed -bd 2 -relief raised -width 10 + pack .e + .e insert end "01234\t67890" + update + .e xview 3 + list [.e index @39] [.e index @40] +} {5 6} +test entry-6.7 {EntryComputeGeometry procedure} {fonts} { + catch {destroy .e} + entry .e -font $big -bd 3 -relief raised -width 5 + pack .e + .e insert end "01234567" + update + list [winfo reqwidth .e] [winfo reqheight .e] +} {77 39} +test entry-6.8 {EntryComputeGeometry procedure} {fonts} { + catch {destroy .e} + entry .e -font $big -bd 3 -relief raised -width 0 + pack .e + .e insert end "01234567" + update + list [winfo reqwidth .e] [winfo reqheight .e] +} {116 39} +test entry-6.9 {EntryComputeGeometry procedure} {fonts} { + catch {destroy .e} + entry .e -font $big -bd 3 -relief raised -width 0 -highlightthickness 2 + pack .e + update + list [winfo reqwidth .e] [winfo reqheight .e] +} {25 39} +test entry-6.10 {EntryComputeGeometry procedure} {fonts} { + catch {destroy .e} + entry .e -bd 1 -relief raised -width 0 -show . + .e insert 0 12345 + pack .e + update + set x [winfo reqwidth .e] + .e configure -show X + lappend x [winfo reqwidth .e] + .e configure -show "" + lappend x [winfo reqwidth .e] +} {23 53 43} + +catch {destroy .e} +entry .e -width 10 -font $fixed -textvariable contents -xscrollcommand scroll +pack .e +focus .e +test entry-7.1 {InsertChars procedure} { + .e delete 0 end + .e insert 0 abcde + .e insert 2 XXX + update + list [.e get] $contents $scrollInfo +} {abXXXcde abXXXcde {0 1}} +test entry-7.2 {InsertChars procedure} { + .e delete 0 end + .e insert 0 abcde + .e insert 500 XXX + update + list [.e get] $contents $scrollInfo +} {abcdeXXX abcdeXXX {0 1}} +test entry-7.3 {InsertChars procedure} { + .e delete 0 end + .e insert 0 0123456789 + .e select from 2 + .e select to 6 + .e insert 2 XXX + set x "[.e index sel.first] [.e index sel.last]" + .e select to 8 + lappend x [.e index sel.first] [.e index sel.last] +} {5 9 5 8} +test entry-7.4 {InsertChars procedure} { + .e delete 0 end + .e insert 0 0123456789 + .e select from 2 + .e select to 6 + .e insert 3 XXX + set x "[.e index sel.first] [.e index sel.last]" + .e select to 8 + lappend x [.e index sel.first] [.e index sel.last] +} {2 9 2 8} +test entry-7.5 {InsertChars procedure} { + .e delete 0 end + .e insert 0 0123456789 + .e select from 2 + .e select to 6 + .e insert 5 XXX + set x "[.e index sel.first] [.e index sel.last]" + .e select to 8 + lappend x [.e index sel.first] [.e index sel.last] +} {2 9 2 8} +test entry-7.6 {InsertChars procedure} { + .e delete 0 end + .e insert 0 0123456789 + .e select from 2 + .e select to 6 + .e insert 6 XXX + set x "[.e index sel.first] [.e index sel.last]" + .e select to 5 + lappend x [.e index sel.first] [.e index sel.last] +} {2 6 2 5} +test entry-7.7 {InsertChars procedure} { + .e delete 0 end + .e insert 0 0123456789 + .e icursor 4 + .e insert 4 XXX + .e index insert +} {7} +test entry-7.8 {InsertChars procedure} { + .e delete 0 end + .e insert 0 0123456789 + .e icursor 4 + .e insert 5 XXX + .e index insert +} {4} +test entry-7.9 {InsertChars procedure} { + .e delete 0 end + .e insert 0 "This is a very long string" + update + .e xview 4 + .e insert 3 XXX + .e index @0 +} {7} +test entry-7.10 {InsertChars procedure} { + .e delete 0 end + .e insert 0 "This is a very long string" + update + .e xview 4 + .e insert 4 XXX + .e index @0 +} {4} +.e configure -width 0 +test entry-7.11 {InsertChars procedure} {fonts} { + .e delete 0 end + .e insert 0 "xyzzy" + update + .e insert 2 00 + winfo reqwidth .e +} {59} + +.e configure -width 10 +test entry-8.1 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 abcde + .e delete 2 4 + update + list [.e get] $contents $scrollInfo +} {abe abe {0 1}} +test entry-8.2 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 abcde + .e delete -2 2 + update + list [.e get] $contents $scrollInfo +} {cde cde {0 1}} +test entry-8.3 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 abcde + .e delete 3 1000 + update + list [.e get] $contents $scrollInfo +} {abc abc {0 1}} +test entry-8.4 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e select from 3 + .e select to 8 + .e delete 1 3 + update + set x "[.e index sel.first] [.e index sel.last]" + .e select to 5 + lappend x [.e index sel.first] [.e index sel.last] +} {1 6 1 5} +test entry-8.5 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e select from 3 + .e select to 8 + .e delete 1 4 + update + set x "[.e index sel.first] [.e index sel.last]" + .e select to 4 + lappend x [.e index sel.first] [.e index sel.last] +} {1 5 1 4} +test entry-8.6 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e select from 3 + .e select to 8 + .e delete 1 7 + update + set x "[.e index sel.first] [.e index sel.last]" + .e select to 5 + lappend x [.e index sel.first] [.e index sel.last] +} {1 2 1 5} +test entry-8.7 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e select from 3 + .e select to 8 + .e delete 1 8 + list [catch {.e index sel.first} msg] $msg +} {1 {selection isn't in entry}} +test entry-8.8 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e select from 3 + .e select to 8 + .e delete 3 7 + update + set x "[.e index sel.first] [.e index sel.last]" + .e select to 8 + lappend x [.e index sel.first] [.e index sel.last] +} {3 4 3 8} +test entry-8.9 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e select from 3 + .e select to 8 + .e delete 3 8 + list [catch {.e index sel.first} msg] $msg +} {1 {selection isn't in entry}} +test entry-8.10 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e select from 8 + .e select to 3 + .e delete 5 8 + update + set x "[.e index sel.first] [.e index sel.last]" + .e select to 8 + lappend x [.e index sel.first] [.e index sel.last] +} {3 5 5 8} +test entry-8.11 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e select from 8 + .e select to 3 + .e delete 8 10 + update + set x "[.e index sel.first] [.e index sel.last]" + .e select to 4 + lappend x [.e index sel.first] [.e index sel.last] +} {3 8 4 8} +test entry-8.12 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e icursor 4 + .e delete 1 4 + .e index insert +} {1} +test entry-8.13 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e icursor 4 + .e delete 1 5 + .e index insert +} {1} +test entry-8.14 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 0123456789abcde + .e icursor 4 + .e delete 4 6 + .e index insert +} {4} +test entry-8.15 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 "This is a very long string" + .e xview 4 + .e delete 1 4 + .e index @0 +} {1} +test entry-8.16 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 "This is a very long string" + .e xview 4 + .e delete 1 5 + .e index @0 +} {1} +test entry-8.17 {DeleteChars procedure} { + .e delete 0 end + .e insert 0 "This is a very long string" + .e xview 4 + .e delete 4 6 + .e index @0 +} {4} +.e configure -width 0 +test entry-8.18 {DeleteChars procedure} {fonts} { + .e delete 0 end + .e insert 0 "xyzzy" + update + .e delete 2 4 + winfo reqwidth .e +} {31} + +test entry-9.1 {EntryValueChanged procedure} { + catch {destroy .e} + proc override args { + global x + set x 12345 + } + catch {unset x} + trace variable x w override + entry .e -textvariable x + .e insert 0 foo + set result [list $x [.e get]] + unset x; rename override {} + set result +} {12345 12345} + +catch {destroy .e} +entry .e +pack .e +.e configure -width 0 +test entry-10.1 {EntrySetValue procedure} {fonts} { + set x abcde + set y ab + .e configure -textvariable x + update + .e configure -textvariable y + update + list [.e get] [winfo reqwidth .e] +} {ab 24} +test entry-10.2 {EntrySetValue procedure, updating selection} { + catch {destroy .e} + entry .e -textvariable x + .e insert 0 "abcdefghjklmnopqrstu" + .e selection range 4 10 + set x "a" + list [catch {.e index sel.first} msg] $msg +} {1 {selection isn't in entry}} +test entry-10.3 {EntrySetValue procedure, updating selection} { + catch {destroy .e} + entry .e -textvariable x + .e insert 0 "abcdefghjklmnopqrstu" + .e selection range 4 10 + set x "abcdefg" + list [.e index sel.first] [.e index sel.last] +} {4 7} +test entry-10.4 {EntrySetValue procedure, updating selection} { + catch {destroy .e} + entry .e -textvariable x + .e insert 0 "abcdefghjklmnopqrstu" + .e selection range 4 10 + set x "abcdefghijklmn" + list [.e index sel.first] [.e index sel.last] +} {4 10} +test entry-10.5 {EntrySetValue procedure, updating display position} { + catch {destroy .e} + entry .e -width 10 -font $fixed -textvariable x + pack .e + .e insert 0 "abcdefghjklmnopqrstuvwxyz" + .e xview 10 + update + set x "abcdefg" + update + .e index @0 +} {0} +test entry-10.6 {EntrySetValue procedure, updating display position} { + catch {destroy .e} + entry .e -width 10 -font $fixed -textvariable x + pack .e + .e insert 0 "abcdefghjklmnopqrstuvwxyz" + .e xview 10 + update + set x "1234567890123456789012" + update + .e index @0 +} {10} +test entry-10.7 {EntrySetValue procedure, updating insertion cursor} { + catch {destroy .e} + entry .e -width 10 -font $fixed -textvariable x + pack .e + .e insert 0 "abcdefghjklmnopqrstuvwxyz" + .e icursor 5 + set x "123" + .e index insert +} {3} +test entry-10.8 {EntrySetValue procedure, updating insertion cursor} { + catch {destroy .e} + entry .e -width 10 -font $fixed -textvariable x + pack .e + .e insert 0 "abcdefghjklmnopqrstuvwxyz" + .e icursor 5 + set x "123456" + .e index insert +} {5} + +test entry-11.1 {EntryEventProc procedure} { + catch {destroy .e} + entry .e + .e insert 0 abcdefg + destroy .e + update +} {} +test entry-11.2 {EntryEventProc procedure} { + eval destroy [winfo children .] + entry .e1 -fg #112233 + rename .e1 .e2 + set x {} + lappend x [winfo children .] + lappend x [.e2 cget -fg] + destroy .e1 + lappend x [info command .e*] [winfo children .] +} {.e1 #112233 {} {}} + +test entry-12.1 {EntryCmdDeletedProc procedure} { + eval destroy [winfo children .] + button .e1 -text "xyz_123" + rename .e1 {} + list [info command .e*] [winfo children .] +} {{} {}} + +catch {destroy .e} +entry .e -font $fixed -width 5 -bd 2 -relief sunken +pack .e +.e insert 0 012345678901234567890 +.e xview 4 +update +test entry-13.1 {GetEntryIndex procedure} { + .e index end +} {21} +test entry-13.2 {GetEntryIndex procedure} { + list [catch {.e index abogus} msg] $msg +} {1 {bad entry index "abogus"}} +test entry-13.3 {GetEntryIndex procedure} { + .e select from 1 + .e select to 6 + .e index anchor +} {1} +test entry-13.4 {GetEntryIndex procedure} { + .e select from 4 + .e select to 1 + .e index anchor +} {4} +test entry-13.5 {GetEntryIndex procedure} { + .e select from 3 + .e select to 15 + .e select adjust 4 + .e index anchor +} {15} +test entry-13.6 {GetEntryIndex procedure} { + list [catch {.e index ebogus} msg] $msg +} {1 {bad entry index "ebogus"}} +test entry-13.7 {GetEntryIndex procedure} { + .e icursor 2 + .e index insert +} {2} +test entry-13.8 {GetEntryIndex procedure} { + list [catch {.e index ibogus} msg] $msg +} {1 {bad entry index "ibogus"}} +test entry-13.9 {GetEntryIndex procedure} { + .e select from 1 + .e select to 6 + list [.e index sel.first] [.e index sel.last] +} {1 6} +selection clear .e +test entry-13.10 {GetEntryIndex procedure} {pc} { + .e index sel.first +} {1} +test entry-13.11 {GetEntryIndex procedure} {!pc} { + list [catch {.e index sel.first} msg] $msg +} {1 {selection isn't in entry}} +test entry-13.12 {GetEntryIndex procedure} {pc} { + list [catch {.e index sbogus} msg] $msg +} {1 {bad entry index "sbogus"}} +test entry-13.13 {GetEntryIndex procedure} {!pc} { + list [catch {.e index sbogus} msg] $msg +} {1 {selection isn't in entry}} +test entry-13.14 {GetEntryIndex procedure} { + list [catch {.e index @xyz} msg] $msg +} {1 {bad entry index "@xyz"}} +test entry-13.15 {GetEntryIndex procedure} {fonts} { + .e index @4 +} {4} +test entry-13.16 {GetEntryIndex procedure} {fonts} { + .e index @11 +} {4} +test entry-13.17 {GetEntryIndex procedure} {fonts} { + .e index @12 +} {5} +test entry-13.18 {GetEntryIndex procedure} {fonts} { + .e index @[expr [winfo width .e] - 6] +} {8} +test entry-13.19 {GetEntryIndex procedure} {fonts} { + .e index @[expr [winfo width .e] - 5] +} {9} +test entry-13.20 {GetEntryIndex procedure} { + .e index @1000 +} {9} +test entry-13.21 {GetEntryIndex procedure} { + list [catch {.e index 1xyz} msg] $msg +} {1 {bad entry index "1xyz"}} +test entry-13.22 {GetEntryIndex procedure} { + .e index -10 +} {0} +test entry-13.23 {GetEntryIndex procedure} { + .e index 12 +} {12} +test entry-13.24 {GetEntryIndex procedure} { + .e index 49 +} {21} +test entry-13.25 {GetEntryIndex procedure} {fonts} { + catch {destroy .e} + entry .e -show . + .e insert 0 XXXYZZY + pack .e + update + list [.e index @7] [.e index @8] +} {0 1} + +# XXX Still need to write tests for EntryScanTo and EntrySelectTo. + +set x {} +for {set i 1} {$i <= 500} {incr i} { + append x "This is line $i, out of 500\n" +} +test entry-14.1 {EntryFetchSelection procedure} { + catch {destroy .e} + entry .e + .e insert end "This is a test string" + .e select from 1 + .e select to 18 + selection get +} {his is a test str} +test entry-14.2 {EntryFetchSelection procedure} { + catch {destroy .e} + entry .e -show * + .e insert end "This is a test string" + .e select from 1 + .e select to 18 + selection get +} {*****************} +test entry-14.3 {EntryFetchSelection procedure} { + catch {destroy .e} + entry .e + .e insert end $x + .e select from 0 + .e select to end + string compare [selection get] $x +} 0 + +test entry-15.1 {EntryLostSelection} { + catch {destroy .e} + entry .e + .e insert 0 "Text" + .e select from 0 + .e select to 4 + set result [selection get] + selection clear + .e select from 0 + .e select to 4 + lappend result [selection get] +} {Text Text} + +# No tests for EventuallyRedraw. + +catch {destroy .e} +entry .e -width 10 -xscrollcommand scroll +pack .e +update + +test entry-16.1 {EntryVisibleRange procedure} {fonts} { + .e delete 0 end + .e insert 0 ............................. + .e xview +} {0 0.827586} +test entry-16.2 {EntryVisibleRange procedure} {fonts} { + .e configure -show X + .e delete 0 end + .e insert 0 ............................. + .e xview +} {0 0.275862} +.e configure -show "" +test entry-16.3 {EntryVisibleRange procedure} { + .e delete 0 end + .e xview +} {0 1} + +catch {destroy .e} +entry .e -width 10 -xscrollcommand scroll -font $fixed +pack .e +update +test entry-17.1 {EntryUpdateScrollbar procedure} { + .e delete 0 end + .e insert 0 123 + update + set scrollInfo +} {0 1} +test entry-17.2 {EntryUpdateScrollbar procedure} { + .e delete 0 end + .e insert 0 0123456789abcdef + .e xview 3 + update + set scrollInfo +} {0.1875 0.8125} +test entry-17.3 {EntryUpdateScrollbar procedure} { + .e delete 0 end + .e insert 0 abcdefghijklmnopqrs + .e xview 6 + update + set scrollInfo +} {0.315789 0.842105} +test entry-17.4 {EntryUpdateScrollbar procedure} { + catch {destroy .e} + proc bgerror msg { + global x + set x $msg + } + entry .e -width 5 -xscrollcommand bogus + pack .e + update + rename bgerror {} + list $x $errorInfo +} {{invalid command name "bogus"} {invalid command name "bogus" + while executing +"bogus 0 1" + (horizontal scrolling command executed by entry)}} + +set l [interp hidden] +eval destroy [winfo children .] + +test entry-18.1 {Entry widget vs hiding} { + catch {destroy .e} + entry .e + interp hide {} .e + destroy .e + list [winfo children .] [interp hidden] +} [list {} $l] + +# XXX Still need to write tests for EntryBlinkProc, EntryFocusProc, +# and EntryTextVarProc. + + +option clear diff --git a/tests/event.test b/tests/event.test new file mode 100644 index 0000000..a8ab3de --- /dev/null +++ b/tests/event.test @@ -0,0 +1,41 @@ +# This file is a Tcl script to test the code in tkEvent.c. It is +# organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) event.test 1.6 96/09/12 09:25:44 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +# XXX This test file is woefully incomplete. Right now it only tests +# a few of the procedures in tkEvent.c. Please add more tests whenever +# possible. + +test event-1.1 {Tk_HandleEvent procedure, filter events for dead windows} { + button .b -text Test + pack .b + bindtags .b .b + update + bind .b <Destroy> { + lappend x destroy + event generate .b <1> + } + bind .b <1> { + lappend x button + } + set x {} + destroy .b + set x +} {destroy} diff --git a/tests/filebox.test b/tests/filebox.test new file mode 100644 index 0000000..6bae6c5 --- /dev/null +++ b/tests/filebox.test @@ -0,0 +1,251 @@ +# This file is a Tcl script to test out Tk's "tk_getOpenFile" and +# "tk_getSaveFile" commands. It is organized in the standard fashion +# for Tcl tests. +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) filebox.test 1.5 97/10/10 11:03:21 +# + +set tk_strictMotif_old $tk_strictMotif + +#---------------------------------------------------------------------- +# +# Procedures needed by this test file +# +#---------------------------------------------------------------------- + +proc ToPressButton {parent btn} { + global isNative + if {!$isNative} { + after 100 SendButtonPress $parent $btn mouse + } +} + +proc ToEnterFileByKey {parent fileName fileDir} { + global isNative + if {!$isNative} { + after 100 EnterFileByKey $parent [list $fileName] [list $fileDir] + } +} + +proc PressButton {btn} { + event generate $btn <Enter> + event generate $btn <1> -x 5 -y 5 + event generate $btn <ButtonRelease-1> -x 5 -y 5 +} + +proc EnterFileByKey {parent fileName fileDir} { + global tk_strictMotif + set w .__tk_filedialog + upvar #0 [winfo name $w] data + + if {$tk_strictMotif} { + $data(sEnt) delete 0 end + $data(sEnt) insert 0 [file join $fileDir $fileName] + } else { + $data(ent) delete 0 end + $data(ent) insert 0 $fileName + } + + update + SendButtonPress $parent ok mouse +} + +proc SendButtonPress {parent btn type} { + global tk_strictMotif + set w .__tk_filedialog + upvar #0 [winfo name $w] data + + set button $data($btn\Btn) + if ![winfo ismapped $button] { + update + } + + if {$type == "mouse"} { + PressButton $button + } else { + event generate $w <Enter> + focus $w + event generate $button <Enter> + event generate $w <KeyPress> -keysym Return + } +} + + +#---------------------------------------------------------------------- +# +# The test suite proper +# +#---------------------------------------------------------------------- + +if {[string compare test [info procs test]] == 1} { + source defs +} + +if {$tcl_platform(platform) == "unix"} { + set modes "0 1" +} else { + set modes 1 +} + +set unknownOptionsMsg {1 {unknown option "-foo", must be -defaultextension, -filetypes, -initialdir, -initialfile, -parent or -title}} + +foreach mode $modes { + + # + # Test both the motif version and the "tk" version of the file dialog + # box on Unix. + # + + if {$tcl_platform(platform) == "unix"} { + set tk_strictMotif $mode + } + + # + # Test both the "open" and the "save" dialogs + # + + foreach command "tk_getOpenFile tk_getSaveFile" { + + test filebox-1.1 "$command command" { + list [catch {$command -foo} msg] $msg + } $unknownOptionsMsg + + regsub -all , $msg "" options + regsub \"-foo\" $options "" options + + foreach option $options { + if {[string index $option 0] == "-"} { + test filebox-1.2 "$command command" { + list [catch {$command $option} msg] $msg + } [list 1 "value for \"$option\" missing"] + } + } + + test filebox-1.3 "$command command" { + list [catch {$command -foo bar} msg] $msg + } $unknownOptionsMsg + + test filebox-1.4 "$command command" { + list [catch {$command -initialdir} msg] $msg + } {1 {value for "-initialdir" missing}} + + test filebox-1.5 "$command command" { + list [catch {$command -parent foo.bar} msg] $msg + } {1 {bad window path name "foo.bar"}} + + test filebox-1.6 "$command command" { + list [catch {$command -filetypes {Foo}} msg] $msg + } {1 {bad file type "Foo", should be "typeName {extension ?extensions ...?} ?{macType ?macTypes ...?}?"}} + + if {[info commands tkMotifFDialog] == "" && [info commands tkFDialog] == ""} { + set isNative 1 + } else { + set isNative 0 + } + + if {$isNative && ![info exists INTERACTIVE]} { + continue + } + + set parent . + + set verylongstring longstring: + set verylongstring $verylongstring$verylongstring + set verylongstring $verylongstring$verylongstring + set verylongstring $verylongstring$verylongstring + set verylongstring $verylongstring$verylongstring +# set verylongstring $verylongstring$verylongstring +# set verylongstring $verylongstring$verylongstring +# set verylongstring $verylongstring$verylongstring +# set verylongstring $verylongstring$verylongstring +# set verylongstring $verylongstring$verylongstring + + set color #404040 + test filebox-2.1 "$command command" { + ToPressButton $parent cancel + $command -title "Press Cancel ($verylongstring)" -parent $parent + } "" + + + if {$command == "tk_getSaveFile"} { + set fileName "12x 455" + set fileDir [pwd] + set pathName [file join [pwd] $fileName] + } else { + set thisFile [info script] + set fileName [file tail $thisFile] + set appPWD [pwd] + cd [file dirname $thisFile] + set fileDir [pwd] + cd $appPWD + set pathName [file join $fileDir $fileName] + } + + test filebox-2.2 "$command command" { + ToPressButton $parent ok + set choice [$command -title "Press Ok" \ + -parent $parent -initialfile $fileName -initialdir $fileDir] + } $pathName + + test filebox-2.3 "$command command" { + ToEnterFileByKey $parent $fileName $fileDir + set choice [$command -title "Enter \"$fileName\" and press Ok" \ + -parent $parent -initialdir $fileDir] + } $pathName + + set filters(1) {} + + set filters(2) { + {"Text files" {.txt .doc} } + {"Text files" {} TEXT} + {"Tcl Scripts" {.tcl} TEXT} + {"C Source Files" {.c .h} } + {"All Source Files" {.tcl .c .h} } + {"Image Files" {.gif} } + {"Image Files" {.jpeg .jpg} } + {"Image Files" "" {GIFF JPEG}} + {"All files" *} + } + + set filters(3) { + {"Text files" {.txt .doc} TEXT} + {"Foo" {""} TEXT} + } + + foreach x [lsort -integer [array names filters]] { + test filebox-3.$x "$command command" { + ToPressButton $parent ok + set choice [$command -title "Press Ok" -filetypes $filters($x)\ + -parent $parent -initialfile $fileName -initialdir $fileDir] + } $pathName + } + + # + # The rest of the tests need to be executed on Unix only. The test whether + # the dialog box widgets were implemented correctly. These tests are not + # needed on the other platforms because they use native file dialogs. + # + + + + + # end inner if + } + + # end outer if +} + +set tk_strictMotif $tk_strictMotif_old + +if {$isNative && ![info exists INTERACTIVE]} { + puts " Some tests were skipped because they could not be performed" + puts " automatically on this platform. If you wish to execute them" + puts " interactively, set the TCL variable INTERACTIVE and re-run" + puts " the test." + return +} diff --git a/tests/focus.test b/tests/focus.test new file mode 100644 index 0000000..4aa4da3 --- /dev/null +++ b/tests/focus.test @@ -0,0 +1,630 @@ +# This file is a Tcl script to test out the "focus" command and the +# other procedures in the file tkFocus.c. It is organized in the +# standard fashion for Tcl tests. +# +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) focus.test 1.24 97/08/11 09:39:34 + +if {$tcl_platform(platform) != "unix"} { + return +} + +if {[info procs test] != "test"} { + source defs +} + +eval destroy [winfo children .] +wm geometry . {} +raise . + +button .b -text .b -relief raised -bd 2 +pack .b + +proc focusSetup {} { + catch {destroy .t} + toplevel .t + wm geom .t +0+0 + foreach i {b1 b2 b3 b4} { + button .t.$i -text .t.$i -relief raised -bd 2 + pack .t.$i + } + tkwait visibility .t.b4 +} +proc focusSetupAlt {} { + global env + catch {destroy .alt} + toplevel .alt -screen $env(TK_ALT_DISPLAY) + wm withdraw .alt + foreach i {a b c d} { + button .alt.$i -text .alt.$i -relief raised -bd 2 + pack .alt.$i + } + tkwait visibility .alt.d +} + +# Make sure the window manager knows who has focus +fixfocus + +# The following procedure ensures that there is no input focus +# in this application. It does it by arranging for another +# application to grab the focus. The "after" and "update" stuff +# is needed to wait long enough for pending actions to get through +# the X server and possibly also the window manager. + +setupbg +proc focusClear {} { + global x; + after 200 {set x 1} + tkwait variable x + dobg {focus -force .; update} + update +} + +focusSetup +set altDisplay [info exists env(TK_ALT_DISPLAY)] +if $altDisplay { + focusSetupAlt +} +update + +bind all <FocusIn> { + append focusInfo "in %W %d\n" +} +bind all <FocusOut> { + append focusInfo "out %W %d\n" +} +bind all <KeyPress> { + append focusInfo "press %W %K" +} + +test focus-1.1 {Tk_FocusCmd procedure} { + focusClear + focus +} {} +if $altDisplay { + test focus-1.2 {Tk_FocusCmd procedure} { + focus .alt.b + focus + } {} +} +test focus-1.3 {Tk_FocusCmd procedure} { + focusClear + focus .t.b3 + focus +} {} +test focus-1.4 {Tk_FocusCmd procedure} { + list [catch {focus ""} msg] $msg +} {0 {}} +test focus-1.5 {Tk_FocusCmd procedure} { + focusClear + focus -force .t + focus .t.b3 + focus +} {.t.b3} +test focus-1.6 {Tk_FocusCmd procedure} { + list [catch {focus .gorp} msg] $msg +} {1 {bad window path name ".gorp"}} +test focus-1.7 {Tk_FocusCmd procedure} { + list [catch {focus .gorp a} msg] $msg +} {1 {bad option ".gorp": must be -displayof, -force, or -lastfor}} +test focus-1.8 {Tk_FocusCmd procedure, focussing on dead window} { + toplevel .t2 + wm geom .t2 +10+10 + frame .t2.f -width 200 -height 100 -bd 2 -relief raised + frame .t2.f2 -width 200 -height 100 -bd 2 -relief raised + pack .t2.f .t2.f2 + bind .t2.f <Destroy> {focus .t2.f} + bind .t2.f2 <Destroy> {focus .t2} + focus -force .t2.f2 + tkwait visibility .t2.f2 + update + set x [focus] + destroy .t2.f2 + lappend x [focus] + destroy .t2.f + lappend x [focus] + destroy .t2 + set x +} {.t2.f2 .t2 .t2} +test focus-1.9 {Tk_FocusCmd procedure, -displayof option} { + list [catch {focus -displayof} msg] $msg +} {1 {wrong # args: should be "focus -displayof window"}} +test focus-1.10 {Tk_FocusCmd procedure, -displayof option} { + list [catch {focus -displayof a b} msg] $msg +} {1 {wrong # args: should be "focus -displayof window"}} +test focus-1.11 {Tk_FocusCmd procedure, -displayof option} { + list [catch {focus -displayof .lousy} msg] $msg +} {1 {bad window path name ".lousy"}} +test focus-1.12 {Tk_FocusCmd procedure, -displayof option} { + focusClear + focus .t + focus -displayof .t.b3 +} {} +test focus-1.13 {Tk_FocusCmd procedure, -displayof option} { + focusClear + focus -force .t + focus -displayof .t.b3 +} {.t} +if $altDisplay { + test focus-1.14 {Tk_FocusCmd procedure, -displayof option} { + focus -force .alt.c + focus -displayof .alt + } {.alt.c} +} +test focus-1.15 {Tk_FocusCmd procedure, -force option} { + list [catch {focus -force} msg] $msg +} {1 {wrong # args: should be "focus -force window"}} +test focus-1.16 {Tk_FocusCmd procedure, -force option} { + list [catch {focus -force a b} msg] $msg +} {1 {wrong # args: should be "focus -force window"}} +test focus-1.17 {Tk_FocusCmd procedure, -force option} { + list [catch {focus -force foo} msg] $msg +} {1 {bad window path name "foo"}} +test focus-1.18 {Tk_FocusCmd procedure, -force option} { + list [catch {focus -force ""} msg] $msg +} {0 {}} +test focus-1.19 {Tk_FocusCmd procedure, -force option} { + focusClear + focus .t.b1 + set x [list [focus]] + focus -force .t.b1 + lappend x [focus] +} {{} .t.b1} +test focus-1.20 {Tk_FocusCmd procedure, -lastfor option} { + list [catch {focus -lastfor} msg] $msg +} {1 {wrong # args: should be "focus -lastfor window"}} +test focus-1.21 {Tk_FocusCmd procedure, -lastfor option} { + list [catch {focus -lastfor 1 2} msg] $msg +} {1 {wrong # args: should be "focus -lastfor window"}} +test focus-1.22 {Tk_FocusCmd procedure, -lastfor option} { + list [catch {focus -lastfor who_knows?} msg] $msg +} {1 {bad window path name "who_knows?"}} +test focus-1.23 {Tk_FocusCmd procedure, -lastfor option} { + focus .b + focus .t.b1 + list [focus -lastfor .] [focus -lastfor .t.b3] +} {.b .t.b1} +test focus-1.24 {Tk_FocusCmd procedure, -lastfor option} { + destroy .t + focusSetup + update + focus -lastfor .t.b2 +} {.t} +test focus-1.25 {Tk_FocusCmd procedure} { + list [catch {focus -unknown} msg] $msg +} {1 {bad option "-unknown": must be -displayof, -force, or -lastfor}} + +test focus-2.1 {TkFocusFilterEvent procedure} {nonPortable} { + focus -force .b + destroy .t + focusSetup + update + set focusInfo {} + event gen [testwrapper .t] <FocusIn> -detail NotifyAncestor -sendevent 0x54217567 + list $focusInfo +} {{}} +test focus-2.2 {TkFocusFilterEvent procedure} {nonPortable} { + focus -force .b + destroy .t + focusSetup + update + set focusInfo {} + event gen .t <FocusIn> -detail NotifyAncestor -sendevent 0x547321ac + list $focusInfo [focus] +} {{in .t NotifyAncestor +} .b} +test focus-2.3 {TkFocusFilterEvent procedure} {nonPortable} { + focus -force .b + destroy .t + focusSetup + update + set focusInfo {} + event gen [testwrapper .t] <FocusIn> -detail NotifyAncestor + update + list $focusInfo [focus -lastfor .t] +} {{out .b NotifyNonlinear +out . NotifyNonlinearVirtual +in .t NotifyNonlinear +} .t} +test focus-2.4 {TkFocusFilterEvent procedure, FocusIn events} {nonPortable} { + set result {} + focus .t.b1 + # Important to end with NotifyAncestor, which is an + # event that is processed normally. This has a side + # effect on text 2.5 + foreach detail {NotifyAncestor NotifyNonlinear + NotifyNonlinearVirtual NotifyPointer NotifyPointerRoot + NotifyVirtual NotifyAncestor} { + focus -force . + update + event gen [testwrapper .t] <FocusIn> -detail $detail + set focusInfo {} + update + lappend result $focusInfo + } + set result +} {{out . NotifyNonlinear +in .t NotifyNonlinearVirtual +in .t.b1 NotifyNonlinear +} {out . NotifyNonlinear +in .t NotifyNonlinearVirtual +in .t.b1 NotifyNonlinear +} {} {out . NotifyNonlinear +in .t NotifyNonlinearVirtual +in .t.b1 NotifyNonlinear +} {} {} {out . NotifyNonlinear +in .t NotifyNonlinearVirtual +in .t.b1 NotifyNonlinear +}} +test focus-2.5 {TkFocusFilterEvent procedure, creating FocusInfo struct} {nonPortable} { + focusSetup + focus .t.b1 + update + event gen [testwrapper .t] <FocusIn> -detail NotifyAncestor + list $focusInfo [focus] +} {{out . NotifyNonlinear +in .t NotifyNonlinearVirtual +in .t.b1 NotifyNonlinear +} .t.b1} +test focus-2.6 {TkFocusFilterEvent procedure, FocusIn events} { + focus .t.b1 + focus . + update + event gen [testwrapper .t] <FocusIn> -detail NotifyAncestor + set focusInfo {} + set x [focus] + event gen . <KeyPress-x> + list $x $focusInfo +} {.t.b1 {press .t.b1 x}} +test focus-2.7 {TkFocusFilterEvent procedure, FocusOut events} { + set result {} + foreach detail {NotifyAncestor NotifyInferior NotifyNonlinear + NotifyNonlinearVirtual NotifyPointer NotifyPointerRoot + NotifyVirtual} { + focus -force .t.b1 + event gen [testwrapper .t] <FocusOut> -detail $detail + update + lappend result [focus] + } + set result +} {{} .t.b1 {} {} .t.b1 .t.b1 {}} +test focus-2.8 {TkFocusFilterEvent procedure, FocusOut events} { + focus -force .t.b1 + event gen .t.b1 <FocusOut> -detail NotifyAncestor + focus +} {.t.b1} +test focus-2.9 {TkFocusFilterEvent procedure, FocusOut events} { + focus .t.b1 + event gen [testwrapper .] <FocusOut> -detail NotifyAncestor + focus +} {} +test focus-2.10 {TkFocusFilterEvent procedure, Enter events} { + set result {} + focus .t.b1 + focusClear + foreach detail {NotifyAncestor NotifyInferior NotifyNonlinear + NotifyNonlinearVirtual NotifyVirtual} { + event gen [testwrapper .t] <Enter> -detail $detail -focus 1 + update + lappend result [focus] + event gen [testwrapper .t] <Leave> -detail NotifyAncestor + update + } + set result +} {.t.b1 {} .t.b1 .t.b1 .t.b1} +test focus-2.11 {TkFocusFilterEvent procedure, Enter events} { + focusClear + set focusInfo {} + event gen [testwrapper .t] <Enter> -detail NotifyAncestor + update + set focusInfo +} {} +test focus-2.12 {TkFocusFilterEvent procedure, Enter events} { + focus -force .b + update + set focusInfo {} + event gen [testwrapper .t] <Enter> -detail NotifyAncestor -focus 1 + update + set focusInfo +} {} +test focus-2.13 {TkFocusFilterEvent procedure, Enter events} { + focus .t.b1 + focusClear + event gen [testwrapper .t] <Enter> -detail NotifyAncestor -focus 1 + set focusInfo {} + update + set focusInfo +} {in .t NotifyVirtual +in .t.b1 NotifyAncestor +} +test focus-2.14 {TkFocusFilterEvent procedure, Enter events, ignore errors when setting focus due to implicit focus} { + focusClear + catch {destroy .t2} + toplevel .t2 + wm withdraw .t2 + update + set focusInfo {} + event gen [testwrapper .t2] <Enter> -detail NotifyAncestor -focus 1 + update + destroy .t2 +} {} +test focus-2.15 {TkFocusFilterEvent procedure, Leave events} { + set result {} + focus .t.b1 + foreach detail {NotifyAncestor NotifyInferior NotifyNonlinear + NotifyNonlinearVirtual NotifyVirtual} { + focusClear + event gen [testwrapper .t] <Enter> -detail NotifyAncestor -focus 1 + update + event gen [testwrapper .t] <Leave> -detail $detail + update + lappend result [focus] + } + set result +} {{} .t.b1 {} {} {}} +test focus-2.16 {TkFocusFilterEvent procedure, Leave events} { + set result {} + focus .t.b1 + event gen [testwrapper .t] <Enter> -detail NotifyAncestor -focus 1 + update + set focusInfo {} + event gen [testwrapper .t] <Leave> -detail NotifyAncestor + update + set focusInfo +} {out .t.b1 NotifyAncestor +out .t NotifyVirtual +} +test focus-2.17 {TkFocusFilterEvent procedure, Leave events} { + set result {} + focus .t.b1 + event gen [testwrapper .t] <Enter> -detail NotifyAncestor -focus 1 + update + set focusInfo {} + event gen .t.b1 <Leave> -detail NotifyAncestor + event gen [testwrapper .] <Leave> -detail NotifyAncestor + update + list $focusInfo [focus] +} {{out .t.b1 NotifyAncestor +out .t NotifyVirtual +} {}} + +test focus-3.1 {SetFocus procedure, create record on focus} { + toplevel .t2 -width 250 -height 100 + wm geometry .t2 +0+0 + update + focus -force .t2 + update + focus +} {.t2} +catch {destroy .t2} +# This test produces no result, but it will generate a protocol +# error if Tk forgets to make the window exist before focussing +# on it. +test focus-3.2 {SetFocus procedure, making window exist} { + update + button .b2 -text "Another button" + focus .b2 + update +} {} +catch {destroy .b2} +update +# The following test doesn't produce a check-able result, but if +# there are bugs it may generate an X protocol error. +test focus-3.3 {SetFocus procedure, delaying claim of X focus} { + focusSetup + focus -force .t.b2 + update +} {} +test focus-3.4 {SetFocus procedure, delaying claim of X focus} { + focusSetup + wm withdraw .t + focus -force .t.b2 + toplevel .t2 -width 250 -height 100 + wm geometry .t2 +10+10 + focus -force .t2 + wm withdraw .t2 + update + wm deiconify .t2 + wm deiconify .t +} {} +catch {destroy .t2} +test focus-3.5 {SetFocus procedure, generating events} { + focusSetup + focusClear + set focusInfo {} + focus -force .t.b2 + update + set focusInfo +} {in .t NotifyVirtual +in .t.b2 NotifyAncestor +} +test focus-3.6 {SetFocus procedure, generating events} { + focusSetup + focus -force .b + update + set focusInfo {} + focus .t.b2 + update + set focusInfo +} {out .b NotifyNonlinear +out . NotifyNonlinearVirtual +in .t NotifyNonlinearVirtual +in .t.b2 NotifyNonlinear +} +test focus-3.7 {SetFocus procedure, generating events} {nonPortable} { + # Non-portable because some platforms generate extra events. + + focusSetup + focusClear + set focusInfo {} + focus .t.b2 + update + set focusInfo +} {} + +test focus-4.1 {TkFocusDeadWindow procedure} { + focusSetup + update + focus -force .b + update + destroy .t + focus +} {.b} +test focus-4.2 {TkFocusDeadWindow procedure} { + focusSetup + update + focus -force .t.b2 + focus .b + update + destroy .t.b2 + update + focus +} {.b} + +# Non-portable due to wm-specific redirection of input focus when +# windows are deleted: + +test focus-4.3 {TkFocusDeadWindow procedure} {nonPortable} { + focusSetup + update + focus .t + update + destroy .t + update + focus +} {} +test focus-4.4 {TkFocusDeadWindow procedure} { + focusSetup + focus -force .t.b2 + update + destroy .t.b2 + focus +} {.t} + +# I don't know how to test most of the remaining procedures of this file +# explicitly; they've already been exercised by the preceding tests. + +test focus-5.1 {ChangeXFocus procedure, don't take focus unless have it} { + focusSetup + focus -force .t + update + set result [focus] + send [dobg {tk appname}] {focus -force .; update} + lappend result [focus] + focus .t.b2 + update + lappend result [focus] +} {.t .t {}} + +catch {destroy .t} +bind all <FocusIn> {} +bind all <FocusOut> {} +bind all <KeyPress> {} +cleanupbg +fixfocus + +test focus-6.1 {miscellaneous - embedded application in same process} {unixOnly} { + eval interp delete [interp slaves] + catch {destroy .t} + toplevel .t + wm geometry .t +0+0 + frame .t.f1 -container 1 + frame .t.f2 + pack .t.f1 .t.f2 + entry .t.f2.e1 -bg red + pack .t.f2.e1 + bind all <FocusIn> {lappend x "focus in %W %d"} + bind all <FocusOut> {lappend x "focus out %W %d"} + interp create child + child eval "set argv {-use [winfo id .t.f1]}" + load {} tk child + child eval { + entry .e1 -bg lightBlue + pack .e1 + bind all <FocusIn> {lappend x "focus in %W %d"} + bind all <FocusOut> {lappend x "focus out %W %d"} + set x {} + } + + # Claim the focus and wait long enough for it to really arrive. + + focus -force .t.f2.e1 + after 300 {set timer 1} + vwait timer + set x {} + lappend x [focus] [child eval focus] + + # See if a "focus" command will move the focus to the embedded + # application. + + child eval {focus .e1} + after 300 {set timer 1} + vwait timer + lappend x | + child eval {lappend x |} + + # Bring the focus back to the main application. + + focus .t.f2.e1 + after 300 {set timer 1} + vwait timer + set result [list $x [child eval {set x}]] + interp delete child + set result +} {{.t.f2.e1 {} {focus out .t.f2.e1 NotifyNonlinear} {focus out .t.f2 NotifyNonlinearVirtual} {focus in .t.f1 NotifyNonlinear} | {focus out .t.f1 NotifyNonlinear} {focus in .t.f2 NotifyNonlinearVirtual} {focus in .t.f2.e1 NotifyNonlinear}} {{focus in . NotifyVirtual} {focus in .e1 NotifyAncestor} | {focus out .e1 NotifyAncestor} {focus out . NotifyVirtual}}} +test focus-6.2 {miscellaneous - embedded application in different process} {unixOnly} { + eval interp delete [interp slaves] + catch {destroy .t} + setupbg + toplevel .t + wm geometry .t +0+0 + frame .t.f1 -container 1 + frame .t.f2 + pack .t.f1 .t.f2 + entry .t.f2.e1 -bg red + pack .t.f2.e1 + bind all <FocusIn> {lappend x "focus in %W %d"} + bind all <FocusOut> {lappend x "focus out %W %d"} + setupbg -use [winfo id .t.f1] + dobg { + entry .e1 -bg lightBlue + pack .e1 + bind all <FocusIn> {lappend x "focus in %W %d"} + bind all <FocusOut> {lappend x "focus out %W %d"} + set x {} + } + + # Claim the focus and wait long enough for it to really arrive. + + focus -force .t.f2.e1 + after 300 {set timer 1} + vwait timer + set x {} + lappend x [focus] [dobg focus] + + # See if a "focus" command will move the focus to the embedded + # application. + + dobg {focus .e1} + after 300 {set timer 1} + vwait timer + lappend x | + dobg {lappend x |} + + # Bring the focus back to the main application. + + focus .t.f2.e1 + after 300 {set timer 1} + vwait timer + set result [list $x [dobg {set x}]] + cleanupbg + set result +} {{.t.f2.e1 {} {focus out .t.f2.e1 NotifyNonlinear} {focus out .t.f2 NotifyNonlinearVirtual} {focus in .t.f1 NotifyNonlinear} | {focus out .t.f1 NotifyNonlinear} {focus in .t.f2 NotifyNonlinearVirtual} {focus in .t.f2.e1 NotifyNonlinear}} {{focus in . NotifyVirtual} {focus in .e1 NotifyAncestor} | {focus out .e1 NotifyAncestor} {focus out . NotifyVirtual}}} + +eval destroy [winfo children .] +bind all <FocusIn> {} +bind all <FocusOut> {} diff --git a/tests/focusTcl.test b/tests/focusTcl.test new file mode 100644 index 0000000..2154041 --- /dev/null +++ b/tests/focusTcl.test @@ -0,0 +1,279 @@ +# This file is a Tcl script to test out the features of the script +# file focus.tcl, which includes the procedures tk_focusNext and +# tk_focusPrev, among other things. This file is organized in the +# standard fashion for Tcl tests. +# +# Copyright (c) 1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) focusTcl.test 1.7 96/09/26 10:25:58 + +if {[info procs test] != "test"} { + source defs +} + +eval destroy [winfo children .] +wm geometry . {} +raise . + +proc setup1 w { + if {$w == "."} { + set w "" + } + foreach i {a b c d} { + frame $w.$i -width 100 -height 50 -bd 2 -relief raised + pack $w.$i + } + .b configure -width 0 -height 0 + foreach i {x y z} { + button $w.b.$i -text "Button $w.b.$i" + pack $w.b.$i -side left + } + tkwait visibility $w.b.z +} + +option add *takeFocus 1 +option add *highlightThickness 2 +. configure -takefocus 1 -highlightthickness 2 +test focusTcl-1.1 {tk_focusNext procedure, no children} { + tk_focusNext . +} {.} +setup1 . +test focusTcl-1.2 {tk_focusNext procedure, basic tree traversal} { + tk_focusNext . +} {.a} +test focusTcl-1.3 {tk_focusNext procedure, basic tree traversal} { + tk_focusNext .a +} {.b} +test focusTcl-1.4 {tk_focusNext procedure, basic tree traversal} { + tk_focusNext .b +} {.b.x} +test focusTcl-1.5 {tk_focusNext procedure, basic tree traversal} { + tk_focusNext .b.x +} {.b.y} +test focusTcl-1.6 {tk_focusNext procedure, basic tree traversal} { + tk_focusNext .b.y +} {.b.z} +test focusTcl-1.7 {tk_focusNext procedure, basic tree traversal} { + tk_focusNext .b.z +} {.c} +test focusTcl-1.8 {tk_focusNext procedure, basic tree traversal} { + tk_focusNext .c +} {.d} +test focusTcl-1.9 {tk_focusNext procedure, basic tree traversal} { + tk_focusNext .d +} {.} +foreach w {.b .b.x .b.y .c .d} { + $w configure -takefocus 0 +} +test focusTcl-1.10 {tk_focusNext procedure, basic tree traversal} { + tk_focusNext .a +} {.b.z} +test focusTcl-1.11 {tk_focusNext procedure, basic tree traversal} { + tk_focusNext .b.z +} {.} +test focusTcl-1.12 {tk_focusNext procedure, basic tree traversal} { + eval destroy [winfo child .] + setup1 . + update + . configure -takefocus 0 + tk_focusNext .d +} {.a} +. configure -takefocus 1 + +eval destroy [winfo child .] +setup1 . +toplevel .t +wm geom .t +0+0 +toplevel .t2 +wm geom .t2 -0+0 +raise .t .a +test focusTcl-2.1 {tk_focusNext procedure, toplevels} { + tk_focusNext .a +} {.b} +test focusTcl-2.2 {tk_focusNext procedure, toplevels} { + tk_focusNext .d +} {.} +test focusTcl-2.3 {tk_focusNext procedure, toplevels} { + tk_focusNext .t +} {.t} +setup1 .t +raise .t.b +test focusTcl-2.4 {tk_focusNext procedure, toplevels} { + tk_focusNext .t +} {.t.a} +test focusTcl-2.5 {tk_focusNext procedure, toplevels} { + tk_focusNext .t.b.z +} {.t} + +eval destroy [winfo child .] +test focusTcl-3.1 {tk_focusPrev procedure, no children} { + tk_focusPrev . +} {.} +setup1 . +test focusTcl-3.2 {tk_focusPrev procedure, basic tree traversal} { + tk_focusPrev . +} {.d} +test focusTcl-3.3 {tk_focusPrev procedure, basic tree traversal} { + tk_focusPrev .d +} {.c} +test focusTcl-3.4 {tk_focusPrev procedure, basic tree traversal} { + tk_focusPrev .c +} {.b.z} +test focusTcl-3.5 {tk_focusPrev procedure, basic tree traversal} { + tk_focusPrev .b.z +} {.b.y} +test focusTcl-3.6 {tk_focusPrev procedure, basic tree traversal} { + tk_focusPrev .b.y +} {.b.x} +test focusTcl-3.7 {tk_focusPrev procedure, basic tree traversal} { + tk_focusPrev .b.x +} {.b} +test focusTcl-3.8 {tk_focusPrev procedure, basic tree traversal} { + tk_focusPrev .b +} {.a} +test focusTcl-3.9 {tk_focusPrev procedure, basic tree traversal} { + tk_focusPrev .a +} {.} + +eval destroy [winfo child .] +setup1 . +toplevel .t +wm geom .t +0+0 +toplevel .t2 +wm geom .t2 -0+0 +raise .t .a +test focusTcl-4.1 {tk_focusPrev procedure, toplevels} { + tk_focusPrev . +} {.d} +test focusTcl-4.2 {tk_focusPrev procedure, toplevels} { + tk_focusPrev .b +} {.a} +test focusTcl-4.3 {tk_focusPrev procedure, toplevels} { + tk_focusPrev .t +} {.t} +setup1 .t +update +.t configure -takefocus 0 +raise .t.b +test focusTcl-4.4 {tk_focusPrev procedure, toplevels} { + tk_focusPrev .t +} {.t.b.z} +test focusTcl-4.5 {tk_focusPrev procedure, toplevels} { + tk_focusPrev .t.a +} {.t.b.z} + +eval destroy [winfo child .] +test focusTcl-5.1 {tkFocusOK procedure, -takefocus 0} { + eval destroy [winfo child .] + setup1 . + .b.x configure -takefocus 0 + tk_focusNext .b +} {.b.y} +test focusTcl-5.2 {tkFocusOK procedure, -takefocus 1} { + eval destroy [winfo child .] + setup1 . + pack forget .b + update + .b configure -takefocus "" + .b.y configure -takefocus "" + .b.z configure -takefocus "" + list [tk_focusNext .a] [tk_focusNext .b.x] +} {.c .c} +test focusTcl-5.3 {tkFocusOK procedure, -takefocus procedure} { + proc t w { + if {$w == ".b.x"} { + return 1 + } elseif {$w == ".b.y"} { + return "" + } + return 0 + } + eval destroy [winfo child .] + setup1 . + pack forget .b.y + update + .b configure -takefocus "" + foreach w {.b.x .b.y .b.z .c} { + $w configure -takefocus t + } + list [tk_focusNext .a] [tk_focusNext .b.x] +} {.b.x .d} +test focusTcl-5.4 {tkFocusOK procedure, -takefocus ""} { + eval destroy [winfo child .] + setup1 . + .b.x configure -takefocus "" + update + tk_focusNext .b +} {.b.x} +test focusTcl-5.5 {tkFocusOK procedure, -takefocus "", not mapped} { + eval destroy [winfo child .] + setup1 . + .b.x configure -takefocus "" + pack unpack .b.x + update + tk_focusNext .b +} {.b.y} +test focusTcl-5.6 {tkFocusOK procedure, -takefocus "", not mapped} { + eval destroy [winfo child .] + setup1 . + foreach w {.b.x .b.y .b.z} { + $w configure -takefocus "" + } + pack unpack .b + update + tk_focusNext .b +} {.c} +test focusTcl-5.7 {tkFocusOK procedure, -takefocus "", not mapped} { + eval destroy [winfo child .] + setup1 . + .b.y configure -takefocus 1 + pack unpack .b.y + update + tk_focusNext .b.x +} {.b.z} +test focusTcl-5.8 {tkFocusOK procedure, -takefocus "", not mapped} { + proc always args {return 1} + eval destroy [winfo child .] + setup1 . + .b.y configure -takefocus always + pack unpack .b.y + update + tk_focusNext .b.x +} {.b.y} +test focusTcl-5.9 {tkFocusOK procedure, -takefocus "", window disabled} { + eval destroy [winfo child .] + setup1 . + foreach w {.b.x .b.y .b.z} { + $w configure -takefocus "" + } + update + .b.x configure -state disabled + tk_focusNext .b +} {.b.y} +test focusTcl-5.10 {tkFocusOK procedure, -takefocus "", check for bindings} { + eval destroy [winfo child .] + setup1 . + foreach w {.a .b .c .d} { + $w configure -takefocus "" + } + update + bind .a <Key> {foo} + list [tk_focusNext .] [tk_focusNext .a] +} {.a .b.x} +test focusTcl-5.11 {tkFocusOK procedure, -takefocus "", check for bindings} { + eval destroy [winfo child .] + setup1 . + foreach w {.a .b .c .d} { + $w configure -takefocus "" + } + update + bind Frame <Key> {foo} + list [tk_focusNext .] [tk_focusNext .a] +} {.a .b} + +bind Frame <Key> {} +. configure -takefocus 0 -highlightthickness 0 +option clear diff --git a/tests/font.test b/tests/font.test new file mode 100644 index 0000000..a526470 --- /dev/null +++ b/tests/font.test @@ -0,0 +1,1092 @@ +# This file is a Tcl script to test out Tk's "font" command +# plus the procedures in tkFont.c. It is organized in the +# standard fashion for Tcl tests. +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) font.test 1.22 97/10/10 14:34:54 + +if {[string compare test [info procs test]] != 0} { + source defs +} + +catch {destroy .b} +toplevel .b +wm geom .b +0+0 +update idletasks + +proc setup {} { + catch {destroy .b.f} + catch {font delete xyz} + label .b.f + pack .b.f + update +} + +label .b.l -padx 0 -pady 0 -bd 0 -highlightthickness 0 -justify left -text "0" -font "Helvetica -12 bold" +pack .b.l +canvas .b.c -closeenough 0 +.b.c create text 0 0 -tags text -anchor nw -just left -font "Helvetica -12 bold" +pack .b.c +update + +set ax [winfo reqwidth .b.l] +set ay [winfo reqheight .b.l] +proc getsize {} { + update + return "[winfo reqwidth .b.l] [winfo reqheight .b.l]" +} + +proc csetup {{str ""}} { + focus -force .b.c + .b.c dchars text 0 end + .b.c insert text 0 $str + .b.c focus text +} + +setup + +case $tcl_platform(platform) { + unix {set fixed "fixed"} + windows {set fixed "courier 12"} + macintosh {set fixed "monaco 9"} +} +set times [font actual {times 0} -family] + +test font-1.1 {font command: general} { + list [catch {font} msg] $msg +} {1 {wrong # args: should be "font option ?arg?"}} +test font-1.2 {font command: actual: arguments} { + list [catch {font actual xyz -displayof} msg] $msg +} {1 {value for "-displayof" missing}} +test font-1.3 {font command: actual: arguments} { + list [catch {font actual} msg] $msg +} {1 {wrong # args: should be "font actual font ?-displayof window? ?option?"}} +test font-1.4 {font command: actual: arguments} { + list [catch {font actual xyz abc def} msg] $msg +} {1 {wrong # args: should be "font actual font ?-displayof window? ?option?"}} +test font-1.5 {font command: actual: arguments} { + list [catch {font actual {}} msg] $msg +} {1 {font "" doesn't exist}} +test font-1.6 {font command: actual: displayof specified, so skip to next} { + catch {font actual xyz -displayof . -size} +} {0} +test font-1.7 {font command: actual: displayof specified, so skip to next} { + lindex [font actual xyz -displayof .] 0 +} {-family} +test font-1.8 {font command: actual} {unix || mac} { + string tolower [font actual {-family times} -family] +} {times} +test font-1.9 {font command: actual} {pcOnly} { + font actual {-family times} -family +} {Times New Roman} +test font-1.10 {font command: actual} { + lindex [font actual {-family times}] 0 +} {-family} +test font-1.11 {font command: bad option} { + list [catch {font actual xyz -style} msg] $msg +} {1 {bad option "-style": must be -family, -size, -weight, -slant, -underline, or -overstrike}} + +test font-2.1 {font command: configure} { + list [catch {font configure} msg] $msg +} {1 {wrong # args: should be "font configure fontname ?options?"}} +test font-2.2 {font command: configure: non-existent font} { + list [catch {font configure xyz} msg] $msg +} {1 {named font "xyz" doesn't exist}} +test font-2.3 {font command: configure: "deleted" font} { + setup + font create xyz + .b.f configure -font xyz + font delete xyz + list [catch {font configure xyz} msg] $msg +} {1 {named font "xyz" doesn't exist}} +test font-2.4 {font command: configure: get all options} { + setup + font create xyz -family xyz + lindex [font configure xyz] 1 +} xyz +test font-2.5 {font command: configure: get one option} { + setup + font create xyz -family xyz + font configure xyz -family +} xyz +test font-2.6 {font command: configure: update existing font} { + setup + font create xyz + font configure xyz -family xyz + update + font configure xyz -family +} xyz +test font-2.7 {font command: configure: bad option} { + setup + font create xyz + list [catch {font configure xyz -style} msg] $msg +} {1 {bad option "-style": must be -family, -size, -weight, -slant, -underline, or -overstrike}} + +test font-3.1 {font command: create: make up name} { + font delete [font create] + font delete [font create -family xyz] +} {} +test font-3.2 {font command: create: already exists} { + setup + font create xyz + list [catch {font create xyz} msg] $msg +} {1 {font "xyz" already exists}} +test font-3.3 {font command: create: error recreating "deleted" font} { + setup + font create xyz + .b.f configure -font xyz + font delete xyz + list [catch {font create xyz -xyz times} msg] $msg +} {1 {bad option "-xyz": must be -family, -size, -weight, -slant, -underline, or -overstrike}} +test font-3.4 {font command: create: recreate "deleted" font} { + setup + font create xyz + .b.f configure -font xyz + font delete xyz + font actual xyz + font create xyz -family times + update + font configure xyz -family +} {times} +test font-3.5 {font command: create: bad option creating new font} { + setup + list [catch {font create xyz -xyz times} msg] $msg +} {1 {bad option "-xyz": must be -family, -size, -weight, -slant, -underline, or -overstrike}} +test font-3.6 {font command: create: totally new font} { + setup + font create xyz -family xyz + font configure xyz -family +} {xyz} + +test font-4.1 {font command: delete: arguments} { + list [catch {font delete} msg] $msg +} {1 {wrong # args: should be "font delete fontname ?fontname ...?"}} +test font-4.2 {font command: delete: loop test} { + font create a -underline 1 + font create b -underline 1 + font create c -underline 1 + font delete a b c + list [font actual a -underline] [font actual b -underline] [font actual c -underline] +} {0 0 0} +test font-4.3 {font command: delete: non-existent} { + setup + list [catch {font delete xyz} msg] $msg +} {1 {named font "xyz" doesn't exist}} +test font-4.4 {font command: delete: mark for later deletion} { + setup + font create xyz + .b.f configure -font xyz + font delete xyz + font actual xyz + list [catch {font configure xyz} msg] $msg +} {1 {named font "xyz" doesn't exist}} +test font-4.5 {font command: delete: actually delete} { + setup + font create xyz -underline 1 + font delete xyz + font actual xyz -underline +} {0} + +test font-5.1 {font command: families: arguments} { + list [catch {font families -displayof} msg] $msg +} {1 {value for "-displayof" missing}} +test font-5.2 {font command: families: arguments} { + list [catch {font families xyz} msg] $msg +} {1 {wrong # args: should be "font families ?-displayof window?"}} +test font-5.3 {font command: families} { + font families + set x {} +} {} + +test font-6.1 {font command: measure: arguments} { + list [catch {font measure xyz -displayof} msg] $msg +} {1 {value for "-displayof" missing}} +test font-6.2 {font command: measure: arguments} { + list [catch {font measure} msg] $msg +} {1 {wrong # args: should be "font measure font ?-displayof window? text"}} +test font-6.3 {font command: measure: arguments} { + list [catch {font measure xyz abc def} msg] $msg +} {1 {wrong # args: should be "font measure font ?-displayof window? text"}} +test font-6.4 {font command: measure: arguments} { + list [catch {font measure {} abc} msg] $msg +} {1 {font "" doesn't exist}} +test font-6.5 {font command: measure} { + expr [font measure $fixed "abcdefg"]==[font measure $fixed "a"]*7 +} {1} + +test font-7.1 {font command: metrics: arguments} { + list [catch {font metrics xyz -displayof} msg] $msg +} {1 {value for "-displayof" missing}} +test font-7.2 {font command: metrics: arguments} { + list [catch {font metrics} msg] $msg +} {1 {wrong # args: should be "font metrics font ?-displayof window? ?option?"}} +test font-7.3 {font command: metrics: get all metrics} { + catch {unset a} + array set a [font metrics {-family xyz}] + set x [lsort [array names a]] + unset a + set x +} {-ascent -descent -fixed -linespace} +test font-7.4 {font command: metrics: get ascent} { + catch {expr [font metrics $fixed -ascent]} +} {0} +test font-7.5 {font command: metrics: get descent} { + catch {expr [font metrics {-family xyz} -descent]} +} {0} +test font-7.6 {font command: metrics: get linespace} { + catch {expr [font metrics {-family fixed} -linespace]} +} {0} +test font-7.7 {font command: metrics: get fixed} { + catch {expr [font metrics {-family fixed} -fixed]} +} {0} +test font-7.8 {font command: metrics: get ascent} { + catch {expr [font metrics {-family xyz} -ascent]} +} {0} +test font-7.9 {font command: metrics: get descent} { + catch {expr [font metrics {-family xyz} -descent]} +} {0} +test font-7.10 {font command: metrics: get linespace} { + catch {expr [font metrics {-family fixed} -linespace]} +} {0} +test font-7.11 {font command: metrics: get fixed} { + catch {expr [font metrics {-family fixed} -fixed]} +} {0} +test font-7.12 {font command: metrics: bad metric} { + list [catch {font metrics {-family fixed} -xyz} msg] $msg +} {1 {bad metric "-xyz": must be -ascent, -descent, -linespace, or -fixed}} + +test font-8.1 {font command: names: arguments} { + list [catch {font names xyz} msg] $msg +} {1 {wrong # args: should be "font names"}} +test font-8.2 {font command: names} { + setup + font create xyz + font create abc + set x [lsort [font names]] + font delete abc + font delete xyz + set x +} {abc xyz} +test font-8.3 {font command: names} { + setup + font create xyz + font create abc + set x [lsort [font names]] + .b.f config -font xyz + font delete xyz + lappend x [font names] + font delete abc + set x +} {abc xyz abc} + +test font-9.1 {font command: unknown option} { + list [catch {font xyz} msg] $msg +} {1 {bad option "xyz": must be actual, configure, create, delete, families, measure, metrics, or names}} + +test font-10.1 {UpdateDependantFonts procedure: no users} { + setup + font create xyz + font configure xyz -family times +} {} +test font-10.2 {UpdateDependantFonts procedure: pings the widgets} { + setup + font create xyz -family times -size 20 + .b.f config -font xyz -text "abcd" -padx 0 -bd 0 -highlightthickness 0 + set a1 [font measure xyz "abcd"] + update + set b1 [winfo reqwidth .b.f] + font configure xyz -family helvetica -size 20 + set a2 [font measure xyz "abcd"] + update + set b2 [winfo reqwidth .b.f] + expr {$a1==$b1 && $a2==$b2} +} {1} + +test font-11.1 {Tk_GetFont procedure: bump ref count} { + setup + .b.f config -font {-family fixed} + lindex [font actual {-family fixed}] 0 +} {-family} +test font-11.2 {Tk_GetFont procedure: bump ref count of named font, too} { + setup + font create xyz + .b.f config -font xyz + lindex [font actual xyz] 0 +} {-family} +test font-11.3 {Tk_GetFont procedure: get named font} { + setup + font create xyz + .b.f config -font xyz +} {} +test font-11.4 {Tk_GetFont procedure: get native font} {unixOnly} { + setup + .b.f config -font fixed +} {} +test font-11.5 {Tk_GetFont procedure: get native font} {pcOnly} { + setup + .b.f config -font oemfixed +} {} +test font-11.6 {Tk_GetFont procedure: get native font} {macOnly} { + setup + .b.f config -font application +} {} +test font-11.7 {Tk_GetFont procedure: get attribute font} { + list [catch {.b.f config -font {xxx yyy zzz}} msg] $msg +} {1 {expected integer but got "yyy"}} +test font-11.8 {Tk_GetFont procedure: get attribute font} { + lindex [font actual {plan 9}] 0 +} {-family} +test font-11.9 {Tk_GetFont procedure: no match} { + list [catch {font actual {}} msg] $msg +} {1 {font "" doesn't exist}} + +test font-12.1 {Tk_NameOfFont procedure} { + setup + .b.f config -font {-family fixed} + .b.f cget -font +} {-family fixed} + +test font-13.1 {Tk_FreeFont procedure: one ref} { + setup + .b.f config -font {-family fixed} + destroy .b.f +} {} +test font-13.2 {Tk_FreeFont procedure: multiple ref} { + setup + .b.f config -font {-family fixed} + button .b.b -font {-family fixed} + destroy .b.f + set x [.b.b cget -font] + destroy .b.b + set x +} {-family fixed} +test font-13.3 {Tk_FreeFont procedure: named font} { + setup + font create xyz + .b.f config -font xyz + destroy .b.f + font names +} {xyz} +test font-13.4 {Tk_FreeFont procedure: named font} { + setup + font create xyz -underline 1 + .b.f config -font xyz + font delete xyz + set x [font actual xyz -underline] + destroy .b.f + list [font actual xyz -underline] $x +} {0 1} +test font-13.5 {Tk_FreeFont procedure: named font not deleted yet} { + setup + font create xyz + .b.f config -font xyz + button .b.b -font xyz + font delete xyz + set x [font actual xyz] + destroy .b.b + list [lindex [font actual xyz] 0] [lindex $x 0] +} {-family -family} + +test font-14.1 {Tk_FontId} { + .b.f config -font "times 20" + update +} {} + +test font-15.1 {Tk_FontMetrics procedure} { + button .b.w1 -text abc + entry .b.w2 -text abcd + update + destroy .b.w1 .b.w2 +} {} + +proc psfontname {name} { + set a [.b.c itemcget text -font] + .b.c itemconfig text -font $name + set post [.b.c postscript] + .b.c itemconfig text -font $a + set end [string first "findfont" $post] + incr end -2 + set post [string range $post [expr $end-70] $end] + set start [string first "gsave" $post] + return [string range $post [expr $start+7] end] +} +test font-16.1 {Tk_PostscriptFontName procedure: native} {unixOnly} { + set x [font actual {{itc avant garde} 10} -family] + if {[string match *avant*garde $x]} { + psfontname "{itc avant garde} 10" + } else { + set x {AvantGarde-Book} + } +} {AvantGarde-Book} +test font-16.2 {Tk_PostscriptFontName procedure: native} {pcOnly} { + psfontname "arial 10" +} {Helvetica} +test font-16.3 {Tk_PostscriptFontName procedure: native} {pcOnly} { + psfontname "{times new roman} 10" +} {Times-Roman} +test font-16.4 {Tk_PostscriptFontName procedure: native} {pcOnly} { + psfontname "{courier new} 10" +} {Courier} +test font-16.5 {Tk_PostscriptFontName procedure: native} {macOnly} { + psfontname "geneva 10" +} {Helvetica} +test font-16.6 {Tk_PostscriptFontName procedure: native} {macOnly} { + psfontname "{new york} 10" +} {Times-Roman} +test font-16.7 {Tk_PostscriptFontName procedure: native} {macOnly} { + psfontname "monaco 10" +} {Courier} +test font-16.8 {Tk_PostscriptFontName procedure: spaces} {unixOnly} { + set x [font actual {{lucida bright} 10} -family] + if {[string match lucida*bright $x]} { + psfontname "{lucida bright} 10" + } else { + set x {LucidaBright} + } +} {LucidaBright} +test font-16.9 {Tk_PostscriptFontName procedure: spaces} {unixOnly} { + psfontname "{new century schoolbook} 10" +} {NewCenturySchlbk-Roman} +set i 10 +foreach p { + {"avantgarde" AvantGarde-Book AvantGarde-Demi AvantGarde-BookOblique AvantGarde-DemiOblique} + {"bookman" Bookman-Light Bookman-Demi Bookman-LightItalic Bookman-DemiItalic} + {"courier" Courier Courier-Bold Courier-Oblique Courier-BoldOblique} + {"helvetica" Helvetica Helvetica-Bold Helvetica-Oblique Helvetica-BoldOblique} + {"new century schoolbook" NewCenturySchlbk-Roman NewCenturySchlbk-Bold NewCenturySchlbk-Italic NewCenturySchlbk-BoldItalic} + {"palatino" Palatino-Roman Palatino-Bold Palatino-Italic Palatino-BoldItalic} + {"symbol" Symbol Symbol Symbol Symbol} + {"times" Times-Roman Times-Bold Times-Italic Times-BoldItalic} + {"zapfchancery" ZapfChancery-MediumItalic ZapfChancery-MediumItalic ZapfChancery-MediumItalic ZapfChancery-MediumItalic} + {"zapfdingbats" ZapfDingbats ZapfDingbats ZapfDingbats ZapfDingbats} +} { + test font-16.$i {Tk_PostscriptFontName procedure: exhaustive} {unixOnly} { + set family [lindex $p 0] + set x {} + set i 1 + foreach slant {roman italic} { + foreach weight {normal bold} { + set name [list $family 12 $slant $weight] + if {[font actual $name -family] == $family} { + lappend x [psfontname $name] + } else { + lappend x [lindex $p $i] + } + incr i + } + } + incr i + set x + } [lrange $p 1 end] +} +foreach p { + {"arial" Helvetica Helvetica-Bold Helvetica-Oblique Helvetica-BoldOblique} + {"courier new" Courier Courier-Bold Courier-Oblique Courier-BoldOblique} + {"helvetica" Helvetica Helvetica-Bold Helvetica-Oblique Helvetica-BoldOblique} + {"symbol" Symbol Symbol-Bold Symbol-Italic Symbol-BoldItalic} + {"times new roman" Times-Roman Times-Bold Times-Italic Times-BoldItalic} +} { + test font-16.$i {Tk_PostscriptFontName procedure: exhaustive} {pcOnly} { + set family [lindex $p 0] + set x {} + foreach slant {roman italic} { + foreach weight {normal bold} { + lappend x [psfontname [list $family 12 "$slant $weight"]] + } + } + incr i + set x + } [lrange $p 1 end] +} +foreach p { + {"courier" Courier Courier-Bold Courier-Oblique Courier-BoldOblique} + {"geneva" Helvetica Helvetica-Bold Helvetica-Oblique Helvetica-BoldOblique} + {"helvetica" Helvetica Helvetica-Bold Helvetica-Oblique Helvetica-BoldOblique} + {"monaco" Courier Courier-Bold Courier-Oblique Courier-BoldOblique} + {"new york" Times-Roman Times-Bold Times-Italic Times-BoldItalic} + {"symbol" Symbol Symbol-Bold Symbol-Italic Symbol-BoldItalic} + {"times" Times-Roman Times-Bold Times-Italic Times-BoldItalic} +} { + test font-16.$i {Tk_PostscriptFontName procedure: exhaustive} {macOnly} { + set family [lindex $p 0] + set x {} + foreach slant {roman italic} { + foreach weight {normal bold} { + lappend x [psfontname [list $family 12 $slant $weight]] + } + } + incr i + set x + } [lrange $p 1 end] +} + +test font-17.1 {Tk_UnderlineChars procedure} { + text .b.t + .b.t insert 1.0 abc\tdefg + .b.t tag config sel -underline 1 + .b.t tag add sel 1.0 end + update +} {} + +setup +test font-18.1 {Tk_ComputeTextLayout: empty string} { + .b.l config -text "" +} {} +test font-18.2 {Tk_ComputeTextLayout: simple string} { + .b.l config -text "000" + getsize +} "[expr $ax*3] $ay" +test font-18.3 {Tk_ComputeTextLayout: find special chars} { + .b.l config -text "000\n000" + getsize +} "[expr $ax*3] [expr $ay*2]" +test font-18.4 {Tk_ComputeTextLayout: calls Tk_MeasureChars} { + .b.l config -text "000\n000" + getsize +} "[expr $ax*3] [expr $ay*2]" +test font-18.5 {Tk_ComputeTextLayout: break line} { + .b.l config -text "000\t00000" -wrap [expr 9*$ax] + set x [getsize] + .b.l config -wrap 0 + set x +} "[expr 8*$ax] [expr 2*$ay]" +test font-18.6 {Tk_ComputeTextLayout: normal ended on special char} { + .b.l config -text "000\n000" +} {} +test font-18.7 {Tk_ComputeTextLayout: special char was \n} { + .b.l config -text "000\n0000" + getsize +} "[expr $ax*4] [expr $ay*2]" +test font-18.8 {Tk_ComputeTextLayout: special char was \t} { + .b.l config -text "000\t00" + getsize +} "[expr $ax*10] $ay" +test font-18.9 {Tk_ComputeTextLayout: tab didn't cause break} { + set x {} + .b.l config -text "000\t000" + lappend x [getsize] + .b.l config -text "000\t000" -wrap [expr 100*$ax] + lappend x [getsize] + .b.l config -wrap 0 + set x +} "{[expr $ax*11] $ay} {[expr $ax*11] $ay}" +test font-18.10 {Tk_ComputeTextLayout: tab caused break} { + set x {} + .b.l config -text "000\t" + lappend x [getsize] + .b.l config -text "000\t00" -wrap [expr $ax*6] + lappend x [getsize] + .b.l config -wrap 0 + set x +} "{[expr $ax*3] $ay} {[expr $ax*3] [expr $ay*2]}" +test font-18.11 {Tk_ComputeTextLayout: absorb spaces at eol} { + set x {} + .b.l config -text "000 000" -wrap [expr $ax*5] + lappend x [getsize] + .b.l config -text "000 " + lappend x [getsize] + .b.l config -wrap 0 + set x +} "{[expr $ax*3] [expr $ay*2]} {[expr $ax*3] $ay}" +test font-18.12 {Tk_ComputeTextLayout: append non-printing spaces to chunk} { + set x {} + .b.l config -text "000 0000" -wrap [expr $ax*5] + lappend x [getsize] + .b.l config -text "000\t00 0000" -wrap [expr $ax*12] + lappend x [getsize] + .b.l config -wrap 0 + set x +} "{[expr $ax*4] [expr $ay*2]} {[expr $ax*10] [expr $ay*2]}" +test font-18.13 {Tk_ComputeTextLayout: many lines -> realloc line array} { + .b.l config -text "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + getsize +} "1 [expr $ay*129]" +test font-18.14 {Tk_ComputeTextLayout: text ended with \n} { + list [.b.l config -text "0000"; getsize] [.b.l config -text "0000\n"; getsize] +} "{[expr $ax*4] $ay} {[expr $ax*4] [expr $ay*2]}" +test font-18.15 {Tk_ComputeTextLayout: justification} { + csetup "000\n00000" + set x {} + .b.c itemconfig text -just left + lappend x [.b.c index text @[expr $ax*2],0] + .b.c itemconfig text -just center + lappend x [.b.c index text @[expr $ax*2],0] + .b.c itemconfig text -just right + lappend x [.b.c index text @[expr $ax*2],0] + .b.c itemconfig text -just left + set x +} {2 1 0} + +test font-19.1 {Tk_FreeTextLayout procedure} { + setup + .b.f config -text foo + .b.f config -text boo +} {} + +test font-20.1 {Tk_DrawTextLayout procedure: auto-detect last char} { + .b.f config -text foo +} {} +test font-20.2 {Tk_DrawTextLayout procedure: multiple chunks} { + csetup "000\t00\n000" +} {} +test font-20.3 {Tk_DrawTextLayout: draw subset of chunk: numDisplay <= 0} { + csetup "000\t00" + .b.c select from text 3 + .b.c select to text 5 +} {} +test font-20.4 {Tk_DrawTextLayout: draw subset of chunk: firstChar <= 0} { + .b.c select from text 3 + .b.c select to text 5 +} {} +test font-20.5 {Tk_DrawTextLayout: draw subset of chunk: firstChar > 0} { + .b.c select from text 2 + .b.c select to text 2 +} {} +test font-20.6 {Tk_DrawTextLayout: draw subset of chunk: lastChar < numChars} { + .b.c select from text 4 + .b.c select to text 4 +} {} + +test font-21.1 {Tk_UnderlineTextLayout procedure: no underline chosen} { + .b.f config -text "foo" -under -1 +} {} +test font-21.2 {Tk_UnderlineTextLayout procedure: underline not visible} { + .b.f config -text "000 00000" -wrap [expr $ax*7] -under 10 +} {} +test font-21.3 {Tk_UnderlineTextLayout procedure: underline is visible} { + .b.f config -text "000 00000" -wrap [expr $ax*7] -under 5 + .b.f config -wrap -1 -under -1 +} {} + +test font-22.1 {Tk_PointToChar procedure: above all lines} { + csetup "000" + .b.c index text @-1,0 +} {0} +test font-22.2 {Tk_PointToChar procedure: no chars} { + # After fixing the following bug: + # + # In canvas text item, it was impossible to click to position the + # insertion point just after the last character. + # + # introduced another bug that Tk_PointToChar() would return a character + # index of 1 if TextLayout contained 0 characters. + + csetup "" + .b.c index text @100,100 +} {0} +test font-22.3 {Tk_PointToChar procedure: loop test} { + csetup "000\n000\n000\n000" + .b.c index text @10000,0 +} {3} +test font-22.4 {Tk_PointToChar procedure: intersect line} { + csetup "000\n000\n000" + .b.c index text @0,$ay +} {4} +test font-22.5 {Tk_PointToChar procedure: to the left of all chunks} { + .b.c index text @-100,$ay +} {4} +test font-22.6 {Tk_PointToChar procedure: past any possible chunk} { + .b.c index text @100000,$ay +} {7} +test font-22.7 {Tk_PointToChar procedure: which chunk on this line} { + csetup "000\n000\t000\t000\n000" + .b.c index text @[expr $ax*2],$ay +} {6} +test font-22.8 {Tk_PointToChar procedure: which chunk on this line} { + csetup "000\n000\t000\t000\n000" + .b.c index text @[expr $ax*10],$ay +} {10} +test font-22.9 {Tk_PointToChar procedure: in special chunk} { + csetup "000\n000\t000\t000\n000" + .b.c index text @[expr $ax*6],$ay +} {7} +test font-22.10 {Tk_PointToChar procedure: past all chars in chunk} { + csetup "000 0000000" + .b.c itemconfig text -width [expr $ax*5] + set x [.b.c index text @[expr $ax*5],0] + .b.c itemconfig text -width 0 + set x +} {3} +test font-22.11 {Tk_PointToChar procedure: below all chunks} { + csetup "000 0000000" + .b.c index text @0,1000000 +} {11} + +test font-23.1 {Tk_CharBBox procedure: index < 0} { + .b.f config -text "000" -underline -1 +} {} +test font-23.2 {Tk_CharBBox procedure: loop} { + .b.f config -text "000\t000\t000\t000" -underline 9 +} {} +test font-23.3 {Tk_CharBBox procedure: special char} { + .b.f config -text "000\t000\t000" -underline 7 +} {} +test font-23.4 {Tk_CharBBox procedure: normal char} { + .b.f config -text "000" -underline 1 +} {} +test font-23.5 {Tk_CharBBox procedure: right edge of bbox truncated} { + .b.f config -text "0 0000" -wrap [expr $ax*4] -under 2 + .b.f config -wrap 0 +} {} +test font-23.6 {Tk_CharBBox procedure: bbox pegged to right edge} { + .b.f config -text "0 0000" -wrap [expr $ax*4] -under 3 + .b.f config -wrap 0 +} {} + +.b.c bind all <Enter> {lappend x [.b.c index current @%x,%y]} + +test font-24.1 {Tk_TextLayoutToPoint procedure: loop once} { + csetup "000\n000\n000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x 0 -y 0 + set x +} {0} +test font-24.2 {Tk_TextLayoutToPoint procedure: loop multiple} { + csetup "000\n000\n000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x $ax -y $ay + set x +} {5} +test font-24.3 {Tk_TextLayoutToPoint procedure: loop to end} { + csetup "000\n0\n000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x [expr $ax*2] -y $ay + set x +} {} +test font-24.4 {Tk_TextLayoutToPoint procedure: hit a special char (tab)} { + csetup "000\t000\n000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x [expr $ax*6] -y 0 + set x +} {3} +test font-24.5 {Tk_TextLayoutToPoint procedure: ignore newline} { + csetup "000\n0\n000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x [expr $ax*2] -y $ay + set x +} {} +test font-24.6 {Tk_TextLayoutToPoint procedure: ignore spaces at eol} { + csetup "000\n000 000000000" + .b.c itemconfig text -width [expr $ax*10] + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x [expr $ax*5] -y $ay + .b.c itemconfig text -width 0 + set x +} {} +.b.c itemconfig text -justify center +test font-24.7 {Tk_TextLayoutToPoint procedure: on left side} { + csetup "0\n000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x 0 -y 0 + set x +} {} +test font-24.8 {Tk_TextLayoutToPoint procedure: on right side} { + csetup "0\n000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x [expr $ax*2] -y 0 + set x +} {} +test font-24.9 {Tk_TextLayoutToPoint procedure: inside line} { + csetup "0\n000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x $ax -y 0 + set x +} {0} +test font-24.10 {Tk_TextLayoutToPoint procedure: above line} { + csetup "0\n000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x 0 -y 0 + set x +} {} +test font-24.11 {Tk_TextLayoutToPoint procedure: below line} { + csetup "000\n0" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x 0 -y $ay + set x +} {} +test font-24.12 {Tk_TextLayoutToPoint procedure: in line} { + csetup "0\n000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x $ax -y $ay + set x +} {3} +.b.c itemconfig text -justify left +test font-24.13 {Tk_TextLayoutToPoint procedure: exact hit} { + csetup "000" + set x {} + event generate .b.c <Leave> + event generate .b.c <Enter> -x $ax -y 0 + set x +} {1} + +test font-25.1 {Tk_TextLayoutToArea procedure: loop once} { + csetup "000\n000\n000" + .b.c find overlapping 0 0 0 0 +} [.b.c find withtag text] +test font-25.2 {Tk_TextLayoutToArea procedure: loop multiple} { + csetup "000\t000\t000" + .b.c find overlapping [expr $ax*10] 0 [expr $ax*10] 0 +} [.b.c find withtag text] +test font-25.3 {Tk_TextLayoutToArea procedure: loop to end} { + csetup "0\n000" + .b.c find overlapping [expr $ax*2] 0 [expr $ax*2] 0 +} {} +test font-25.4 {Tk_TextLayoutToArea procedure: hit a special char (tab)} { + csetup "000\t000" + .b.c find overlapping [expr $ax*6] 0 [expr $ax*6] 0 +} [.b.c find withtag text] +test font-25.5 {Tk_TextLayoutToArea procedure: ignore newlines} { + csetup "000\n0\n000" + .b.c find overlapping $ax $ay $ax $ay +} {} +test font-25.6 {Tk_TextLayoutToArea procedure: ignore spaces at eol} { + csetup "000\n000 000000000" + .b.c itemconfig text -width [expr $ax*10] + set x [.b.c find overlapping [expr $ax*5] $ay [expr $ax*5] $ay] + .b.c itemconfig text -width 0 + set x +} {} + +test font-26.1 {Tk_TextLayoutToPostscript: ensure buffer doesn't overflow} { + # If there were a whole bunch of returns or tabs in a row, then the + # temporary buffer could overflow and write on the stack. + + csetup "qwertyuiopasdfghjklzxcvbnm1234qwertyuiopasdfghjklzxcvbnm\n" + .b.c itemconfig text -width 800 + .b.c insert text end "qwertyuiopasdfghjklzxcvbnm1234qwertyuiopasdfghjklzxcvbnm\n" + .b.c insert text end "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + .b.c insert text end "end" + set x [.b.c postscript] + set i [string first "(qwerty" $x] + string range $x $i [expr {$i + 213}] +} {(qwertyuiopasdfghjklzxcvbnm1234qwertyuiopasdfghjklzxcvbnm) +(qwertyuiopasdfghjklzxcvbnm1234qwertyuiopasdfghjklzxcvbnm) +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +() +(end) +} + +test font-27.1 {Tk_TextWidth procedure} { + font measure [.b.l cget -font] "000" +} [expr $ax*3] + +test font-28.1 {SetupFontMetrics procedure} { + setup + .b.f config -font $fixed +} {} + +test font-29.1 {TkInitFontAttributes procedure} { + setup + font create xyz + font config xyz +} {-family {} -size 0 -weight normal -slant roman -underline 0 -overstrike 0} + +test font-30.1 {ConfigAttributes procedure: arguments} { + setup + list [catch {font create xyz -family} msg] $msg +} {1 {missing value for "-family" option}} +test font-30.2 {ConfigAttributes procedure: arguments} { + setup + list [catch {font create xyz -xyz xyz} msg] $msg +} {1 {bad option "-xyz": must be -family, -size, -weight, -slant, -underline, or -overstrike}} +set i 3 +foreach p { + {family xyz times} + {size 20 40} + {weight normal bold} + {slant roman italic} + {underline 0 1} + {overstrike 0 1} +} { + set opt [lindex $p 0] + test font-30.$i "ConfigAttributes procedure: $opt" { + setup + set x {} + font create xyz -$opt [lindex $p 1] + lappend x [font config xyz -$opt] + font config xyz -$opt [lindex $p 2] + lappend x [font config xyz -$opt] + } [lrange $p 1 2] + incr i +} +foreach p { + {size xyz {1 {expected integer but got "xyz"}}} + {weight xyz {1 {bad -weight value "xyz": must be normal, bold}}} + {slant xyz {1 {bad -slant value "xyz": must be roman, italic}}} + {underline xyz {1 {expected boolean value but got "xyz"}}} + {overstrike xyz {1 {expected boolean value but got "xyz"}}} +} { + test font-30.$i "ConfigAttributes procedure: [lindex $p 0]" { + setup + list [catch {font create xyz -[lindex $p 0] [lindex $p 1]} msg] $msg + } [lindex $p 2] + incr i +} + +test font-31.1 {GetAttributeInfo procedure: error} { + list [catch {font actual xyz -style} msg] $msg +} {1 {bad option "-style": must be -family, -size, -weight, -slant, -underline, or -overstrike}} +test font-31.2 {GetAttributeInfo procedure: all attributes} { + setup + font create xyz -family xyz + font config xyz +} {-family xyz -size 0 -weight normal -slant roman -underline 0 -overstrike 0} +set i 3 +foreach p { + {family xyz xyz} + {size 20 20} + {weight normal normal} + {slant italic italic} + {underline yes 1} + {overstrike false 0} +} { + test font-31.$i "GetAttributeInfo procedure: [lindex $p 0]" { + setup + font create xyz -[lindex $p 0] [lindex $p 1] + font config xyz -[lindex $p 0] + } [lindex $p 2] + incr i +} + +# In tests below, one field is set to "xyz" so that font name doesn't +# look like a native X font, so that ParseFontName or TkParseXLFD will +# be called. + +setup + +test font-32.1 {ParseFontName procedure: begins with -} { + lindex [font actual -xyz-times-*-*-*-*-*-*-*-*-*-*-*-*] 1 +} $times +test font-32.2 {ParseFontName procedure: begins with -*} { + lindex [font actual -*-times-xyz-*-*-*-*-*-*-*-*-*-*-*] 1 +} $times +test font-32.3 {ParseFontName procedure: begins with -, doesn't look like list} { + lindex [font actual -xyz-times-*-*-*-*-*-*-*-*-*-*-*-*] 1 +} $times +test font-32.4 {ParseFontName procedure: begins with -, looks like list} { + lindex [font actual {-family times}] 1 +} $times +test font-32.5 {ParseFontName procedure: begins with *} { + lindex [font actual *-times-xyz-*-*-*-*-*-*-*-*-*-*-*] 1 +} $times +test font-32.6 {ParseFontName procedure: begins with *} { + font actual *-times-xyz -family +} $times +test font-32.7 {ParseFontName procedure: arguments} { + list [catch {font actual {}} msg] $msg +} {1 {font "" doesn't exist}} +test font-32.8 {ParseFontName procedure: arguments} { + list [catch {font actual {times 20 xyz xyz}} msg] $msg +} {1 {unknown font style "xyz"}} +test font-32.9 {ParseFontName procedure: arguments} { + list [catch {font actual {times xyz xyz}} msg] $msg +} {1 {expected integer but got "xyz"}} +test font-32.10 {ParseFontName procedure: stylelist loop} {macOnly} { + lrange [font actual {times 12 bold italic overstrike underline}] 4 end +} {-weight bold -slant italic -underline 1 -overstrike 0} +test font-32.11 {ParseFontName procedure: stylelist loop} {unixOrPc} { + lrange [font actual {times 12 bold italic overstrike underline}] 4 end +} {-weight bold -slant italic -underline 1 -overstrike 1} +test font-32.12 {ParseFontName procedure: stylelist error} { + list [catch {font actual {times 12 bold xyz}} msg] $msg +} {1 {unknown font style "xyz"}} + +test font-33.1 {TkParseXLFD procedure: initial dash} { + font actual -xyz-times-*-*-*-*-*-*-*-*-*-*-*-* -family +} $times +test font-33.2 {TkParseXLFD procedure: no initial dash} { + font actual *-times-*-*-*-*-*-*-*-*-*-*-*-xyz -family +} $times +test font-33.3 {TkParseXLFD procedure: not enough fields} { + font actual -xyz-times-*-*-* -family +} $times +test font-33.4 {TkParseXLFD procedure: all fields unspecified} { + lindex [font actual -xyz-*-*-*-*-*-*-*-*-*-*-*-*-*] 0 +} {-family} +test font-33.5 {TkParseXLFD procedure: all fields specified} { + lindex [font actual -foundry-times-weight-slant-setwidth-addstyle-10-10-10-10-spacing-avgwidth-registry-encoding] 1 +} $times +test font-33.6 {TkParseXLFD procedure: arguments} { + # XLFD with bad pointsize: fallback to some system font. + font actual -*-*-*-*-*-*-xyz-*-*-*-*-*-*-* + set x {} +} {} +test font-33.7 {TkParseXLFD procedure: arguments} { + # XLFD with bad pixelsize: fallback to some system font. + font actual -*-*-*-*-*-*-*-xyz-*-*-*-*-*-* + set x {} +} {} +test font-33.8 {TkParseXLFD procedure: pixelsize specified} { + font metrics -xyz-times-*-*-*-*-12-*-*-*-*-*-*-* -linespace + set x {} +} {} +test font-33.9 {TkParseXLFD procedure: weird pixelsize specified} { + font metrics {-xyz-times-*-*-*-*-[ 12.0 0 12.0 0]-*-*-*-*-*-*-*} -linespace + set x {} +} {} +test font-33.10 {TkParseXLFD procedure: pointsize specified} { + font metrics -xyz-times-*-*-*-*-*-120-*-*-*-*-*-* -linespace + set x {} +} {} +test font-33.11 {TkParseXLFD procedure: weird pointsize specified} { + font metrics {-xyz-times-*-*-*-*-*-[ 12.0 0 12.0 0]-*-*-*-*-*-*} -linespace + set x {} +} {} + +test font-34.1 {FieldSpecified procedure: specified vs. non-specified} { + font actual -xyz--*-*-*-*-*-*-*-*-*-*-*-* + font actual -xyz-*-*-*-*-*-*-*-*-*-*-*-*-* + font actual -xyz-?-*-*-*-*-*-*-*-*-*-*-*-* + lindex [font actual -xyz-times-*-*-*-*-*-*-*-*-*-*-*-*] 1 +} $times + +test font-35.1 {NewChunk procedure: test realloc} { + .b.f config -text "xxx\nxxx\txxx\nxxx\t\t\t" +} {} + +destroy .b +return diff --git a/tests/frame.test b/tests/frame.test new file mode 100644 index 0000000..c23d851 --- /dev/null +++ b/tests/frame.test @@ -0,0 +1,617 @@ +# This file is a Tcl script to test out the "frame" and "toplevel" +# commands of Tk. It is organized in the standard fashion for Tcl +# tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) frame.test 1.29 97/10/10 15:52:19 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + catch {destroy $i} +} +wm geometry . {} +raise . + +# eatColors -- +# Creates a toplevel window and allocates enough colors in it to +# use up all the slots in the colormap. +# +# Arguments: +# w - Name of toplevel window to create. + +proc eatColors {w} { + catch {destroy $w} + toplevel $w + wm geom $w +0+0 + canvas $w.c -width 400 -height 200 -bd 0 + pack $w.c + for {set y 0} {$y < 8} {incr y} { + for {set x 0} {$x < 40} {incr x} { + set color [format #%02x%02x%02x [expr $x*6] [expr $y*30] 0] + $w.c create rectangle [expr 10*$x] [expr 20*$y] \ + [expr 10*$x + 10] [expr 20*$y + 20] -outline {} \ + -fill $color + } + } + update +} + +# colorsFree -- +# +# Returns 1 if there appear to be free colormap entries in a window, +# 0 otherwise. +# +# Arguments: +# w - Name of window in which to check. +# red, green, blue - Intensities to use in a trial color allocation +# to see if there are colormap entries free. + +proc colorsFree {w {red 31} {green 245} {blue 192}} { + set vals [winfo rgb $w [format #%02x%02x%02x $red $green $blue]] + expr ([lindex $vals 0]/256 == $red) && ([lindex $vals 1]/256 == $green) \ + && ([lindex $vals 2]/256 == $blue) +} + +test frame-1.1 {frame configuration options} { + frame .f -class NewFrame + list [.f configure -class] [catch {.f configure -class Different} msg] $msg +} {{-class class Class Frame NewFrame} 1 {can't modify -class option after widget is created}} +catch {destroy .f} +test frame-1.2 {frame configuration options} { + list [catch {frame .f -colormap new} msg] $msg +} {0 .f} +catch {destroy .f} +test frame-1.3 {frame configuration options} { + list [catch {frame .f -visual default} msg] $msg +} {0 .f} +catch {destroy .f} +test frame-1.4 {frame configuration options} { + list [catch {frame .f -screen bogus} msg] $msg +} {1 {unknown option "-screen"}} +test frame-1.5 {frame configuration options} { + set result [list [catch {frame .f -container true} msg] $msg \ + [.f configure -container]] + destroy .f + set result +} {0 .f {-container container Container 0 1}} +test frame-1.6 {frame configuration options} { + list [catch {frame .f -container bogus} msg] $msg +} {1 {expected boolean value but got "bogus"}} +test frame-1.7 {frame configuration options} { + frame .f + set result [list [catch {.f configure -container 1} msg] $msg] + destroy .f + set result +} {1 {can't modify -container option after widget is created}} +frame .f +set i 8 +foreach test { + {-background #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-bd 4 4 badValue {bad screen distance "badValue"}} + {-bg #00ff00 #00ff00 non-existent + {unknown color name "non-existent"}} + {-borderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-cursor arrow arrow badValue {bad cursor spec "badValue"}} + {-height 100 100 not_a_number {bad screen distance "not_a_number"}} + {-highlightbackground #112233 #112233 ugly {unknown color name "ugly"}} + {-highlightcolor #123456 #123456 non-existent + {unknown color name "non-existent"}} + {-highlightthickness 6 6 badValue {bad screen distance "badValue"}} + {-relief ridge ridge badValue {bad relief type "badValue": must be flat, groove, raised, ridge, solid, or sunken}} + {-takefocus "any string" "any string" {} {}} + {-width 32 32 badValue {bad screen distance "badValue"}} +} { + set name [lindex $test 0] + test frame-1.$i {frame configuration options} { + .f configure $name [lindex $test 1] + lindex [.f configure $name] 4 + } [lindex $test 2] + incr i + if {[lindex $test 3] != ""} { + test frame-1.$i {frame configuration options} { + list [catch {.f configure $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .f configure $name [lindex [.f configure $name] 3] + incr i +} +destroy .f + +set i 1 +test frame-2.1 {toplevel configuration options} { + catch {destroy .t} + toplevel .t -width 200 -height 100 -class NewClass + wm geometry .t +0+0 + list [.t configure -class] [catch {.t configure -class Another} msg] $msg +} {{-class class Class Toplevel NewClass} 1 {can't modify -class option after widget is created}} +test frame-2.2 {toplevel configuration options} { + catch {destroy .t} + toplevel .t -width 200 -height 100 -colormap new + wm geometry .t +0+0 + list [.t configure -colormap] [catch {.t configure -colormap .} msg] $msg +} {{-colormap colormap Colormap {} new} 1 {can't modify -colormap option after widget is created}} +test frame-2.3 {toplevel configuration options} { + catch {destroy .t} + toplevel .t -width 200 -height 100 + wm geometry .t +0+0 + list [catch {.t configure -container 1} msg] $msg [.t configure -container] +} {1 {can't modify -container option after widget is created} {-container container Container 0 0}} +test frame-2.4 {toplevel configuration options} { + catch {destroy .t} + list [catch {toplevel .t -width 200 -height 100 -colormap bogus} msg] $msg +} {1 {bad window path name "bogus"}} +set default "[winfo visual .] [winfo depth .]" +test frame-2.5 {toplevel configuration options} { + catch {destroy .t} + toplevel .t -width 200 -height 100 + wm geometry .t +0+0 + list [catch {.t configure -use 0x44022} msg] $msg [.t configure -use] +} {1 {can't modify -use option after widget is created} {-use use Use {} {}}} +test frame-2.6 {toplevel configuration options} { + catch {destroy .t} + toplevel .t -width 200 -height 100 -visual default + wm geometry .t +0+0 + list [.t configure -visual] [catch {.t configure -visual best} msg] $msg +} {{-visual visual Visual {} default} 1 {can't modify -visual option after widget is created}} +test frame-2.7 {toplevel configuration options} { + catch {destroy .t} + list [catch {toplevel .t -width 200 -height 100 -visual who_knows?} msg] $msg +} {1 {unknown or ambiguous visual name "who_knows?": class must be best, directcolor, grayscale, greyscale, pseudocolor, staticcolor, staticgray, staticgrey, truecolor, or default}} +if [info exists env(DISPLAY)] { + test frame-2.8 {toplevel configuration options} { + catch {destroy .t} + toplevel .t -width 200 -height 100 -screen $env(DISPLAY) + wm geometry .t +0+0 + list [.t configure -screen] \ + [catch {.t configure -screen another} msg] $msg + } [list [list -screen screen Screen {} $env(DISPLAY)] 1 {can't modify -screen option after widget is created}] +} +test frame-2.9 {toplevel configuration options} { + catch {destroy .t} + list [catch {toplevel .t -width 200 -height 100 -screen bogus} msg] $msg +} {1 {couldn't connect to display "bogus"}} +catch {destroy .t} +toplevel .t -width 300 -height 150 +wm geometry .t +0+0 +update +set i 8 +foreach test { + {-background #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-bd 4 4 badValue {bad screen distance "badValue"}} + {-bg #00ff00 #00ff00 non-existent + {unknown color name "non-existent"}} + {-borderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-cursor arrow arrow badValue {bad cursor spec "badValue"}} + {-height 100 100 not_a_number {bad screen distance "not_a_number"}} + {-highlightcolor #123456 #123456 non-existent + {unknown color name "non-existent"}} + {-highlightthickness 3 3 badValue {bad screen distance "badValue"}} + {-relief ridge ridge badValue {bad relief type "badValue": must be flat, groove, raised, ridge, solid, or sunken}} + {-width 32 32 badValue {bad screen distance "badValue"}} +} { + set name [lindex $test 0] + test frame-2.$i {frame configuration options} { + .t configure $name [lindex $test 1] + lindex [.t configure $name] 4 + } [lindex $test 2] + incr i + if {[lindex $test 3] != ""} { + test frame-2.$i {frame configuration options} { + list [catch {.t configure $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .t configure $name [lindex [.t configure $name] 3] + incr i +} + +test frame-3.1 {TkCreateFrame procedure} { + list [catch frame msg] $msg +} {1 {wrong # args: should be "frame pathName ?options?"}} +test frame-3.2 {TkCreateFrame procedure} { + catch {destroy .f} + frame .f + set result [.f configure -class] + destroy .f + set result +} {-class class Class Frame Frame} +test frame-3.3 {TkCreateFrame procedure} { + catch {destroy .t} + toplevel .t + wm geometry .t +0+0 + set result [.t configure -class] + destroy .t + set result +} {-class class Class Toplevel Toplevel} +test frame-3.4 {TkCreateFrame procedure} { + catch {destroy .t} + toplevel .t -width 350 -class NewClass -bg black -visual default -height 90 + wm geometry .t +0+0 + update + list [lindex [.t configure -width] 4] \ + [lindex [.t configure -background] 4] \ + [lindex [.t configure -height] 4] +} {350 black 90} + +# Be sure that the -class, -colormap, and -visual options are processed +# before configuring the widget. + +test frame-3.5 {TkCreateFrame procedure} { + catch {destroy .f} + option add *NewFrame.background #123456 + frame .f -class NewFrame + option clear + lindex [.f configure -background] 4 +} {#123456} +test frame-3.6 {TkCreateFrame procedure} { + catch {destroy .f} + option add *NewFrame.background #123456 + frame .f -class NewFrame + option clear + lindex [.f configure -background] 4 +} {#123456} +test frame-3.7 {TkCreateFrame procedure} { + catch {destroy .f} + option add *NewFrame.background #332211 + option add *f.class NewFrame + frame .f + option clear + list [lindex [.f configure -class] 4] [lindex [.f configure -background] 4] +} {NewFrame #332211} +test frame-3.8 {TkCreateFrame procedure} { + catch {destroy .f} + option add *Silly.background #122334 + option add *f.Class Silly + frame .f + option clear + list [lindex [.f configure -class] 4] [lindex [.f configure -background] 4] +} {Silly #122334} +test frame-3.9 {TkCreateFrame procedure, -use option} unixOnly { + catch {destroy .t} + catch {destroy .x} + toplevel .t -container 1 -width 300 -height 120 + wm geometry .t +0+0 + toplevel .x -width 140 -height 300 -use [winfo id .t] -bg green + tkwait visibility .x + set result "[expr [winfo rootx .x] - [winfo rootx .t]] [expr [winfo rooty .x] - [winfo rooty .t]] [winfo width .t] [winfo height .t]" + destroy .t + set result +} {0 0 140 300} +test frame-3.10 {TkCreateFrame procedure, -use option} unixOnly { + catch {destroy .t} + catch {destroy .x} + toplevel .t -container 1 -width 300 -height 120 + wm geometry .t +0+0 + option add *x.use [winfo id .t] + toplevel .x -width 140 -height 300 -bg green + tkwait visibility .x + set result "[expr [winfo rootx .x] - [winfo rootx .t]] [expr [winfo rooty .x] - [winfo rooty .t]] [winfo width .t] [winfo height .t]" + destroy .t + option clear + set result +} {0 0 140 300} + +# The tests below require specific display characteristics. Even so, +# they are non-portable: some machines don't seem to ever run out of +# colors. + +if {([winfo visual .] == "pseudocolor") && ([winfo depth .] == 8)} { + eatColors .t1 + test frame-3.11 {TkCreateFrame procedure} {nonPortable} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bg #475601 + wm geometry .t +0+0 + update + colorsFree .t + } {0} + test frame-3.12 {TkCreateFrame procedure} {nonPortable} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bg #475601 -colormap new + wm geometry .t +0+0 + update + colorsFree .t + } {1} + test frame-3.13 {TkCreateFrame procedure} {nonPortable} { + catch {destroy .t} + option add *t.class Toplevel2 + option add *Toplevel2.colormap new + toplevel .t -width 300 -height 200 -bg #475601 + wm geometry .t +0+0 + update + option clear + colorsFree .t + } {1} + test frame-3.14 {TkCreateFrame procedure} {nonPortable} { + catch {destroy .t} + option add *t.class Toplevel3 + option add *Toplevel3.Colormap new + toplevel .t -width 300 -height 200 -bg #475601 -colormap new + wm geometry .t +0+0 + update + option clear + colorsFree .t + } {1} + test frame-3.15 {TkCreateFrame procedure, -use and -colormap} {unixOnly nonPortable} { + catch {destroy .t} + catch {destroy .x} + toplevel .t -container 1 -width 300 -height 120 + wm geometry .t +0+0 + toplevel .x -width 140 -height 300 -use [winfo id .t] -bg green -colormap new + tkwait visibility .x + set result "[colorsFree .t] [colorsFree .x]" + destroy .t + set result + } {0 1} + test frame-3.16 {TkCreateFrame procedure} {nonPortable} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bg #475601 -visual default + wm geometry .t +0+0 + update + colorsFree .t + } {0} + test frame-3.17 {TkCreateFrame procedure} {nonPortable} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bg #475601 -visual default \ + -colormap new + wm geometry .t +0+0 + update + colorsFree .t + } {1} + if {[lsearch -exact [winfo visualsavailable .] {grayscale 8}] >= 0} { + test frame-3.18 {TkCreateFrame procedure} {nonPortable} { + catch {destroy .t} + toplevel .t -visual {grayscale 8} -width 300 -height 200 \ + -bg #434343 + wm geometry .t +0+0 + update + colorsFree .t 131 131 131 + } {1} + test frame-3.19 {TkCreateFrame procedure} {nonPortable} { + catch {destroy .t} + option add *t.class T4 + option add *T4.visual {grayscale 8} + toplevel .t -width 300 -height 200 -bg #434343 + wm geometry .t +0+0 + update + option clear + list [colorsFree .t 131 131 131] [lindex [.t configure -visual] 4] + } {1 {grayscale 8}} + test frame-3.20 {TkCreateFrame procedure} {nonPortable} { + catch {destroy .t} + set x ok + option add *t.class T5 + option add *T5.Visual {grayscale 8} + toplevel .t -width 300 -height 200 -bg #434343 + wm geometry .t +0+0 + update + option clear + list [colorsFree .t 131 131 131] [lindex [.t configure -visual] 4] + } {1 {grayscale 8}} + test frame-3.21 {TkCreateFrame procedure} {nonPortable} { + catch {destroy .t} + set x ok + toplevel .t -visual {grayscale 8} -width 300 -height 200 \ + -bg #434343 + wm geometry .t +0+0 + update + colorsFree .t 131 131 131 + } {1} + } + destroy .t1 +} +test frame-3.22 {TkCreateFrame procedure, default dimensions} { + catch {destroy .t} + toplevel .t + wm geometry .t +0+0 + update + set result "[winfo reqwidth .t] [winfo reqheight .t]" + frame .t.f -bg red + pack .t.f + update + lappend result [winfo reqwidth .t.f] [winfo reqheight .t.f] + destroy .t + set result +} {200 200 1 1} +test frame-3.23 {TkCreateFrame procedure} { + catch {destroy .f} + list [catch {frame .f -gorp glob} msg] $msg +} {1 {unknown option "-gorp"}} +test frame-3.24 {TkCreateFrame procedure} { + catch {destroy .t} + list [catch { + toplevel .t -width 300 -height 200 -colormap new -bogus option + wm geometry .t +0+0 + } msg] $msg +} {1 {unknown option "-bogus"}} + +test frame-4.1 {TkCreateFrame procedure} { + catch {destroy .f} + catch {frame .f -gorp glob} + winfo exists .f +} 0 +test frame-4.2 {TkCreateFrame procedure} { + catch {destroy .f} + list [frame .f -width 200 -height 100] [winfo exists .f] +} {.f 1} + +catch {destroy .f} +frame .f -highlightcolor black +test frame-5.1 {FrameWidgetCommand procedure} { + list [catch .f msg] $msg +} {1 {wrong # args: should be ".f option ?arg arg ...?"}} +test scale-5.2 {FrameWidgetCommand procedure, cget option} { + list [catch {.f cget} msg] $msg +} {1 {wrong # args: should be ".f cget option"}} +test scale-5.3 {FrameWidgetCommand procedure, cget option} { + list [catch {.f cget a b} msg] $msg +} {1 {wrong # args: should be ".f cget option"}} +test scale-5.4 {FrameWidgetCommand procedure, cget option} { + list [catch {.f cget -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test scale-5.5 {FrameWidgetCommand procedure, cget option} { + .f cget -highlightcolor +} {black} +test scale-5.6 {FrameWidgetCommand procedure, cget option} { + list [catch {.f cget -screen} msg] $msg +} {1 {unknown option "-screen"}} +test scale-5.7 {FrameWidgetCommand procedure, cget option} { + catch {destroy .t} + toplevel .t + catch {.t cget -screen} +} {0} +catch {destroy .t} +test frame-5.8 {FrameWidgetCommand procedure, configure option} { + llength [.f configure] +} {16} +test frame-5.9 {FrameWidgetCommand procedure, configure option} { + list [catch {.f configure -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test frame-5.10 {FrameWidgetCommand procedure, configure option} { + list [catch {.f configure -gorp bogus} msg] $msg +} {1 {unknown option "-gorp"}} +test frame-5.11 {FrameWidgetCommand procedure, configure option} { + list [catch {.f configure -width 200 -height} msg] $msg +} {1 {value for "-height" missing}} +test frame-5.12 {FrameWidgetCommand procedure} { + list [catch {.f swizzle} msg] $msg +} {1 {bad option "swizzle": must be cget or configure}} + +test frame-6.1 {ConfigureFrame procedure} { + catch {destroy .f} + frame .f -width 150 + list [winfo reqwidth .f] [winfo reqheight .f] +} {150 1} +test frame-6.2 {ConfigureFrame procedure} { + catch {destroy .f} + frame .f -height 97 + list [winfo reqwidth .f] [winfo reqheight .f] +} {1 97} +test frame-6.3 {ConfigureFrame procedure} { + catch {destroy .f} + frame .f + set result {} + lappend result [winfo reqwidth .f] [winfo reqheight .f] + .f configure -width 100 -height 180 + lappend result [winfo reqwidth .f] [winfo reqheight .f] + .f configure -width 0 -height 0 + lappend result [winfo reqwidth .f] [winfo reqheight .f] +} {1 1 100 180 100 180} + +test frame-7.1 {FrameEventProc procedure} { + frame .frame2 + set result [info commands .frame2] + destroy .frame2 + lappend result [info commands .frame2] +} {.frame2 {}} +test frame-7.2 {FrameEventProc procedure} { + eval destroy [winfo children .] + frame .f1 -bg #543210 + rename .f1 .f2 + set x {} + lappend x [winfo children .] + lappend x [.f2 cget -bg] + destroy .f1 + lappend x [info command .f*] [winfo children .] +} {.f1 #543210 {} {}} + +test frame-8.1 {FrameCmdDeletedProc procedure} { + eval destroy [winfo children .] + frame .f1 + rename .f1 {} + list [info command .f*] [winfo children .] +} {{} {}} +test frame-8.2 {FrameCmdDeletedProc procedure} { + eval destroy [winfo children .] + toplevel .f1 -menu .m + wm geometry .f1 +0+0 + update + rename .f1 {} + update + list [info command .f*] [winfo children .] +} {{} {}} +test frame-8.3 {FrameCmdDeletedProc procedure} { + eval destroy [winfo children .] + toplevel .f1 -menu .m + wm geometry .f1 +0+0 + menu .m + update + rename .f1 {} + update + set result [list [info command .f*] [winfo children .]] + eval destroy [winfo children .] + set result +} {{} .m} + +test frame-9.1 {MapFrame procedure} { + catch {destroy .t} + toplevel .t -width 100 -height 400 + wm geometry .t +0+0 + set result [winfo ismapped .t] + update idletasks + lappend result [winfo ismapped .t] +} {0 1} +test frame-9.2 {MapFrame procedure} { + catch {destroy .t} + toplevel .t -width 100 -height 400 + wm geometry .t +0+0 + destroy .t + update + winfo exists .t +} {0} +test frame-9.3 {MapFrame procedure, window deleted while mapping} { + toplevel .t2 -width 200 -height 200 + wm geometry .t2 +0+0 + tkwait visibility .t2 + catch {destroy .t} + toplevel .t -width 100 -height 400 + wm geometry .t +0+0 + frame .t2.f -width 50 -height 50 + bind .t2.f <Configure> {destroy .t} + pack .t2.f -side top + update idletasks + winfo exists .t +} {0} + +set l [interp hidden] +eval destroy [winfo children .] + +test frame-10.1 {frame widget vs hidden commands} { + catch {destroy .t} + frame .t + interp hide {} .t + destroy .t + list [winfo children .] [interp hidden] +} [list {} $l] + +test frame-11.1 {TkInstallFrameMenu} { + catch {destroy .t} + menu .m1 + .m1 add cascade -menu .m1.system + menu .m1.system -tearoff 0 + .m1.system add command -label foo + list [toplevel .t -menu .m1] [destroy .m1] [destroy .t] +} {.t {} {}} +test frame-11.2 {TkInstallFrameMenu - frame renamed} { + catch {destroy .t} + catch {rename foo {}} + menu .m1 + .m1 add cascade -menu .m1.system + menu .m1.system -tearoff 0 + .m1.system add command -label foo + toplevel .t + list [rename .t foo] [destroy .t] [destroy foo] [destroy .m1] +} {{} {} {} {}} + + +catch {destroy .f} +rename eatColors {} +rename colorsFree {} diff --git a/tests/geometry.test b/tests/geometry.test new file mode 100644 index 0000000..d5d1f01 --- /dev/null +++ b/tests/geometry.test @@ -0,0 +1,251 @@ +# This file is a Tcl script to test the procedures in the file +# tkGeometry.c (generic support for geometry managers). It is +# organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) geometry.test 1.9 96/02/16 10:55:06 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . 300x300 +raise . +update + +frame .f -bd 2 -relief raised +frame .f.f -bd 2 -relief sunken +frame .f.f.f -bd 2 -relief raised +button .b1 -text .b1 +button .b2 -text .b2 +button .b3 -text .b3 +button .f.f.b4 -text .b4 + +test geometry-1.1 {Tk_ManageGeometry procedure} { + place .b1 -x 120 -y 80 + update + list [winfo x .b1] [winfo y .b1] +} {120 80} +test geometry-1.2 {Tk_ManageGeometry procedure} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3} { + place forget $w + } + place .f -x 20 -y 30 -width 200 -height 200 + place .b1 -in .f -x 40 -y 30 + update + pack .b1 -side top -anchor w + place .f -x 30 -y 40 + update + list [winfo x .b1] [winfo y .b1] +} {0 0} + +test geometry-2.1 {Tk_GeometryRequest procedure} { + frame .f2 + set result [list [winfo reqwidth .f2] [winfo reqheight .f2]] + .f2 configure -width 150 -height 300 + update + lappend result [winfo reqwidth .f2] [winfo reqheight .f2] \ + [winfo geom .f2] + place .f2 -x 10 -y 20 + update + lappend result [winfo geom .f2] + .f2 configure -width 100 -height 80 + update + lappend result [winfo geom .f2] +} {1 1 150 300 1x1+0+0 150x300+10+20 100x80+10+20} +catch {destroy .f2} + +test geometry-3.1 {Tk_SetInternalBorder procedure} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3} { + place forget $w + } + place .f -x 20 -y 30 -width 200 -height 200 + place .b1 -in .f -x 50 -y 5 + update + set x [list [winfo x .b1] [winfo y .b1]] + .f configure -bd 5 + update + lappend x [winfo x .b1] [winfo y .b1] +} {72 37 75 40} +.f configure -bd 2 + +test geometry-4.1 {Tk_MaintainGeometry and Tk_UnmaintainGeometry} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3} { + place forget $w + } + place .f -x 20 -y 30 -width 200 -height 200 + place .f.f -x 15 -y 5 -width 150 -height 120 + place .f.f.f -width 100 -height 80 + place .b1 -in .f.f.f -x 50 -y 5 + update + list [winfo x .b1] [winfo y .b1] +} {91 46} +test geometry-4.2 {Tk_MaintainGeometry and Tk_UnmaintainGeometry} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3} { + place forget $w + } + place .f -x 20 -y 30 -width 200 -height 200 + place .f.f -x 15 -y 5 -width 150 -height 120 + place .f.f.f -width 100 -height 80 + place .b1 -in .f.f.f -x 50 -y 5 + place .b2 -in .f.f.f -x 10 -y 25 + place .b3 -in .f.f.f -x 50 -y 25 + update + place .f -x 30 -y 25 + update + list [winfo x .b1] [winfo y .b1] [winfo x .b2] [winfo y .b2] \ + [winfo x .b3] [winfo y .b3] +} {101 41 61 61 101 61} +test geometry-4.3 {Tk_MaintainGeometry and Tk_UnmaintainGeometry} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3} { + place forget $w + } + place .f -x 20 -y 30 -width 200 -height 200 + place .f.f -x 15 -y 5 -width 150 -height 120 + place .f.f.f -width 100 -height 80 + place .b1 -in .f.f.f -x 50 -y 5 + place .b2 -in .f.f.f -x 10 -y 25 + place .b3 -in .f.f.f -x 50 -y 25 + update + destroy .b1 + button .b1 -text .b1 + place .f.f -x 10 -y 25 + update + list [winfo x .b1] [winfo y .b1] [winfo x .b2] [winfo y .b2] \ + [winfo x .b3] [winfo y .b3] +} {0 0 46 86 86 86} +test geometry-4.4 {Tk_MaintainGeometry and Tk_UnmaintainGeometry} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3} { + place forget $w + } + place .f -x 20 -y 30 -width 200 -height 200 + place .f.f -x 15 -y 5 -width 150 -height 120 + place .f.f.f -width 100 -height 80 + place .b1 -in .f.f.f -x 50 -y 5 + place .b2 -in .f.f.f -x 10 -y 25 + place .b3 -in .f.f.f -x 50 -y 25 + update + destroy .b2 + button .b2 -text .b2 + place .f.f.f -x 2 -y 3 + update + list [winfo x .b1] [winfo y .b1] [winfo x .b2] [winfo y .b2] \ + [winfo x .b3] [winfo y .b3] +} {93 49 0 0 93 69} +test geometry-4.5 {Tk_MaintainGeometry and Tk_UnmaintainGeometry} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3} { + place forget $w + } + place .f -x 20 -y 30 -width 200 -height 200 + place .f.f -x 15 -y 5 -width 150 -height 120 + place .f.f.f -width 100 -height 80 + place .b1 -in .f.f.f -x 50 -y 5 + place .b2 -in .f.f.f -x 10 -y 25 + place .b3 -in .f.f.f -x 50 -y 25 + update + destroy .b3 + button .b3 -text .b3 + place .f.f.f -x 2 -y 3 + update + list [winfo x .b1] [winfo y .b1] [winfo x .b2] [winfo y .b2] \ + [winfo x .b3] [winfo y .b3] +} {93 49 53 69 0 0} +test geometry-4.6 {Tk_MaintainGeometry and Tk_UnmaintainGeometry} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3 .f.f.b4} { + place forget $w + } + place .f -x 20 -y 30 -width 200 -height 200 + place .f.f -x 15 -y 5 -width 150 -height 120 + place .f.f.f -width 100 -height 80 + place .f.f.b4 -in .f.f.f -x 50 -y 5 + place .b2 -in .f.f.f -x 10 -y 25 + update + place .f -x 25 -y 35 + update + list [winfo x .f.f.b4] [winfo y .f.f.b4] [winfo x .b2] [winfo y .b2] +} {54 9 56 71} +test geometry-4.7 {Tk_MaintainGeometry and Tk_UnmaintainGeometry} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3 .f.f.b4} { + place forget $w + } + bind .b1 <Configure> {lappend x configure} + place .f -x 20 -y 30 -width 200 -height 200 + place .f.f -x 15 -y 5 -width 150 -height 120 + place .f.f.f -width 100 -height 80 + place .f.f.b4 -in .f.f.f -x 50 -y 5 + place .b1 -in .f.f.f -x 10 -y 25 + update + set x init + place .f -x 25 -y 35 + update + lappend x | + place .f -x 30 -y 40 + place .f.f -x 10 -y 0 + update + bind .b1 <Configure> {} + set x +} {init configure |} +test geometry-4.8 {Tk_MaintainGeometry and Tk_UnmaintainGeometry} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3} { + place forget $w + } + place .f -x 20 -y 30 -width 200 -height 200 + place .f.f -x 15 -y 5 -width 150 -height 120 + place .f.f.f -width 100 -height 80 + place .b1 -in .f.f.f -x 50 -y 5 + place .b2 -in .f.f.f -x 10 -y 25 + place .b3 -in .f.f.f -x 50 -y 25 + update + destroy .f.f + frame .f.f -bd 2 -relief raised + frame .f.f.f -bd 2 -relief raised + place .f -x 30 -y 25 + update + list [winfo x .b1] [winfo y .b1] [winfo ismapped .b1] \ + [winfo x .b2] [winfo y .b2] [winfo ismapped .b2] \ + [winfo x .b3] [winfo y .b3] [winfo ismapped .b3] +} {91 46 0 51 66 0 91 66 0} +test geometry-4.9 {Tk_MaintainGeometry and Tk_UnmaintainGeometry} { + foreach w {.f .f.f .f.f.f .b1 .b2 .b3} { + place forget $w + } + place .f -x 20 -y 30 -width 200 -height 200 + place .f.f -x 15 -y 5 -width 150 -height 120 + place .f.f.f -width 100 -height 80 + place .b1 -in .f.f.f -x 50 -y 5 + update + set result [winfo ismapped .b1] + place forget .f.f + update + lappend result [winfo ismapped .b1] + place .f.f -x 15 -y 5 -width 150 -height 120 + update + lappend result [winfo ismapped .b1] +} {1 0 1} +test geometry-4.10 {Tk_MaintainGeometry and Tk_UnmaintainGeometry} { + toplevel .t + wm geometry .t +0+0 + tkwait visibility .t + update + frame .t.f + pack .t.f + button .t.quit -text Quit -command exit + pack .t.quit -in .t.f + wm iconify .t + set x 0 + after 500 {set x 1} + tkwait variable x + wm deiconify .t + update + winfo ismapped .t.quit +} {1} +catch {destroy .t} +concat diff --git a/tests/grid.test b/tests/grid.test new file mode 100644 index 0000000..fae31fe --- /dev/null +++ b/tests/grid.test @@ -0,0 +1,1205 @@ +# This file is a Tcl script to test out the *NEW* "grid" command +# of Tk. It is (almost) organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) grid.test 1.22 97/10/10 10:07:31 + +if {[string compare test [info procs test]] == 1} then \ + {source ../tests/defs} + +# Test Arguments: +# name - Name of test, in the form foo-1.2. +# description - Short textual description of the test, to +# help humans understand what it does. +# constraints - A list of one or more keywords, each of +# which must be the name of an element in +# the array "testConfig". If any of these +# elements is zero, the test is skipped. +# This argument may be omitted. +# script - Script to run to carry out the test. It must +# return a result that can be checked for +# correctness. +# answer - Expected result from script. + +# helper routine to return "." to a sane state after a test +# The variable GRID_VERBOSE can be used to "look" at the result +# of one or all of the tests + +proc grid_reset {{test ?} {top .}} { + global GRID_VERBOSE + if {[info exists GRID_VERBOSE]} { + if {$GRID_VERBOSE=="" || $GRID_VERBOSE==$test} { + puts -nonewline "grid test $test: " + flush stdout + gets stdin + } + } + eval destroy [winfo children $top] + update + foreach {cols rows} [grid size .] {} + for {set i 0} {$i <= $cols} {incr i} { + grid columnconfigure . $i -weight 0 -minsize 0 -pad 0 + } + for {set i 0} {$i <= $rows} {incr i} { + grid rowconfigure . $i -weight 0 -minsize 0 -pad 0 + } + grid propagate . 1 + update +} + +grid_reset 0.0 +wm geometry . {} + +test grid-1.1 {basic argument checking} { + list [catch grid msg] $msg +} {1 {wrong # args: should be "grid option arg ?arg ...?"}} + +test grid-1.2 {basic argument checking} { + list [catch {grid foo bar} msg] $msg +} {1 {bad option "foo": must be bbox, columnconfigure, configure, forget, info, location, propagate, remove, rowconfigure, size, or slaves.}} + +test grid-1.3 {basic argument checking} { + button .b + list [catch {grid .b -row 0 -column} msg] $msg +} {1 {extra option or option with no value}} +grid_reset 1.3 + +test grid-1.4 {basic argument checking} { + button .b + list [catch {grid configure .b - foo} msg] $msg +} {1 {unexpected parameter, "foo", in configure list. Should be window name or option}} +grid_reset 1.4 + +test grid-1.5 {basic argument checking} { + list [catch {grid .} msg] $msg +} {1 {can't manage ".": it's a top-level window}} + +test grid-1.6 {basic argument checking} { + list [catch {grid x} msg] $msg +} {1 {can't determine master window}} + +test grid-2.1 {bbox} { + list [catch {grid bbox .} msg] $msg +} {0 {0 0 0 0}} + +test grid-2.2 {bbox} { + button .b + grid .b + destroy .b + update + list [catch {grid bbox .} msg] $msg +} {0 {0 0 0 0}} + +test grid-2.3 {bbox: argument checking} { + list [catch {grid bbox . 0 0 5} msg] $msg +} {1 {wrong number of arguments: must be "grid bbox master ?column row ?column row??"}} + +test grid-2.4 {bbox} { + list [catch {grid bbox .bad 0 0} msg] $msg +} {1 {bad window path name ".bad"}} + +test grid-2.5 {bbox} { + list [catch {grid bbox . x 0} msg] $msg +} {1 {expected integer but got "x"}} + +test grid-2.6 {bbox} { + list [catch {grid bbox . 0 x} msg] $msg +} {1 {expected integer but got "x"}} + +test grid-2.7 {bbox} { + list [catch {grid bbox . 0 0 x 0} msg] $msg +} {1 {expected integer but got "x"}} + +test grid-2.8 {bbox} { + list [catch {grid bbox . 0 0 0 x} msg] $msg +} {1 {expected integer but got "x"}} + +test grid-2.9 {bbox} { + frame .1 -width 75 -height 75 -bg red + frame .2 -width 90 -height 90 -bg red + grid .1 -row 0 -column 0 + grid .2 -row 1 -column 1 + update + set a "" + lappend a [grid bbox .] + lappend a [grid bbox . 0 0] + lappend a [grid bbox . 0 0 1 1] + lappend a [grid bbox . 1 1] + set a +} {{0 0 165 165} {0 0 75 75} {0 0 165 165} {75 75 90 90}} +grid_reset 2.9 + +test grid-2.10 {bbox} { + frame .1 -width 75 -height 75 -bg red + frame .2 -width 90 -height 90 -bg red + grid .1 -row 0 -column 0 + grid .2 -row 1 -column 1 + update + set a "" + lappend a [grid bbox . 10 10 0 0] + lappend a [grid bbox . -2 -2 -1 -1] + lappend a [grid bbox . 10 10 12 12] + set a +} {{0 0 165 165} {0 0 0 0} {165 165 0 0}} +grid_reset 2.10 + +test grid-3.1 {configure: basic argument checking} { + list [catch {grid configure foo} msg] $msg +} {1 {bad argument "foo": must be name of window}} + +test grid-3.2 {configure: basic argument checking} { + button .b + grid configure .b + grid slaves . +} {.b} +grid_reset 3.2 + +test grid-3.3 {configure: basic argument checking} { + button .b + list [catch {grid .b -row -1} msg] $msg +} {1 {bad grid value "-1": must be a non-negative integer}} +grid_reset 3.3 + +test grid-3.4 {configure: basic argument checking} { + button .b + list [catch {grid .b -column -1} msg] $msg +} {1 {bad column value "-1": must be a non-negative integer}} +grid_reset 3.4 + +test grid-3.5 {configure: basic argument checking} { + button .b + list [catch {grid .b -rowspan 0} msg] $msg +} {1 {bad rowspan value "0": must be a positive integer}} +grid_reset 3.5 + +test grid-3.6 {configure: basic argument checking} { + button .b + list [catch {grid .b -columnspan 0} msg] $msg +} {1 {bad columnspan value "0": must be a positive integer}} +grid_reset 3.6 + +test grid-3.7 {configure: basic argument checking} { + frame .f + button .f.b + list [catch {grid .f .f.b} msg] $msg +} {1 {can't put .f.b inside .}} +grid_reset 3.7 + +test grid-4.1 {forget: basic argument checking} { + list [catch {grid forget foo} msg] $msg +} {1 {bad window path name "foo"}} + +test grid-4.2 {forget} { + button .c + grid [button .b] + set a [grid slaves .] + grid forget .b .c + lappend a [grid slaves .] + set a +} {.b {}} +grid_reset 4.2 + +test grid-4.3 {forget} { + button .c + grid .c -row 2 -column 2 -rowspan 2 -columnspan 2 -padx 3 -pady 4 -sticky ns + grid forget .c + grid .c -row 0 -column 0 + grid info .c +} {-in . -column 0 -row 0 -columnspan 1 -rowspan 1 -ipadx 0 -ipady 0 -padx 0 -pady 0 -sticky {}} +grid_reset 4.3 + +test grid-4.4 {forget, calling Tk_UnmaintainGeometry} { + frame .f -bd 2 -relief raised + place .f -x 10 -y 20 -width 200 -height 100 + frame .f2 -width 50 -height 30 -bg red + grid .f2 -in .f + update + set x [winfo ismapped .f2] + grid forget .f2 + place .f -x 30 + update + lappend x [winfo ismapped .f2] +} {1 0} +grid_reset 4.4 + +test grid-5.1 {info: basic argument checking} { + list [catch {grid info a b} msg] $msg +} {1 {wrong # args: should be "grid info window"}} + +test grid-5.2 {info} { + frame .1 -width 75 -height 75 -bg red + grid .1 -row 0 -column 0 + update + list [catch {grid info .x} msg] $msg +} {1 {bad window path name ".x"}} +grid_reset 5.2 + +test grid-5.3 {info} { + frame .1 -width 75 -height 75 -bg red + grid .1 -row 0 -column 0 + update + list [catch {grid info .1} msg] $msg +} {0 {-in . -column 0 -row 0 -columnspan 1 -rowspan 1 -ipadx 0 -ipady 0 -padx 0 -pady 0 -sticky {}}} +grid_reset 5.3 + +test grid-5.4 {info} { + frame .1 -width 75 -height 75 -bg red + update + list [catch {grid info .1} msg] $msg +} {0 {}} +grid_reset 5.4 + +test grid-6.1 {location: basic argument checking} { + list [catch "grid location ." msg] $msg +} {1 {wrong # args: should be "grid location master x y"}} + +test grid-6.2 {location: basic argument checking} { + list [catch "grid location .bad 0 0" msg] $msg +} {1 {bad window path name ".bad"}} + +test grid-6.3 {location: basic argument checking} { + list [catch "grid location . x y" msg] $msg +} {1 {bad screen distance "x"}} + +test grid-6.4 {location: basic argument checking} { + list [catch "grid location . 1c y" msg] $msg +} {1 {bad screen distance "y"}} + +test grid-6.5 {location: basic argument checking} { + frame .f + grid location .f 10 10 +} {-1 -1} +grid_reset 6.5 + +test grid-6.6 {location (x)} { + frame .f -width 200 -height 100 -highlightthickness 0 -bg red + grid .f + update + set got "" + set result "" + for {set x -10} { $x < 220} { incr x} { + set a [grid location . $x 0] + if {$a != $got} { + lappend result $x->$a + set got $a + } + } + set result +} {{-10->-1 0} {0->0 0} {201->1 0}} +grid_reset 6.6 + +test grid-6.7 {location (y)} { + frame .f -width 200 -height 100 -highlightthickness 0 -bg red + grid .f + update + set got "" + set result "" + for {set y -10} { $y < 110} { incr y} { + set a [grid location . 0 $y] + if {$a != $got} { + lappend result $y->$a + set got $a + } + } + set result +} {{-10->0 -1} {0->0 0} {101->0 1}} +grid_reset 6.7 + +test grid-6.8 {location (weights)} { + frame .f -width 200 -height 100 -highlightthickness 0 -bg red + frame .a + grid .a + grid .f -in .a + grid rowconfigure .f 0 -weight 1 + grid columnconfigure .f 0 -weight 1 + grid propagate .a 0 + .a configure -width 110 -height 15 + update + set got "" + set result "" + for {set y -10} { $y < 120} { incr y} { + set a [grid location . $y $y] + if {$a != $got} { + lappend result $y->$a + set got $a + } + } + set result +} {{-10->-1 -1} {0->0 0} {16->0 1} {111->1 1}} +grid_reset 6.8 + +test grid-6.9 {location: check updates pending} { + set a "" + foreach i {0 1 2} { + frame .$i -width 120 -height 75 -bg red + lappend a [grid location . 150 90] + grid .$i -row $i -column $i + } + set a +} {{0 0} {1 1} {1 1}} +grid_reset 6.9 + +test grid-7.1 {propagate} { + list [catch {grid propagate . 1 xxx} msg] $msg +} {1 {wrong # args: should be "grid propagate window ?boolean?"}} +grid_reset 7.1 + +test grid-7.2 {propagate} { + list [catch {grid propagate .} msg] $msg +} {0 1} +grid_reset 7.2 + +test grid-7.3 {propagate} { + list [catch {grid propagate . 0;grid propagate .} msg] $msg +} {0 0} +grid_reset 7.3 + +test grid-7.4 {propagate} { + list [catch {grid propagate .x} msg] $msg +} {1 {bad window path name ".x"}} +grid_reset 7.4 + +test grid-7.5 {propagate} { + list [catch {grid propagate . x} msg] $msg +} {1 {expected boolean value but got "x"}} +grid_reset 7.5 + +test grid-7.6 {propagate} { + frame .f -width 100 -height 100 -bg red + grid .f -row 0 -column 0 + update + set a [winfo width .f]x[winfo height .f] + grid propagate .f 0 + frame .g -width 75 -height 85 -bg green + grid .g -in .f -row 0 -column 0 + update + lappend a [winfo width .f]x[winfo height .f] + grid propagate .f 1 + update + lappend a [winfo width .f]x[winfo height .f] + set a +} {100x100 100x100 75x85} +grid_reset 7.6 + + +test grid-8.1 {size} { + list [catch {grid size . foo} msg] $msg +} {1 {wrong # args: should be "grid size window"}} +grid_reset 8.1 + +test grid-8.2 {size} { + list [catch {grid size .x} msg] $msg +} {1 {bad window path name ".x"}} +grid_reset 8.2 + +test grid-8.3 {size} { + frame .f + list [catch {grid size .f} msg] $msg +} {0 {0 0}} +grid_reset 8.3 + +test grid-8.4 {size} { + catch {unset a} + scale .f + grid .f -row 0 -column 0 + update + lappend a [grid size .] + grid .f -row 4 -column 5 + update + lappend a [grid size .] + grid .f -row 947 -column 663 + update + lappend a [grid size .] + grid .f -row 0 -column 0 + update + lappend a [grid size .] + set a +} {{1 1} {6 5} {664 948} {1 1}} +grid_reset 8.4 + +test grid-8.5 {size} { + catch {unset a} + scale .f + grid .f -row 0 -column 0 + update + lappend a [grid size .] + grid rowconfigure . 17 -weight 1 + update + lappend a [grid size .] + grid columnconfigure . 63 -weight 1 + update + lappend a [grid size .] + grid columnconfigure . 63 -weight 0 + grid rowconfigure . 17 -weight 0 + update + lappend a [grid size .] + set a +} {{1 1} {1 18} {64 18} {1 1}} +grid_reset 8.5 + +test grid-8.6 {size} { + catch {unset a} + scale .f + grid .f -row 10 -column 50 + update + lappend a [grid size .] + grid columnconfigure . 15 -weight 1 + grid columnconfigure . 30 -weight 1 + update + lappend a [grid size .] + grid .f -row 10 -column 20 + update + lappend a [grid size .] + grid columnconfigure . 30 -weight 0 + update + lappend a [grid size .] + grid .f -row 0 -column 0 + update + lappend a [grid size .] + grid columnconfigure . 15 -weight 0 + update + lappend a [grid size .] + set a +} {{51 11} {51 11} {31 11} {21 11} {16 1} {1 1}} +grid_reset 8.6 + +test grid-9.1 {slaves} { + list [catch {grid slaves .} msg] $msg +} {0 {}} + +test grid-9.2 {slaves} { + list [catch {grid slaves .foo} msg] $msg +} {1 {bad window path name ".foo"}} + +test grid-9.3 {slaves} { + list [catch {grid slaves a b} msg] $msg +} {1 {wrong # args: should be "grid slaves window ?-option value...?"}} + +test grid-9.4 {slaves} { + list [catch {grid slaves . a b} msg] $msg +} {1 {invalid args: should be "grid slaves window ?-option value...?"}} + +test grid-9.5 {slaves} { + list [catch {grid slaves . -foo x} msg] $msg +} {1 {expected integer but got "x"}} + +test grid-9.6 {slaves} { + list [catch {grid slaves . -foo -3} msg] $msg +} {1 {-foo is an invalid value: should NOT be < 0}} + +test grid-9.7 {slaves} { + list [catch {grid slaves . -foo 3} msg] $msg +} {1 {-foo is an invalid option: should be "-row, -column"}} + +test grid-9.8 {slaves} { + list [catch {grid slaves .x -row 3} msg] $msg +} {1 {bad window path name ".x"}} + +test grid-9.9 {slaves} { + list [catch {grid slaves . -row 3} msg] $msg +} {0 {}} + +test grid-9.10 {slaves} { + foreach i {0 1 2} { + label .$i -text $i + grid .$i -row $i -column $i + } + list [catch {grid slaves .} msg] $msg +} {0 {.2 .1 .0}} +grid_reset 9.10 + +test grid-9.11 {slaves} { + catch {unset a} + foreach i {0 1 2} { + label .$i -text $i + label .$i-x -text $i-x + grid .$i -row $i -column $i + grid .$i-x -row $i -column [incr i] + } + foreach row {0 1 2 3} { + lappend a $row{[grid slaves . -row $row]} + } + foreach col {0 1 2 3} { + lappend a $col{[grid slaves . -column $col]} + } + set a +} {{0{.0-x .0}} {1{.1-x .1}} {2{.2-x .2}} 3{} 0{.0} {1{.1 .0-x}} {2{.2 .1-x}} 3{.2-x}} +grid_reset 9.11 + +# column/row configure + +test grid-10.1 {column/row configure} { + list [catch {grid columnconfigure .} msg] $msg +} {1 {wrong # args: should be "grid columnconfigure master index ?-option value...?"}} +grid_reset 10.1 + +test grid-10.2 {column/row configure} { + list [catch {grid columnconfigure . 0 -weight 0 -pad} msg] $msg +} {1 {wrong # args: should be "grid columnconfigure master index ?-option value...?"}} +grid_reset 10.2 + +test grid-10.3 {column/row configure} { + list [catch {grid columnconfigure .f 0 -weight} msg] $msg +} {1 {bad window path name ".f"}} +grid_reset 10.3 + +test grid-10.4 {column/row configure} { + list [catch {grid columnconfigure . nine -weight} msg] $msg +} {1 {expected integer but got "nine"}} +grid_reset 10.4 + +test grid-10.5 {column/row configure} { + list [catch {grid columnconfigure . 265 -weight} msg] $msg +} {0 0} +grid_reset 10.5 + +test grid-10.6 {column/row configure} { + list [catch {grid columnconfigure . 0} msg] $msg +} {0 {-minsize 0 -pad 0 -weight 0}} +grid_reset 10.6 + +test grid-10.7 {column/row configure} { + list [catch {grid columnconfigure . 0 -foo} msg] $msg +} {1 {invalid arg "-foo": expecting -minsize, -pad, or -weight.}} +grid_reset 10.7 + +test grid-10.8 {column/row configure} { + list [catch {grid columnconfigure . 0 -minsize foo} msg] $msg +} {1 {bad screen distance "foo"}} +grid_reset 10.8 + +test grid-10.9 {column/row configure} { + list [catch {grid columnconfigure . 0 -minsize foo} msg] $msg +} {1 {bad screen distance "foo"}} +grid_reset 10.9 + +test grid-10.10 {column/row configure} { + grid columnconfigure . 0 -minsize 10 + grid columnconfigure . 0 -minsize +} {10} +grid_reset 10.10 + +test grid-10.11 {column/row configure} { + list [catch {grid columnconfigure . 0 -weight bad} msg] $msg +} {1 {expected integer but got "bad"}} +grid_reset 10.10a + +test grid-10.12 {column/row configure} { + list [catch {grid columnconfigure . 0 -weight -3} msg] $msg +} {1 {invalid arg "-weight": should be non-negative}} +grid_reset 10.11 + +test grid-10.13 {column/row configure} { + grid columnconfigure . 0 -weight 3 + grid columnconfigure . 0 -weight +} {3} +grid_reset 10.12 + +test grid-10.14 {column/row configure} { + list [catch {grid columnconfigure . 0 -pad foo} msg] $msg +} {1 {bad screen distance "foo"}} +grid_reset 10.13 + +test grid-10.15 {column/row configure} { + list [catch {grid columnconfigure . 0 -pad -3} msg] $msg +} {1 {invalid arg "-pad": should be non-negative}} +grid_reset 10.14 + +test grid-10.16 {column/row configure} { + grid columnconfigure . 0 -pad 3 + grid columnconfigure . 0 -pad +} {3} +grid_reset 10.15 + +test grid-10.17 {column/row configure} { + frame .f + set a "" + grid columnconfigure .f 0 -weight 0 + lappend a [grid columnconfigure .f 0 -weight] + grid columnconfigure .f 0 -weight 1 + lappend a [grid columnconfigure .f 0 -weight] + grid rowconfigure .f 0 -weight 0 + lappend a [grid rowconfigure .f 0 -weight] + grid rowconfigure .f 0 -weight 1 + lappend a [grid columnconfigure .f 0 -weight] + grid columnconfigure .f 0 -weight 0 + set a +} {0 1 0 1} +grid_reset 10.16 + +test grid-10.18 {column/row configure} { + frame .f + grid columnconfigure .f 0 -minsize 10 -weight 1 + list [grid columnconfigure .f 0 -minsize] \ + [grid columnconfigure .f 1 -minsize] \ + [grid columnconfigure .f 0 -weight] \ + [grid columnconfigure .f 1 -weight] +} {10 0 1 0} +grid_reset 10.17 + +# auto-placement tests + +test grid-11.1 {default widget placement} { + list [catch {grid ^} msg] $msg +} {1 {can't use '^', cant find master}} +grid_reset 11.1 + +test grid-11.2 {default widget placement} { + button .b + list [catch {grid .b ^} msg] $msg +} {1 {can't find slave to extend with "^".}} +grid_reset 11.2 + +test grid-11.3 {default widget placement} { + button .b + list [catch {grid .b - - .c} msg] $msg +} {1 {bad window path name ".c"}} +grid_reset 11.3 + +test grid-11.4 {default widget placement} { + button .b + list [catch {grid .b - - = -} msg] $msg +} {1 {invalid window shortcut, "=" should be '-', 'x', or '^'}} +grid_reset 11.4 + +test grid-11.5 {default widget placement} { + button .b + list [catch {grid .b - x -} msg] $msg +} {1 {Must specify window before shortcut '-'.}} +grid_reset 11.5 + +test grid-11.6 {default widget placement} { + foreach i {1 2 3 4 5 6} { + frame .f$i -width 50 -height 50 -highlightthickness 0 -bg red + } + grid .f1 .f2 .f3 .f4 + grid .f5 - x .f6 -sticky nsew + update + set a "" + foreach i {5 6} { + lappend a "[winfo x .f$i],[winfo y .f$i] \ + [winfo width .f$i],[winfo height .f$i]" + } + set a +} {{0,50 100,50} {150,50 50,50}} +grid_reset 11.6 + +test grid-11.7 {default widget placement} { + frame .f -width 20 -height 20 -highlightthickness 0 -bg red + grid .f -row 5 -column 5 + list [catch "grid .f x -" msg] $msg +} {1 {Must specify window before shortcut '-'.}} +grid_reset 11.7 + +test grid-11.8 {default widget placement} { + frame .f -width 20 -height 20 -highlightthickness 0 -bg red + grid .f -row 5 -column 5 + list [catch "grid .f ^ -" msg] $msg +} {1 {Must specify window before shortcut '-'.}} +grid_reset 11.8 + +test grid-11.9 {default widget placement} { + frame .f -width 20 -height 20 -highlightthickness 0 -bg red + grid .f -row 5 -column 5 + list [catch "grid .f x ^" msg] $msg +} {1 {can't find slave to extend with "^".}} +grid_reset 11.9 + +test grid-11.10 {default widget placement} { + foreach i {1 2 3} { + frame .f$i -width 100 -height 50 -highlightthickness 0 -bg red + } + grid .f1 .f2 -sticky nsew + grid .f3 ^ -sticky nsew + update + set a "" + foreach i {1 2 3} { + lappend a "[winfo x .f$i],[winfo y .f$i] \ + [winfo width .f$i],[winfo height .f$i]" + } + set a +} {{0,0 100,50} {100,0 100,100} {0,50 100,50}} +grid_reset 11.10 + +test grid-11.11 {default widget placement} { + foreach i {1 2 3 4 5 6 7 8 9 10 11 12} { + frame .f$i -width 50 -height 50 -highlightthickness 1 -highlightbackground black + } + grid .f1 .f2 .f3 .f4 -sticky nsew + grid .f5 .f6 - .f7 -sticky nsew + grid .f8 ^ ^ .f9 -sticky nsew + grid .f10 ^ ^ .f11 -sticky nsew + grid .f12 - - - -sticky nsew + update + set a "" + foreach i {5 6 7 8 9 10 11 12 } { + lappend a "[winfo x .f$i],[winfo y .f$i] \ + [winfo width .f$i],[winfo height .f$i]" + } + set a +} {{0,50 50,50} {50,50 100,150} {150,50 50,50} {0,100 50,50} {150,100 50,50} {0,150 50,50} {150,150 50,50} {0,200 200,50}} +grid_reset 11.11 + +test grid-11.12 {default widget placement} { + foreach i {1 2 3 4} { + frame .f$i -width 75 -height 50 -highlightthickness 1 -highlightbackground black + } + grid .f1 .f2 .f3 -sticky nsew + grid .f4 ^ -sticky nsew + update + set a "" + foreach i {1 2 3 4} { + lappend a "[winfo x .f$i],[winfo y .f$i] \ + [winfo width .f$i],[winfo height .f$i]" + } + grid .f4 ^ -column 1 + update + foreach i {1 2 3 4} { + lappend a "[winfo x .f$i],[winfo y .f$i] \ + [winfo width .f$i],[winfo height .f$i]" + } + set a +} {{0,0 75,50} {75,0 75,100} {150,0 75,50} {0,50 75,50} {0,0 75,50} {75,0 75,100} {150,0 75,100} {75,50 75,50}} +grid_reset 11.12 + +test grid-11.13 {default widget placement} { + foreach i {1 2 3 4 5 6 7} { + frame .f$i -width 40 -height 50 -highlightthickness 1 -highlightbackground black + } + grid .f1 .f2 .f3 .f4 .f5 -sticky nsew + grid .f6 - .f7 -sticky nsew -columnspan 2 + update + set a "" + foreach i {6 7} { + lappend a "[winfo x .f$i],[winfo y .f$i] \ + [winfo width .f$i],[winfo height .f$i]" + } + set a +} {{0,50 120,50} {120,50 80,50}} +grid_reset 11.13 + +test grid-11.14 {default widget placement} { + foreach i {1 2 3} { + frame .f$i -width 50 -height 50 -highlightthickness 0 -bg red + } + grid .f1 .f2 + grid ^ .f3 + update + set a "" + foreach i {1 2 3} { + lappend a "[winfo x .f$i],[winfo y .f$i] \ + [winfo width .f$i],[winfo height .f$i]" + } + set a +} {{0,25 50,50} {50,0 50,50} {50,50 50,50}} +grid_reset 11.14 + +test grid-12.1 {-sticky} { + catch {unset data} + frame .f -width 200 -height 100 -highlightthickness 0 -bg red + set a "" + grid .f + grid rowconfigure . 0 -weight 1 + grid columnconfigure . 0 -weight 1 + grid propagate . 0 + . configure -width 250 -height 150 + foreach i { {} n s e w ns ew nw ne se sw nse nsw sew new nsew} { + grid .f -sticky $i + update + array set data [grid info .f] + append a "($data(-sticky)) [winfo x .f] [winfo y .f] [winfo width .f] [winfo height .f]\n" + } + set a +} {() 25 25 200 100 +(n) 25 0 200 100 +(s) 25 50 200 100 +(e) 50 25 200 100 +(w) 0 25 200 100 +(ns) 25 0 200 150 +(ew) 0 25 250 100 +(nw) 0 0 200 100 +(ne) 50 0 200 100 +(es) 50 50 200 100 +(sw) 0 50 200 100 +(nes) 50 0 200 150 +(nsw) 0 0 200 150 +(esw) 0 50 250 100 +(new) 0 0 250 100 +(nesw) 0 0 250 150 +} +grid_reset 12.1 + +test grid-12.2 {-sticky} { + frame .f -bg red + list [catch "grid .f -sticky glue" msg] $msg +} {1 {bad stickyness value "glue": must be a string containing n, e, s, and/or w}} +grid_reset 12.2 + +test grid-12.3 {-sticky} { + frame .f -bg red + grid .f -sticky {n,s,e,w} + array set A [grid info .f] + set A(-sticky) +} {nesw} +grid_reset 12.3 + +test grid-13.1 {-in} { + frame .f -bg red + list [catch "grid .f -in .f" msg] $msg +} {1 {Window can't be managed in itself}} +grid_reset 13.1 + +test grid-13.2 {-in} { + frame .f -bg red + list [catch "grid .f -in .bad" msg] $msg +} {1 {bad window path name ".bad"}} +grid_reset 13.2 + +test grid-13.3 {-in} { + frame .f -bg red + toplevel .top + list [catch "grid .f -in .top" msg] $msg +} {1 {can't put .f inside .top}} +destroy .top +grid_reset 13.3 + +test grid-13.4 {-ipadx} { + frame .f -width 20 -height 20 -highlightthickness 0 -bg red + list [catch "grid .f -ipadx x" msg] $msg +} {1 {bad ipadx value "x": must be positive screen distance}} +grid_reset 13.4 + +test grid-13.5 {-ipadx} { + frame .f -width 200 -height 100 -highlightthickness 0 -bg red + grid .f + update + set a [winfo width .f] + grid .f -ipadx 1 + update + list $a [winfo width .f] +} {200 202} +grid_reset 13.5 + +test grid-13.6 {-ipady} { + frame .f -width 20 -height 20 -highlightthickness 0 -bg red + list [catch "grid .f -ipady x" msg] $msg +} {1 {bad ipady value "x": must be positive screen distance}} +grid_reset 13.6 + +test grid-13.7 {-ipady} { + frame .f -width 200 -height 100 -highlightthickness 0 -bg red + grid .f + update + set a [winfo height .f] + grid .f -ipady 1 + update + list $a [winfo height .f] +} {100 102} +grid_reset 13.7 + +test grid-13.8 {-padx} { + frame .f -width 20 -height 20 -highlightthickness 0 -bg red + list [catch "grid .f -padx x" msg] $msg +} {1 {bad padx value "x": must be positive screen distance}} +grid_reset 13.8 + +test grid-13.9 {-padx} { + frame .f -width 200 -height 100 -highlightthickness 0 -bg red + grid .f + update + set a "[winfo width .f] [winfo width .]" + grid .f -padx 1 + update + list $a "[winfo width .f] [winfo width .]" +} {{200 200} {200 202}} +grid_reset 13.9 + +test grid-13.10 {-pady} { + frame .f -width 20 -height 20 -highlightthickness 0 -bg red + list [catch "grid .f -pady x" msg] $msg +} {1 {bad pady value "x": must be positive screen distance}} +grid_reset 13.10 + +test grid-13.11 {-pady} { + frame .f -width 200 -height 100 -highlightthickness 0 -bg red + grid .f + update + set a "[winfo height .f] [winfo height .]" + grid .f -pady 1 + update + list $a "[winfo height .f] [winfo height .]" +} {{100 100} {100 102}} +grid_reset 13.11 + +test grid-13.12 {-ipad x and y} { + frame .f -width 20 -height 20 -highlightthickness 0 -bg red + grid columnconfigure . 0 -minsize 150 + grid rowconfigure . 0 -minsize 100 + set a "" + foreach x {0 5} { + foreach y {0 5} { + grid .f -ipadx $x -ipady $y + update + append a " $x,$y:" + foreach prop {x y width height} { + append a ,[winfo $prop .f] + } + } + } + set a +} { 0,0:,65,40,20,20 0,5:,65,35,20,30 5,0:,60,40,30,20 5,5:,60,35,30,30} +grid_reset 13.12 + +test grid-13.13 {reparenting} { + frame .1 + frame .2 + button .b + grid .1 .2 + grid .b -in .1 + set a "" + catch {unset info}; array set info [grid info .b] + lappend a [grid slaves .1],[grid slaves .2],$info(-in) + grid .b -in .2 + catch {unset info}; array set info [grid info .b] + lappend a [grid slaves .1],[grid slaves .2],$info(-in) + unset info + set a +} {.b,,.1 ,.b,.2} +grid_reset 13.13 + +test grid-14.1 {structure notify} { + frame .f -width 200 -height 100 -highlightthickness 0 -bg red + frame .g -width 200 -height 100 -highlightthickness 0 -bg red + grid .f + grid .g -in .f + update + set a "" + lappend a "[winfo x .g],[winfo y .g] \ + [winfo width .g],[winfo height .g]" + .f configure -bd 5 -relief raised + update + lappend a "[winfo x .g],[winfo y .g] \ + [winfo width .g],[winfo height .g]" + set a +} {{0,0 200,100} {5,5 200,100}} +grid_reset 14.1 + +test grid-14.2 {structure notify} { + frame .f -width 200 -height 100 + frame .f.g -width 200 -height 100 + grid .f + grid .f.g + update + set a "" + lappend a [grid bbox .],[grid bbox .f] + .f config -bd 20 + update + lappend a [grid bbox .],[grid bbox .f] +} {{0 0 200 100,0 0 200 100} {0 0 240 140,20 20 200 100}} +grid_reset 14.2 + +test grid-14.3 {map notify} { + global A + catch {unset A} + bind . <Configure> {incr A(%W)} + set A(.) 0 + foreach i {0 1 2} { + frame .$i -width 100 -height 75 + set A(.$i) 0 + } + grid .0 .1 .2 + update + bind <Configure> .1 {destroy .0} + .2 configure -bd 10 + update + bind . <Configure> {} + array get A +} {.2 2 .0 1 . 1 .1 1} +grid_reset 14.3 + +test grid-15.1 {lost slave} { + button .b + grid .b + set a [grid slaves .] + pack .b + lappend a [grid slaves .] + grid .b + lappend a [grid slaves .] +} {.b {} .b} +grid_reset 15.1 + +test grid-15.2 {lost slave} { + frame .f + grid .f + button .b + grid .b -in .f + set a [grid slaves .f] + pack .b + lappend a [grid slaves .f] + grid .b -in .f + lappend a [grid slaves .f] +} {.b {} .b} +grid_reset 15.2 + +test grid-16.1 {layout centering} { + foreach i {0 1 2} { + frame .$i -bg gray -width 75 -height 50 -bd 2 -relief ridge + grid .$i -row $i -column $i -sticky nswe + } + grid propagate . 0 + . configure -width 300 -height 250 + update + grid bbox . +} {37 50 225 150} +grid_reset 16.1 + +test grid-16.2 {layout weights (expanding)} { + foreach i {0 1 2} { + frame .$i -bg gray -width 75 -height 50 -bd 2 -relief ridge + grid .$i -row $i -column $i -sticky nswe + grid rowconfigure . $i -weight [expr $i + 1] + grid columnconfigure . $i -weight [expr $i + 1] + } + grid propagate . 0 + . configure -width 500 -height 300 + set a "" + update + foreach i {0 1 2} { + lappend a [winfo width .$i]-[winfo height .$i] + } + set a +} {120-75 167-100 213-125} +grid_reset 16.2 + +test grid-16.3 {layout weights (shrinking)} { + foreach i {0 1 2} { + frame .$i -bg gray -width 100 -height 75 -bd 2 -relief ridge + grid .$i -row $i -column $i -sticky nswe + grid rowconfigure . $i -weight [expr $i + 1] + grid columnconfigure . $i -weight [expr $i + 1] + } + grid propagate . 0 + . configure -width 200 -height 150 + set a "" + update + foreach i {0 1 2} { + lappend a [winfo width .$i]-[winfo height .$i] + } + set a +} {84-63 66-50 50-37} +grid_reset 16.3 + +test grid-16.4 {layout weights (shrinking with minsize)} { + foreach i {0 1 2} { + frame .$i -bg gray -width 100 -height 75 -bd 2 -relief ridge + grid .$i -row $i -column $i -sticky nswe + grid rowconfigure . $i -weight [expr $i + 1] -minsize 45 + grid columnconfigure . $i -weight [expr $i + 1] -minsize 65 + } + grid propagate . 0 + . configure -width 200 -height 150 + set a "" + update + foreach i {0 1 2} { + lappend a [winfo width .$i]-[winfo height .$i] + } + set a +} {70-60 65-45 65-45} +grid_reset 16.4 + +test grid-16.5 {layout weights (shrinking at minsize)} { + foreach i {0 1 2} { + frame .$i -bg gray -width 100 -height 75 -bd 2 -relief ridge + grid .$i -row $i -column $i -sticky nswe + grid rowconfigure . $i -weight 0 -minsize 70 + grid columnconfigure . $i -weight 0 -minsize 90 + } + grid propagate . 0 + . configure -width 100 -height 75 + set a "" + update + foreach i {0 1 2} { + lappend a [winfo width .$i]-[winfo height .$i] + } + set a +} {100-75 100-75 100-75} +grid_reset 16.5 + + +test grid-16.6 {layout weights (shrinking at minsize)} { + foreach i {0 1 2} { + frame .$i -bg gray -width 100 -height 75 -bd 2 -relief ridge + grid .$i -row $i -column $i -sticky nswe + grid rowconfigure . $i -weight [expr $i + 1] -minsize 52 + grid columnconfigure . $i -weight [expr $i + 1] -minsize 69 + } + grid propagate . 0 + . configure -width 200 -height 150 + set a "" + update + foreach i {0 1 2} { + lappend a [winfo width .$i]-[winfo height .$i] + } + set a +} {69-52 69-52 69-52} +grid_reset 16.6 + +test grid-16.7 {layout weights (shrinking at minsize)} { + foreach i {0 1 2} { + frame .$i -bg gray -width 100 -height 75 -bd 2 -relief ridge + grid .$i -row $i -column $i -sticky nswe + } + grid propagate . 0 + grid columnconfigure . 1 -weight 1 -minsize 0 + grid rowconfigure . 1 -weight 1 -minsize 0 + . configure -width 100 -height 75 + set a "" + update + foreach i {0 1 2} { + lappend a [winfo width .$i]-[winfo height .$i]-[winfo ismapped .$i] + } + set a +} {100-75-1 1-1-0 200-150-1} +grid_reset 16.7 + +test grid-16.8 {layout internal constraints} { + foreach i {0 1 2 3 4} { + frame .$i -bg gray -width 30 -height 25 -bd 2 -relief ridge + grid .$i -row $i -column $i -sticky nswe + } + frame .f -bg red -width 250 -height 200 + frame .g -bg green -width 200 -height 180 + lower .f + raise .g .f + grid .f -row 1 -column 1 -rowspan 3 -columnspan 3 -sticky nswe + grid .g -row 1 -column 1 -rowspan 2 -columnspan 2 -sticky nswe + update + set a "" + foreach i {0 1 2 3 4} { + append a "[winfo x .$i] " + } + append a ", " + grid remove .f + update + foreach i {0 1 2 3 4} { + append a "[winfo x .$i] " + } + append a ", " + grid remove .g + grid .f + update + foreach i {0 1 2 3 4} { + append a "[winfo x .$i] " + } + append a ", " + grid remove .f + update + foreach i {0 1 2 3 4} { + append a "[winfo x .$i] " + } + set a +} {0 30 70 250 280 , 0 30 130 230 260 , 0 30 113 197 280 , 0 30 60 90 120 } diff --git a/tests/id.test b/tests/id.test new file mode 100644 index 0000000..2589d48 --- /dev/null +++ b/tests/id.test @@ -0,0 +1,96 @@ +# This file is a Tcl script to test out the procedures in the file +# tkId.c, which recycle X resource identifiers. It is organized in +# the standard fashion for Tcl tests. +# +# Copyright (c) 1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) id.test 1.7 97/05/15 09:47:10 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +test id-1.1 {WindowIdCleanup, delaying window release} {unixOnly} { + bind all <Destroy> {lappend x %W} + catch {unset map} + frame .f + set j 0 + foreach i {a b c d e f g h i j k l m n o p q} { + toplevel .f.$i -height 50 -width 100 + wm geometry .f.$i +$j+$j + incr j 10 + update + set map([winfo id .f.$i]) .f.$i + set map([testwrapper .f.$i]) wrapper.f.$i + } + set x {} + destroy .f + + # Destroy events should have occurred for all windows. + set result [list [lsort $x]] + + set x {} + update idletasks + set reused {} + foreach i {a b c d e} { + set w .${i}2 + frame $w -height 20 -width 100 -bd 2 -relief raised + pack $w + if [info exists map([winfo id $w])] { + lappend reused $map([winfo id $w]) + } + set map([winfo id $w]) $w + } + + # No window ids should have been reused: stale Destroy events still + # pending in queue. + lappend result [lsort $reused] + + # Wait a few seconds, then try again; ids should still not have + # been re-used. + + set y 0 + after 2000 {set y 1} + tkwait variable y + foreach i {a b c} { + set w .${i}3 + frame $w -height 20 -width 100 -bd 2 -relief raised + pack $w + if [info exists map([winfo id $w])] { + lappend reused $map([winfo id $w]) + } + set map([winfo id $w])] $w + } + + # Ids should not yet have been reused. + lappend result [lsort $reused] + + + # Wait a few more seconds, to give ids enough time to be recycled. + set y 0 + after 6000 {set y 1} + tkwait variable y + foreach i {a b c d e f} { + set w .${i}4 + frame $w -height 20 -width 100 -bd 2 -relief raised + pack $w + if [info exists map([winfo id $w])] { + lappend reused $map([winfo id $w]) + } + set map([winfo id $w])] $w + } + + # Ids should be reused now, due to time delay. Destroy events should + # have been discarded. + lappend result [lsort $reused] [lsort $x] +} {{.f .f.a .f.b .f.c .f.d .f.e .f.f .f.g .f.h .f.i .f.j .f.k .f.l .f.m .f.n .f.o .f.p .f.q} {} {} {.f.o .f.p .f.q wrapper.f.p wrapper.f.q} {}} +bind all <Destroy> {} diff --git a/tests/image.test b/tests/image.test new file mode 100644 index 0000000..b4e7ad7 --- /dev/null +++ b/tests/image.test @@ -0,0 +1,357 @@ +# This file is a Tcl script to test out the "image" command and the +# other procedures in the file tkImage.c. It is organized in the +# standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) image.test 1.15 97/07/31 10:17:25 + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\" image" + puts "type, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +eval image delete [image names] +canvas .c -highlightthickness 2 +pack .c +update +test image-1.1 {Tk_ImageCmd procedure, "create" option} { + list [catch image msg] $msg +} {1 {wrong # args: should be "image option ?args?"}} +test image-1.2 {Tk_ImageCmd procedure, "create" option} { + list [catch {image gorp} msg] $msg +} {1 {bad option "gorp": must be create, delete, height, names, type, types, or width}} +test image-1.3 {Tk_ImageCmd procedure, "create" option} { + list [catch {image create} msg] $msg +} {1 {wrong # args: should be "image create type ?name? ?options?"}} +test image-1.4 {Tk_ImageCmd procedure, "create" option} { + list [catch {image c bad_type} msg] $msg +} {1 {image type "bad_type" doesn't exist}} +test image-1.5 {Tk_ImageCmd procedure, "create" option} { + list [image create test myimage] [image names] +} {myimage myimage} +test image-1.6 {Tk_ImageCmd procedure, "create" option} { + scan [image create test] image%d first + image create test myimage + scan [image create test -variable x] image%d second + expr $second-$first +} {1} +test image-1.7 {Tk_ImageCmd procedure, "create" option} { + image delete myimage + image create test myimage -variable x + .c create image 100 50 -image myimage + .c create image 100 150 -image myimage + update + set x {} + image create test myimage -variable x + update + set x +} {{myimage free} {myimage free} {myimage delete} {myimage get} {myimage get} {myimage display 0 0 30 15 30 30} {myimage display 0 0 30 15 30 130}} +test image-1.8 {Tk_ImageCmd procedure, "create" option} { + .c delete all + image create test myimage -variable x + .c create image 100 50 -image myimage + .c create image 100 150 -image myimage + image delete myimage + update + set x {} + image create test myimage -variable x + update + set x +} {{myimage get} {myimage get} {myimage display 0 0 30 15 30 30} {myimage display 0 0 30 15 30 130}} +test image-1.9 {Tk_ImageCmd procedure, "create" option} { + .c delete all + eval image delete [image names] + list [catch {image create test -badName foo} msg] $msg [image names] +} {1 {bad option name "-badName"} {}} + +test image-2.1 {Tk_ImageCmd procedure, "delete" option} { + list [catch {image delete} msg] $msg +} {0 {}} +test image-2.2 {Tk_ImageCmd procedure, "delete" option} { + .c delete all + eval image delete [image names] + image create test myimage + image create test img2 + set result {} + lappend result [lsort [image names]] + image d myimage img2 + lappend result [image names] +} {{img2 myimage} {}} +test image-2.3 {Tk_ImageCmd procedure, "delete" option} { + .c delete all + eval image delete [image names] + image create test myimage + image create test img2 + list [catch {image delete myimage gorp img2} msg] $msg [image names] +} {1 {image "gorp" doesn't exist} img2} + +test image-3.1 {Tk_ImageCmd procedure, "height" option} { + list [catch {image height} msg] $msg +} {1 {wrong # args: should be "image height name"}} +test image-3.2 {Tk_ImageCmd procedure, "height" option} { + list [catch {image height a b} msg] $msg +} {1 {wrong # args: should be "image height name"}} +test image-3.3 {Tk_ImageCmd procedure, "height" option} { + list [catch {image height foo} msg] $msg +} {1 {image "foo" doesn't exist}} +test image-3.4 {Tk_ImageCmd procedure, "height" option} { + image create test myimage + set x [image h myimage] + myimage changed 0 0 0 0 60 50 + list $x [image height myimage] +} {15 50} + +test image-4.1 {Tk_ImageCmd procedure, "names" option} { + list [catch {image names x} msg] $msg +} {1 {wrong # args: should be "image names"}} +test image-4.2 {Tk_ImageCmd procedure, "names" option} { + .c delete all + eval image delete [image names] + image create test myimage + image create test img2 + image create test 24613 + lsort [image names] +} {24613 img2 myimage} +test image-4.3 {Tk_ImageCmd procedure, "names" option} { + .c delete all + eval image delete [image names] + lsort [image names] +} {} + +test image-5.1 {Tk_ImageCmd procedure, "type" option} { + list [catch {image type} msg] $msg +} {1 {wrong # args: should be "image type name"}} +test image-5.2 {Tk_ImageCmd procedure, "type" option} { + list [catch {image type a b} msg] $msg +} {1 {wrong # args: should be "image type name"}} +test image-5.3 {Tk_ImageCmd procedure, "type" option} { + list [catch {image type foo} msg] $msg +} {1 {image "foo" doesn't exist}} +test image-5.4 {Tk_ImageCmd procedure, "type" option} { + image create test myimage + image type myimage +} {test} +test image-5.5 {Tk_ImageCmd procedure, "type" option} { + image create test myimage + .c create image 50 50 -image myimage + image delete myimage + image type myimage +} {} + +test image-6.1 {Tk_ImageCmd procedure, "types" option} { + list [catch {image types x} msg] $msg +} {1 {wrong # args: should be "image types"}} +test image-6.2 {Tk_ImageCmd procedure, "types" option} { + lsort [image types] +} {bitmap photo test} + +test image-7.1 {Tk_ImageCmd procedure, "width" option} { + list [catch {image width} msg] $msg +} {1 {wrong # args: should be "image width name"}} +test image-7.2 {Tk_ImageCmd procedure, "width" option} { + list [catch {image width a b} msg] $msg +} {1 {wrong # args: should be "image width name"}} +test image-7.3 {Tk_ImageCmd procedure, "width" option} { + list [catch {image width foo} msg] $msg +} {1 {image "foo" doesn't exist}} +test image-7.4 {Tk_ImageCmd procedure, "width" option} { + image create test myimage + set x [image w myimage] + myimage changed 0 0 0 0 60 50 + list $x [image width myimage] +} {30 60} + +test image-8.1 {Tk_ImageChanged procedure} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 50 -image foo + update + set x {} + foo changed 5 6 7 8 30 15 + update + set x +} {{foo display 5 6 7 8 30 30}} +test image-8.2 {Tk_ImageChanged procedure} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 50 -image foo + .c create image 90 100 -image foo + update + set x {} + foo changed 5 6 7 8 30 15 + update + set x +} {{foo display 5 6 25 9 30 30} {foo display 0 0 12 14 65 74}} + +test image-9.1 {Tk_GetImage procedure} { + list [catch {.c create image 100 10 -image bad_name} msg] $msg +} {1 {image "bad_name" doesn't exist}} +test image-9.2 {Tk_GetImage procedure} { + image create test mytest + catch {destroy .l} + label .l -image mytest + image delete mytest + set result [list [catch {label .l2 -image mytest} msg] $msg] + destroy .l + set result +} {1 {image "mytest" doesn't exist}} + +test image-10.1 {Tk_FreeImage procedure} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 50 -image foo -tags i1 + .c create image 90 100 -image foo -tags i2 + pack forget .c + update + set x {} + .c delete i1 + pack .c + update + list [image names] $x +} {foo {{foo free} {foo display 0 0 30 15 103 121}}} +test image-10.2 {Tk_FreeImage procedure} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 50 -image foo -tags i1 + image delete foo + update + set names [image names] + set x {} + .c delete i1 + pack forget .c + pack .c + update + list $names [image names] $x +} {foo {} {}} + +# Non-portable, apparently due to differences in rounding: + +test image-11.1 {Tk_RedrawImage procedure, redisplay area clipping} \ + {nonPortable} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 60 -image foo -tags i1 -anchor nw + update + .c create rectangle 30 40 55 65 -width 0 -fill black -outline {} + set x {} + update + set x +} {{foo display 0 0 5 5 50 50}} +test image-11.2 {Tk_RedrawImage procedure, redisplay area clipping} \ + {nonPortable} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 60 -image foo -tags i1 -anchor nw + update + .c create rectangle 60 40 100 65 -width 0 -fill black -outline {} + set x {} + update + set x +} {{foo display 10 0 20 5 30 50}} +test image-11.3 {Tk_RedrawImage procedure, redisplay area clipping} \ + {nonPortable} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 60 -image foo -tags i1 -anchor nw + update + .c create rectangle 60 70 100 200 -width 0 -fill black -outline {} + set x {} + update + set x +} {{foo display 10 10 20 5 30 30}} +test image-11.4 {Tk_RedrawImage procedure, redisplay area clipping} \ + {nonPortable} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 60 -image foo -tags i1 -anchor nw + update + .c create rectangle 30 70 55 200 -width 0 -fill black -outline {} + set x {} + update + set x +} {{foo display 0 10 5 5 50 30}} +test image-11.5 {Tk_RedrawImage procedure, redisplay area clipping} \ + {nonPortable} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 60 -image foo -tags i1 -anchor nw + update + .c create rectangle 10 20 120 130 -width 0 -fill black -outline {} + set x {} + update + set x +} {{foo display 0 0 30 15 70 70}} +test image-11.6 {Tk_RedrawImage procedure, redisplay area clipping} \ + {nonPortable} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 60 -image foo -tags i1 -anchor nw + update + .c create rectangle 55 65 75 70 -width 0 -fill black -outline {} + set x {} + update + set x +} {{foo display 5 5 20 5 30 30}} + +test image-12.1 {Tk_SizeOfImage procedure} { + eval image delete [image names] + image create test foo -variable x + set result [list [image width foo] [image height foo]] + foo changed 0 0 0 0 85 60 + lappend result [image width foo] [image height foo] +} {30 15 85 60} + +test image-12.2 {DeleteImage procedure} { + .c delete all + eval image delete [image names] + image create test foo -variable x + .c create image 50 50 -image foo -tags i1 + .c create image 90 100 -image foo -tags i2 + set x {} + image delete foo + lappend x | [image names] | + image delete foo + lappend x | [image names] | +} {{foo free} {foo free} {foo delete} | foo | | foo |} + +catch {image delete hidden} +set l [image names] +set h [interp hidden] + +test image-13.1 {image command vs hidden commands} { + catch {image delete hidden} + image create photo hidden + interp hide {} hidden + image delete hidden + list [image names] [interp hidden] +} [list $l $h] + +destroy .c +eval image delete [image names] diff --git a/tests/imgBmap.test b/tests/imgBmap.test new file mode 100644 index 0000000..928f7a4 --- /dev/null +++ b/tests/imgBmap.test @@ -0,0 +1,474 @@ +# This file is a Tcl script to test out images of type "bitmap" (i.e., +# the procedures in the file tkImgBmap.c). It is organized in the +# standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) imgBmap.test 1.15 97/03/10 14:12:38 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +set data1 {#define foo_width 16 +#define foo_height 16 +#define foo_x_hot 3 +#define foo_y_hot 3 +static unsigned char foo_bits[] = { + 0xff, 0xff, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, + 0x81, 0x81, 0xff, 0xff, 0xff, 0xff, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, + 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xff, 0xff}; +} +set data2 { + #define foo2_width 16 + #define foo2_height 16 + static char foo2_bits[] = { + 0xff, 0xff, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0xff}; +} +makeFile $data1 foo.bm +makeFile $data2 foo2.bm + +eval image delete [image names] +canvas .c +pack .c +update +image create bitmap i1 +.c create image 200 100 -image i1 +update +proc bgerror msg { + global errMsg + set errMsg $msg +} +test imageBmap-1.1 {options for bitmap images} { + image create bitmap i1 -background #123456 + lindex [i1 configure -background] 4 +} {#123456} +test imageBmap-1.2 {options for bitmap images} { + set errMsg {} + image create bitmap i1 -background lousy + update + list $errMsg $errorInfo +} {{unknown color name "lousy"} {unknown color name "lousy" + (while configuring image "i1")}} +test imageBmap-1.3 {options for bitmap images} { + image create bitmap i1 -data $data1 + lindex [i1 configure -data] 4 +} $data1 +test imageBmap-1.4 {options for bitmap images} { + list [catch {image create bitmap i1 -data bogus} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-1.5 {options for bitmap images} { + image create bitmap i1 -file foo.bm + lindex [i1 configure -file] 4 +} foo.bm +test imageBmap-1.6 {options for bitmap images} { + list [catch {image create bitmap i1 -file bogus} msg] [string tolower $msg] +} {1 {couldn't read bitmap file "bogus": no such file or directory}} +test imageBmap-1.7 {options for bitmap images} { + image create bitmap i1 -foreground #00ff00 + lindex [i1 configure -foreground] 4 +} {#00ff00} +test imageBmap-1.8 {options for bitmap images} { + set errMsg {} + image create bitmap i1 -foreground bad_color + update + list $errMsg $errorInfo +} {{unknown color name "bad_color"} {unknown color name "bad_color" + (while configuring image "i1")}} +test imageBmap-1.9 {options for bitmap images} { + image create bitmap i1 -data $data1 -maskdata $data2 + lindex [i1 configure -maskdata] 4 +} $data2 +test imageBmap-1.10 {options for bitmap images} { + list [catch {image create bitmap i1 -data $data1 -maskdata bogus} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-1.11 {options for bitmap images} { + image create bitmap i1 -file foo.bm -maskfile foo2.bm + lindex [i1 configure -maskfile] 4 +} foo2.bm +test imageBmap-1.12 {options for bitmap images} { + list [catch {image create bitmap i1 -data $data1 -maskfile bogus} msg] \ + [string tolower $msg] +} {1 {couldn't read bitmap file "bogus": no such file or directory}} +rename bgerror {} + +test imageBmap-2.1 {ImgBmapCreate procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap -gorp dum} msg] $msg [image names] +} {1 {unknown option "-gorp"} {}} +test imageBmap-2.2 {ImgBmapCreate procedure} { + eval image delete [image names] + .c delete all + image create bitmap image1 + list [info commands image1] [image names] \ + [image width image1] [image height image1] \ + [lindex [image1 configure -foreground] 4] \ + [lindex [image1 configure -background] 4] +} {image1 image1 0 0 #000000 {}} + +test imageBmap-3.1 {ImgBmapConfigureMaster procedure, memory de-allocation} { + image create bitmap i1 -data $data1 + i1 configure -data $data1 +} {} +test imageBmap-3.2 {ImgBmapConfigureMaster procedure} { + image create bitmap i1 -data $data1 + list [catch {i1 configure -data bogus} msg] $msg [image width i1] \ + [image height i1] +} {1 {format error in bitmap data} 16 16} +test imageBmap-3.3 {ImgBmapConfigureMaster procedure, memory de-allocation} { + image create bitmap i1 -data $data1 -maskdata $data2 + i1 configure -maskdata $data2 +} {} +test imageBmap-3.4 {ImgBmapConfigureMaster procedure} { + image create bitmap i1 + list [catch {i1 configure -maskdata $data2} msg] $msg +} {1 {can't have mask without bitmap}} +test imageBmap-3.5 {ImgBmapConfigureMaster procedure} { + list [catch {image create bitmap i1 -data $data1 -maskdata { + #define foo_width 8 + #define foo_height 16 + static char foo_bits[] = { + 0xff, 0xff, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, + 0x81, 0x81, 0xff, 0xff, 0xff, 0xff, 0x81, 0x81}; + } + } msg] $msg +} {1 {bitmap and mask have different sizes}} +test imageBmap-3.6 {ImgBmapConfigureMaster procedure} { + list [catch {image create bitmap i1 -data $data1 -maskdata { + #define foo_width 16 + #define foo_height 8 + static char foo_bits[] = { + 0xff, 0xff, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, + 0x81, 0x81, 0xff, 0xff, 0xff, 0xff, 0x81, 0x81}; + } + } msg] $msg +} {1 {bitmap and mask have different sizes}} +test imageBmap-3.7 {ImgBmapConfigureMaster procedure} { + image create bitmap i1 -data $data1 + .c create image 100 100 -image i1 -tags i1.1 -anchor nw + .c create image 200 100 -image i1 -tags i1.2 -anchor nw + update + i1 configure -data { + #define foo2_height 14 + #define foo2_width 15 + static char foo2_bits[] = { + 0xff, 0xff, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0xff}; + } + update + list [image width i1] [image height i1] [.c bbox i1.1] [.c bbox i1.2] +} {15 14 {100 100 115 114} {200 100 215 114}} + +test imageBmap-4.1 {ImgBmapConfigureInstance procedure: check error handling} { + proc bgerror args {} + .c delete all + image create bitmap i1 -file foo.bm + .c create image 100 100 -image i1 + update + i1 configure -foreground bogus + update +} {} + +test imageBmap-5.1 {GetBitmapData procedure} { + list [catch {image create bitmap -file ~bad_user/a/b} msg] \ + [string tolower $msg] +} {1 {user "bad_user" doesn't exist}} +test imageBmap-5.2 {GetBitmapData procedure} { + list [catch {image create bitmap -file bad_name} msg] [string tolower $msg] +} {1 {couldn't read bitmap file "bad_name": no such file or directory}} +test imageBmap-5.3 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap -data { }} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.4 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap -data {#define foo2_width}} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.5 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap -data {#define foo2_width gorp}} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.6 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap -data {#define foo2_width 1.4}} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.7 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap -data {#define foo2_height}} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.8 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap -data {#define foo2_height gorp}} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.9 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap -data {#define foo2_height 1.4}} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.10 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + image create bitmap i1 -data { + #define foo2_height 14 + #define foo2_width 15 xx _widtg 18 xwidth 18 _heighz 18 xheight 18 + static char foo2_bits[] = { + 0xff, 0xff, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0xff}; + } + list [image width i1] [image height i1] +} {15 14} +test imageBmap-5.11 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + image create bitmap i1 -data { + _height 14 _width 15 + char { + 0xff, 0xff, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0xff} + } + list [image width i1] [image height i1] +} {15 14} +test imageBmap-5.12 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap i1 -data { + #define foo2_height 14 + #define foo2_width 15 + static short foo2_bits[] = { + 0xff, 0xff, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0xff}; + }} msg] $msg +} {1 {format error in bitmap data; looks like it's an obsolete X10 bitmap file}} +test imageBmap-5.13 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap i1 -data { + #define foo2_height 16 + #define foo2_width 16 + static char foo2_bits[] = + 0xff, 0xff, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0xff; + }} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.14 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap i1 -data { + #define foo2_width 16 + static char foo2_bits[] = { + 0xff, 0xff, 0xff, }}} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.15 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap i1 -data { + #define foo2_height 16 + static char foo2_bits[] = { + 0xff, 0xff, 0xff, }}} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.16 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap i1 -data { + #define foo2_height 16 + #define foo2_width 16 + static char foo2_bits[] = { + 0xff, 0xff, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, foo}; + }} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-5.17 {GetBitmapData procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap i1 -data " + #define foo2_height 16 + #define foo2_width 16 + static char foo2_bits[] = \{ + 0xff, 0xff, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, + 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, 0xff, 0x81, + 0xff + "} msg] $msg +} {1 {format error in bitmap data}} + +test imageBmap-6.1 {NextBitmapWord procedure} { + eval image delete [image names] + .c delete all + list [catch {image create bitmap i1 -data {1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890}} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-6.2 {NextBitmapWord procedure} { + eval image delete [image names] + .c delete all + makeFile {1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890} foo3.bm + list [catch {image create bitmap i1 -file foo3.bm} msg] $msg +} {1 {format error in bitmap data}} +test imageBmap-6.3 {NextBitmapWord procedure} { + eval image delete [image names] + .c delete all + makeFile { } foo3.bm + list [catch {image create bitmap i1 -file foo3.bm} msg] $msg +} {1 {format error in bitmap data}} +removeFile foo3.bm + +eval image delete [image names] +.c delete all +image create bitmap i1 +test imageBmap-7.1 {ImgBmapCmd procedure} { + list [catch {i1} msg] $msg +} {1 {wrong # args: should be "i1 option ?arg arg ...?"}} +test imageBmap-7.2 {ImgBmapCmd procedure, "cget" option} { + list [catch {i1 cget} msg] $msg +} {1 {wrong # args: should be "i1 cget option"}} +test imageBmap-7.3 {ImgBmapCmd procedure, "cget" option} { + list [catch {i1 cget a b} msg] $msg +} {1 {wrong # args: should be "i1 cget option"}} +test imageBmap-7.4 {ImgBmapCmd procedure, "cget" option} { + i1 co -foreground #123456 + i1 cget -foreground +} {#123456} +test imageBmap-7.5 {ImgBmapCmd procedure, "cget" option} { + list [catch {i1 cget -stupid} msg] $msg +} {1 {unknown option "-stupid"}} +test imageBmap-7.6 {ImgBmapCmd procedure} { + llength [i1 configure] +} {6} +test imageBmap-7.7 {ImgBmapCmd procedure} { + i1 co -foreground #001122 + i1 configure -foreground +} {-foreground {} {} #000000 #001122} +test imageBmap-7.8 {ImgBmapCmd procedure} { + list [catch {i1 configure -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test imageBmap-7.9 {ImgBmapCmd procedure} { + list [catch {i1 configure -foreground #221100 -background} msg] $msg +} {1 {value for "-background" missing}} +test imageBmap-7.10 {ImgBmapCmd procedure} { + list [catch {i1 gorp} msg] $msg +} {1 {bad option "gorp": must be cget or configure}} + +test imageBmap-8.1 {ImgBmapGet/Free procedures, shared instances} { + eval image delete [image names] + .c delete all + image create bitmap i1 -data $data1 + .c create image 50 100 -image i1 -tags i1.1 + .c create image 150 100 -image i1 -tags i1.2 + .c create image 250 100 -image i1 -tags i1.3 + update + .c delete i1.1 + i1 configure -background black + update + .c delete i1.2 + i1 configure -background white + update + .c delete i1.3 + i1 configure -background black + update + image delete i1 +} {} + +test imageBmap-9.1 {ImgBmapDisplay procedure, nothing to display} { + proc bgerror args {} + eval image delete [image names] + .c delete all + image create bitmap i1 -data $data1 + .c create image 50 100 -image i1 -tags i1.1 + i1 configure -data {} + update +} {} +test imageBmap-9.2 {ImgBmapDisplay procedure, nothing to display} { + proc bgerror args {} + eval image delete [image names] + .c delete all + image create bitmap i1 -data $data1 + .c create image 50 100 -image i1 -tags i1.1 + i1 configure -foreground bogus + update +} {} +if {[info exists bgerror]} { + rename bgerror {} +} + +test imageBmap-10.1 {ImgBmapFree procedure, resource freeing} { + eval image delete [image names] + .c delete all + image create bitmap i1 -data $data1 -maskdata $data2 -foreground #112233 \ + -background #445566 + .c create image 100 100 -image i1 + update + .c delete all + image delete i1 +} {} +test imageBmap-10.2 {ImgBmapFree procedures, unlinking} { + eval image delete [image names] + .c delete all + image create bitmap i1 -data $data1 -maskdata $data2 -foreground #112233 \ + -background #445566 + .c create image 100 100 -image i1 + button .b1 -image i1 + button .b2 -image i1 + button .b3 -image i1 + pack .b1 .b2 .b3 + update + destroy .b2 + update + destroy .b3 + update + destroy .b1 + update + .c delete all +} {} + +test imageBmap-11.1 {ImgBmapDelete procedure} { + image create bitmap i2 -file foo.bm -maskfile foo2.bm + image delete i2 + info command i2 +} {} +test imageBmap-11.2 {ImgBmapDelete procedure} { + image create bitmap i2 -file foo.bm -maskfile foo2.bm + rename i2 newi2 + set x [list [info command i2] [info command new*] [newi2 cget -file]] + image delete i2 + lappend x [info command new*] +} {{} newi2 foo.bm {}} + +test imageBmap-12.1 {ImgBmapCmdDeletedProc procedure} { + image create bitmap i2 -file foo.bm -maskfile foo2.bm + rename i2 {} + list [lsearch -exact [image names] i2] [catch {i2 foo} msg] $msg +} {-1 1 {invalid command name "i2"}} + +removeFile foo.bm +removeFile foo2.bm +destroy .c +eval image delete [image names] diff --git a/tests/imgPPM.test b/tests/imgPPM.test new file mode 100644 index 0000000..044a274 --- /dev/null +++ b/tests/imgPPM.test @@ -0,0 +1,156 @@ +# This file is a Tcl script to test out the code in tkImgFmtPPM.c, +# which reads and write PPM-format image files for photo widgets. +# The files is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) imgPPM.test 1.14 97/10/28 14:47:05 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +eval image delete [image names] + +proc put {file data} { + set f [open $file w] + fconfigure $f -translation lf + puts -nonewline $f $data + close $f +} + +test imgPPM-1.1 {FileReadPPM procedure} { + put test.ppm "P6\n0 256\n255\nabcdef" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {PPM image file "test.ppm" has dimension(s) <= 0}} +test imgPPM-1.2 {FileReadPPM procedure} { + put test.ppm "P6\n-2 256\n255\nabcdef" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {PPM image file "test.ppm" has dimension(s) <= 0}} +test imgPPM-1.3 {FileReadPPM procedure} { + put test.ppm "P6\n10 0\n255\nabcdef" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {PPM image file "test.ppm" has dimension(s) <= 0}} +test imgPPM-1.4 {FileReadPPM procedure} { + put test.ppm "P6\n10 -2\n255\nabcdef" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {PPM image file "test.ppm" has dimension(s) <= 0}} +test imgPPM-1.5 {FileReadPPM procedure} { + put test.ppm "P6\n10 20\n256\nabcdef" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {PPM image file "test.ppm" has bad maximum intensity value 256}} +test imgPPM-1.6 {FileReadPPM procedure} { + put test.ppm "P6\n10 20\n0\nabcdef" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {PPM image file "test.ppm" has bad maximum intensity value 0}} +test imgPPM-1.7 {FileReadPPM procedure} { + put test.ppm "P6\n10 10\n255\nabcdef" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {error reading PPM image file "test.ppm": not enough data}} +test imgPPM-1.8 {FileReadPPM procedure} { + put test.ppm "P6\n5 4\n255\n01234567890123456789012345678901234567890123456789012345678" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {error reading PPM image file "test.ppm": not enough data}} +test imgPPM-1.9 {FileReadPPM procedure} { + put test.ppm "P6\n5 4\n150\n012345678901234567890123456789012345678901234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg \ + [image width p1] [image height p1] +} {0 p1 5 4} + +catch {image delete p1} +put test.ppm "P6\n5 4\n255\n012345678901234567890123456789012345678901234567890123456789" +image create photo p1 -file test.ppm +test imgPPM-2.1 {FileWritePPM procedure} { + list [catch {p1 write not_a_dir/bar/baz/gorp} msg] [string tolower $msg] \ + [string tolower $errorCode] +} {1 {couldn't open "not_a_dir/bar/baz/gorp": no such file or directory} {posix enoent {no such file or directory}}} +test imgPPM-2.2 {FileWritePPM procedure} { + catch {unset data} + p1 write test2.ppm + set fd [open test2.ppm] + set data [read $fd] + close $fd + set data +} {P6 +5 4 +255 +012345678901234567890123456789012345678901234567890123456789} + +test imgPPM-3.1 {ReadPPMFileHeader procedure} { + catch {image delete p1} + put test.ppm "# \n#\n#\nP6\n#\n##\n5 4\n255\n012345678901234567890123456789012345678901234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {0 p1} +test imgPPM-3.2 {ReadPPMFileHeader procedure} { + catch {image delete p1} + put test.ppm "P6\n5\n 4 255\n012345678901234567890123456789012345678901234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {0 p1} +test imgPPM-3.3 {ReadPPMFileHeader procedure} { + catch {image delete p1} + put test.ppm "P6\n# asdfasdf\n5 4\n255\n012345678901234567890123456789012345678901234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {0 p1} +test imgPPM-3.4 {ReadPPMFileHeader procedure} { + catch {image delete p1} + put test.ppm "P6 \n5 4\n255\n012345678901234567890123456789012345678901234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {0 p1} +test imgPPM-3.5 {ReadPPMFileHeader procedure} { + catch {image delete p1} + put test.ppm "P5\n5 4\n255\n01234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {0 p1} +test imgPPM-3.6 {ReadPPMFileHeader procedure} { + catch {image delete p1} + put test.ppm "P3\n5 4\n255\n012345678901234567890123456789012345678901234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {couldn't recognize data in image file "test.ppm"}} +test imgPPM-3.7 {ReadPPMFileHeader procedure} { + catch {image delete p1} + put test.ppm "P6x\n5 4\n255\n012345678901234567890123456789012345678901234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {couldn't recognize data in image file "test.ppm"}} +test imgPPM-3.8 {ReadPPMFileHeader procedure} { + catch {image delete p1} + put test.ppm "P6\nxy5 4\n255\n012345678901234567890123456789012345678901234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {couldn't recognize data in image file "test.ppm"}} +test imgPPM-3.9 {ReadPPMFileHeader procedure} { + catch {image delete p1} + put test.ppm "P6\n5\n255\n!012345678901234567890123456789012345678901234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {couldn't recognize data in image file "test.ppm"}} +test imgPPM-3.10 {ReadPPMFileHeader procedure} { + catch {image delete p1} + put test.ppm "P6\n5 4\nzz255\n012345678901234567890123456789012345678901234567890123456789" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {couldn't recognize data in image file "test.ppm"}} +test imgPPM-3.11 {ReadPPMFileHeader procedure, empty file} { + catch {image delete p1} + put test.ppm " " + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {couldn't recognize data in image file "test.ppm"}} +test imgPPM-3.12 {ReadPPMFileHeader procedure, file ends too soon} { + catch {image delete p1} + put test.ppm "P6\n566" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {couldn't recognize data in image file "test.ppm"}} +test imgPPM-3.13 {ReadPPMFileHeader procedure, file ends too soon} { + catch {image delete p1} + put test.ppm "P6\n566\n#asdf" + list [catch {image create photo p1 -file test.ppm} msg] $msg +} {1 {couldn't recognize data in image file "test.ppm"}} + +removeFile test.ppm +removeFile test2.ppm +eval image delete [image names] diff --git a/tests/imgPhoto.test b/tests/imgPhoto.test new file mode 100644 index 0000000..ec7c635 --- /dev/null +++ b/tests/imgPhoto.test @@ -0,0 +1,423 @@ +# This file is a Tcl script to test out the "photo" image type and the +# other procedures in the file tkImgPhoto.c. It is organized in the +# standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Australian National University +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# Author: Paul Mackerras (paulus@cs.anu.edu.au) +# +# SCCS: @(#) imgPhoto.test 1.23 97/08/08 11:29:25 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +eval image delete [image names] + +canvas .c +pack .c +update + +test imgPhoto-1.1 {options for photo images} { + image create photo p1 -width 79 -height 83 + list [lindex [p1 configure -width] 4] [lindex [p1 configure -height] 4] \ + [image width p1] [image height p1] +} {79 83 79 83} +test imgPhoto-1.2 {options for photo images} { + list [catch {image create photo p1 -file no.such.file} err] \ + [string tolower $err] +} {1 {couldn't open "no.such.file": no such file or directory}} +test imgPhoto-1.3 {options for photo images} { + list [catch {image create photo p1 -file \ + [file join $tk_library demos/images/teapot.ppm] \ + -format no.such.format} err] $err +} {1 {image file format "no.such.format" is not supported}} +test imgPhoto-1.4 {options for photo images} { + image create photo p1 -file [file join $tk_library demos/images/teapot.ppm] + list [image width p1] [image height p1] +} {256 256} +test imgPhoto-1.5 {options for photo images} { + image create photo p1 \ + -file [file join $tk_library demos/images/teapot.ppm] \ + -format ppm -width 79 -height 83 + list [image width p1] [image height p1] \ + [lindex [p1 configure -file] 4] [lindex [p1 configure -format] 4] +} [list 79 83 [file join $tk_library demos/images/teapot.ppm] ppm] +test imgPhoto-1.6 {options for photo images} { + image create photo p1 -palette 2/2/2 -gamma 2.2 + list [format %.1f [lindex [p1 configure -gamma] 4]] \ + [lindex [p1 configure -palette] 4] +} {2.2 2/2/2} +test imgPhoto-1.7 {options for photo images} { + list [catch {image create photo p1 -file README} err] $err +} {1 {couldn't recognize data in image file "README"}} +test imgPhoto-1.8 {options for photo images} { + list [catch {image create photo -blah blah} err] $err +} {1 {unknown option "-blah"}} + +test imgPhoto-2.1 {ImgPhotoCreate procedure} { + eval image delete [image names] + catch {image create photo -blah blah} + image names +} {} +test imgPhoto-2.2 {ImgPhotoCreate procedure} { + eval image delete [image names] + image create photo image1 + list [info commands image1] [image names] \ + [image width image1] [image height image1] +} {image1 image1 0 0} +# test imgPhoto-2.3 {ImgPhotoCreate procedure: creation failure} { +# image create photo p1 +# image create photo p2 -width 10 -height 10 +# catch {image create photo p2 -file bogus.img} msg +# p1 copy p2 +# set msg +# } {couldn't open "bogus.img": no such file or directory} + +test imgPhoto-3.1 {ImgPhotoConfigureMaster procedure} { + image create photo p1 -file [file join $tk_library demos/images/teapot.ppm] + p1 configure -file [file join $tk_library demos/images/teapot.ppm] +} {} +test imgPhoto-3.2 {ImgPhotoConfigureMaster procedure} { + image create photo p1 -file [file join $tk_library demos/images/teapot.ppm] + list [catch {p1 configure -file bogus} err] [string tolower $err] \ + [image width p1] [image height p1] +} {1 {couldn't open "bogus": no such file or directory} 256 256} +test imgPhoto-3.3 {ImgPhotoConfigureMaster procedure} { + image create photo p1 + .c create image 10 10 -image p1 -tags p1.1 -anchor nw + .c create image 300 10 -image p1 -tags p1.2 -anchor nw + update + p1 configure -file [file join $tk_library demos/images/teapot.ppm] + update + list [image width p1] [image height p1] [.c bbox p1.1] [.c bbox p1.2] +} {256 256 {10 10 266 266} {300 10 556 266}} + +eval image delete [image names] +image create photo p1 +.c create image 10 10 -image p1 +update + +test imgPhoto-4.1 {ImgPhotoCmd procedure} { + list [catch {p1} err] $err +} {1 {wrong # args: should be "p1 option ?arg arg ...?"}} +test imgPhoto-4.2 {ImgPhotoCmd procedure} { + list [catch {p1 blah} err] $err +} {1 {bad option "blah": must be blank, cget, configure, copy, get, put, read, redither, or write}} +test imgPhoto-4.3 {ImgPhotoCmd procedure: blank option} { + p1 blank + list [catch {p1 blank x} err] $err +} {1 {wrong # args: should be "p1 blank"}} +test imgPhoto-4.4 {ImgPhotoCmd procedure: cget option} { + list [catch {p1 cget} msg] $msg +} {1 {wrong # args: should be "p1 cget option"}} +test imgPhoto-4.5 {ImgPhotoCmd procedure: cget option} { + image create photo p2 -width 25 -height 30 + list [p2 cget -width] [p2 cget -height] +} {25 30} +test imgPhoto-4.6 {ImgPhotoCmd procedure: configure option} { + llength [p1 configure] +} {7} +test imgPhoto-4.7 {ImgPhotoCmd procedure: configure option} { + p1 conf -palette 3/4/2 + p1 configure -palette +} {-palette {} {} {} 3/4/2} +test imgPhoto-4.8 {ImgPhotoCmd procedure: configure option} { + list [catch {p1 configure -blah} msg] $msg +} {1 {unknown option "-blah"}} +test imgPhoto-4.9 {ImgPhotoCmd procedure: configure option} { + list [catch {p1 configure -palette {} -gamma} msg] $msg +} {1 {value for "-gamma" missing}} +test imgPhoto-4.10 {ImgPhotoCmd procedure: copy option} { + image create photo p2 -file [file join $tk_library demos/images/teapot.ppm] + p1 configure -width 0 -height 0 -palette {} -gamma 1 + p1 copy p2 + list [image width p1] [image height p1] [p1 get 100 100] +} {256 256 {169 117 90}} +test imgPhoto-4.11 {ImgPhotoCmd procedure: copy option} { + list [catch {p1 copy} msg] $msg +} {1 {wrong # args: should be "p1 copy source-image ?-from x1 y1 x2 y2? ?-to x1 y1 x2 y2? ?-zoom x y? ?-subsample x y?"}} +test imgPhoto-4.12 {ImgPhotoCmd procedure: copy option} { + list [catch {p1 copy blah} msg] $msg +} {1 {image "blah" doesn't exist or is not a photo image}} +test imgPhoto-4.13 {ImgPhotoCmd procedure: copy option} { + list [catch {p1 copy p2 -blah} msg] $msg +} {1 {unrecognized option "-blah": must be -from, -shrink, -subsample, -to, or -zoom}} +test imgPhoto-4.14 {ImgPhotoCmd procedure: copy option} { + list [catch {p1 copy p2 -from -to} msg] $msg +} {1 {the "-from" option requires one to four integer values}} +test imgPhoto-4.15 {ImgPhotoCmd procedure: copy option} { + p1 copy p2 + p1 copy p2 -from 0 70 60 120 -shrink + list [image width p1] [image height p1] [p1 get 20 10] +} {60 50 {215 154 120}} +test imgPhoto-4.16 {ImgPhotoCmd procedure: copy option} { + p1 copy p2 -from 60 120 0 70 -to 20 50 + list [image width p1] [image height p1] [p1 get 40 80] +} {80 100 {19 92 192}} +test imgPhoto-4.17 {ImgPhotoCmd procedure: copy option} { + p1 copy p2 -from 0 120 60 70 -to 0 0 100 100 + list [image width p1] [image height p1] [p1 get 80 60] +} {100 100 {215 154 120}} +test imgPhoto-4.18 {ImgPhotoCmd procedure: copy option} { + p1 copy p2 -from 60 70 0 120 -zoom 2 + list [image width p1] [image height p1] [p1 get 100 50] +} {120 100 {169 99 47}} +test imgPhoto-4.19 {ImgPhotoCmd procedure: copy option} { + p1 copy p2 -from 0 70 60 120 + list [image width p1] [image height p1] [p1 get 100 50] +} {120 100 {169 99 47}} +test imgPhoto-4.20 {ImgPhotoCmd procedure: copy option} { + p1 copy p2 -from 20 20 200 180 -subsample 2 -shrink + list [image width p1] [image height p1] [p1 get 50 30] +} {90 80 {207 146 112}} +test imgPhoto-4.21 {ImgPhotoCmd procedure: copy option} { + p1 copy p2 + set result [list [image width p1] [image height p1]] + p1 conf -width 49 -height 51 + lappend result [image width p1] [image height p1] + p1 copy p2 + lappend result [image width p1] [image height p1] + p1 copy p2 -from 0 0 10 10 -shrink + lappend result [image width p1] [image height p1] + p1 conf -width 0 + p1 copy p2 -from 0 0 10 10 -shrink + lappend result [image width p1] [image height p1] + p1 conf -height 0 + p1 copy p2 -from 0 0 10 10 -shrink + lappend result [image width p1] [image height p1] +} {256 256 49 51 49 51 49 51 10 51 10 10} +test imgPhoto-4.22 {ImgPhotoCmd procedure: get option} { + p1 read [file join $tk_library demos/images/teapot.ppm] + list [p1 get 100 100] [p1 get 150 100] [p1 get 100 150] +} {{169 117 90} {172 115 84} {35 35 35}} +test imgPhoto-4.23 {ImgPhotoCmd procedure: get option} { + list [catch {p1 get 256 0} err] $err +} {1 {p1 get: coordinates out of range}} +test imgPhoto-4.24 {ImgPhotoCmd procedure: get option} { + list [catch {p1 get 0 -1} err] $err +} {1 {p1 get: coordinates out of range}} +test imgPhoto-4.25 {ImgPhotoCmd procedure: get option} { + list [catch {p1 get} err] $err +} {1 {wrong # args: should be "p1 get x y"}} +test imgPhoto-4.26 {ImgPhotoCmd procedure: put option} { + list [catch {p1 put} err] $err +} {1 {wrong # args: should be "p1 put {{colors...}...} ?-to x1 y1 x2 y2?"}} +test imgPhoto-4.27 {ImgPhotoCmd procedure: put option} { + list [catch {p1 put {{white} {white white}}} err] $err +} {1 {all elements of color list must have the same number of elements}} +test imgPhoto-4.28 {ImgPhotoCmd procedure: put option} { + list [catch {p1 put {{blahgle}}} err] $err +} {1 {can't parse color "blahgle"}} +test imgPhoto-4.29 {ImgPhotoCmd procedure: put option} { + p1 put -to 10 10 20 20 {{white}} + p1 get 19 19 +} {255 255 255} +test imgPhoto-4.30 {ImgPhotoCmd procedure: read option} { + list [catch {p1 read} err] $err +} {1 {wrong # args: should be "p1 read fileName ?-format format-name? ?-from x1 y1 x2 y2? ?-to x y? ?-shrink?"}} +test imgPhoto-4.31 {ImgPhotoCmd procedure: read option} { + list [catch {p1 read [file join $tk_library demos/images/teapot.ppm] \ + -zoom 2} err] $err +} {1 {unrecognized option "-zoom": must be -format, -from, -shrink, or -to}} +test imgPhoto-4.32 {ImgPhotoCmd procedure: read option} { + list [catch {p1 read bogus} err] [string tolower $err] +} {1 {couldn't open "bogus": no such file or directory}} +test imgPhoto-4.33 {ImgPhotoCmd procedure: read option} { + list [catch {p1 read [file join $tk_library demos/images/teapot.ppm] \ + -format bogus} err] $err +} {1 {image file format "bogus" is not supported}} +test imgPhoto-4.34 {ImgPhotoCmd procedure: read option} { + list [catch {p1 read README} err] $err +} {1 {couldn't recognize data in image file "README"}} +test imgPhoto-4.35 {ImgPhotoCmd procedure: read option} { + p1 read [file join $tk_library demos/images/teapot.ppm] -shrink + list [image width p1] [image height p1] [p1 get 120 120] +} {256 256 {161 109 82}} +test imgPhoto-4.36 {ImgPhotoCmd procedure: read option} { + p1 read [file join $tk_library demos/images/teapot.ppm] \ + -from 0 70 60 120 -to 10 10 -shrink + list [image width p1] [image height p1] [p1 get 29 19] +} {70 60 {244 180 144}} +test imgPhoto-4.37 {ImgPhotoCmd procedure: redither option} { + p1 redither + list [catch {p1 redither x} err] $err +} {1 {wrong # args: should be "p1 redither"}} +test imgPhoto-4.38 {ImgPhotoCmd procedure: write option} { + list [catch {p1 write} err] $err +} {1 {wrong # args: should be "p1 write fileName ?-format format-name??-from x1 y1 x2 y2?"}} +test imgPhoto-4.39 {ImgPhotoCmd procedure: write option} { + list [catch {p1 write teapot.tmp -format bogus} err] $err +} {1 {image file format "bogus" is unknown}} + +test imgPhoto-5.1 {ImgPhotoGet/Free procedures, shared instances} { + eval image delete [image names] + .c delete all + image create photo p1 -file [file join $tk_library demos/images/teapot.ppm] + .c create image 0 0 -image p1 -tags p1.1 + .c create image 256 0 -image p1 -tags p1.2 + .c create image 0 256 -image p1 -tags p1.3 + update + .c delete i1.1 + p1 configure -width 1 + update + .c delete i1.2 + p1 configure -height 1 + update + image delete p1 +} {} + +test imgPhoto-6.1 {ImgPhotoDisplay procedure, blank display} { + .c delete all + image create photo p1 -width 10 -height 10 + p1 blank + .c create image 10 10 -image p1 + update +} {} + +test imgPhoto-7.1 {ImgPhotoFree procedure, resource freeing} { + eval image delete [image names] + .c delete all + image create photo p1 -file [file join $tk_library demos/images/teapot.ppm] + .c create image 0 0 -image p1 -anchor nw + update + .c delete all + image delete p1 +} {} +test imgPhoto-7.2 {ImgPhotoFree procedures, unlinking} { + image create photo p1 -file [file join $tk_library demos/images/teapot.ppm] + .c create image 10 10 -image p1 -anchor nw + button .b1 -image p1 + button .b2 -image p1 + button .b3 -image p1 + pack .b1 .b2 .b3 + update + destroy .b2 + update + destroy .b3 + update + destroy .b1 + update + .c delete all +} {} +test imgPhoto-7.3 {ImgPhotoFree procedures, multiple visuals} { + image create photo p1 -file [file join $tk_library demos/images/teapot.ppm] + button .b1 -image p1 + frame .f -visual best + button .f.b2 -image p1 + pack .f.b2 + pack .b1 .f + update + destroy .b1 + update + .f.b2 configure -image {} + update + destroy .f + image delete p1 +} {} + +test imgPhoto-8.1 {ImgPhotoDelete procedure} { + image create photo p2 -file [file join $tk_library demos/images/teapot.ppm] + image delete p2 +} {} +test imagePhoto-8.2 {ImgPhotoDelete procedure} { + image create photo p2 -file [file join $tk_library demos/images/teapot.ppm] + rename p2 newp2 + set x [list [info command p2] [info command new*] [newp2 cget -file]] + image delete p2 + lappend x [info command new*] +} [list {} newp2 [file join $tk_library demos/images/teapot.ppm] {}] +test imagePhoto-8.3 {ImgPhotoDelete procedure, name cleanup} { + image create photo p1 + image create photo p2 -width 10 -height 10 + image delete p2 + list [catch {p1 copy p2} msg] $msg +} {1 {image "p2" doesn't exist or is not a photo image}} + +test imagePhoto-9.1 {ImgPhotoCmdDeletedProc procedure} { + image create photo p2 -file [file join $tk_library demos/images/teapot.ppm] + rename p2 {} + list [lsearch -exact [image names] p2] [catch {p2 foo} msg] $msg +} {-1 1 {invalid command name "p2"}} + +test imgPhoto-10.1 {Tk_ImgPhotoPutBlock procedure} { + eval image delete [image names] + image create photo p1 + p1 put {{#ff0000 #ff0000 #ff0000 #ff0000 #ff0000 #ff0000 #ff0000 #ff0000}} \ + -to 0 0 + p1 put {{#00ff00 #00ff00}} -to 2 0 + list [p1 get 2 0] [p1 get 3 0] [p1 get 4 0] +} {{0 255 0} {0 255 0} {255 0 0}} + +test imgPhoto-11.1 {Tk_FindPhoto} { + eval image delete [image names] + image create bitmap i1 + image create photo p1 + list [catch {p1 copy i1} msg] $msg +} {1 {image "i1" doesn't exist or is not a photo image}} + +test imgPhoto-12.1 {Tk_PhotoPutZoomedBlock} { + image create photo p3 -file [file join $tk_library demos/images/teapot.ppm] + set result [list [p3 get 50 50] [p3 get 100 100]] + p3 copy p3 -zoom 2 + lappend result [image width p3] [image height p3] [p3 get 100 100] + image delete p3 + set result +} {{19 92 192} {169 117 90} 512 512 {19 92 192}} + +test imgPhoto-13.1 {check separation of images in different interpreters} { + eval image delete [image names] + set data { + R0lGODlhQgBkAPUAANbWxs7Wxs7OxsbOxsbGxsbGvb3Gvca9vcDAwL21vbW1vbW1tbWtta2t + ta2ltaWltaWlraWctaWcrZycrZyUrZSUrZSMrZSMpYyMrYyMpYyEpYSEpYR7pYR7nHp7pYRz + pYRynHtzpXtznHtrnHNrnHNjnGtjnGtjlGtalGNalGNSlGNSjFpSlFpKlFpKjFJKjFJCjFI5 + jEo5jEo5hEoxhEIxhDkphDkhhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAQgBkAAAG + /kCEcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P + 7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmOBZxXnAQEnKIIBUQJCguoDKkIBgWhpUev + CA4TDwgEUpwKERUaHCIiJCQjIiEUQhwqKiwqLjDQMCwoIha3oUO5ESMuLSwtLSIMsU4Tzi4o + JBwWFA8ODQoMCkIMq6sNDQ4UFhwlzC4qSGhgkMvCsAoM6E0oAWMCOSUFGrgQcauAgAACSqGa + l6SAK1EaJXBA0SIDBw0KBiCg8EtEBgEWYCxoooAigFwIJGgQYQIF/goTAjk6sXhxAwwFnHRO + mEmAwoQAIUo8lCWhRgoOElJVkJBQFCwhCRqkYlUE1QMKHEywoBCrQaeIMCgQeOCi3AkYMmRI + S5EuxEkN7OApkGDhF4fDxoSVMAFUBAWkRxI0a+XghVAkBSqMsFCBwj4OI0igSKGCdLN0wYKd + zGDBwUYhn6YOKUCioQECGk7INpIArQgUKkr87TyhAYIDQxQgLkYsRIcQIDjcgi2Lw8RYKaAz + MXCgAs8UJrZGmOA5AkeQBlqRKsIpvYMQDx4S4NCCxIJSKJpFYMIgnPlSF2ygAQWuCUHAAp6x + E4EEE5BXQQUWYLABBySoAIMLHBSBWwso/jxwIAoyzMAWEw3AEEJCt6nUwAQagCDCYcCQwJcK + 6QD3DDQxwNDCCSg9NIAGKpwwgQAOtDADDBbsdkQDIPhkwosDPgDPAg1EAME++1jTnhAKdAnb + VAR04EIJFAhwwQs0sBDfE7cZwEAE++yU2joOtDcKE7GUcoIKH6RSmwwnQCZFKAo8cE2es7my + HnuxKTDgAA6owEEBjoL3wqRUNDBCCnyRYMFMRSDoWYPvyBPPA738lt1KKTxgpjolrDDiFAWU + cAMKE+CipAMRZMDTCSSUQMIJPQHLwWOcrDKBCBpokAIJgmYqQgosxIAOCS8iJEQD7HR2QbMh + WCCEK7Ck90Cz/oAFu+YVigpTwTsLyJOcBJ6N6plxRihA3E4cOKTkFCU6FMoAA7wiygAZgURA + ekYsEJYFGTSATRccQEMjti8eZsEFFuA7z2WkEJAAl7iEQekEhQHGzgQR4INUKLB8pYAFJaQA + KhleKdwAByEkFswHIoxQQn4AcYBvGRosisDICCjQAIMJGnZYBsUd4JEZBIhQwgPzKFwAwggL + IHbOQzCtxZ1NL0BlKmmhIOwwHGTg2YMUEBdtKzBfbQWlhMHoHIXBnvABBGE9UMKNMKhgQgnG + nNQO0wVQoI4FEohFyr9GzDIYaaPxxWy0rCjKQJUMQvxBaMOgNMQChcU4DAkZ6PoV/hIUoP4i + Z7g/YHZHIPXeyWyONgsaCi4AOoLjXP8uhAAvPpCQ2Akr38UpXW60Ij8yPkMmwwj8KAI8QWtQ + +eXSixEb37WhcHQBERz2rdZ8leCBBcXNY3XevQ8VG/6+F5CACDYgATlmYYD27aRmLngBNADC + GGxxQEAWUJDzqpcctc2DARN4kNRgtJxhnKAFV0kIEhYAJ34IQwUhqkENYFCCE5BmGf9wwWmA + 5UGgXAAVtfCFMIgRLMbFLQIPYFACcMI7TjQoH2eJQIs2poEMYMAp5XGAvFrBCYS9ImzQG1vT + arGTEQhIhE7QjLA+MKDOxClGwuoJtWi0uBIUIxjDSE2wQ4iHl7ywQDjGwZws/NcAlgBjaKQJ + JDVuoQBeUeACoFkMcFqgQL1IgxpRSsjsqHA/gy0tHvmAx2z2BxIupaJrnVxCEAAAOw== + } + interp create x1 + interp create x2 + x1 eval {load {} Tk} + x2 eval {load {} Tk} + x1 eval [list image create photo T1_data -data $data] + x2 eval [list image create photo T1_data -data $data] + unset data + interp delete x1 + interp delete x2 +} {} + +destroy .c +eval image delete [image names] diff --git a/tests/listbox.test b/tests/listbox.test new file mode 100644 index 0000000..cb1a4e3 --- /dev/null +++ b/tests/listbox.test @@ -0,0 +1,1658 @@ +# This file is a Tcl script to test out the "listbox" command +# of Tk. It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1993-1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) listbox.test 1.45 97/10/29 13:05:46 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . +set fixed {Courier -12} + +proc record args { + global log + lappend log $args +} + +proc getsize w { + regexp {(^[^+-]*)} [wm geometry $w] foo x + return $x +} + +proc resetGridInfo {} { + # Some window managers, such as mwm, don't reset gridding information + # unless the window is withdrawn and re-mapped. If this procedure + # isn't invoked, the window manager will stay in gridded mode, which + # can cause all sorts of problems. The "wm positionfrom" command is + # needed so that the window manager doesn't ask the user to + # manually position the window when it is re-mapped. + + wm withdraw . + wm positionfrom . user + wm deiconify . +} + +# Procedure that creates a second listbox for checking things related +# to partially visible lines. + +proc mkPartial {{w .partial}} { + catch {destroy $w} + toplevel $w + wm geometry $w +0+0 + listbox $w.l -width 30 -height 5 + pack $w.l -expand 1 -fill both + $w.l insert end one two three four five six seven eight nine ten \ + eleven twelve thirteen fourteen fifteen + update + scan [wm geometry $w] "%dx%d" width height + wm geometry $w ${width}x[expr $height-3] + update +} + +# Create entries in the option database to be sure that geometry options +# like border width have predictable values. + +option add *Listbox.borderWidth 2 +option add *Listbox.highlightThickness 2 +option add *Listbox.font {Helvetica -12 bold} + +listbox .l +pack .l +update +resetGridInfo +set i 1 + +foreach test { + {-background #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-bd 4 4 badValue {bad screen distance "badValue"}} + {-bg #ff0000 #ff0000 non-existent {unknown color name "non-existent"}} + {-borderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-cursor arrow arrow badValue {bad cursor spec "badValue"}} + {-exportselection yes 1 xyzzy {expected boolean value but got "xyzzy"}} + {-fg #110022 #110022 bogus {unknown color name "bogus"}} + {-font {Helvetica 12} {Helvetica 12} {} {font "" doesn't exist}} + {-foreground #110022 #110022 bogus {unknown color name "bogus"}} + {-height 30 30 20p {expected integer but got "20p"}} + {-highlightbackground #112233 #112233 ugly {unknown color name "ugly"}} + {-highlightcolor #123456 #123456 bogus {unknown color name "bogus"}} + {-highlightthickness 6 6 bogus {bad screen distance "bogus"}} + {-highlightthickness -2 0 {} {}} + {-relief groove groove 1.5 {bad relief type "1.5": must be flat, groove, raised, ridge, solid, or sunken}} + {-selectbackground #110022 #110022 bogus {unknown color name "bogus"}} + {-selectborderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-selectforeground #654321 #654321 bogus {unknown color name "bogus"}} + {-selectmode string string {} {}} + {-setgrid false 0 lousy {expected boolean value but got "lousy"}} + {-takefocus "any string" "any string" {} {}} + {-width 45 45 3p {expected integer but got "3p"}} + {-xscrollcommand {Some command} {Some command} {} {}} + {-yscrollcommand {Another command} {Another command} {} {}} +} { + set name [lindex $test 0] + test listbox-1.$i {configuration options} { + .l configure $name [lindex $test 1] + list [lindex [.l configure $name] 4] [.l cget $name] + } [list [lindex $test 2] [lindex $test 2]] + incr i + if {[lindex $test 3] != ""} { + test listbox-1.$i {configuration options} { + list [catch {.l configure $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .l configure $name [lindex [.l configure $name] 3] + incr i +} + +test listbox-2.1 {Tk_ListboxCmd procedure} { + list [catch {listbox} msg] $msg +} {1 {wrong # args: should be "listbox pathName ?options?"}} +test listbox-2.2 {Tk_ListboxCmd procedure} { + list [catch {listbox gorp} msg] $msg +} {1 {bad window path name "gorp"}} +test listbox-2.3 {Tk_ListboxCmd procedure} { + catch {destroy .l} + listbox .l + list [winfo exists .l] [winfo class .l] [info commands .l] +} {1 Listbox .l} +test listbox-2.4 {Tk_ListboxCmd procedure} { + catch {destroy .l} + list [catch {listbox .l -gorp foo} msg] $msg [winfo exists .l] \ + [info commands .l] +} {1 {unknown option "-gorp"} 0 {}} +test listbox-2.5 {Tk_ListboxCmd procedure} { + catch {destroy .l} + listbox .l +} {.l} + +catch {destroy .l} +listbox .l -width 20 -height 5 -bd 4 -highlightthickness 1 -selectborderwidth 2 +pack .l +.l insert 0 el0 el1 el2 el3 el4 el5 el6 el7 el8 el9 el10 el11 el12 el13 el14 \ + el15 el16 el17 +update +test listbox-3.1 {ListboxWidgetCmd procedure} { + list [catch .l msg] $msg +} {1 {wrong # args: should be ".l option ?arg arg ...?"}} +test listbox-3.2 {ListboxWidgetCmd procedure, "activate" option} { + list [catch {.l activate} msg] $msg +} {1 {wrong # args: should be ".l activate index"}} +test listbox-3.3 {ListboxWidgetCmd procedure, "activate" option} { + list [catch {.l activate a b} msg] $msg +} {1 {wrong # args: should be ".l activate index"}} +test listbox-3.4 {ListboxWidgetCmd procedure, "activate" option} { + list [catch {.l activate fooey} msg] $msg +} {1 {bad listbox index "fooey": must be active, anchor, end, @x,y, or a number}} +test listbox-3.5 {ListboxWidgetCmd procedure, "activate" option} { + .l activate 3 + .l index active +} 3 +test listbox-3.6 {ListboxWidgetCmd procedure, "activate" option} { + .l activate -1 + .l index active +} {0} +test listbox-3.7 {ListboxWidgetCmd procedure, "activate" option} { + .l activate 30 + .l index active +} {17} +test listbox-3.8 {ListboxWidgetCmd procedure, "activate" option} { + .l activate end + .l index active +} {17} +test listbox-3.9 {ListboxWidgetCmd procedure, "bbox" option} { + list [catch {.l bbox} msg] $msg +} {1 {wrong # args: should be ".l bbox index"}} +test listbox-3.10 {ListboxWidgetCmd procedure, "bbox" option} { + list [catch {.l bbox a b} msg] $msg +} {1 {wrong # args: should be ".l bbox index"}} +test listbox-3.11 {ListboxWidgetCmd procedure, "bbox" option} { + list [catch {.l bbox fooey} msg] $msg +} {1 {bad listbox index "fooey": must be active, anchor, end, @x,y, or a number}} +test listbox-3.12 {ListboxWidgetCmd procedure, "bbox" option} { + .l yview 3 + update + list [.l bbox 2] [.l bbox 8] +} {{} {}} +test listbox-3.13 {ListboxWidgetCmd procedure, "bbox" option} { + # Used to generate a core dump before a bug was fixed (the last + # element would be on-screen if it existed, but it doesn't exist). + + listbox .l2 + pack .l2 -side top + tkwait visibility .l2 + set x [.l2 bbox 0] + destroy .l2 + set x +} {} +test listbox-3.14 {ListboxWidgetCmd procedure, "bbox" option} {fonts} { + .l yview 3 + update + list [.l bbox 3] [.l bbox 4] +} {{7 7 17 14} {7 26 17 14}} +test listbox-3.15 {ListboxWidgetCmd procedure, "bbox" option} {fonts} { + .l yview 0 + update + list [.l bbox -1] [.l bbox 0] +} {{} {7 7 17 14}} +test listbox-3.16 {ListboxWidgetCmd procedure, "bbox" option} {fonts} { + .l yview end + update + list [.l bbox 17] [.l bbox end] [.l bbox 18] +} {{7 83 24 14} {7 83 24 14} {}} +test listbox-3.17 {ListboxWidgetCmd procedure, "bbox" option} {fonts} { + catch {destroy .t} + toplevel .t + wm geom .t +0+0 + listbox .t.l -width 10 -height 5 + .t.l insert 0 "Short" "Somewhat longer" "Really, quite a whole lot longer than can possibly fit on the screen" "Short" + pack .t.l + update + .t.l xview moveto .2 + .t.l bbox 2 +} {-72 39 393 14} +test listbox-3.18 {ListboxWidgetCmd procedure, "bbox" option, partial last line} {fonts} { + mkPartial + list [.partial.l bbox 3] [.partial.l bbox 4] +} {{5 56 24 14} {5 73 23 14}} +test listbox-3.19 {ListboxWidgetCmd procedure, "cget" option} { + list [catch {.l cget} msg] $msg +} {1 {wrong # args: should be ".l cget option"}} +test listbox-3.20 {ListboxWidgetCmd procedure, "cget" option} { + list [catch {.l cget a b} msg] $msg +} {1 {wrong # args: should be ".l cget option"}} +test listbox-3.21 {ListboxWidgetCmd procedure, "cget" option} { + list [catch {.l cget -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test listbox-3.22 {ListboxWidgetCmd procedure, "cget" option} { + .l cget -setgrid +} {0} +test listbox-3.23 {ListboxWidgetCmd procedure, "configure" option} { + llength [.l configure] +} {23} +test listbox-3.24 {ListboxWidgetCmd procedure, "configure" option} { + list [catch {.l configure -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test listbox-3.25 {ListboxWidgetCmd procedure, "configure" option} { + .l configure -setgrid +} {-setgrid setGrid SetGrid 0 0} +test listbox-3.26 {ListboxWidgetCmd procedure, "configure" option} { + list [catch {.l configure -gorp is_messy} msg] $msg +} {1 {unknown option "-gorp"}} +test listbox-3.27 {ListboxWidgetCmd procedure, "configure" option} { + set oldbd [.l cget -bd] + set oldht [.l cget -highlightthickness] + .l configure -bd 3 -highlightthickness 0 + set x "[.l cget -bd] [.l cget -highlightthickness]" + .l configure -bd $oldbd -highlightthickness $oldht + set x +} {3 0} +test listbox-3.28 {ListboxWidgetCmd procedure, "curselection" option} { + list [catch {.l curselection a} msg] $msg +} {1 {wrong # args: should be ".l curselection"}} +test listbox-3.29 {ListboxWidgetCmd procedure, "curselection" option} { + .l selection clear 0 end + .l selection set 3 6 + .l selection set 9 + .l curselection +} {3 4 5 6 9} +test listbox-3.30 {ListboxWidgetCmd procedure, "delete" option} { + list [catch {.l delete} msg] $msg +} {1 {wrong # args: should be ".l delete firstIndex ?lastIndex?"}} +test listbox-3.31 {ListboxWidgetCmd procedure, "delete" option} { + list [catch {.l delete a b c} msg] $msg +} {1 {wrong # args: should be ".l delete firstIndex ?lastIndex?"}} +test listbox-3.32 {ListboxWidgetCmd procedure, "delete" option} { + list [catch {.l delete badIndex} msg] $msg +} {1 {bad listbox index "badIndex": must be active, anchor, end, @x,y, or a number}} +test listbox-3.33 {ListboxWidgetCmd procedure, "delete" option} { + list [catch {.l delete 2 123ab} msg] $msg +} {1 {bad listbox index "123ab": must be active, anchor, end, @x,y, or a number}} +test listbox-3.34 {ListboxWidgetCmd procedure, "delete" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert 0 el0 el1 el2 el3 el4 el5 el6 el7 + .l2 delete 3 + list [.l2 get 2] [.l2 get 3] [.l2 index end] +} {el2 el4 7} +test listbox-3.35 {ListboxWidgetCmd procedure, "delete" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert 0 el0 el1 el2 el3 el4 el5 el6 el7 + .l2 delete 2 4 + list [.l2 get 1] [.l2 get 2] [.l2 index end] +} {el1 el5 5} +test listbox-3.36 {ListboxWidgetCmd procedure, "delete" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert 0 el0 el1 el2 el3 el4 el5 el6 el7 + .l2 delete -3 2 + .l2 get 0 end +} {el3 el4 el5 el6 el7} +test listbox-3.37 {ListboxWidgetCmd procedure, "delete" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert 0 el0 el1 el2 el3 el4 el5 el6 el7 + .l2 delete -3 -1 + .l2 get 0 end +} {el0 el1 el2 el3 el4 el5 el6 el7} +test listbox-3.38 {ListboxWidgetCmd procedure, "delete" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert 0 el0 el1 el2 el3 el4 el5 el6 el7 + .l2 delete 2 end + .l2 get 0 end +} {el0 el1} +test listbox-3.39 {ListboxWidgetCmd procedure, "delete" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert 0 el0 el1 el2 el3 el4 el5 el6 el7 + .l2 delete 5 20 + .l2 get 0 end +} {el0 el1 el2 el3 el4} +test listbox-3.40 {ListboxWidgetCmd procedure, "delete" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert 0 el0 el1 el2 el3 el4 el5 el6 el7 + .l2 delete end 20 + .l2 get 0 end +} {el0 el1 el2 el3 el4 el5 el6} +test listbox-3.41 {ListboxWidgetCmd procedure, "delete" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert 0 el0 el1 el2 el3 el4 el5 el6 el7 + .l2 delete 8 20 + .l2 get 0 end +} {el0 el1 el2 el3 el4 el5 el6 el7} +test listbox-3.42 {ListboxWidgetCmd procedure, "get" option} { + list [catch {.l get} msg] $msg +} {1 {wrong # args: should be ".l get first ?last?"}} +test listbox-3.43 {ListboxWidgetCmd procedure, "get" option} { + list [catch {.l get a b c} msg] $msg +} {1 {wrong # args: should be ".l get first ?last?"}} +test listbox-3.44 {ListboxWidgetCmd procedure, "get" option} { + list [catch {.l get 2.4} msg] $msg +} {1 {bad listbox index "2.4": must be active, anchor, end, @x,y, or a number}} +test listbox-3.45 {ListboxWidgetCmd procedure, "get" option} { + list [catch {.l get end bogus} msg] $msg +} {1 {bad listbox index "bogus": must be active, anchor, end, @x,y, or a number}} +test listbox-3.46 {ListboxWidgetCmd procedure, "get" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert 0 el0 el1 el2 el3 el4 el5 el6 el7 + list [.l2 get 0] [.l2 get 3] [.l2 get end] +} {el0 el3 el7} +test listbox-3.47 {ListboxWidgetCmd procedure, "get" option} { + catch {destroy .l2} + listbox .l2 + list [.l2 get 0] [.l2 get end] +} {{} {}} +test listbox-3.48 {ListboxWidgetCmd procedure, "get" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert 0 el0 el1 el2 "two words" el4 el5 el6 el7 + .l2 get 3 end +} {{two words} el4 el5 el6 el7} +test listbox-3.49 {ListboxWidgetCmd procedure, "get" option} { + .l get -1 +} {} +test listbox-3.50 {ListboxWidgetCmd procedure, "get" option} { + .l get -2 -1 +} {} +test listbox-3.51 {ListboxWidgetCmd procedure, "get" option} { + .l get -2 3 +} {el0 el1 el2 el3} +test listbox-3.52 {ListboxWidgetCmd procedure, "get" option} { + .l get 12 end +} {el12 el13 el14 el15 el16 el17} +test listbox-3.53 {ListboxWidgetCmd procedure, "get" option} { + .l get 12 20 +} {el12 el13 el14 el15 el16 el17} +test listbox-3.54 {ListboxWidgetCmd procedure, "get" option} { + .l get end +} {el17} +test listbox-3.55 {ListboxWidgetCmd procedure, "get" option} { + .l get 30 +} {} +test listbox-3.56 {ListboxWidgetCmd procedure, "get" option} { + .l get 30 35 +} {} +test listbox-3.57 {ListboxWidgetCmd procedure, "index" option} { + list [catch {.l index} msg] $msg +} {1 {wrong # args: should be ".l index index"}} +test listbox-3.58 {ListboxWidgetCmd procedure, "index" option} { + list [catch {.l index a b} msg] $msg +} {1 {wrong # args: should be ".l index index"}} +test listbox-3.59 {ListboxWidgetCmd procedure, "index" option} { + list [catch {.l index @} msg] $msg +} {1 {bad listbox index "@": must be active, anchor, end, @x,y, or a number}} +test listbox-3.60 {ListboxWidgetCmd procedure, "index" option} { + .l index 2 +} 2 +test listbox-3.61 {ListboxWidgetCmd procedure, "index" option} { + .l index -1 +} -1 +test listbox-3.62 {ListboxWidgetCmd procedure, "index" option} { + .l index end +} 18 +test listbox-3.63 {ListboxWidgetCmd procedure, "index" option} { + .l index 34 +} 34 +test listbox-3.64 {ListboxWidgetCmd procedure, "insert" option} { + list [catch {.l insert} msg] $msg +} {1 {wrong # args: should be ".l insert index ?element element ...?"}} +test listbox-3.65 {ListboxWidgetCmd procedure, "insert" option} { + list [catch {.l insert badIndex} msg] $msg +} {1 {bad listbox index "badIndex": must be active, anchor, end, @x,y, or a number}} +test listbox-3.66 {ListboxWidgetCmd procedure, "insert" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert end a b c d e + .l2 insert 3 x y z + .l2 get 0 end +} {a b c x y z d e} +test listbox-3.67 {ListboxWidgetCmd procedure, "insert" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert end a b c + .l2 insert -1 x + .l2 get 0 end +} {x a b c} +test listbox-3.68 {ListboxWidgetCmd procedure, "insert" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert end a b c + .l2 insert end x + .l2 get 0 end +} {a b c x} +test listbox-3.69 {ListboxWidgetCmd procedure, "insert" option} { + catch {destroy .l2} + listbox .l2 + .l2 insert end a b c + .l2 insert 43 x + .l2 get 0 end +} {a b c x} +test listbox-3.70 {ListboxWidgetCmd procedure, "nearest" option} { + list [catch {.l nearest} msg] $msg +} {1 {wrong # args: should be ".l nearest y"}} +test listbox-3.71 {ListboxWidgetCmd procedure, "nearest" option} { + list [catch {.l nearest a b} msg] $msg +} {1 {wrong # args: should be ".l nearest y"}} +test listbox-3.72 {ListboxWidgetCmd procedure, "nearest" option} { + list [catch {.l nearest 20p} msg] $msg +} {1 {expected integer but got "20p"}} +test listbox-3.73 {ListboxWidgetCmd procedure, "nearest" option} { + .l yview 3 + .l nearest 1000 +} {7} +test listbox-3.74 {ListboxWidgetCmd procedure, "scan" option} { + list [catch {.l scan a b} msg] $msg +} {1 {wrong # args: should be ".l scan mark|dragto x y"}} +test listbox-3.75 {ListboxWidgetCmd procedure, "scan" option} { + list [catch {.l scan a b c d} msg] $msg +} {1 {wrong # args: should be ".l scan mark|dragto x y"}} +test listbox-3.76 {ListboxWidgetCmd procedure, "scan" option} { + list [catch {.l scan foo bogus 2} msg] $msg +} {1 {expected integer but got "bogus"}} +test listbox-3.77 {ListboxWidgetCmd procedure, "scan" option} { + list [catch {.l scan foo 2 2.3} msg] $msg +} {1 {expected integer but got "2.3"}} +test listbox-3.78 {ListboxWidgetCmd procedure, "scan" option} {fonts} { + catch {destroy .t} + toplevel .t + wm geom .t +0+0 + listbox .t.l -width 10 -height 5 + .t.l insert 0 "Short" "Somewhat longer" "Really, quite a whole lot longer than can possibly fit on the screen" "Short" a b c d e f g h i j + pack .t.l + update + .t.l scan mark 100 140 + .t.l scan dragto 90 137 + update + list [.t.l xview] [.t.l yview] +} {{0.249364 0.427481} {0.0714286 0.428571}} +test listbox-3.79 {ListboxWidgetCmd procedure, "scan" option} { + list [catch {.l scan foo 2 4} msg] $msg +} {1 {bad scan option "foo": must be mark or dragto}} +test listbox-3.80 {ListboxWidgetCmd procedure, "see" option} { + list [catch {.l see} msg] $msg +} {1 {wrong # args: should be ".l see index"}} +test listbox-3.81 {ListboxWidgetCmd procedure, "see" option} { + list [catch {.l see a b} msg] $msg +} {1 {wrong # args: should be ".l see index"}} +test listbox-3.82 {ListboxWidgetCmd procedure, "see" option} { + list [catch {.l see gorp} msg] $msg +} {1 {bad listbox index "gorp": must be active, anchor, end, @x,y, or a number}} +test listbox-3.83 {ListboxWidgetCmd procedure, "see" option} { + .l yview 7 + .l see 7 + .l index @0,0 +} {7} +test listbox-3.84 {ListboxWidgetCmd procedure, "see" option} { + .l yview 7 + .l see 11 + .l index @0,0 +} {7} +test listbox-3.85 {ListboxWidgetCmd procedure, "see" option} { + .l yview 7 + .l see 6 + .l index @0,0 +} {6} +test listbox-3.86 {ListboxWidgetCmd procedure, "see" option} { + .l yview 7 + .l see 5 + .l index @0,0 +} {3} +test listbox-3.87 {ListboxWidgetCmd procedure, "see" option} { + .l yview 7 + .l see 12 + .l index @0,0 +} {8} +test listbox-3.88 {ListboxWidgetCmd procedure, "see" option} { + .l yview 7 + .l see 13 + .l index @0,0 +} {11} +test listbox-3.89 {ListboxWidgetCmd procedure, "see" option} { + .l yview 7 + .l see -1 + .l index @0,0 +} {0} +test listbox-3.90 {ListboxWidgetCmd procedure, "see" option} { + .l yview 7 + .l see end + .l index @0,0 +} {13} +test listbox-3.91 {ListboxWidgetCmd procedure, "see" option} { + .l yview 7 + .l see 322 + .l index @0,0 +} {13} +test listbox-3.92 {ListboxWidgetCmd procedure, "see" option, partial last line} { + mkPartial + .partial.l see 4 + .partial.l index @0,0 +} {1} +test listbox-3.93 {ListboxWidgetCmd procedure, "selection" option} { + list [catch {.l select a} msg] $msg +} {1 {wrong # args: should be ".l selection option index ?index?"}} +test listbox-3.94 {ListboxWidgetCmd procedure, "selection" option} { + list [catch {.l select a b c d} msg] $msg +} {1 {wrong # args: should be ".l selection option index ?index?"}} +test listbox-3.95 {ListboxWidgetCmd procedure, "selection" option} { + list [catch {.l selection a bogus} msg] $msg +} {1 {bad listbox index "bogus": must be active, anchor, end, @x,y, or a number}} +test listbox-3.96 {ListboxWidgetCmd procedure, "selection" option} { + list [catch {.l selection a 0 lousy} msg] $msg +} {1 {bad listbox index "lousy": must be active, anchor, end, @x,y, or a number}} +test listbox-3.97 {ListboxWidgetCmd procedure, "selection" option} { + list [catch {.l selection anchor 0 0} msg] $msg +} {1 {wrong # args: should be ".l selection anchor index"}} +test listbox-3.98 {ListboxWidgetCmd procedure, "selection" option} { + list [.l selection anchor 5; .l index anchor] \ + [.l selection anchor 0; .l index anchor] +} {5 0} +test listbox-3.99 {ListboxWidgetCmd procedure, "selection" option} { + .l selection anchor -1 + .l index anchor +} {0} +test listbox-3.100 {ListboxWidgetCmd procedure, "selection" option} { + .l selection anchor end + .l index anchor +} {17} +test listbox-3.101 {ListboxWidgetCmd procedure, "selection" option} { + .l selection anchor 44 + .l index anchor +} {17} +test listbox-3.102 {ListboxWidgetCmd procedure, "selection" option} { + .l selection clear 0 end + .l selection set 2 8 + .l selection clear 3 4 + .l curselection +} {2 5 6 7 8} +test listbox-3.103 {ListboxWidgetCmd procedure, "selection" option} { + list [catch {.l selection includes 0 0} msg] $msg +} {1 {wrong # args: should be ".l selection includes index"}} +test listbox-3.104 {ListboxWidgetCmd procedure, "selection" option} { + .l selection clear 0 end + .l selection set 2 8 + .l selection clear 4 + list [.l selection includes 3] [.l selection includes 4] \ + [.l selection includes 5] +} {1 0 1} +test listbox-3.105 {ListboxWidgetCmd procedure, "selection" option} { + .l selection set 0 end + .l selection includes -1 +} {0} +test listbox-3.106 {ListboxWidgetCmd procedure, "selection" option} { + .l selection clear 0 end + .l selection set end + .l selection includes end +} {1} +test listbox-3.107 {ListboxWidgetCmd procedure, "selection" option} { + .l selection set 0 end + .l selection includes 44 +} {0} +test listbox-3.108 {ListboxWidgetCmd procedure, "selection" option} { + catch {destroy .l2} + listbox .l2 + .l2 selection includes 0 +} {0} +test listbox-3.109 {ListboxWidgetCmd procedure, "selection" option} { + .l selection clear 0 end + .l selection set 2 + .l selection set 5 7 + .l curselection +} {2 5 6 7} +test listbox-3.110 {ListboxWidgetCmd procedure, "selection" option} { + .l selection set 5 7 + .l curselection +} {2 5 6 7} +test listbox-3.111 {ListboxWidgetCmd procedure, "selection" option} { + list [catch {.l selection badOption 0 0} msg] $msg +} {1 {bad selection option "badOption": must be anchor, clear, includes, or set}} +test listbox-3.112 {ListboxWidgetCmd procedure, "size" option} { + list [catch {.l size a} msg] $msg +} {1 {wrong # args: should be ".l size"}} +test listbox-3.113 {ListboxWidgetCmd procedure, "size" option} { + .l size +} {18} +test listbox-3.114 {ListboxWidgetCmd procedure, "xview" option} { + catch {destroy .l2} + listbox .l2 + update + .l2 xview +} {0 1} +test listbox-3.115 {ListboxWidgetCmd procedure, "xview" option} { + catch {destroy .l} + listbox .l -width 10 -height 5 -font $fixed + .l insert 0 a b c d e f g h i j k l m n o p q r s t + pack .l + update + .l xview +} {0 1} +catch {destroy .l} +listbox .l -width 10 -height 5 -font $fixed +.l insert 0 a b c d e f g h i j k l m n o p q r s t +.l insert 1 "0123456789a123456789b123456789c123456789d123456789" +pack .l +update +test listbox-3.116 {ListboxWidgetCmd procedure, "xview" option} {fonts} { + .l xview 4 + .l xview +} {0.08 0.28} +test listbox-3.117 {ListboxWidgetCmd procedure, "xview" option} { + list [catch {.l xview foo} msg] $msg +} {1 {expected integer but got "foo"}} +test listbox-3.118 {ListboxWidgetCmd procedure, "xview" option} { + list [catch {.l xview zoom a b} msg] $msg +} {1 {unknown option "zoom": must be moveto or scroll}} +test listbox-3.119 {ListboxWidgetCmd procedure, "xview" option} {fonts} { + .l xview 0 + .l xview moveto .4 + update + .l xview +} {0.4 0.6} +test listbox-3.120 {ListboxWidgetCmd procedure, "xview" option} {fonts} { + .l xview 0 + .l xview scroll 2 units + update + .l xview +} {0.04 0.24} +test listbox-3.121 {ListboxWidgetCmd procedure, "xview" option} {fonts} { + .l xview 30 + .l xview scroll -1 pages + update + .l xview +} {0.44 0.64} +test listbox-3.122 {ListboxWidgetCmd procedure, "xview" option} {fonts} { + .l configure -width 1 + update + .l xview 30 + .l xview scroll -4 pages + update + .l xview +} {0.52 0.54} +test listbox-3.123 {ListboxWidgetCmd procedure, "yview" option} { + catch {destroy .l} + listbox .l + pack .l + update + .l yview +} {0 1} +test listbox-3.124 {ListboxWidgetCmd procedure, "yview" option} { + catch {destroy .l} + listbox .l + .l insert 0 el1 + pack .l + update + .l yview +} {0 1} +catch {destroy .l} +listbox .l -width 10 -height 5 -font $fixed +.l insert 0 a b c d e f g h i j k l m n o p q r s t +pack .l +update +test listbox-3.125 {ListboxWidgetCmd procedure, "yview" option} { + .l yview 4 + update + .l yview +} {0.2 0.45} +test listbox-3.126 {ListboxWidgetCmd procedure, "yview" option, partial last line} { + mkPartial + .partial.l yview +} {0 0.266667} +test listbox-3.127 {ListboxWidgetCmd procedure, "xview" option} { + list [catch {.l yview foo} msg] $msg +} {1 {bad listbox index "foo": must be active, anchor, end, @x,y, or a number}} +test listbox-3.128 {ListboxWidgetCmd procedure, "xview" option} { + list [catch {.l yview foo a b} msg] $msg +} {1 {unknown option "foo": must be moveto or scroll}} +test listbox-3.129 {ListboxWidgetCmd procedure, "xview" option} { + .l yview 0 + .l yview moveto .31 + .l yview +} {0.3 0.55} +test listbox-3.130 {ListboxWidgetCmd procedure, "xview" option} { + .l yview 2 + .l yview scroll 2 pages + .l yview +} {0.4 0.65} +test listbox-3.131 {ListboxWidgetCmd procedure, "xview" option} { + .l yview 10 + .l yview scroll -3 units + .l yview +} {0.35 0.6} +test listbox-3.132 {ListboxWidgetCmd procedure, "xview" option} { + .l configure -height 2 + update + .l yview 15 + .l yview scroll -4 pages + .l yview +} {0.55 0.65} +test listbox-3.133 {ListboxWidgetCmd procedure, "xview" option} { + list [catch {.l whoknows} msg] $msg +} {1 {bad option "whoknows": must be activate, bbox, cget, configure, curselection, delete, get, index, insert, nearest, scan, see, selection, size, xview, or yview}} +test listbox-3.134 {ListboxWidgetCmd procedure, "xview" option} { + list [catch {.l c} msg] $msg +} {1 {bad option "c": must be activate, bbox, cget, configure, curselection, delete, get, index, insert, nearest, scan, see, selection, size, xview, or yview}} +test listbox-3.135 {ListboxWidgetCmd procedure, "xview" option} { + list [catch {.l in} msg] $msg +} {1 {bad option "in": must be activate, bbox, cget, configure, curselection, delete, get, index, insert, nearest, scan, see, selection, size, xview, or yview}} +test listbox-3.136 {ListboxWidgetCmd procedure, "xview" option} { + list [catch {.l s} msg] $msg +} {1 {bad option "s": must be activate, bbox, cget, configure, curselection, delete, get, index, insert, nearest, scan, see, selection, size, xview, or yview}} +test listbox-3.137 {ListboxWidgetCmd procedure, "xview" option} { + list [catch {.l se} msg] $msg +} {1 {bad option "se": must be activate, bbox, cget, configure, curselection, delete, get, index, insert, nearest, scan, see, selection, size, xview, or yview}} + +# No tests for DestroyListbox: I can't come up with anything to test +# in this procedure. + +test listbox-4.1 {ConfigureListbox procedure} {fonts} { + catch {destroy .l} + listbox .l -setgrid 1 -width 25 -height 15 + pack .l + update + set x [getsize .] + .l configure -setgrid 0 + update + list $x [getsize .] +} {25x15 185x263} +resetGridInfo +test listbox-4.2 {ConfigureListbox procedure} { + .l configure -highlightthickness -3 + .l cget -highlightthickness +} {0} +test listbox-4.3 {ConfigureListbox procedure} { + .l configure -exportselection 0 + .l delete 0 end + .l insert 0 el0 el1 el2 el3 el4 el5 el6 el7 el8 + .l selection set 3 5 + .l configure -exportselection 1 + selection get +} {el3 +el4 +el5} +test listbox-4.4 {ConfigureListbox procedure} { + catch {destroy .e} + entry .e + .e insert 0 abc + .e select from 0 + .e select to 2 + .l configure -exportselection 0 + .l delete 0 end + .l insert 0 el0 el1 el2 el3 el4 el5 el6 el7 el8 + .l selection set 3 5 + .l selection clear 3 5 + .l configure -exportselection 1 + list [selection own] [selection get] +} {.e ab} +test listbox-4.5 {-exportselection option} { + selection clear . + .l configure -exportselection 1 + .l delete 0 end + .l insert 0 el0 el1 el2 el3 el4 el5 el6 el7 el8 + .l selection set 1 1 + set x {} + lappend x [catch {selection get} msg] $msg [.l curselection] + .l config -exportselection 0 + lappend x [catch {selection get} msg] $msg [.l curselection] + .l selection clear 0 end + lappend x [catch {selection get} msg] $msg [.l curselection] + .l selection set 1 3 + lappend x [catch {selection get} msg] $msg [.l curselection] + .l config -exportselection 1 + lappend x [catch {selection get} msg] $msg [.l curselection] +} {0 el1 1 1 {PRIMARY selection doesn't exist or form "STRING" not defined} 1 1 {PRIMARY selection doesn't exist or form "STRING" not defined} {} 1 {PRIMARY selection doesn't exist or form "STRING" not defined} {1 2 3} 0 {el1 +el2 +el3} {1 2 3}} +test listbox-4.6 {ConfigureListbox procedure} {fonts} { + catch {destroy .l} + + # The following code (reset geometry, withdraw, etc.) is necessary + # to reset the state of some window managers like olvwm under + # SunOS 4.1.3. + + wm geom . 300x300 + update + wm geom . {} + wm withdraw . + listbox .l -font $fixed -width 15 -height 20 + pack .l + update + wm deiconify . + set x [getsize .] + .l configure -setgrid 1 + update + list $x [getsize .] +} {115x328 15x20} +test listbox-4.7 {ConfigureListbox procedure} { + catch {destroy .l} + wm withdraw . + listbox .l -font $fixed -width 30 -height 20 -setgrid 1 + wm geom . +0+0 + pack .l + update + wm deiconify . + set result [getsize .] + wm geom . 26x15 + update + lappend result [getsize .] + .l configure -setgrid 1 + update + lappend result [getsize .] +} {30x20 26x15 26x15} +wm geom . {} +catch {destroy .l} +resetGridInfo +test listbox-4.8 {ConfigureListbox procedure} { + catch {destroy .l} + listbox .l -width 15 -height 20 -xscrollcommand "record x" \ + -yscrollcommand "record y" + pack .l + update + .l configure -fg black + set log {} + update + set log +} {{y 0 1} {x 0 1}} + +# No tests for DisplayListbox: I don't know how to test this procedure. + +test listbox-5.1 {ListboxComputeGeometry procedure} {fonts} { + catch {destroy .l} + listbox .l -font $fixed -width 15 -height 20 + pack .l + list [winfo reqwidth .l] [winfo reqheight .l] +} {115 328} +test listbox-5.2 {ListboxComputeGeometry procedure} {fonts} { + catch {destroy .l} + listbox .l -font $fixed -width 0 -height 10 + pack .l + update + list [winfo reqwidth .l] [winfo reqheight .l] +} {17 168} +test listbox-5.3 {ListboxComputeGeometry procedure} {fonts} { + catch {destroy .l} + listbox .l -font $fixed -width 0 -height 10 -bd 3 + .l insert 0 Short "Really much longer" Longer + pack .l + update + list [winfo reqwidth .l] [winfo reqheight .l] +} {138 170} +test listbox-5.4 {ListboxComputeGeometry procedure} {fonts} { + catch {destroy .l} + listbox .l -font $fixed -width 10 -height 0 + pack .l + update + list [winfo reqwidth .l] [winfo reqheight .l] +} {80 24} +test listbox-5.5 {ListboxComputeGeometry procedure} {fonts} { + catch {destroy .l} + listbox .l -font $fixed -width 10 -height 0 -highlightthickness 0 + .l insert 0 Short "Really much longer" Longer + pack .l + update + list [winfo reqwidth .l] [winfo reqheight .l] +} {76 52} +test listbox-5.6 {ListboxComputeGeometry procedure} { + # If "0" in selected font had 0 width, caused divide-by-zero error. + + catch {destroy .l} + pack [listbox .l -font {{open look glyph}}] + update +} {} + + +catch {destroy .l} +listbox .l -height 2 -xscrollcommand "record x" -yscrollcommand "record y" +pack .l +update +test listbox-6.1 {InsertEls procedure} { + .l delete 0 end + .l insert end a b c d + .l insert 5 x y z + .l insert 2 A + .l insert 0 q r s + .l get 0 end +} {q r s a b A c d x y z} +test listbox-6.2 {InsertEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l selection anchor 2 + .l insert 2 A B + .l index anchor +} {4} +test listbox-6.3 {InsertEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l selection anchor 2 + .l insert 3 A B + .l index anchor +} {2} +test listbox-6.4 {InsertEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l yview 3 + update + .l insert 2 A B + .l index @0,0 +} {5} +test listbox-6.5 {InsertEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l yview 3 + update + .l insert 3 A B + .l index @0,0 +} {3} +test listbox-6.6 {InsertEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l activate 5 + .l insert 5 A B + .l index active +} {7} +test listbox-6.7 {InsertEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l activate 5 + .l insert 6 A B + .l index active +} {5} +test listbox-6.8 {InsertEls procedure} { + .l delete 0 end + .l insert 0 a b c + .l index active +} {2} +test listbox-6.9 {InsertEls procedure} { + .l delete 0 end + .l insert 0 + .l index active +} {0} +test listbox-6.10 {InsertEls procedure} { + .l delete 0 end + .l insert 0 a b "two words" c d e f g h i j + update + set log {} + .l insert 0 word + update + set log +} {{y 0 0.166667}} +test listbox-6.11 {InsertEls procedure} { + .l delete 0 end + .l insert 0 a b "two words" c d e f g h i j + update + set log {} + .l insert 0 "much longer entry" + update + set log +} {{y 0 0.166667} {x 0 1}} +test listbox-6.12 {InsertEls procedure} {fonts} { + catch {destroy .l2} + listbox .l2 -width 0 -height 0 + pack .l2 -side top + .l2 insert 0 a b "two words" c d + set x {} + lappend x [winfo reqwidth .l2] [winfo reqheight .l2] + .l2 insert 0 "much longer entry" + lappend x [winfo reqwidth .l2] [winfo reqheight .l2] +} {80 93 122 110} + +test listbox-7.1 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l selection set 1 6 + .l delete 4 3 + list [.l size] [selection get] +} {10 {b +c +d +e +f +g}} +test listbox-7.2 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l selection set 3 6 + .l delete 4 4 + list [.l size] [.l get 4] [.l curselection] +} {9 f {3 4 5}} +test listbox-7.3 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l delete 0 3 + list [.l size] [.l get 0] [.l get 1] +} {6 e f} +test listbox-7.4 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l delete 8 1000 + list [.l size] [.l get 7] +} {8 h} +test listbox-7.5 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l selection anchor 2 + .l delete 0 1 + .l index anchor +} {0} +test listbox-7.6 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l selection anchor 2 + .l delete 2 + .l index anchor +} {2} +test listbox-7.7 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l selection anchor 4 + .l delete 2 5 + .l index anchor +} {2} +test listbox-7.8 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l selection anchor 3 + .l delete 4 5 + .l index anchor +} {3} +test listbox-7.9 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l yview 3 + update + .l delete 1 2 + .l index @0,0 +} {1} +test listbox-7.10 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l yview 3 + update + .l delete 3 4 + .l index @0,0 +} {3} +test listbox-7.11 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l yview 3 + update + .l delete 4 6 + .l index @0,0 +} {3} +test listbox-7.12 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l yview 3 + update + .l delete 3 end + .l index @0,0 +} {1} +test listbox-7.13 {DeleteEls procedure, updating view with partial last line} { + mkPartial + .partial.l yview 8 + update + .partial.l delete 10 13 + .partial.l index @0,0 +} {7} +test listbox-7.14 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l activate 6 + .l delete 3 4 + .l index active +} {4} +test listbox-7.15 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l activate 6 + .l delete 5 7 + .l index active +} {5} +test listbox-7.16 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l activate 6 + .l delete 5 end + .l index active +} {4} +test listbox-7.17 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j + .l activate 6 + .l delete 0 end + .l index active +} {0} +test listbox-7.18 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c "two words" d e f g h i j + update + set log {} + .l delete 4 6 + update + set log +} {{y 0 0.25}} +test listbox-7.19 {DeleteEls procedure} { + .l delete 0 end + .l insert 0 a b c "two words" d e f g h i j + update + set log {} + .l delete 3 + update + set log +} {{y 0 0.2} {x 0 1}} +test listbox-7.20 {DeleteEls procedure} {fonts} { + catch {destroy .l2} + listbox .l2 -width 0 -height 0 + pack .l2 -side top + .l2 insert 0 a b "two words" c d e f g + set x {} + lappend x [winfo reqwidth .l2] [winfo reqheight .l2] + .l2 delete 2 4 + lappend x [winfo reqwidth .l2] [winfo reqheight .l2] +} {80 144 17 93} +catch {destroy .l2} + +test listbox-8.1 {ListboxEventProc procedure} {fonts} { + catch {destroy .l} + listbox .l -setgrid 1 + pack .l + update + set x [getsize .] + destroy .l + list $x [getsize .] [winfo exists .l] [info command .l] +} {20x10 150x178 0 {}} +resetGridInfo +test listbox-8.2 {ListboxEventProc procedure} {fonts} { + catch {destroy .l} + listbox .l -height 5 -width 10 + .l insert 0 a b c "A string that is very very long" d e f g h i j k + pack .l + update + place .l -width 50 -height 80 + update + list [.l xview] [.l yview] +} {{0 0.222222} {0 0.333333}} +test listbox-8.3 {ListboxEventProc procedure} { + eval destroy [winfo children .] + listbox .l1 -bg #543210 + rename .l1 .l2 + set x {} + lappend x [winfo children .] + lappend x [.l2 cget -bg] + destroy .l1 + lappend x [info command .l*] [winfo children .] +} {.l1 #543210 {} {}} + +test listbox-9.1 {ListboxCmdDeletedProc procedure} { + eval destroy [winfo children .] + listbox .l1 + rename .l1 {} + list [info command .l*] [winfo children .] +} {{} {}} +test listbox-9.2 {ListboxCmdDeletedProc procedure, disabling -setgrid} fonts { + catch {destroy .top} + toplevel .top + wm geom .top +0+0 + listbox .top.l -setgrid 1 -width 20 -height 10 + pack .top.l + update + set x [wm geometry .top] + rename .top.l {} + update + lappend x [wm geometry .top] + destroy .top + set x +} {20x10+0+0 150x178+0+0} + +catch {destroy .l} +listbox .l +pack .l +.l delete 0 end +.l insert 0 el0 el1 el2 el3 el4 el5 el6 el7 el8 el9 el10 el11 +test listbox-10.1 {GetListboxIndex procedure} { + .l activate 3 + list [.l activate 3; .l index active] [.l activate 6; .l index active] +} {3 6} +test listbox-10.2 {GetListboxIndex procedure} { + .l selection anchor 2 + .l index anchor +} 2 +test listbox-10.3 {GetListboxIndex procedure} { + .l insert end A B C D E + .l selection anchor end + .l delete 12 end + list [.l index anchor] [.l index end] +} {12 12} +test listbox-10.4 {GetListboxIndex procedure} { + list [catch {.l index a} msg] $msg +} {1 {bad listbox index "a": must be active, anchor, end, @x,y, or a number}} +test listbox-10.5 {GetListboxIndex procedure} { + .l index end +} {12} +test listbox-10.6 {GetListboxIndex procedure} { + .l get end +} {el11} +test listbox-10.7 {GetListboxIndex procedure} { + .l delete 0 end + .l index end +} 0 +.l delete 0 end +.l insert 0 el0 el1 el2 el3 el4 el5 el6 el7 el8 el9 el10 el11 +update +test listbox-10.8 {GetListboxIndex procedure} { + list [catch {.l index @} msg] $msg +} {1 {bad listbox index "@": must be active, anchor, end, @x,y, or a number}} +test listbox-10.9 {GetListboxIndex procedure} { + list [catch {.l index @foo} msg] $msg +} {1 {bad listbox index "@foo": must be active, anchor, end, @x,y, or a number}} +test listbox-10.10 {GetListboxIndex procedure} { + list [catch {.l index @1x3} msg] $msg +} {1 {bad listbox index "@1x3": must be active, anchor, end, @x,y, or a number}} +test listbox-10.11 {GetListboxIndex procedure} { + list [catch {.l index @1,} msg] $msg +} {1 {bad listbox index "@1,": must be active, anchor, end, @x,y, or a number}} +test listbox-10.12 {GetListboxIndex procedure} { + list [catch {.l index @1,foo} msg] $msg +} {1 {bad listbox index "@1,foo": must be active, anchor, end, @x,y, or a number}} +test listbox-10.13 {GetListboxIndex procedure} { + list [catch {.l index @1,2x} msg] $msg +} {1 {bad listbox index "@1,2x": must be active, anchor, end, @x,y, or a number}} +test listbox-10.14 {GetListboxIndex procedure} {fonts} { + list [.l index @5,57] [.l index @5,58] +} {3 3} +test listbox-10.15 {GetListboxIndex procedure} { + list [catch {.l index 1xy} msg] $msg +} {1 {bad listbox index "1xy": must be active, anchor, end, @x,y, or a number}} +test listbox-10.16 {GetListboxIndex procedure} { + .l index 3 +} {3} +test listbox-10.17 {GetListboxIndex procedure} { + .l index 20 +} {20} +test listbox-10.18 {GetListboxIndex procedure} { + .l get 20 +} {} +test listbox-10.19 {GetListboxIndex procedure} { + .l index -2 +} -2 +test listbox-10.20 {GetListboxIndex procedure} { + .l delete 0 end + .l index 1 +} 1 + +test listbox-11.1 {ChangeListboxView procedure, boundary conditions for index} { + catch {destroy .l} + listbox .l -height 5 + pack .l + .l insert 0 a b c d e f g h i j + .l yview 3 + update + set x [.l index @0,0] + .l yview -1 + update + lappend x [.l index @0,0] +} {3 0} +test listbox-11.2 {ChangeListboxView procedure, boundary conditions for index} { + catch {destroy .l} + listbox .l -height 5 + pack .l + .l insert 0 a b c d e f g h i j + .l yview 3 + update + set x [.l index @0,0] + .l yview 20 + update + lappend x [.l index @0,0] +} {3 5} +test listbox-11.3 {ChangeListboxView procedure} { + catch {destroy .l} + listbox .l -height 5 -yscrollcommand "record y" + pack .l + .l insert 0 a b c d e f g h i j + update + set log {} + .l yview 2 + update + list [.l yview] $log +} {{0.2 0.7} {{y 0.2 0.7}}} +test listbox-11.4 {ChangeListboxView procedure} { + catch {destroy .l} + listbox .l -height 5 -yscrollcommand "record y" + pack .l + .l insert 0 a b c d e f g h i j + update + set log {} + .l yview 8 + update + list [.l yview] $log +} {{0.5 1} {{y 0.5 1}}} +test listbox-11.5 {ChangeListboxView procedure} { + catch {destroy .l} + listbox .l -height 5 -yscrollcommand "record y" + pack .l + .l insert 0 a b c d e f g h i j + .l yview 3 + update + set log {} + .l yview 3 + update + list [.l yview] $log +} {{0.3 0.8} {}} +test listbox-11.6 {ChangeListboxView procedure, partial last line} { + mkPartial + .partial.l yview 13 + .partial.l index @0,0 +} {11} + +catch {destroy .l} +listbox .l -font $fixed -xscrollcommand "record x" -width 10 +.l insert 0 0123456789a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789 +pack .l +update +test listbox-12.1 {ChangeListboxOffset procedure} {fonts} { + set log {} + .l xview 99 + update + list [.l xview] $log +} {{0.9 1} {{x 0.9 1}}} +test listbox-12.2 {ChangeListboxOffset procedure} {fonts} { + set log {} + .l xview moveto -.25 + update + list [.l xview] $log +} {{0 0.1} {{x 0 0.1}}} +test listbox-12.3 {ChangeListboxOffset procedure} {fonts} { + .l xview 10 + update + set log {} + .l xview 10 + update + list [.l xview] $log +} {{0.1 0.2} {}} + +catch {destroy .l} +listbox .l -font $fixed -width 10 -height 5 +pack .l +.l insert 0 a bb c d e f g h i j k l m n o p q r s +.l insert 0 0123456789a123456789b123456789c123456789d123456789 +update +set width [expr [lindex [.l bbox 2] 2] - [lindex [.l bbox 1] 2]] +set height [expr [lindex [.l bbox 2] 1] - [lindex [.l bbox 1] 1]] +test listbox-13.1 {ListboxScanTo procedure} {fonts} { + .l yview 0 + .l xview 0 + .l scan mark 10 20 + .l scan dragto [expr 10-$width] [expr 20-$height] + update + list [.l xview] [.l yview] +} {{0.2 0.4} {0.5 0.75}} +test listbox-13.2 {ListboxScanTo procedure} {fonts} { + .l yview 5 + .l xview 10 + .l scan mark 10 20 + .l scan dragto 20 40 + update + set x [list [.l xview] [.l yview]] + .l scan dragto [expr 20-$width] [expr 40-$height] + update + lappend x [.l xview] [.l yview] +} {{0 0.2} {0 0.25} {0.2 0.4} {0.5 0.75}} +test listbox-13.3 {ListboxScanTo procedure} {fonts} { + .l yview moveto 1.0 + .l xview moveto 1.0 + .l scan mark 10 20 + .l scan dragto 5 10 + update + set x [list [.l xview] [.l yview]] + .l scan dragto [expr 5+$width] [expr 10+$height] + update + lappend x [.l xview] [.l yview] +} {{0.8 1} {0.75 1} {0.62 0.82} {0.25 0.5}} + +test listbox-14.1 {NearestListboxElement procedure, partial last line} { + mkPartial + .partial.l nearest [winfo height .partial.l] +} {4} +catch {destroy .l} +listbox .l -font $fixed -width 20 -height 10 +.l insert 0 a b c d e f g h i j k l m n o p q r s t +.l yview 4 +pack .l +update +test listbox-14.2 {NearestListboxElement procedure} {fonts} { + .l index @50,0 +} {4} +test listbox-14.3 {NearestListboxElement procedure} {fonts} { + list [.l index @50,35] [.l index @50,36] +} {5 6} +test listbox-14.4 {NearestListboxElement procedure} {fonts} { + .l index @50,200 +} {13} + +test listbox-15.1 {ListboxSelect procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j k l m n o p + .l select set 2 4 + .l select set 7 12 + .l select clear 4 7 + .l curselection +} {2 3 8 9 10 11 12} +test listbox-15.2 {ListboxSelect procedure} { + .l delete 0 end + .l insert 0 a b c d e f g h i j k l m n o p + catch {destroy .e} + entry .e + .e insert 0 "This is some text" + .e select from 0 + .e select to 7 + .l selection clear 2 4 + set x [selection own] + .l selection set 3 + list $x [selection own] [selection get] +} {.e .l d} +test listbox-15.3 {ListboxSelect procedure} { + .l delete 0 end + .l selection clear 0 end + .l select set 0 end + .l curselection +} {} +test listbox-15.4 {ListboxSelect procedure, boundary conditions for indices} { + .l delete 0 end + .l insert 0 a b c d e f + .l select clear 0 end + .l select set -2 -1 + .l curselection +} {} +test listbox-15.5 {ListboxSelect procedure, boundary conditions for indices} { + .l delete 0 end + .l insert 0 a b c d e f + .l select clear 0 end + .l select set -1 3 + .l curselection +} {0 1 2 3} +test listbox-15.6 {ListboxSelect procedure, boundary conditions for indices} { + .l delete 0 end + .l insert 0 a b c d e f + .l select clear 0 end + .l select set 2 4 + .l curselection +} {2 3 4} +test listbox-15.7 {ListboxSelect procedure, boundary conditions for indices} { + .l delete 0 end + .l insert 0 a b c d e f + .l select clear 0 end + .l select set 4 end + .l curselection +} {4 5} +test listbox-15.8 {ListboxSelect procedure, boundary conditions for indices} { + .l delete 0 end + .l insert 0 a b c d e f + .l select clear 0 end + .l select set 4 30 + .l curselection +} {4 5} +test listbox-15.9 {ListboxSelect procedure, boundary conditions for indices} { + .l delete 0 end + .l insert 0 a b c d e f + .l select clear 0 end + .l select set end 30 + .l curselection +} {5} +test listbox-15.10 {ListboxSelect procedure, boundary conditions for indices} { + .l delete 0 end + .l insert 0 a b c d e f + .l select clear 0 end + .l select set 20 25 + .l curselection +} {} + +test listbox-16.1 {ListboxFetchSelection procedure} { + .l delete 0 end + .l insert 0 a b c "two words" e f g h i \\ k l m n o p + .l selection set 2 4 + .l selection set 9 + .l selection set 11 12 + selection get +} "c\ntwo words\ne\n\\\nl\nm" +test listbox-16.2 {ListboxFetchSelection procedure} { + .l delete 0 end + .l insert 0 a b c "two words" e f g h i \\ k l m n o p + .l selection set 3 + selection get +} "two words" +test listbox-16.3 {ListboxFetchSelection procedure, retrieve in several parts} { + set long "This is quite a long string\n" + append long $long $long $long $long + append long $long $long $long $long + append long $long $long + .l delete 0 end + .l insert 0 1$long 2$long 3$long 4$long 5$long + .l selection set 0 end + set sel [selection get] + string compare 1$long\n2$long\n3$long\n4$long\n5$long $sel +} {0} +catch {unset long sel} + +test listbox-17.1 {ListboxLostSelection procedure} { + .l delete 0 end + .l insert 0 a b c d e + .l select set 0 end + catch {destroy .e} + entry .e + .e insert 0 "This is some text" + .e select from 0 + .e select to 5 + .l curselection +} {} +test listbox-17.2 {ListboxLostSelection procedure} { + .l delete 0 end + .l insert 0 a b c d e + .l select set 0 end + .l configure -exportselection 0 + catch {destroy .e} + entry .e + .e insert 0 "This is some text" + .e select from 0 + .e select to 5 + .l curselection +} {0 1 2 3 4} + +catch {destroy .l} +listbox .l -font $fixed -width 10 -height 5 +pack .l +update +test listbox-18.1 {ListboxUpdateVScrollbar procedure} { + .l configure -yscrollcommand "record y" + set log {} + .l insert 0 a b c + update + .l insert end d e f g h + update + .l delete 0 end + update + set log +} {{y 0 1} {y 0 0.625} {y 0 1}} +test listbox-18.2 {ListboxUpdateVScrollbar procedure, partial last line} { + mkPartial + .partial.l configure -yscrollcommand "record y" + set log {} + .partial.l yview 3 + update + set log +} {{y 0.2 0.466667}} +test listbox-18.3 {ListboxUpdateVScrollbar procedure} { + proc bgerror args { + global x errorInfo + set x [list $args $errorInfo] + } + .l configure -yscrollcommand gorp + .l insert 0 foo + update + set x +} {{{invalid command name "gorp"}} {invalid command name "gorp" + while executing +"gorp 0 1" + (vertical scrolling command executed by listbox)}} +if {[info exists bgerror]} { + rename bgerror {} +} + +catch {destroy .l} +listbox .l -font $fixed -width 10 -height 5 +pack .l +update +test listbox-19.1 {ListboxUpdateVScrollbar procedure} {fonts} { + .l configure -xscrollcommand "record x" + set log {} + .l insert 0 abc + update + .l insert 0 "This is a much longer string..." + update + .l delete 0 end + update + set log +} {{x 0 1} {x 0 0.322581} {x 0 1}} +test listbox-19.2 {ListboxUpdateVScrollbar procedure} { + proc bgerror args { + global x errorInfo + set x [list $args $errorInfo] + } + .l configure -xscrollcommand bogus + .l insert 0 foo + update + set x +} {{{invalid command name "bogus"}} {invalid command name "bogus" + while executing +"bogus 0 1" + (horizontal scrolling command executed by listbox)}} + +set l [interp hidden] +eval destroy [winfo children .] + +test listbox-20.1 {listbox vs hidden commands} { + catch {destroy .l} + listbox .l + interp hide {} .l + destroy .l + list [winfo children .] [interp hidden] +} [list {} $l] + +resetGridInfo +catch {destroy .l2} +catch {destroy .t} +catch {destroy .e} +catch {destroy .partial} +option clear + diff --git a/tests/macEmbed.test b/tests/macEmbed.test new file mode 100644 index 0000000..f912dcd --- /dev/null +++ b/tests/macEmbed.test @@ -0,0 +1,290 @@ +# This file is a Tcl script to test out the procedures in the file +# tkMacEmbed.c. It is organized in the standard fashion for Tcl +# tests. +# +# Copyright (c) 1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) macEmbed.test 1.1 97/08/06 21:18:53 + +if {$tcl_platform(platform) != "macintosh"} { + return +} + +if {[info procs test] != "test"} { + source defs +} + +eval destroy [winfo children .] +wm geometry . {} +raise . + + +test macEmbed-1.1 {TkpUseWindow procedure, bad window identifier} { + catch {destroy .t} + list [catch {toplevel .t -use xyz} msg] $msg +} {1 {expected integer but got "xyz"}} +test macEmbed-1.2 {TkpUseWindow procedure, bad window identifier} { + catch {destroy .t} + list [catch {toplevel .t -use 47} msg] $msg +} {1 {The window ID 47 does not correspond to a valid Tk Window.}} +test macEmbed-1.3 {TkpUseWindow procedure, creating Container records} { + eval destroy [winfo child .] + frame .f1 -container 1 -width 200 -height 50 + frame .f2 -container 1 -width 200 -height 50 + pack .f1 .f2 + set w [winfo id .f1] + toplevel .t -use $w + list [testembed] [expr [lindex [lindex [testembed all] 1] 0] - $w] +} {{{XXX .f2 {} {}} {XXX .f1 XXX .t}} 0} +test macEmbed-1.4 {TkpUseWindow procedure, creating Container records} { + eval destroy [winfo child .] + frame .f1 -container 1 -width 200 -height 50 + frame .f2 -container 1 -width 200 -height 50 + pack .f1 .f2 + set w1 [winfo id .f1] + set w2 [winfo id .f2] + toplevel .t1 -use $w1 + toplevel .t2 -use $w2 + testembed +} {{XXX .f2 XXX .t2} {XXX .f1 XXX .t1}} + +# Can't think of any way to test the procedures TkpMakeWindow, +# TkpMakeContainer, or EmbedErrorProc. + +test macEmbed-2.1 {EmbeddedEventProc procedure} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + set w1 [winfo id .f1] + toplevel .t1 -use $w1 + testembed + destroy .t1 + update + testembed +} {} +test macEmbed-2.2 {EmbeddedEventProc procedure} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + toplevel .t1 -use [winfo id .f1] + update + destroy .f1 + testembed +} {} +test macEmbed-2.3 {EmbeddedEventProc procedure} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + toplevel .t1 -use [winfo id .f1] + update + destroy .t1 + update + list [testembed] [winfo children .] +} {{} {}} + +test macEmbed-3.1 {EmbeddedEventProc procedure, detect creation} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + set w1 [winfo id .f1] + set x [testembed] + toplevel .t1 -use $w1 + wm withdraw .t1 + list $x [testembed] +} {{{XXX .f1 {} {}}} {{XXX .f1 XXX .t1}}} +test macEmbed-3.2 {EmbeddedEventProc procedure, disallow position changes} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + set w1 [winfo id .f1] + toplevel .t1 -use $w1 -bd 2 -relief raised + update + wm geometry .t1 +30+40 + update + wm geometry .t1 +} {200x200+0+0} +test macEmbed-3.3 {EmbeddedEventProc procedure, disallow position changes} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + set w1 [winfo id .f1] + toplevel .t1 -use $w1 + update + wm geometry .t1 300x100+30+40 + update + wm geometry .t1 +} {300x100+0+0} +test macEmbed-3.4 {EmbeddedEventProc procedure, geometry requests} { + foreach w [winfo child .] { + catch {destroy $w} + } + toplevel .t1 -container 1 -width 200 -height 50 + set w1 [winfo id .t1] + toplevel .t2 -use $w1 + update + .t1 configure -width 300 -height 80 + update + list [winfo width .t1] [winfo height .t1] [wm geometry .t2] +} {300 80 300x80+0+0} +test macEmbed-3.5 {EmbeddedEventProc procedure, map requests} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + set w1 [winfo id .f1] + toplevel .t1 -use $w1 + set x unmapped + bind .t1 <Map> {set x mapped} + update + after 100 + update + set x +} {mapped} +test macEmbed-3.6 {EmbeddedEventProc procedure, destroy events} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + set w1 [winfo id .f1] + bind .f1 <Destroy> {set x dead} + set x alive + toplevel .t1 -use $w1 + update + destroy .t1 + update + list $x [winfo exists .f1] +} {dead 0} + +test macEmbed-4.1 {EmbedStructureProc procedure, configure events} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + set w1 [winfo id .f1] + toplevel .t1 -use $w1 + update + .t1 configure -width 180 -height 100 + update + winfo geometry .t1 +} {180x100+0+0} +test macEmbed-4.2 {EmbedStructureProc procedure, destroy events} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + set w1 [winfo id .f1] + toplevel .t1 -use $w1 + update + set x [testembed] + destroy .f1 + list $x [testembed] +} {{{XXX .f1 XXX .t1}} {}} + +# Can't think up any tests for TkpGetOtherWindow procedure. + +test unixEmbed-5.1 {TkpClaimFocus procedure} {tempNotMac} { + catch {interp delete child} + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + frame .f2 -width 200 -height 50 + pack .f1 .f2 + interp create child + child eval "set argv {-use [winfo id .f1]}" + load {} tk child + child eval { + . configure -bd 2 -highlightthickness 2 -relief sunken + } + focus -force .f2 + update + list [child eval { + focus . + set x [list [focus]] + update + lappend x [focus] + }] [focus] +} {{{} .} .f1} +catch {interp delete child} + +test macEmbed-6.1 {EmbedWindowDeleted procedure, check parentPtr} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + frame .f2 -container 1 -width 200 -height 50 + frame .f3 -container 1 -width 200 -height 50 + frame .f4 -container 1 -width 200 -height 50 + pack .f1 .f2 .f3 .f4 + set x {} + lappend x [testembed] + foreach w {.f3 .f4 .f1 .f2} { + destroy $w + lappend x [testembed] + } + set x +} {{{XXX .f4 {} {}} {XXX .f3 {} {}} {XXX .f2 {} {}} {XXX .f1 {} {}}} {{XXX .f4 {} {}} {XXX .f2 {} {}} {XXX .f1 {} {}}} {{XXX .f2 {} {}} {XXX .f1 {} {}}} {{XXX .f2 {} {}}} {}} +test macEmbed-6.2 {EmbedWindowDeleted procedure, check embeddedPtr} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + set w1 [winfo id .f1] + toplevel .t1 -use $w1 -highlightthickness 2 -bd 2 -relief sunken + set x {} + lappend x [testembed] + destroy .t1 + update + lappend x [testembed] +} {{{XXX .f1 XXX .t1}} {}} + +test macEmbed-7.1 {geometry propagation in tkUnixWm.c/UpdateGeometryInfo} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + toplevel .t1 -use [winfo id .f1] -width 150 -height 80 + update + wm geometry .t1 +40+50 + update + wm geometry .t1 +} {150x80+0+0} +test macEmbed-7.2 {geometry propagation in tkUnixWm.c/UpdateGeometryInfo} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + toplevel .t1 -use [winfo id .f1] -width 150 -height 80 + update + wm geometry .t1 70x300+10+20 + update + wm geometry .t1 +} {70x300+0+0} + + + +foreach w [winfo child .] { + catch {destroy $w} +} diff --git a/tests/macFont.test b/tests/macFont.test new file mode 100644 index 0000000..aa342a6 --- /dev/null +++ b/tests/macFont.test @@ -0,0 +1,182 @@ +# This file is a Tcl script to test out the procedures in tkMacFont.c. +# It is organized in the standard fashion for Tcl tests. +# +# Some of these tests are visually oriented and cannot be checked +# programmatically (such as "does an underlined font appear to be +# underlined?"); these tests attempt to exercise the code in question, +# but there are no results that can be checked. +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) macFont.test 1.5 97/05/05 14:21:05 + +if {$tcl_platform(platform)!="macintosh"} { + return +} + +if {[string compare test [info procs test]] != 0} { + source defs +} + +catch {destroy .b} +toplevel .b +update idletasks + +set courier {Courier 10} +set cx [font measure $courier 0] + +label .b.l -padx 0 -pady 0 -bd 0 -highlightthickness 0 -justify left -text "0" -font "Monaco 9" +pack .b.l +canvas .b.c -closeenough 0 + +set t [.b.c create text 0 0 -anchor nw -just left -font $courier] +pack .b.c +update + +set ax [winfo reqwidth .b.l] +set ay [winfo reqheight .b.l] +proc getsize {} { + update + return "[winfo reqwidth .b.l] [winfo reqheight .b.l]" +} + +test macfont-1.1 {TkpGetNativeFont procedure: not native} { + list [catch {font measure {} xyz} msg] $msg +} {1 {font "" doesn't exist}} +test macfont-1.2 {TkpGetNativeFont procedure: native} { + font measure system "0" + font measure application "0" + set x {} +} {} + +test macfont-2.1 {TkpGetFontFromAttributes procedure: no family} { + font actual {-underline 1} -family +} [font actual system -family] +test macfont-2.2 {TkpGetFontFromAttributes procedure: long family name} { + set x "12345678901234567890123456789012345678901234567890" + set x "$x$x$x$x$x$x" + font actual "-family $x" -family +} [font actual system -family] +test macfont-2.3 {TkpGetFontFromAttributes procedure: family} { + font actual {-family Courier} -family +} {Courier} +test macfont-2.4 {TkpGetFontFromAttributes procedure: Times fonts} { + set x {} + lappend x [font actual {-family "Times"} -family] + lappend x [font actual {-family "Times New Roman"} -family] +} {Times Times} +test macfont-2.5 {TkpGetFontFromAttributes procedure: Courier fonts} { + set x {} + lappend x [font actual {-family "Courier"} -family] + lappend x [font actual {-family "Courier New"} -family] +} {Courier Courier} +test macfont-2.6 {TkpGetFontFromAttributes procedure: Helvetica fonts} { + set x {} + lappend x [font actual {-family "Geneva"} -family] + lappend x [font actual {-family "Helvetica"} -family] + lappend x [font actual {-family "Arial"} -family] +} {Geneva Helvetica Helvetica} +test macfont-2.7 {TkpGetFontFromAttributes procedure: styles} { + font actual {-weight normal} -weight +} {normal} +test macfont-2.8 {TkpGetFontFromAttributes procedure: styles} { + font actual {-weight bold} -weight +} {bold} +test macfont-2.9 {TkpGetFontFromAttributes procedure: styles} { + font actual {-slant roman} -slant +} {roman} +test macfont-2.10 {TkpGetFontFromAttributes procedure: styles} { + font actual {-slant italic} -slant +} {italic} +test macfont-2.11 {TkpGetFontFromAttributes procedure: styles} { + font actual {-underline false} -underline +} {0} +test macfont-2.12 {TkpGetFontFromAttributes procedure: styles} { + font actual {-underline true} -underline +} {1} +test macfont-2.13 {TkpGetFontFromAttributes procedure: styles} { + font actual {-overstrike false} -overstrike +} {0} +test macfont-2.14 {TkpGetFontFromAttributes procedure: styles} { + font actual {-overstrike true} -overstrike +} {0} + +test macfont-3.1 {TkpDeleteFont procedure} { + font actual {-family xyz} + set x {} +} {} + +test macfont-4.1 {TkpGetFontFamilies procedure} { + font families + set x {} +} {} + +test macfont-5.1 {Tk_MeasureChars procedure: unbounded right margin} { + .b.l config -wrap 0 -text "000000" + getsize +} "[expr $ax*6] $ay" +test macfont-5.2 {Tk_MeasureChars procedure: static width buffer exceeded} { + .b.l config -wrap 100000 -text "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + getsize +} "[expr $ax*256] $ay" +test macfont-5.3 {Tk_MeasureChars procedure: all chars did fit} { + .b.l config -wrap [expr $ax*10] -text "00000000" + getsize +} "[expr $ax*8] $ay" +test macfont-5.4 {Tk_MeasureChars procedure: not all chars fit} { + .b.l config -wrap [expr $ax*6] -text "00000000" + getsize +} "[expr $ax*6] [expr $ay*2]" +test macfont-5.5 {Tk_MeasureChars procedure: already saw space in line} { + .b.l config -wrap [expr $ax*12] -text "000000 0000000" + getsize +} "[expr $ax*7] [expr $ay*2]" +test macfont-5.6 {Tk_MeasureChars procedure: internal spaces significant} { + .b.l config -wrap [expr $ax*12] -text "000 00 00000" + getsize +} "[expr $ax*7] [expr $ay*2]" +test macfont-5.7 {Tk_MeasureChars procedure: include last partial char} { + .b.c dchars $t 0 end + .b.c insert $t 0 "0000" + .b.c index $t @[expr int($ax*2.5)],1 +} {2} +test macfont-5.8 {Tk_MeasureChars procedure: at least one char on line} { + .b.l config -text "000000" -wrap 1 + getsize +} "$ax [expr $ay*6]" +test macfont-5.9 {Tk_MeasureChars procedure: whole words} { + .b.l config -wrap [expr $ax*8] -text "000000 0000" + getsize +} "[expr $ax*6] [expr $ay*2]" +test macfont-5.10 {Tk_MeasureChars procedure: make first part of word fit} { + .b.l config -wrap [expr $ax*12] -text "0000000000000000" + getsize +} "[expr $ax*12] [expr $ay*2]" + +test macfont-6.1 {Tk_DrawChars procedure} { + .b.l config -text "a" + update +} {} + +test macfont-7.1 {AllocMacFont procedure: use old font} { + font create xyz + button .c -font xyz + font configure xyz -family times + update + destroy .c + font delete xyz +} {} +test macfont-7.2 {AllocMacFont procedure: extract info from style} { + font actual {Monaco 9 bold italic underline overstrike} +} {-family Monaco -size 9 -weight bold -slant italic -underline 1 -overstrike 0} +test macfont-7.3 {AllocMacFont procedure: extract text metrics} { + font metric {Geneva 10} -fixed +} {0} +test macfont-7.4 {AllocMacFont procedure: extract text metrics} { + font metric "Monaco 9" -fixed +} {1} + +destroy .b diff --git a/tests/macMenu.test b/tests/macMenu.test new file mode 100644 index 0000000..2c10e86 --- /dev/null +++ b/tests/macMenu.test @@ -0,0 +1,1565 @@ +# This file is a Tcl script to test menus in Tk. It is +# organized in the standard fashion for Tcl tests. This +# file tests the Macintosh-specific features of the menu +# system. +# +# Copyright (c) 1995-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) macMenu.test 1.23 97/07/10 13:35:52 + +if {$tcl_platform(platform) != "macintosh"} { + return +} + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\" image" + puts "type, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +proc deleteWindows {} { + foreach i [winfo children .] { + catch [destroy $i] + } +} + +deleteWindows +wm geometry . {} +raise . + +test macMenu-1.0 {TkMacUseMenuID} {} { + # Can't really test TkMacUseMenuID; it's only called on startup. +} {} + +test macMenu-2.1 {GetNewID} { + catch {destroy .m1} + list [catch {menu .m1} msg] $msg [destroy .m1] +} {0 .m1 {}} +test macMenu-2.2 {GetNewID - cascade menu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m2 + list [catch {menu .m2} msg] $msg [destroy .m1] [destroy .m2] +} {0 .m2 {} {}} +test macMenu-2.3 {GetNewID - running out of ids} { + deleteWindows + menu .menu + for {set i 0} {$i < 230} {incr i} { + menu .m$i + .menu add cascade -label ".m$i" -menu .m$i + } + menu .breaker + list [catch {.menu add cascade -menu .breaker} msg] $msg [deleteWindows] +} {1 {No more menus can be allocated.} {}} + +test macMenu-3.1 {FreeID} { + catch {destroy .m1} + menu .m1 + list [catch {destroy .m1} msg] $msg +} {0 {}} + +# No way to test running out of ids in TkpNewPlatformMenu +test macMenu-4.1 {TkpNewMenu} { + catch {destroy .m1} + list [catch {menu .m1} msg] $msg [catch {destroy .m1} msg2] $msg2 +} {0 .m1 0 {}} +test macMenu-4.2 {TkpNewMenu - checking for help menu when one is there} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m1.help -tearoff 0 + .m1.help add command -label Test + . configure -menu .m1 + raise . + update + list [catch {menu .m2} msg] $msg [destroy .m1] [destroy .m2] [. configure -menu ""] +} {0 .m2 {} {} {}} +test macMenu-4.3 {TkpNewMenu - menubar set but different interp} { + catch {interp delete testinterp} + catch {destroy .m1} + interp create testinterp + load {} Tk testinterp + interp eval testinterp {raise .} + interp eval testinterp {menu .m1} + interp eval testinterp {. configure -menu .m1} + interp eval testinterp {update} + list [catch {menu .m1} msg] $msg [destroy .m1] [interp delete testinterp] +} {0 .m1 {} {}} +test macMenu-4.4 {TkpNewMenu - menubar set but new menu has different parent} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 -tearoff 0 + .m1 add cascade -menu .m1.help + menu .m2 + .m2 add cascade -menu .m2.help + . configure -menu .m1 + raise . + update + list [catch {menu .m2.help} msg] $msg [. configure -menu ""] [destroy .m1] [destroy .m2] +} {0 .m2.help {} {} {}} +test macMenu-4.5 {TkpNewMenu - menubar set, same parent, not .help} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -menu .m1.help + . configure -menu .m1 + raise . + update + list [catch {menu .m1.foo} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 .m1.foo {} {}} +test macMenu-4.6 {TkpNewMenu - creating the help menu} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -menu .m1.help + . configure -menu .m1 + raise . + update + list [catch {menu .m1.help} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 .m1.help {} {}} + +test macMenu-5.1 {TkpDestroyMenu} { + catch {destroy .m1} + menu .m1 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test macMenu-5.2 {TkpDestroyMenu - help menu} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -menu .m1.help + . configure -menu .m1 + menu .m1.help + raise . + update + list [catch {destroy .m1.help} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-5.3 {TkpDestroyMenu - idle handler pending} { + catch {destroy .m1} + menu .m1 + .m1 add command -label test + list [catch {destroy .m1} msg] $msg +} {0 {}} +test macMenu-5.4 {TkpDestroyMenu - idle handler not pending} { + catch {destroy .m1} + menu .m1 + .m1 add command -label test + update idletasks + list [catch {destroy .m1} msg] $msg +} {0 {}} + +test macMenu-6.1 {SetMenuCascade} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + list [catch {.m2 add cascade -menu .m1} msg] $msg [destroy .m1 .m2] +} {0 {} {}} +test macMenu-6.2 {SetMenuCascade - running out of ids} { + deleteWindows + menu .menu + for {set i 0} {$i < 230} {incr i} { + menu .m$i + .menu add cascade -label ".m$i" -menu .m$i + } + menu .breaker + list [catch {.menu add cascade -menu .breaker} msg] $msg [deleteWindows] +} {1 {No more menus can be allocated.} {}} + +test macMenu-7.1 {TkpDestroyMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 delete 1} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-7.2 {TkpDestroyMenuEntry - help menu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.help + menu .m1.help -tearoff 0 + .m1.help add command -label "test" + . configure -menu .m1 + raise . + update + list [catch {.m1.help delete test} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} + +test macMenu-8.1 {GetEntryText} { + catch {destroy .m1} + list [catch {menu .m1} msg] $msg [destroy .m1] +} {0 .m1 {}} +test macMenu-8.2 {GetEntryText} { + catch {destroy .m1} + catch {image delete image1} + menu .m1 + image create test image1 + list [catch {.m1 add command -image image1} msg] $msg [destroy .m1] [image delete image1] +} {0 {} {} {}} +test macMenu-8.3 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -bitmap questhead} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-8.4 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-8.5 {GetEntryText} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + list [catch {.m1 add command -label "foo"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-8.6 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "This is a very long string. 9012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890"} \ + msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-8.7 {GetEntryText - elipses character} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "foo..."} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-8.8 {GetEntryText - false elipses character} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "foo."} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-8.9 {GetEntryText - false elipses character} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "foo.."} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-8.10 {GetEntryText - false elipses character} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "foo.b"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-8.11 {GetEntryText - false elipses character} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "foo..b"} msg] $msg [destroy .m1] +} {0 {} {}} + + +# test macMenu-9.1 - assumes some fonts +test macMenu-9.1 {FindMarkCharacter} { + catch {destroy .m1} + menu .m1 -font "Helvetica 12" -tearoff 0 + .m1 add checkbutton -label test + .m1 invoke test + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +# All standard fonts have "¥" defined. We can't test further. + +test macMenu-10.1 {SetMenuIndicator - cascade entry} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add cascade -label foo} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-10.2 {SetMenuIndicator - not radio or checkbutton} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label foo} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-10.3 {SetMenuIndicator - indiatorOn false} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add checkbutton -label foo -indicatoron 0} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-10.4 {SetMenuIndicator - entry not selected} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add checkbutton -label foo} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-10.5 {SetMenuIndicator - checkbutton} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + list [catch {.m1 invoke foo} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-10.6 {SetMenuIndicator - radio button} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label foo + list [catch {.m1 invoke foo} msg] $msg [destroy .m1] +} {0 {} {}} + +test macMenu-11.1 {SetMenuTitle} { + catch {destroy .m1} + catch {destroy .container} + menu .container + menu .m1 +#previous title is .m1 + .container add cascade -label "File" -menu .m1 + list [catch {. configure -menu .container} msg] $msg [. configure -menu ""] [destroy .container .m1] +} {0 {} {} {}} +test macMenu-11.2 {SetMenuTitle} { + menu .container + menu .m1 + . configure -menu "" +#previous title is .m1 + .container add cascade -label "F" -menu .m1 + list [catch {. configure -menu .container} msg] $msg [. configure -menu ""] [destroy .container .m1] +} {0 {} {} {}} + +test macMenu-12.1 {TkpConfigureMenuEntry} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + .m1 add cascade -menu .m3 + list [catch {.m1 entryconfigure 1 -menu .m2} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.2 {TkpConfigureMenuEntry} { + catch {destroy .m1} + catch {destroy .m2} + . configure -menu "" + menu .m1 + .m1 add cascade -menu .m3 + menu .m2 + list [catch {.m1 entryconfigure 1 -menu .m2} msg] $msg [destroy .m1 .m2] +} {0 {} {}} +test macMenu-12.3 {TkpConfigureMenuEntry - running out of ids} { + deleteWindows + menu .menu + for {set i 0} {$i < 230} {incr i} { + menu .m$i + .menu add cascade -label ".m$i" -menu .m$i + } + menu .breaker + list [catch {.menu add cascade -menu .breaker} msg] $msg [deleteWindows] +} {1 {No more menus can be allocated.} {}} +test macMenu-12.4 {TkpConfigureMenuEntry - Control} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -accel "Control+S"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.5 {TkpConfigureMenuEntry - Ctrl} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -accel "Ctrl+S"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.6 {TkpConfigureMenuEntry - Shift} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -accel "Shift+S"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.7 {TkpConfigureMenuEntry - Option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -accel "Opt+S"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.8 {TkpConfigureMenuEntry - Command} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -accel "Command+S"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.9 {TkpConfigureMenuEntry - Cmd} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -accel "Cmd+S"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.10 {TkpConfigureMenuEntry - Alt} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -accel "Alt+S"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.11 {TkpConfigureMenuEntry - Meta} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -accel "Meta+S"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.12 {TkpConfigureMenuEntry - Two modifiers} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -accel "Cmd+Shift+S"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.13 {TkpConfigureMenuEntry - dash instead of plus} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -accel "Command-S"} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.14 {TkpConfigureMenuEntry - idler pending} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label test + list [catch {.m1 entryconfigure test -label test2} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-12.15 {TkpConfigureMenuEntry - idler not pending} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label test + update idletasks + list [catch {.m1 entryconfigure test -label test2} msg] $msg [destroy .m1] +} {0 {} {}} + +test macMenu-13.1 {ReconfigureIndividualMenu - getting rid of zero items} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label test + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.2 {ReconfigureIndividualMenu - getting rid of one item} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label test + update idletasks + .m1 delete test + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.3 {ReconfigureIndividualMenu - getting rid of more than one} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label test + .m1 add command -label test2 + update idletasks + .m1 entryconfigure test2 -label "test two" + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.4 {ReconfigureIndividualMenu - separator} { + catch {destroy .m1} + menu .m1 + .m1 add separator + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.5 {ReconfigureIndividualMenu - disabled} { + catch {destroy .m1} + menu .m1 + .m1 add command + .m1 entryconfigure 1 -state disabled + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.6 {ReconfigureIndividualMenu - active} { + catch {destroy .m1} + menu .m1 + .m1 add command + .m1 entryconfigure 1 -state active + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.7 {ReconfigureIndividualMenu - checkbutton not checked} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label test + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.8 {ReconfigureIndividualMenu - checkbutton - indicator off} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label test -indicatoron 0 + .m1 invoke test + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.9 {ReconfigureIndividualMenu - checkbutton on} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label test + .m1 invoke test + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.10 {ReconfigureIndividualMenu - radiobutton not checked} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label test + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.11 {ReconfigureIndividualMenu - radiobutton - indicator off} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label test -indicatoron 0 + .m1 invoke test + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.12 {ReconfigureIndividualMenu - radiobutton on} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label test + .m1 invoke test + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.13 {ReconfigureIndividualMenu} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + .m1 add cascade -menu .m3 + .m1 entryconfigure 1 -menu .m2 + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.14 {ReconfigureIndividualMenu} { + catch {destroy .m1} + catch {destroy .m2} + . configure -menu "" + menu .m1 + .m1 add cascade -menu .m3 + menu .m2 + .m1 entryconfigure 1 -menu .m2 + list [catch {update idletasks} msg] $msg [destroy .m1 .m2] +} {0 {} {}} +test macMenu-13.15 {ReconfigureIndividualMenu - accelerator} { + catch {destroy .m1} + menu .m1 + .m1 add command -accel "Command-S" + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.16 {ReconfigureIndividualMenu - parent is disabled} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label .m1.edit -label "Edit" -state disabled + menu .m1.edit + .m1.edit add command -label foo + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-13.17 {ReconfigureIndividualMenu - disabling parent} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label .m1.edit -label Edit + menu .m1.edit + .m1.edit add command -label foo + .m1 entryconfigure Edit -state disabled + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} + +test macMenu-14.1 {ReconfigureMacintoshMenu - normal menu} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label test + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-14.2 {ReconfigureMacintoshMenu - apple menu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.apple + menu .m1.apple -tearoff 0 + .m1.apple add command -label test + . configure -menu .m1 + raise . + list [catch {update idletasks} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-14.3 {ReconfigureMacintoshMenu - help menu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.help + menu .m1.help -tearoff 0 + .m1.help add command -label test + . configure -menu .m1 + raise . + list [catch {update idletasks} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-14.4 {ReconfigureMacintoshMenu - menubar} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.file -label "foo" + menu .m1.file + . configure -menu .m1 + raise . + .m1 entryconfigure foo -label "File" + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} + +test macMenu-15.1 {CompleteIdlers - no idle pending} { + catch {destroy .m1} + menu .m1 + .m1 add command -label test + update idletasks + list [catch {.m1 post 40 40} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-15.2 {CompleteIdlers - idle pending} { + catch {destroy .m1} + menu .m1 + .m1 add command -label test + list [catch {.m1 post 40 40} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-15.3 {CompleteIdlers - recursive} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.m2 -label test + menu .m1.m2 + .m1.m2 add command -label test + list [catch {.m1 post 40 40} msg] $msg [destroy .m1] +} {0 {} {}} + +#Don't know how to generate nested post menus +test macMenu-16.1 {TkpPostMenu} { + catch {destroy .m1} + menu .m1 -postcommand "destroy .m1" + list [catch {.m1 post 40 40} msg] $msg +} {0 {}} +test macMenu-16.2 {TkpPostMenu} { + catch {destroy .m1} + menu .m1 -postcommand "blork" + list [catch {.m1 post 40 40} msg] $msg [destroy .m1] +} {1 {invalid command name "blork"} {}} +# We need to write the interactive test for menu posting. + +test macMenu-17.1 {TkpMenuNewEntry - no idle pending} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label test} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-17.2 {TkpMenuNewEntry - idle pending} { + catch {destroy .m1} + menu .m1 + .m1 add command -label test + list [catch {.m1 add command -label test2} msg] $msg [destroy .m1] +} {0 {} {}} + +test macMenu-18.1 {DrawMenuBarWhenIdle} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + . configure -menu .m1 + list [catch {update idletasks} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.2 {DrawMenuBarWhenIdle - clearing old apple menu out} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.apple + menu .m1.apple + .m1.apple add command -label test + . configure -menu .m1 + raise . + update + . configure -menu "" + raise . + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-18.3 {DrawMenuBarWhenIdle - clearing out old help menu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.help + menu .m1.help + .m1.help add command -label test + . configure -menu .m1 + raise . + update + . configure -menu "" + raise . + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-18.4 {DrawMenuBarWhenIdle - menu not there} { + catch {destroy .m1} + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] +} {0 {} {}} +test macMenu-18.5 {DrawMenuBarWhenIdle - menu there} { + catch {destroy .m1} + menu .m1 + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.6 {DrawMenuBarWhenIdle - no apple menu} { + catch {destroy .m1} + menu .m1 + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.7 {DrawMenuBarWhenIdle - apple menu references but not there} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.apple + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.8 {DrawMenuBarWhenIdle - apple menu there} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.apple + menu .m1.apple + .m1.apple add command -label test + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.9 {DrawMenuBarWhenIdle - apple menu there; no idle handler} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.apple + menu .m1.apple + .m1.apple add command -label test + . configure -menu .m1 + raise . + update idletasks + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.10 {DrawMenuBarWhenIdle - no help menu} { + catch {destroy .m1} + menu .m1 + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.11 {DrawMenuBarWhenIdle - help menu referenced but not there} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.help + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.12 {DrawMenuBarWhenIdle - help menu there} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.help + menu .m1.help + .m1.help add command -label test + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.13 {DrawMenuBarWhenIdle - help menu there - no idlers} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.help + menu .m1.help + .m1.help add command -label test + . configure -menu .m1 + raise . + update idletasks + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +# Can't generate no menubar clone +test macMenu-18.14 {DrawMenuBarWhenIdle - apple and help menus in tearoff menubar} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.apple + .m1 add cascade -menu .m1.help + menu .m1.apple + menu .m1.help + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.15 {DrawMenuBarWhenIdle - apple and help menus in non-tearoff menubar} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -menu .m1.apple + .m1 add cascade -menu .m1.help + menu .m1.apple + menu .m1.help + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.16 {DrawMenuBarWhenIdle - no apple menu} { + catch {destroy .m1} + menu .m1 -tearoff 0 + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.17 {DrawMenuBarWhenIdle - apple menu} { + catch {destroy .m1} + menu .m1 -tearoff 0 + . configure -menu .m1 + .m1 add cascade -menu .m1.apple + menu .m1.apple + .m1.apple add cascade -label test -menu .m1.apple.test + menu .m1.apple.test + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.18 {DrawMenuBarWhenIdle - big for loop} { + catch {destroy .m1} + menu .m1 -tearoff 0 + menu .m1.apple -tearoff 0 + menu .m1.help -tearoff 0 + menu .m1.foo -tearoff 0 + .m1 add cascade -menu .m1.apple + .m1 add cascade -menu .m1.help + .m1 add cascade -label Foo -menu .m1.foo + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-18.19 {DrawMenuBarWhenIdle = disabled menu} { + catch {destroy .m1} + menu .m1 -tearoff 0 + menu .m1.edit -tearoff 0 + .m1 add cascade -menu .m1.edit -label Edit + . configure -menu .m1 + raise . + .m1 entryconfigure Edit -state disabled + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} + +test macMenu-19.1 {RecursivelyInsertMenu} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .main} + catch {destroy .t2} + toplevel .t2 -menu .main + wm geometry .t2 +0+0 + menu .main + .main add cascade -menu .m1 -label ".m1" + menu .m1 + .m1 add command -label "Test 2" + .m1 add cascade -label ".m2" -menu .m2 + menu .m2 + .m2 add command -label "Test 3" + list [catch {raise .t2} msg] $msg [destroy .t2 .main .m1 .m2] +} {0 {} {}} +test macMenu-19.2 {RecursivelyInsertMenu} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .main} + catch {destroy .t2} + toplevel .t2 -menu .main + wm geometry .t2 +0+0 + menu .main + .main add cascade -menu .m1 -label ".m1" + menu .m1 + .m1 add command -label "Test 2" + .m1 add cascade -label ".m2" -menu .m2 + menu .m2 + .m2 add command -label "Test 3" + list [catch {raise .t2} msg] $msg [destroy .t2 .main .m1 .m2] +} {0 {} {}} + +test macMenu-20.1 {SetDefaultMenuBar} { + . configure -menu "" + raise . + list [catch {update} msg] $msg +} {0 {}} + +test macMenu-21.1 {TkpSetMainMenubar - not front window} { + catch {destroy .m1} + catch {destroy .t2} + toplevel .t2 + wm geometry .t2 +50+50 + menu .m1 + raise . + update + list [catch {.t2 configure -menu .m1} msg] $msg [destroy .t2] [destroy .m1] +} {0 {} {} {}} +test macMenu-21.2 {TkpSetMainMenubar - menu null} { + . configure -menu "" + raise . + list [catch {update} msg] $msg +} {0 {}} +test macMenu-21.3 {TkpSetMainMenubar - different interps} { + catch {destroy .m1} + catch {interp delete testinterp} + interp create testinterp + load {} tk testinterp + menu .m1 + . configure -menu .m1 + raise . + update + interp eval testinterp {menu .m1} + interp eval testinterp {. configure -menu .m1} + interp eval testinterp {raise .} + list [catch {interp eval testinterp {update}} msg] $msg [interp delete testinterp] [. configure -menu ""] [destroy .m1] +} {0 {} {} {} {}} +test macMenu-21.4 {TkpSetMainMenubar - different windows} { + catch {destroy .m1} + catch {destroy .t2} + menu .m1 + . configure -menu .m1 + toplevel .t2 + wm geometry .t2 +50+50 + .t2 configure -menu .m1 + raise . + update + raise .t2 + list [catch {update} msg] $msg [destroy .t2] [. configure -menu ""] [destroy .m1] +} {0 {} {} {} {}} +test macMenu-21.5 {TkpSetMainMenubar - old menu was null} { + catch {destroy .m1} + . configure -menu "" + update + menu .m1 + . configure -menu .m1 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test macMenu-21.6 {TkpSetMainMenubar - old menu different} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + . configure -menu .m1 + raise . + update + . configure -menu .m2 + raise . + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] [destroy .m2] +} {0 {} {} {} {}} +test macMenu-21.7 {TkpSetMainMenubar - child window NULL - parent window now} { + catch {destroy .m1} + catch {destroy .t2} + toplevel .t2 + menu .m1 + .m1 add cascade -label Foo -menu .m1.foo + menu .m1.foo + .m1.foo add command -label foo + . configure -menu .m1 + raise .t2 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] [destroy .t2] +} {0 {} {} {} {}} +test macMenu-21.8 {TkpSetMainMenubar - tearoff window} { + catch {destroy .t2} + toplevel .t2 -menu .t2.m1 + menu .t2.m1 + .t2.m1 add cascade -label File -menu .t2.m1.foo + menu .t2.m1.foo + .t2.m1.foo add command -label foo + raise .t2 + tkTearOffMenu .t2.m1.foo 100 100 + list [catch {update} msg] $msg [destroy .t2] +} {0 {} {}} + +test macMenu-22.1 {TkSetWindowMenuBar} { +} {} + +test macMenu-23.1 {TkMacDispatchMenuEvent} { + # needs to be interactive. +} {} + +test macMenu-24.1 {GetMenuIndicatorGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + .m1 invoke foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} + +test macMenu-25.1 {GetMenuAccelGeometry - cascade entry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test macMenu-25.2 {GetMenuAccelGeometry - no accel} { + catch {destroy .m1} + menu .m1 + .m1 add command + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test macMenu-25.3 {GetMenuAccelGeometry - no special chars - arbitrary string} { + catch {destroy .m1} + menu .m1 + .m1 add command -accel "Test" + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test macMenu-25.4 {GetMenuAccelGeometry - Command} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Cmd+S" + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test macMenu-25.5 {GetMenuAccelGeometry - Control} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Ctrl+S" + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test macMenu-25.6 {GetMenuAccelGeometry - Shift} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Shift+S" + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test macMenu-25.7 {GetMenuAccelGeometry - Option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Opt+S" + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test macMenu-25.8 {GetMenuAccelGeometry - Combination} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Cmd+Shift+S" + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test macMenu-25.9 {GetMenuAccelGeometry - extra text} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Command+Delete" + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} + +test macMenu-26.1 {GetTearoffEntryGeometry} { + # can't call this on power mac. +} {} + +test macMenu-27.1 {GetMenuSeparatorGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add separator + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} + +test macMenu-28.1 {DrawMenuEntryIndicator - non-checkbutton} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-28.2 {DrawMenuEntryIndicator - indicator off} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo -indicatoron 0 + .m1 invoke foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-28.3 {DrawMenuEntryIndicator - not selected} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-28.4 {DrawMenuEntryIndicator - checkbutton} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + .m1 invoke foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-28.5 {DrawMenuEntryIndicator - radiobutton} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label foo + .m1 invoke foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +# Cannot reproduce resources missing or color allocation failing easily. +test macMenu-29.1 {DrawSICN} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Cmd+S" + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +# Cannot reproduce resources missing +test macMenu-30.1 {DrawMenuEntryAccelerator - cascade entry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-30.2 {DrawMenuEntryAccelerator - no accel string} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-30.3 {DrawMenuEntryAccelerator - random accel string} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-30.4 {DrawMenuEntryAccelerator - Command} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Cmd+S" + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-30.5 {DrawMenuEntryAccelerator - Option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Opt+S" + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-30.6 {DrawMenuEntryAccelerator - Shift} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Shift+S" + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-30.7 {DrawMenuEntryAccelerator - Control} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Ctrl+S" + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test macMenu-30.8 {DrawMenuEntryAccelerator - combination} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Cmd+Shift+S" + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +test macMenu-31.1 {DrawMenuSeparator} { + catch {destroy .m1} + menu .m1 + .m1 add separator + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +test macMenu-32.1 {TkpDrawMenuEntryLabel} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +test macMenu-33.1 {MenuDefProc - No way to test automatically.} {} {} +test macMenu-34.1 {TkMacHandleTearoffMenu - no way to test automatically} {} {} +test macMenu-35.1 {TkpInitializeMenuBindings - nothing to do} {} {} + +test macMenu-36.1 {TkpComputeMenubarGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + . configure -menu .m1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} + +test macMenu-37.1 {DrawTearoffEntry - can't do automatically} {} {} +test macMenu-38.1 {TkMacSetHelpMenuItemCount - called at boot time} {} {} +test macMenu-39.1 {TkMacMenuClick - can't do automatically} {} {} + +test macMenu-40.1 {TkpDrawMenuEntry - gc for active and not strict motif} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.2 {TkpDrawMenuEntry - gc for active menu item with its own gc} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -activeforeground red + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.3 {TkpDrawMenuEntry - gc for active and strict motif} { + catch {destroy .m1} + menu .m1 + set tk_strictMotif 1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] [set tk_strictMotif 0] +} {{} {} 0} +test macMenu-40.4 {TkpDrawMenuEntry - gc for disabled with disabledfg and custom entry} { + catch {destroy .m1} + menu .m1 -disabledforeground blue + .m1 add command -label foo -state disabled -background red + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.5 {TkpDrawMenuEntry - gc for disabled with disabledFg} { + catch {destroy .m1} + menu .m1 -disabledforeground blue + .m1 add command -label foo -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.6 {TkpDrawMenuEntry - gc for disabled - no disabledFg} { + catch {destroy .m1} + menu .m1 -disabledforeground "" + .m1 add command -label foo -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.7 {TkpDrawMenuEntry - gc for normal - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -foreground red + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.8 {TkpDrawMenuEntry - gc for normal} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.9 {TkpDrawMenuEntry - gc for indicator - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo -selectcolor orange + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.10 {TkpDrawMenuEntry - gc for indicator} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.11 {TkpDrawMenuEntry - border - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -activebackground green + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.12 {TkpDrawMenuEntry - border} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.13 {TkpDrawMenuEntry - active border - strict motif} { + catch {destroy .m1} + set tk_strictMotif 1 + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] [set tk_strictMotif 0] +} {{} {} 0} +test macMenu-40.14 {TkpDrawMenuEntry - active border - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -activeforeground yellow + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.15 {TkpDrawMenuEntry - active border} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.16 {TkpDrawMenuEntry - font - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -font "Helvectica 72" + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.17 {TkpDrawMenuEntry - font} { + catch {destroy .m1} + menu .m1 -font "Courier 72" + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.18 {TkpDrawMenuEntry - separator} { + catch {destroy .m1} + menu .m1 + .m1 add separator + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.19 {TkpDrawMenuEntry - standard} { + catch {destroy .mb} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.20 {TkpDrawMenuEntry - disabled cascade item} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label File -menu .m1.file + menu .m1.file + .m1.file add command -label foo + .m1 entryconfigure File -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.21 {TkpDrawMenuEntry - indicator} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label macMenu-40.20 + .m1 invoke 0 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-40.22 {TkpDrawMenuEntry - indicator - hideMargin} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label macMenu-40.21 -hidemargin 1 + .m1 invoke 0 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} + +test macMenu-41.1 {TkpComputeStandardMenuGeometry - no entries} { + catch {destroy .m1} + menu .m1 + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.2 {TkpComputeStandardMenuGeometry - one entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.3 {TkpComputeStandardMenuGeometry - more than one entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + .m1 add command -label "two" + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.4 {TkpComputeStandardMenuGeometry - separator} { + catch {destroy .m1} + menu .m1 + .m1 add separator + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.5 {TkpComputeStandardMenuGeometry - standard label geometry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.6 {TkpComputeStandardMenuGeometry - different font for entry} { + catch {destroy .m1} + menu .m1 -font "Helvetica 12" + .m1 add command -label "test" -font "Courier 12" + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.7 {TkpComputeStandardMenuGeometry - second entry larger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add command -label "test test" + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.8 {TkpComputeStandardMenuGeometry - first entry larger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test test" + .m1 add command -label "test" + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.9 {TkpComputeStandardMenuGeometry - accelerator} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" -accel "Ctrl+S" + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.10 {TkpComputeStandardMenuGeometry - second accel larger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" -accel "1" + .m1 add command -label "test" -accel "1 1" + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.11 {TkpComputeStandardMenuGeometry - second accel smaller} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" -accel "1 1" + .m1 add command -label "test" -accel "1" + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.12 {TkpComputeStandardMenuGeometry - indicator} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label test + .m1 invoke 1 + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.13 {TkpComputeStandardMenuGeometry - second indicator less or equal } { + catch {destroy .m1} + catch {image delete image1} + image create test image1 + menu .m1 + .m1 add checkbutton -image image1 + .m1 invoke 1 + .m1 add checkbutton -label test + .m1 invoke 2 + list [update idletasks] [destroy .m1] [image delete image1] +} {{} {} {}} +test macMenu-41.14 {TkpComputeStandardMenuGeometry - hidden margin} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label macMenu-41.15 -hidemargin 1 + .m1 invoke macMenu-41.15 + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.15 {TkpComputeStandardMenuGeometry - zero sized menus} { + catch {destroy .m1} + menu .m1 -tearoff 0 + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.16 {TkpComputeStandardMenuGeometry - first column bigger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label one + .m1 add command -label two + .m1 add command -label three -columnbreak 1 + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.17 {TkpComputeStandardMenuGeometry - second column bigger} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label one + .m1 add command -label two -columnbreak 1 + .m1 add command -label three + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.18 {TkpComputeStandardMenuGeometry - three columns} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label one + .m1 add command -label two -columnbreak 1 + .m1 add command -label three + .m1 add command -label four + .m1 add command -label five -columnbreak 1 + .m1 add command -label six + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.19 {TkpComputeStandardMenuGeometry - entry without accel long} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label "This is a long item with no accel." + .m1 add command -label foo -accel "Cmd+S" + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-41.20 {TkpComputeStandardMenuGeometry - entry with accel long} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label foo + .m1 add command -label "This is a long label with an accel." -accel "Cmd+W" + list [update idletasks] [destroy .m1] +} {{} {}} + +test macMenu-42.1 {DrawMenuEntryLabel - setting indicatorSpace} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + set tearoff [tkTearOffMenu .m1] + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-42.2 {DrawMenuEntryLabel - drawing image} { + catch {destroy .m1} + catch {image delete image1} + image create test image1 + menu .m1 + .m1 add command -image image1 + set tearoff [tkTearOffMenu .m1] + list [update idletasks] [destroy .m1] [image delete image1] +} {{} {} {}} +test macMenu-42.3 {DrawMenuEntryLabel - drawing select image} { + catch {destroy .m1} + catch {eval image delete [image names]} + image create test image1 + image create test image2 + menu .m1 + .m1 add checkbutton -image image1 -selectimage image2 + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1] + list [update idletasks] [destroy .m1] [eval image delete [image names]] +} {{} {} {}} +test macMenu-42.4 {DrawMenuEntryLabel - drawing a bitmap} { + catch {destroy .m1} + menu .m1 + .m1 add command -bitmap questhead + set tearoff [tkTearOffMenu .m1] + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-42.5 {DrawMenuEntryLabel - drawing null label} { + catch {destroy .m1} + menu .m1 + .m1 add command + set tearoff [tkTearOffMenu .m1] + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-42.6 {DrawMenuEntryLabel - drawing real label} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "This is a long label" -underline 3 + set tearoff [tkTearOffMenu .m1] + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-42.7 {DrawMenuEntryLabel - drawing disabled label} { + catch {destroy .m1} + menu .m1 -disabledforeground "" + .m1 add command -label "This is a long label" -state disabled + set tearoff [tkTearOffMenu .m1] + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-42.8 {DrawMenuEntryLabel - disabled images} { + catch {destroy .m1} + catch {image delete image1} + image create test image1 + menu .m1 + .m1 add command -image image1 -state disabled + set tearoff [tkTearOffMenu .m1 100 100] + list [update idletasks] [destroy .m1] [image delete image1] +} {{} {} {}} + +test macMenu-43.1 {GetMenuLabelGeometry - image} { + catch {destroy .m1} + catch {image delete image1} + menu .m1 + image create test image1 + .m1 add command -image image1 + list [update idletasks] [destroy .m1] [image delete image1] +} {{} {} {}} +test macMenu-43.2 {GetMenuLabelGeometry - bitmap} { + catch {destroy .m1} + menu .m1 + .m1 add command -bitmap questhead + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-43.3 {GetMenuLabelGeometry - no text} { + catch {destroy .m1} + menu .m1 + .m1 add command + list [update idletasks] [destroy .m1] +} {{} {}} +test macMenu-43.4 {GetMenuLabelGeometry - text} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "This is a test." + list [update idletasks] [destroy .m1] +} {{} {}} + +test macMenu-44.1 {DrawMenuEntryBackground} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test macMenu-44.2 {DrawMenuEntryBackground} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + $tearoff activate 0 + list [update] [destroy .m1] +} {{} {}} + +test macMenu-45.1 {TkpMenuInit - called at boot time} {} {} + +deleteWindows + diff --git a/tests/macWinMenu.test b/tests/macWinMenu.test new file mode 100644 index 0000000..7b6ac12 --- /dev/null +++ b/tests/macWinMenu.test @@ -0,0 +1,117 @@ +# This file is a Tcl script to test menus in Tk. It is +# organized in the standard fashion for Tcl tests. It tests +# the common implementation of Macintosh and Windows menus. +# +# Copyright (c) 1995-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) macWinMenu.test 1.13 97/04/10 14:41:29 + +if {$tcl_platform(platform) == "unix"} { + return +} + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\" image" + puts "type, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +proc deleteWindows {} { + foreach i [winfo children .] { + catch [destroy $i] + } +} + +deleteWindows +wm geometry . {} +raise . + +if {$tcl_platform(platform) == "windows" && ![info exists INTERACTIVE]} { + puts " Some tests were skipped because they could not be performed" + puts " automatically on this platform. If you wish to execute them" + puts " interactively, set the TCL variable INTERACTIVE and re-run" + puts " the test." +} + +test macWinMenu-1.1 {PreprocessMenu} { + catch {destroy .m1} + menu .m1 -postcommand "destroy .m1" + .m1 add command -label "macWinMenu-1.1: Hit Escape" + list [catch {.m1 post 40 40} msg] $msg +} {0 {}} +if {$tcl_platform(platform) != "windows" || [info exists INTERACTIVE]} { + test macWinMenu-1.2 {PreprocessMenu} { + catch {destroy .m1} + catch {destroy .m2} + set foo1 foo + set foo2 foo + menu .m1 -postcommand "set foo1 .m1" + .m1 add cascade -menu .m2 -label "macWinMenu-1.2: Hit Escape" + menu .m2 -postcommand "set foo2 .m2" + update idletasks + list [catch {.m1 post 40 40} msg] $msg [set foo1] [set foo2] [destroy .m1 .m2] [catch {unset foo1}] [catch {unset foo2}] + } {0 .m2 .m1 .m2 {} 0 0} +} +test macWinMenu-1.3 {PreprocessMenu} { + catch {destroy .l1} + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + label .l1 -text "Preparing menus..." + pack .l1 + update idletasks + menu .m1 -postcommand ".l1 configure -text \"Destroying .m1...\"; update idletasks; destroy .m1" + menu .m2 -postcommand ".l1 configure -text \"Destroying .m2...\"; update idletasks; destroy .m2" + menu .m3 -postcommand ".l1 configure -text \"Destroying .m3...\"; update idletasks; destroy .m3" + .m1 add cascade -menu .m2 -label "macWinMenu-1.3: Hit Escape (.m2)" + .m1 add cascade -menu .m3 -label ".m3" + update idletasks + list [catch {.m1 post 40 40} msg] $msg [destroy .l1 .m2 .m3] +} {0 {} {}} +test macWinMenu-1.4 {PreprocessMenu} { + catch {destroy .l1} + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + catch {destroy .m4} + label .l1 -text "Preparing menus..." + pack .l1 + update idletasks + menu .m1 -postcommand ".l1 configure -text \"Destroying .m1...\"; update idletasks; destroy .m1" + .m1 add cascade -menu .m2 -label "macWinMenu-1.4: Hit Escape (.m2)" + .m1 add cascade -menu .m3 -label ".m3" + menu .m2 -postcommand ".l1 configure -text \"Destroying .m2...\"; update idletasks; destroy .m2" + .m2 add cascade -menu .m4 -label ".m4" + menu .m3 -postcommand ".l1 configure -text \"Destroying .m3...\"; update idletasks; destroy .m3" + menu .m4 -postcommand ".l1 configure -text \"Destroying .m4...\"; update idletasks; destroy .m4" + update idletasks + list [catch {.m1 post 40 40} msg] $msg [destroy .l1 .m2 .m3 .m4] +} {0 {} {}} +test macWinMenu-1.5 {PreprocessMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add cascade -menu .m2 -label "You may need to hit Escape to get this menu to go away." + menu .m2 -postcommand glorp + list [catch {.m1 post 40 40} msg] $msg [destroy .m1 .m2] +} {1 {invalid command name "glorp"} {}} + +if {$tcl_platform(platform) != "windows" || [info exists INTERACTIVE]} { + test macWinMenu-2.1 {TkPreprocessMenu} { + catch {destroy .m1} + set foo test + menu .m1 -postcommand "set foo 2.1" + .m1 add command -label "macWinMenu-2.1: Hit Escape" + list [catch {.m1 post 40 40} msg] $msg [set foo] [destroy .m1] [unset foo] + } {0 2.1 2.1 {} {}} +} + +deleteWindows diff --git a/tests/macscrollbar.test b/tests/macscrollbar.test new file mode 100644 index 0000000..0dd6646 --- /dev/null +++ b/tests/macscrollbar.test @@ -0,0 +1,101 @@ +# This file is a Tcl script to test out scrollbar widgets and +# the "scrollbar" command of Tk. This file only tests Macintosh +# specific features. It is organized in the standard fashion for +# Tcl tests. +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) macscrollbar.test 1.3 97/06/24 13:48:34 + +# Only run this test on the Macintosh +if {$tcl_platform(platform) != "macintosh"} return + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . +update + +# Tests for display and layout +wm geometry . 50x300 +scrollbar .s +pack .s -fill y -expand 1 +update +test macscroll-1.1 {TkpDisplayScrollbar procedure} { + list [.s configure -width] [.s configure -bd] +} {{-width width Width 16 16} {-borderwidth borderWidth BorderWidth 0 0}} +test macscroll-1.2 {TkpDisplayScrollbar procedure} { + # Exercise drawing 3D relief + pack .s -fill y -expand 1 -anchor center + .s configure -bd 4 + update + focus .s + update +} {} +test macscroll-1.3 {TkpDisplayScrollbar procedure} { + pack .s -fill y -expand 1 -anchor e + update + set x [.s configure -width] + pack .s -fill y -expand 1 -anchor w + update + list [.s configure -width] $x +} {{-width width Width 16 16} {-width width Width 16 16}} +test macscroll-1.4 {TkpDisplayScrollbar procedure} { + wm geometry . 300x50 + .s configure -bd 0 -orient horizontal + pack .s -fill x -expand 1 -anchor center + update + set x [.s configure -width] + pack .s -fill x -expand 1 -anchor n + update + set y [.s configure -width] + pack .s -fill x -expand 1 -anchor s + update + list [.s configure -width] $x $y +} {{-width width Width 16 16} {-width width Width 16 16} {-width width Width 16 16}} +test macscroll-1.5 {TkpDisplayScrollbar procedure} { + wm geometry . 300x16 + .s configure -bd 0 -orient horizontal + pack .s -fill x -expand 1 -anchor s + update + wm geometry . 300x15 + update + wm geometry . 300x14 + update +} {} +test macscroll-1.6 {TkpDisplayScrollbar procedure} { + # Check the drawing of the resize hack + wm geometry . 20x300 + wm resizable . 1 1 + .s configure -bd 0 -orient vertical + pack .s -fill y -expand 1 -anchor e + update + set x [.s identify 12 295] + wm resizable . 0 0 + update + set y [.s identify 12 295] + wm resizable . 1 1 + pack .s -fill y -expand 1 -anchor center + update + list $x $y [.s identify 12 295] +} {{} arrow2 arrow2} +test macscroll-1.7 {TkpDisplayScrollbar procedure} { + wm geometry . 300x300 + pack .s -fill y -expand 1 -anchor e + catch {destroy .s2} + scrollbar .s2 -orient horizontal + place .s2 -x 0 -y 284 -width 300 +} {} + +foreach i [winfo children .] { + destroy $i +} +concat {} diff --git a/tests/main.test b/tests/main.test new file mode 100644 index 0000000..49365c3 --- /dev/null +++ b/tests/main.test @@ -0,0 +1,31 @@ +# This file contains tests for the tkMain.c file. +# +# This file contains a collection of tests for one or more of the Tcl +# built-in commands. Sourcing this file into Tcl runs the tests and +# generates output for errors. No output means no errors were found. +# +# Copyright (c) 1997 by Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) main.test 1.2 97/09/10 17:49:20 + +if {[info procs test] != "test"} { + source defs +} + +test main-1.1 {StdinProc} {unixOnly} { + catch {removeFile script} + set fd [open script w] + puts $fd { + close stdin; exit + } + close $fd + if {[catch {exec $tktest <script} msg]} { + set error 1 + } else { + set error 0 + } + list $error $msg +} {0 {}} diff --git a/tests/menu.test b/tests/menu.test new file mode 100644 index 0000000..3f54a8d --- /dev/null +++ b/tests/menu.test @@ -0,0 +1,2385 @@ +# This file is a Tcl script to test menus in Tk. It is +# organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1995-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) menu.test 1.43 97/10/28 13:51:13 + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\" image" + puts "type, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +if {$tcl_platform(platform) == "windows" && ![info exists INTERACTIVE]} { + puts " Some tests were skipped because they could not be performed" + puts " automatically on this platform. If you wish to execute them" + puts " interactively, set the TCL variable INTERACTIVE and re-run" + puts " the test." + set testConfig(menuInteractive) 0 +} else { + set testConfig(menuInteractive) 1 +} + +proc deleteWindows {} { + foreach i [winfo children .] { + catch [destroy $i] + } +} + +deleteWindows +wm geometry . {} +raise . + +test menu-1.1 {Tk_MenuCmd procedure} { + list [catch menu msg] $msg +} {1 {wrong # args: should be "menu pathName ?options?"}} +test menu-1.2 {Tk_MenuCmd procedure} { + list [catch "menu bogus" msg] $msg +} {1 {bad window path name "bogus"}} +test menu-1.3 {Tk_MenuCmd procedure} { + list [catch "menu .m1 foo" msg] $msg +} {1 {unknown option "foo"}} +test menu-1.4 {Tk_MenuCmd procedure} { + catch {destroy .m1} + list [catch {menu .m1} msg] $msg [destroy .m1] +} {0 .m1 {}} +test menu-1.5 {Tk_MenuCmd - creating menubar} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label Test -menu "" + list [. configure -menu .m1] [. configure -menu ""] [destroy .m1] +} {{} {} {}} +test menu-1.6 {Tk_MenuCmd procedure menu ref no cascade} { + catch {destroy .t2} + catch {destroy .m1} + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + list [catch {menu .m1} msg] $msg [destroy .m1 .t2] +} {0 .m1 {}} +test menu-1.7 {Tk_MenuCmd procedure one clone cascade} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .t2} + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + menu .m1 + .m1 add cascade -menu .m2 + list [catch {menu .m2} msg] $msg [destroy .t2 .m1 .m2] +} {0 .m2 {}} +test menu-1.8 {Tk_MenuCmd procedure two clone cascades} { + catch {destroy .m1} + catch {destroy .t2} + catch {destroy .t3} + catch {destroy .m2} + menu .m1 + .m1 add cascade -menu .m2 + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + toplevel .t3 -menu .m1 + wm geometry .t3 +0+0 + list [catch {menu .m2} msg] $msg [destroy .t2 .t3 .m1 .m2] +} {0 .m2 {}} +test menu-1.9 {Tk_MenuCmd procedure two clone cascades different order} { + catch {destroy .t2} + catch {destroy .m1} + catch {destroy .t3} + catch {destroy .m2} + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + menu .m1 + .m1 add cascade -menu .m2 + toplevel .t3 -menu .m1 + wm geometry .t3 +0+0 + list [catch {menu .m2} msg] $msg [destroy .t2 .t3 .m1 .m2] +} {0 .m2 {}} +test menu-1.10 {Tk_MenuCmd procedure two clone cascades menus last} { + catch {destroy .t2} + catch {destroy .t3} + catch {destroy .m1} + catch {destroy .m2} + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + toplevel .t3 -menu .m1 + wm geometry .t3 +0+0 + menu .m1 + .m1 add cascade -menu .m2 + list [catch {menu .m2} msg] $msg [destroy .t2 .t3 .m1 .m2] +} {0 .m2 {}} +test menu-1.11 {Tk_MenuCmd procedure three clones cascades} { + catch {destroy .t2} + catch {destroy .t3} + catch {destroy .t4} + catch {destroy .m1} + catch {destroy .m2} + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + toplevel .t3 -menu .m1 + wm geometry .t3 +0+0 + toplevel .t4 -menu .m1 + wm geometry .t4 +0+0 + menu .m1 + .m1 add cascade -menu .m2 + list [catch {menu .m2} msg] $msg [destroy .t2 .t3 .t4 .m1 .m2] +} {0 .m2 {}} +test menu-1.12 {Tk_MenuCmd procedure} { + catch {destroy .t2} + catch {destroy .m1} + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + list [catch {menu .m1} msg] $msg [destroy .t2 .m1] +} {0 .m1 {}} +test menu-1.13 {Tk_MenuCmd procedure} { + catch {destroy .t2} + catch {destroy .t3} + catch {destroy .m1} + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + toplevel .t3 -menu .m1 + wm geometry .t3 +0+0 + list [catch {menu .m1} msg] $msg [destroy .t2 .t3 .m1] +} {0 .m1 {}} +test menu-1.14 {Tk_MenuCmd procedure} { + catch {destroy .t2} + catch {destroy .t3} + catch {destroy .t4} + catch {destroy .m1} + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + toplevel .t3 -menu .m1 + wm geometry .t3 +0+0 + toplevel .t4 -menu .m1 + wm geometry .t4 +0+0 + list [catch {menu .m1} msg] $msg [destroy .t2 .t3 .t4 .m1] +} {0 .m1 {}} + +catch {destroy .m1} +menu .m1 +set i 1 +foreach test { + {-activebackground #012345 #012345 non-existent + {unknown color name "non-existent"}} + {-activeborderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-activeforeground #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-background #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-bg #110022 #110022 bogus {unknown color name "bogus"}} + {-borderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-cursor arrow arrow badValue {bad cursor spec "badValue"}} + {-disabledforeground #00ff00 #00ff00 xyzzy {unknown color name "xyzzy"}} + {-fg #110022 #110022 bogus {unknown color name "bogus"}} + {-font -Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* + -Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* {} + {font "" doesn't exist}} + {-foreground #110022 #110022 bogus {unknown color name "bogus"}} + {-postcommand "any old string" "any old string" {} {}} + {-relief groove groove 1.5 {bad relief type "1.5": must be flat, groove, raised, ridge, solid, or sunken}} + {-selectcolor #110022 #110022 bogus {unknown color name "bogus"}} + {-takefocus "any string" "any string" {} {}} + {-tearoff 0 0} + {-tearoff 1 1} + {-tearoffcommand "any old string" "any old string" {} {}} +} { + set name [lindex $test 0] + test menu-2.$i {configuration options} { + .m1 configure $name [lindex $test 1] + lindex [.m1 configure $name] 4 + } [lindex $test 2] + incr i + if {[lindex $test 3] != ""} { + test menu-2.$i {configuration options} { + list [catch {.m1 configure $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .m1 configure $name [lindex [.m1 configure $name] 3] + incr i +} +destroy .m1 + +# We need to test all of the options with all of the different types of +# menu entries. The following code sets up .m1 with 6 items. It then +# runs through the big table below it. +# index 0 is tearoff, 1 command, 2 cascade, 3 separator, 4 checkbutton, +# 5 radiobutton + +menu .m1 +.m1 add command -label "command" +menu .m2 +.m2 add command -label "test" +.m1 add cascade -label "cascade" -menu .m2 +.m1 add separator +.m1 add checkbutton -label "checkbutton" -variable check -onvalue on -offvalue off +.m1 add radiobutton -label "radiobutton" -variable radio +image create photo image1 -file [file join $tk_library demos images earth.gif] + +foreach test { + {-activebackground + {{#012345 + {{unknown option "-activebackground"} #012345 #012345 + {unknown option "-activebackground"} #012345 #012345 + } + } + {non-existent + {{unknown option "-activebackground"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + {unknown option "-activebackground"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + } + }} + } + {-activeforeground + {{#ff0000 + {{unknown option "-activeforeground"} + #ff0000 #ff0000 {unknown option "-activeforeground"} #ff0000 #ff0000 + } + } + {non-existent + {{unknown option "-activeforeground"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + {unknown option "-activeforeground"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + } + }} + } + {-accelerator + {{"Ctrl+S" + {{unknown option "-accelerator"} + "Ctrl+S" "Ctrl+S" {unknown option "-accelerator"} + "Ctrl+S" "Ctrl+S" + } + }} + } + {-background + {{#ff0000 + {#ff0000 #ff0000 #ff0000 #ff0000 #ff0000 #ff0000 + } + } + {non-existent + {{unknown color name "non-existent"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + } + }} + } + {-bitmap + {{questhead + {{unknown option "-bitmap"} questhead questhead + {unknown option "-bitmap"} questhead questhead + } + } + {badValue + {{unknown option "-bitmap"} + {bitmap "badValue" not defined} + {bitmap "badValue" not defined} + {unknown option "-bitmap"} + {bitmap "badValue" not defined} + {bitmap "badValue" not defined} + } + }} + } + {-columnbreak + {{1 + {{unknown option "-columnbreak"} 1 1 {unknown option "-columnbreak"} 1 1} + }} + } + {-command + {{beep + {{unknown option "-command"} beep beep + {unknown option "-command"} beep beep + } + }} + } + {-font + {{-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* + {{unknown option "-font"} + -Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* + -Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* + {unknown option "-font"} + -Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* + -Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-* + } + } + {{kill rock stars} + {{unknown option "-font"} + {expected integer but got "rock"} + {expected integer but got "rock"} + {unknown option "-font"} + {expected integer but got "rock"} + {expected integer but got "rock"} + } + }} + } + {-foreground + {{#110022 + {{unknown option "-foreground"} #110022 #110022 + {unknown option "-foreground"} #110022 #110022 + } + } + {non-existent + {{unknown option "-foreground"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + {unknown option "-foreground"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + } + }} + } + {-image + {{image1 + {{unknown option "-image"} image1 image1 + {unknown option "-image"} image1 image1 + } + } + {bogus + {{unknown option "-image"} + {image "bogus" doesn't exist} + {image "bogus" doesn't exist} + {unknown option "-image"} + {image "bogus" doesn't exist} + {image "bogus" doesn't exist} + } + } + {"" + {{unknown option "-image"} + {} + {} + {unknown option "-image"} + {} + {} + } + }} + } + {-indicatoron + {{1 + {{unknown option "-indicatoron"} + {unknown option "-indicatoron"} + {unknown option "-indicatoron"} + {unknown option "-indicatoron"} 1 1 + } + }} + } + {-label + {{test + {{unknown option "-label"} test test + {unknown option "-label"} test test + } + }} + } + {-menu + {{.m2 + {{unknown option "-menu"} + {unknown option "-menu"} .m2 + {unknown option "-menu"} + {unknown option "-menu"} + {unknown option "-menu"} + } + }} + } + {-offvalue + {{off + {{unknown option "-offvalue"} + {unknown option "-offvalue"} + {unknown option "-offvalue"} + {unknown option "-offvalue"} + off + {unknown option "-offvalue"} + } + }} + } + {-onvalue + {{on + {{unknown option "-onvalue"} + {unknown option "-onvalue"} + {unknown option "-onvalue"} + {unknown option "-onvalue"} + on + {unknown option "-onvalue"} + } + }} + } + {-selectcolor + {{#110022 + {{unknown option "-selectcolor"} + {unknown option "-selectcolor"} + {unknown option "-selectcolor"} + {unknown option "-selectcolor"} + #110022 + #110022 + } + } + {non-existent + {{unknown option "-selectcolor"} + {unknown option "-selectcolor"} + {unknown option "-selectcolor"} + {unknown option "-selectcolor"} + {unknown color name "non-existent"} + {unknown color name "non-existent"} + } + }} + } + {-selectimage + {{image1 + {{unknown option "-selectimage"} + {unknown option "-selectimage"} + {unknown option "-selectimage"} + {unknown option "-selectimage"} image1 image1 + } + } + {bogus + {{unknown option "-selectimage"} + {unknown option "-selectimage"} + {unknown option "-selectimage"} + {unknown option "-selectimage"} + {image "bogus" doesn't exist} + {image "bogus" doesn't exist} + } + } + {"" + {{unknown option "-selectimage"} + {unknown option "-selectimage"} + {unknown option "-selectimage"} + {unknown option "-selectimage"} + {} + {} + } + }} + } + {-state + {{normal + {normal normal normal + {unknown option "-state"} normal normal + } + }} + } + {-value + {{"any string" + {{unknown option "-value"} + {unknown option "-value"} + {unknown option "-value"} + {unknown option "-value"} + {unknown option "-value"} "any string" + } + }} + } + {-variable + {{"any string" + {{unknown option "-variable"} + {unknown option "-variable"} + {unknown option "-variable"} + {unknown option "-variable"} + "any string" + "any string" + } + }} + } + {-underline + {{0 + {{unknown option "-underline"} 0 0 + {unknown option "-underline"} 0 0 + } + } + {3p + {{unknown option "-underline"} + {expected integer but got "3p"} + {expected integer but got "3p"} + {unknown option "-underline"} + {expected integer but got "3p"} + {expected integer but got "3p"} + } + }} + } +} { + set name [lindex $test 0] + foreach attempt [lindex $test 1] { + set value [lindex $attempt 0] + set options [lindex $attempt 1] + foreach item {0 1 2 3 4 5} { + catch {unset msg} + test menu-2.$i [list entry configuration options $name $item $value] { + set result [catch {.m1 entryconfigure $item $name $value} msg] + if {$result == 1} { + set msg + } else { + lindex [.m1 entryconfigure $item $name] 4 + } + } [lindex $options $item] + incr i + } + } +} + +image delete image1 +destroy .m1 +destroy .m2 + +test menu-3.1 {MenuWidgetCmd procedure} { + catch {destroy .m1} + menu .m1 + list [catch {.m1} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 option ?arg arg ...?"} {}} +test menu-3.2 {MenuWidgetCmd, Tcl_Preserve and Tcl_Release} {menuInteractive} { + catch {destroy .m1} + menu .m1 -postcommand "destroy .m1" + .m1 add command -label "menu-3.2: Hit Escape" + list [catch {.m1 post 40 40} msg] $msg +} {0 {}} +test menu-3.3 {MenuWidgetCmd procedure, "activate" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 activate} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 activate index"} {}} +test menu-3.4 {MenuWidgetCmd procedure, "activate" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 activate "foo"} msg] $msg [destroy .m1] +} {1 {bad menu entry index "foo"} {}} +test menu-3.5 {MenuWidgetCmd procedure, "activate" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add separator + list [catch {.m1 activate 2} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.6 {MenuWidgetCmd procedure, "activate" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 entryconfigure 1 -state disabled + list [catch {.m1 activate 1} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.7 {MenuWidgetCmd procedure, "activate" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 activate 1} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.8 {MenuWidgetCmd procedure, "add" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 add type ?options?"} {}} +test menu-3.9 {MenuWidgetCmd procedure, "add" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add foo} msg] $msg [destroy .m1] +} {1 {bad menu entry type "foo": must be cascade, checkbutton, command, radiobutton, or separator} {}} +test menu-3.10 {MenuWidgetCmd procedure, "add" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add separator} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.11 {MenuWidgetCmd procedure, "cget" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 cget} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 cget option"} {}} +test menu-3.12 {MenuWidgetCmd procedure, "cget" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 cget -gorp} msg] $msg [destroy .m1] +} {1 {unknown option "-gorp"} {}} +test menu-3.13 {MenuWidgetCmd procedure, "cget" option} { + catch {destroy .m1} + menu .m1 + .m1 configure -postcommand "Some string" + list [catch {.m1 cget -postcommand} msg] $msg [destroy .m1] +} {0 {Some string} {}} +test menu-3.14 {MenuWidgetCmd procedure, "clone" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 clone} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 clone newMenuName ?menuType?"} {}} +test menu-3.15 {MenuWidgetCmd procedure, "clone" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 clone a b c d} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 clone newMenuName ?menuType?"} {}} +test menu-3.16 {MenuWidgetCmd procedure, "clone" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 clone .m1.clone1} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.17 {MenuWidgetCmd procedure, "clone" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 clone .m1.clone1 tearoff} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.18 {MenuWidgetCmd procedure, "configure" option} { + catch {destroy .m1} + menu .m1 + list [catch {llength [.m1 configure]} msg] $msg [destroy .m1] +} {0 20 {}} +test menu-3.19 {MenuWidgetCmd procedure, "configure" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 configure -gorp} msg] $msg [destroy .m1] +} {1 {unknown option "-gorp"} {}} +test menu-3.20 {MenuWidgetCmd procedure, "configure" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 configure -postcommand "A random String"} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.21 {MenuWidgetCmd procedure, "configure" option} { + catch {destroy .m1} + menu .m1 + .m1 configure -postcommand "Another string" + list [catch {lindex [.m1 configure -postcommand] 4} msg] $msg [destroy .m1] +} {0 {Another string} {}} +test menu-3.22 {MenuWidgetCmd procedure, "delete" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 delete} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 delete first ?last?"} {}} +test menu-3.23 {MenuWidgetCmd procedure, "delete" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 delete foo} msg] $msg [destroy .m1] +} {1 {bad menu entry index "foo"} {}} +test menu-3.24 {MenuWidgetCmd procedure, "delete" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 delete 0 "foo"} msg] $msg [destroy .m1] +} {1 {bad menu entry index "foo"} {}} +test menu-3.25 {MenuWidgetCmd procedure, "delete" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 delete 0} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.26 {MenuWidgetCmd procedure, "delete" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + list [catch {.m1 delete 1 0} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.27 {MenuWidgetCmd procedure, "delete" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "1" + .m1 add command -label "2" + .m1 add command -label "3" + list [catch {.m1 delete 1 3} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.28 {MenuWidgetCmd procedure, "delete" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "1" + .m1 add command -label "2" + .m1 add command -label "3" + .m1 activate 2 + list [catch {.m1 delete 1 3} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.29 {MenuWidgetCmd procedure, "delete" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "1" + .m1 add command -label "2" + .m1 add command -label "3" + .m1 activate 3 + list [catch {.m1 delete 1} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.30 {MenuWidgetCmd procedure, "entrycget" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 entrycget} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 entrycget index option"} {}} +test menu-3.31 {MenuWidgetCmd procedure, "entrycget" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 entrycget index option foo} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 entrycget index option"} {}} +test menu-3.32 {MenuWidgetCmd procedure, "entrycget" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 entrycget foo -label} msg] $msg [destroy .m1] +} {1 {bad menu entry index "foo"} {}} +test menu-3.33 {MenuWidgetCmd procedure, "entrycget" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 entrycget 1 -label} msg] $msg [destroy .m1] +} {0 test {}} +test menu-3.34 {MenuWidgetCmd procedure, "entryconfigure" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 entryconfigure} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 entryconfigure index ?option value ...?"} {}} +test menu-3.35 {MenuWidgetCmd procedure, "entryconfigure" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 entryconfigure foo} msg] $msg [destroy .m1] +} {1 {bad menu entry index "foo"} {}} +test menu-3.36 {MenuWidgetCmd procedure, "entryconfigure" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {llength [.m1 entryconfigure 1]} msg] $msg [destroy .m1] +} {0 14 {}} +test menu-3.37 {MenuWidgetCmd procedure, "entryconfigure" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {lindex [.m1 entryconfigure 1 -label] 4} msg] $msg [destroy .m1] +} {0 test {}} +test menu-3.38 {MenuWidgetCmd procedure, "entryconfigure" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 entryconfigure 1 -label "changed" + list [catch {lindex [.m1 entryconfigure 1 -label] 4} msg] $msg [destroy .m1] +} {0 changed {}} +test menu-3.39 {MenuWidgetCmd procedure, "index" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 index} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 index string"} {}} +test menu-3.40 {MenuWidgetCmd procedure, "index" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 index foo} msg] $msg [destroy .m1] +} {1 {bad menu entry index "foo"} {}} +test menu-3.41 {MenuWidgetCmd procedure, "index" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 index "test"} msg] $msg [destroy .m1] +} {0 1 {}} +test menu-3.42 {MenuWidgetCmd procedure, "insert" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 insert} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 insert index type ?options?"} {}} +test menu-3.43 {MenuWidgetCmd procedure, "insert" option} { + catch {destroy .m1} + menu .m1 + .m1 insert 1 command -label "test" + list [catch {.m1 entrycget 1 -label} msg] $msg [destroy .m1] +} {0 test {}} +test menu-3.44 {MenuWidgetCmd procedure, "invoke" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 invoke} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 invoke index"} {}} +test menu-3.45 {MenuWidgetCmd procedure, "invoke" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 invoke foo} msg] $msg [destroy .m1] +} {1 {bad menu entry index "foo"} {}} +test menu-3.46 {MenuWidgetCmd procedure, "invoke" option} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + .m1 add command -label "set foo" -command "set foo hello" + list [catch {.m1 invoke 1} msg] $msg [catch {set foo} msg2] $msg2 [catch {unset foo} msg3] $msg3 [destroy .m1] +} {0 hello 0 hello 0 {} {}} +test menu-3.47 {MenuWidgetCmd procedure, "post" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "On Windows, hit Escape to get this menu to go away" + list [catch {.m1 post} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 post x y"} {}} +test menu-3.48 {MenuWidgetCmd procedure, "post" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 post foo 40} msg] $msg [destroy .m1] +} {1 {expected integer but got "foo"} {}} +test menu-3.49 {MenuWidgetCmd procedure, "post" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 post 40 bar} msg] $msg [destroy .m1] +} {1 {expected integer but got "bar"} {}} +test menu-3.50 {MenuWidgetCmd procedure, "post" option} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "menu-3.53: hit Escape" -command "puts hello" + list [catch {.m1 post 40 40} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.51 {MenuWidgetCmd procedure, "postcascade" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 postcascade} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 postcascade index"} {}} +test menu-3.52 {MenuWidgetCmd procedure, "postcascade" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 postcascade foo} msg] $msg [destroy .m1] +} {1 {bad menu entry index "foo"} {}} +test menu-3.53 {MenuWidgetCmd procedure, "postcascade" option} {menuInteractive} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add command -label "menu-3.56 - hit Escape" + menu .m2 + .m1 post 40 40 + .m1 add cascade -menu .m2 + list [catch {.m1 postcascade 1} msg] $msg [destroy .m1 .m2] +} {0 {} {}} +test menu-3.54 {MenuWidgetCmd procedure, "postcascade" option} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + .m1 add cascade -menu .m2 -label "menu-3.57 - hit Escape" + .m1 postcascade 1 + list [catch {.m1 postcascade none} msg] $msg [destroy .m1 .m2] +} {0 {} {}} +test menu-3.55 {MenuWidgetCmd procedure, "type" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 type} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 type index"} {}} +test menu-3.56 {MenuWidgetCmd procedure, "type" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 type foo} msg] $msg [destroy .m1] +} {1 {bad menu entry index "foo"} {}} +test menu-3.57 {MenuWidgetCmd procedure, "type" option} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 type 1} msg] $msg [destroy .m1] +} {0 command {}} +test menu-3.58 {MenuWidgetCmd procedure, "type" option} { + catch {destroy .m1} + menu .m1 + .m1 add separator + list [catch {.m1 type 1} msg] $msg [destroy .m1] +} {0 separator {}} +test menu-3.59 {MenuWidgetCmd procedure, "type" option} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label "test" + list [catch {.m1 type 1} msg] $msg [destroy .m1] +} {0 checkbutton {}} +test menu-3.60 {MenuWidgetCmd procedure, "type" option} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label "test" + list [catch {.m1 type 1} msg] $msg [destroy .m1] +} {0 radiobutton {}} +test menu-3.61 {MenuWidgetCmd procedure, "type" option} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label "test" + list [catch {.m1 type 1} msg] $msg [destroy .m1] +} {0 cascade {}} +test menu-3.62 {MenuWidgetCmd procedure, "type" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 type 0} msg] $msg [destroy .m1] +} {0 tearoff {}} +test menu-3.63 {MenuWidgetCmd procedure, "unpost" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 unpost foo} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 unpost"} {}} +test menu-3.64 {MenuWidgetCmd procedure, "unpost" option} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "menu-3.68 - hit Escape" + .m1 post 40 40 + list [catch {.m1 unpost} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-3.65 {MenuWidgetCmd procedure, "yposition" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 yposition} msg] $msg [destroy .m1] +} {1 {wrong # args: should be ".m1 yposition index"} {}} +test menu-3.66 {MenuWidgetCmd procedure, "yposition" option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 yposition 1}] [destroy .m1] +} {0 {}} +test menu-3.67 {MenuWidgetCmd procedure, bad option} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 foo} msg] $msg [destroy .m1] +} {1 {bad option "foo": must be activate, add, cget, clone, configure, delete, entrycget, entryconfigure, index, insert, invoke, post, postcascade, type, unpost, or yposition} {}} + +test menu-4.1 {TkInvokeMenu} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 invoke 0} msg] [destroy .m1] +} {0 {}} +test menu-4.2 {TkInvokeMenu} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + .m1 add checkbutton -label "test" -variable foo -onvalue on -offvalue off + list [catch {.m1 invoke 1} msg] $msg [catch {set foo} msg2] $msg2 [catch {unset foo} msg3] $msg3 [destroy .m1] +} {0 {} 0 on 0 {} {}} +test menu-4.3 {TkInvokeMenu} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + .m1 add checkbutton -label "test" -variable foo -onvalue on -offvalue off + .m1 invoke 1 + list [catch {.m1 invoke 1} msg] $msg [catch {set foo} msg2] $msg2 [catch {unset foo} msg3] $msg3 [destroy .m1] +} {0 {} 0 off 0 {} {}} +test menu-4.4 {TkInvokeMenu} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + .m1 add radiobutton -label "1" -variable foo -value one + .m1 add radiobutton -label "2" -variable foo -value two + .m1 add radiobutton -label "3" -variable foo -value three + list [catch {.m1 invoke 1} msg] $msg [catch {set foo} msg2] $msg2 [catch {unset foo} msg3] $msg3 [destroy .m1] +} {0 {} 0 one 0 {} {}} +test menu-4.5 {TkInvokeMenu} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + .m1 add radiobutton -label "1" -variable foo -value one + .m1 add radiobutton -label "2" -variable foo -value two + .m1 add radiobutton -label "3" -variable foo -value three + list [catch {.m1 invoke 2} msg] $msg [catch {set foo} msg2] $msg2 [catch {unset foo} msg3] $msg3 [destroy .m1] +} {0 {} 0 two 0 {} {}} +test menu-4.6 {TkInvokeMenu} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + .m1 add radiobutton -label "1" -variable foo -value one + .m1 add radiobutton -label "2" -variable foo -value two + .m1 add radiobutton -label "3" -variable foo -value three + list [catch {.m1 invoke 3} msg] $msg [catch {set foo} msg2] $msg2 [catch {unset foo} msg3] $msg3 [destroy .m1] +} {0 {} 0 three 0 {} {}} +test menu-4.7 {TkInvokeMenu} { + catch {destroy .m1} + catch {unset menu_test} + menu .m1 + .m1 add command -label "test" -command "set menu_test menu-4.8" + list [catch {.m1 invoke 1} msg] $msg [catch {set menu_test} msg2] $msg2 [catch {unset menu_test} msg3] $msg3 [destroy .m1] +} {0 menu-4.8 0 menu-4.8 0 {} {}} +test menu-4.8 {TkInvokeMenu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label "test" -menu .m1.m2 + list [catch {.m1 invoke 1} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-4.9 {TkInvokeMenu} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" -command ".m1 delete 1" + list [catch {.m1 invoke 1} msg] $msg [catch {.m1 type "test"} msg2] $msg2 [destroy .m1] +} {0 {} 1 {bad menu entry index "test"} {}} + +test menu-5.1 {DestroyMenuInstance} { + catch {destroy .m1} + menu .m1 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-5.2 {DestroyMenuInstance - cascade menu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add cascade -menu .m2 + menu .m2 + list [catch {destroy .m2} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-5.3 {DestroyMenuInstance - multiple cascade parents} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + .m1 add cascade -menu .m3 + menu .m2 + .m2 add cascade -menu .m3 + menu .m3 + list [catch {destroy .m3} msg] $msg [destroy .m1 .m2] +} {0 {} {}} +test menu-5.4 {DestroyMenuInstance - multiple cascade parents} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + catch {destroy .m4} + menu .m1 + .m1 add cascade -menu .m4 + menu .m2 + .m2 add cascade -menu .m4 + menu .m3 + .m3 add cascade -menu .m4 + menu .m4 + list [catch {destroy .m4} msg] $msg [destroy .m1 .m2 .m3] +} {0 {} {}} +test menu-5.5 {DestroyMenuInstance - cascades of cloned menus} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + .m1 add cascade -menu .m2 + . configure -menu .m1 + list [catch {destroy .m2} msg] $msg [.m1 entrycget 1 -menu] [. configure -menu ""] [destroy .m1] +} {0 {} .m2 {} {}} +test menu-5.6 {DestroyMenuInstance - cascades of cloned menus} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .t2} + menu .m1 + .m1 add cascade -menu .m2 + menu .m2 + . configure -menu .m1 + toplevel .t2 + wm geometry .t2 +0+0 + .t2 configure -menu .m1 + list [catch {destroy .m2} msg] $msg [. configure -menu ""] [destroy .t2 .m1] +} {0 {} {} {}} +test menu-5.7 {DestroyMenuInstance - basic clones} { + catch {destroy .m1} + menu .m1 + set tearoff [tkTearOffMenu .m1] + list [catch {destroy $tearoff} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-5.8 {DestroyMenuInstance - multiple clones} { + catch {destroy .m1} + menu .m1 + set tearoff1 [tkTearOffMenu .m1] + set tearoff2 [tkTearOffMenu .m1] + list [catch {destroy $tearoff1} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-5.9 {DestroyMenuInstace - master menu} { + catch {destroy .m1} + menu .m1 + tkTearOffMenu .m1 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-5.10 {DestroyMenuInstance - freeing entries} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-5.11 {DestroyMenuInstace - no entries} { + catch {destroy .m1} + menu .m1 + .m1 configure -tearoff 0 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-5.12 {DestroyMenuInstance - platform data} { + catch {destroy .m1} + menu .m1 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-5.13 {DestroyMenuInstance - clones when mismatched tearoffs} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + .m1 add cascade -menu .m2 + set tearoff [tkTearOffMenu .m1 40 40] + list [destroy .m2] [destroy .m1] +} {{} {}} + +test menu-6.1 {TkDestroyMenu} { + catch {destroy .m1} + menu .m1 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-6.2 {TkDestroyMenu - reentrancy} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + bind .m1 <Destroy> {destroy .m1} + menu .m2 + bind .m2 <Destroy> {destroy .m2} + list [catch {destroy .m1} msg] $msg [destroy .m2] +} {0 {} {}} +test menu-6.3 {TkDestroyMenu - reentrancy} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + bind .m1 <Destroy> {destroy .m2} + .m1 clone .m2 + .m1 clone .m3 + list [catch {destroy .m1} msg] $msg [winfo exists .m2] +} {0 {} 0} +test menu-6.4 {TkDestroyMenu - reentrancy - clones} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 clone .m2 + .m1 clone .m1.m3 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-6.5 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 clone .m2 + destroy .m1 + winfo exists .m2 +} {0} +test menu-6.6 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 clone .m2 tearoff + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-6.7 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 clone .m2 + destroy .m2 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-6.8 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + .m1 clone .m2 + .m1 clone .m3 + destroy .m1 + list [winfo exists .m2] [winfo exists .m3] +} {0 0} +test menu-6.9 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + .m1 clone .m2 + .m1 clone .m3 + list [catch {destroy .m2} msg] $msg [catch {destroy .m3} msg2] $msg2 [catch {destroy .m1} msg3] $msg3 +} {0 {} 0 {} 0 {}} +test menu-6.10 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + .m1 clone .m2 + .m1 clone .m3 + list [catch {destroy .m3} msg] $msg [catch {destroy .m1} msg2] $msg2 +} {0 {} 0 {}} +test menu-6.11 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + catch {destroy .m4} + menu .m1 + .m1 clone .m2 + .m1 clone .m3 + .m1 clone .m4 + list [catch {destroy .m2} msg1] $msg1 [catch {destroy .m1} msg2] $msg2 +} {0 {} 0 {}} +test menu-6.12 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + catch {destroy .m4} + menu .m1 + .m1 clone .m2 + .m1 clone .m3 + .m1 clone .m4 + list [catch {destroy .m3} msg1] $msg1 [catch {destroy .m1} msg2] $msg2 +} {0 {} 0 {}} +test menu-6.13 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + catch {destroy .m4} + menu .m1 + .m1 clone .m2 + .m1 clone .m3 + .m1 clone .m4 + list [catch {destroy .m4} msg1] $msg1 [catch {destroy .m1} msg2] $msg2 +} {0 {} 0 {}} +test menu-6.14 {TkDestroyMenu} { + catch {destroy .m1} + menu .m1 + . configure -menu .m1 + list [catch {destroy .m1} msg] $msg [. configure -menu ""] +} {0 {} {}} +test menu-6.15 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .t2} + menu .m1 + toplevel .t2 + wm geometry .t2 +0+0 + . configure -menu .m1 + .t2 configure -menu .m1 + list [catch {destroy .m1} msg] $msg [destroy .t2] [. configure -menu ""] +} {0 {} {} {}} +test menu-6.16 {TkDestroyMenu} { + catch {destroy .m1} + catch {destroy .t2} + catch {destroy .t3} + menu .m1 + toplevel .t2 + wm geometry .t2 +0+0 + toplevel .t3 + wm geometry .t3 +0+0 + . configure -menu .m1 + .t2 configure -menu .m1 + .t3 configure -menu .m1 + list [catch {destroy .m1} msg] $msg [destroy .t2] [destroy .t3] [. configure -menu ""] +} {0 {} {} {} {}} + +test menu-7.1 {UnhookCascadeEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-7.2 {UnhookCascadeEntry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m2 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-7.3 {UnhookCascadeEntry} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + .m2 add cascade -menu .cascade + .m1 add cascade -menu .cascade + list [catch {destroy .m1} msg] $msg [destroy .m2] +} {0 {} {}} +test menu-7.4 {UnhookCascadeEntry} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + .m1 add cascade -menu .cascade + .m2 add cascade -menu .cascade + list [catch {destroy .m1} msg] $msg [destroy .m2] +} {0 {} {}} +test menu-7.5 {UnhookCascadeEntry} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + menu .m2 + menu .m3 + .m1 add cascade -menu .cascade + .m2 add cascade -menu .cascade + .m3 add cascade -menu .cascade + list [catch {destroy .m1} msg] $msg [destroy .m2 .m3] +} {0 {} {}} +test menu-7.6 {UnhookCascadeEntry} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + menu .m2 + menu .m3 + .m1 add cascade -menu .cascade + .m2 add cascade -menu .cascade + .m3 add cascade -menu .cascade + list [catch {destroy .m2} msg] $msg [destroy .m1 .m3] +} {0 {} {}} +test menu-7.7 {UnhookCascadeEntry} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + menu .m2 + menu .m3 + .m1 add cascade -menu .cascade + .m2 add cascade -menu .cascade + .m3 add cascade -menu .cascade + list [catch {destroy .m3} msg] $msg [destroy .m1 .m2] +} {0 {} {}} +test menu-7.8 {UnhookCascadeEntry} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + .m1 add cascade -menu .m2 + list [catch {destroy .m1} msg] $msg [destroy .m2] +} {0 {} {}} +test menu-7.9 {UnhookCascadeEntry} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + .m1 add cascade -menu .m2 + destroy .m1 + list [catch {destroy .m2} msg] $msg +} {0 {}} + +test menu-8.1 {DestroyMenuEntry} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + .m1 add cascade -menu .m2 + list [catch {.m1 delete 1} msg] $msg [destroy .m1 .m2] +} {0 {} {}} +test menu-8.2 {DestroyMenuEntry} { + catch {image delete image1a} + catch {destroy .m1} + image create photo image1a -file [file join $tk_library demos images earth.gif] + menu .m1 + .m1 add command -image image1a + list [catch {.m1 delete 1} msg] $msg [destroy .m1] [image delete image1a] +} {0 {} {} {}} +test menu-8.3 {DestroyMenuEntry} { + catch {eval image delete [image names]} + catch {destroy .m1} + image create test image1 + image create test image2 + menu .m1 + .m1 add checkbutton -image image1 -selectimage image2 + .m1 invoke 1 + list [catch {.m1 delete 1} msg] $msg [destroy .m1] [eval image delete [image names]] +} {0 {} {} {}} +test menu-8.4 {DestroyMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -variable foo + list [catch {.m1 delete 1} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-8.5 {DestroyMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 delete 1} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-8.6 {DestroyMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + .m1 add command -label "two" + list [catch {.m1 delete 1} msg] $msg [.m1 entrycget 1 -label] [destroy .m1] +} {0 {} two {}} +test menu-8.7 {DestroyMenuEntry} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add command -label "one" + .m1 clone .m2 tearoff + list [catch {.m2 delete 0} msg] $msg [destroy .m1] +} {0 {} {}} + +# test menu-9 - Can only change when fonts change on system, which cannot +# be done from tcl. + +test menu-9.1 {ConfigureMenu} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 configure -postcommand "beep"} msg] $msg [.m1 cget -postcommand] [destroy .m1] +} {0 {} beep {}} +test menu-9.2 {ConfigureMenu} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 configure -tearoff 0} msg] $msg [.m1 entrycget 1 -label] [destroy .m1] +} {0 {} test {}} +test menu-9.3 {ConfigureMenu} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 configure -postcommand "beep"} msg] $msg [.m1 cget -postcommand] [destroy .m1] +} {0 {} beep {}} +test menu-9.4 {ConfigureMenu} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 configure -fg red} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-9.5 {ConfigureMenu} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add command -label "two" + list [catch {.m1 configure -fg red} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-9.6 {ConfigureMenu} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add command -label "two" + .m1 add command -label "three" + list [catch {.m1 configure -fg red} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-9.7 {ConfigureMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 clone .m2 tearoff + list [catch {.m1 configure -fg red} msg] $msg [.m2 cget -fg] [destroy .m1] +} {0 {} red {}} +test menu-9.8 {ConfigureMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 clone .m2 tearoff + list [catch {.m2 configure -fg red} msg] $msg [.m1 cget -fg] [destroy .m1] +} {0 {} red {}} +test menu-9.9 {ConfigureMenu} { + catch {destroy .m1} + menu .m1 + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} + +test menu-10.1 {ConfigureMenuEntry} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + .m1 add checkbutton -variable foo -onvalue on -offvalue off -label "Nonsense" + list [catch {.m1 entryconfigure 1 -variable bar} msg] $msg [.m1 entrycget 1 -variable] [destroy .m1] +} {0 {} bar {}} +test menu-10.2 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 entryconfigure 1 -label ""} msg] $msg [.m1 entrycget 1 -label] [destroy .m1] +} {0 {} {} {}} +test menu-10.3 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command + list [catch {.m1 entryconfigure 1 -label "test"} cmd] $cmd [.m1 entrycget 1 -label] [destroy .m1] +} {0 {} test {}} +test menu-10.4 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command + list [catch {.m1 entryconfigure 1 -accel "S"} msg] $msg [.m1 entrycget 1 -accel] [destroy .m1] +} {0 {} S {}} +test menu-10.5 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command + list [catch {.m1 entryconfigure 1 -label "test"} msg] $msg [.m1 entrycget 1 -label] [destroy .m1] +} {0 {} test {}} +test menu-10.6 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command + list [catch {.m1 entryconfigure 1 -label "test"} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-10.7 {ConfigureMenuEntry} { + catch {destroy .m1} + catch {destroy .m2} + menu .m2 + menu .m1 + .m1 add cascade + list [catch {.m1 entryconfigure 1 -label "test" -menu .m2} msg] $msg [destroy .m1 .m2] +} {0 {} {}} +test menu-10.8 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade + list [catch {.m1 entryconfigure 1 -label "test" -menu .m2} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-10.9 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m3 + list [catch {.m1 entryconfigure 1 -label "test" -menu .m2} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-10.10 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade + list [catch {.m1 entryconfigure 1 -label "test" -menu .m2} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-10.11 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m2 + list [catch {.m1 entryconfigure 1 -label "test" -menu .m2} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-10.12 {ConfigureMenuEntry} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + catch {destroy .m4} + catch {destroy .m5} + menu .m1 + menu .m2 + .m2 add cascade -menu .m1 + menu .m3 + .m3 add cascade -menu .m1 + menu .m4 + .m4 add cascade -menu .m1 + menu .m5 + .m5 add cascade + list [catch {.m5 entryconfigure 1 -label "test" -menu .m1} msg] $msg [destroy .m1 .m2 .m3 .m4 .m5] +} {0 {} {}} +test menu-10.13 {ConfigureMenuEntry} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + catch {destroy .m4} + menu .m1 + menu .m2 + .m2 add cascade -menu .m1 + menu .m3 + .m3 add cascade -menu .m1 + menu .m4 + .m4 add cascade -menu .m1 + list [catch {.m3 entryconfigure 1 -label "test" -menu .m1} msg] $msg [destroy .m1 .m2 .m3 .m4] +} {0 {} {}} +test menu-10.14 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton + list [catch {.m1 entryconfigure 1 -variable "test"} msg] $msg [.m1 entrycget 1 -variable] [destroy .m1] +} {0 {} test {}} +test menu-10.15 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add checkbutton -label "test"} msg] $msg [.m1 entrycget 1 -variable] [destroy .m1] +} {0 {} test {}} +test menu-10.16 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add radiobutton -label "test"} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-10.17 {ConfigureMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton + list [catch {.m1 entryconfigure 1 -onvalue "test"} msg] $msg [.m1 entrycget 1 -onvalue] [destroy .m1] +} {0 {} test {}} +test menu-10.18 {ConfigureMenuEntry} { + catch {destroy .m1} + catch {image delete image1} + menu .m1 + .m1 add command + image create test image1 + list [catch {.m1 entryconfigure 1 -image image1} msg] $msg [destroy .m1] [image delete image1] +} {0 {} {} {}} +test menu-10.19 {ConfigureMenuEntry} { + catch {destroy .m1} + catch {image delete image1} + catch {image delete image2} + image create test image1 + image create photo image2 -file [file join $tk_library demos images earth.gif] + menu .m1 + .m1 add command -image image1 + list [catch {.m1 entryconfigure 1 -image image2} msg] $msg [destroy .m1] [image delete image1] [image delete image2] +} {0 {} {} {} {}} +test menu-10.20 {ConfigureMenuEntry} { + catch {destroy .m1} + catch {image delete image1} + catch {image delete image2} + image create photo image1 -file [file join $tk_library demos images earth.gif] + image create test image2 + menu .m1 + .m1 add checkbutton -image image1 + list [catch {.m1 entryconfigure 1 -selectimage image2} msg] $msg [destroy .m1] [image delete image1] [image delete image2] +} {0 {} {} {} {}} +test menu-10.21 {ConfigureMenuEntry} { + catch {destroy .m1} + catch {image delete image1} + catch {image delete image2} + catch {image delete image3} + image create photo image1 -file [file join $tk_library demos images earth.gif] + image create test image2 + image create test image3 + menu .m1 + .m1 add checkbutton -image image1 -selectimage image2 + list [catch {.m1 entryconfigure 1 -selectimage image3} msg] $msg [destroy .m1] [image delete image1] [image delete image2] [image delete image3] +} {0 {} {} {} {} {}} + +test menu-11.1 {ConfigureMenuCloneEntries} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + .m1 clone .m2 + .m2 configure -tearoff 0 + .m1 clone .m3 + .m1 add command -label "test" + .m1 add command -label "test2" + list [list [catch {.m1 entryconfigure 1 -gork "foo"} msg] $msg] [destroy .m1] +} {{1 {unknown option "-gork"}} {}} +test menu-11.2 {ConfigureMenuCloneEntries} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + catch {destroy .m4} + menu .m1 + .m1 clone .m2 + menu .m3 + .m1 add cascade -menu .m3 + menu .m4 + list [catch {.m1 entryconfigure 1 -menu .m4} msg] $msg [destroy .m1] [destroy .m3] [destroy .m4] +} {0 {} {} {} {}} +test menu-11.3 {ConfigureMenuCloneEntries} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 clone .m2 + .m1 add cascade -label dummy + list [catch {.m1 entryconfigure dummy -menu .m3} msg] $msg [destroy .m1] +} {0 {} {}} + +test menu-12.1 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "active" + .m1 add command -label "test2" + .m1 add command -label "test3" + .m1 activate 2 + list [catch {.m1 entrycget active -label} msg] $msg [destroy .m1] +} {0 test2 {}} +test menu-12.2 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "last" + .m1 add command -label "test2" + .m1 add command -label "test3" + .m1 activate 2 + list [catch {.m1 entrycget last -label} msg] $msg [destroy .m1] +} {0 test3 {}} +test menu-12.3 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "last" + .m1 add command -label "test2" + .m1 add command -label "test3" + .m1 activate 2 + list [catch {.m1 entrycget end -label} msg] $msg [destroy .m1] +} {0 test3 {}} +test menu-12.4 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 insert last command -label "test2"} msg] $msg [.m1 entrycget last -label] [destroy .m1] +} {0 {} test2 {}} +test menu-12.5 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 insert end command -label "test2"} msg] $msg [.m1 entrycget end -label] [destroy .m1] +} {0 {} test2 {}} +test menu-12.6 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "active" + .m1 add command -label "test2" + .m1 add command -label "test3" + .m1 activate 2 + list [catch {.m1 entrycget none -label} msg] $msg [destroy .m1] +} {0 {} {}} +#test menu-13.7 - Need to add @test here. +test menu-12.7 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "active" + .m1 add command -label "test2" + .m1 add command -label "test3" + list [catch {.m1 entrycget 1 -label} msg] $msg [destroy .m1] +} {0 active {}} +test menu-12.8 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "active" + list [catch {.m1 entrycget -1 -label} msg] $msg [destroy .m1] +} {1 {bad menu entry index "-1"} {}} +test menu-12.9 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add command -label "test2" + list [catch {.m1 entrycget 999 -label} msg] $msg [destroy .m1] +} {0 test2 {}} +test menu-12.10 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 insert 999 command -label "test" + list [catch {.m1 entrycget 1 -label} msg] $msg [destroy .m1] +} {0 test {}} +test menu-12.11 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "1test" + list [catch {.m1 entrycget 1test -label} msg] $msg [destroy .m1] +} {0 1test {}} +test menu-12.12 {TkGetMenuIndex} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add command -label "test2" -command "beep" + .m1 add command -label "test3" + list [catch {.m1 entrycget test2 -command} msg] $msg [destroy .m1] +} {0 beep {}} + +test menu-13.1 {MenuCmdDeletedProc} { + catch {destroy .m1} + menu .m1 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-13.2 {MenuCmdDeletedProc} { + catch {destroy .m1} + menu .m1 + .m1 clone .m2 + list [catch {destroy .m1} msg] $msg +} {0 {}} + +test menu-14.1 {MenuNewEntry} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "test"} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-14.2 {MenuNewEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add command -label "test3" + list [catch {.m1 insert 2 command -label "test2"} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-14.3 {MenuNewEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 add command -label "test2"} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-14.4 {MenuNewEntry} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "test"} msg] $msg [destroy .m1] +} {0 {} {}} + +test menu-15.1 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 insert foo command -label "test"} msg] $msg [destroy .m1] +} {1 {bad menu entry index "foo"} {}} +test menu-15.2 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 insert test command -label "foo"} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-15.3 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 insert -1 command -label "test"} msg] $msg [destroy .m1] +} {1 {bad menu entry index "-1"} {}} +test menu-15.4 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 insert 0 command -label "test2" + list [catch {.m1 entrycget 1 -label} msg] $msg [destroy .m1] +} {0 test2 {}} +test menu-15.5 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add cascade} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-15.6 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add checkbutton} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-15.7 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-15.8 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add radiobutton} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-15.9 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add separator} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-15.10 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add blork} msg] $msg [destroy .m1] +} {1 {bad menu entry type "blork": must be cascade, checkbutton, command, radiobutton, or separator} {}} +test menu-15.11 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-15.12 {MenuAddOrInsert} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + .m1 clone .m2 + .m2 clone .m3 + list [catch {.m2 add command -label "test"} msg1] $msg1 [catch {.m1 entrycget 1 -label} msg2] $msg2 [catch {.m3 entrycget 1 -label} msg3] $msg3 [destroy .m1] +} {0 {} 0 test 0 test {}} +test menu-15.13 {MenuAddOrInsert} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + .m1 clone .m2 + .m2 clone .m3 + list [catch {.m3 add command -label "test"} msg1] $msg1 [catch {.m1 entrycget 1 -label} msg2] $msg2 [catch {.m2 entrycget 1 -label} msg3] $msg3 [destroy .m1] +} {0 {} 0 test 0 test {}} +test menu-15.14 {MenuAddOrInsert} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -blork} msg] $msg [destroy .m1] +} {1 {unknown option "-blork"} {}} +test menu-15.15 {MenuAddOrInsert} { + catch {destroy .m1} + catch {destroy .container} + menu .m1 + .m1 add command -label "File" + menu .container + . configure -menu .container + list [catch {.container add cascade -label "File" -menu .m1} msg] $msg [. configure -menu ""] [destroy .container .m1] +} {0 {} {} {}} +test menu-15.16 {MenuAddOrInsert} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + set tearoff [tkTearOffMenu .m2] + list [catch {.m2 add cascade -menu .m1} msg] $msg [$tearoff unpost] [catch {destroy .m1} msg2] $msg2 [catch {destroy .m2} msg3] $msg3 +} {0 {} {} 0 {} 0 {}} +test menu-15.17 {MenuAddOrInsert} { + catch {destroy .m1} + catch {destroy .container} + menu .m1 + menu .container + . configure -menu .container + set tearoff [tkTearOffMenu .container] + list [catch {.container add cascade -label "File" -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1 .container] +} {0 {} {} {}} +test menu-15.18 {MenuAddOrInsert} { + catch {destroy .m1} + catch {destroy .container} + menu .m1 + menu .container + .container add cascade -menu .m1 + . configure -menu .container + list [catch {.container add cascade -label "File" -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1 .container] +} {0 {} {} {}} +test menu-15.19 {MenuAddOrInsert - Insert a cascade deep into the tree} { + catch {destroy .menubar} + menu .menubar + menu .menubar.test -tearoff 0 + .menubar add cascade -label Test -underline 0 -menu .menubar.test + menu .menubar.test.cascade -tearoff 0 + .menubar.test.cascade add command -label SubItem -command "puts SubItemSelected" + . configure -menu .menubar + list [catch {.menubar.test add cascade -label SubMenu \ + -menu .menubar.test.cascade} msg] \ + [info commands .\#menubar.\#menubar\#test.\#menubar\#test\#cascade] \ + [. configure -menu ""] [destroy .menubar] +} {0 .#menubar.#menubar#test.#menubar#test#cascade {} {}} + +test menu-16.1 {MenuVarProc} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + set foo "hello" + list [catch {.m1 add checkbutton -variable foo -onvalue hello -offvalue goodbye} msg] $msg [catch {unset foo} msg2] $msg2 [destroy .m1] +} {0 {} 0 {} {}} +# menu-17.2 - Don't know how to generate the flags in the if +test menu-16.2 {MenuVarProc} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + list [catch {.m1 add checkbutton -variable foo -onvalue hello -offvalue goodbye} msg] $msg [set foo ""] [destroy .m1] +} {0 {} {} {}} +test menu-16.3 {MenuVarProc} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + set foo "hello" + list [catch {.m1 add checkbutton -variable foo -onvalue hello -offvalue goodbye} msg] $msg [set foo "hello"] [destroy .m1] [catch {unset foo} msg2] $msg2 +} {0 {} hello {} 0 {}} +test menu-16.4 {MenuVarProc} { + catch {destroy .m1} + menu .m1 + set foo "goodbye" + list [catch {.m1 add checkbutton -variable foo -onvalue hello -offvalue goodbye} msg] $msg [set foo "hello"] [destroy .m1] [catch {unset foo} msg2] $msg2 +} {0 {} hello {} 0 {}} +test menu-16.5 {MenuVarProc} { + catch {destroy .m1} + menu .m1 + set foo "hello" + list [catch {.m1 add checkbutton -variable foo -onvalue hello -offvalue goodbye} msg] $msg [set foo "goodbye"] [destroy .m1] [catch {unset foo} msg2] $msg2 +} {0 {} goodbye {} 0 {}} + +test menu-17.1 {TkActivateMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 activate 1} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-17.2 {TkActivateMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [catch {.m1 activate 0} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-17.3 {TkActivateMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add command -label "test2" + .m1 activate 1 + list [catch {.m1 activate 2} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-17.4 {TkActivateMenuEntry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add command -label "test2" + .m1 activate 1 + list [catch {.m1 activate 1} msg] $msg [destroy .m1] +} {0 {} {}} + +test menu-18.1 {TkPostCommand} {menuInteractive} { + catch {destroy .m1} + menu .m1 -postcommand "set menu_test menu-19.1" + .m1 add command -label "menu-19.1 - hit Escape" + list [catch {.m1 post 40 40} msg] $msg [.m1 unpost] [set menu_test] [destroy .m1] +} {0 menu-19.1 {} menu-19.1 {}} +test menu-18.2 {TkPostCommand} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "menu-19.2 - hit Escape" + list [catch {.m1 post 40 40} msg] $msg [.m1 unpost] [destroy .m1] +} {0 {} {} {}} + +test menu-19.1 {CloneMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + list [catch {.m1 clone .m2} msg1] $msg1 [destroy .m1] +} {0 {} {}} +test menu-19.2 {CloneMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + list [catch {.m1 clone .m2 normal} msg1] $msg1 [destroy .m1] +} {0 {} {}} +test menu-19.3 {CloneMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + list [catch {.m1 clone .m2 tearoff} msg1] $msg1 [destroy .m1] +} {0 {} {}} +test menu-19.4 {CloneMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + list [catch {.m1 clone .m2 menubar} msg1] $msg1 [destroy .m1] +} {0 {} {}} +test menu-19.5 {CloneMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + list [catch {.m1 clone .m2 foo} msg1] $msg1 [destroy .m1] +} {1 {bad menu type - must be normal, tearoff, or menubar} {}} +test menu-19.6 {CloneMenu - hooking up bookeeping ptrs} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + list [catch {.m1 clone .m2} msg] $msg [destroy .m1] + } {0 {} {}} + test menu-19.7 {CloneMenu - hooking up bookeeping ptrs - multiple children} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + .m1 clone .m2 + list [catch {.m1 clone .m3} msg] $msg [destroy .m1] + } {0 {} {}} + test menu-19.8 {CloneMenu - cascade entries} { + catch {destroy .m1} + catch {destroy .foo} + menu .m1 + .m1 add cascade -menu .m2 + list [catch {.m1 clone .foo} msg] $msg [destroy .m1] + } {0 {} {}} + test menu-19.9 {CloneMenu - cascades entries} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .foo} + menu .m1 + .m1 add cascade -menu .m2 + menu .m2 + list [catch {.m1 clone .foo} msg] $msg [destroy .m1 .m2] + } {0 {} {}} +test menu-19.10 {CloneMenu - tearoff fields} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + list [catch {.m1 clone .m2 normal} msg1] $msg1 [catch {.m2 cget -tearoff} msg2] $msg2 [destroy .m1] +} {0 {} 0 1 {}} +test menu-19.11 {CloneMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + menu .m2 + list [catch {.m1 clone .m2} msg] $msg [destroy .m1 .m2] +} {1 {window name "m2" already exists in parent} {}} + +test menu-20.1 {MenuDoYPosition} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 yposition glorp} msg] $msg [destroy .m1] +} {1 {bad menu entry index "glorp"} {}} +test menu-20.2 {MenuDoYPosition} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "Test" + list [catch {.m1 yposition 1}] [destroy .m1] +} {0 {}} + +test menu-21.1 {GetIndexFromCoords} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 configure -tearoff 0 + list [catch {.m1 index @5} msg] $msg [destroy .m1] +} {0 0 {}} +test menu-21.2 {GetIndexFromCoords} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 configure -tearoff 0 + list [catch {.m1 index @5,5} msg] $msg [destroy .m1] +} {0 0 {}} + +test menu-22.1 {RecursivelyDeleteMenu} { + catch {destroy .m1} + menu .m1 + . configure -menu .m1 + list [catch {. configure -menu ""} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-22.2 {RecursivelyDeleteMenu} { + catch {destroy .m1} + catch {destroy .m2} + menu .m2 + .m2 add command -label "test2" + menu .m1 + .m1 add cascade -label "test1" -menu .m2 + . configure -menu .m1 + list [catch {. configure -menu ""} msg] $msg [destroy .m1 .m2] +} {0 {} {}} + +test menu-23.1 {TkNewMenuName} { + catch {destroy .m1} + menu .m1 + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test menu-23.2 {TkNewMenuName} { + catch {destroy .m1} + catch {destroy .m1\#0} + menu .m1 + menu .m1\#0 + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test menu-23.3 {TkNewMenuName} { + catch {destroy .#m} + menu .#m + rename .#m hideme + list [catch {. configure -menu [menu .m]} $msg] [. configure -menu ""] [destroy .#m] [destroy .m] [destroy hideme] +} {0 {} {} {} {}} + +test menu-24.1 {TkSetWindowMenuBar} { + . configure -menu "" + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] +} {0 {} {}} +test menu-24.2 {TkSetWindowMenuBar} { + . configure -menu "" + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] +} {0 {} {}} +test menu-24.3 {TkSetWindowMenuBar} { + . configure -menu "" + catch {destroy .m1} + menu .m1 + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test menu-24.4 {TkSetWindowMenuBar} { + catch {destroy .m1} + catch {destroy .m2} + . configure -menu "" + menu .m1 + . configure -menu .m1 + menu .m2 + list [catch {. configure -menu .m2} msg] $msg [. configure -menu ""] [destroy .m1 .m2] +} {0 {} {} {}} +test menu-24.5 {TkSetWindowMenuBar} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + . configure -menu "" + menu .m1 + . configure -menu .m1 + .m1 clone .m2 + menu .m3 + list [catch {. configure -menu .m3} msg] $msg [. configure -menu ""] [destroy .m1 .m3] +} {0 {} {} {}} +test menu-24.6 {TkSetWindowMenuBar} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + . configure -menu "" + menu .m1 + .m1 clone .m2 + . configure -menu .m2 + menu .m3 + list [catch {. configure -menu .m3} msg] $msg [. configure -menu ""] [destroy .m1 .m3] +} {0 {} {} {}} +test menu-24.7 {TkSetWindowMenuBar} { + catch {destroy .m1} + catch {destroy .m2} + . configure -menu "" + menu .m1 + menu .m2 + . configure -menu .m1 + toplevel .t2 + .t2 configure -menu .m1 + list [catch {.t2 configure -menu .m2} msg] $msg [. configure -menu ""] [destroy .t2 .m1 .m2] +} {0 {} {} {}} +test menu-24.8 {TkSetWindowMenuBar} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .t2} + . configure -menu "" + menu .m1 + menu .m2 + . configure -menu .m1 + toplevel .t2 + wm geometry .t2 +0+0 + .t2 configure -menu .m1 + list [catch {. configure -menu .m2} msg] $msg [. configure -menu ""] [destroy .t2 .m1 .m2] +} {0 {} {} {}} +test menu-24.9 {TkSetWindowMenuBar} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .t2} + catch {destroy .t3} + . configure -menu "" + menu .m1 + menu .m2 + . configure -menu .m1 + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + toplevel .t3 -menu .m1 + wm geometry .t3 +0+0 + list [catch {.t3 configure -menu .m2} msg] $msg [. configure -menu ""] [destroy .t2 .t3 .m1 .m2] +} {0 {} {} {}} +test menu-24.10 {TkSetWindowMenuBar} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .t2} + catch {destroy .t3} + . configure -menu "" + menu .m1 + menu .m2 + . configure -menu .m1 + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + toplevel .t3 -menu .m1 + wm geometry .t3 +0+0 + list [catch {.t2 configure -menu .m2} msg] $msg [. configure -menu ""] [destroy .t2 .t3 .m1 .m2] +} {0 {} {} {}} +test menu-24.11 {TkSetWindowMenuBar} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .t2} + catch {destroy .t3} + . configure -menu "" + menu .m1 + menu .m2 + . configure -menu .m1 + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + toplevel .t3 -menu .m1 + wm geometry .t3 +0+0 + list [catch {. configure -menu .m2} msg] $msg [. configure -menu ""] [destroy .t2 .t3 .m1 .m2] +} {0 {} {} {}} +test menu-24.12 {TkSetWindowMenuBar} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test menu-24.13 {TkSetWindowMenuBar} { + . configure -menu "" + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] +} {0 {} {}} +test menu-24.14 {TkSetWindowMenuBar} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test menu-24.15 {TkSetWindowMenuBar} { + . configure -menu "" + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] +} {0 {} {}} +test menu-24.16 {TkSetWindowMenuBar} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + . configure -menu .m1 + list [catch {toplevel .t2 -menu m1} msg] $msg [. configure -menu ""] [destroy .t2 .m1] +} {0 .t2 {} {}} + +test menu-25.1 {DestroyMenuHashTable} { + catch {interp destroy testinterp} + interp create testinterp + load {} Tk testinterp + interp eval testinterp {menu .m1} + list [catch {interp delete testinterp} msg] $msg +} {0 {}} + +test menu-26.1 {GetMenuHashTable} { + catch {interp destroy testinterp} + interp create testinterp + load {} tk testinterp + list [catch {interp eval testinterp {menu .m1}} msg] $msg [interp delete testinterp] +} {0 .m1 {}} + +test menu-27.1 {TkCreateMenuReferences - not there before} { + catch {destroy .m1} + list [catch {menu .m1} msg] $msg [destroy .m1] +} {0 .m1 {}} +test menu-27.2 {TkCreateMenuReferences - there already} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add cascade -menu .m2 + list [catch {menu .m2} msg] $msg [destroy .m1 .m2] +} {0 .m2 {}} + +test menu-28.1 {TkFindMenuReferences - not there} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + .m1 add cascade -menu .m2 + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test menu-29.1 {TkFindMenuReferences - there already} { + catch {destroy .m1} + catch {destroy .m2} + . configure -menu "" + menu .m1 + menu .m2 + .m1 add cascade -menu .m2 + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1 .m2] +} {0 {} {} {}} + +test menu-30.1 {TkFreeMenuReferences - menuPtr} { + catch {destroy .m1} + menu .m1 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test menu-30.2 {TkFreeMenuReferences - cascadePtr} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + .m1 add cascade -menu .m2 + list [catch {.m1 entryconfigure 1 -menu .m3} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-30.3 {TkFreeMenuReferences - topLevelListPtr} { + . configure -menu .m1 + list [catch {. configure -menu ""} msg] $msg +} {0 {}} +test menu-30.4 {TkFreeMenuReferences - not empty} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add cascade -menu .m3 + menu .m2 + .m2 add cascade -menu .m3 + list [catch {.m2 entryconfigure 1 -menu ".foo"} msg] $msg [destroy .m1 .m2] +} {0 {} {}} + +test menu-31.1 {DeleteMenuCloneEntries} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add command -label foo + .m1 clone .m2 + list [catch {.m1 delete 1} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-31.2 {DeleteMenuCloneEntries} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add command -label one + .m1 add command -label two + .m1 add command -label three + .m1 add command -label four + .m1 clone .m2 + list [catch {.m1 delete 2 3} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-31.3 {DeleteMenuCloneEntries} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 -tearoff 0 + .m1 add command -label one + .m1 add command -label two + .m1 add command -label three + .m1 add command -label four + .m1 clone .m2 + .m2 configure -tearoff 1 + list [catch {.m1 delete 1 2} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-31.4 {DeleteMenuCloneEntries} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add command -label one + .m1 add command -label two + .m1 add command -label three + .m1 add command -label four + .m1 clone .m2 + .m2 configure -tearoff 0 + list [catch {.m1 delete 2 3} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-31.5 {DeleteMenuCloneEntries} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add command -label one + .m1 add command -label two + .m1 clone .m2 + .m1 activate one + list [catch {.m1 delete one} msg] $msg [destroy .m1] +} {0 {} {}} +test menu-31.6 {DeleteMenuCloneEntries - reentrancy - crashes tk8.0} { + catch {destroy .m1} + menu .m1 + .m1 add command -label test -command ".m1 delete test ; .m1 add command -label test -command \".m1 delete test\"; .m1 delete test" + list [catch {.m1 invoke test} msg] $msg [destroy .m1] +} {0 {} {}} + +set l [interp hidden] +eval destroy [winfo children .] + +test menu-32.1 {menu vs command hiding} { + catch {destroy .m} + menu .m + interp hide {} .m + destroy .m + list [winfo children .] [interp hidden] +} [list {} $l] + +# menu-34 MenuInit only called at boot time + +deleteWindows diff --git a/tests/menuDraw.test b/tests/menuDraw.test new file mode 100644 index 0000000..291d2a2 --- /dev/null +++ b/tests/menuDraw.test @@ -0,0 +1,546 @@ +# This file is a Tcl script to test drawing of menus in Tk. It is +# organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1996-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) menuDraw.test 1.11 97/06/24 13:50:34 + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\" image" + puts "type, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +proc deleteWindows {} { + foreach i [winfo children .] { + catch [destroy $i] + } +} + +deleteWindows +wm geometry . {} +raise . + +if {$tcl_platform(platform) == "windows" && ![info exists INTERACTIVE]} { + puts " Some tests were skipped because they could not be performed" + puts " automatically on this platform. If you wish to execute them" + puts " interactively, set the TCL variable INTERACTIVE and re-run" + puts " the test." + set testConfig(menuInteractive) 0 +} else { + set testConfig(menuInteractive) 1 +} + +test menuDraw-1.1 {TkMenuInitializeDrawingFields} { + catch {destroy .m1} + list [menu .m1] [destroy .m1] +} {.m1 {}} + +test menuDraw-2.1 {TkIntializeMenuEntryDrawingFields} { + catch {destroy .m1} + menu .m1 + list [.m1 add command] [destroy .m1] +} {{} {}} + +test menuDraw-3.1 {TkMenuFreeDrawOptions} { + catch {destroy .m1} + menu .m1 + list [destroy .m1] +} {{}} + +test menuDraw-4.1 {TkMenuEntryFreeDrawOptions} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "This is a test" + list [destroy .m1] +} {{}} +test menuDraw-4.2 {TkMenuEntryFreeDrawOptions} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label "This is a test." -font "Courier 12" -activeforeground red -background green -selectcolor purple + list [destroy .m1] +} {{}} + +test menuDraw-5.1 {TkMenuConfigureDrawOptions - new menu} { + catch {destroy .m1} + list [menu .m1] [destroy .m1] +} {.m1 {}} +test menuDraw-5.2 {TkMenuConfigureDrawOptions - old menu} { + catch {destroy .m1} + menu .m1 + list [.m1 configure -fg red] [destroy .m1] +} {{} {}} +test menuDraw-5.3 {TkMenuConfigureDrawOptions - no disabledFg} { + catch {destroy .m1} + list [menu .m1 -disabledforeground ""] [destroy .m1] +} {.m1 {}} + +test menuDraw-6.1 {TkMenuConfigureEntryDrawOptions - no tkfont specified} { + catch {destroy .m1} + menu .m1 + list [.m1 add command -label "foo"] [destroy .m1] +} {{} {}} +test menuDraw-6.2 {TkMenuConfigureEntryDrawOptions - tkfont specified} { + catch {destroy .m1} + menu .m1 + list [.m1 add command -label "foo" -font "Courier 12"] [destroy .m1] +} {{} {}} +test menuDraw-6.3 {TkMenuConfigureEntryDrawOptions - active state - wrong entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + list [.m1 entryconfigure 1 -state active] [destroy .m1] +} {{} {}} +test menuDraw-6.4 {TkMenuConfigureEntryDrawOptions - active state - correct entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + .m1 activate 1 + list [.m1 entryconfigure 1 -state active] [destroy .m1] +} {{} {}} +test menuDraw-6.5 {TkMenuConfigureEntryDrawOptions - deactivate entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + .m1 activate 1 + list [.m1 entryconfigure 1 -state normal] [destroy .m1] +} {{} {}} +test menuDraw-6.6 {TkMenuConfigureEntryDrawOptions - bad state} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + list [catch {.m1 entryconfigure 1 -state foo} msg] $msg [destroy .m1] +} {1 {bad state value "foo": must be normal, active, or disabled} {}} +test menuDraw-6.7 {TkMenuConfigureEntryDrawOptions - tkfont specified} { + catch {destroy .m1} + menu .m1 + list [.m1 add command -label "foo" -font "Courier 12"] [destroy .m1] +} {{} {}} +test menuDraw-6.8 {TkMenuConfigureEntryDrawOptions - border specified} { + catch {destroy .m1} + menu .m1 + list [.m1 add command -label "foo" -background "red"] [destroy .m1] +} {{} {}} +test menuDraw-6.9 {TkMenuConfigureEntryDrawOptions - foreground specified} { + catch {destroy .m1} + menu .m1 + list [.m1 add command -label "foo" -foreground "red"] [destroy .m1] +} {{} {}} +test menuDraw-6.10 {TkMenuConfigureEntryDrawOptions - activeBorder specified} { + catch {destroy .m1} + menu .m1 + list [.m1 add command -label "foo" -activebackground "red"] [destroy .m1] +} {{} {}} +test menuDraw-6.11 {TkMenuConfigureEntryDrawOptions - activeforeground specified} { + catch {destroy .m1} + menu .m1 + list [.m1 add command -label "foo" -activeforeground "red"] [destroy .m1] +} {{} {}} +test menuDraw-6.12 {TkMenuConfigureEntryDrawOptions - selectcolor specified} { + catch {destroy .m1} + menu .m1 + list [.m1 add radiobutton -label "foo" -selectcolor "red"] [destroy .m1] +} {{} {}} +test menuDraw-6.13 {TkMenuConfigureEntryDrawOptions - textGC disposal} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" -font "Helvetica 12" + list [.m1 entryconfigure 1 -font "Courier 12"] [destroy .m1] +} {{} {}} +test menuDraw-6.14 {TkMenuConfigureEntryDrawOptions - activeGC disposal} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" -activeforeground "red" + list [.m1 entryconfigure 1 -activeforeground "green"] [destroy .m1] +} {{} {}} +test menuDraw-6.15 {TkMenuConfigureEntryDrawOptions - disabledGC disposal} { + catch {destroy .m1} + menu .m1 -disabledforeground "red" + .m1 add command -label "foo" + list [.m1 configure -disabledforeground "green"] [destroy .m1] +} {{} {}} +test menuDraw-6.16 {TkMenuConfigureEntryDrawOptions - indicatorGC disposal} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label "foo" -selectcolor "red" + list [.m1 entryconfigure 1 -selectcolor "green"] [destroy .m1] +} {{} {}} + +test menuDraw-7.1 {TkEventuallyRecomputeMenu} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "This is a long label" + set tearoff [tkTearOffMenu .m1] + update idletasks + list [.m1 entryconfigure 1 -label "foo"] [destroy .m1] +} {{} {}} +test menuDraw-7.2 {TkEventuallyRecomputeMenu - update pending} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "This is a long label" + set tearoff [tkTearOffMenu .m1] + list [.m1 entryconfigure 1 -label "foo"] [destroy .m1] +} {{} {}} + + +test menuDraw-8.1 {TkRecomputeMenu} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 configure -postcommand [.m1 add command -label foo] + .m1 add command -label "Hit ESCAPE to make this menu go away." + list [.m1 post 0 0] [destroy .m1] +} {{} {}} + + +test menuDraw-9.1 {TkEventuallyRedrawMenu - entry test} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + set foo 0 + .m1 add radiobutton -variable foo -label test + tkTearOffMenu .m1 + update idletasks + list [set foo test] [destroy .m1] [unset foo] +} {test {} {}} +test menuDraw-9.2 {TkEventuallyRedrawMenu - whole menu} { + catch {destroy .m1} + menu .m1 + list [catch {tkTearOffMenu .m1}] [destroy .m1] +} {0 {}} + +# Don't know how to test when window has been deleted and ComputeMenuGeometry +# gets called. +test menuDraw-10.1 {ComputeMenuGeometry - menubar} { + catch {destroy .m1} + menu .m1 + .m1 add command -label test + . configure -menu .m1 + list [update idletasks] [. configure -menu ""] [destroy .m1] +} {{} {} {}} +test menuDraw-10.2 {ComputeMenuGeometry - non-menubar} { + catch {destroy .m1} + menu .m1 + .m1 add command -label test + list [update idletasks] [destroy .m1] +} {{} {}} +test menuDraw-10.3 {ComputeMenuGeometry - Resize necessary} { + catch {destroy .m1} + menu .m1 + .m1 add command -label test + list [update idletasks] [destroy .m1] +} {{} {}} +test menuDraw-10.4 {ComputeMenuGeometry - resize not necessary} { + catch {destroy .m1} + menu .m1 + .m1 add command -label test + update idletasks + .m1 entryconfigure 1 -label test + list [update idletasks] [destroy .m1] +} {{} {}} + +test menuDraw-11.1 {TkMenuSelectImageProc - entry selected; redraw not pending} { + catch {destroy .m1} + catch {eval image delete [image names]} + image create test image1 + image create test image2 + menu .m1 + .m1 add checkbutton -image image1 -selectimage image2 + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1 40 40] + update idletasks + list [image delete image2] [destroy .m1] [eval image delete [image names]] +} {{} {} {}} +test menuDraw-11.2 {TkMenuSelectImageProc - entry selected; redraw pending} { + catch {destroy .m1} + catch {eval image delete [image names]} + image create test image1 + image create test image2 + menu .m1 + .m1 add checkbutton -image image1 -selectimage image2 + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1 40 40] + list [image delete image2] [destroy .m1] [eval image delete [image names]] +} {{} {} {}} +test menuDraw-11.3 {TkMenuSelectImageProc - entry not selected} { + catch {destroy .m1} + catch {eval image delete [image names]} + image create test image1 + image create test image2 + menu .m1 + .m1 add checkbutton -image image1 -selectimage image2 + set tearoff [tkTearOffMenu .m1 40 40] + update idletasks + list [image delete image2] [destroy .m1] [eval image delete [image names]] +} {{} {} {}} + +#Don't know how to test missing tkwin in DisplayMenu +test menuDraw-12.1 {DisplayMenu - menubar background} {unixOnly} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo -menu .m2 + . configure -menu .m1 + list [update] [. configure -menu ""] [destroy .m1] +} {{} {} {}} +test menuDraw-12.2 {Display menu - no entries} { + catch {destroy .m1} + menu .m1 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test menuDraw-12.3 {DisplayMenu - one entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test menuDraw-12.4 {DisplayMenu - two entries} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + .m1 add command -label "two" + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test menuDraw.12.5 {DisplayMenu - two columns - first bigger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + .m1 add command -label "two" + .m1 add command -label "three" -columnbreak 1 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test menuDraw-12.5 {DisplayMenu - two column - second bigger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + .m1 add command -label "two" -columnbreak 1 + .m1 add command -label "three" + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test menuDraw.12.7 {DisplayMenu - three columns} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + .m1 add command -label "two" -columnbreak 1 + .m1 add command -label "three" + .m1 add command -label "four" + .m1 add command -label "five" + .m1 add command -label "six" + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test menuDraw-12.6 {Display menu - testing for extra space and menubars} {unixOnly} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + . configure -menu .m1 + list [update] [. configure -menu ""] [destroy .m1] +} {{} {} {}} +test menuDraw-12.7 {Display menu - extra space at end of menu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + set tearoff [tkTearOffMenu .m1 40 40] + wm geometry $tearoff 200x100 + list [update] [destroy .m1] +} {{} {}} + +test menuDraw-13.1 {TkMenuEventProc - Expose} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add command -label "one" + menu .m2 + .m2 add command -label "two" + set tearoff1 [tkTearOffMenu .m1 40 40] + set tearoff2 [tkTearOffMenu .m2 40 40] + list [raise $tearoff2] [update] [destroy .m1] [destroy .m2] +} {{} {} {} {}} +test menuDraw-13.2 {TkMenuEventProc - ConfigureNotify} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + set tearoff [tkTearOffMenu .m1 40 40] + list [wm geometry $tearoff 200x100] [update] [destroy .m1] +} {{} {} {}} +test menuDraw-13.3 {TkMenuEventProc - ActivateNotify} {macOnly} { + catch {destroy .t2} + toplevel .t2 -menu .t2.m1 + menu .t2.m1 + .t2.m1 add command -label foo + tkTearOffMenu .t2.m1 40 40 + list [catch {update} msg] $msg [destroy .t2] +} {0 {} {}} +# Testing deletes is hard, and I am going to do my best. Don't know how +# to test the case where we have already cleared the tkwin field in the +# menuPtr. +test menuDraw-13.4 {TkMenuEventProc - simple delete} { + catch {destroy .m1} + menu .m1 + list [destroy .m1] +} {{}} +test menuDraw-13.5 {TkMenuEventProc - nothing pending} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + update idletasks + list [destroy .m1] +} {{}} + +test menuDraw-14.1 {TkMenuImageProc} { + catch {destroy .m1} + catch {image delete image1} + menu .m1 + image create test image1 + .m1 add command -image image1 + update idletasks + list [image delete image1] [destroy .m1] +} {{} {}} +test menuDraw-14.2 {TkMenuImageProc} { + catch {destroy .m1} + catch {image delete image1} + menu .m1 + image create test image1 + .m1 add command -image image1 + list [image delete image1] [destroy .m1] +} {{} {}} + +test menuDraw-15.1 {TkPostTearoffMenu - Basic posting} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test menuDraw-15.2 {TkPostTearoffMenu - Deactivation} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" -state active + set tearoff [tkTearOffMenu .m1 40 40] + list [$tearoff index active] [destroy .m1] +} {none {}} +test menuDraw-15.3 {TkPostTearoffMenu - post command} { + catch {destroy .m1} + catch {unset foo} + menu .m1 -postcommand "set foo .m1" + .m1 add command -label "foo" + list [catch {tkTearOffMenu .m1 40 40}] [set foo] [unset foo] [destroy .m1] +} {0 .m1 {} {}} +test menuDraw-15.4 {TkPostTearoffMenu - post command deleting the menu} { + catch {destroy .m1} + menu .m1 -postcommand "destroy .m1" + .m1 add command -label "foo" + list [catch {tkTearOffMenu .m1 40 40} msg] $msg [winfo exists .m1] +} {0 {} 0} +test menuDraw-15.5 {TkPostTearoffMenu - tearoff at edge of screen} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + set height [winfo screenheight .m1] + list [catch {tkTearOffMenu .m1 40 $height}] [destroy .m1] +} {0 {}} +test menuDraw-15.6 {TkPostTearoffMenu - tearoff off right} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "foo" + set width [winfo screenwidth .m1] + list [catch {tkTearOffMenu .m1 $width 40}] [destroy .m1] +} {0 {}} + + +test menuDraw-16.1 {TkPostSubmenu} {unixOnly} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add cascade -label test -menu .m2 + menu .m2 + .m2 add command -label "Hit ESCAPE to make this menu go away." + set tearoff [tkTearOffMenu .m1 40 40] + $tearoff postcascade 0 + list [$tearoff postcascade 0] [destroy .m1] [destroy .m2] +} {{} {} {}} +test menuDraw-16.2 {TkPostSubMenu} {unixOnly} { + catch {destroy .m1} + catch {destroy .m2} + catch {destroy .m3} + menu .m1 + .m1 add cascade -label "two" -menu .m2 + .m1 add cascade -label "three" -menu .m3 + menu .m2 + .m2 add command -label "two" + menu .m3 + .m3 add command -label "three" + set tearoff [tkTearOffMenu .m1 40 40] + $tearoff postcascade 0 + list [$tearoff postcascade 1] [destroy .m1] [destroy .m2] [destroy .m3] +} {{} {} {} {}} +test menuDraw-16.3 {TkPostSubMenu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label test -menu .m2 + list [.m1 postcascade 1] [destroy .m1] +} {{} {}} +test menuDraw-16.4 {TkPostSubMenu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label test + set tearoff [tkTearOffMenu .m1 40 40] + list [$tearoff postcascade 0] [destroy .m1] +} {{} {}} +test menuDraw-16.5 {TkPostSubMenu} {unixOnly} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add cascade -label test -menu .m2 + menu .m2 -postcommand "glorp" + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {$tearoff postcascade test} msg] $msg [destroy .m1] [destroy .m2] +} {1 {invalid command name "glorp"} {} {}} +test menuDraw-16.6 {TkPostSubMenu} {menuInteractive} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add cascade -label test -menu .m2 + menu .m2 + .m2 add command -label "Hit ESCAPE to get rid of this menu" + set tearoff [tkTearOffMenu .m1 40 40] + list [$tearoff postcascade 0] [destroy .m1] [destroy .m2] +} {{} {} {}} + +test menuDraw-17.1 {AdjustMenuCoords - menubar} {unixOnly} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 -tearoff 0 + .m1 add cascade -label test -menu .m2 + menu .m2 -tearoff 0 + .m2 add command -label foo + . configure -menu .m1 + foreach w [winfo children .] { + if {[$w cget -type] == "menubar"} { + break + } + } + list [$w postcascade 0] [. configure -menu ""] [destroy .m1] [destroy .m2] +} {{} {} {} {}} +test menuDraw-17.2 {AdjustMenuCoords - menu} {menuInteractive} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 + .m1 add cascade -label test -menu .m2 + menu .m2 + .m2 add command -label "Hit ESCAPE to make this menu go away" + set tearoff [tkTearOffMenu .m1 40 40] + list [$tearoff postcascade 0] [destroy .m1] [destroy .m2] +} {{} {} {}} + +deleteWindows diff --git a/tests/menubut.test b/tests/menubut.test new file mode 100644 index 0000000..8a5c14a --- /dev/null +++ b/tests/menubut.test @@ -0,0 +1,352 @@ +# This file is a Tcl script to test menubuttons in Tk. It is +# organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) menubut.test 1.26 97/07/31 10:08:50 + +# XXX This test file is woefully incomplete right now. If any part +# XXX of a procedure has tests then the whole procedure has tests, +# XXX but many procedures have no tests. + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\" image" + puts "type, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +# Create entries in the option database to be sure that geometry options +# like border width have predictable values. + +option add *Menubutton.borderWidth 2 +option add *Menubutton.highlightThickness 2 +option add *Menubutton.font {Helvetica -12 bold} +option add *Button.borderWidth 2 +option add *Button.highlightThickness 2 +option add *Button.font {Helvetica -12 bold} + +eval image delete [image names] +image create test image1 +menubutton .mb -text "Test" +pack .mb +update +set i 1 +foreach test { + {-activebackground #012345 #012345 non-existent + {unknown color name "non-existent"}} + {-activeforeground #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-anchor nw nw bogus {bad anchor position "bogus": must be n, ne, e, se, s, sw, w, nw, or center}} + {-background #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-bd 4 4 badValue {bad screen distance "badValue"}} + {-bg #ff0000 #ff0000 non-existent {unknown color name "non-existent"}} + {-bitmap questhead questhead badValue {bitmap "badValue" not defined}} + {-borderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-cursor arrow arrow badValue {bad cursor spec "badValue"}} + {-direction below below badValue {bad direction value "badValue": must be above, below, left, right, or flush}} + {-disabledforeground #00ff00 #00ff00 xyzzy {unknown color name "xyzzy"}} + {-fg #110022 #110022 bogus {unknown color name "bogus"}} + {-font {Helvetica 12} {Helvetica 12} {} {font "" doesn't exist}} + {-foreground #110022 #110022 bogus {unknown color name "bogus"}} + {-height 18 18 20.0 {expected integer but got "20.0"}} + {-highlightbackground #112233 #112233 ugly {unknown color name "ugly"}} + {-highlightcolor #110022 #110022 bogus {unknown color name "bogus"}} + {-highlightthickness 18 18 badValue {bad screen distance "badValue"}} + {-image image1 image1 bogus {image "bogus" doesn't exist}} + {-indicatoron yes 1 no_way {expected boolean value but got "no_way"}} + {-justify right right bogus {bad justification "bogus": must be left, right, or center}} + {-menu "any old string" "any old string" {} {}} + {-padx 12 12 420x {bad screen distance "420x"}} + {-pady 12 12 420x {bad screen distance "420x"}} + {-relief groove groove 1.5 {bad relief type "1.5": must be flat, groove, raised, ridge, solid, or sunken}} + {-state normal normal bogus {bad state value "bogus": must be normal, active, or disabled}} + {-takefocus "any string" "any string" {} {}} + {-text "Sample text" {Sample text} {} {}} + {-textvariable i i {} {}} + {-underline 5 5 3p {expected integer but got "3p"}} + {-width 402 402 3p {expected integer but got "3p"}} + {-wraplength 100 100 6x {bad screen distance "6x"}} +} { + set name [lindex $test 0] + test menubutton-1.$i {configuration options} { + .mb configure $name [lindex $test 1] + lindex [.mb configure $name] 4 + } [lindex $test 2] + incr i + if {[lindex $test 3] != ""} { + test menubutton-1.$i {configuration options} { + list [catch {.mb configure $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .mb configure $name [lindex [.mb configure $name] 3] + incr i +} + +test menubutton-2.1 {Tk_MenubuttonCmd procedure} { + list [catch {menubutton} msg] $msg +} {1 {wrong # args: should be "menubutton pathName ?options?"}} +test menubutton-2.2 {Tk_MenubuttonCmd procedure} { + list [catch {menubutton foo} msg] $msg +} {1 {bad window path name "foo"}} +test menubutton-2.3 {Tk_MenubuttonCmd procedure} { + catch {destroy .mb} + menubutton .mb + winfo class .mb +} {Menubutton} +test menubutton-2.4 {Tk_ButtonCmd procedure} { + catch {destroy .mb} + list [catch {menubutton .mb -gorp foo} msg] $msg [winfo exists .mb] +} {1 {unknown option "-gorp"} 0} + +catch {destroy .mb} +menubutton .mb -text "Test Menu" +pack .mb +test menubutton-3.1 {MenuButtonWidgetCmd procedure} { + list [catch {.mb} msg] $msg +} {1 {wrong # args: should be ".mb option ?arg arg ...?"}} +test menubutton-3.2 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.mb c} msg] $msg +} {1 {bad option "c": must be cget or configure}} +test menubutton-3.3 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.mb cget} msg] $msg +} {1 {wrong # args: should be ".mb cget option"}} +test menubutton-3.4 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.mb cget a b} msg] $msg +} {1 {wrong # args: should be ".mb cget option"}} +test menubutton-3.5 {ButtonWidgetCmd procedure, "cget" option} { + list [catch {.mb cget -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test menubutton-3.6 {ButtonWidgetCmd procedure, "cget" option} { + .mb configure -highlightthickness 3 + .mb cget -highlightthickness +} {3} +test menubutton-3.7 {ButtonWidgetCmd procedure, "configure" option} { + llength [.mb configure] +} {32} +test menubutton-3.8 {ButtonWidgetCmd procedure, "configure" option} { + list [catch {.mb configure -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test menubutton-3.9 {ButtonWidgetCmd procedure, "configure" option} { + list [catch {.mb co -bg #ffffff -fg} msg] $msg +} {1 {value for "-fg" missing}} +test menubutton-3.10 {ButtonWidgetCmd procedure, "configure" option} { + .mb configure -fg #123456 + .mb configure -bg #654321 + lindex [.mb configure -fg] 4 +} {#123456} +test menubutton-3.11 {ButtonWidgetCmd procedure, "configure" option} { + list [catch {.mb foobar} msg] $msg +} {1 {bad option "foobar": must be cget or configure}} + +# XXX Need to add tests for several procedures here. The tests for XXX +# XXX ConfigureMenuButton aren't complete either. XXX + +test menubutton-4.1 {ConfigureMenuButton procedure} { + catch {destroy .mb1} + button .mb1 -text "Menubutton 1" + list [catch {.mb1 configure -width 1i} msg] $msg $errorInfo +} {1 {expected integer but got "1i"} {expected integer but got "1i" + (processing -width option) + invoked from within +".mb1 configure -width 1i"}} +test menubutton-4.2 {ConfigureMenuButton procedure} { + catch {destroy .mb1} + button .mb1 -text "Menubutton 1" + list [catch {.mb1 configure -height 0.5c} msg] $msg $errorInfo +} {1 {expected integer but got "0.5c"} {expected integer but got "0.5c" + (processing -height option) + invoked from within +".mb1 configure -height 0.5c"}} +test menubutton-4.3 {ConfigureMenuButton procedure} { + catch {destroy .mb1} + button .mb1 -bitmap questhead + list [catch {.mb1 configure -width abc} msg] $msg $errorInfo +} {1 {bad screen distance "abc"} {bad screen distance "abc" + (processing -width option) + invoked from within +".mb1 configure -width abc"}} +test menubutton-4.4 {ConfigureMenuButton procedure} { + catch {destroy .mb1} + eval image delete [image names] + image create test image1 + button .mb1 -image image1 + list [catch {.mb1 configure -height 0.5x} msg] $msg $errorInfo +} {1 {bad screen distance "0.5x"} {bad screen distance "0.5x" + (processing -height option) + invoked from within +".mb1 configure -height 0.5x"}} +test menubutton-4.5 {ConfigureMenuButton procedure} {fonts} { + catch {destroy .mb1} + button .mb1 -text "Sample text" -width 10 -height 2 + pack .mb1 + set result "[winfo reqwidth .mb1] [winfo reqheight .mb1]" + .mb1 configure -bitmap questhead + lappend result [winfo reqwidth .mb1] [winfo reqheight .mb1] +} {102 46 20 12} +test menubutton-4.6 {ConfigureMenuButton procedure - bad direction} { + catch {destroy .mb} + menubutton .mb -text "Test" + list [catch {.mb configure -direction badValue} msg] $msg \ + [.mb cget -direction] [destroy .mb] +} {1 {bad direction value "badValue": must be above, below, left, right, or flush} below {}} + +# XXX Need to add tests for several procedures here. XXX + +test menubutton-5.1 {MenuButtonEventProc procedure} { + eval destroy [winfo children .] + menubutton .mb1 -bg #543210 + rename .mb1 .mb2 + set x {} + lappend x [winfo children .] + lappend x [.mb2 cget -bg] + destroy .mb1 + lappend x [info command .mb*] [winfo children .] +} {.mb1 #543210 {} {}} + +test menubutton-6.1 {MenuButtonCmdDeletedProc procedure} { + eval destroy [winfo children .] + menubutton .mb1 + rename .mb1 {} + list [info command .mb*] [winfo children .] +} {{} {}} + +test menubutton-7.1 {ComputeMenuButtonGeometry procedure} { + catch {destroy .mb} + menubutton .mb -image image1 -bd 4 -highlightthickness 0 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {38 23} +test menubutton-7.2 {ComputeMenuButtonGeometry procedure} { + catch {destroy .mb} + menubutton .mb -image image1 -bd 1 -highlightthickness 2 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {36 21} +test menubutton-7.3 {ComputeMenuButtonGeometry procedure} { + catch {destroy .mb} + menubutton .mb -image image1 -bd 0 -highlightthickness 2 -padx 5 -pady 5 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {34 19} +test menubutton-7.4 {ComputeMenuButtonGeometry procedure} { + catch {destroy .mb} + menubutton .mb -image image1 -bd 2 -relief raised -width 40 \ + -highlightthickness 2 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {48 23} +test menubutton-7.5 {ComputeMenuButtonGeometry procedure} { + catch {destroy .mb} + menubutton .mb -image image1 -bd 2 -relief raised -height 30 \ + -highlightthickness 2 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {38 38} +test menubutton-7.6 {ComputeMenuButtonGeometry procedure} { + catch {destroy .mb} + menubutton .mb -bitmap question -bd 2 -relief raised \ + -highlightthickness 2 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {25 35} +test menubutton-7.7 {ComputeMenuButtonGeometry procedure} { + catch {destroy .mb} + menubutton .mb -bitmap question -bd 2 -relief raised -width 40 \ + -highlightthickness 1 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {46 33} +test menubutton-7.8 {ComputeMenuButtonGeometry procedure} { + catch {destroy .mb} + menubutton .mb -bitmap question -bd 2 -relief raised -height 50 \ + -highlightthickness 1 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {23 56} +test menubutton-7.9 {ComputeMenuButtonGeometry procedure} {fonts} { + catch {destroy .mb} + menubutton .mb -text String -bd 2 -relief raised -padx 0 -pady 0 \ + -highlightthickness 1 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {42 20} +test menubutton-7.10 {ComputeMenuButtonGeometry procedure} {fonts} { + catch {destroy .mb} + menubutton .mb -text String -bd 2 -relief raised -width 20 \ + -padx 0 -pady 0 -highlightthickness 1 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {146 20} +test menubutton-7.11 {ComputeMenuButtonGeometry procedure} {fonts} { + catch {destroy .mb} + menubutton .mb -text String -bd 2 -relief raised -height 2 \ + -padx 0 -pady 0 -highlightthickness 1 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {42 34} +test menubutton-7.12 {ComputeMenuButtonGeometry procedure} {fonts} { + catch {destroy .mb} + menubutton .mb -text String -bd 2 -relief raised -padx 10 -pady 5 \ + -highlightthickness 1 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {62 30} +test menubutton-7.13 {ComputeMenuButtonGeometry procedure} {fonts} { + catch {destroy .mb} + menubutton .mb -text String -bd 2 -relief raised \ + -highlightthickness 1 -indicatoron 1 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {78 28} +test menubutton-7.14 {ComputeMenuButtonGeometry procedure} {unix nonPortable} { + # The following test is non-portable because the indicator's pixel + # size varies to maintain constant absolute size. + + catch {destroy .mb} + menubutton .mb -image image1 -bd 2 -relief raised \ + -highlightthickness 2 -indicatoron 1 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {64 23} +test menubutton-7.15 {ComputeMenuButtonGeometry procedure} {pc nonPortable} { + # The following test is non-portable because the indicator's pixel + # size varies to maintain constant absolute size. + + catch {destroy .mb} + menubutton .mb -image image1 -bd 2 -relief raised \ + -highlightthickness 2 -indicatoron 1 + pack .mb + list [winfo reqwidth .mb] [winfo reqheight .mb] +} {65 23} + +set l [interp hidden] +eval destroy [winfo children .] + +test menubutton-8.1 {menubutton vs hidden commands} { + catch {destroy .mb} + menubutton .mb + interp hide {} .mb + destroy .mb + list [winfo children .] [interp hidden] +} [list {} $l] + +eval image delete [image names] +eval destroy [winfo children .] +option clear + diff --git a/tests/msgbox.test b/tests/msgbox.test new file mode 100644 index 0000000..c23ddaf --- /dev/null +++ b/tests/msgbox.test @@ -0,0 +1,157 @@ +# This file is a Tcl script to test out Tk's "tk_messageBox" command. +# It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) msgbox.test 1.7 97/07/31 10:05:25 +# + +if {[string compare test [info procs test]] == 1} { + source defs +} + +test msgbox-1.1 {tk_messageBox command} { + list [catch {tk_messageBox -foo} msg] $msg +} {1 {unknown option "-foo", must be -default, -icon, -message, -parent, -title or -type}} +test msgbox-1.2 {tk_messageBox command} { + list [catch {tk_messageBox -foo bar} msg] $msg +} {1 {unknown option "-foo", must be -default, -icon, -message, -parent, -title or -type}} + +catch {tk_messageBox -foo bar} msg +regsub -all , $msg "" options +regsub \"-foo\" $options "" options + +foreach option $options { + if {[string index $option 0] == "-"} { + test msgbox-1.3 {tk_messageBox command} { + list [catch {tk_messageBox $option} msg] $msg + } [list 1 "value for \"$option\" missing"] + } +} + +test msgbox-1.4 {tk_messageBox command} { + list [catch {tk_messageBox -default} msg] $msg +} {1 {value for "-default" missing}} + +test msgbox-1.5 {tk_messageBox command} { + list [catch {tk_messageBox -type foo} msg] $msg +} {1 {invalid message box type "foo", must be abortretryignore, ok, okcancel, retrycancel, yesno or yesnocancel}} + +test msgbox-1.6 {tk_messageBox command} { + list [catch {tk_messageBox -default 1.1} msg] $msg +} {1 {invalid default button "1.1"}} + +test msgbox-1.7 {tk_messageBox command} { + list [catch {tk_messageBox -default foo} msg] $msg +} {1 {invalid default button "foo"}} + +test msgbox-1.8 {tk_messageBox command} { + list [catch {tk_messageBox -type yesno -default 3} msg] $msg +} {1 {invalid default button "3"}} + +test msgbox-1.9 {tk_messageBox command} { + list [catch {tk_messageBox -icon foo} msg] $msg +} {1 {invalid icon "foo", must be error, info, question or warning}} + +test msgbox-1.10 {tk_messageBox command} { + list [catch {tk_messageBox -parent foo.bar} msg] $msg +} {1 {bad window path name "foo.bar"}} + +if {[info commands tkMessageBox] == ""} { + set isNative 1 +} else { + set isNative 0 +} + +if {$isNative && ![info exists INTERACTIVE]} { + puts " Some tests were skipped because they could not be performed" + puts " automatically on this platform. If you wish to execute them" + puts " interactively, set the TCL variable INTERACTIVE and re-run" + puts " the test" + return +} + +proc ChooseMsg {parent btn} { + global isNative + if {!$isNative} { + after 100 SendEventToMsg $parent $btn mouse + } +} + +proc ChooseMsgByKey {parent btn} { + global isNative + if {!$isNative} { + after 100 SendEventToMsg $parent $btn key + } +} + +proc PressButton {btn} { + event generate $btn <Enter> + event generate $btn <ButtonPress-1> -x 5 -y 5 + event generate $btn <ButtonRelease-1> -x 5 -y 5 +} + +proc SendEventToMsg {parent btn type} { + if {$parent != "."} { + set w $parent.__tk__messagebox + } else { + set w .__tk__messagebox + } + if ![winfo ismapped $w.$btn] { + update + } + if {$type == "mouse"} { + PressButton $w.$btn + } else { + event generate $w <Enter> + focus $w + event generate $w.$btn <Enter> + event generate $w <KeyPress> -keysym Return + } +} + +set parent . + +set specs { + {"abortretryignore" MB_ABORTRETRYIGNORE 3 {"abort" "retry" "ignore"}} + {"ok" MB_OK 1 {"ok" }} + {"okcancel" MB_OKCANCEL 2 {"ok" "cancel" }} + {"retrycancel" MB_RETRYCANCEL 2 {"retry" "cancel" }} + {"yesno" MB_YESNO 2 {"yes" "no" }} + {"yesnocancel" MB_YESNOCANCEL 3 {"yes" "no" "cancel"}} +} + +# +# Try out all combinations of (type) x (default button) and +# (type) x (icon). +# +foreach spec $specs { + set type [lindex $spec 0] + set buttons [lindex $spec 3] + + set button [lindex $buttons 0] + test msgbox-2.1 {tk_messageBox command} { + ChooseMsg $parent $button + tk_messageBox -title Hi -message "Please press $button" \ + -type $type + } $button + + foreach icon {warning error info question} { + test msgbox-2.2 {tk_messageBox command -icon option} { + ChooseMsg $parent $button + tk_messageBox -title Hi -message "Please press $button" \ + -type $type -icon $icon + } $button + } + + foreach button $buttons { + test msgbox-2.3 {tk_messageBox command} { + ChooseMsg $parent $button + tk_messageBox -title Hi -message "Please press $button" \ + -type $type -default $button + } "$button" + } +} diff --git a/tests/oldpack.test b/tests/oldpack.test new file mode 100644 index 0000000..a63eaef --- /dev/null +++ b/tests/oldpack.test @@ -0,0 +1,508 @@ +# This file is a Tcl script to test out the old syntax of Tk's +# "pack" command (before release 3.3). It is organized in the +# standard fashion for Tcl tests. +# +# Copyright (c) 1991-1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) oldpack.test 1.10 97/06/24 13:32:16 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +# First, test a single window packed in various ways in a parent + +catch {destroy .pack} +frame .pack +place .pack -width 100 -height 100 +frame .pack.red -width 10 -height 20 +label .pack.red.l -text R -bd 2 -relief raised +place .pack.red.l -relwidth 1.0 -relheight 1.0 +frame .pack.green -width 30 -height 40 +label .pack.green.l -text G -bd 2 -relief raised +place .pack.green.l -relwidth 1.0 -relheight 1.0 +frame .pack.blue -width 40 -height 40 +label .pack.blue.l -text B -bd 2 -relief raised +place .pack.blue.l -relwidth 1.0 -relheight 1.0 +frame .pack.violet -width 80 -height 20 +label .pack.violet.l -text P -bd 2 -relief raised +place .pack.violet.l -relwidth 1.0 -relheight 1.0 + +test pack-1.1 {basic positioning} { + pack ap .pack .pack.red top + update + winfo geometry .pack.red +} 10x20+45+0 +test pack-1.2 {basic positioning} { + pack append .pack .pack.red bottom + update + winfo geometry .pack.red +} 10x20+45+80 +test pack-1.3 {basic positioning} { + pack append .pack .pack.red left + update + winfo geometry .pack.red +} 10x20+0+40 +test pack-1.4 {basic positioning} { + pack append .pack .pack.red right + update + winfo geometry .pack.red +} 10x20+90+40 + +# Try adding padding around the window and make sure that the +# window gets a larger frame. + +test pack-2.1 {padding} { + pack append .pack .pack.red {t padx 20} + update + winfo geometry .pack.red +} 10x20+45+0 +test pack-2.2 {padding} { + pack append .pack .pack.red {top pady 20} + update + winfo geometry .pack.red +} 10x20+45+10 +test pack-2.3 {padding} { + pack append .pack .pack.red {l padx 20} + update + winfo geometry .pack.red +} 10x20+10+40 +test pack-2.4 {padding} { + pack append .pack .pack.red {left pady 20} + update + winfo geometry .pack.red +} 10x20+0+40 + +# Position the window at different positions in its frame to +# make sure they all work. Try two differenet frame locations, +# to make sure that frame offsets are being added in correctly. + +test pack-3.1 {framing} { + pack append .pack .pack.red {b padx 20 pady 30} + update + winfo geometry .pack.red +} 10x20+45+65 +test pack-3.2 {framing} { + pack append .pack .pack.red {bottom padx 20 pady 30 fr n} + update + winfo geometry .pack.red +} 10x20+45+50 +test pack-3.3 {framing} { + pack append .pack .pack.red {bottom padx 20 pady 30 frame ne} + update + winfo geometry .pack.red +} 10x20+90+50 +test pack-3.4 {framing} { + pack append .pack .pack.red {bottom padx 20 pady 30 frame e} + update + winfo geometry .pack.red +} 10x20+90+65 +test pack-3.5 {framing} { + pack append .pack .pack.red {bottom padx 20 pady 30 frame se} + update + winfo geometry .pack.red +} 10x20+90+80 +test pack-3.6 {framing} { + pack append .pack .pack.red {bottom padx 20 pady 30 frame s} + update + winfo geometry .pack.red +} 10x20+45+80 +test pack-3.7 {framing} { + pack append .pack .pack.red {bottom padx 20 pady 30 frame sw} + update + winfo geometry .pack.red +} 10x20+0+80 +test pack-3.8 {framing} { + pack append .pack .pack.red {bottom padx 20 pady 30 frame w} + update + winfo geometry .pack.red +} 10x20+0+65 +test pack-3.9 {framing} { + pack append .pack .pack.red {bottom padx 20 pady 30 frame nw} + update + winfo geometry .pack.red +} 10x20+0+50 +test pack-3.10 {framing} { + pack append .pack .pack.red {bottom padx 20 pady 30 frame c} + update + winfo geometry .pack.red +} 10x20+45+65 +test pack-3.11 {framing} { + pack append .pack .pack.red {r padx 20 pady 30} + update + winfo geometry .pack.red +} 10x20+80+40 +test pack-3.12 {framing} { + pack append .pack .pack.red {right padx 20 pady 30 frame n} + update + winfo geometry .pack.red +} 10x20+80+0 +test pack-3.13 {framing} { + pack append .pack .pack.red {right padx 20 pady 30 frame ne} + update + winfo geometry .pack.red +} 10x20+90+0 +test pack-3.14 {framing} { + pack append .pack .pack.red {right padx 20 pady 30 frame e} + update + winfo geometry .pack.red +} 10x20+90+40 +test pack-3.15 {framing} { + pack append .pack .pack.red {right padx 20 pady 30 frame se} + update + winfo geometry .pack.red +} 10x20+90+80 +test pack-3.16 {framing} { + pack append .pack .pack.red {right padx 20 pady 30 frame s} + update + winfo geometry .pack.red +} 10x20+80+80 +test pack-3.17 {framing} { + pack append .pack .pack.red {right padx 20 pady 30 frame sw} + update + winfo geometry .pack.red +} 10x20+70+80 +test pack-3.18 {framing} { + pack append .pack .pack.red {right padx 20 pady 30 frame w} + update + winfo geometry .pack.red +} 10x20+70+40 +test pack-3.19 {framing} { + pack append .pack .pack.red {right padx 20 pady 30 frame nw} + update + winfo geometry .pack.red +} 10x20+70+0 +test pack-3.20 {framing} { + pack append .pack .pack.red {right padx 20 pady 30 frame center} + update + winfo geometry .pack.red +} 10x20+80+40 + +# Try out various filling combinations in a couple of different +# frame locations. + +test pack-4.1 {filling} { + pack append .pack .pack.red {bottom padx 20 pady 30 fillx} + update + winfo geometry .pack.red +} 100x20+0+65 +test pack-4.2 {filling} { + pack append .pack .pack.red {bottom padx 20 pady 30 filly} + update + winfo geometry .pack.red +} 10x50+45+50 +test pack-4.3 {filling} { + pack append .pack .pack.red {bottom padx 20 pady 30 fill} + update + winfo geometry .pack.red +} 100x50+0+50 +test pack-4.4 {filling} { + pack append .pack .pack.red {right padx 20 pady 30 fillx} + update + winfo geometry .pack.red +} 30x20+70+40 +test pack-4.5 {filling} { + pack append .pack .pack.red {right padx 20 pady 30 filly} + update + winfo geometry .pack.red +} 10x100+80+0 +test pack-4.6 {filling} { + pack append .pack .pack.red {right padx 20 pady 30 fill} + update + winfo geometry .pack.red +} 30x100+70+0 + +# Multiple windows: make sure that space is properly subtracted +# from the cavity as windows are positioned inwards from all +# different sides. Also make sure that windows get unmapped if +# there isn't enough space for them. + +pack append .pack .pack.red top .pack.green top .pack.blue top \ + .pack.violet top +update +test pack-5.1 {multiple windows} {winfo geometry .pack.red} 10x20+45+0 +test pack-5.2 {multiple windows} {winfo geometry .pack.green} 30x40+35+20 +test pack-5.3 {multiple windows} {winfo geometry .pack.blue} 40x40+30+60 +test pack-5.4 {multiple windows} {winfo ismapped .pack.violet} 0 +pack b .pack.blue .pack.violet top +update +test pack-5.5 {multiple windows} {winfo ismapped .pack.violet} 1 +test pack-5.6 {multiple windows} {winfo geometry .pack.violet} 80x20+10+60 +test pack-5.7 {multiple windows} {winfo geometry .pack.blue} 40x20+30+80 +pack after .pack.blue .pack.red top +update +test pack-5.8 {multiple windows} {winfo geometry .pack.green} 30x40+35+0 +test pack-5.9 {multiple windows} {winfo geometry .pack.violet} 80x20+10+40 +test pack-5.10 {multiple windows} {winfo geometry .pack.blue} 40x40+30+60 +test pack-5.11 {multiple windows} {winfo ismapped .pack.red} 0 +pack before .pack.green .pack.red right .pack.blue left +update +test pack-5.12 {multiple windows} {winfo ismapped .pack.red} 1 +test pack-5.13 {multiple windows} {winfo geometry .pack.red} 10x20+90+40 +test pack-5.14 {multiple windows} {winfo geometry .pack.blue} 40x40+0+30 +test pack-5.15 {multiple windows} {winfo geometry .pack.green} 30x40+50+0 +test pack-5.16 {multiple windows} {winfo geometry .pack.violet} 50x20+40+40 +pack append .pack .pack.violet left .pack.green bottom .pack.red bottom \ + .pack.blue bottom +update +test pack-5.17 {multiple windows} {winfo geometry .pack.violet} 80x20+0+40 +test pack-5.18 {multiple windows} {winfo geometry .pack.green} 20x40+80+60 +test pack-5.19 {multiple windows} {winfo geometry .pack.red} 10x20+85+40 +test pack-5.20 {multiple windows} {winfo geometry .pack.blue} 20x40+80+0 +pack after .pack.blue .pack.blue top .pack.red right .pack.green right \ + .pack.violet right +update +test pack-5.21 {multiple windows} {winfo geometry .pack.blue} 40x40+30+0 +test pack-5.22 {multiple windows} {winfo geometry .pack.red} 10x20+90+60 +test pack-5.23 {multiple windows} {winfo geometry .pack.green} 30x40+60+50 +test pack-5.24 {multiple windows} {winfo geometry .pack.violet} 60x20+0+60 +pack after .pack.blue .pack.red left .pack.green left .pack.violet left +update +test pack-5.25 {multiple windows} {winfo geometry .pack.blue} 40x40+30+0 +test pack-5.26 {multiple windows} {winfo geometry .pack.red} 10x20+0+60 +test pack-5.27 {multiple windows} {winfo geometry .pack.green} 30x40+10+50 +test pack-5.28 {multiple windows} {winfo geometry .pack.violet} 60x20+40+60 +pack append .pack .pack.violet left .pack.green left .pack.blue left \ + .pack.red left +update +test pack-5.29 {multiple windows} {winfo geometry .pack.violet} 80x20+0+40 +test pack-5.30 {multiple windows} {winfo geometry .pack.green} 20x40+80+30 +test pack-5.31 {multiple windows} {winfo ismapped .pack.blue} 0 +test pack-5.32 {multiple windows} {winfo ismapped .pack.red} 0 + + +# Test the ability of the packer to propagate geometry information +# to its parent. Make sure it computes the parent's needs both in +# the direction of packing (width for "left" and "right" windows, +# for example), and perpendicular to the pack direction (height for +# "left" and "right" windows). + +pack append .pack .pack.red top .pack.green top .pack.blue top \ + .pack.violet top +update +test pack-6.1 {geometry propagation} {winfo reqwidth .pack} 80 +test pack-6.2 {geometry propagation} {winfo reqheight .pack} 120 +destroy .pack.violet +update +test pack-6.3 {geometry propagation} {winfo reqwidth .pack} 40 +test pack-6.4 {geometry propagation} {winfo reqheight .pack} 100 +frame .pack.violet -width 80 -height 20 -bg violet +label .pack.violet.l -text P -bd 2 -relief raised +place .pack.violet.l -relwidth 1.0 -relheight 1.0 +pack append .pack .pack.red left .pack.green right .pack.blue bottom \ + .pack.violet top +update +test pack-6.5 {geometry propagation} {winfo reqwidth .pack} 120 +test pack-6.6 {geometry propagation} {winfo reqheight .pack} 60 +pack append .pack .pack.violet top .pack.green top .pack.blue left \ + .pack.red left +update +test pack-6.7 {geometry propagation} {winfo reqwidth .pack} 80 +test pack-6.8 {geometry propagation} {winfo reqheight .pack} 100 + +# Test the "expand" option, and make sure space is evenly divided +# when several windows request expansion. + +pack append .pack .pack.violet top .pack.green {left e} \ + .pack.blue {left expand} .pack.red {left expand} +update +test pack-7.1 {multiple expanded windows} { + pack append .pack .pack.violet top .pack.green {left e} \ + .pack.blue {left expand} .pack.red {left expand} + update + list [winfo geometry .pack.green] [winfo geometry .pack.blue] \ + [winfo geometry .pack.red] +} {30x40+3+40 40x40+39+40 10x20+86+50} +test pack-7.2 {multiple expanded windows} { + pack append .pack .pack.green left .pack.violet {bottom expand} \ + .pack.blue {bottom expand} .pack.red {bottom expand} + update + list [winfo geometry .pack.violet] [winfo geometry .pack.blue] \ + [winfo geometry .pack.red] +} {70x20+30+77 40x40+45+30 10x20+60+3} +test pack-7.3 {multiple expanded windows} { + foreach i [winfo child .pack] { + pack unpack $i + } + pack append .pack .pack.green {left e fill} .pack.red {left expand fill} \ + .pack.blue {top fill} + update + list [winfo geometry .pack.green] [winfo geometry .pack.red] \ + [winfo geometry .pack.blue] +} {40x100+0+0 20x100+40+0 40x40+60+0} +test pack-7.4 {multiple expanded windows} { + foreach i [winfo child .pack] { + pack unpack $i + } + pack append .pack .pack.red {top expand} .pack.violet {top expand} \ + .pack.blue {right fill} + update + list [winfo geometry .pack.red] [winfo geometry .pack.violet] \ + [winfo geometry .pack.blue] +} {10x20+45+5 80x20+10+35 40x40+60+60} +test pack-7.5 {multiple expanded windows} { + foreach i [winfo child .pack] { + pack unpack $i + } + pack append .pack .pack.green {right frame s} .pack.red {top expand} + update + list [winfo geometry .pack.green] [winfo geometry .pack.red] +} {30x40+70+60 10x20+30+40} +test pack-7.6 {multiple expanded windows} { + foreach i [winfo child .pack] { + pack unpack $i + } + pack append .pack .pack.violet {bottom frame e} .pack.red {right expand} + update + list [winfo geometry .pack.violet] [winfo geometry .pack.red] +} {80x20+20+80 10x20+45+30} + +# Need more bizarre tests with combinations of expanded windows and +# windows in opposing directions! Also, include padding in expanded +# (and unexpanded) windows. + +# Syntax errors on pack commands + +test pack-8.1 {syntax errors} { + set msg "" + set result [catch {pack} msg] + concat $result $msg +} {1 wrong # args: should be "pack option arg ?arg ...?"} +test pack-8.2 {syntax errors} { + set msg "" + set result [catch {pack append} msg] + concat $result $msg +} {1 wrong # args: should be "pack option arg ?arg ...?"} +test pack-8.3 {syntax errors} { + set msg "" + set result [catch {pack gorp foo} msg] + concat $result $msg +} {1 bad option "gorp": must be configure, forget, info, propagate, or slaves} +test pack-8.4 {syntax errors} { + set msg "" + set result [catch {pack a .pack} msg] + concat $result $msg +} {1 bad option "a": must be configure, forget, info, propagate, or slaves} +test pack-8.5 {syntax errors} { + set msg "" + set result [catch {pack after foobar} msg] + concat $result $msg +} {1 bad window path name "foobar"} +test pack-8.6 {syntax errors} { + frame .pack.yellow -bg yellow + set msg "" + set result [catch {pack after .pack.yellow} msg] + destroy .pack.yellow + concat $result $msg +} {1 window ".pack.yellow" isn't packed} +test pack-8.7 {syntax errors} { + set msg "" + set result [catch {pack append foobar} msg] + concat $result $msg +} {1 bad window path name "foobar"} +test pack-8.8 {syntax errors} { + set msg "" + set result [catch {pack before foobar} msg] + concat $result $msg +} {1 bad window path name "foobar"} +test pack-8.9 {syntax errors} { + frame .pack.yellow -bg yellow + set msg "" + set result [catch {pack before .pack.yellow} msg] + destroy .pack.yellow + concat $result $msg +} {1 window ".pack.yellow" isn't packed} +test pack-8.10 {syntax errors} { + set msg "" + set result [catch {pack info .pack help} msg] + concat $result $msg +} {1 wrong # args: should be "pack info window"} +test pack-8.11 {syntax errors} { + set msg "" + set result [catch {pack info foobar} msg] + concat $result $msg +} {1 bad window path name "foobar"} +test pack-8.12 {syntax errors} { + set msg "" + set result [catch {pack append .pack .pack.blue} msg] + concat $result $msg +} {1 wrong # args: window ".pack.blue" should be followed by options} +test pack-8.13 {syntax errors} { + set msg "" + set result [catch {pack append . .pack.blue top} msg] + concat $result $msg +} {1 can't pack .pack.blue inside .} +test pack-8.14 {syntax errors} { + set msg "" + set result [catch {pack append .pack .pack.blue f} msg] + concat $result $msg +} {1 bad option "f": should be top, bottom, left, right, expand, fill, fillx, filly, padx, pady, or frame} +test pack-8.15 {syntax errors} { + set msg "" + set result [catch {pack append .pack .pack.blue pad} msg] + concat $result $msg +} {1 bad option "pad": should be top, bottom, left, right, expand, fill, fillx, filly, padx, pady, or frame} +test pack-8.16 {syntax errors} { + set msg "" + set result [catch {pack append .pack .pack.blue {frame south}} msg] + concat $result $msg +} {1 bad anchor position "south": must be n, ne, e, se, s, sw, w, nw, or center} +test pack-8.17 {syntax errors} { + set msg "" + set result [catch {pack append .pack .pack.blue {padx -2}} msg] + concat $result $msg +} {1 bad pad value "-2": must be positive screen distance} +test pack-8.18 {syntax errors} { + set msg "" + set result [catch {pack append .pack .pack.blue {padx}} msg] + concat $result $msg +} {1 wrong # args: "padx" option must be followed by screen distance} +test pack-8.19 {syntax errors} { + set msg "" + set result [catch {pack append .pack .pack.blue {pady -2}} msg] + concat $result $msg +} {1 bad pad value "-2": must be positive screen distance} +test pack-8.20 {syntax errors} { + set msg "" + set result [catch {pack append .pack .pack.blue {pady}} msg] + concat $result $msg +} {1 wrong # args: "pady" option must be followed by screen distance} +test pack-8.21 {syntax errors} { + set msg "" + set result [catch {pack append .pack .pack.blue "\{abc"} msg] + concat $result $msg +} {1 unmatched open brace in list} +test pack-8.22 {syntax errors} { + set msg "" + set result [catch {pack append .pack .pack.blue frame} msg] + concat $result $msg +} {1 wrong # args: "frame" option must be followed by anchor point} + +# Test "pack info" command output. + +test pack-9.1 {information output} { + pack append .pack .pack.blue {top fillx frame n} \ + .pack.red {bottom filly frame s} .pack.green {left fill frame w} \ + .pack.violet {right expand frame e} + list [pack slaves .pack] [pack info .pack.blue] [pack info .pack.red] \ + [pack info .pack.green] [pack info .pack.violet] +} {{.pack.blue .pack.red .pack.green .pack.violet} {-in .pack -anchor n -expand 0 -fill x -ipadx 0 -ipady 0 -padx 0 -pady 0 -side top} {-in .pack -anchor s -expand 0 -fill y -ipadx 0 -ipady 0 -padx 0 -pady 0 -side bottom} {-in .pack -anchor w -expand 0 -fill both -ipadx 0 -ipady 0 -padx 0 -pady 0 -side left} {-in .pack -anchor e -expand 1 -fill none -ipadx 0 -ipady 0 -padx 0 -pady 0 -side right}} +test pack-9.2 {information output} { + pack append .pack .pack.blue {padx 10 frame nw} \ + .pack.red {pady 20 frame ne} .pack.green {frame se} \ + .pack.violet {frame sw} + list [pack slaves .pack] [pack info .pack.blue] [pack info .pack.red] \ + [pack info .pack.green] [pack info .pack.violet] +} {{.pack.blue .pack.red .pack.green .pack.violet} {-in .pack -anchor nw -expand 0 -fill none -ipadx 0 -ipady 0 -padx 5 -pady 0 -side top} {-in .pack -anchor ne -expand 0 -fill none -ipadx 0 -ipady 0 -padx 0 -pady 10 -side top} {-in .pack -anchor se -expand 0 -fill none -ipadx 0 -ipady 0 -padx 0 -pady 0 -side top} {-in .pack -anchor sw -expand 0 -fill none -ipadx 0 -ipady 0 -padx 0 -pady 0 -side top}} +test pack-9.3 {information output} { + pack append .pack .pack.blue {frame center} .pack.red {frame center} \ + .pack.green {frame c} .pack.violet {frame c} + list [pack slaves .pack] [pack info .pack.blue] [pack info .pack.red] \ + [pack info .pack.green] [pack info .pack.violet] +} {{.pack.blue .pack.red .pack.green .pack.violet} {-in .pack -anchor center -expand 0 -fill none -ipadx 0 -ipady 0 -padx 0 -pady 0 -side top} {-in .pack -anchor center -expand 0 -fill none -ipadx 0 -ipady 0 -padx 0 -pady 0 -side top} {-in .pack -anchor center -expand 0 -fill none -ipadx 0 -ipady 0 -padx 0 -pady 0 -side top} {-in .pack -anchor center -expand 0 -fill none -ipadx 0 -ipady 0 -padx 0 -pady 0 -side top}} + +catch {destroy .pack} +concat {} diff --git a/tests/option.test b/tests/option.test new file mode 100644 index 0000000..aad9197 --- /dev/null +++ b/tests/option.test @@ -0,0 +1,232 @@ +# This file is a Tcl script to test out the option-handling facilities +# of Tk. It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1991-1993 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) option.test 1.20 97/08/07 15:54:37 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +catch {destroy .op1} +catch {destroy .op2} +set appName [winfo name .] + +# First, test basic retrievals, being sure to trigger all the various +# types of NodeElements (EXACT_LEAF_NAME, WILDCARD_NODE_CLASS, and +# everything in-between). + +frame .op1 -class Class1 +frame .op2 -class Class2 +frame .op1.op3 -class Class1 +frame .op1.op4 -class Class3 +frame .op2.op5 -class Class2 +frame .op1.op3.op6 -class Class4 + +option clear +option add *Color1 red +option add *x blue +option add *Class1.x yellow +option add $appName.op1.x green +option add *Class2.Color1 orange +option add $appName.op2.op5.Color2 purple +option add $appName.Class1.Class3.y brown +option add $appName*op6*Color2 black +option add $appName*Class1.op1.Color2 grey + +test option-1.1 {basic option retrieval} {option get . x Color1} blue +test option-1.2 {basic option retrieval} {option get . y Color1} red +test option-1.3 {basic option retrieval} {option get . z Color1} red +test option-1.4 {basic option retrieval} {option get . x Color2} blue +test option-1.5 {basic option retrieval} {option get . y Color2} {} +test option-1.6 {basic option retrieval} {option get . z Color2} {} + +test option-2.1 {basic option retrieval} {option get .op1 x Color1} green +test option-2.2 {basic option retrieval} {option get .op1 y Color1} red +test option-2.3 {basic option retrieval} {option get .op1 z Color1} red +test option-2.4 {basic option retrieval} {option get .op1 x Color2} green +test option-2.5 {basic option retrieval} {option get .op1 y Color2} {} +test option-2.6 {basic option retrieval} {option get .op1 z Color2} {} + +test option-3.1 {basic option retrieval} {option get .op1.op3 x Color1} yellow +test option-3.2 {basic option retrieval} {option get .op1.op3 y Color1} red +test option-3.3 {basic option retrieval} {option get .op1.op3 z Color1} red +test option-3.4 {basic option retrieval} {option get .op1.op3 x Color2} yellow +test option-3.5 {basic option retrieval} {option get .op1.op3 y Color2} {} +test option-3.6 {basic option retrieval} {option get .op1.op3 z Color2} {} + +test option-4.1 {basic option retrieval} {option get .op1.op3.op6 x Color1} blue +test option-4.2 {basic option retrieval} {option get .op1.op3.op6 y Color1} red +test option-4.3 {basic option retrieval} {option get .op1.op3.op6 z Color1} red +test option-4.4 {basic option retrieval} {option get .op1.op3.op6 x Color2} black +test option-4.5 {basic option retrieval} {option get .op1.op3.op6 y Color2} black +test option-4.6 {basic option retrieval} {option get .op1.op3.op6 z Color2} black + +test option-5.1 {basic option retrieval} {option get .op1.op4 x Color1} blue +test option-5.2 {basic option retrieval} {option get .op1.op4 y Color1} brown +test option-5.3 {basic option retrieval} {option get .op1.op4 z Color1} red +test option-5.4 {basic option retrieval} {option get .op1.op4 x Color2} blue +test option-5.5 {basic option retrieval} {option get .op1.op4 y Color2} brown +test option-5.6 {basic option retrieval} {option get .op1.op4 z Color2} {} + +test option-6.1 {basic option retrieval} {option get .op2 x Color1} orange +test option-6.2 {basic option retrieval} {option get .op2 y Color1} orange +test option-6.3 {basic option retrieval} {option get .op2 z Color1} orange +test option-6.4 {basic option retrieval} {option get .op2 x Color2} blue +test option-6.5 {basic option retrieval} {option get .op2 y Color2} {} +test option-6.6 {basic option retrieval} {option get .op2 z Color2} {} + +test option-7.1 {basic option retrieval} {option get .op2.op5 x Color1} orange +test option-7.2 {basic option retrieval} {option get .op2.op5 y Color1} orange +test option-7.3 {basic option retrieval} {option get .op2.op5 z Color1} orange +test option-7.4 {basic option retrieval} {option get .op2.op5 x Color2} purple +test option-7.5 {basic option retrieval} {option get .op2.op5 y Color2} purple +test option-7.6 {basic option retrieval} {option get .op2.op5 z Color2} purple + +# Now try similar tests to above, except jump around non-hierarchically +# between windows to make sure that the option stacks are pushed and +# popped correctly. + +option get . foo Foo +test option-8.1 {stack pushing/popping} {option get .op2.op5 x Color1} orange +test option-8.2 {stack pushing/popping} {option get .op2.op5 y Color1} orange +test option-8.3 {stack pushing/popping} {option get .op2.op5 z Color1} orange +test option-8.4 {stack pushing/popping} {option get .op2.op5 x Color2} purple +test option-8.5 {stack pushing/popping} {option get .op2.op5 y Color2} purple +test option-8.6 {stack pushing/popping} {option get .op2.op5 z Color2} purple + +test option-9.1 {stack pushing/popping} {option get . x Color1} blue +test option-9.2 {stack pushing/popping} {option get . y Color1} red +test option-9.3 {stack pushing/popping} {option get . z Color1} red +test option-9.4 {stack pushing/popping} {option get . x Color2} blue +test option-9.5 {stack pushing/popping} {option get . y Color2} {} +test option-9.6 {stack pushing/popping} {option get . z Color2} {} + +test option-10.1 {stack pushing/popping} {option get .op1.op3.op6 x Color1} blue +test option-10.2 {stack pushing/popping} {option get .op1.op3.op6 y Color1} red +test option-10.3 {stack pushing/popping} {option get .op1.op3.op6 z Color1} red +test option-10.4 {stack pushing/popping} {option get .op1.op3.op6 x Color2} black +test option-10.5 {stack pushing/popping} {option get .op1.op3.op6 y Color2} black +test option-10.6 {stack pushing/popping} {option get .op1.op3.op6 z Color2} black + +test option-11.1 {stack pushing/popping} {option get .op1.op3 x Color1} yellow +test option-11.2 {stack pushing/popping} {option get .op1.op3 y Color1} red +test option-11.3 {stack pushing/popping} {option get .op1.op3 z Color1} red +test option-11.4 {stack pushing/popping} {option get .op1.op3 x Color2} yellow +test option-11.5 {stack pushing/popping} {option get .op1.op3 y Color2} {} +test option-11.6 {stack pushing/popping} {option get .op1.op3 z Color2} {} + +test option-12.1 {stack pushing/popping} {option get .op1 x Color1} green +test option-12.2 {stack pushing/popping} {option get .op1 y Color1} red +test option-12.3 {stack pushing/popping} {option get .op1 z Color1} red +test option-12.4 {stack pushing/popping} {option get .op1 x Color2} green +test option-12.5 {stack pushing/popping} {option get .op1 y Color2} {} +test option-12.6 {stack pushing/popping} {option get .op1 z Color2} {} + +# Test the major priority levels (widgetDefault, etc.) + +option add $appName.op1.a 100 100 +option add $appName.op1.A interactive interactive +option add $appName.op1.b userDefault userDefault +option add $appName.op1.B startupFile startupFile +option add $appName.op1.c widgetDefault widgetDefault +option add $appName.op1.C 0 0 + +test option-13.1 {priority levels} {option get .op1 a A} 100 +test option-13.2 {priority levels} {option get .op1 b A} interactive +test option-13.3 {priority levels} {option get .op1 b B} userDefault +test option-13.4 {priority levels} {option get .op1 c B} startupFile +test option-13.5 {priority levels} {option get .op1 c C} widgetDefault +option add $appName.op1.B file2 widget +test option-13.6 {priority levels} {option get .op1 c B} startupFile +option add $appName.op1.B file2 startupFile +test option-13.7 {priority levels} {option get .op1 c B} file2 + +# Test various error conditions + +test option-14.1 {error conditions} { + list [catch {option} msg] $msg +} {1 {wrong # args: should be "option cmd arg ?arg ...?"}} +test option-14.2 {error conditions} { + list [catch {option x} msg] $msg +} {1 {bad option "x": must be add, clear, get, or readfile}} +test option-14.3 {error conditions} { + list [catch {option foo 3} msg] $msg +} {1 {bad option "foo": must be add, clear, get, or readfile}} +test option-14.4 {error conditions} { + list [catch {option add 3} msg] $msg +} {1 {wrong # args: should be "option add pattern value ?priority?"}} +test option-14.5 {error conditions} { + list [catch {option add . a b c} msg] $msg +} {1 {wrong # args: should be "option add pattern value ?priority?"}} +test option-14.6 {error conditions} { + list [catch {option add . a -1} msg] $msg +} {1 {bad priority level "-1": must be widgetDefault, startupFile, userDefault, interactive, or a number between 0 and 100}} +test option-14.7 {error conditions} { + list [catch {option add . a 101} msg] $msg +} {1 {bad priority level "101": must be widgetDefault, startupFile, userDefault, interactive, or a number between 0 and 100}} +test option-14.8 {error conditions} { + list [catch {option add . a gorp} msg] $msg +} {1 {bad priority level "gorp": must be widgetDefault, startupFile, userDefault, interactive, or a number between 0 and 100}} +test option-14.9 {error conditions} { + list [catch {option get 3} msg] $msg +} {1 {wrong # args: should be "option get window name class"}} +test option-14.10 {error conditions} { + list [catch {option get 3 4} msg] $msg +} {1 {wrong # args: should be "option get window name class"}} +test option-14.11 {error conditions} { + list [catch {option get 3 4 5 6} msg] $msg +} {1 {wrong # args: should be "option get window name class"}} +test option-14.12 {error conditions} { + list [catch {option get .gorp.gorp a A} msg] $msg +} {1 {bad window path name ".gorp.gorp"}} + +if {$tcl_platform(os) == "Win32s"} { + set option1 OPTION~2.FIL + set option2 OPTION~1.FIL + set option3 OPTION~3.FIL +} else { + set option1 option.file1 + set option2 option.file2 + set option3 option.file3 +} + +test option-15.1 {database files} { + list [catch {option read non-existent} msg] $msg +} {1 {couldn't open "non-existent": no such file or directory}} +option read $option1 +test option-15.2 {database files} {option get . x1 color} blue +if {$appName == "tktest"} { + test option-15.3 {database files} {option get . x2 color} green +} +test option-15.4 {database files} {option get . x3 color} purple +test option-15.5 {database files} {option get . {x 4} color} brown +test option-15.6 {database files} {option get . x6 color} {} +test option-15.7 {database files} { + list [catch {option read $option1 widget foo} msg] $msg +} {1 {wrong # args: should be "option readfile fileName ?priority?"}} +option add *x3 burgundy +catch {option read $option1 userDefault} +test option-15.8 {database files} {option get . x3 color} burgundy +test option-15.9 {database files} { + list [catch {option read $option2} msg] $msg +} {1 {missing colon on line 2}} + +test option-16.1 {ReadOptionFile} { + set file [open "$option3" w] + fconfigure $file -translation crlf + puts $file "*x7: true\n*x8: false" + close $file + option read $option3 userDefault + set result [list [option get . x7 color] [option get . x8 color]] + removeFile $option3 + set result +} {true false} + +catch {destroy .op1} +catch {destroy .op2} +concat {} diff --git a/tests/pack.test b/tests/pack.test new file mode 100644 index 0000000..3443d74 --- /dev/null +++ b/tests/pack.test @@ -0,0 +1,969 @@ +# This file is a Tcl script to test out the "pack" command +# of Tk. It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1993 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) pack.test 1.27 97/07/01 18:06:56 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +# Utility procedures: + +proc pack1 {args} { + pack forget .pack.a .pack.b .pack.c .pack.d + eval pack .pack.a $args + pack .pack.b -expand yes -fill both + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] +} +proc pack2 {args} { + pack forget .pack.a .pack.b .pack.c .pack.d + eval pack .pack.a $args + update + winfo geometry .pack.a +} +proc pack3 {args} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side top + pack .pack.c -side left + eval pack .pack.b $args + update + winfo geometry .pack.b +} +proc pack4 {option value} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a $option $value + set i [pack info .pack.a] + lindex $i [expr [lsearch -exact $i $option]+1] +} + +# Create some test windows. + +catch {destroy .pack} +toplevel .pack +wm geom .pack 300x200+0+0 +wm minsize .pack 1 1 +update idletasks +foreach i {a b c d} { + frame .pack.$i + label .pack.$i.label -text $i -relief raised + place .pack.$i.label -relwidth 1.0 -relheight 1.0 +} +.pack.a config -width 20 -height 40 +.pack.b config -width 50 -height 30 +.pack.c config -width 80 -height 80 +.pack.d config -width 40 -height 30 + +test pack-1.1 {-side option} { + pack1 -side top +} {20x40+140+0 300x160+0+40} +test pack-1.2 {-side option} { + pack1 -side bottom +} {20x40+140+160 300x160+0+0} +test pack-1.3 {-side option} { + pack1 -side left +} {20x40+0+80 280x200+20+0} +test pack-1.4 {-side option} { + pack1 -side right +} {20x40+280+80 280x200+0+0} + +test pack-2.1 {x padding and filling} { + pack1 -side right -padx 20 +} {20x40+260+80 240x200+0+0} +test pack-2.2 {x padding and filling} { + pack1 -side right -ipadx 20 +} {60x40+240+80 240x200+0+0} +test pack-2.3 {x padding and filling} { + pack1 -side right -ipadx 5 -padx 10 +} {30x40+260+80 250x200+0+0} +test pack-2.4 {x padding and filling} { + pack1 -side right -padx 20 -fill x +} {20x40+260+80 240x200+0+0} +test pack-2.5 {x padding and filling} { + pack1 -side right -ipadx 20 -fill x +} {60x40+240+80 240x200+0+0} +test pack-2.6 {x padding and filling} { + pack1 -side right -ipadx 5 -padx 10 -fill x +} {30x40+260+80 250x200+0+0} +test pack-2.7 {x padding and filling} { + pack1 -side top -padx 20 +} {20x40+140+0 300x160+0+40} +test pack-2.8 {x padding and filling} { + pack1 -side top -ipadx 20 +} {60x40+120+0 300x160+0+40} +test pack-2.9 {x padding and filling} { + pack1 -side top -ipadx 5 -padx 10 +} {30x40+135+0 300x160+0+40} +test pack-2.10 {x padding and filling} { + pack1 -side top -padx 20 -fill x +} {260x40+20+0 300x160+0+40} +test pack-2.11 {x padding and filling} { + pack1 -side top -ipadx 20 -fill x +} {300x40+0+0 300x160+0+40} +test pack-2.12 {x padding and filling} { + pack1 -side top -ipadx 5 -padx 10 -fill x +} {280x40+10+0 300x160+0+40} +set pad [winfo pixels .pack 1c] +test pack-2.13 {x padding and filling} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -padx 1c + set x [pack info .pack.a] + lindex $x [expr [lsearch -exact $x -padx]+1] +} $pad +test pack-2.14 {x padding and filling} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -ipadx 1c + set x [pack info .pack.a] + lindex $x [expr [lsearch -exact $x -ipadx]+1] +} $pad + +test pack-3.1 {y padding and filling} { + pack1 -side right -pady 20 +} {20x40+280+80 280x200+0+0} +test pack-3.2 {y padding and filling} { + pack1 -side right -ipady 20 +} {20x80+280+60 280x200+0+0} +test pack-3.3 {y padding and filling} { + pack1 -side right -ipady 5 -pady 10 +} {20x50+280+75 280x200+0+0} +test pack-3.4 {y padding and filling} { + pack1 -side right -pady 20 -fill y +} {20x160+280+20 280x200+0+0} +test pack-3.5 {y padding and filling} { + pack1 -side right -ipady 20 -fill y +} {20x200+280+0 280x200+0+0} +test pack-3.6 {y padding and filling} { + pack1 -side right -ipady 5 -pady 10 -fill y +} {20x180+280+10 280x200+0+0} +test pack-3.7 {y padding and filling} { + pack1 -side top -pady 20 +} {20x40+140+20 300x120+0+80} +test pack-3.8 {y padding and filling} { + pack1 -side top -ipady 20 +} {20x80+140+0 300x120+0+80} +test pack-3.9 {y padding and filling} { + pack1 -side top -ipady 5 -pady 10 +} {20x50+140+10 300x130+0+70} +test pack-3.10 {y padding and filling} { + pack1 -side top -pady 20 -fill y +} {20x40+140+20 300x120+0+80} +test pack-3.11 {y padding and filling} { + pack1 -side top -ipady 20 -fill y +} {20x80+140+0 300x120+0+80} +test pack-3.12 {y padding and filling} { + pack1 -side top -ipady 5 -pady 10 -fill y +} {20x50+140+10 300x130+0+70} +set pad [winfo pixels .pack 1c] +test pack-3.13 {y padding and filling} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -pady 1c + set x [pack info .pack.a] + lindex $x [expr [lsearch -exact $x -pady]+1] +} $pad +test pack-3.14 {y padding and filling} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -ipady 1c + set x [pack info .pack.a] + lindex $x [expr [lsearch -exact $x -ipady]+1] +} $pad + +test pack-4.1 {anchors} { + pack2 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor n +} {30x70+135+20} +test pack-4.2 {anchors} { + pack2 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor ne +} {30x70+260+20} +test pack-4.3 {anchors} { + pack2 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor e +} {30x70+260+65} +test pack-4.4 {anchors} { + pack2 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor se +} {30x70+260+110} +test pack-4.5 {anchors} { + pack2 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor s +} {30x70+135+110} +test pack-4.6 {anchors} { + pack2 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor sw +} {30x70+10+110} +test pack-4.7 {anchors} { + pack2 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor w +} {30x70+10+65} +test pack-4.8 {anchors} { + pack2 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor nw +} {30x70+10+20} +test pack-4.9 {anchors} { + pack2 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor center +} {30x70+135+65} + +# Repeat above tests, but with a frame that isn't at (0,0), so that +# we can be sure that the frame offset is being added in correctly. + +test pack-5.1 {more anchors} { + pack3 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor n +} {60x60+160+60} +test pack-5.2 {more anchors} { + pack3 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor ne +} {60x60+230+60} +test pack-5.3 {more anchors} { + pack3 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor e +} {60x60+230+90} +test pack-5.4 {more anchors} { + pack3 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor se +} {60x60+230+120} +test pack-5.5 {more anchors} { + pack3 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor s +} {60x60+160+120} +test pack-5.6 {more anchors} { + pack3 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor sw +} {60x60+90+120} +test pack-5.7 {more anchors} { + pack3 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor w +} {60x60+90+90} +test pack-5.8 {more anchors} { + pack3 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor nw +} {60x60+90+60} +test pack-5.9 {more anchors} { + pack3 -side top -ipadx 5 -padx 10 -ipady 15 -pady 20 -expand y -anchor center +} {60x60+160+90} + +test pack-6.1 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side left + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {20x40+0+80 50x30+20+85 80x80+70+60 40x30+150+85} +test pack-6.2 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side left -expand yes + pack .pack.b -side left + pack .pack.c .pack.d -side left -expand 1 + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {20x40+18+80 50x30+56+85 80x80+124+60 40x30+241+85} +test pack-6.3 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side top + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {20x40+140+0 50x30+125+40 80x80+110+70 40x30+130+150} +test pack-6.4 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side top -expand yes + pack .pack.b -side top + pack .pack.c .pack.d -side top -expand 1 + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {20x40+140+3 50x30+125+46 80x80+110+79 40x30+130+166} +test pack-6.5 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side right + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {20x40+280+80 50x30+230+85 80x80+150+60 40x30+110+85} +test pack-6.6 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side right -expand yes + pack .pack.b -side right + pack .pack.c .pack.d -side right -expand 1 + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {20x40+262+80 50x30+194+85 80x80+95+60 40x30+18+85} +test pack-6.7 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side bottom + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {20x40+140+160 50x30+125+130 80x80+110+50 40x30+130+20} +test pack-6.8 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side bottom -expand yes + pack .pack.b -side bottom + pack .pack.c .pack.d -side bottom -expand 1 + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {20x40+140+157 50x30+125+124 80x80+110+40 40x30+130+3} +test pack-6.9 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side bottom -expand yes -fill both + pack .pack.b -side right + pack .pack.c -side top -expand 1 -fill both + pack .pack.d -side left + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {300x65+0+135 50x30+250+52 250x105+0+0 40x30+0+105} +test pack-6.10 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side left -expand yes -fill both + pack .pack.b -side top + pack .pack.c -side right -expand 1 -fill both + pack .pack.d -side bottom + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {100x200+0+0 50x30+175+0 160x170+140+30 40x30+100+170} +test pack-6.11 {-expand option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side left -expand yes -fill both + pack .pack.b -side top -expand yes -fill both + pack .pack.c -side right -expand 1 -fill both + pack .pack.d -side bottom -expand yes -fill both + update + list [winfo geometry .pack.a] [winfo geometry .pack.b] \ + [winfo geometry .pack.c] [winfo geometry .pack.d] +} {100x200+0+0 200x100+100+0 160x100+140+100 40x100+100+100} +catch {destroy .pack2} +toplevel .pack2 -height 400 -width 400 +wm geometry .pack2 +0+0 +pack propagate .pack2 0 +pack forget .pack2.a .pack2.b .pack2.c .pack2.d +foreach i {w1 w2 w3} { + frame .pack2.$i -width 30 -height 30 -bd 2 -relief raised + label .pack2.$i.l -text $i + place .pack2.$i.l -relwidth 1.0 -relheight 1.0 +} +test pack-6.12 {-expand option} { + pack .pack2.w1 .pack2.w2 .pack2.w3 -padx 5 -ipadx 4 -pady 2 -ipady 6 -expand 1 -side left + update + list [winfo geometry .pack2.w1] [winfo geometry .pack2.w2] [winfo geometry .pack2.w3] +} {38x42+47+179 38x42+180+179 38x42+314+179} +test pack-6.13 {-expand option} { + pack forget .pack2.w1 .pack2.w2 .pack2.w3 + pack .pack2.w1 .pack2.w2 .pack2.w3 -padx 5 -ipadx 4 -pady 2 \ + -ipady 6 -expand 1 -side top + update + list [winfo geometry .pack2.w1] [winfo geometry .pack2.w2] [winfo geometry .pack2.w3] +} {38x42+181+45 38x42+181+178 38x42+181+312} +catch {destroy .pack2} + +wm geometry .pack {} +test pack-7.1 {requesting size for parent} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side left -padx 5 -pady 10 + update + list [winfo reqwidth .pack] [winfo reqheight .pack] +} {230 100} +test pack-7.2 {requesting size for parent} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side top -padx 5 -pady 10 + update + list [winfo reqwidth .pack] [winfo reqheight .pack] +} {90 260} +test pack-7.3 {requesting size for parent} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side right -padx 5 -pady 10 + update + list [winfo reqwidth .pack] [winfo reqheight .pack] +} {230 100} +test pack-7.4 {requesting size for parent} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side bottom -padx 5 -pady 10 + update + list [winfo reqwidth .pack] [winfo reqheight .pack] +} {90 260} +test pack-7.5 {requesting size for parent} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side top -padx 5 -pady 10 + pack .pack.b -side right -padx 5 -pady 10 + pack .pack.c -side bottom -padx 5 -pady 10 + pack .pack.d -side left -padx 5 -pady 10 + update + list [winfo reqwidth .pack] [winfo reqheight .pack] +} {150 210} +test pack-7.6 {requesting size for parent} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side top + pack .pack.c -side left + pack .pack.d -side bottom + update + list [winfo reqwidth .pack] [winfo reqheight .pack] +} {120 120} +test pack-7.7 {requesting size for parent} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side right + pack .pack.c -side bottom + pack .pack.d -side top + update + list [winfo reqwidth .pack] [winfo reqheight .pack] +} {100 110} + + +# For the tests below, create a couple of "pad" windows to shrink +# the available space for the remaining windows. The tests have to +# be done this way rather than shrinking the whole window, because +# some window managers like mwm won't let a top-level window get +# very small. + +pack forget .pack.a .pack.b .pack.c .pack.d +frame .pack.right -width 200 -height 10 -bd 2 -relief raised +frame .pack.bottom -width 10 -height 150 -bd 2 -relief raised +pack .pack.right -side right +pack .pack.bottom -side bottom +pack .pack.a .pack.b .pack.c -side top +update +test pack-8.1 {insufficient space} { + list [winfo geometry .pack.a] [winfo ismapped .pack.a] \ + [winfo geometry .pack.b] [winfo ismapped .pack.b] \ + [winfo geometry .pack.c] [winfo ismapped .pack.c] +} {20x40+30+0 1 50x30+15+40 1 80x80+0+70 1} +wm geom .pack 270x250 +update +test pack-8.2 {insufficient space} { + list [winfo geometry .pack.a] [winfo ismapped .pack.a] \ + [winfo geometry .pack.b] [winfo ismapped .pack.b] \ + [winfo geometry .pack.c] [winfo ismapped .pack.c] +} {20x40+25+0 1 50x30+10+40 1 70x30+0+70 1} +wm geom .pack 240x220 +update +test pack-8.3 {insufficient space} { + list [winfo geometry .pack.a] [winfo ismapped .pack.a] \ + [winfo geometry .pack.b] [winfo ismapped .pack.b] \ + [winfo geometry .pack.c] [winfo ismapped .pack.c] +} {20x40+10+0 1 40x30+0+40 1 70x30+0+70 0} +wm geom .pack 350x350 +update +test pack-8.4 {insufficient space} { + list [winfo geometry .pack.a] [winfo ismapped .pack.a] \ + [winfo geometry .pack.b] [winfo ismapped .pack.b] \ + [winfo geometry .pack.c] [winfo ismapped .pack.c] +} {20x40+65+0 1 50x30+50+40 1 80x80+35+70 1} +wm geom .pack {} +pack .pack.a -side left +pack .pack.b -side right +pack .pack.c -side left +update +test pack-8.5 {insufficient space} { + list [winfo geometry .pack.a] [winfo ismapped .pack.a] \ + [winfo geometry .pack.b] [winfo ismapped .pack.b] \ + [winfo geometry .pack.c] [winfo ismapped .pack.c] +} {20x40+0+20 1 50x30+100+25 1 80x80+20+0 1} +wm geom .pack 320x180 +update +test pack-8.6 {insufficient space} { + list [winfo geometry .pack.a] [winfo ismapped .pack.a] \ + [winfo geometry .pack.b] [winfo ismapped .pack.b] \ + [winfo geometry .pack.c] [winfo ismapped .pack.c] +} {20x30+0+0 1 50x30+70+0 1 50x30+20+0 1} +wm geom .pack 250x180 +update +test pack-8.7 {insufficient space} { + list [winfo geometry .pack.a] [winfo ismapped .pack.a] \ + [winfo geometry .pack.b] [winfo ismapped .pack.b] \ + [winfo geometry .pack.c] [winfo ismapped .pack.c] +} {20x30+0+0 1 30x30+20+0 1 50x30+20+0 0} +pack forget .pack.b +update +test pack-8.8 {insufficient space} { + list [winfo geometry .pack.a] [winfo ismapped .pack.a] \ + [winfo geometry .pack.b] [winfo ismapped .pack.b] \ + [winfo geometry .pack.c] [winfo ismapped .pack.c] +} {20x30+0+0 1 30x30+20+0 0 30x30+20+0 1} +pack .pack.b -side right -after .pack.a +wm geom .pack {} +update +test pack-8.9 {insufficient space} { + list [winfo geometry .pack.a] [winfo ismapped .pack.a] \ + [winfo geometry .pack.b] [winfo ismapped .pack.b] \ + [winfo geometry .pack.c] [winfo ismapped .pack.c] +} {20x40+0+20 1 50x30+100+25 1 80x80+20+0 1} +pack forget .pack.right .pack.bottom + +test pack-9.1 {window ordering} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side top + pack .pack.a -after .pack.b + pack slaves .pack +} {.pack.b .pack.a .pack.c .pack.d} +test pack-9.2 {window ordering} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side top + pack .pack.a -after .pack.a + pack slaves .pack +} {.pack.a .pack.b .pack.c .pack.d} +test pack-9.3 {window ordering} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side top + pack .pack.a -before .pack.d + pack slaves .pack +} {.pack.b .pack.c .pack.a .pack.d} +test pack-9.4 {window ordering} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side top + pack .pack.d -before .pack.a + pack slaves .pack +} {.pack.d .pack.a .pack.b .pack.c} +test pack-9.5 {window ordering} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side top + pack propagate .pack.c 0 + pack .pack.a -in .pack.c + list [pack slaves .pack] [pack slaves .pack.c] +} {{.pack.b .pack.c .pack.d} .pack.a} +test pack-9.6 {window ordering} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side top + pack .pack.a -in .pack + pack slaves .pack +} {.pack.b .pack.c .pack.d .pack.a} +test pack-9.7 {window ordering} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d -side top + pack .pack.a -padx 0 + pack slaves .pack +} {.pack.a .pack.b .pack.c .pack.d} +test pack-9.8 {window ordering} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c + pack .pack.d + pack slaves .pack +} {.pack.a .pack.b .pack.c .pack.d} +test pack-9.9 {window ordering} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d + pack .pack.b .pack.d .pack.c -before .pack.a + pack slaves .pack +} {.pack.b .pack.d .pack.c .pack.a} +test pack-9.10 {window ordering} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.c .pack.d .pack.b -after .pack.a + pack slaves .pack +} {.pack.a .pack.c .pack.d .pack.b} + +test pack-10.1 {retaining/clearing configuration state} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side bottom -anchor n -padx 1 -pady 2 -ipadx 3 -ipady 4 \ + -fill both -expand 1 + pack forget .pack.a + pack .pack.a + pack info .pack.a +} {-in .pack -anchor center -expand 0 -fill none -ipadx 0 -ipady 0 -padx 0 -pady 0 -side top} +test pack-10.2 {retaining/clearing configuration state} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side bottom -anchor n -padx 1 -pady 2 -ipadx 3 -ipady 4 \ + -fill both -expand 1 + pack .pack.a -pady 14 + pack info .pack.a +} {-in .pack -anchor n -expand 1 -fill both -ipadx 3 -ipady 4 -padx 1 -pady 14 -side bottom} + +test pack-11.1 {info option} { + pack4 -in .pack +} .pack +test pack-11.2 {info option} { + pack4 -anchor n +} n +test pack-11.3 {info option} { + pack4 -anchor sw +} sw +test pack-11.4 {info option} { + pack4 -expand yes +} 1 +test pack-11.5 {info option} { + pack4 -expand no +} 0 +test pack-11.6 {info option} { + pack4 -fill x +} x +test pack-11.7 {info option} { + pack4 -fill y +} y +test pack-11.8 {info option} { + pack4 -fill both +} both +test pack-11.9 {info option} { + pack4 -fill none +} none +test pack-11.10 {info option} { + pack4 -ipadx 14 +} 14 +test pack-11.11 {info option} { + pack4 -ipady 22 +} 22 +test pack-11.12 {info option} { + pack4 -padx 2 +} 2 +test pack-11.13 {info option} { + pack4 -pady 3 +} 3 +test pack-11.14 {info option} { + pack4 -side top +} top +test pack-11.15 {info option} { + pack4 -side bottom +} bottom +test pack-11.16 {info option} { + pack4 -side left +} left +test pack-11.17 {info option} { + pack4 -side right +} right + +test pack-12.1 {command options and errors} { + list [catch {pack} msg] $msg +} {1 {wrong # args: should be "pack option arg ?arg ...?"}} +test pack-12.2 {command options and errors} { + list [catch {pack foo} msg] $msg +} {1 {wrong # args: should be "pack option arg ?arg ...?"}} +test pack-12.3 {command options and errors} { + list [catch {pack configure x} msg] $msg +} {1 {bad argument "x": must be name of window}} +test pack-12.4 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack configure .pack.b .pack.c + pack slaves .pack +} {.pack.b .pack.c} +test pack-12.5 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .foo} msg] $msg +} {1 {bad window path name ".foo"}} +test pack-12.6 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack} msg] $msg +} {1 {can't pack ".pack": it's a top-level window}} +test pack-12.7 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -after .foo} msg] $msg +} {1 {bad window path name ".foo"}} +test pack-12.8 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -after .pack.b} msg] $msg +} {1 {window ".pack.b" isn't packed}} +test pack-12.9 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -anchor gorp} msg] $msg +} {1 {bad anchor position "gorp": must be n, ne, e, se, s, sw, w, nw, or center}} +test pack-12.10 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -before gorp} msg] $msg +} {1 {bad window path name "gorp"}} +test pack-12.11 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -before .pack.b} msg] $msg +} {1 {window ".pack.b" isn't packed}} +test pack-12.12 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -expand "who cares?"} msg] $msg +} {1 {expected boolean value but got "who cares?"}} +test pack-12.13 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -fill z} msg] $msg +} {1 {bad fill style "z": must be none, x, y, or both}} +test pack-12.14 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -in z} msg] $msg +} {1 {bad window path name "z"}} +set pad [winfo pixels .pack 1c] +test pack-12.15 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -padx abc} msg] $msg +} {1 {bad pad value "abc": must be positive screen distance}} +test pack-12.16 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -padx -1} msg] $msg +} {1 {bad pad value "-1": must be positive screen distance}} +test pack-12.17 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -pady abc} msg] $msg +} {1 {bad pad value "abc": must be positive screen distance}} +test pack-12.18 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -pady -1} msg] $msg +} {1 {bad pad value "-1": must be positive screen distance}} +test pack-12.19 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -ipadx abc} msg] $msg +} {1 {bad pad value "abc": must be positive screen distance}} +test pack-12.20 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -ipadx -1} msg] $msg +} {1 {bad pad value "-1": must be positive screen distance}} +test pack-12.21 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -ipady abc} msg] $msg +} {1 {bad pad value "abc": must be positive screen distance}} +test pack-12.22 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -ipady -1} msg] $msg +} {1 {bad pad value "-1": must be positive screen distance}} +test pack-12.23 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -side bac} msg] $msg +} {1 {bad side "bac": must be top, bottom, left, or right}} +test pack-12.24 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -lousy bac} msg] $msg +} {1 {unknown or ambiguous option "-lousy": must be -after, -anchor, -before, -expand, -fill, -in, -ipadx, -ipady, -padx, -pady, or -side}} +test pack-12.25 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -padx} msg] $msg +} {1 {extra option "-padx" (option with no value?)}} +test pack-12.26 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a {} 22} msg] $msg +} {1 {unknown or ambiguous option "": must be -after, -anchor, -before, -expand, -fill, -in, -ipadx, -ipady, -padx, -pady, or -side}} +test pack-12.27 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -in .} msg] $msg +} {1 {can't pack .pack.a inside .}} +test pack-12.28 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + frame .pack.a.a + list [catch {pack .pack.a.a -in .pack.b} msg] $msg +} {1 {can't pack .pack.a.a inside .pack.b}} +test pack-12.29 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack .pack.a -in .pack.a} msg] $msg +} {1 {can't pack .pack.a inside itself}} +test pack-12.30 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.b .pack.c .pack.d + pack forget .pack.a .pack.d + pack slaves .pack +} {.pack.b .pack.c} +test pack-12.31 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + .pack configure -width 300 -height 200 + pack propagate .pack 0 + pack .pack.a + update + set result [list [winfo reqwidth .pack] [winfo reqheight .pack]] + pack propagate .pack 1 + update + lappend result [winfo reqwidth .pack] [winfo reqheight .pack] + set result +} {300 200 20 40} +test pack-12.32 {command options and errors} { + set result [pack propagate .pack.d] + pack propagate .pack.d 0 + lappend result [pack propagate .pack.d] + pack propagate .pack.d 1 + lappend result [pack propagate .pack.d] + set result +} {1 0 1} +test pack-12.33 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack propagate .dum} msg] $msg +} {1 {bad window path name ".dum"}} +test pack-12.34 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack propagate .pack foo} msg] $msg +} {1 {expected boolean value but got "foo"}} +test pack-12.35 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack propagate .pack foo bar} msg] $msg +} {1 {wrong # args: should be "pack propagate window ?boolean?"}} +test pack-12.36 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack slaves} msg] $msg +} {1 {wrong # args: should be "pack option arg ?arg ...?"}} +test pack-12.37 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack slaves a b} msg] $msg +} {1 {wrong # args: should be "pack slaves window"}} +test pack-12.38 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack slaves .x} msg] $msg +} {1 {bad window path name ".x"}} +test pack-12.39 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack slaves .pack.a} msg] $msg +} {0 {}} +test pack-12.40 {command options and errors} { + pack forget .pack.a .pack.b .pack.c .pack.d + list [catch {pack lousy .pack} msg] $msg +} {1 {bad option "lousy": must be configure, forget, info, propagate, or slaves}} + +pack .pack.right -side right +pack .pack.bottom -side bottom +test pack-13.1 {window deletion} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a .pack.d .pack.b .pack.c -side top + update + destroy .pack.d + update + set result [list [pack slaves .pack] [winfo geometry .pack.a] \ + [winfo geometry .pack.b] [winfo geometry .pack.c]] +} {{.pack.right .pack.bottom .pack.a .pack.b .pack.c} 20x40+30+0 50x30+15+40 80x80+0+70} + +test pack-14.1 {respond to changes in expansion} { + pack forget .pack.a .pack.b .pack.c .pack.d + wm geom .pack {} + pack .pack.a + update + set result [winfo geom .pack.a] + wm geom .pack 400x300 + update + lappend result [winfo geom .pack.a] + pack .pack.a -expand true -fill both + update + lappend result [winfo geom .pack.a] +} {20x40+0+0 20x40+90+0 200x150+0+0} +wm geom .pack {} + +test pack-15.1 {managing geometry with -in option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side top + frame .pack.f + lower .pack.f + pack .pack.f -side top + frame .pack.f.f2 + lower .pack.f.f2 + pack .pack.f.f2 -side top + pack .pack.b -in .pack.f.f2 + update + set result [winfo geom .pack.b] + pack unpack .pack.a + update + lappend result [winfo geom .pack.b] +} {50x30+0+40 50x30+0+0} +catch {destroy .pack.f} +test pack-15.2 {managing geometry with -in option} { + pack forget .pack.a .pack.b .pack.c .pack.d + frame .pack.f + lower .pack.f + pack .pack.a -in .pack.f -side top + update + set result [winfo ismapped .pack.a] + place .pack.f -x 30 -y 45 + update + lappend result [winfo ismapped .pack.a] [winfo geometry .pack.a] + place forget .pack.f + update + lappend result [winfo ismapped .pack.a] +} {0 1 20x40+30+45 0} +catch {destroy .pack.f} +test pack-15.3 {managing geometry with -in option} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a -side top + frame .pack.f + lower .pack.f + pack .pack.f -side top + frame .pack.f.f2 + lower .pack.f.f2 + pack .pack.f.f2 -side top + pack .pack.b -in .pack.f.f2 + update + set result [winfo ismapped .pack.b] + pack unpack .pack.f + update + lappend result [winfo ismapped .pack.b] +} {1 0} +catch {destroy .pack.f} +test pack-15.4 {managing geometry with -in option} { + pack forget .pack.a .pack.b .pack.c .pack.d + foreach i {1 2} { + frame .pack.f$i -width 100 -height 40 -bd 2 -relief raised + lower .pack.f$i + pack propagate .pack.f$i 0 + pack .pack.f$i -side top + } + pack .pack.b -in .pack.f1 -side right + update + set result {} + lappend result [winfo geometry .pack.b] [winfo ismapped .pack.b] + pack .pack.b -in .pack.f2 -side bottom + update + lappend result [winfo geometry .pack.b] [winfo ismapped .pack.b] + .pack.f1 configure -width 50 -height 20 + update + lappend result [winfo geometry .pack.b] [winfo ismapped .pack.b] + pack forget .pack.b + update + lappend result [winfo geometry .pack.b] [winfo ismapped .pack.b] +} {50x30+48+5 1 50x30+25+48 1 50x30+25+28 1 50x30+25+28 0} +catch {destroy .pack.f1 .pack.f2} +test pack-15.5 {managing geometry with -in option} { + pack forget .pack.a .pack.b .pack.c .pack.d + foreach i {1 2} { + frame .pack.f$i -width 100 -height 20 -bd 2 -relief raised + lower .pack.f$i + pack propagate .pack.f$i 0 + pack .pack.f$i -side top + } + pack .pack.b -in .pack.f2 -side top + update + set result {} + lappend result [winfo geometry .pack.b] [winfo ismapped .pack.b] + pack .pack.a -before .pack.b -side top + update + lappend result [winfo geometry .pack.b] [winfo ismapped .pack.b] +} {50x16+25+22 1 50x16+25+22 0} +catch {destroy .pack.f1 .pack.f2} + +test pack-16.1 {geometry manager name} { + pack forget .pack.a .pack.b .pack.c .pack.d + set result {} + lappend result [winfo manager .pack.a] + pack .pack.a + lappend result [winfo manager .pack.a] + pack forget .pack.a + lappend result [winfo manager .pack.a] +} {{} pack {}} + +test pack-17.1 {PackLostSlaveProc procedure} { + pack forget .pack.a .pack.b .pack.c .pack.d + pack .pack.a + update + place .pack.a -x 40 -y 10 + update + list [winfo manager .pack.a] [winfo geometry .pack.a] \ + [catch {pack info .pack.a} msg] $msg +} {place 20x40+40+10 1 {window ".pack.a" isn't packed}} + +test pack-18.1 {unmap slaves when master unmapped} {tempNotPc} { + # On the PC, when the width/height is configured while the window is + # unmapped, the changes don't take effect until the window is remapped. + # Who knows why? + + eval destroy [winfo child .pack] + frame .pack.a -width 100 -height 50 -relief raised -bd 2 + pack .pack.a + update + set result [winfo ismapped .pack.a] + wm iconify .pack + update + lappend result [winfo ismapped .pack.a] + .pack.a configure -width 200 -height 75 + update + lappend result [winfo width .pack.a ] [winfo height .pack.a] \ + [winfo ismapped .pack.a] + wm deiconify .pack + update + lappend result [winfo ismapped .pack.a] +} {1 0 200 75 0 1} +test pack-18.2 {unmap slaves when master unmapped} { + eval destroy [winfo child .pack] + frame .pack.a -relief raised -bd 2 + frame .pack.b -width 70 -height 30 -relief sunken -bd 2 + pack .pack.a + pack .pack.b -in .pack.a + update + set result [winfo ismapped .pack.b] + wm iconify .pack + update + lappend result [winfo ismapped .pack.b] + .pack.b configure -width 100 -height 30 + update + lappend result [winfo width .pack.b ] [winfo height .pack.b] \ + [winfo ismapped .pack.b] + wm deiconify .pack + update + lappend result [winfo ismapped .pack.b] +} {1 0 100 30 0 1} +destroy .pack +foreach i {pack1 pack2 pack3 pack4} { + rename $i {} +} diff --git a/tests/place.test b/tests/place.test new file mode 100644 index 0000000..06540e3 --- /dev/null +++ b/tests/place.test @@ -0,0 +1,221 @@ +# This file is a Tcl script to test out the "place" command. It is +# organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) place.test 1.6 96/02/16 10:56:01 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +# XXX - This test file is woefully incomplete. At present, only a +# few of the features are tested. + +toplevel .t -width 300 -height 200 -bd 0 +wm geom .t +0+0 +frame .t.f -width 154 -height 84 -bd 2 -relief raised +place .t.f -x 48 -y 38 +frame .t.f2 -width 30 -height 60 -bd 2 -relief raised +update + +test place-1.1 {Tk_PlaceCmd procedure, "info" option} { + place .t.f2 -x 0 + place info .t.f2 +} {-x 0 -relx 0 -y 0 -rely 0 -width {} -relwidth {} -height {} -relheight {} -anchor nw} +test place-1.2 {Tk_PlaceCmd procedure, "info" option} { + place .t.f2 -x 1 -y 2 -width 3 -height 4 -relx 0.1 -rely 0.2 \ + -relwidth 0.3 -relheight 0.4 -anchor se -in .t.f \ + -bordermode outside + place info .t.f2 +} {-x 1 -relx 0.1 -y 2 -rely 0.2 -width 3 -relwidth 0.3 -height 4 -relheight 0.4 -anchor se -bordermode outside -in .t.f} + +test place-2.1 {ConfigureSlave procedure, -height option} { + list [catch {place .t.f2 -height abcd} msg] $msg +} {1 {bad screen distance "abcd"}} +test place-2.2 {ConfigureSlave procedure, -height option} { + place forget .t.f2 + place .t.f2 -in .t.f -height 40 + update + winfo height .t.f2 +} {40} +test place-2.3 {ConfigureSlave procedure, -height option} { + place forget .t.f2 + place .t.f2 -in .t.f -height 120 + update + place .t.f2 -height {} + update + winfo height .t.f2 +} {60} + +test place-3.1 {ConfigureSlave procedure, -relheight option} { + list [catch {place .t.f2 -relheight abcd} msg] $msg +} {1 {expected floating-point number but got "abcd"}} +test place-3.2 {ConfigureSlave procedure, -relheight option} { + place forget .t.f2 + place .t.f2 -in .t.f -relheight .5 + update + winfo height .t.f2 +} {40} +test place-3.3 {ConfigureSlave procedure, -relheight option} { + place forget .t.f2 + place .t.f2 -in .t.f -relheight .8 + update + place .t.f2 -relheight {} + update + winfo height .t.f2 +} {60} + +test place-4.1 {ConfigureSlave procedure, bad -in options} { + place forget .t.f2 + list [catch {place .t.f2 -in .t.f2} msg] $msg +} {1 {can't place .t.f2 relative to itself}} + +test place-5.1 {ConfigureSlave procedure, -relwidth option} { + list [catch {place .t.f2 -relwidth abcd} msg] $msg +} {1 {expected floating-point number but got "abcd"}} +test place-5.2 {ConfigureSlave procedure, -relwidth option} { + place forget .t.f2 + place .t.f2 -in .t.f -relwidth .5 + update + winfo width .t.f2 +} {75} +test place-5.3 {ConfigureSlave procedure, -relwidth option} { + place forget .t.f2 + place .t.f2 -in .t.f -relwidth .8 + update + place .t.f2 -relwidth {} + update + winfo width .t.f2 +} {30} + +test place-6.1 {ConfigureSlave procedure, -width option} { + list [catch {place .t.f2 -width abcd} msg] $msg +} {1 {bad screen distance "abcd"}} +test place-6.2 {ConfigureSlave procedure, -width option} { + place forget .t.f2 + place .t.f2 -in .t.f -width 100 + update + winfo width .t.f2 +} {100} +test place-6.3 {ConfigureSlave procedure, -width option} { + place forget .t.f2 + place .t.f2 -in .t.f -width 120 + update + place .t.f2 -width {} + update + winfo width .t.f2 +} {30} + +test place-7.1 {ReconfigurePlacement procedure, computing position} { + place forget .t.f2 + place .t.f2 -in .t.f -x -2 -relx .5 -y 3 -rely .4 + update + winfo geometry .t.f2 +} {30x60+123+75} +test place-7.2 {ReconfigurePlacement procedure, position rounding} { + place forget .t.f2 + place .t.f2 -in .t.f -x -1.4 -y -2.3 + update + winfo geometry .t.f2 +} {30x60+49+38} +test place-7.3 {ReconfigurePlacement procedure, position rounding} { + place forget .t.f2 + place .t.f2 -in .t.f -x 1.4 -y 2.3 + update + winfo geometry .t.f2 +} {30x60+51+42} +test place-7.4 {ReconfigurePlacement procedure, position rounding} { + place forget .t.f2 + place .t.f2 -in .t.f -x -1.6 -y -2.7 + update + winfo geometry .t.f2 +} {30x60+48+37} +test place-7.5 {ReconfigurePlacement procedure, position rounding} { + place forget .t.f2 + place .t.f2 -in .t.f -x 1.6 -y 2.7 + update + winfo geometry .t.f2 +} {30x60+52+43} +test place-7.6 {ReconfigurePlacement procedure, position rounding} { + frame .t.f3 -width 100 -height 100 -bg #f00000 -bd 0 + place .t.f3 -x 0 -y 0 + raise .t.f2 + place forget .t.f2 + place .t.f2 -in .t.f3 -relx .303 -rely .406 -relwidth .304 -relheight .206 + update + winfo geometry .t.f2 +} {31x20+30+41} +catch {destroy .t.f3} +test place-7.7 {ReconfigurePlacement procedure, computing size} { + place forget .t.f2 + place .t.f2 -in .t.f -width 120 -height 89 + update + list [winfo width .t.f2] [winfo height .t.f2] +} {120 89} +test place-7.8 {ReconfigurePlacement procedure, computing size} { + place forget .t.f2 + place .t.f2 -in .t.f -relwidth .4 -relheight .5 + update + list [winfo width .t.f2] [winfo height .t.f2] +} {60 40} +test place-7.9 {ReconfigurePlacement procedure, computing size} { + place forget .t.f2 + place .t.f2 -in .t.f -width 10 -relwidth .4 -height -4 -relheight .5 + update + list [winfo width .t.f2] [winfo height .t.f2] +} {70 36} +test place-7.10 {ReconfigurePlacement procedure, computing size} { + place forget .t.f2 + place .t.f2 -in .t.f -width 10 -relwidth .4 -height -4 -relheight .5 + place .t.f2 -width {} -relwidth {} -height {} -relheight {} + update + list [winfo width .t.f2] [winfo height .t.f2] +} {30 60} + + +test place-8.1 {MasterStructureProc, mapping and unmapping slaves} { + place forget .t.f2 + place forget .t.f + place .t.f2 -relx 1.0 -rely 1.0 -anchor sw + update + set result [winfo ismapped .t.f2] + wm iconify .t + update + lappend result [winfo ismapped .t.f2] + place .t.f2 -x 40 -y 30 -relx 0 -rely 0 -anchor nw + update + lappend result [winfo x .t.f2] [winfo y .t.f2] [winfo ismapped .t.f2] + wm deiconify .t + update + lappend result [winfo ismapped .t.f2] +} {1 0 40 30 0 1} +test place-8.2 {MasterStructureProc, mapping and unmapping slaves} { + place forget .t.f2 + place forget .t.f + place .t.f -x 0 -y 0 -width 200 -height 100 + place .t.f2 -in .t.f -relx 1.0 -rely 1.0 -anchor sw -width 50 -height 20 + update + set result [winfo ismapped .t.f2] + wm iconify .t + update + lappend result [winfo ismapped .t.f2] + place .t.f2 -x 40 -y 30 -relx 0 -rely 0 -anchor nw + update + lappend result [winfo x .t.f2] [winfo y .t.f2] [winfo ismapped .t.f2] + wm deiconify .t + update + lappend result [winfo ismapped .t.f2] +} {1 0 42 32 0 1} + +catch {destroy .t} +concat diff --git a/tests/raise.test b/tests/raise.test new file mode 100644 index 0000000..af13746 --- /dev/null +++ b/tests/raise.test @@ -0,0 +1,299 @@ +# This file is a Tcl script to test out Tk's "raise" and +# "lower" commands, plus associated code to manage window +# stacking order. It is organized in the standard fashion +# for Tcl tests. +# +# Copyright (c) 1993-1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) raise.test 1.8 96/02/16 10:55:18 + +if {[info commands testmakeexist] == {}} { + puts "This application hasn't been compiled with the \"testmakeexist\"" + puts "command, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +# Procedure to create a bunch of overlapping windows, which should +# make it easy to detect differences in order. + +proc raise_setup {} { + foreach i [winfo child .raise] { + destroy $i + } + foreach i {a b c d e} { + label .raise.$i -text $i -relief raised -bd 2 + } + place .raise.a -x 20 -y 60 -width 60 -height 80 + place .raise.b -x 60 -y 60 -width 60 -height 80 + place .raise.c -x 100 -y 60 -width 60 -height 80 + place .raise.d -x 40 -y 20 -width 100 -height 60 + place .raise.e -x 40 -y 120 -width 100 -height 60 +} + +# Procedure to return information about which windows are on top +# of which other windows. + +proc raise_getOrder {} { + set x [winfo rootx .raise] + set y [winfo rooty .raise] + list [winfo name [winfo containing [expr $x+50] [expr $y+70]]] \ + [winfo name [winfo containing [expr $x+90] [expr $y+70]]] \ + [winfo name [winfo containing [expr $x+130] [expr $y+70]]] \ + [winfo name [winfo containing [expr $x+70] [expr $y+100]]] \ + [winfo name [winfo containing [expr $x+110] [expr $y+100]]] \ + [winfo name [winfo containing [expr $x+50] [expr $y+130]]] \ + [winfo name [winfo containing [expr $x+90] [expr $y+130]]] \ + [winfo name [winfo containing [expr $x+130] [expr $y+130]]] +} + +# Procedure to set up a collection of top-level windows + +proc raise_makeToplevels {} { + foreach i [winfo child .] { + destroy $i + } + foreach i {.raise1 .raise2 .raise3} { + toplevel $i + wm geom $i 150x100+0+0 + update + } +} + +foreach i [winfo child .] { + destroy $i +} +toplevel .raise +wm geom .raise 250x200+0+0 + +test raise-1.1 {preserve creation order} { + raise_setup + update + raise_getOrder +} {d d d b c e e e} +test raise-1.2 {preserve creation order} { + raise_setup + testmakeexist .raise.a + update + raise_getOrder +} {d d d b c e e e} +test raise-1.3 {preserve creation order} { + raise_setup + testmakeexist .raise.c + update + raise_getOrder +} {d d d b c e e e} +test raise-1.4 {preserve creation order} { + raise_setup + testmakeexist .raise.e + update + raise_getOrder +} {d d d b c e e e} +test raise-1.5 {preserve creation order} { + raise_setup + testmakeexist .raise.d .raise.c .raise.b + update + raise_getOrder +} {d d d b c e e e} + +test raise-2.1 {raise internal windows before creation} { + raise_setup + raise .raise.a + update + raise_getOrder +} {a d d a c a e e} +test raise-2.2 {raise internal windows before creation} { + raise_setup + raise .raise.c + update + raise_getOrder +} {d d c b c e e c} +test raise-2.3 {raise internal windows before creation} { + raise_setup + raise .raise.e + update + raise_getOrder +} {d d d b c e e e} +test raise-2.4 {raise internal windows before creation} { + raise_setup + raise .raise.e .raise.a + update + raise_getOrder +} {d d d b c e b c} +test raise-2.5 {raise internal windows before creation} { + raise_setup + raise .raise.a .raise.d + update + raise_getOrder +} {a d d a c e e e} + +test raise-3.1 {raise internal windows after creation} { + raise_setup + update + raise .raise.a .raise.d + raise_getOrder +} {a d d a c e e e} +test raise-3.2 {raise internal windows after creation} { + raise_setup + testmakeexist .raise.a .raise.b + raise .raise.a .raise.b + update + raise_getOrder +} {d d d a c e e e} +test raise-3.3 {raise internal windows after creation} { + raise_setup + testmakeexist .raise.a .raise.d + raise .raise.a .raise.b + update + raise_getOrder +} {d d d a c e e e} +test raise-3.4 {raise internal windows after creation} { + raise_setup + testmakeexist .raise.a .raise.c .raise.d + raise .raise.a .raise.b + update + raise_getOrder +} {d d d a c e e e} + +test raise-4.1 {raise relative to nephews} { + raise_setup + update + frame .raise.d.child + raise .raise.a .raise.d.child + raise_getOrder +} {a d d a c e e e} +test raise-4.2 {raise relative to nephews} { + raise_setup + update + frame .raise2 + list [catch {raise .raise.a .raise2} msg] $msg +} {1 {can't raise ".raise.a" above ".raise2"}} +catch {destroy .raise2} + +test raise-5.1 {lower internal windows} { + raise_setup + update + lower .raise.d + raise_getOrder +} {a b c b c e e e} +test raise-5.2 {lower internal windows} { + raise_setup + update + lower .raise.d .raise.b + raise_getOrder +} {d b c b c e e e} +test raise-5.3 {lower internal windows} { + raise_setup + update + lower .raise.a .raise.e + raise_getOrder +} {a d d a c e e e} +test raise-5.4 {lower internal windows} { + raise_setup + update + frame .raise2 + list [catch {lower .raise.a .raise2} msg] $msg +} {1 {can't lower ".raise.a" below ".raise2"}} +catch {destroy .raise2} + +test raise-6.1 {raise/lower toplevel windows} {nonPortable} { + raise_makeToplevels + update + raise .raise1 + winfo containing [winfo rootx .raise1] [winfo rooty .raise1] +} .raise1 +test raise-6.2 {raise/lower toplevel windows} {nonPortable} { + raise_makeToplevels + update + raise .raise2 + winfo containing [winfo rootx .raise1] [winfo rooty .raise1] +} .raise2 +test raise-6.3 {raise/lower toplevel windows} {nonPortable} { + raise_makeToplevels + update + raise .raise3 + raise .raise2 + raise .raise1 .raise3 + set result [winfo containing [winfo rootx .raise1] \ + [winfo rooty .raise1]] + destroy .raise2 + update + after 500 + list $result [winfo containing [winfo rootx .raise1] \ + [winfo rooty .raise1]] +} {.raise2 .raise1} +test raise-6.4 {raise/lower toplevel windows} {nonPortable} { + raise_makeToplevels + update + raise .raise2 + raise .raise1 + lower .raise3 .raise1 + set result [winfo containing [winfo rootx .raise1] \ + [winfo rooty .raise1]] + wm geometry .raise2 +30+30 + wm geometry .raise1 +60+60 + destroy .raise1 + update + after 500 + list $result [winfo containing [winfo rootx .raise2] \ + [winfo rooty .raise2]] +} {.raise1 .raise3} +test raise-6.5 {raise/lower toplevel windows} {nonPortable} { + raise_makeToplevels + raise .raise1 + set time [lindex [time {raise .raise1}] 0] + expr {$time < 2000000} +} 1 +test raise-6.6 {raise/lower toplevel windows} {nonPortable} { + raise_makeToplevels + update + raise .raise2 + raise .raise1 + raise .raise3 + frame .raise1.f1 + frame .raise1.f1.f2 + lower .raise3 .raise1.f1.f2 + set result [winfo containing [winfo rootx .raise1] \ + [winfo rooty .raise1]] + destroy .raise1 + update + after 500 + list $result [winfo containing [winfo rootx .raise2] \ + [winfo rooty .raise2]] +} {.raise1 .raise3} + +test raise-7.1 {errors in raise/lower commands} { + list [catch {raise} msg] $msg +} {1 {wrong # args: should be "raise window ?aboveThis?"}} +test raise-7.2 {errors in raise/lower commands} { + list [catch {raise a b c} msg] $msg +} {1 {wrong # args: should be "raise window ?aboveThis?"}} +test raise-7.3 {errors in raise/lower commands} { + list [catch {raise badName} msg] $msg +} {1 {bad window path name "badName"}} +test raise-7.4 {errors in raise/lower commands} { + list [catch {raise . badName2} msg] $msg +} {1 {bad window path name "badName2"}} +test raise-7.5 {errors in raise/lower commands} { + list [catch {lower} msg] $msg +} {1 {wrong # args: should be "lower window ?belowThis?"}} +test raise-7.6 {errors in raise/lower commands} { + list [catch {lower a b c} msg] $msg +} {1 {wrong # args: should be "lower window ?belowThis?"}} +test raise-7.7 {errors in raise/lower commands} { + list [catch {lower badName3} msg] $msg +} {1 {bad window path name "badName3"}} +test raise-7.8 {errors in raise/lower commands} { + list [catch {lower . badName4} msg] $msg +} {1 {bad window path name "badName4"}} + +foreach i [winfo child .] { + destroy $i +} diff --git a/tests/safe.test b/tests/safe.test new file mode 100644 index 0000000..65aed36 --- /dev/null +++ b/tests/safe.test @@ -0,0 +1,122 @@ +# This file is a Tcl script to test the Safe Tk facility. It is organized +# in the standard fashion for Tk tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) safe.test 1.15 97/08/13 16:05:17 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} + +# The set of hidden commands is platform dependent: + +if {"$tcl_platform(platform)" == "macintosh"} { + set hidden_cmds {beep bell cd clipboard echo exit fconfigure file glob grab load ls menu open pwd selection socket source tk tk_chooseColor tk_getOpenFile tk_getSaveFile tk_messageBox toplevel wm} +} elseif {"$tcl_platform(platform)" == "windows"} { + set hidden_cmds {bell cd clipboard exec exit fconfigure file glob grab load menu open pwd selection socket source tk tk_chooseColor tk_getOpenFile tk_getSaveFile tk_messageBox toplevel wm} +} else { + set hidden_cmds {bell cd clipboard exec exit fconfigure file glob grab load menu open pwd selection send socket source tk tk_chooseColor tk_getOpenFile tk_getSaveFile tk_messageBox toplevel wm} +} + +test safe-1.1 {Safe Tk loading into an interpreter} { + catch {safe::interpDelete a} + safe::loadTk [safe::interpCreate a] + safe::interpDelete a + set x {} + set x +} "" +test safe-1.2 {Safe Tk loading into an interpreter} { + catch {safe::interpDelete a} + safe::interpCreate a + safe::loadTk a + set l [lsort [interp hidden a]] + safe::interpDelete a + set l +} $hidden_cmds +test safe-1.3 {Safe Tk loading into an interpreter} { + catch {safe::interpDelete a} + safe::interpCreate a + safe::loadTk a + set l [lsort [interp aliases a]] + safe::interpDelete a + set l +} {exit file load source} + +test safe-2.1 {Unsafe commands not available} { + catch {safe::interpDelete a} + safe::interpCreate a + safe::loadTk a + set status broken + if {[catch {interp eval a {toplevel .t}} msg]} { + set status ok + } + safe::interpDelete a + set status +} ok +test safe-2.2 {Unsafe commands not available} { + catch {safe::interpDelete a} + safe::interpCreate a + safe::loadTk a + set status broken + if {[catch {interp eval a {menu .m}} msg]} { + set status ok + } + safe::interpDelete a + set status +} ok + +test safe-3.1 {Unsafe commands are available hidden} { + catch {safe::interpDelete a} + safe::interpCreate a + safe::loadTk a + set status ok + if {[catch {interp invokehidden a toplevel .t} msg]} { + set status broken + } + safe::interpDelete a + set status +} ok +test safe-3.2 {Unsafe commands are available hidden} { + catch {safe::interpDelete a} + safe::interpCreate a + safe::loadTk a + set status ok + if {[catch {interp invokehidden a menu .m} msg]} { + set status broken + } + safe::interpDelete a + set status +} ok + +test safe-4.1 {testing loadTk} { + # no error shall occur, the user will + # eventually see a new toplevel + set i [safe::loadTk [safe::interpCreate]] + interp eval $i {button .b -text "hello world!"; pack .b} +# lets don't update because it might impy that the user has +# to position the window (if the wm does not do it automatically) +# and thus make the test suite not runable non interactively + safe::interpDelete $i +} {} + +test safe-4.2 {testing loadTk -use} { + set w .safeTkFrame + catch {destroy $w} + frame $w -container 1; + pack .safeTkFrame + set i [safe::loadTk [safe::interpCreate] -use [winfo id $w]] + interp eval $i {button .b -text "hello world!"; pack .b} + safe::interpDelete $i + destroy $w +} {} + +unset hidden_cmds diff --git a/tests/scale.test b/tests/scale.test new file mode 100644 index 0000000..405a529 --- /dev/null +++ b/tests/scale.test @@ -0,0 +1,801 @@ +# This file is a Tcl script to test out the "scale" command +# of Tk. It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) scale.test 1.28 97/07/31 10:20:43 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +# Create entries in the option database to be sure that geometry options +# like border width have predictable values. + +option add *Scale.borderWidth 2 +option add *Scale.highlightThickness 2 +option add *Scale.font {Helvetica -12 bold} + +scale .s -from 100 -to 300 +pack .s +update +set i 1 +foreach test { + {-activebackground #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-background #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-bd 4 4 badValue {bad screen distance "badValue"}} + {-bigincrement 12.5 12.5 badValue + {expected floating-point number but got "badValue"}} + {-bg #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-borderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-command "set x" {set x} {} {}} + {-cursor arrow arrow badValue {bad cursor spec "badValue"}} + {-digits 5 5 badValue {expected integer but got "badValue"}} + {-fg #00ff00 #00ff00 badValue {unknown color name "badValue"}} + {-font fixed fixed {} {font "" doesn't exist}} + {-foreground green green badValue {unknown color name "badValue"}} + {-from -15.0 -15.0 badValue + {expected floating-point number but got "badValue"}} + {-highlightbackground #112233 #112233 ugly {unknown color name "ugly"}} + {-highlightcolor #123456 #123456 non-existent + {unknown color name "non-existent"}} + {-highlightthickness 2 2 badValue {bad screen distance "badValue"}} + {-label "Some text" {Some text} {} {}} + {-length 130 130 badValue {bad screen distance "badValue"}} + {-orient horizontal horizontal badValue + {bad orientation "badValue": must be vertical or horizontal}} + {-orient horizontal horizontal {} {}} + {-relief ridge ridge badValue {bad relief type "badValue": must be flat, groove, raised, ridge, solid, or sunken}} + {-repeatdelay 14 14 bogus {expected integer but got "bogus"}} + {-repeatinterval 14 14 bogus {expected integer but got "bogus"}} + {-resolution 2.0 2.0 badValue + {expected floating-point number but got "badValue"}} + {-showvalue 0 0 badValue {expected boolean value but got "badValue"}} + {-sliderlength 86 86 badValue {bad screen distance "badValue"}} + {-sliderrelief raised raised badValue {bad relief type "badValue": must be flat, groove, raised, ridge, solid, or sunken}} + {-state disabled disabled badValue + {bad state value "badValue": must be normal, active, or disabled}} + {-state normal normal {} {}} + {-takefocus "any string" "any string" {} {}} + {-tickinterval 4.3 4.0 badValue + {expected floating-point number but got "badValue"}} + {-to 14.9 15.0 badValue + {expected floating-point number but got "badValue"}} + {-troughcolor #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-variable x x {} {}} + {-width 32 32 badValue {bad screen distance "badValue"}} +} { + set name [lindex $test 0] + test scale-1.$i {configuration options} { + .s configure $name [lindex $test 1] + lindex [.s configure $name] 4 + } [lindex $test 2] + incr i + if {[lindex $test 3] != ""} { + test scale-1.$i {configuration options} { + list [catch {.s configure $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .s configure $name [lindex [.s configure $name] 3] + incr i +} + +destroy .s +test scale-2.1 {Tk_ScaleCmd procedure} { + list [catch {scale} msg] $msg +} {1 {wrong # args: should be "scale pathName ?options?"}} +test scale-2.2 {Tk_ScaleCmd procedure} { + list [catch {scale foo} msg] $msg [winfo child .] +} {1 {bad window path name "foo"} {}} +test scale-2.3 {Tk_ScaleCmd procedure} { + list [catch {scale .s -gorp dumb} msg] $msg [winfo child .] +} {1 {unknown option "-gorp"} {}} + +scale .s -from 100 -to 200 +pack .s +update idletasks +test scale-3.1 {ScaleWidgetCmd procedure} { + list [catch {.s} msg] $msg +} {1 {wrong # args: should be ".s option ?arg arg ...?"}} +test scale-3.2 {ScaleWidgetCmd procedure, cget option} { + list [catch {.s cget} msg] $msg +} {1 {wrong # args: should be ".s cget option"}} +test scale-3.3 {ScaleWidgetCmd procedure, cget option} { + list [catch {.s cget a b} msg] $msg +} {1 {wrong # args: should be ".s cget option"}} +test scale-3.4 {ScaleWidgetCmd procedure, cget option} { + list [catch {.s cget -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test scale-3.5 {ScaleWidgetCmd procedure, cget option} { + .s cget -highlightthickness +} {2} +test scale-3.6 {ScaleWidgetCmd procedure, configure option} { + list [llength [.s configure]] [lindex [.s configure] 5] +} {33 {-borderwidth borderWidth BorderWidth 2 2}} +test scale-3.7 {ScaleWidgetCmd procedure, configure option} { + list [catch {.s configure -foo} msg] $msg +} {1 {unknown option "-foo"}} +test scale-3.8 {ScaleWidgetCmd procedure, configure option} { + list [catch {.s configure -borderwidth 2 -bg} msg] $msg +} {1 {value for "-bg" missing}} +test scale-3.9 {ScaleWidgetCmd procedure, coords option} { + list [catch {.s coords a b} msg] $msg +} {1 {wrong # args: should be ".s coords ?value?"}} +test scale-3.10 {ScaleWidgetCmd procedure, coords option} { + list [catch {.s coords bad} msg] $msg +} {1 {expected floating-point number but got "bad"}} +test scale-3.11 {ScaleWidgetCmd procedure} {fonts} { + .s set 120 + .s coords +} {38 34} +test scale-3.12 {ScaleWidgetCmd procedure, coords option} {fonts} { + .s configure -orient horizontal + update + .s set 120 + .s coords +} {34 31} +.s configure -orient vertical +update +test scale-3.13 {ScaleWidgetCmd procedure, get option} { + list [catch {.s get a} msg] $msg +} {1 {wrong # args: should be ".s get ?x y?"}} +test scale-3.14 {ScaleWidgetCmd procedure, get option} { + list [catch {.s get a b c} msg] $msg +} {1 {wrong # args: should be ".s get ?x y?"}} +test scale-3.15 {ScaleWidgetCmd procedure, get option} { + list [catch {.s get a 11} msg] $msg +} {1 {expected integer but got "a"}} +test scale-3.16 {ScaleWidgetCmd procedure, get option} { + list [catch {.s get 12 b} msg] $msg +} {1 {expected integer but got "b"}} +test scale-3.17 {ScaleWidgetCmd procedure, get option} { + .s set 133 + .s get +} 133 +test scale-3.18 {ScaleWidgetCmd procedure, get option} { + .s configure -resolution 0.5 + .s set 150 + .s get 37 34 +} 119.5 +.s configure -resolution 1 +test scale-3.19 {ScaleWidgetCmd procedure, identify option} { + list [catch {.s identify} msg] $msg +} {1 {wrong # args: should be ".s identify x y"}} +test scale-3.20 {ScaleWidgetCmd procedure, identify option} { + list [catch {.s identify 1 2 3} msg] $msg +} {1 {wrong # args: should be ".s identify x y"}} +test scale-3.21 {ScaleWidgetCmd procedure, identify option} { + list [catch {.s identify boo 16} msg] $msg +} {1 {expected integer but got "boo"}} +test scale-3.22 {ScaleWidgetCmd procedure, identify option} { + list [catch {.s identify 17 bad} msg] $msg +} {1 {expected integer but got "bad"}} +test scale-3.23 {ScaleWidgetCmd procedure, identify option} {fonts} { + .s set 120 + list [.s identify 35 10] [.s identify 35 30] [.s identify 35 80] [.s identify 5 80] +} {trough1 slider trough2 {}} +test scale-3.24 {ScaleWidgetCmd procedure, set option} { + list [catch {.s set} msg] $msg +} {1 {wrong # args: should be ".s set value"}} +test scale-3.25 {ScaleWidgetCmd procedure, set option} { + list [catch {.s set a b} msg] $msg +} {1 {wrong # args: should be ".s set value"}} +test scale-3.26 {ScaleWidgetCmd procedure, set option} { + list [catch {.s set bad} msg] $msg +} {1 {expected floating-point number but got "bad"}} +test scale-3.27 {ScaleWidgetCmd procedure, set option} { + .s set 142 +} {} +test scale-3.28 {ScaleWidgetCmd procedure, set option} { + .s set 118 + .s configure -state disabled + .s set 181 + .s configure -state normal + .s get +} {118} +test scale-3.29 {ScaleWidgetCmd procedure} { + list [catch {.s dumb} msg] $msg +} {1 {bad option "dumb": must be cget, configure, coords, get, identify, or set}} +test scale-3.30 {ScaleWidgetCmd procedure} { + list [catch {.s c} msg] $msg +} {1 {bad option "c": must be cget, configure, coords, get, identify, or set}} +test scale-3.31 {ScaleWidgetCmd procedure} { + list [catch {.s co} msg] $msg +} {1 {bad option "co": must be cget, configure, coords, get, identify, or set}} +test scale-3.32 {ScaleWidgetCmd procedure, Tk_Preserve} { + proc kill args { + destroy .s + } + catch {destroy .s} + scale .s -variable x -from 0 -to 100 -orient horizontal + pack .s + update + .s configure -command kill + .s set 55 +} {} + +test scale-4.1 {DestroyScale procedure} { + catch {destroy .s} + set x 50 + scale .s -variable x -from 0 -to 100 -orient horizontal + pack .s + update + destroy .s + list [catch {set x foo} msg] $msg $x +} {0 foo foo} + +test scale-5.1 {ConfigureScale procedure} { + catch {destroy .s} + set x 66 + set y 77 + scale .s -variable x -from 0 -to 100 + pack .s + update + .s configure -variable y + list [catch {set x foo} msg] $msg $x [.s get] +} {0 foo foo 77} +test scale-5.2 {ConfigureScale procedure} { + catch {destroy .s} + scale .s -from 0 -to 100 + list [catch {.s configure -foo bar} msg] $msg +} {1 {unknown option "-foo"}} +test scale-5.3 {ConfigureScale procedure} { + catch {destroy .s} + catch {unset x} + scale .s -from 0 -to 100 -variable x + set result $x + lappend result [.s get] + set x 92 + lappend result [.s get] + .s set 3 + lappend result $x + unset x + lappend result [catch {set x} msg] $msg +} {0 0 92 3 0 3} +test scale-5.4 {ConfigureScale procedure} { + catch {destroy .s} + scale .s -from 0 -to 100 + list [catch {.s configure -orient dumb} msg] $msg +} {1 {bad orientation "dumb": must be vertical or horizontal}} +test scale-5.5 {ConfigureScale procedure} { + catch {destroy .s} + scale .s -from 1.11 -to 1.89 -resolution .1 -tickinterval .76 + list [format %.1f [.s cget -from]] [format %.1f [.s cget -to]] \ + [format %.1f [.s cget -tickinterval]] +} {1.1 1.9 0.8} +test scale-5.6 {ConfigureScale procedure} { + catch {destroy .s} + scale .s -from 1 -to 10 -tickinterval -2 + pack .s + set result [lindex [.s configure -tickinterval] 4] + .s configure -from 10 -to 1 -tickinterval 2 + lappend result [lindex [.s configure -tickinterval] 4] +} {2.0 -2.0} +test scale-5.7 {ConfigureScale procedure} { + catch {destroy .s} + list [catch {scale .s -from 0 -to 100 -state bogus} msg] $msg +} {1 {bad state value "bogus": must be normal, active, or disabled}} + +catch {destroy .s} +scale .s -orient horizontal -length 200 +pack .s +test scale-6.1 {ComputeFormat procedure} { + .s configure -from 10 -to 100 -resolution 10 + .s set 49.3 + .s get +} {50} +test scale-6.2 {ComputeFormat procedure} { + .s configure -from 100 -to 1000 -resolution 100 + .s set 493 + .s get +} {500} +test scale-6.3 {ComputeFormat procedure} { + .s configure -from 1000 -to 10000 -resolution 1000 + .s set 4930 + .s get +} {5000} +test scale-6.4 {ComputeFormat procedure} { + .s configure -from 10000 -to 100000 -resolution 10000 + .s set 49000 + .s get +} {50000} +test scale-6.5 {ComputeFormat procedure} { + .s configure -from 100000 -to 1000000 -resolution 100000 + .s set 493000 + .s get +} {500000} +test scale-6.6 {ComputeFormat procedure} {nonPortable} { + # This test is non-portable because some platforms format the + # result as 5e+06. + + .s configure -from 1000000 -to 10000000 -resolution 1000000 + .s set 4930000 + .s get +} {5000000} +test scale-6.7 {ComputeFormat procedure} { + .s configure -from 1000000000 -to 10000000000 -resolution 1000000000 + .s set 4930000000 + .s get +} {5.0e+09} +test scale-6.8 {ComputeFormat procedure} { + .s configure -from .1 -to 1 -resolution .1 + .s set .6 + .s get +} {0.6} +test scale-6.9 {ComputeFormat procedure} { + .s configure -from .01 -to .1 -resolution .01 + .s set .06 + .s get +} {0.06} +test scale-6.10 {ComputeFormat procedure} { + .s configure -from .001 -to .01 -resolution .001 + .s set .006 + .s get +} {0.006} +test scale-6.11 {ComputeFormat procedure} { + .s configure -from .0001 -to .001 -resolution .0001 + .s set .0006 + .s get +} {0.0006} +test scale-6.12 {ComputeFormat procedure} { + .s configure -from .00001 -to .0001 -resolution .00001 + .s set .00006 + .s get +} {0.00006} +test scale-6.13 {ComputeFormat procedure} { + .s configure -from .000001 -to .00001 -resolution .000001 + .s set .000006 + .s get +} {6.0e-06} +test scale-6.14 {ComputeFormat procedure} { + .s configure -to .00001 -from .0001 -resolution .00001 + .s set .00006 + .s get +} {0.00006} +test scale-6.15 {ComputeFormat procedure} { + .s configure -to .000001 -from .00001 -resolution .000001 + .s set .000006 + .s get +} {6.0e-06} +test scale-6.16 {ComputeFormat procedure} { + .s configure -from .00001 -to .0001 -resolution .00001 -digits 1 + .s set .00006 + .s get +} {6e-05} +test scale-6.17 {ComputeFormat procedure} { + .s configure -from 10000000 -to 100000000 -resolution 10000000 -digits 3 + .s set 49300000 + .s get +} {50000000} +test scale-6.18 {ComputeFormat procedure} { + .s configure -length 200 -from 0 -to 10 -resolution 0 -digits 0 + .s set .111111111 + .s get +} {0.11} +test scale-6.19 {ComputeFormat procedure} { + .s configure -length 200 -from 1000 -to 1002 -resolution 0 -digits 0 + .s set 1001.23456789 + .s get +} {1001.23} +test scale-6.20 {ComputeFormat procedure} { + .s configure -length 200 -from 1000 -to 1001.8 -resolution 0 -digits 0 + .s set 1001.23456789 + .s get +} {1001.235} + +test scale-7.1 {ComputeScaleGeometry procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 10 -label "Short" -orient vertical -length 5i + pack .s + update + list [winfo reqwidth .s] [winfo reqheight .s] +} {88 458} +test scale-7.2 {ComputeScaleGeometry procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 1000 -label "Long string" -orient vertical -tick 200 + pack .s + update + list [winfo reqwidth .s] [winfo reqheight .s] +} {168 108} +test scale-7.3 {ComputeScaleGeometry procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 1000 -orient vertical -showvalue 0 -width 10 \ + -sliderlength 10 + pack .s + update + list [winfo reqwidth .s] [winfo reqheight .s] +} {22 108} +test scale-7.4 {ComputeScaleGeometry procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 1000 -orient vertical -showvalue 0 -bd 5 \ + -relief sunken + pack .s + update + list [winfo reqwidth .s] [winfo reqheight .s] +} {39 114} +test scale-7.5 {ComputeScaleGeometry procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 10 -label "Short" -orient horizontal -length 5i + pack .s + update + list [winfo reqwidth .s] [winfo reqheight .s] +} {458 61} +test scale-7.6 {ComputeScaleGeometry procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 1000 -label "Long string" -orient horizontal \ + -tick 500 + pack .s + update + list [winfo reqwidth .s] [winfo reqheight .s] +} {108 79} +test scale-7.7 {ComputeScaleGeometry procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 1000 -orient horizontal -showvalue 0 + pack .s + update + list [winfo reqwidth .s] [winfo reqheight .s] +} {108 27} +test scale-7.8 {ComputeScaleGeometry procedure} { + catch {destroy .s} + scale .s -from 0 -to 1000 -orient horizontal -showvalue 0 -bd 5 \ + -relief raised -highlightthickness 2 + pack .s + update + list [winfo reqwidth .s] [winfo reqheight .s] +} {114 39} + +test scale-8.1 {ScaleElement procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 100 -orient vertical -bd 1 -tick 20 -length 300 + pack .s + .s set 30 + update + list [.s identify 53 52] [.s identify 54 52] [.s identify 70 52] \ + [.s identify 71 52] +} {{} trough1 trough1 {}} +test scale-8.2 {ScaleElement procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 100 -orient vertical -bd 1 -tick 20 -length 300 + pack .s + .s set 30 + update + list [.s identify 60 2] [.s identify 60 3] [.s identify 60 302] \ + [.s identify 60 303] +} {{} trough1 trough2 {}} +test scale-8.3 {ScaleElement procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 100 -orient vertical -bd 1 -tick 20 -length 300 + pack .s + .s set 30 + update + list [.s identify 60 83] [.s identify 60 84] [.s identify 60 113] \ + [.s identify 60 114] \ +} {trough1 slider slider trough2} +test scale-8.4 {ScaleElement procedure} { + catch {destroy .s} + scale .s -from 0 -to 100 -orient vertical -bd 4 -width 10 \ + -highlightthickness 1 -length 300 -showvalue 0 + pack .s + .s set 30 + update + list [.s identify 4 40] [.s identify 5 40] [.s identify 22 40] \ + [.s identify 23 40] \ +} {{} trough1 trough1 {}} +test scale-8.5 {ScaleElement procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 100 -orient horizontal -bd 1 \ + -highlightthickness 2 -tick 20 -sliderlength 20 \ + -length 200 -label Test + pack .s + .s set 30 + update + list [.s identify 150 36] [.s identify 150 37] [.s identify 150 53] \ + [.s identify 150 54] +} {{} trough2 trough2 {}} +test scale-8.6 {ScaleElement procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 100 -orient horizontal -bd 2 \ + -highlightthickness 1 -tick 20 -length 200 + pack .s + .s set 30 + update + list [.s identify 150 20] [.s identify 150 21] [.s identify 150 39] \ + [.s identify 150 40] +} {{} trough2 trough2 {}} +test scale-8.7 {ScaleElement procedure} { + catch {destroy .s} + scale .s -from 0 -to 100 -orient horizontal -bd 4 -highlightthickness 2 \ + -length 200 -width 10 -showvalue 0 + pack .s + .s set 30 + update + list [.s identify 30 5] [.s identify 30 6] [.s identify 30 23] \ + [.s identify 30 24] +} {{} trough1 trough1 {}} +test scale-8.8 {ScaleElement procedure} { + catch {destroy .s} + scale .s -from 0 -to 100 -orient horizontal -bd 1 -highlightthickness 2 \ + -tick 20 -sliderlength 20 -length 200 -label Test -showvalue 0 + pack .s + .s set 30 + update + list [.s identify 2 28] [.s identify 3 28] [.s identify 202 28] \ + [.s identify 203 28] +} {{} trough1 trough2 {}} +test scale-8.9 {ScaleElement procedure} { + catch {destroy .s} + scale .s -from 0 -to 100 -orient horizontal -bd 1 -highlightthickness 2 \ + -tick 20 -sliderlength 20 -length 200 -label Test -showvalue 0 + pack .s + .s set 80 + update + list [.s identify 145 28] [.s identify 146 28] [.s identify 165 28] \ + [.s identify 166 28] +} {trough1 slider slider trough2} + +catch {destroy .s} +scale .s -from 0 -to 100 -sliderlength 10 -length 114 -bd 2 +pack .s +update +test scale-9.1 {PixelToValue procedure} { + .s get 46 0 +} 0 +test scale-9.2 {PixelToValue procedure} { + .s get -10 9 +} 0 +test scale-9.3 {PixelToValue procedure} { + .s get -10 12 +} 1 +test scale-9.4 {PixelToValue procedure} { + .s get -10 46 +} 35 +test scale-9.5 {PixelToValue procedure} { + .s get -10 110 +} 99 +test scale-9.6 {PixelToValue procedure} { + .s get -10 111 +} 100 +test scale-9.7 {PixelToValue procedure} { + .s get -10 112 +} 100 +test scale-9.8 {PixelToValue procedure} { + .s get -10 154 +} 100 +.s configure -orient horizontal +update +test scale-9.9 {PixelToValue procedure} { + .s get 76 152 +} 65 + +test scale-10.1 {ValueToPixel procedure} {fonts} { + catch {destroy .s} + scale .s -from 0 -to 100 -sliderlength 20 -length 124 -bd 2 \ + -orient horizontal -label Test -tick 20 + pack .s + update + list [.s coords -10] [.s coords 40] [.s coords 1000] +} {{16 47} {56 47} {116 47}} +test scale-10.2 {ValueToPixel procedure} {fonts} { + catch {destroy .s} + scale .s -from 100 -to 0 -sliderlength 20 -length 122 -bd 1 \ + -orient vertical -label Test -tick 20 + pack .s + update + list [.s coords -10] [.s coords 40] [.s coords 1000] +} {{62 114} {62 74} {62 14}} + +test scale-11.1 {ScaleEventProc procedure} { + proc killScale value { + global x + if {$value > 30} { + destroy .s1 + lappend x [winfo exists .s1] [info commands .s1] + } + } + catch {destroy .s1} + set x initial + scale .s1 -from 0 -to 100 -command killScale + .s1 set 20 + pack .s1 + update idletasks + lappend x [winfo exists .s1] + .s1 set 40 + update idletasks + rename killScale {} + set x +} {initial 1 0 {}} +test scale-11.2 {ScaleEventProc procedure} { + eval destroy [winfo children .] + scale .s1 -bg #543210 + rename .s1 .s2 + set x {} + lappend x [winfo children .] + lappend x [.s2 cget -bg] + destroy .s1 + lappend x [info command .s*] [winfo children .] +} {.s1 #543210 {} {}} + +test scale-12.1 {ScaleCmdDeletedProc procedure} { + eval destroy [winfo children .] + scale .s1 + rename .s1 {} + list [info command .s*] [winfo children .] +} {{} {}} + +catch {destroy .s} +scale .s -from 0 -to 100 -command {set x} -variable y +pack .s +update +proc varTrace args { + global traceInfo + set traceInfo $args +} +test scale-13.1 {SetScaleValue procedure} { + set x xyzzy + .s set 44 + set result [list $x $y] + update + lappend result $x $y +} {xyzzy 44 44 44} +test scale-13.2 {SetScaleValue procedure} { + .s set -3 + .s get +} 0 +test scale-13.3 {SetScaleValue procedure} { + .s set 105 + .s get +} 100 +.s configure -from 100 -to 0 +test scale-13.4 {SetScaleValue procedure} { + .s set -3 + .s get +} 0 +test scale-13.5 {SetScaleValue procedure} { + .s set 105 + .s get +} 100 +test scale-13.6 {SetScaleValue procedure} { + .s set 50 + update + trace variable y w varTrace + set traceInfo empty + set x untouched + .s set 50 + update + list $x $traceInfo +} {untouched empty} + +catch {destroy .s} +scale .s -from 0 -to 100 -sliderlength 10 -length 114 -bd 2 -orient horizontal +pack .s +update +.s configure -resolution 4.0 +update +test scale-14.1 {RoundToResolution procedure} { + .s get 84 152 +} 72 +test scale-14.2 {RoundToResolution procedure} { + .s get 86 152 +} 76 +.s configure -from 100 -to 0 +update +test scale-14.3 {RoundToResolution procedure} { + .s get 84 152 +} 28 +test scale-14.4 {RoundToResolution procedure} { + .s get 86 152 +} 24 +.s configure -from -100 -to 0 +update +test scale-14.5 {RoundToResolution procedure} { + .s get 84 152 +} -28 +test scale-14.6 {RoundToResolution procedure} { + .s get 86 152 +} -24 +.s configure -from 0 -to -100 +update +test scale-14.7 {RoundToResolution procedure} { + .s get 84 152 +} -72 +test scale-14.8 {RoundToResolution procedure} { + .s get 86 152 +} -76 +.s configure -from 0 -to 2.25 -resolution 0 +update +test scale-14.9 {RoundToResolution procedure} { + .s get 84 152 +} 1.64 +test scale-14.10 {RoundToResolution procedure} { + .s get 86 152 +} 1.69 +.s configure -from 0 -to 225 -resolution 0 -digits 5 +update +test scale-14.11 {RoundToResolution procedure} { + .s get 84 152 +} 164.25 +test scale-14.12 {RoundToResolution procedure} { + .s get 86 152 +} 168.75 + +test scale-15.1 {ScaleVarProc procedure} { + catch {destroy .s} + set y -130 + scale .s -from 0 -to -200 -variable y -orient horizontal -length 150 + pack .s + set y +} -130 +test scale-15.2 {ScaleVarProc procedure} { + catch {destroy .s} + set y -130 + scale .s -from -200 -to 0 -variable y -orient horizontal -length 150 + pack .s + set y -87 + .s get +} -87 +test scale-15.3 {ScaleVarProc procedure} { + catch {destroy .s} + set y -130 + scale .s -from -200 -to 0 -variable y -orient horizontal -length 150 + pack .s + list [catch {set y 40q} msg] $msg [.s get] +} {1 {can't set "y": can't assign non-numeric value to scale variable} -130} +test scale-15.4 {ScaleVarProc procedure} { + catch {destroy .s} + set y 1 + scale .s -from 1 -to 0 -variable y -orient horizontal -length 150 + pack .s + list [catch {set y x} msg] $msg [.s get] +} {1 {can't set "y": can't assign non-numeric value to scale variable} 1} +test scale-15.5 {ScaleVarProc procedure, variable deleted} { + catch {destroy .s} + set y 6 + scale .s -from 10 -to 0 -variable y -orient horizontal -length 150 \ + -command "set x" + pack .s + update + set x untouched + unset y + update + list [catch {set y} msg] $msg [.s get] $x +} {0 6 6 untouched} +test scale-15.6 {ScaleVarProc procedure, don't call -command} { + catch {destroy .s} + set y 6 + scale .s -from 0 -to 100 -variable y -orient horizontal -length 150 \ + -command "set x" + pack .s + update + set x untouched + set y 60 + update + list $x [.s get] +} {untouched 60} + +set l [interp hidden] +eval destroy [winfo children .] + +test scale-16.1 {scale widget vs hidden commands} { + catch {destroy .s} + scale .s + interp hide {} .s + destroy .s + list [winfo children .] [interp hidden] +} [list {} $l] + +catch {destroy .s} +option clear diff --git a/tests/scrollbar.test b/tests/scrollbar.test new file mode 100644 index 0000000..9242acb --- /dev/null +++ b/tests/scrollbar.test @@ -0,0 +1,665 @@ +# This file is a Tcl script to test out scrollbar widgets and +# the "scrollbar" command of Tk. It is organized in the standard +# fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) scrollbar.test 1.33 97/08/13 17:37:19 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . +update + +proc scroll args { + global scrollInfo + set scrollInfo $args +} + +proc getTroughSize {w} { + global tcl_platform + if {$tcl_platform(platform) == "windows"} { + if [string match v* [$w cget -orient]] { + return [expr [winfo height $w] - 2*[testmetrics cyvscroll]] + } else { + return [expr [winfo width $w] - 2*[testmetrics cxhscroll]] + } + } else { + if [string match v* [$w cget -orient]] { + return [expr [winfo height $w] \ + - ([winfo width $w] \ + - [$w cget -highlightthickness] \ + - [$w cget -bd] + 1)*2] + } else { + return [expr [winfo width $w] \ + - ([winfo height $w] \ + - [$w cget -highlightthickness] \ + - [$w cget -bd] + 1)*2] + } + } +} + +# XXX Note: this test file is woefully incomplete. Right now there are +# only bits and pieces of tests. Please make this file more complete +# as you fix bugs and add features. + +foreach {width height} [wm minsize .] { + set height [expr ($height < 200) ? 200 : $height] + set width [expr ($width < 1) ? 1 : $width] +} + +frame .f -height $height -width $width +pack .f -side left +scrollbar .s +pack .s -side right -fill y +update +set i 1 +foreach test { + {-activebackground #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-activerelief sunken sunken non-existent + {bad relief type "non-existent": must be flat, groove, raised, ridge, solid, or sunken}} + {-background #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-bd 4 4 badValue {bad screen distance "badValue"}} + {-bg #ff0000 #ff0000 non-existent + {unknown color name "non-existent"}} + {-borderwidth 1.3 1 badValue {bad screen distance "badValue"}} + {-command "set x" {set x} {} {}} + {-elementborderwidth 4 4 badValue {bad screen distance "badValue"}} + {-cursor arrow arrow badValue {bad cursor spec "badValue"}} + {-highlightbackground #112233 #112233 ugly {unknown color name "ugly"}} + {-highlightcolor #123456 #123456 bogus {unknown color name "bogus"}} + {-highlightthickness 6 6 bogus {bad screen distance "bogus"}} + {-highlightthickness -2 0 {} {}} + {-jump true 1 silly {expected boolean value but got "silly"}} + {-orient horizontal horizontal badValue + {bad orientation "badValue": must be vertical or horizontal}} + {-orient horizontal horizontal bogus {bad orientation "bogus": must be vertical or horizontal}} + {-relief ridge ridge badValue {bad relief type "badValue": must be flat, groove, raised, ridge, solid, or sunken}} + {-repeatdelay 140 140 129.3 {expected integer but got "129.3"}} + {-repeatinterval 140 140 129.3 {expected integer but got "129.3"}} + {-takefocus "any string" "any string" {} {}} + {-trough #432 #432 lousy {unknown color name "lousy"}} + {-width 32 32 badValue {bad screen distance "badValue"}} +} { + set name [lindex $test 0] + test scrollbar-1.1 {configuration options} { + .s configure $name [lindex $test 1] + lindex [.s configure $name] 4 + } [lindex $test 2] + incr i + if {[lindex $test 3] != ""} { + test scrollbar-1.2 {configuration options} { + list [catch {.s configure $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .s configure $name [lindex [.s configure $name] 3] + incr i +} + +destroy .s +test scrollbar-2.1 {Tk_ScrollbarCmd procedure} { + list [catch {scrollbar} msg] $msg +} {1 {wrong # args: should be "scrollbar pathName ?options?"}} +test scrollbar-2.2 {Tk_ScrollbarCmd procedure} { + list [catch {scrollbar gorp} msg] $msg +} {1 {bad window path name "gorp"}} +test scrollbar-2.3 {Tk_ScrollbarCmd procedure} { + scrollbar .s + set x "[winfo class .s] [info command .s]" + destroy .s + set x +} {Scrollbar .s} +test scrollbar-2.4 {Tk_ScrollbarCmd procedure} { + list [catch {scrollbar .s -gorp blah} msg] $msg [winfo exists .s] \ + [info command .s] +} {1 {unknown option "-gorp"} 0 {}} +test scrollbar-2.5 {Tk_ScrollbarCmd procedure} { + set x [scrollbar .s] + destroy .s + set x +} {.s} + +scrollbar .s -orient vertical -command scroll -highlightthickness 2 -bd 2 +pack .s -side right -fill y +update +test scrollbar-3.1 {ScrollbarWidgetCmd procedure} { + list [catch {.s} msg] $msg +} {1 {wrong # args: should be ".s option ?arg arg ...?"}} +test scrollbar-3.2 {ScrollbarWidgetCmd procedure, "cget" option} { + list [catch {.s cget} msg] $msg +} {1 {wrong # args: should be ".s cget option"}} +test scrollbar-3.3 {ScrollbarWidgetCmd procedure, "cget" option} { + list [catch {.s cget -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test scrollbar-3.4 {ScrollbarWidgetCmd procedure, "activate" option} { + list [catch {.s activate a b} msg] $msg +} {1 {wrong # args: should be ".s activate element"}} +test scrollbar-3.5 {ScrollbarWidgetCmd procedure, "activate" option} { + .s activate arrow1 + .s activate +} {arrow1} +test scrollbar-3.6 {ScrollbarWidgetCmd procedure, "activate" option} { + .s activate slider + .s activate +} {slider} +test scrollbar-3.7 {ScrollbarWidgetCmd procedure, "activate" option} { + .s activate arrow2 + .s activate +} {arrow2} +test scrollbar-3.8 {ScrollbarWidgetCmd procedure, "activate" option} { + .s activate s + .s activate {} + .s activate +} {} +test scrollbar-3.9 {ScrollbarWidgetCmd procedure, "activate" option} { + list [catch {.s activate trough1} msg] $msg +} {0 {}} +test scrollbar-3.10 {ScrollbarWidgetCmd procedure, "cget" option} { + list [catch {.s cget -orient} msg] $msg +} {0 vertical} +scrollbar .s2 +test scrollbar-3.11 {ScrollbarWidgetCmd procedure, "cget" option} {pc} { + list [catch {.s2 cget -bd} msg] $msg +} {0 0} +test scrollbar-3.12 {ScrollbarWidgetCmd procedure, "cget" option} {!pc} { + list [catch {.s2 cget -bd} msg] $msg +} {0 2} +test scrollbar-3.13 {ScrollbarWidgetCmd procedure, "cget" option} {pc} { + list [catch {.s2 cget -highlightthickness} msg] $msg +} {0 0} +test scrollbar-3.14 {ScrollbarWidgetCmd procedure, "cget" option} {!pc} { + list [catch {.s2 cget -highlightthickness} msg] $msg +} {0 1} +destroy .s2 +test scrollbar-3.15 {ScrollbarWidgetCmd procedure, "configure" option} { + llength [.s configure] +} {20} +test scrollbar-3.16 {ScrollbarWidgetCmd procedure, "configure" option} { + list [catch {.s configure -bad} msg] $msg +} {1 {unknown option "-bad"}} +test scrollbar-3.17 {ScrollbarWidgetCmd procedure, "configure" option} { + .s configure -orient +} {-orient orient Orient vertical vertical} +test scrollbar-3.18 {ScrollbarWidgetCmd procedure, "configure" option} { + .s configure -orient horizontal + set x [.s cget -orient] + .s configure -orient vertical + set x +} {horizontal} +test scrollbar-3.19 {ScrollbarWidgetCmd procedure, "configure" option} { + list [catch {.s configure -bad worse} msg] $msg +} {1 {unknown option "-bad"}} +test scrollbar-3.20 {ScrollbarWidgetCmd procedure, "delta" option} { + list [catch {.s delta 24} msg] $msg +} {1 {wrong # args: should be ".s delta xDelta yDelta"}} +test scrollbar-3.21 {ScrollbarWidgetCmd procedure, "delta" option} { + list [catch {.s delta 24 35 42} msg] $msg +} {1 {wrong # args: should be ".s delta xDelta yDelta"}} +test scrollbar-3.22 {ScrollbarWidgetCmd procedure, "delta" option} { + list [catch {.s delta silly 24} msg] $msg +} {1 {expected integer but got "silly"}} +test scrollbar-3.23 {ScrollbarWidgetCmd procedure, "delta" option} { + list [catch {.s delta 18 xxyz} msg] $msg +} {1 {expected integer but got "xxyz"}} +test scrollbar-3.24 {ScrollbarWidgetCmd procedure, "delta" option} { + list [catch {.s delta 18 xxyz} msg] $msg +} {1 {expected integer but got "xxyz"}} +test scrollbar-3.25 {ScrollbarWidgetCmd procedure, "delta" option} { + .s delta 20 0 +} {0} +test scrollbar-3.26 {ScrollbarWidgetCmd procedure, "delta" option} { + .s delta 0 20 +} [format %.6g [expr 20.0/([getTroughSize .s]-1)]] +test scrollbar-3.27 {ScrollbarWidgetCmd procedure, "delta" option} { + .s delta 0 -20 +} [format %.6g [expr -20.0/([getTroughSize .s]-1)]] +test scrollbar-3.28 {ScrollbarWidgetCmd procedure, "delta" option} { + toplevel .t -width 250 -height 100 + wm geom .t +0+0 + scrollbar .t.s -orient horizontal -borderwidth 2 + place .t.s -width 201 + update + set result [list [.t.s delta 0 20] \ + [.t.s delta [expr [getTroughSize .t.s] - 1] 0]] + destroy .t + set result +} {0 1} +test scrollbar-3.29 {ScrollbarWidgetCmd procedure, "fraction" option} { + list [catch {.s fraction 24} msg] $msg +} {1 {wrong # args: should be ".s fraction x y"}} +test scrollbar-3.30 {ScrollbarWidgetCmd procedure, "fraction" option} { + list [catch {.s fraction 24 30 32} msg] $msg +} {1 {wrong # args: should be ".s fraction x y"}} +test scrollbar-3.31 {ScrollbarWidgetCmd procedure, "fraction" option} { + list [catch {.s fraction silly 24} msg] $msg +} {1 {expected integer but got "silly"}} +test scrollbar-3.32 {ScrollbarWidgetCmd procedure, "fraction" option} { + list [catch {.s fraction 24 bogus} msg] $msg +} {1 {expected integer but got "bogus"}} +test scrollbar-3.33 {ScrollbarWidgetCmd procedure, "fraction" option} { + .s fraction 0 0 +} {0} +test scrollbar-3.34 {ScrollbarWidgetCmd procedure, "fraction" option} { + .s fraction 0 1000 +} {1} +test scrollbar-3.35 {ScrollbarWidgetCmd procedure, "fraction" option} { + .s fraction 4 21 +} [format %.6g [expr (21.0 - ([winfo height .s] - [getTroughSize .s])/2.0) \ + /([getTroughSize .s] - 1)]] +test scrollbar-3.36 {ScrollbarWidgetCmd procedure, "fraction" option} {unixOnly} { + .s fraction 4 179 +} {1} +test scrollbar-3.37 {ScrollbarWidgetCmd procedure, "fraction" option} {macOrPc} { + .s fraction 4 [expr 200 - [testmetrics cyvscroll .s]] +} {1} +test scrollbar-3.38 {ScrollbarWidgetCmd procedure, "fraction" option} {unixOnly} { + .s fraction 4 178 +} {0.993711} +test scrollbar-3.39 {ScrollbarWidgetCmd procedure, "fraction" option} {pcOnly} { + expr [.s fraction 4 [expr 200 - [testmetrics cyvscroll .s] - 2]] \ + == [format %g [expr (200.0 - [testmetrics cyvscroll .s]*2 - 2) \ + / ($height - 1 - [testmetrics cyvscroll .s]*2)]] +} 1 +test scrollbar-3.40 {ScrollbarWidgetCmd procedure, "fraction" option} {macOnly} { + .s fraction 4 178 +} {0.97006} + +toplevel .t -width 250 -height 100 +wm geom .t +0+0 +scrollbar .t.s -orient horizontal -borderwidth 2 +place .t.s -width 201 +update + +test scrollbar-3.41 {ScrollbarWidgetCmd procedure, "fraction" option} { + .t.s fraction 100 0 +} {0.5} +if {$tcl_platform(platform) == "windows"} { + place configure .t.s -width [expr 2*[testmetrics cxhscroll]+1] +} else { + place configure .t.s -width [expr [winfo reqwidth .t.s] - 4] +} +update +test scrollbar-3.42 {ScrollbarWidgetCmd procedure, "fraction" option} { + .t.s fraction 100 0 +} {0} +destroy .t +test scrollbar-3.43 {ScrollbarWidgetCmd procedure, "get" option} { + list [catch {.s get a} msg] $msg +} {1 {wrong # args: should be ".s get"}} +test scrollbar-3.44 {ScrollbarWidgetCmd procedure, "get" option} { + .s set 100 10 13 14 + .s get +} {100 10 13 14} +test scrollbar-3.45 {ScrollbarWidgetCmd procedure, "get" option} { + .s set 0.6 0.8 + set result {} + foreach element [.s get] { + lappend result [format %.1f $element] + } + set result +} {0.6 0.8} +test scrollbar-3.46 {ScrollbarWidgetCmd procedure, "identify" option} { + list [catch {.s identify 0} msg] $msg +} {1 {wrong # args: should be ".s identify x y"}} +test scrollbar-3.47 {ScrollbarWidgetCmd procedure, "identify" option} { + list [catch {.s identify 0 0 1} msg] $msg +} {1 {wrong # args: should be ".s identify x y"}} +test scrollbar-3.48 {ScrollbarWidgetCmd procedure, "identify" option} { + list [catch {.s identify bogus 2} msg] $msg +} {1 {expected integer but got "bogus"}} +test scrollbar-3.49 {ScrollbarWidgetCmd procedure, "identify" option} { + list [catch {.s identify -1 bogus} msg] $msg +} {1 {expected integer but got "bogus"}} +test scrollbar-3.50 {ScrollbarWidgetCmd procedure, "identify" option} { + .s identify 5 5 +} {arrow1} +test scrollbar-3.51 {ScrollbarWidgetCmd procedure, "identify" option} { + .s identify 5 35 +} {trough1} +test scrollbar-3.52 {ScrollbarWidgetCmd procedure, "identify" option} { + .s set .3 .6 + .s identify 5 80 +} {slider} +test scrollbar-3.53 {ScrollbarWidgetCmd procedure, "identify" option} { + .s identify 5 145 +} {trough2} +test scrollbar-3.54 {ScrollbarWidgetCmd procedure, "identify" option} {unixOrPc} { + .s identify 5 195 +} {arrow2} +test scrollbar-3.55 {ScrollbarWidgetCmd procedure, "identify" option} {macOnly} { + .s identify 5 195 +} {} +test scrollbar-3.56 {ScrollbarWidgetCmd procedure, "identify" option} {unixOnly} { + .s identify 0 0 +} {} +test scrollbar-3.57 {ScrollbarWidgetCmd procedure, "set" option} { + list [catch {.s set abc def} msg] $msg +} {1 {expected floating-point number but got "abc"}} +test scrollbar-3.58 {ScrollbarWidgetCmd procedure, "set" option} { + list [catch {.s set 0.6 def} msg] $msg +} {1 {expected floating-point number but got "def"}} +test scrollbar-3.59 {ScrollbarWidgetCmd procedure, "set" option} { + .s set -.2 .3 + set result {} + foreach element [.s get] { + lappend result [format %.1f $element] + } + set result +} {0.0 0.3} +test scrollbar-3.60 {ScrollbarWidgetCmd procedure, "set" option} { + .s set 1.1 .4 + .s get +} {1.0 1.0} +test scrollbar-3.61 {ScrollbarWidgetCmd procedure, "set" option} { + .s set .5 -.3 + .s get +} {0.5 0.5} +test scrollbar-3.62 {ScrollbarWidgetCmd procedure, "set" option} { + .s set .5 87 + .s get +} {0.5 1.0} +test scrollbar-3.63 {ScrollbarWidgetCmd procedure, "set" option} { + .s set .4 .3 + set result {} + foreach element [.s get] { + lappend result [format %.1f $element] + } + set result +} {0.4 0.4} +test scrollbar-3.64 {ScrollbarWidgetCmd procedure, "set" option} { + list [catch {.s set abc def ghi jkl} msg] $msg +} {1 {expected integer but got "abc"}} +test scrollbar-3.65 {ScrollbarWidgetCmd procedure, "set" option} { + list [catch {.s set 1 def ghi jkl} msg] $msg +} {1 {expected integer but got "def"}} +test scrollbar-3.66 {ScrollbarWidgetCmd procedure, "set" option} { + list [catch {.s set 1 2 ghi jkl} msg] $msg +} {1 {expected integer but got "ghi"}} +test scrollbar-3.67 {ScrollbarWidgetCmd procedure, "set" option} { + list [catch {.s set 1 2 3 jkl} msg] $msg +} {1 {expected integer but got "jkl"}} +test scrollbar-3.68 {ScrollbarWidgetCmd procedure, "set" option} { + .s set -10 50 20 30 + .s get +} {0 50 0 0} +test scrollbar-3.69 {ScrollbarWidgetCmd procedure, "set" option} { + .s set 100 -10 20 30 + .s get +} {100 0 20 30} +test scrollbar-3.70 {ScrollbarWidgetCmd procedure, "set" option} { + .s set 100 50 30 20 + .s get +} {100 50 30 30} +test scrollbar-3.71 {ScrollbarWidgetCmd procedure, "set" option} { + list [catch {.s set 1 2 3} msg] $msg +} {1 {wrong # args: should be ".s set firstFraction lastFraction" or ".s set totalUnits windowUnits firstUnit lastUnit"}} +test scrollbar-3.72 {ScrollbarWidgetCmd procedure, "set" option} { + list [catch {.s set 1 2 3 4 5} msg] $msg +} {1 {wrong # args: should be ".s set firstFraction lastFraction" or ".s set totalUnits windowUnits firstUnit lastUnit"}} +test scrollbar-3.73 {ScrollbarWidgetCmd procedure} { + list [catch {.s bogus} msg] $msg +} {1 {bad option "bogus": must be activate, cget, configure, delta, fraction, get, identify, or set}} +test scrollbar-3.74 {ScrollbarWidgetCmd procedure} { + list [catch {.s c} msg] $msg +} {1 {bad option "c": must be activate, cget, configure, delta, fraction, get, identify, or set}} + +test scrollbar-4.1 {ScrollbarEventProc procedure} { + catch {destroy .s1} + scrollbar .s1 -bg #543210 + rename .s1 .s2 + set x {} + lappend x [winfo exists .s1] + lappend x [.s2 cget -bg] + destroy .s1 + lappend x [info command .s?] [winfo exists .s1] [winfo exists .s2] +} {1 #543210 {} 0 0} + +test scrollbar-5.1 {ScrollbarCmdDeletedProc procedure} { + catch {destroy .s1} + scrollbar .s1 + rename .s1 {} + list [info command .s?] [winfo exists .s1] +} {{} 0} + +catch {destroy .s} +scrollbar .s -orient vertical -relief sunken -bd 2 -highlightthickness 2 +pack .s -side left -fill y +.s set .2 .4 +update +test scrollbar-6.1 {ScrollbarPosition procedure} {unixOnly} { + .s identify 8 3 +} {} +test scrollbar-6.2 {ScrollbarPosition procedure} {macOnly} { + .s identify 8 3 +} {arrow1} +test scrollbar-6.3 {ScrollbarPosition procedure} {macOrUnix} { + .s identify 8 196 +} {} +test scrollbar-6.4 {ScrollbarPosition procedure} {unixOnly} { + .s identify 3 100 +} {} +test scrollbar-6.5 {ScrollbarPosition procedure} {macOnly} { + .s identify 3 100 +} {trough2} +test scrollbar-6.6 {ScrollbarPosition procedure} {macOrUnix} { + .s identify 19 100 +} {} +test scrollbar-6.7 {ScrollbarPosition procedure} { + .s identify [expr [winfo width .s] / 2] -1 +} {} +test scrollbar-6.8 {ScrollbarPosition procedure} { + .s identify [expr [winfo width .s] / 2] [expr [winfo height .s]] +} {} +test scrollbar-6.9 {ScrollbarPosition procedure} { + .s identify -1 [expr [winfo height .s] / 2] +} {} +test scrollbar-6.10 {ScrollbarPosition procedure} { + .s identify [winfo width .s] [expr [winfo height .s] / 2] +} {} + +test scrollbar-6.11 {ScrollbarPosition procedure} {macOrUnix} { + .s identify 8 4 +} {arrow1} +test scrollbar-6.12 {ScrollbarPosition procedure} {unixOnly} { + .s identify 8 19 +} {arrow1} +test scrollbar-6.13 {ScrollbarPosition procedure} {macOnly} { + .s identify 8 19 +} {trough1} +test scrollbar-6.14 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] / 2] 0 +} {arrow1} +test scrollbar-6.15 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] / 2] [expr [testmetrics cyvscroll] - 1] +} {arrow1} + +test scrollbar-6.16 {ScrollbarPosition procedure} {macOrUnix} { + .s identify 8 20 +} {trough1} +test scrollbar-6.17 {ScrollbarPosition procedure} {macOrUnix nonPortable} { + # Don't know why this is non-portable, but it doesn't work on + # some platforms. + .s identify 8 51 +} {trough1} +test scrollbar-6.18 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] / 2] [testmetrics cyvscroll] +} {trough1} +test scrollbar-6.19 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] / 2] [expr int(.2 / [.s delta 0 1]) \ + + [testmetrics cyvscroll] - 1] +} {trough1} + +test scrollbar-6.20 {ScrollbarPosition procedure} {macOrUnix} { + .s identify 8 52 +} {slider} +test scrollbar-6.21 {ScrollbarPosition procedure} {macOrUnix nonPortable} { + # Don't know why this is non-portable, but it doesn't work on + # some platforms. + .s identify 8 83 +} {slider} +test scrollbar-6.22 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] / 2] [expr int(.2 / [.s delta 0 1]) \ + + [testmetrics cyvscroll]] +} {slider} +test scrollbar-6.23 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] / 2] [expr int(.4 / [.s delta 0 1]) \ + + [testmetrics cyvscroll] - 1] +} {slider} + +test scrollbar-6.24 {ScrollbarPosition procedure} {macOrUnix} { + .s identify 8 84 +} {trough2} +test scrollbar-6.25 {ScrollbarPosition procedure} {unixOnly} { + .s identify 8 179 +} {trough2} +test scrollbar-6.26 {ScrollbarPosition procedure} {macOnly} { + .s identify 8 179 +} {arrow2} +test scrollbar-6.27 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] / 2] [expr int(.4 / [.s delta 0 1]) \ + + [testmetrics cyvscroll]] +} {trough2} +test scrollbar-6.28 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] / 2] [expr [winfo height .s] \ + - [testmetrics cyvscroll] - 1] +} {trough2} + +test scrollbar-6.29 {ScrollbarPosition procedure} {macOrUnix} { + .s identify 8 180 +} {arrow2} +test scrollbar-6.30 {ScrollbarPosition procedure} {unixOnly} { + .s identify 8 195 +} {arrow2} +test scrollbar-6.31 {ScrollbarPosition procedure} {macOnly} { + .s identify 8 195 +} {} +test scrollbar-6.32 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] / 2] [expr [winfo height .s] \ + - [testmetrics cyvscroll]] +} {arrow2} +test scrollbar-6.33 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] / 2] [expr [winfo height .s] - 1] +} {arrow2} + +test scrollbar-6.34 {ScrollbarPosition procedure} {macOrUnix} { + .s identify 4 100 +} {trough2} +test scrollbar-6.35 {ScrollbarPosition procedure} {unixOnly} { + .s identify 18 100 +} {trough2} +test scrollbar-6.36 {ScrollbarPosition procedure} {macOnly} { + .s identify 18 100 +} {} +test scrollbar-6.37 {ScrollbarPosition procedure} {pcOnly} { + .s identify 0 100 +} {trough2} +test scrollbar-6.38 {ScrollbarPosition procedure} {pcOnly} { + .s identify [expr [winfo width .s] - 1] 100 +} {trough2} + +catch {destroy .t} +toplevel .t -width 250 -height 150 +wm geometry .t +0+0 +scrollbar .t.s -orient horizontal -relief sunken -bd 2 -highlightthickness 2 +place .t.s -width 200 +.t.s set .2 .4 +update +test scrollbar-6.39 {ScrollbarPosition procedure} {macOrUnix} { + .t.s identify 4 8 +} {arrow1} +test scrollbar-6.40 {ScrollbarPosition procedure} {pcOnly} { + .t.s identify 0 [expr [winfo height .t.s] / 2] +} {arrow1} +test scrollbar-6.41 {ScrollbarPosition procedure} {unixOnly} { + .t.s identify 82 8 +} {slider} +test scrollbar-6.42 {ScrollbarPosition procedure} {macOnly} { + .t.s identify 82 8 +} {} +test scrollbar-6.43 {ScrollbarPosition procedure} {pcOnly} { + .t.s identify [expr int(.4 / [.t.s delta 1 0]) + [testmetrics cxhscroll] \ + - 1] [expr [winfo height .t.s] / 2] +} {slider} +test scrollbar-6.44 {ScrollbarPosition procedure} {unixOnly} { + .t.s identify 100 18 +} {trough2} +test scrollbar-6.45 {ScrollbarPosition procedure} {macOnly} { + .t.s identify 100 18 +} {} +test scrollbar-6.46 {ScrollbarPosition procedure} {pcOnly} { + .t.s identify 100 [expr [winfo height .t.s] - 1] +} {trough2} + +test scrollbar-7.1 {EventuallyRedraw} { + .s configure -orient horizontal + update + set result [.s cget -orient] + .s configure -orient vertical + update + lappend result [.s cget -orient] +} {horizontal vertical} + +catch {destroy .t} +toplevel .t +wm geometry .t +0+0 +test scrollbar-8.1 {TkScrollbarEventProc: recursive deletion} { + proc doit {args} { destroy .t.f } + proc bgerror {args} {} + frame .t.f + scrollbar .t.f.s -command doit + pack .t.f -fill both -expand 1 + pack .t.f.s -fill y -expand 1 -side right + wm geometry .t 100x100 + .t.f.s set 0 .5 + update + set result [winfo exists .t.f.s] + event generate .t.f.s <ButtonPress> -button 1 -x [expr [winfo width .t.f.s] / 2] -y 5 + update + lappend result [winfo exists .t.f.s] [winfo exists .t.f] + rename bgerror {} + set result +} {1 0 0} +test scrollbar-8.2 {TkScrollbarEventProc: recursive deletion} { + proc doit {args} { destroy .t.f.s } + proc bgerror {args} {} + frame .t.f + scrollbar .t.f.s -command doit + pack .t.f -fill both -expand 1 + pack .t.f.s -fill y -expand 1 -side right + wm geometry .t 100x100 + .t.f.s set 0 .5 + update + set result [winfo exists .t.f.s] + event generate .t.f.s <ButtonPress> -button 1 -x [expr [winfo width .t.f.s] / 2] -y 5 + update + lappend result [winfo exists .t.f.s] [winfo exists .t.f] + rename bgerror {} + set result +} {1 0 1} + +set l [interp hidden] +eval destroy [winfo children .] + +test scrollbar-9.1 {scrollbar widget vs hidden commands} { + catch {destroy .s} + scrollbar .s + interp hide {} .s + destroy .s + list [winfo children .] [interp hidden] +} [list {} $l] + +catch {destroy .s} +catch {destroy .t} +concat {} diff --git a/tests/select.test b/tests/select.test new file mode 100644 index 0000000..82db030 --- /dev/null +++ b/tests/select.test @@ -0,0 +1,987 @@ +# This file is a Tcl script to test out Tk's selection management code, +# especially the "selection" command. It is organized in the standard +# fashion for Tcl tests. +# +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) select.test 1.17 96/12/09 17:25:48 + +# +# Note: Multiple display selection handling will only be tested if the +# environment variable TK_ALT_DISPLAY is set to an alternate display. +# + +if {[string compare test [info procs test]] == 1} { + source defs +} + +eval destroy [winfo child .] + +global longValue selValue selInfo + +set selValue {} +set selInfo {} + +proc handler {type offset count} { + global selValue selInfo + lappend selInfo $type $offset $count + set numBytes [expr {[string length $selValue] - $offset}] + if {$numBytes <= 0} { + return "" + } + string range $selValue $offset [expr $numBytes+$offset] +} + +proc errIncrHandler {type offset count} { + global selValue selInfo pass + if {$offset == 4000} { + if {$pass == 0} { + # Just sizing the selection; don't do anything here. + set pass 1 + } else { + # Fetching the selection; wait long enough to cause a timeout. + after 6000 + } + } + lappend selInfo $type $offset $count + set numBytes [expr {[string length $selValue] - $offset}] + if {$numBytes <= 0} { + return "" + } + string range $selValue $offset [expr $numBytes+$offset] +} + +proc errHandler args { + error "selection handler aborted" +} + +proc badHandler {path type offset count} { + global selValue selInfo + selection handle -type $type $path {} + lappend selInfo $path $type $offset $count + set numBytes [expr {[string length $selValue] - $offset}] + if {$numBytes <= 0} { + return "" + } + string range $selValue $offset [expr $numBytes+$offset] +} +proc reallyBadHandler {path type offset count} { + global selValue selInfo pass + if {$offset == 4000} { + if {$pass == 0} { + set pass 1 + } else { + selection handle -type $type $path {} + } + } + lappend selInfo $path $type $offset $count + set numBytes [expr {[string length $selValue] - $offset}] + if {$numBytes <= 0} { + return "" + } + string range $selValue $offset [expr $numBytes+$offset] +} + +# Eliminate any existing selection on the screen. This is needed in case +# there is a selection in some other application, in order to prevent races +# from causing false errors in the tests below. + +selection clear . +after 1500 + +# common setup code +proc setup {{path .f1} {display {}}} { + catch {destroy $path} + if {$display == {}} { + frame $path + } else { + toplevel $path -screen $display + wm geom $path +0+0 + } + selection own $path +} + +# set up a very large buffer to test INCR retrievals +set longValue "" +foreach i {a b c d e f g j h i j k l m o p q r s t u v w x y z} { + set j $i.1$i.2$i.3$i.4$i.5$i.6$i.7$i.8$i.9$i.10$i.11$i.12$i.13$i.14 + append longValue A$j B$j C$j D$j E$j F$j G$j H$j I$j K$j L$j M$j N$j +} + +# Now we start the main body of the test code + +test select-1.1 {Tk_CreateSelHandler procedure} { + setup + lsort [selection get TARGETS] +} {MULTIPLE TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW} +test select-1.2 {Tk_CreateSelHandler procedure} { + setup + selection handle .f1 {handler TEST} TEST + lsort [selection get TARGETS] +} {MULTIPLE TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW} +test select-1.3 {Tk_CreateSelHandler procedure} { + global selValue selInfo + setup + selection handle .f1 {handler TEST} TEST + set selValue "Test value" + set selInfo "" + list [selection get TEST] $selInfo +} {{Test value} {TEST 0 4000}} +test select-1.4 {Tk_CreateSelHandler procedure} { + setup + selection handle .f1 {handler TEST} TEST + selection handle .f1 {handler STRING} + lsort [selection get TARGETS] +} {MULTIPLE STRING TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW} +test select-1.5 {Tk_CreateSelHandler procedure} { + global selValue selInfo + setup + selection handle .f1 {handler TEST} TEST + selection handle .f1 {handler STRING} + set selValue "" + set selInfo "" + list [selection get] $selInfo +} {{} {STRING 0 4000}} +test select-1.6 {Tk_CreateSelHandler procedure} { + global selValue selInfo + setup + selection handle .f1 {handler TEST} TEST + selection handle .f1 {handler STRING} + set selValue "" + set selInfo "" + selection get + selection get -type TEST + selection handle .f1 {handler TEST2} TEST + selection get -type TEST + list [set selInfo] [lsort [selection get TARGETS]] +} {{STRING 0 4000 TEST 0 4000 TEST2 0 4000} {MULTIPLE STRING TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW}} +test select-1.7 {Tk_CreateSelHandler procedure} { + setup + selection own -selection CLIPBOARD .f1 + selection handle -selection CLIPBOARD .f1 {handler TEST} TEST + selection handle -selection PRIMARY .f1 {handler TEST2} STRING + list [lsort [selection get -selection PRIMARY TARGETS]] \ + [lsort [selection get -selection CLIPBOARD TARGETS]] +} {{MULTIPLE STRING TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW} {MULTIPLE TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW}} +test select-1.8 {Tk_CreateSelHandler procedure} { + setup + selection handle -format INTEGER -type TEST .f1 {handler TEST} + lsort [selection get TARGETS] +} {MULTIPLE TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW} + +############################################################################## + +test select-2.1 {Tk_DeleteSelHandler procedure} { + setup + selection handle .f1 {handler STRING} + selection handle -type TEST .f1 {handler TEST} + selection handle -type USER .f1 {handler USER} + set result [list [lsort [selection get TARGETS]]] + selection handle -type TEST .f1 {} + lappend result [lsort [selection get TARGETS]] +} {{MULTIPLE STRING TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW USER} {MULTIPLE STRING TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW USER}} +test select-2.2 {Tk_DeleteSelHandler procedure} { + setup + selection handle .f1 {handler STRING} + selection handle -type TEST .f1 {handler TEST} + selection handle -type USER .f1 {handler USER} + set result [list [lsort [selection get TARGETS]]] + selection handle -type USER .f1 {} + lappend result [lsort [selection get TARGETS]] +} {{MULTIPLE STRING TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW USER} {MULTIPLE STRING TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW}} +test select-2.3 {Tk_DeleteSelHandler procedure} { + setup + selection own -selection CLIPBOARD .f1 + selection handle -selection PRIMARY .f1 {handler STRING} + selection handle -selection CLIPBOARD .f1 {handler STRING} + selection handle -selection CLIPBOARD .f1 {} + list [lsort [selection get TARGETS]] \ + [lsort [selection get -selection CLIPBOARD TARGETS]] +} {{MULTIPLE STRING TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW} {MULTIPLE TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW}} +test select-2.4 {Tk_DeleteSelHandler procedure} { + setup + selection handle .f1 {handler STRING} + list [selection handle .f1 {}] [selection handle .f1 {}] +} {{} {}} + +############################################################################## + +test select-3.1 {Tk_OwnSelection procedure} { + setup + selection own +} {.f1} +test select-3.2 {Tk_OwnSelection procedure} { + setup .f1 + set result [selection own] + setup .f2 + lappend result [selection own] +} {.f1 .f2} +test select-3.3 {Tk_OwnSelection procedure} { + setup .f1 + setup .f2 + selection own -selection CLIPBOARD .f1 + list [selection own] [selection own -selection CLIPBOARD] +} {.f2 .f1} +test select-3.4 {Tk_OwnSelection procedure} { + global lostSel + setup + set lostSel {owned} + selection own -command { set lostSel {lost} } .f1 + selection clear .f1 + set lostSel +} {lost} +test select-3.5 {Tk_OwnSelection procedure} { + global lostSel + setup .f1 + setup .f2 + set lostSel {owned} + selection own -command { set lostSel {lost1} } .f1 + selection own -command { set lostSel {lost2} } .f2 + list $lostSel [selection own] +} {lost1 .f2} +test select-3.6 {Tk_OwnSelection procedure} { + global lostSel + setup + set lostSel {owned} + selection own -command { set lostSel {lost1} } .f1 + selection own -command { set lostSel {lost2} } .f1 + set result $lostSel + selection clear .f1 + lappend result $lostSel +} {owned lost2} +test select-3.7 {Tk_OwnSelection procedure} {unixOnly} { + global lostSel + setup + setupbg + set lostSel {owned} + selection own -command { set lostSel {lost1} } .f1 + update + set result {} + lappend result [dobg { selection own . }] + lappend result [dobg {selection own}] + update + cleanupbg + lappend result $lostSel +} {{} . lost1} +# check reentrancy on selection replacement +test select-3.8 {Tk_OwnSelection procedure} { + setup + selection own -selection CLIPBOARD -command { destroy .f1 } .f1 + selection own -selection CLIPBOARD . +} {} +test select-3.9 {Tk_OwnSelection procedure} { + setup .f2 + setup .f1 + selection own -selection CLIPBOARD -command { destroy .f2 } .f1 + selection own -selection CLIPBOARD .f2 +} {} + +# multiple display tests +if {[info exists env(TK_ALT_DISPLAY)]} { + + test select-3.10 {Tk_OwnSelection procedure} { + setup .f1 + setup .f2 $env(TK_ALT_DISPLAY) + list [selection own -displayof .f1] [selection own -displayof .f2] + } {.f1 .f2} + test select-3.11 {Tk_OwnSelection procedure} { + setup .f1 + setup .f2 $env(TK_ALT_DISPLAY) + setupbg + update + set result "" + lappend result [dobg "toplevel .t -screen $env(TK_ALT_DISPLAY); wm geom .t +0+0; selection own .t; update"] + lappend result [selection own -displayof .f1] \ + [selection own -displayof .f2] + cleanupbg + set result + } {{} .f1 {}} + +} +############################################################################## + +test select-4.1 {Tk_ClearSelection procedure} { + setup + set result [selection own] + selection clear .f1 + lappend result [selection own] +} {.f1 {}} +test select-4.2 {Tk_ClearSelection procedure} { + setup + selection own -selection CLIPBOARD .f1 + selection clear .f1 + selection own -selection CLIPBOARD +} {.f1} +test select-4.3 {Tk_ClearSelection procedure} { + setup + list [selection clear .f1] [selection clear .f1] +} {{} {}} +test select-4.4 {Tk_ClearSelection procedure} {unixOnly} { + global lostSel + setup + setupbg + set lostSel {owned} + selection own -command { set lostSel {lost1} } .f1 + update + set result {} + lappend result [dobg {selection clear; update}] + update + cleanupbg + lappend result [selection own] +} {{} {}} + +# multiple display tests +if {[info exists env(TK_ALT_DISPLAY)]} { + test select-4.5 {Tk_ClearSelection procedure} { + global lostSel lostSel2 + setup .f1 + setup .f2 $env(TK_ALT_DISPLAY) + set lostSel {owned} + set lostSel2 {owned2} + selection own -command { set lostSel {lost1} } .f1 + selection own -command { set lostSel2 {lost2} } .f2 + update + selection clear -displayof .f2 + update + list $lostSel $lostSel2 + } {owned lost2} + test select-4.6 {Tk_ClearSelection procedure} {unixOnly} { + setup .f1 + setup .f2 $env(TK_ALT_DISPLAY) + setupbg + set lostSel {owned} + set lostSel2 {owned2} + selection own -command { set lostSel {lost1} } .f1 + selection own -command { set lostSel2 {lost2} } .f2 + update + set result "" + lappend result [dobg "toplevel .t -screen $env(TK_ALT_DISPLAY); wm geom .t +0+0; selection own .t; update"] + lappend result [selection own -displayof .f1] \ + [selection own -displayof .f2] $lostSel $lostSel2 + cleanupbg + set result + } {{} .f1 {} owned lost2} + +} +############################################################################## + +test select-5.1 {Tk_GetSelection procedure} { + setup + list [catch {selection get TEST} msg] $msg +} {1 {PRIMARY selection doesn't exist or form "TEST" not defined}} +test select-5.2 {Tk_GetSelection procedure} { + setup + selection get TK_WINDOW +} {.f1} +test select-5.3 {Tk_GetSelection procedure} { + setup + selection handle -selection PRIMARY .f1 {handler TEST} TEST + set selValue "Test value" + set selInfo "" + list [selection get TEST] $selInfo +} {{Test value} {TEST 0 4000}} +test select-5.4 {Tk_GetSelection procedure} { + setup + selection handle .f1 ERROR errHandler + list [catch {selection get ERROR} msg] $msg +} {1 {PRIMARY selection doesn't exist or form "ERROR" not defined}} +test select-5.5 {Tk_GetSelection procedure} { + setup + set selValue $longValue + set selInfo "" + selection handle .f1 {handler STRING} + list [selection get] $selInfo +} "$longValue {STRING 0 4000 STRING 4000 4000 STRING 8000 4000 STRING 12000 4000 STRING 16000 4000}" +test select-5.6 {Tk_GetSelection procedure} { + proc weirdHandler {type offset count} { + selection handle .f1 {} + handler $type $offset $count + } + setup + set selValue $longValue + set selInfo "" + selection handle .f1 {weirdHandler STRING} + list [catch {selection get} msg] $msg +} {1 {PRIMARY selection doesn't exist or form "STRING" not defined}} +test select-5.7 {Tk_GetSelection procedure} { + proc weirdHandler {type offset count} { + destroy .f1 + handler $type $offset $count + } + setup + set selValue "Test Value" + set selInfo "" + selection handle .f1 {weirdHandler STRING} + list [catch {selection get} msg] $msg +} {1 {PRIMARY selection doesn't exist or form "STRING" not defined}} +test select-5.8 {Tk_GetSelection procedure} { + proc weirdHandler {type offset count} { + selection clear + handler $type $offset $count + } + setup + set selValue $longValue + set selInfo "" + selection handle .f1 {weirdHandler STRING} + list [selection get] $selInfo [catch {selection get} msg] $msg +} "$longValue {STRING 0 4000 STRING 4000 4000 STRING 8000 4000 STRING 12000 4000 STRING 16000 4000} 1 {PRIMARY selection doesn't exist or form \"STRING\" not defined}" +test select-5.9 {Tk_GetSelection procedure} {unixOnly} { + setup + setupbg + selection handle -selection PRIMARY .f1 {handler TEST} TEST + update + set selValue "Test value" + set selInfo "" + set result "" + lappend result [dobg {selection get TEST}] + cleanupbg + lappend result $selInfo +} {{Test value} {TEST 0 4000}} +test select-5.10 {Tk_GetSelection procedure} {unixOnly} { + setup + setupbg + selection handle -selection PRIMARY .f1 {handler TEST} TEST + update + set selValue "Test value" + set selInfo "" + selection own .f1 + set result "" + fileevent $fd readable {} + puts $fd {catch {selection get TEST} msg; update; puts $msg; flush stdout} + flush $fd + lappend result [gets $fd] + cleanupbg + lappend result $selInfo +} {{selection owner didn't respond} {}} + +# multiple display tests +if {[info exists env(TK_ALT_DISPLAY)]} { + test select-5.11 {Tk_GetSelection procedure} { + setup .f1 + setup .f2 $env(TK_ALT_DISPLAY) + selection handle -selection PRIMARY .f1 {handler TEST} TEST + selection handle -selection PRIMARY .f2 {handler TEST2} TEST + set selValue "Test value" + set selInfo "" + set result [list [selection get TEST] $selInfo] + set selValue "Test value2" + set selInfo "" + lappend result [selection get -displayof .f2 TEST] $selInfo + } {{Test value} {TEST 0 4000} {Test value2} {TEST2 0 4000}} + test select-5.12 {Tk_GetSelection procedure} { + global lostSel lostSel2 + setup .f1 + setup .f2 $env(TK_ALT_DISPLAY) + selection handle -selection PRIMARY .f1 {handler TEST} TEST + selection handle -selection PRIMARY .f2 {} TEST + set selValue "Test value" + set selInfo "" + set result [list [catch {selection get TEST} msg] $msg $selInfo] + set selValue "Test value2" + set selInfo "" + lappend result [catch {selection get -displayof .f2 TEST} msg] $msg \ + $selInfo + } {0 {Test value} {TEST 0 4000} 1 {PRIMARY selection doesn't exist or form "TEST" not defined} {}} + test select-5.13 {Tk_GetSelection procedure} {unixOnly} { + setup .f1 + setup .f2 $env(TK_ALT_DISPLAY) + setupbg + selection handle -selection PRIMARY .f1 {handler TEST} TEST + selection own .f1 + selection handle -selection PRIMARY .f2 {handler TEST2} TEST + selection own .f2 + set selValue "Test value" + set selInfo "" + update + set result "" + lappend result [dobg "toplevel .t -screen $env(TK_ALT_DISPLAY); wm geom .t +0+0; selection get -displayof .t TEST"] + set selValue "Test value2" + lappend result [dobg "selection get TEST"] + cleanupbg + lappend result $selInfo + } {{Test value} {Test value2} {TEST2 0 4000 TEST 0 4000}} + test select-5.14 {Tk_GetSelection procedure} {unixOnly} { + setup .f1 + setup .f2 $env(TK_ALT_DISPLAY) + setupbg + selection handle -selection PRIMARY .f1 {handler TEST} TEST + selection own .f1 + selection handle -selection PRIMARY .f2 {} TEST + selection own .f2 + set selValue "Test value" + set selInfo "" + update + set result "" + lappend result [dobg "toplevel .t -screen $env(TK_ALT_DISPLAY); wm geom .t +0+0; selection get -displayof .t TEST"] + set selValue "Test value2" + lappend result [dobg "selection get TEST"] + cleanupbg + lappend result $selInfo + } {{PRIMARY selection doesn't exist or form "TEST" not defined} {Test value2} {TEST 0 4000}} + +} +############################################################################## + +test select-6.1 {Tk_SelectionCmd procedure} { + list [catch {selection} cmd] $cmd +} {1 {wrong # args: should be "selection option ?arg arg ...?"}} + +# selection clear +test select-6.2 {Tk_SelectionCmd procedure} { + list [catch {selection clear -selection} cmd] $cmd +} {1 {value for "-selection" missing}} +test select-6.3 {Tk_SelectionCmd procedure} { + setup + selection own . + set result [selection own] + selection clear -displayof .f1 + lappend result [selection own] +} {. {}} +test select-6.4 {Tk_SelectionCmd procedure} { + setup + selection own -selection CLIPBOARD .f1 + set result [list [selection own] [selection own -selection CLIPBOARD]] + selection clear -selection CLIPBOARD .f1 + lappend result [selection own] [selection own -selection CLIPBOARD] +} {.f1 .f1 .f1 {}} +test select-6.5 {Tk_SelectionCmd procedure} { + setup + selection own -selection CLIPBOARD . + set result [list [selection own] [selection own -selection CLIPBOARD]] + selection clear -selection CLIPBOARD -displayof .f1 + lappend result [selection own] [selection own -selection CLIPBOARD] +} {.f1 . .f1 {}} +test select-6.6 {Tk_SelectionCmd procedure} { + list [catch {selection clear -badopt foo} cmd] $cmd +} {1 {unknown option "-badopt"}} +test select-6.7 {Tk_SelectionCmd procedure} { + list [catch {selection clear -selectionfoo foo} cmd] $cmd +} {1 {unknown option "-selectionfoo"}} +test select-6.8 {Tk_SelectionCmd procedure} { + catch {destroy .f2} + list [catch {selection clear -displayof .f2} cmd] $cmd +} {1 {bad window path name ".f2"}} +test select-6.9 {Tk_SelectionCmd procedure} { + catch {destroy .f2} + list [catch {selection clear .f2} cmd] $cmd +} {1 {bad window path name ".f2"}} +test select-6.10 {Tk_SelectionCmd procedure} { + setup + set result [selection own -selection PRIMARY] + selection clear + lappend result [selection own -selection PRIMARY] +} {.f1 {}} +test select-6.11 {Tk_SelectionCmd procedure} { + setup + selection own -selection CLIPBOARD .f1 + set result [selection own -selection CLIPBOARD] + selection clear -selection CLIPBOARD + lappend result [selection own -selection CLIPBOARD] +} {.f1 {}} +test select-6.12 {Tk_SelectionCmd procedure} { + list [catch {selection clear foo bar} cmd] $cmd +} {1 {wrong # args: should be "selection clear ?options?"}} + +# selection get +test select-6.13 {Tk_SelectionCmd procedure} { + list [catch {selection get -selection} cmd] $cmd +} {1 {value for "-selection" missing}} +test select-6.14 {Tk_SelectionCmd procedure} { + global selValue selInfo + setup + selection handle .f1 {handler TEST} + set selValue "Test value" + set selInfo "" + list [selection get -displayof .f1] $selInfo +} {{Test value} {TEST 0 4000}} +test select-6.15 {Tk_SelectionCmd procedure} { + global selValue selInfo + setup + selection handle .f1 {handler STRING} + selection handle -selection CLIPBOARD .f1 {handler TEST} + selection own -selection CLIPBOARD .f1 + set selValue "Test value" + set selInfo "" + list [selection get -selection CLIPBOARD] $selInfo +} {{Test value} {TEST 0 4000}} +test select-6.16 {Tk_SelectionCmd procedure} { + global selValue selInfo + setup + selection handle -type TEST .f1 {handler TEST} + selection handle -type STRING .f1 {handler STRING} + set selValue "Test value" + set selInfo "" + list [selection get -type TEST] $selInfo +} {{Test value} {TEST 0 4000}} +test select-6.17 {Tk_SelectionCmd procedure} { + list [catch {selection get -badopt foo} cmd] $cmd +} {1 {unknown option "-badopt"}} +test select-6.18 {Tk_SelectionCmd procedure} { + list [catch {selection get -selectionfoo foo} cmd] $cmd +} {1 {unknown option "-selectionfoo"}} +test select-6.19 {Tk_SelectionCmd procedure} { + catch { destroy .f2 } + list [catch {selection get -displayof .f2} cmd] $cmd +} {1 {bad window path name ".f2"}} +test select-6.20 {Tk_SelectionCmd procedure} { + list [catch {selection get foo bar} cmd] $cmd +} {1 {wrong # args: should be "selection get ?options?"}} +test select-6.21 {Tk_SelectionCmd procedure} { + global selValue selInfo + setup + selection handle -type TEST .f1 {handler TEST} + selection handle -type STRING .f1 {handler STRING} + set selValue "Test value" + set selInfo "" + list [selection get TEST] $selInfo +} {{Test value} {TEST 0 4000}} + +# selection handle +# most of the handle section has been covered earlier +test select-6.22 {Tk_SelectionCmd procedure} { + list [catch {selection handle -selection} cmd] $cmd +} {1 {value for "-selection" missing}} +test select-6.23 {Tk_SelectionCmd procedure} { + global selValue selInfo + setup + set selValue "Test value" + set selInfo "" + list [selection handle -format INTEGER .f1 {handler TEST}] [selection get -displayof .f1] $selInfo +} {{} {Test value} {TEST 0 4000}} +test select-6.24 {Tk_SelectionCmd procedure} { + list [catch {selection handle -badopt foo} cmd] $cmd +} {1 {unknown option "-badopt"}} +test select-6.25 {Tk_SelectionCmd procedure} { + list [catch {selection handle -selectionfoo foo} cmd] $cmd +} {1 {unknown option "-selectionfoo"}} +test select-6.26 {Tk_SelectionCmd procedure} { + list [catch {selection handle} cmd] $cmd +} {1 {wrong # args: should be "selection handle ?options? window command"}} +test select-6.27 {Tk_SelectionCmd procedure} { + list [catch {selection handle .} cmd] $cmd +} {1 {wrong # args: should be "selection handle ?options? window command"}} +test select-6.28 {Tk_SelectionCmd procedure} { + list [catch {selection handle . foo bar baz blat} cmd] $cmd +} {1 {wrong # args: should be "selection handle ?options? window command"}} +test select-6.29 {Tk_SelectionCmd procedure} { + catch { destroy .f2 } + list [catch {selection handle .f2 dummy} cmd] $cmd +} {1 {bad window path name ".f2"}} + +# selection own +test select-6.30 {Tk_SelectionCmd procedure} { + list [catch {selection own -selection} cmd] $cmd +} {1 {value for "-selection" missing}} +test select-6.31 {Tk_SelectionCmd procedure} { + setup + selection own . + selection own -displayof .f1 +} {.} +test select-6.32 {Tk_SelectionCmd procedure} { + setup + selection own . + selection own -selection CLIPBOARD .f1 + list [selection own] [selection own -selection CLIPBOARD] +} {. .f1} +test select-6.33 {Tk_SelectionCmd procedure} { + global lostSel + setup + set lostSel owned + selection own -command { set lostSel lost } . + selection own -selection CLIPBOARD .f1 + set result $lostSel + selection own .f1 + lappend result $lostSel +} {owned lost} +test select-6.34 {Tk_SelectionCmd procedure} { + list [catch {selection own -badopt foo} cmd] $cmd +} {1 {unknown option "-badopt"}} +test select-6.35 {Tk_SelectionCmd procedure} { + list [catch {selection own -selectionfoo foo} cmd] $cmd +} {1 {unknown option "-selectionfoo"}} +test select-6.36 {Tk_SelectionCmd procedure} { + catch {destroy .f2} + list [catch {selection own -displayof .f2} cmd] $cmd +} {1 {bad window path name ".f2"}} +test select-6.37 {Tk_SelectionCmd procedure} { + catch {destroy .f2} + list [catch {selection own .f2} cmd] $cmd +} {1 {bad window path name ".f2"}} +test select-6.38 {Tk_SelectionCmd procedure} { + list [catch {selection own foo bar baz} cmd] $cmd +} {1 {wrong # args: should be "selection own ?options? ?window?"}} + +test select-6.39 {Tk_SelectionCmd procedure} { + list [catch {selection foo} cmd] $cmd +} {1 {bad option "foo": must be clear, get, handle, or own}} + +############################################################################## + + # This test is non-portable because some old X11/News servers ignore + # a selection request when the window doesn't exist, which causes a + # different error message. + + test select-7.1 {TkSelDeadWindow procedure} {nonPortable} { + setup + selection handle .f1 { handler TEST } + set result [selection own] + destroy .f1 + lappend result [selection own] [catch { selection get } msg] $msg + } {.f1 {} 1 {PRIMARY selection doesn't exist or form "STRING" not defined}} + +############################################################################## + +# Check reentrancy on losing selection + +test select-8.1 {TkSelEventProc procedure} {unixOnly} { + setup + setupbg + selection own -selection CLIPBOARD -command { destroy .f1 } .f1 + update + set result [dobg {selection own -selection CLIPBOARD .}] + cleanupbg + set result +} {} + +############################################################################## + +test select-9.1 {SelCvtToX and SelCvtFromX procedures} {unixOnly} { + global selValue selInfo + setup + setupbg + set selValue "1024" + set selInfo "" + selection handle -selection PRIMARY -format INTEGER -type TEST \ + .f1 {handler TEST} + update + set result "" + lappend result [dobg {selection get TEST}] + cleanupbg + lappend result $selInfo +} {0x400 {TEST 0 4000}} +test select-9.2 {SelCvtToX and SelCvtFromX procedures} {unixOnly} { + global selValue selInfo + setup + setupbg + set selValue "1024 0xffff 2048 -2 " + set selInfo "" + selection handle -selection PRIMARY -format INTEGER -type TEST \ + .f1 {handler TEST} + set result "" + lappend result [dobg {selection get TEST}] + cleanupbg + lappend result $selInfo +} {{0x400 0xffff 0x800 0xfffffffe} {TEST 0 4000}} +test select-9.3 {SelCvtToX and SelCvtFromX procedures} {unixOnly} { + global selValue selInfo + setup + setupbg + set selValue " " + set selInfo "" + selection handle -selection PRIMARY -format INTEGER -type TEST \ + .f1 {handler TEST} + set result "" + lappend result [dobg {selection get TEST}] + cleanupbg + lappend result $selInfo +} {{} {TEST 0 4000}} +test select-9.4 {SelCvtToX and SelCvtFromX procedures} {unixOnly} { + global selValue selInfo + setup + setupbg + set selValue "16 foobar 32" + set selInfo "" + selection handle -selection PRIMARY -format INTEGER -type TEST \ + .f1 {handler TEST} + set result "" + lappend result [dobg {selection get TEST}] + cleanupbg + lappend result $selInfo +} {{0x10 0x0 0x20} {TEST 0 4000}} + +############################################################################## + +# note, we are not testing MULTIPLE style selections + +# most control paths have been exercised above +test select-10.1 {ConvertSelection procedure, race with selection clear} {unixOnly} { + setup + setupbg + set selValue "Just a simple test" + set selInfo "" + selection handle .f1 {handler STRING} + update + puts $fd {puts "[catch {selection get} msg] $msg"; puts **DONE**; flush stdout} + flush $fd + after 200 + selection own . + set bgData {} + tkwait variable bgDone + cleanupbg + list $bgData $selInfo +} {{1 PRIMARY selection doesn't exist or form "STRING" not defined} {}} +test select-10.2 {ConvertSelection procedure} {unixOnly} { + setup + setupbg + set selValue [string range $longValue 0 3999] + set selInfo "" + selection handle .f1 {handler STRING} + set result "" + lappend result [dobg {selection get}] + cleanupbg + lappend result $selInfo +} [list [string range $longValue 0 3999] {STRING 0 4000 STRING 4000 4000 STRING 0 4000 STRING 4000 4000}] +test select-10.3 {ConvertSelection procedure} {unixOnly} { + setup + setupbg + selection handle .f1 ERROR errHandler + set result "" + lappend result [dobg {selection get ERROR}] + cleanupbg + set result +} {{PRIMARY selection doesn't exist or form "ERROR" not defined}} +# testing timers +test select-10.4 {ConvertSelection procedure} {unixOnly} { + setup + setupbg + set selValue $longValue + set selInfo "" + selection handle .f1 {errIncrHandler STRING} + set result "" + set pass 0 + lappend result [dobg {selection get}] + cleanupbg + lappend result $selInfo +} {{selection owner didn't respond} {STRING 0 4000 STRING 4000 4000 STRING 8000 4000 STRING 12000 4000 STRING 16000 4000 STRING 0 4000 STRING 4000 4000}} +test select-10.5 {ConvertSelection procedure, reentrancy issues} {unixOnly} { + setup + setupbg + set selValue "Test value" + set selInfo "" + selection handle -type TEST .f1 { handler TEST } + selection handle -type STRING .f1 { badHandler .f1 STRING } + set result "" + lappend result [dobg {selection get}] + cleanupbg + lappend result $selInfo +} {{PRIMARY selection doesn't exist or form "STRING" not defined} {.f1 STRING 0 4000}} +test select-10.6 {ConvertSelection procedure, reentrancy issues} {unixOnly} { + proc weirdHandler {type offset count} { + destroy .f1 + handler $type $offset $count + } + setup + setupbg + set selValue $longValue + set selInfo "" + selection handle .f1 {weirdHandler STRING} + set result "" + lappend result [dobg {selection get}] + cleanupbg + lappend result $selInfo +} {{PRIMARY selection doesn't exist or form "STRING" not defined} {STRING 0 4000}} + +############################################################################## + +# testing reentrancy +test select-11.1 {TkSelPropProc procedure} {unixOnly} { + setup + setupbg + set selValue $longValue + set selInfo "" + selection handle -type TEST .f1 { handler TEST } + selection handle -type STRING .f1 { reallyBadHandler .f1 STRING } + set result "" + set pass 0 + lappend result [dobg {selection get}] + cleanupbg + lappend result $selInfo +} {{selection owner didn't respond} {.f1 STRING 0 4000 .f1 STRING 4000 4000 .f1 STRING 8000 4000 .f1 STRING 12000 4000 .f1 STRING 16000 4000 .f1 STRING 0 4000 .f1 STRING 4000 4000}} + +############################################################################## + +# Note, this assumes we are using CurrentTtime +test select-12.1 {DefaultSelection procedure} {unixOnly} { + setup + set result [selection get -type TIMESTAMP] + setupbg + lappend result [dobg {selection get -type TIMESTAMP}] + cleanupbg + set result +} {0x0 0x0} +test select-12.2 {DefaultSelection procedure} {unixOnly} { + setup + set result [lsort [list [selection get -type TARGETS]]] + setupbg + lappend result [dobg {lsort [selection get -type TARGETS]}] + cleanupbg + set result +} {{MULTIPLE TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW} {MULTIPLE TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW}} +test select-12.3 {DefaultSelection procedure} {unixOnly} { + setup + selection handle .f1 {handler TEST} TEST + set result [list [lsort [selection get -type TARGETS]]] + setupbg + lappend result [dobg {lsort [selection get -type TARGETS]}] + cleanupbg + set result +} {{MULTIPLE TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW} {MULTIPLE TARGETS TEST TIMESTAMP TK_APPLICATION TK_WINDOW}} +test select-12.4 {DefaultSelection procedure} {unixOnly} { + setup + set result "" + lappend result [selection get -type TK_APPLICATION] + setupbg + lappend result [dobg {selection get -type TK_APPLICATION}] + cleanupbg + set result +} [list [winfo name .] [winfo name .]] +test select-12.5 {DefaultSelection procedure} {unixOnly} { + setup + set result [selection get -type TK_WINDOW] + setupbg + lappend result [dobg {selection get -type TK_WINDOW}] + cleanupbg + set result +} {.f1 .f1} +test select-12.6 {DefaultSelection procedure} { + global selValue selInfo + setup + selection handle .f1 {handler TARGETS.f1} TARGETS + set selValue "Targets value" + set selInfo "" + set result [list [selection get TARGETS] $selInfo] + selection handle .f1 {} TARGETS + lappend result [selection get TARGETS] +} {{Targets value} {TARGETS.f1 0 4000} {MULTIPLE TARGETS TIMESTAMP TK_APPLICATION TK_WINDOW}} + +test select-13.1 {SelectionSize procedure, handler deleted} {unixOnly} { + proc badHandler {path type offset count} { + global selValue selInfo abortCount + incr abortCount -1 + if {$abortCount == 0} { + selection handle -type $type $path {} + } + lappend selInfo $path $type $offset $count + set numBytes [expr {[string length $selValue] - $offset}] + if {$numBytes <= 0} { + return "" + } + string range $selValue $offset [expr $numBytes+$offset] + } + setup + setupbg + set selValue $longValue + set selInfo "" + selection handle .f1 {badHandler .f1 STRING} + set result "" + set abortCount 2 + lappend result [dobg {selection get}] + cleanupbg + lappend result $selInfo +} {{PRIMARY selection doesn't exist or form "STRING" not defined} {.f1 STRING 0 4000 .f1 STRING 4000 4000}} + +catch {rename weirdHandler {}} +concat diff --git a/tests/send.test b/tests/send.test new file mode 100644 index 0000000..7addb73 --- /dev/null +++ b/tests/send.test @@ -0,0 +1,656 @@ +# This file is a Tcl script to test out the "send" command and the +# other procedures in the file tkSend.c. It is organized in the +# standard fashion for Tcl tests. +# +# Copyright (c) 1994 Sun Microsystems, Inc. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) send.test 1.26 96/12/09 17:26:42 + +if {$tcl_platform(platform) == "macintosh"} { + puts "send is not available on the Mac - skipping tests" + return +} +if {$tcl_platform(platform) == "window"} { + puts "send is not available under Windows - skipping tests" + return +} +if {[auto_execok xhost] == ""} { + puts "xhost application isn't available - skipping tests" + return +} + +if {[info procs test] != "test"} { + source defs +} +if {[info commands testsend] == "testsend"} { + set gotTestCmds 1 +} else { + set gotTestCmds 0 +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +# If send is disabled because of inadequate security, don't run any +# of these tests at all. + +setupbg +set app [dobg {tk appname}] +if {[catch {send $app set a 0} msg] == 1} { + if [string match "X server insecure *" $msg] { + puts -nonewline "Your X server is insecure, so \"send\" can't be used;" + puts " skipping \"send\" tests." + cleanupbg + return + } +} +cleanupbg + +# Compute a script that will load Tk into a child interpreter. + +foreach pkg [info loaded] { + if {[lindex $pkg 1] == "Tk"} { + set loadTk "load $pkg" + break + } +} + +# Procedure to create a new application with a given name and class. + +proc newApp {screen name class} { + global loadTk + interp create $name + $name eval [list set argv [list -display $screen -name $name -class $class]] + eval $loadTk $name +} + +set name [tk appname] +if $gotTestCmds { + set registry [testsend prop root InterpRegistry] + set commId [lindex [testsend prop root InterpRegistry] 0] +} +tk appname tktest +catch {send t_s_1 destroy .} +catch {send t_s_2 destroy .} + +if $gotTestCmds { + test send-1.1 {RegOpen procedure, bogus property} { + testsend bogus + set result [winfo interps] + tk appname tktest + list $result [winfo interps] + } {{} tktest} + test send-1.2 {RegOpen procedure, bogus property} { + testsend prop root InterpRegistry {} + set result [winfo interps] + tk appname tktest + list $result [winfo interps] + } {{} tktest} + test send-1.3 {RegOpen procedure, bogus property} { + testsend prop root InterpRegistry abcdefg + tk appname tktest + set x [testsend prop root InterpRegistry] + string range $x [string first " " $x] end + } " tktest\nabcdefg\n" + + frame .f -width 1 -height 1 + set id [string range [winfo id .f] 2 end] + test send-2.1 {RegFindName procedure} { + testsend prop root InterpRegistry {} + list [catch {send foo bar} msg] $msg + } {1 {no application named "foo"}} + test send-2.2 {RegFindName procedure} { + testsend prop root InterpRegistry " abc\n def\nghi\n\n$id foo\n" + tk appname foo + } {foo #2} + test send-2.3 {RegFindName procedure} { + testsend prop root InterpRegistry "gyz foo\n" + tk appname foo + } {foo} + test send-2.4 {RegFindName procedure} { + testsend prop root InterpRegistry "${id}z foo\n" + tk appname foo + } {foo} + + test send-3.1 {RegDeleteName procedure} { + tk appname tktest + testsend prop root InterpRegistry "012345 gorp\n12345 foo\n12345 tktest" + tk appname x + set x [testsend prop root InterpRegistry] + string range $x [string first " " $x] end + } " x\n012345 gorp\n12345 foo\n" + test send-3.2 {RegDeleteName procedure} { + tk appname tktest + testsend prop root InterpRegistry "012345 gorp\n12345 tktest\n23456 tktest" + tk appname x + set x [testsend prop root InterpRegistry] + string range $x [string first " " $x] end + } " x\n012345 gorp\n23456 tktest\n" + test send-3.3 {RegDeleteName procedure} { + tk appname tktest + testsend prop root InterpRegistry "012345 tktest\n12345 bar\n23456 tktest" + tk appname x + set x [testsend prop root InterpRegistry] + string range $x [string first " " $x] end + } " x\n12345 bar\n23456 tktest\n" + test send-3.4 {RegDeleteName procedure} { + tk appname tktest + testsend prop root InterpRegistry "foo" + tk appname x + set x [testsend prop root InterpRegistry] + string range $x [string first " " $x] end + } " x\nfoo\n" + test send-3.5 {RegDeleteName procedure} { + tk appname tktest + testsend prop root InterpRegistry "" + tk appname x + set x [testsend prop root InterpRegistry] + string range $x [string first " " $x] end + } " x\n" + + test send-4.1 {RegAddName procedure} { + testsend prop root InterpRegistry "" + tk appname bar + testsend prop root InterpRegistry + } "$commId bar\n" + test send-4.2 {RegAddName procedure} { + testsend prop root InterpRegistry "abc def" + tk appname bar + tk appname foo + testsend prop root InterpRegistry + } "$commId foo\nabc def\n" + + # Previous checks should already cover the Regclose procedure. + + test send-5.1 {ValidateName procedure} { + testsend prop root InterpRegistry "123 abc\n" + winfo interps + } {} + test send-5.2 {ValidateName procedure} { + testsend prop root InterpRegistry "$id Hi there" + winfo interps + } {{Hi there}} + test send-5.3 {ValidateName procedure} { + testsend prop root InterpRegistry "$id Bogus" + list [catch {send Bogus set a 44} msg] $msg + } {1 {target application died or uses a Tk version before 4.0}} + test send-5.4 {ValidateName procedure} { + tk appname test + testsend prop root InterpRegistry "$commId Bogus\n$commId test\n" + winfo interps + } {test} +} + +winfo interps +tk appname tktest +update +setupbg +set x [split [exec xhost] \n] +foreach i [lrange $x 1 end] { + exec xhost - $i +} +test send-6.1 {ServerSecure procedure} {nonPortable} { + set a 44 + list [dobg [list send [tk appname] set a 55]] $a +} {55 55} +test send-6.2 {ServerSecure procedure} {nonPortable} { + set a 22 + exec xhost [exec hostname] + list [catch {dobg [list send [tk appname] set a 33]} msg] $a $msg +} {0 22 {X server insecure (must use xauth-style authorization); command ignored}} +test send-6.3 {ServerSecure procedure} {nonPortable} { + set a abc + exec xhost - [exec hostname] + list [dobg [list send [tk appname] set a new]] $a +} {new new} +cleanupbg + +if $gotTestCmds { + test send-7.1 {Tk_SetAppName procedure} { + testsend prop root InterpRegistry "" + tk appname newName + list [tk appname oldName] [testsend prop root InterpRegistry] + } "oldName {$commId oldName\n}" + test send-7.2 {Tk_SetAppName procedure, name not in use} { + testsend prop root InterpRegistry "" + list [tk appname gorp] [testsend prop root InterpRegistry] + } "gorp {$commId gorp\n}" + test send-7.3 {Tk_SetAppName procedure, name in use by us} { + tk appname name1 + testsend prop root InterpRegistry "$commId name2\n" + list [tk appname name2] [testsend prop root InterpRegistry] + } "name2 {$commId name2\n}" + test send-7.4 {Tk_SetAppName procedure, name in use} { + tk appname name1 + testsend prop root InterpRegistry "$id foo\n$id foo #2\n$id foo #3\n" + list [tk appname foo] [testsend prop root InterpRegistry] + } "{foo #4} {$commId foo #4\n$id foo\n$id foo #2\n$id foo #3\n}" +} + +test send-8.1 {Tk_SendCmd procedure, options} { + setupbg + set app [dobg {tk appname}] + set a 66 + send -async $app [list send [tk appname] set a 77] + set result $a + after 200 set x 40 + tkwait variable x + cleanupbg + lappend result $a +} {66 77} +if [info exists env(TK_ALT_DISPLAY)] { + test send-8.2 {Tk_SendCmd procedure, options} { + setupbg -display $env(TK_ALT_DISPLAY) + tk appname xyzgorp + set a homeDisplay + set result [dobg " + toplevel .t -screen [winfo screen .] + wm geometry .t +0+0 + set a altDisplay + tk appname xyzgorp + list \[send xyzgorp set a\] \[send -displayof .t xyzgorp set a\] + "] + cleanupbg + set result + } {altDisplay homeDisplay} +} +test send-8.3 {Tk_SendCmd procedure, options} { + list [catch {send -- -async foo bar baz} msg] $msg +} {1 {no application named "-async"}} +test send-8.4 {Tk_SendCmd procedure, options} { + list [catch {send -gorp foo bar baz} msg] $msg +} {1 {bad option "-gorp": must be -async, -displayof, or --}} +test send-8.5 {Tk_SendCmd procedure, options} { + list [catch {send -async foo} msg] $msg +} {1 {wrong # args: should be "send ?options? interpName arg ?arg ...?"}} +test send-8.6 {Tk_SendCmd procedure, options} { + list [catch {send foo} msg] $msg +} {1 {wrong # args: should be "send ?options? interpName arg ?arg ...?"}} +test send-8.7 {Tk_SendCmd procedure, local execution} { + set a initial + send [tk appname] {set a new} + set a +} {new} +test send-8.8 {Tk_SendCmd procedure, local execution} { + set a initial + send [tk appname] set a new + set a +} {new} +test send-8.9 {Tk_SendCmd procedure, local execution} { + set a initial + string tolower [list [catch {send [tk appname] open bad_file} msg] \ + $msg $errorInfo $errorCode] +} {1 {couldn't open "bad_file": no such file or directory} {couldn't open "bad_file": no such file or directory + while executing +"open bad_file" + invoked from within +"send [tk appname] open bad_file"} {posix enoent {no such file or directory}}} +test send-8.10 {Tk_SendCmd procedure, no such interpreter} { + list [catch {send bogus_name bogus_command} msg] $msg +} {1 {no application named "bogus_name"}} +if $gotTestCmds { + newApp "" t_s_1 Test + t_s_1 eval wm withdraw . + test send-8.11 {Tk_SendCmd procedure, local execution, different interp} { + set a us + send t_s_1 set a them + list $a [send t_s_1 set a] + } {us them} + test send-8.12 {Tk_SendCmd procedure, local execution, different interp} { + set a us + send t_s_1 {set a them} + list $a [send t_s_1 {set a}] + } {us them} + test send-8.13 {Tk_SendCmd procedure, local execution, different interp} { + set a us + send t_s_1 {set a them} + list $a [send t_s_1 {set a}] + } {us them} + test send-8.14 {Tk_SendCmd procedure, local interp killed by send} { + newApp "" t_s_2 Test + list [catch {send t_s_2 {destroy .; concat result}} msg] $msg + } {0 result} + interp delete t_s_2 + test send-8.15 {Tk_SendCmd procedure, local interp, error info} { + catch {error foo} + list [catch {send t_s_1 {if 1 {open bogus_file_name}}} msg] $msg $errorInfo $errorCode + } {1 {couldn't open "bogus_file_name": no such file or directory} {couldn't open "bogus_file_name": no such file or directory + while executing +"open bogus_file_name" + invoked from within +"send t_s_1 {if 1 {open bogus_file_name}}"} {POSIX ENOENT {no such file or directory}}} + test send-8.16 {Tk_SendCmd procedure, bogusCommWindow} { + testsend prop root InterpRegistry "10234 bogus\n" + set result [list [catch {send bogus bogus command} msg] $msg] + winfo interps + tk appname tktest + set result + } {1 {no application named "bogus"}} + interp delete t_s_1 +} +test send-8.17 {Tk_SendCmd procedure, deferring events} {nonPortable} { + # Non-portable because some window managers ignore "raise" + # requests so can't guarantee that new app's window won't + # obscure .f, thereby masking the Expose event. + + setupbg + set app [dobg {tk appname}] + raise . ; # Don't want new app obscuring .f + catch {destroy .f} + frame .f + place .f -x 0 -y 0 + bind .f <Expose> {set a exposed} + set a {no event yet} + set result "" + lappend result [send $app send [list [tk appname]] set a] + lappend result $a + update + cleanupbg + lappend result $a +} {{no event yet} {no event yet} exposed} +test send-8.18 {Tk_SendCmd procedure, error in remote app} { + setupbg + set app [dobg {tk appname}] + set result [string tolower [list [catch {send $app open bad_name} msg] \ + $msg $errorInfo $errorCode]] + cleanupbg + set result +} {1 {couldn't open "bad_name": no such file or directory} {couldn't open "bad_name": no such file or directory + while executing +"open bad_name" + invoked from within +"send $app open bad_name"} {posix enoent {no such file or directory}}} +test send-8.19 {Tk_SendCmd, using modal timeouts} { + setupbg + set app [dobg {tk appname}] + set x no + set result "" + after 0 {set x yes} + lappend result [send $app {concat x y z}] + lappend result $x + update + cleanupbg + lappend result $x +} {{x y z} no yes} + +tk appname tktest +catch {destroy .f} +frame .f +set id [string range [winfo id .f] 2 end] +if $gotTestCmds { + test send-9.1 {Tk_GetInterpNames procedure} { + testsend prop root InterpRegistry \ + "$commId tktest\nfoo bar\n$commId tktest\n$id frame .f\n\n\n" + list [winfo interps] [testsend prop root InterpRegistry] + } "{tktest tktest {frame .f}} {$commId tktest\n$commId tktest\n$id frame .f +}" + test send-9.2 {Tk_GetInterpNames procedure} { + testsend prop root InterpRegistry \ + "$commId tktest\nfoobar\n$commId gorp\n" + list [winfo interps] [testsend prop root InterpRegistry] + } "tktest {$commId tktest\n}" + test send-9.3 {Tk_GetInterpNames procedure} { + testsend prop root InterpRegistry {} + list [winfo interps] [testsend prop root InterpRegistry] + } {{} {}} + + testsend prop root InterpRegistry "$commId tktest\n$id dummy\n" + test send-10.1 {SendEventProc procedure, bogus comm property} { + testsend prop comm Comm {abc def} + testsend prop comm Comm {} + update + } {} + test send-10.2 {SendEventProc procedure, simultaneous messages} { + testsend prop comm Comm \ + "c\n-n tktest\n-s set a 44\nc\n-n tktest\n-s set b 45\n" + set a null + set b xyzzy + update + list $a $b + } {44 45} + test send-10.3 {SendEventProc procedure, simultaneous messages} { + testsend prop comm Comm \ + "c\n-n tktest\n-s set a newA\nr\n-s [testsend serial]\n-r 12345\nc\n-n tktest\n-s set b newB\n" + set a null + set b xyzzy + set x [send dummy bogus] + list $x $a $b + } {12345 newA newB} + test send-10.4 {SendEventProc procedure, leading nulls, bogus commands} { + testsend prop comm Comm \ + "\n\nx\n-bogus\n\nc\n-n tktest\n-s set a 44\n" + set a null + update + set a + } {44} + test send-10.5 {SendEventProc procedure, extraneous command options} { + testsend prop comm Comm \ + "c\n-n tktest\n-x miscellanous\n-y who knows?\n-s set a new\n" + set a null + update + set a + } {new} + test send-10.6 {SendEventProc procedure, unknown interpreter} { + testsend prop [winfo id .f] Comm {} + testsend prop comm Comm \ + "c\n-n unknown\n-r $id 44\n-s set a new\n" + set a null + update + list [testsend prop [winfo id .f] Comm] $a + } "{\nr\n-s 44\n-r receiver never heard of interpreter \"unknown\"\n-c 1\n} null" + test send-10.7 {SendEventProc procedure, error in script} { + testsend prop [winfo id .f] Comm {} + testsend prop comm Comm \ + "c\n-n tktest\n-r $id 62\n-s foreach i {1 2 3} {error {test error} {Initial errorInfo} {test code}}\n" + update + testsend prop [winfo id .f] Comm + } { +r +-s 62 +-r test error +-i Initial errorInfo + ("foreach" body line 1) + invoked from within +"foreach i {1 2 3} {error {test error} {Initial errorInfo} {test code}}" +-e test code +-c 1 +} + test send-10.8 {SendEventProc procedure, exceptional return} { + testsend prop [winfo id .f] Comm {} + testsend prop comm Comm \ + "c\n-n tktest\n-r $id 62\n-s break\n" + update + testsend prop [winfo id .f] Comm + } { +r +-s 62 +-r +-c 3 +} + test send-10.9 {SendEventProc procedure, empty return} { + testsend prop [winfo id .f] Comm {} + testsend prop comm Comm \ + "c\n-n tktest\n-r $id 62\n-s concat\n" + update + testsend prop [winfo id .f] Comm + } { +r +-s 62 +-r +} + test send-10.10 {SendEventProc procedure, asynchronous calls} { + testsend prop [winfo id .f] Comm {} + testsend prop comm Comm \ + "c\n-n tktest\n-s foreach i {1 2 3} {error {test error} {Initial errorInfo} {test code}}\n" + update + testsend prop [winfo id .f] Comm + } {} + test send-10.11 {SendEventProc procedure, exceptional return} { + testsend prop [winfo id .f] Comm {} + testsend prop comm Comm \ + "c\n-n tktest\n-s break\n" + update + testsend prop [winfo id .f] Comm + } {} + test send-10.12 {SendEventProc procedure, empty return} { + testsend prop [winfo id .f] Comm {} + testsend prop comm Comm \ + "c\n-n tktest\n-s concat\n" + update + testsend prop [winfo id .f] Comm + } {} + test send-10.13 {SendEventProc procedure, return processing} { + testsend prop comm Comm \ + "r\n-c 1\n-e test1\n-i test2\n-r test3\n-s [testsend serial]\n" + list [catch {send dummy foo} msg] $msg $errorInfo $errorCode + } {1 test3 {test2 + invoked from within +"send dummy foo"} test1} + test send-10.14 {SendEventProc procedure, extraneous return options} { + testsend prop comm Comm \ + "r\n-x test1\n-y test2\n-r result\n-s [testsend serial]\n" + list [catch {send dummy foo} msg] $msg + } {0 result} + test send-10.15 {SendEventProc procedure, serial number} { + testsend prop comm Comm \ + "r\n-r response\n" + list [catch {send dummy foo} msg] $msg + } {1 {target application died or uses a Tk version before 4.0}} + test send-10.16 {SendEventProc procedure, serial number} { + testsend prop comm Comm \ + "r\n-r response\n\n-s 0" + list [catch {send dummy foo} msg] $msg + } {1 {target application died or uses a Tk version before 4.0}} + test send-10.17 {SendEventProc procedure, errorCode and errorInfo} { + testsend prop comm Comm \ + "r\n-i test1\n-e test2\n-c 4\n-s [testsend serial]\n" + set errorCode oldErrorCode + set errorInfo oldErrorInfo + list [catch {send dummy foo} msg] $msg $errorInfo $errorCode + } {4 {} oldErrorInfo oldErrorCode} + test send-10.18 {SendEventProc procedure, send kills application} { + setupbg + dobg {tk appname t_s_3} + set x [list [catch {send t_s_3 destroy .} msg] $msg] + cleanupbg + set x + } {0 {}} + test send-10.19 {SendEventProc procedure, send exits} { + setupbg + dobg {tk appname t_s_3} + set x [list [catch {send t_s_3 exit} msg] $msg] + close $fd + set x + } {1 {target application died}} + + test send-11.1 {AppendPropCarefully and AppendErrorProc procedures} { + testsend prop root InterpRegistry "0x21447 dummy\n" + list [catch {send dummy foo} msg] $msg + } {1 {no application named "dummy"}} + test send-11.2 {AppendPropCarefully and AppendErrorProc procedures} { + testsend prop comm Comm "c\n-r0x123 44\n-n tktest\n-s concat a b c\n" + update + } {} +} + +winfo interps +tk appname tktest +catch {destroy .f} +frame .f +set id [string range [winfo id .f] 2 end] +if $gotTestCmds { + test send-12.1 {TimeoutProc procedure} { + testsend prop root InterpRegistry "$id dummy\n" + list [catch {send dummy foo} msg] $msg + } {1 {target application died or uses a Tk version before 4.0}} + testsend prop root InterpRegistry "" +} +test send-12.2 {TimeoutProc procedure} { + winfo interps + tk appname tktest + update + setupbg + puts $fd {after 10 {after 5000; exit}; puts [tk appname]; puts **DONE**; flush stdout} + set bgDone 0 + set bgData {} + flush $fd + tkwait variable bgDone + set app $bgData + after 200 + set result [list [catch {send $app foo} msg] $msg] + close $fd + set result +} {1 {target application died}} + +winfo interps +tk appname tktest +test send-13.1 {DeleteProc procedure} { + setupbg + set app [dobg {rename send {}; tk appname}] + set result [list [catch {send $app foo} msg] $msg [winfo interps]] + cleanupbg + set result +} {1 {no application named "tktest #2"} tktest} +test send-13.2 {DeleteProc procedure} { + winfo interps + tk appname tktest + rename send {} + set result {} + lappend result [winfo interps] [info commands send] + tk appname foo + lappend result [winfo interps] [info commands send] +} {{} {} foo send} + +if [info exists env(TK_ALT_DISPLAY)] { + test send-14.1 {SendRestrictProc procedure, sends crossing from different displays} { + setupbg -display $env(TK_ALT_DISPLAY) + set result [dobg " + toplevel .t -screen [winfo screen .] + wm geometry .t +0+0 + tk appname xyzgorp1 + set x child + "] + toplevel .t -screen $env(TK_ALT_DISPLAY) + wm geometry .t +0+0 + tk appname xyzgorp2 + update + set y parent + set result [send -displayof .t xyzgorp1 {list $x [send -displayof .t xyzgorp2 set y]}] + destroy .t + cleanupbg + set result + } {child parent} +} + +if $gotTestCmds { + testsend prop root InterpRegister $registry + tk appname tktest + test send-15.1 {UpdateCommWindow procedure} { + set x [list [testsend prop comm TK_APPLICATION]] + newApp "" t_s_1 Test + send t_s_1 wm withdraw . + newApp "" t_s_2 Test + send t_s_2 wm withdraw . + lappend x [testsend prop comm TK_APPLICATION] + interp delete t_s_1 + lappend x [testsend prop comm TK_APPLICATION] + interp delete t_s_2 + lappend x [testsend prop comm TK_APPLICATION] + } {tktest {t_s_2 t_s_1 tktest} {t_s_2 tktest} tktest} +} + +tk appname $name +if $gotTestCmds { + testsend prop root InterpRegistry $registry +} +if $gotTestCmds { + testdeleteapps +} +rename newApp {} diff --git a/tests/text.test b/tests/text.test new file mode 100644 index 0000000..3bd5a09 --- /dev/null +++ b/tests/text.test @@ -0,0 +1,1262 @@ +# This file is a Tcl script to test the code in the file tkText.c. +# This file is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1992-1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) text.test 1.46 97/10/13 15:18:31 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +eval destroy [winfo child .] + +# Create entries in the option database to be sure that geometry options +# like border width have predictable values. + +option add *Text.borderWidth 2 +option add *Text.highlightThickness 2 +option add *Text.font {Courier -12} + +text .t -width 20 -height 10 +pack append . .t {top expand fill} +update +.t debug on +wm geometry . {} + +# The statements below reset the main window; it's needed if the window +# manager is mwm to make mwm forget about a previous minimum size setting. + +wm withdraw . +wm minsize . 1 1 +wm positionfrom . user +wm deiconify . + +entry .t.e +.t.e insert end abcdefg +.t.e select from 0 + +.t insert 1.0 "Line 1 +abcdefghijklm +12345 +Line 4 +bOy GIrl .#@? x_yz +!@#$% +Line 7" + +catch {destroy .t2} +text .t2 +set i 0 +foreach test { + {-background #ff00ff #ff00ff <gorp>} + {-bd 4 4 foo} + {-bg blue blue #xx} + {-borderwidth 7 7 ++} + {-cursor watch watch lousy} + {-exportselection no 0 maybe} + {-fg red red stupid} + {-font fixed fixed {}} + {-foreground #012 #012 bogus} + {-height 5 5 bad} + {-highlightbackground #123 #123 bogus} + {-highlightcolor #234 #234 bogus} + {-highlightthickness -2 0 bad} + {-insertbackground green green <bogus>} + {-insertborderwidth 45 45 bogus} + {-insertofftime 100 100 2.4} + {-insertontime 47 47 e1} + {-insertwidth 2.3 2 47d} + {-padx 3.4 3 2.4.} + {-pady 82 82 bogus} + {-relief raised raised bumpy} + {-selectbackground #ffff01234567 #ffff01234567 bogus} + {-selectborderwidth 21 21 3x} + {-selectforeground yellow yellow #12345} + {-spacing1 20 20 1.3x} + {-spacing1 -5 0 bogus} + {-spacing2 5 5 bogus} + {-spacing2 -1 0 bogus} + {-spacing3 20 20 bogus} + {-spacing3 -10 0 bogus} + {-state disabled disabled foo} + {-tabs {1i 2i 3i 4i} {1i 2i 3i 4i} bad_tabs} + {-width 73 73 2.4} + {-wrap word word bad_wrap} +} { + test text-1.[incr i] {text options} { + set result {} + lappend result [catch {.t2 configure [lindex $test 0] [lindex $test 3]}] + .t2 configure [lindex $test 0] [lindex $test 1] + lappend result [.t2 cget [lindex $test 0]] + } [list 1 [lindex $test 2]] +} +test text-1.[incr i] {text options} { + .t2 configure -takefocus "any old thing" + .t2 cget -takefocus +} {any old thing} +test text-1.[incr i] {text options} { + .t2 configure -xscrollcommand "x scroll command" + .t2 configure -xscrollcommand +} {-xscrollcommand xScrollCommand ScrollCommand {} {x scroll command}} +test text-1.[incr i] {text options} { + .t2 configure -yscrollcommand "test command" + .t2 configure -yscrollcommand +} {-yscrollcommand yScrollCommand ScrollCommand {} {test command}} +test text-1.[incr i] {text options} { + set result {} + foreach i [.t2 configure] { + lappend result [lindex $i 4] + } + set result +} {blue {} {} 7 watch 0 {} fixed #012 5 #123 #234 0 green 45 100 47 2 3 82 raised #ffff01234567 21 yellow 0 0 0 0 disabled {1i 2i 3i 4i} {any old thing} 73 word {x scroll command} {test command}} + +test text-2.1 {Tk_TextCmd procedure} { + list [catch {text} msg] $msg +} {1 {wrong # args: should be "text pathName ?options?"}} +test text-2.2 {Tk_TextCmd procedure} { + list [catch {text foobar} msg] $msg +} {1 {bad window path name "foobar"}} +test text-2.3 {Tk_TextCmd procedure} { + catch {destroy .t2} + list [catch {text .t2 -gorp nofun} msg] $msg [winfo exists .t2] +} {1 {unknown option "-gorp"} 0} +test text-2.4 {Tk_TextCmd procedure} { + catch {destroy .t2} + list [catch {text .t2 -bd 2 -fg red} msg] $msg \ + [lindex [.t2 config -bd] 4] [lindex [.t2 config -fg] 4] +} {0 .t2 2 red} +if {$tcl_platform(platform) == "macintosh"} { + set relief solid +} elseif {$tcl_platform(platform) == "windows"} { + set relief flat +} else { + set relief raised +} +test text-2.5 {Tk_TextCmd procedure} { + catch {destroy .t2} + text .t2 + .t2 tag cget sel -relief +} $relief +test text-2.6 {Tk_TextCmd procedure} { + catch {destroy .t2} + list [text .t2] [winfo class .t2] +} {.t2 Text} + +test text-3.1 {TextWidgetCmd procedure, basics} { + list [catch {.t} msg] $msg +} {1 {wrong # args: should be ".t option ?arg arg ...?"}} +test text-3.2 {TextWidgetCmd procedure} { + list [catch {.t gorp 1.0 z 1.2} msg] $msg +} {1 {bad option "gorp": must be bbox, cget, compare, configure, debug, delete, dlineinfo, get, image, index, insert, mark, scan, search, see, tag, window, xview, or yview}} + +test text-4.1 {TextWidgetCmd procedure, "bbox" option} { + list [catch {.t bbox} msg] $msg +} {1 {wrong # args: should be ".t bbox index"}} +test text-4.2 {TextWidgetCmd procedure, "bbox" option} { + list [catch {.t bbox a b} msg] $msg +} {1 {wrong # args: should be ".t bbox index"}} +test text-4.3 {TextWidgetCmd procedure, "bbox" option} { + list [catch {.t bbox bad_mark} msg] $msg +} {1 {bad text index "bad_mark"}} + +test text-5.1 {TextWidgetCmd procedure, "cget" option} { + list [catch {.t cget} msg] $msg +} {1 {wrong # args: should be ".t cget option"}} +test text-5.2 {TextWidgetCmd procedure, "cget" option} { + list [catch {.t cget a b} msg] $msg +} {1 {wrong # args: should be ".t cget option"}} +test text-5.3 {TextWidgetCmd procedure, "cget" option} { + list [catch {.t cget -gorp} msg] $msg +} {1 {unknown option "-gorp"}} +test text-5.4 {TextWidgetCmd procedure, "cget" option} { + .t configure -bd 17 + .t cget -bd +} {17} +.t configure -bd [lindex [.t configure -bd] 3] + +test text-6.1 {TextWidgetCmd procedure, "compare" option} { + list [catch {.t compare a b} msg] $msg +} {1 {wrong # args: should be ".t compare index1 op index2"}} +test text-6.2 {TextWidgetCmd procedure, "compare" option} { + list [catch {.t compare a b c d} msg] $msg +} {1 {wrong # args: should be ".t compare index1 op index2"}} +test text-6.3 {TextWidgetCmd procedure, "compare" option} { + list [catch {.t compare @x == 1.0} msg] $msg +} {1 {bad text index "@x"}} +test text-6.4 {TextWidgetCmd procedure, "compare" option} { + list [catch {.t compare 1.0 < @y} msg] $msg +} {1 {bad text index "@y"}} +test text-6.5 {TextWidgetCmd procedure, "compare" option} { + list [.t compare 1.1 < 1.0] [.t compare 1.1 < 1.1] [.t compare 1.1 < 1.2] +} {0 0 1} +test text-6.6 {TextWidgetCmd procedure, "compare" option} { + list [.t compare 1.1 <= 1.0] [.t compare 1.1 <= 1.1] [.t compare 1.1 <= 1.2] +} {0 1 1} +test text-6.7 {TextWidgetCmd procedure, "compare" option} { + list [.t compare 1.1 == 1.0] [.t compare 1.1 == 1.1] [.t compare 1.1 == 1.2] +} {0 1 0} +test text-6.8 {TextWidgetCmd procedure, "compare" option} { + list [.t compare 1.1 >= 1.0] [.t compare 1.1 >= 1.1] [.t compare 1.1 >= 1.2] +} {1 1 0} +test text-6.9 {TextWidgetCmd procedure, "compare" option} { + list [.t compare 1.1 > 1.0] [.t compare 1.1 > 1.1] [.t compare 1.1 > 1.2] +} {1 0 0} +test text-6.10 {TextWidgetCmd procedure, "compare" option} { + list [.t com 1.1 != 1.0] [.t compare 1.1 != 1.1] [.t compare 1.1 != 1.2] +} {1 0 1} +test text-6.11 {TextWidgetCmd procedure, "compare" option} { + list [catch {.t compare 1.0 <x 1.2} msg] $msg +} {1 {bad comparison operator "<x": must be <, <=, ==, >=, >, or !=}} +test text-6.12 {TextWidgetCmd procedure, "compare" option} { + list [catch {.t compare 1.0 >> 1.2} msg] $msg +} {1 {bad comparison operator ">>": must be <, <=, ==, >=, >, or !=}} +test text-6.13 {TextWidgetCmd procedure, "compare" option} { + list [catch {.t compare 1.0 z 1.2} msg] $msg +} {1 {bad comparison operator "z": must be <, <=, ==, >=, >, or !=}} +test text-6.14 {TextWidgetCmd procedure, "compare" option} { + list [catch {.t co 1.0 z 1.2} msg] $msg +} {1 {bad option "co": must be bbox, cget, compare, configure, debug, delete, dlineinfo, get, image, index, insert, mark, scan, search, see, tag, window, xview, or yview}} + +# "configure" option is already covered above + +test text-7.1 {TextWidgetCmd procedure, "debug" option} { + list [catch {.t debug 0 1} msg] $msg +} {1 {wrong # args: should be ".t debug boolean"}} +test text-7.2 {TextWidgetCmd procedure, "debug" option} { + list [catch {.t de 0 1} msg] $msg +} {1 {bad option "de": must be bbox, cget, compare, configure, debug, delete, dlineinfo, get, image, index, insert, mark, scan, search, see, tag, window, xview, or yview}} +test text-7.3 {TextWidgetCmd procedure, "debug" option} { + .t debug true + .t deb +} 1 +test text-7.4 {TextWidgetCmd procedure, "debug" option} { + .t debug false + .t debug +} 0 +.t debug + +test text-8.1 {TextWidgetCmd procedure, "delete" option} { + list [catch {.t delete} msg] $msg +} {1 {wrong # args: should be ".t delete index1 ?index2?"}} +test text-8.2 {TextWidgetCmd procedure, "delete" option} { + list [catch {.t delete a b c} msg] $msg +} {1 {wrong # args: should be ".t delete index1 ?index2?"}} +test text-8.3 {TextWidgetCmd procedure, "delete" option} { + list [catch {.t delete @x 2.2} msg] $msg +} {1 {bad text index "@x"}} +test text-8.4 {TextWidgetCmd procedure, "delete" option} { + list [catch {.t delete 2.3 @y} msg] $msg +} {1 {bad text index "@y"}} +test text-8.5 {TextWidgetCmd procedure, "delete" option} { + .t con -state disabled + .t delete 2.3 + .t g 2.0 2.end +} abcdefghijklm +.t con -state normal +test text-8.6 {TextWidgetCmd procedure, "delete" option} { + .t delete 2.3 + .t get 2.0 2.end +} abcefghijklm +test text-8.7 {TextWidgetCmd procedure, "delete" option} { + .t delete 2.1 2.3 + .t get 2.0 2.end +} aefghijklm + +test text-9.1 {TextWidgetCmd procedure, "get" option} { + list [catch {.t get} msg] $msg +} {1 {wrong # args: should be ".t get index1 ?index2?"}} +test text-9.2 {TextWidgetCmd procedure, "get" option} { + list [catch {.t get a b c} msg] $msg +} {1 {wrong # args: should be ".t get index1 ?index2?"}} +test text-9.3 {TextWidgetCmd procedure, "get" option} { + list [catch {.t get @q 3.1} msg] $msg +} {1 {bad text index "@q"}} +test text-9.4 {TextWidgetCmd procedure, "get" option} { + list [catch {.t get 3.1 @r} msg] $msg +} {1 {bad text index "@r"}} +test text-9.5 {TextWidgetCmd procedure, "get" option} { + .t get 5.7 5.3 +} {} +test text-9.6 {TextWidgetCmd procedure, "get" option} { + .t get 5.3 5.5 +} { G} +test text-9.7 {TextWidgetCmd procedure, "get" option} { + .t get 5.3 end +} { GIrl .#@? x_yz +!@#$% +Line 7 +} +.t mark set a 5.3 +.t mark set b 5.3 +.t mark set c 5.5 +test text-9.8 {TextWidgetCmd procedure, "get" option} { + .t get 5.2 5.7 +} {y GIr} +test text-9.9 {TextWidgetCmd procedure, "get" option} { + .t get 5.2 +} {y} +test text-9.10 {TextWidgetCmd procedure, "get" option} { + .t get 5.2 5.4 +} {y } + +test text-10.1 {TextWidgetCmd procedure, "index" option} { + list [catch {.t index} msg] $msg +} {1 {wrong # args: should be ".t index index"}} +test text-10.2 {TextWidgetCmd procedure, "index" option} { + list [catch {.t ind a b} msg] $msg +} {1 {wrong # args: should be ".t index index"}} +test text-10.3 {TextWidgetCmd procedure, "index" option} { + list [catch {.t in a b} msg] $msg +} {1 {bad option "in": must be bbox, cget, compare, configure, debug, delete, dlineinfo, get, image, index, insert, mark, scan, search, see, tag, window, xview, or yview}} +test text-10.4 {TextWidgetCmd procedure, "index" option} { + list [catch {.t index @xyz} msg] $msg +} {1 {bad text index "@xyz"}} +test text-10.5 {TextWidgetCmd procedure, "index" option} { + .t index 1.2 +} 1.2 + +test text-11.1 {TextWidgetCmd procedure, "insert" option} { + list [catch {.t insert 1.2} msg] $msg +} {1 {wrong # args: should be ".t insert index chars ?tagList chars tagList ...?"}} +test text-11.2 {TextWidgetCmd procedure, "insert" option} { + .t config -state disabled + .t insert 1.2 xyzzy + .t get 1.0 1.end +} {Line 1} +.t config -state normal +test text-11.3 {TextWidgetCmd procedure, "insert" option} { + .t insert 1.2 xyzzy + .t get 1.0 1.end +} {Lixyzzyne 1} +test text-11.4 {TextWidgetCmd procedure, "insert" option} { + .t delete 1.0 end + .t insert 1.0 "Sample text" x + .t tag ranges x +} {1.0 1.11} +test text-11.5 {TextWidgetCmd procedure, "insert" option} { + .t delete 1.0 end + .t insert 1.0 "Sample text" x + .t insert 1.2 "XYZ" y + list [.t tag ranges x] [.t tag ranges y] +} {{1.0 1.2 1.5 1.14} {1.2 1.5}} +test text-11.6 {TextWidgetCmd procedure, "insert" option} { + .t delete 1.0 end + .t insert 1.0 "Sample text" {x y z} + list [.t tag ranges x] [.t tag ranges y] [.t tag ranges z] +} {{1.0 1.11} {1.0 1.11} {1.0 1.11}} +test text-11.7 {TextWidgetCmd procedure, "insert" option} { + .t delete 1.0 end + .t insert 1.0 "Sample text" {x y z} + .t insert 1.3 "A" {a b z} + list [.t tag ranges a] [.t tag ranges b] [.t tag ranges x] [.t tag ranges y] [.t tag ranges z] +} {{1.3 1.4} {1.3 1.4} {1.0 1.3 1.4 1.12} {1.0 1.3 1.4 1.12} {1.0 1.12}} +test text-11.8 {TextWidgetCmd procedure, "insert" option} { + .t delete 1.0 end + list [catch {.t insert 1.0 "Sample text" "a \{b"} msg] $msg +} {1 {unmatched open brace in list}} +test text-11.9 {TextWidgetCmd procedure, "insert" option} { + .t delete 1.0 end + .t insert 1.0 "First" bold " " {} second "x y z" " third" + list [.t get 1.0 1.end] [.t tag ranges bold] [.t tag ranges x] \ + [.t tag ranges y] [.t tag ranges z] +} {{First second third} {1.0 1.5} {1.6 1.12} {1.6 1.12} {1.6 1.12}} +test text-11.10 {TextWidgetCmd procedure, "insert" option} { + .t delete 1.0 end + .t insert 1.0 "First" bold " second" silly + list [.t get 1.0 1.end] [.t tag ranges bold] [.t tag ranges silly] +} {{First second} {1.0 1.5} {1.5 1.12}} + +# Mark, scan, search, see, tag, window, xview, and yview actions are tested elsewhere. + +test text-12.1 {ConfigureText procedure} { + list [catch {.t2 configure -state foobar} msg] $msg +} {1 {bad state value "foobar": must be normal or disabled}} +test text-12.2 {ConfigureText procedure} { + .t2 configure -spacing1 -2 -spacing2 1 -spacing3 1 + list [.t2 cget -spacing1] [.t2 cget -spacing2] [.t2 cget -spacing3] +} {0 1 1} +test text-12.3 {ConfigureText procedure} { + .t2 configure -spacing1 1 -spacing2 -1 -spacing3 1 + list [.t2 cget -spacing1] [.t2 cget -spacing2] [.t2 cget -spacing3] +} {1 0 1} +test text-12.4 {ConfigureText procedure} { + .t2 configure -spacing1 1 -spacing2 1 -spacing3 -3 + list [.t2 cget -spacing1] [.t2 cget -spacing2] [.t2 cget -spacing3] +} {1 1 0} +test text-12.5 {ConfigureText procedure} { + set x [list [catch {.t2 configure -tabs {30 foo}} msg] $msg $errorInfo] + .t2 configure -tabs {10 20 30} + set x +} {1 {bad tab alignment "foo": must be left, right, center, or numeric} {bad tab alignment "foo": must be left, right, center, or numeric + (while processing -tabs option) + invoked from within +".t2 configure -tabs {30 foo}"}} +test text-12.6 {ConfigureText procedure} { + .t2 configure -tabs {10 20 30} + .t2 configure -tabs {} + .t2 cget -tabs +} {} +test text-12.7 {ConfigureText procedure} { + list [catch {.t2 configure -wrap bogus} msg] $msg +} {1 {bad wrap mode "bogus": must be char, none, or word}} +test text-12.8 {ConfigureText procedure} { + .t2 configure -selectborderwidth 17 -selectforeground #332211 \ + -selectbackground #abc + list [lindex [.t2 tag config sel -borderwidth] 4] \ + [lindex [.t2 tag config sel -foreground] 4] \ + [lindex [.t2 tag config sel -background] 4] +} {17 #332211 #abc} +test text-12.9 {ConfigureText procedure} { + .t2 configure -selectborderwidth {} + .t2 tag cget sel -borderwidth +} {} +test text-12.10 {ConfigureText procedure} { + list [catch {.t2 configure -selectborderwidth foo} msg] $msg +} {1 {bad screen distance "foo"}} +test text-12.11 {ConfigureText procedure} { + catch {destroy .t2} + .t.e select to 2 + text .t2 -exportselection 1 + selection get +} {ab} +test text-12.12 {ConfigureText procedure} { + catch {destroy .t2} + .t.e select to 2 + text .t2 -exportselection 0 + .t2 insert insert 1234657890 + .t2 tag add sel 1.0 1.4 + selection get +} {ab} +test text-12.13 {ConfigureText procedure} { + catch {destroy .t2} + .t.e select to 1 + text .t2 -exportselection 1 + .t2 insert insert 1234657890 + .t2 tag add sel 1.0 1.4 + selection get +} {1234} +test text-12.14 {ConfigureText procedure} { + catch {destroy .t2} + .t.e select to 1 + text .t2 -exportselection 0 + .t2 insert insert 1234657890 + .t2 tag add sel 1.0 1.4 + .t2 configure -exportselection 1 + selection get +} {1234} +test text-12.15 {ConfigureText procedure} { + catch {destroy .t2} + text .t2 -exportselection 1 + .t2 insert insert 1234657890 + .t2 tag add sel 1.0 1.4 + set result [selection get] + .t2 configure -exportselection 0 + lappend result [catch {selection get} msg] $msg +} {1234 1 {PRIMARY selection doesn't exist or form "STRING" not defined}} +test text-12.16 {ConfigureText procedure} {fonts} { + # This test is non-portable because the window size will vary depending + # on the font size, which can vary. + + catch {destroy .t2} + toplevel .t2 + text .t2.t -width 20 -height 10 + pack append .t2 .t2.t top + wm geometry .t2 +0+0 + update + wm geometry .t2 +} {150x140+0+0} +test text-12.17 {ConfigureText procedure} { + # This test was failing Windows because the title bar on .t2 + # was a certain minimum size and it was interfering with the size + # requested by the -setgrid. The "overrideredirect" gets rid of the + # titlebar so the toplevel can shrink to the appropriate size. + + catch {destroy .t2} + toplevel .t2 + wm overrideredirect .t2 1 + text .t2.t -width 20 -height 10 -setgrid 1 + pack append .t2 .t2.t top + wm geometry .t2 +0+0 + update + wm geometry .t2 +} {20x10+0+0} +test text-12.18 {ConfigureText procedure} { + # This test was failing on Windows because the title bar on .t2 + # was a certain minimum size and it was interfering with the size + # requested by the -setgrid. The "overrideredirect" gets rid of the + # titlebar so the toplevel can shrink to the appropriate size. + + catch {destroy .t2} + toplevel .t2 + wm overrideredirect .t2 1 + text .t2.t -width 20 -height 10 -setgrid 1 + pack append .t2 .t2.t top + wm geometry .t2 +0+0 + update + set result [wm geometry .t2] + wm geometry .t2 15x8 + update + lappend result [wm geometry .t2] + .t2.t configure -wrap word + update + lappend result [wm geometry .t2] +} {20x10+0+0 15x8+0+0 15x8+0+0} + +test text-13.1 {TextWorldChanged procedure, spacing options} fonts { + catch {destroy .t2} + text .t2 -width 20 -height 10 + set result [winfo reqheight .t2] + .t2 configure -spacing1 2 + lappend result [winfo reqheight .t2] + .t2 configure -spacing3 1 + lappend result [winfo reqheight .t2] + .t2 configure -spacing1 0 + lappend result [winfo reqheight .t2] +} {140 160 170 150} + +test text-14.1 {TextEventProc procedure} { + text .tx1 -bg #543210 + rename .tx1 .tx2 + set x {} + lappend x [winfo exists .tx1] + lappend x [.tx2 cget -bg] + destroy .tx1 + lappend x [info command .tx*] [winfo exists .tx1] [winfo exists .tx2] +} {1 #543210 {} 0 0} + +test text-15.1 {TextCmdDeletedProc procedure} { + text .tx1 + rename .tx1 {} + list [info command .tx*] [winfo exists .tx1] +} {{} 0} +test text-15.2 {TextCmdDeletedProc procedure, disabling -setgrid} fonts { + catch {destroy .top} + toplevel .top + wm geom .top +0+0 + text .top.t -setgrid 1 -width 20 -height 10 + pack .top.t + update + set x [wm geometry .top] + rename .top.t {} + update + lappend x [wm geometry .top] + destroy .top + set x +} {20x10+0+0 150x140+0+0} + +test text-16.1 {InsertChars procedure} { + catch {destroy .t2} + text .t2 + .t2 insert 2.0 abcd\n + .t2 get 1.0 end +} {abcd + +} +test text-16.2 {InsertChars procedure} { + catch {destroy .t2} + text .t2 + .t2 insert 1.0 abcd\n + .t2 insert end 123\n + .t2 get 1.0 end +} {abcd +123 + +} +test text-16.3 {InsertChars procedure} { + catch {destroy .t2} + text .t2 + .t2 insert 1.0 abcd\n + .t2 insert 10.0 123 + .t2 get 1.0 end +} {abcd +123 +} +test text-16.4 {InsertChars procedure, inserting on top visible line} { + catch {destroy .t2} + text .t2 -width 20 -height 4 -wrap word + pack .t2 + .t2 insert insert "Now is the time for all great men to come to the " + .t2 insert insert "aid of their party.\n" + .t2 insert insert "Now is the time for all great men.\n" + .t2 see end + update + .t2 insert 1.0 "Short\n" + .t2 index @0,0 +} {2.56} +test text-16.5 {InsertChars procedure, inserting on top visible line} { + catch {destroy .t2} + text .t2 -width 20 -height 4 -wrap word + pack .t2 + .t2 insert insert "Now is the time for all great men to come to the " + .t2 insert insert "aid of their party.\n" + .t2 insert insert "Now is the time for all great men.\n" + .t2 see end + update + .t2 insert 1.55 "Short\n" + .t2 index @0,0 +} {2.0} +test text-16.6 {InsertChars procedure, inserting on top visible line} { + catch {destroy .t2} + text .t2 -width 20 -height 4 -wrap word + pack .t2 + .t2 insert insert "Now is the time for all great men to come to the " + .t2 insert insert "aid of their party.\n" + .t2 insert insert "Now is the time for all great men.\n" + .t2 see end + update + .t2 insert 1.56 "Short\n" + .t2 index @0,0 +} {1.56} +test text-16.7 {InsertChars procedure, inserting on top visible line} { + catch {destroy .t2} + text .t2 -width 20 -height 4 -wrap word + pack .t2 + .t2 insert insert "Now is the time for all great men to come to the " + .t2 insert insert "aid of their party.\n" + .t2 insert insert "Now is the time for all great men.\n" + .t2 see end + update + .t2 insert 1.57 "Short\n" + .t2 index @0,0 +} {1.56} +catch {destroy .t2} + +proc setup {} { + .t delete 1.0 end + .t insert 1.0 "Line 1 +abcde +12345 +Line 4" +} + +.t delete 1.0 end +test text-17.1 {DeleteChars procedure} { + .t get 1.0 end +} { +} +test text-17.2 {DeleteChars procedure} { + list [catch {.t delete foobar} msg] $msg +} {1 {bad text index "foobar"}} +test text-17.3 {DeleteChars procedure} { + list [catch {.t delete 1.0 lousy} msg] $msg +} {1 {bad text index "lousy"}} +test text-17.4 {DeleteChars procedure} { + setup + .t delete 2.1 + .t get 1.0 end +} {Line 1 +acde +12345 +Line 4 +} +test text-17.5 {DeleteChars procedure} { + setup + .t delete 2.3 + .t get 1.0 end +} {Line 1 +abce +12345 +Line 4 +} +test text-17.6 {DeleteChars procedure} { + setup + .t delete 2.end + .t get 1.0 end +} {Line 1 +abcde12345 +Line 4 +} +test text-17.7 {DeleteChars procedure} { + setup + .t tag add sel 4.2 end + .t delete 4.2 end + list [.t tag ranges sel] [.t get 1.0 end] +} {{} {Line 1 +abcde +12345 +Li +}} +test text-17.8 {DeleteChars procedure} { + setup + .t tag add sel 1.0 end + .t delete 4.0 end + list [.t tag ranges sel] [.t get 1.0 end] +} {{1.0 3.5} {Line 1 +abcde +12345 +}} +test text-17.9 {DeleteChars procedure} { + setup + .t delete 2.2 2.2 + .t get 1.0 end +} {Line 1 +abcde +12345 +Line 4 +} +test text-17.10 {DeleteChars procedure} { + setup + .t delete 2.3 2.1 + .t get 1.0 end +} {Line 1 +abcde +12345 +Line 4 +} +test text-17.11 {DeleteChars procedure} { + catch {destroy .t2} + toplevel .t2 + text .t2.t -width 20 -height 5 + pack append .t2 .t2.t top + wm geometry .t2 +0+0 + .t2.t insert 1.0 "abc\n123\nx\ny\nz\nq\nr\ns" + update + .t2.t delete 1.0 3.0 + list [.t2.t index @0,0] [.t2.t get @0,0] +} {1.0 x} +test text-17.12 {DeleteChars procedure} { + catch {destroy .t2} + toplevel .t2 + text .t2.t -width 20 -height 5 + pack append .t2 .t2.t top + wm geometry .t2 +0+0 + .t2.t insert 1.0 "abc\n123\nx\ny\nz\nq\nr\ns" + .t2.t yview 3.0 + update + .t2.t delete 2.0 4.0 + list [.t2.t index @0,0] [.t2.t get @0,0] +} {2.0 y} +catch {destroy .t2} +toplevel .t2 +text .t2.t -width 1 -height 10 -wrap char +frame .t2.f -width 200 -height 20 -relief raised -bd 2 +pack .t2.f .t2.t -side left +wm geometry .t2 +0+0 +update +test text-17.13 {DeleteChars procedure, updates affecting topIndex} { + .t2.t delete 1.0 end + .t2.t insert end "abcde\n12345\nqrstuv" + .t2.t yview 2.1 + .t2.t delete 1.4 2.3 + .t2.t index @0,0 +} {1.2} +test text-17.14 {DeleteChars procedure, updates affecting topIndex} { + .t2.t delete 1.0 end + .t2.t insert end "abcde\n12345\nqrstuv" + .t2.t yview 2.1 + .t2.t delete 2.3 2.4 + .t2.t index @0,0 +} {2.0} +test text-17.15 {DeleteChars procedure, updates affecting topIndex} { + .t2.t delete 1.0 end + .t2.t insert end "abcde\n12345\nqrstuv" + .t2.t yview 1.3 + .t2.t delete 1.0 1.2 + .t2.t index @0,0 +} {1.1} +test text-17.16 {DeleteChars procedure, updates affecting topIndex} { + catch {destroy .t2} + toplevel .t2 + text .t2.t -width 6 -height 10 -wrap word + frame .t2.f -width 200 -height 20 -relief raised -bd 2 + pack .t2.f .t2.t -side left + wm geometry .t2 +0+0 + update + .t2.t insert end "abc def\n01 2345 678 9101112\nLine 3\nLine 4\nLine 5\n6\n7\n8\n" + .t2.t yview 2.4 + .t2.t delete 2.5 + set x [.t2.t index @0,0] + .t2.t delete 2.5 + list $x [.t2.t index @0,0] +} {2.3 2.0} + +.t delete 1.0 end +foreach i {a b c d e f g h i j k l m n o p q r s t u v w x y z} { + .t insert end $i.0$i.1$i.2$i.3$i.4\n +} +test text-18.1 {TextFetchSelection procedure} { + .t tag add sel 1.3 3.4 + selection get +} {a.1a.2a.3a.4 +b.0b.1b.2b.3b.4 +c.0c} +test text-18.2 {TextFetchSelection procedure} { + .t tag add x 1.2 + .t tag add x 1.4 + .t tag add x 2.0 + .t tag add x 2.3 + .t tag remove sel 1.0 end + .t tag add sel 1.0 3.4 + selection get +} {a.0a.1a.2a.3a.4 +b.0b.1b.2b.3b.4 +c.0c} +test text-18.3 {TextFetchSelection procedure} { + .t tag remove sel 1.0 end + .t tag add sel 13.3 + selection get +} {m} +test text-18.4 {TextFetchSelection procedure} { + .t tag remove x 1.0 end + .t tag add sel 1.0 3.4 + .t tag remove sel 1.0 end + .t tag add sel 1.2 1.5 + .t tag add sel 2.4 3.1 + .t tag add sel 10.0 10.end + .t tag add sel 13.3 + selection get +} {0a..1b.2b.3b.4 +cj.0j.1j.2j.3j.4m} +set x "" +for {set i 1} {$i < 200} {incr i} { + append x "This is line $i, padded to just about 53 characters.\n" +} +test text-18.5 {TextFetchSelection procedure, long selections} { + .t delete 1.0 end + .t insert end $x + .t tag add sel 1.0 end + selection get +} $x\n + +test text-19.1 {TkTextLostSelection procedure} {unixOnly} { + catch {destroy .t2} + text .t2 + .t2 insert 1.0 "abc\ndef\nghijk\n1234" + .t2 tag add sel 1.2 3.3 + .t.e select to 1 + .t2 tag ranges sel +} {} +test text-19.2 {TkTextLostSelection procedure} {macOrPc} { + catch {destroy .t2} + text .t2 + .t2 insert 1.0 "abc\ndef\nghijk\n1234" + .t2 tag add sel 1.2 3.3 + .t.e select to 1 + .t2 tag ranges sel +} {1.2 3.3} +catch {destroy .t2} +test text-19.3 {TkTextLostSelection procedure} { + catch {destroy .t2} + text .t2 + .t2 insert 1.0 "abcdef\nghijk\n1234" + .t2 tag add sel 1.0 1.3 + set x [selection get] + selection clear + lappend x [catch {selection get} msg] $msg + .t2 tag add sel 1.0 1.3 + lappend x [selection get] +} {abc 1 {PRIMARY selection doesn't exist or form "STRING" not defined} abc} + +.t delete 1.0 end +.t insert end "xxyz xyz x. the\nfoo -forward bar xxxxx BaR foo\nxyz xxyzx" +test text-20.1 {TextSearchCmd procedure, argument parsing} { + list [catch {.t search -} msg] $msg +} {1 {bad switch "-": must be -forward, -backward, -exact, -regexp, -nocase, -count, or --}} +test text-20.2 {TextSearchCmd procedure, -backwards option} { + .t search -backwards xyz 1.4 +} {1.1} +test text-20.3 {TextSearchCmd procedure, -forwards option} { + .t search -forwards xyz 1.4 +} {1.5} +test text-20.4 {TextSearchCmd procedure, -exact option} { + .t search -f -exact x. 1.0 +} {1.9} +test text-20.5 {TextSearchCmd procedure, -regexp option} { + .t search -b -regexp x.z 1.4 +} {1.1} +test text-20.6 {TextSearchCmd procedure, -count option} { + set length unmodified + list [.t search -count length x. 1.4] $length +} {1.9 2} +test text-20.7 {TextSearchCmd procedure, -count option} { + list [catch {.t search -count} msg] $msg +} {1 {no value given for "-count" option}} +test text-20.8 {TextSearchCmd procedure, -nocase option} { + list [.t search -nocase BaR 1.1] [.t search BaR 1.1] +} {2.13 2.23} +test text-20.9 {TextSearchCmd procedure, -nocase option} { + .t search -n BaR 1.1 +} {2.13} +test text-20.10 {TextSearchCmd procedure, -- option} { + .t search -- -forward 1.0 +} {2.4} +test text-20.11 {TextSearchCmd procedure, argument parsing} { + list [catch {.t search abc} msg] $msg +} {1 {wrong # args: should be ".t search ?switches? pattern index ?stopIndex?}} +test text-20.12 {TextSearchCmd procedure, argument parsing} { + list [catch {.t search abc d e f} msg] $msg +} {1 {wrong # args: should be ".t search ?switches? pattern index ?stopIndex?}} +test text-20.13 {TextSearchCmd procedure, check index} { + list [catch {.t search abc gorp} msg] $msg +} {1 {bad text index "gorp"}} +test text-20.14 {TextSearchCmd procedure, startIndex == "end"} { + .t search non-existent end +} {} +test text-20.15 {TextSearchCmd procedure, startIndex == "end"} { + .t search non-existent end +} {} +test text-20.16 {TextSearchCmd procedure, bad stopIndex} { + list [catch {.t search abc 1.0 lousy} msg] $msg +} {1 {bad text index "lousy"}} +test text-20.17 {TextSearchCmd procedure, pattern case conversion} { + list [.t search -nocase BAR 1.1] [.t search BAR 1.1] +} {2.13 {}} +test text-20.18 {TextSearchCmd procedure, bad regular expression pattern} { + list [catch {.t search -regexp a( 1.0} msg] $msg +} {1 {couldn't compile regular expression pattern: unmatched ()}} +test text-20.19 {TextSearchCmd procedure, skip dummy last line} { + .t search -backwards BaR end 1.0 +} {2.23} +test text-20.20 {TextSearchCmd procedure, skip dummy last line} { + .t search -backwards \n end 1.0 +} {3.9} +test text-20.21 {TextSearchCmd procedure, skip dummy last line} { + .t search \n end +} {1.15} +test text-20.22 {TextSearchCmd procedure, skip dummy last line} { + .t search -back \n 1.0 +} {3.9} +test text-20.23 {TextSearchCmd procedure, extract line contents} { + .t tag add foo 1.2 + .t tag add x 1.3 + .t mark set silly 1.2 + .t search xyz 3.6 +} {1.1} +test text-20.24 {TextSearchCmd procedure, stripping newlines} { + .t search the\n 1.0 +} {1.12} +test text-20.25 {TextSearchCmd procedure, stripping newlines} { + .t search -regexp the\n 1.0 +} {} +test text-20.26 {TextSearchCmd procedure, stripping newlines} { + .t search -regexp {the$} 1.0 +} {1.12} +test text-20.27 {TextSearchCmd procedure, stripping newlines} { + .t search -regexp \n 1.0 +} {} +test text-20.28 {TextSearchCmd procedure, line case conversion} { + list [.t search -nocase bar 2.18] [.t search bar 2.18] +} {2.23 2.13} +test text-20.29 {TextSearchCmd procedure, firstChar and lastChar} { + .t search -backwards xyz 1.6 +} {1.5} +test text-20.30 {TextSearchCmd procedure, firstChar and lastChar} { + .t search -backwards xyz 1.5 +} {1.1} +test text-20.31 {TextSearchCmd procedure, firstChar and lastChar} { + .t search xyz 1.5 +} {1.5} +test text-20.32 {TextSearchCmd procedure, firstChar and lastChar} { + .t search xyz 1.6 +} {3.0} +test text-20.33 {TextSearchCmd procedure, firstChar and lastChar} { + .t search {} 1.end +} {1.15} +test text-20.34 {TextSearchCmd procedure, firstChar and lastChar} { + .t search f 1.end +} {2.0} +test text-20.35 {TextSearchCmd procedure, firstChar and lastChar} { + .t search {} end +} {1.0} +catch {destroy .t2} +toplevel .t2 +wm geometry .t2 +0+0 +text .t2.t -width 30 -height 10 +pack .t2.t +.t2.t insert 1.0 "This is a line\nand this is another" +.t2.t insert end "\nand this is yet another" +frame .t2.f -width 20 -height 20 -bd 2 -relief raised +.t2.t window create 2.5 -window .t2.f +test text-20.36 {TextSearchCmd procedure, firstChar and lastChar} { + .t2.t search his 2.6 +} {2.6} +test text-20.37 {TextSearchCmd procedure, firstChar and lastChar} { + .t2.t search this 2.6 +} {3.4} +test text-20.38 {TextSearchCmd procedure, firstChar and lastChar} { + .t2.t search is 2.6 +} {2.7} +test text-20.39 {TextSearchCmd procedure, firstChar and lastChar} { + .t2.t search his 2.7 +} {3.5} +test text-20.40 {TextSearchCmd procedure, firstChar and lastChar} { + .t2.t search -backwards "his is another" 2.6 +} {2.6} +test text-20.41 {TextSearchCmd procedure, firstChar and lastChar} { + .t2.t search -backwards "his is" 2.6 +} {1.1} +destroy .t2 +test text-20.42 {TextSearchCmd procedure, firstChar and lastChar} { + .t search -backwards forw 2.5 +} {2.5} +test text-20.43 {TextSearchCmd procedure, firstChar and lastChar} { + .t search forw 2.5 +} {2.5} +test text-20.44 {TextSearchCmd procedure, firstChar and lastChar} { + catch {destroy .t2} + text .t2 + list [.t2 search a 1.0] [.t2 search -backward a 1.0] +} {{} {}} +test text-20.45 {TextSearchCmd procedure, regexp match length} { + set length unchanged + list [.t search -regexp -count length x(.)(.*)z 1.1] $length +} {1.1 7} +test text-20.46 {TextSearchCmd procedure, regexp match length} { + set length unchanged + list [.t search -regexp -backward -count length fo* 2.5] $length +} {2.0 3} +test text-20.47 {TextSearchCmd procedure, checking stopIndex} { + list [.t search bar 2.1 2.13] [.t search bar 2.1 2.14] \ + [.t search bar 2.12 2.14] [.t search bar 2.14 2.14] +} {{} 2.13 2.13 {}} +test text-20.48 {TextSearchCmd procedure, checking stopIndex} { + list [.t search -backwards bar 2.20 2.13] \ + [.t search -backwards bar 2.20 2.14] \ + [.t search -backwards bar 2.14 2.13] \ + [.t search -backwards bar 2.13 2.13] +} {2.13 {} 2.13 {}} +test text-20.49 {TextSearchCmd procedure, embedded windows and index/count} { + frame .t.f1 -width 20 -height 20 -relief raised -bd 2 + frame .t.f2 -width 20 -height 20 -relief raised -bd 2 + frame .t.f3 -width 20 -height 20 -relief raised -bd 2 + frame .t.f4 -width 20 -height 20 -relief raised -bd 2 + .t window create 2.10 -window .t.f3 + .t window create 2.8 -window .t.f2 + .t window create 2.8 -window .t.f1 + .t window create 2.1 -window .t.f4 + set result "" + lappend result [.t search -count x forward 1.0] $x + lappend result [.t search -count x wa 1.0] $x + .t delete 2.1 + .t delete 2.8 2.10 + .t delete 2.10 + set result +} {2.6 10 2.11 2} +test text-20.50 {TextSearchCmd procedure, error setting variable} { + catch {unset a} + set a 44 + list [catch {.t search -count a(2) xyz 1.0} msg] $msg +} {1 {can't set "a(2)": variable isn't array}} +test text-20.51 {TextSearchCmd procedure, wrap-around} { + .t search -backwards xyz 1.1 +} {3.5} +test text-20.52 {TextSearchCmd procedure, wrap-around} { + .t search -backwards xyz 1.1 1.0 +} {} +test text-20.53 {TextSearchCmd procedure, wrap-around} { + .t search xyz 3.6 +} {1.1} +test text-20.54 {TextSearchCmd procedure, wrap-around} { + .t search xyz 3.6 end +} {} +test text-20.55 {TextSearchCmd procedure, no match} { + .t search non_existent 3.5 +} {} +test text-20.56 {TextSearchCmd procedure, no match} { + .t search -regexp non_existent 3.5 +} {} +test text-20.57 {TextSearchCmd procedure, special cases} { + .t search -back x 1.1 +} {1.0} +test text-20.58 {TextSearchCmd procedure, special cases} { + .t search -back x 1.0 +} {3.8} +test text-20.59 {TextSearchCmd procedure, special cases} { + .t search \n {end-2c} +} {3.9} +test text-20.60 {TextSearchCmd procedure, special cases} { + .t search \n end +} {1.15} +test text-20.61 {TextSearchCmd procedure, special cases} { + .t search x 1.0 +} {1.0} +test text-20.62 {TextSearchCmd, freeing copy of pattern} { + # This test doesn't return a result, but it will generate + # a core leak if the pattern copy isn't properly freed. + + set p abcdefg1234567890 + set p $p$p$p$p$p$p$p$p + set p $p$p$p$p$p + .t search -nocase $p 1.0 +} {} + +eval destroy [winfo child .] +text .t2 -highlightthickness 0 -bd 0 -relief flat -padx 0 -width 100 +pack .t2 +.t2 insert end "1\t2\t3\t4\t55.5" +test text-21.1 {TkTextGetTabs procedure} { + list [catch {.t2 configure -tabs "\{{}"} msg] $msg +} {1 {unmatched open brace in list}} +test text-21.2 {TkTextGetTabs procedure} { + list [catch {.t2 configure -tabs xyz} msg] $msg +} {1 {bad screen distance "xyz"}} +test text-21.3 {TkTextGetTabs procedure} { + .t2 configure -tabs {100 200} + update idletasks + list [lindex [.t2 bbox 1.2] 0] [lindex [.t2 bbox 1.4] 0] +} {100 200} +test text-21.4 {TkTextGetTabs procedure} { + .t2 configure -tabs {100 right 200 left 300 center 400 numeric} + update idletasks + list [expr [lindex [.t2 bbox 1.2] 0] + [lindex [.t2 bbox 1.2] 2]] \ + [lindex [.t2 bbox 1.4] 0] \ + [expr [lindex [.t2 bbox 1.6] 0] + [lindex [.t2 bbox 1.6] 2]/2] \ + [lindex [.t2 bbox 1.10] 0] +} {100 200 300 400} +test text-21.5 {TkTextGetTabs procedure} { + .t2 configure -tabs {105 r 205 l 305 c 405 n} + update idletasks + list [expr [lindex [.t2 bbox 1.2] 0] + [lindex [.t2 bbox 1.2] 2]] \ + [lindex [.t2 bbox 1.4] 0] \ + [expr [lindex [.t2 bbox 1.6] 0] + [lindex [.t2 bbox 1.6] 2]/2] \ + [lindex [.t2 bbox 1.10] 0] +} {105 205 305 405} +test text-21.6 {TkTextGetTabs procedure} { + list [catch {.t2 configure -tabs {100 left 200 lork}} msg] $msg +} {1 {bad tab alignment "lork": must be left, right, center, or numeric}} +test text-21.7 {TkTextGetTabs procedure} { + list [catch {.t2 configure -tabs {100 !44 200 lork}} msg] $msg +} {1 {bad screen distance "!44"}} + +eval destroy [winfo child .] +text .t +pack .t +.t insert 1.0 "One Line" +.t mark set insert 1.0 + +test text-22.1 {TextDumpCmd procedure, bad args} { + list [catch {.t dump} msg] $msg +} {1 {Usage: .t dump ?-all -image -text -mark -tag -window? ?-command script? index ?index2?}} +test text-22.2 {TextDumpCmd procedure, bad args} { + list [catch {.t dump -all} msg] $msg +} {1 {Usage: .t dump ?-all -image -text -mark -tag -window? ?-command script? index ?index2?}} +test text-22.3 {TextDumpCmd procedure, bad args} { + list [catch {.t dump -command} msg] $msg +} {1 {Usage: .t dump ?-all -image -text -mark -tag -window? ?-command script? index ?index2?}} +test text-22.4 {TextDumpCmd procedure, bad args} { + list [catch {.t dump -bogus} msg] $msg +} {1 {Usage: .t dump ?-all -image -text -mark -tag -window? ?-command script? index ?index2?}} +test text-22.5 {TextDumpCmd procedure, bad args} { + list [catch {.t dump bogus} msg] $msg +} {1 {bad text index "bogus"}} +test text-22.6 {TextDumpCmd procedure, one index} { + .t dump -text 1.2 +} {text e 1.2} +test text-22.7 {TextDumpCmd procedure, two indices} { + .t dump -text 1.0 1.end +} {text {One Line} 1.0} +test text-22.8 {TextDumpCmd procedure, "end" index} { + .t dump -text 1.end end +} {text { +} 1.8} +test text-22.9 {TextDumpCmd procedure, same indices} { + .t dump 1.5 1.5 +} {} +test text-22.10 {TextDumpCmd procedure, negative range} { + .t dump 1.5 1.0 +} {} + +.t delete 1.0 end +.t insert end "Line One\nLine Two\nLine Three\nLine Four" +.t mark set insert 1.0 +.t mark set current 1.0 + +test text-22.11 {TextDumpCmd procedure, stop at begin-line} { + .t dump -text 1.0 2.0 +} {text {Line One +} 1.0} +test text-22.12 {TextDumpCmd procedure, span multiple lines} { + .t dump -text 1.5 3.end +} {text {One +} 1.5 text {Line Two +} 2.0 text {Line Three} 3.0} + +.t tag add x 2.0 2.end +.t tag add y 1.0 end +.t mark set m 2.4 +.t mark set n 4.0 +.t mark set END end +test text-22.13 {TextDumpCmd procedure, tags only} { + .t dump -tag 2.1 2.8 +} {} +test text-22.14 {TextDumpCmd procedure, tags only} { + .t dump -tag 2.0 2.8 +} {tagon x 2.0} +test text-22.15 {TextDumpCmd procedure, tags only} { + .t dump -tag 1.0 4.end +} {tagon y 1.0 tagon x 2.0 tagoff x 2.8} +test text-22.16 {TextDumpCmd procedure, tags only} { + .t dump -tag 1.0 end +} {tagon y 1.0 tagon x 2.0 tagoff x 2.8 tagoff y 5.0} + +.t mark set insert 1.0 +.t mark set current 1.0 +test text-22.17 {TextDumpCmd procedure, marks only} { + .t dump -mark 1.1 1.8 +} {} +test text-22.18 {TextDumpCmd procedure, marks only} { + .t dump -mark 2.0 2.8 +} {mark m 2.4} +test text-22.19 {TextDumpCmd procedure, marks only} { + .t dump -mark 1.1 4.end +} {mark m 2.4 mark n 4.0} +test text-22.20 {TextDumpCmd procedure, marks only} { + .t dump -mark 1.0 end +} {mark current 1.0 mark insert 1.0 mark m 2.4 mark n 4.0 mark END 5.0} + +button .hello -text Hello +.t window create 3.end -window .hello +for {set i 0} {$i < 100} {incr i} { + .t insert end "-\n" +} +.t window create 100.0 -create { } +test text-22.21 {TextDumpCmd procedure, windows only} { + .t dump -window 1.0 5.0 +} {window .hello 3.10} +test text-22.22 {TextDumpCmd procedure, windows only} { + .t dump -window 5.0 end +} {window {} 100.0} + +.t delete 1.0 end +eval {.t mark unset} [.t mark names] +.t insert end "Line One\nLine Two\nLine Three\nLine Four" +.t mark set insert 1.0 +.t mark set current 1.0 +.t tag add x 2.0 2.end +.t mark set m 2.4 +proc Append {varName key value index} { + upvar #0 $varName x + lappend x $key $index $value +} +test text-22.23 {TextDumpCmd procedure, command script} { + set x {} + .t dump -command {Append x} -all 1.0 end + set x +} {mark 1.0 current mark 1.0 insert text 1.0 {Line One +} tagon 2.0 x text 2.0 Line mark 2.4 m text 2.4 { Two} tagoff 2.8 x text 2.8 { +} text 3.0 {Line Three +} text 4.0 {Line Four +}} +test text-22.24 {TextDumpCmd procedure, command script} { + set x {} + .t dump -mark -command {Append x} 1.0 end + set x +} {mark 1.0 current mark 1.0 insert mark 2.4 m} +catch {unset x} + +set l [interp hidden] +eval destroy [winfo children .] + +test text-23.1 {text widget vs hidden commands} { + catch {destroy .t} + text .t + interp hide {} .t + destroy .t + list [winfo children .] [interp hidden] +} [list {} $l] + +eval destroy [winfo child .] +option clear diff --git a/tests/textBTree.test b/tests/textBTree.test new file mode 100644 index 0000000..0ca5eb2 --- /dev/null +++ b/tests/textBTree.test @@ -0,0 +1,897 @@ +# This file is a Tcl script to test out the B-tree facilities of +# Tk's text widget (the contents of the file "tkTextBTree.c". There are +# several file with additional tests for other features of text widgets. +# This file is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1992-1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) textBTree.test 1.8 96/03/21 15:51:12 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +catch {destroy .t} +text .t +.t debug on + +test btree-1.1 {basic insertions} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLine 3\n" +test btree-1.2 {basic insertions} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t insert 1.3 XXX + .t get 1.0 1000000.0 +} "LinXXXe 1\nLine 2\nLine 3\n" +test btree-1.3 {basic insertions} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t insert 3.0 YYY + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nYYYLine 3\n" +test btree-1.4 {basic insertions} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t insert 2.1 X\nYY + .t get 1.0 1000000.0 +} "Line 1\nLX\nYYine 2\nLine 3\n" +test btree-1.5 {basic insertions} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t insert 2.0 X\n\n\n + .t get 1.0 1000000.0 +} "Line 1\nX\n\n\nLine 2\nLine 3\n" +test btree-1.6 {basic insertions} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t insert 2.6 X\n + .t get 1.0 1000000.0 +} "Line 1\nLine 2X\n\nLine 3\n" +test btree-1.7 {insertion before start of text} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t insert 0.4 XXX + .t get 1.0 1000000.0 +} "XXXLine 1\nLine 2\nLine 3\n" +test btree-1.8 {insertion past end of text} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t insert 100.0 ZZ + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLine 3ZZ\n" +test btree-1.9 {insertion before start of line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t insert 2.-3 Q + .t get 1.0 1000000.0 +} "Line 1\nQLine 2\nLine 3\n" +test btree-1.10 {insertion past end of line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t insert 2.40 XYZZY + .t get 1.0 1000000.0 +} "Line 1\nLine 2XYZZY\nLine 3\n" +test btree-1.11 {insertion past end of last line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t insert 3.40 ABC + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLine 3ABC\n" + +test btree-2.1 {basic deletions} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 1.0 1.3 + .t get 1.0 1000000.0 +} "e 1\nLine 2\nLine 3\n" +test btree-2.2 {basic deletions} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 2.2 + .t get 1.0 1000000.0 +} "Line 1\nLie 2\nLine 3\n" +test btree-2.3 {basic deletions} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 2.0 2.3 + .t get 1.0 1000000.0 +} "Line 1\ne 2\nLine 3\n" +test btree-2.4 {deleting whole lines} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 1.2 3.0 + .t get 1.0 1000000.0 +} "LiLine 3\n" +test btree-2.5 {deleting whole lines} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\n\n\nLine 5" + .t delete 1.0 5.2 + .t get 1.0 1000000.0 +} "ne 5\n" +test btree-2.6 {deleting before start of file} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 0.3 1.2 + .t get 1.0 1000000.0 +} "ne 1\nLine 2\nLine 3\n" +test btree-2.7 {deleting after end of file} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 10.3 + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLine 3\n" +test btree-2.8 {deleting before start of line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 3.-1 3.3 + .t get 1.0 1000000.0 +} "Line 1\nLine 2\ne 3\n" +test btree-2.9 {deleting before start of line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 1.-1 1.0 + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLine 3\n" +test btree-2.10 {deleting after end of line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 1.8 2.1 + .t get 1.0 1000000.0 +} "Line 1ine 2\nLine 3\n" +test btree-2.11 {deleting after end of last line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 3.8 4.1 + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLine 3\n" +test btree-2.12 {deleting before start of file} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 1.8 0.0 + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLine 3\n" +test btree-2.13 {deleting past end of file} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 1.8 4.0 + .t get 1.0 1000000.0 +} "Line 1\n" +test btree-2.14 {deleting with end before start of line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 1.3 2.-3 + .t get 1.0 1000000.0 +} "LinLine 2\nLine 3\n" +test btree-2.15 {deleting past end of line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 1.3 1.9 + .t get 1.0 1000000.0 +} "Lin\nLine 2\nLine 3\n" +test btree-2.16 {deleting past end of line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 3.2 3.15 + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLi\n" +test btree-2.17 {deleting past end of line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 3.0 3.15 + .t get 1.0 1000000.0 +} "Line 1\nLine 2\n\n" +test btree-2.18 {deleting past end of line} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 1.0 3.15 + .t get 1.0 1000000.0 +} "\n" +test btree-2.19 {deleting with negative range} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 3.2 2.4 + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLine 3\n" +test btree-2.20 {deleting with negative range} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 3.2 3.1 + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLine 3\n" +test btree-2.21 {deleting with negative range} { + .t delete 1.0 100000.0 + .t insert 1.0 "Line 1\nLine 2\nLine 3" + .t delete 3.2 3.2 + .t get 1.0 1000000.0 +} "Line 1\nLine 2\nLine 3\n" + +proc setup {} { + .t delete 1.0 100000.0 + .t tag delete x y + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 1.1 + .t tag add x 1.5 1.13 + .t tag add x 2.2 2.6 + .t tag add y 1.5 +} + +test btree-3.1 {inserting with tags} { + setup + .t insert 1.0 XXX + list [.t tag ranges x] [.t tag ranges y] +} {{1.4 1.5 1.8 1.16 2.2 2.6} {1.8 1.9}} +test btree-3.2 {inserting with tags} { + setup + .t insert 1.15 YYY + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 1.5 1.13 2.2 2.6} {1.5 1.6}} +test btree-3.3 {inserting with tags} { + setup + .t insert 1.7 ZZZZ + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 1.5 1.17 2.2 2.6} {1.5 1.6}} +test btree-3.4 {inserting with tags} { + setup + .t insert 1.7 \n\n + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 1.5 3.6 4.2 4.6} {1.5 1.6}} +test btree-3.5 {inserting with tags} { + setup + .t insert 1.5 A\n + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 2.0 2.8 3.2 3.6} {2.0 2.1}} +test btree-3.6 {inserting with tags} { + setup + .t insert 1.13 A\n + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 1.5 1.13 3.2 3.6} {1.5 1.6}} + +test btree-4.1 {deleting with tags} { + setup + .t delete 1.6 1.9 + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 1.5 1.10 2.2 2.6} {1.5 1.6}} +test btree-4.2 {deleting with tags} { + setup + .t delete 1.1 2.3 + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.4} {}} +test btree-4.3 {deleting with tags} { + setup + .t delete 1.4 2.1 + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 1.5 1.9} {}} +test btree-4.4 {deleting with tags} { + setup + .t delete 1.14 2.1 + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 1.5 1.13 1.15 1.19} {1.5 1.6}} +test btree-4.5 {deleting with tags} { + setup + .t delete 1.0 2.10 + list [.t tag ranges x] [.t tag ranges y] +} {{} {}} +test btree-4.6 {deleting with tags} { + setup + .t delete 1.0 1.5 + list [.t tag ranges x] [.t tag ranges y] +} {{1.0 1.8 2.2 2.6} {1.0 1.1}} +test btree-4.7 {deleting with tags} { + setup + .t delete 1.6 1.9 + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 1.5 1.10 2.2 2.6} {1.5 1.6}} +test btree-4.8 {deleting with tags} { + setup + .t delete 1.5 1.13 + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 2.2 2.6} {}} + +set bigText1 {} +for {set i 0} {$i < 10} {incr i} { + append bigText1 "Line $i\n" +} +set bigText2 {} +for {set i 0} {$i < 200} {incr i} { + append bigText2 "Line $i\n" +} +test btree-5.1 {very large inserts, with tags} { + setup + .t insert 1.0 $bigText1 + list [.t tag ranges x] [.t tag ranges y] +} {{11.1 11.2 11.5 11.13 12.2 12.6} {11.5 11.6}} +test btree-5.2 {very large inserts, with tags} { + setup + .t insert 1.2 $bigText2 + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 1.2 201.3 201.11 202.2 202.6} {201.3 201.4}} +test btree-5.3 {very large inserts, with tags} { + setup + for {set i 0} {$i < 200} {incr i} { + .t insert 1.8 "longer line $i\n" + } + list [.t tag ranges x] [.t tag ranges y] [.t get 1.0 1.100] [.t get 198.0 198.100] +} {{1.1 1.2 1.5 201.5 202.2 202.6} {1.5 1.6} {Text forlonger line 199} {longer line 2}} + +test btree-6.1 {very large deletes, with tags} { + setup + .t insert 1.1 $bigText2 + .t delete 1.2 201.2 + list [.t tag ranges x] [.t tag ranges y] +} {{1.4 1.12 2.2 2.6} {1.4 1.5}} +test btree-6.2 {very large deletes, with tags} { + setup + .t insert 1.1 $bigText2 + for {set i 0} {$i < 200} {incr i} { + .t delete 1.2 2.2 + } + list [.t tag ranges x] [.t tag ranges y] +} {{1.4 1.12 2.2 2.6} {1.4 1.5}} +test btree-6.3 {very large deletes, with tags} { + setup + .t insert 1.1 $bigText2 + .t delete 2.3 10000.0 + .t get 1.0 1000.0 +} {TLine 0 +Lin +} +test btree-6.4 {very large deletes, with tags} { + setup + .t insert 1.1 $bigText2 + for {set i 0} {$i < 100} {incr i} { + .t delete 30.0 31.0 + } + list [.t tag ranges x] [.t tag ranges y] +} {{101.0 101.1 101.4 101.12 102.2 102.6} {101.4 101.5}} +test btree-6.5 {very large deletes, with tags} { + setup + .t insert 1.1 $bigText2 + for {set i 0} {$i < 100} {incr i} { + set j [expr $i+2] + set k [expr 1+2*$i] + .t tag add x $j.1 $j.3 + .t tag add y $k.1 $k.6 + } + .t delete 2.0 200.0 + list [.t tag ranges x] [.t tag ranges y] +} {{3.0 3.1 3.4 3.12 4.2 4.6} {1.1 1.6 3.4 3.5}} +test btree-6.6 {very large deletes, with tags} { + setup + .t insert 1.1 $bigText2 + for {set i 0} {$i < 100} {incr i} { + set j [expr $i+2] + set k [expr 1+2*$i] + .t tag add x $j.1 $j.3 + .t tag add y $k.1 $k.6 + } + for {set i 199} {$i >= 2} {incr i -1} { + .t delete $i.0 [expr $i+1].0 + } + list [.t tag ranges x] [.t tag ranges y] +} {{3.0 3.1 3.4 3.12 4.2 4.6} {1.1 1.6 3.4 3.5}} + +.t delete 1.0 end +.t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" +set i 1 +foreach check { + {1.3 1.6 1.7 2.0 {1.3 1.6 1.7 2.0}} + {1.3 1.6 1.6 2.0 {1.3 2.0}} + {1.3 1.6 1.4 2.0 {1.3 2.0}} + {2.0 4.3 1.4 1.10 {1.4 1.10 2.0 4.3}} + {2.0 4.3 1.4 1.end {1.4 1.19 2.0 4.3}} + {2.0 4.3 1.4 2.0 {1.4 4.3}} + {2.0 4.3 1.4 3.0 {1.4 4.3}} + {1.2 1.3 1.6 1.7 1.end 2.0 2.4 2.7 3.0 4.0 1.1 4.2 {1.1 4.2}} + {1.2 1.3 1.6 1.7 1.end 2.0 2.4 2.7 3.0 4.0 1.3 4.2 {1.2 4.2}} + {1.2 1.3 1.6 1.7 1.end 2.0 2.4 2.7 3.0 4.0 1.1 3.0 {1.1 4.0}} + {1.2 1.3 1.6 1.7 1.end 2.0 2.4 2.7 3.0 4.0 1.2 3.0 {1.2 4.0}} +} { + test btree-7.$i {tag addition and removal} { + .t tag remove x 1.0 end + while {[llength $check] > 2} { + .t tag add x [lindex $check 0] [lindex $check 1] + set check [lrange $check 2 end] + } + .t tag ranges x + } [lindex $check [expr [llength $check]-1]] + incr i +} + +test btree-8.1 {tag addition and removal, weird ranges} { + .t delete 1.0 100000.0 + .t tag delete x + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 0.0 1.3 + .t tag ranges x +} {1.0 1.3} +test btree-8.2 {tag addition and removal, weird ranges} { + .t delete 1.0 100000.0 + .t tag delete x + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 1.40 2.4 + .t tag ranges x +} {1.19 2.4} +test btree-8.3 {tag addition and removal, weird ranges} { + .t delete 1.0 100000.0 + .t tag delete x + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 4.40 4.41 + .t tag ranges x +} {} +test btree-8.4 {tag addition and removal, weird ranges} { + .t delete 1.0 100000.0 + .t tag delete x + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 5.1 5.2 + .t tag ranges x +} {} +test btree-8.5 {tag addition and removal, weird ranges} { + .t delete 1.0 100000.0 + .t tag delete x + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 1.1 9.0 + .t tag ranges x +} {1.1 5.0} +test btree-8.6 {tag addition and removal, weird ranges} { + .t delete 1.0 100000.0 + .t tag delete x + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 1.1 1.90 + .t tag ranges x +} {1.1 1.19} +test btree-8.7 {tag addition and removal, weird ranges} { + .t delete 1.0 100000.0 + .t tag delete x + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 1.1 4.90 + .t tag ranges x +} {1.1 4.17} +test btree-8.8 {tag addition and removal, weird ranges} { + .t delete 1.0 100000.0 + .t tag delete x + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 3.0 3.0 + .t tag ranges x +} {} + +test btree-9.1 {tag names} { + setup + .t tag names +} {sel x y} +test btree-9.2 {tag names} { + setup + .t tag add tag1 1.8 + .t tag add tag2 1.8 + .t tag add tag3 1.7 1.9 + .t tag names 1.8 +} {x tag1 tag2 tag3} +test btree-9.3 {lots of tag names} { + setup + .t insert 1.2 $bigText2 + foreach i {tag1 foo ThisOne {x space} q r s t} { + .t tag add $i 150.2 + } + foreach i {u tagA tagB tagC and more {$} \{} { + .t tag add $i 150.1 150.3 + } + .t tag names 150.2 +} {tag1 foo ThisOne {x space} q r s t u tagA tagB tagC and more {$} \{} +test btree-9.4 {lots of tag names} { + setup + .t insert 1.2 $bigText2 + .t tag delete tag1 foo ThisOne more {x space} q r s t u + .t tag delete tagA tagB tagC and {$} \{ more + foreach i {tag1 foo ThisOne more {x space} q r s t} { + .t tag add $i 150.2 + } + foreach i {foo ThisOne u tagA tagB tagC and more {$} \{} { + .t tag add $i 150.4 + } + .t tag delete tag1 more q r tagA + .t tag names 150.2 +} {foo ThisOne {x space} s t} + +proc msetup {} { + .t delete 1.0 100000.0 + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t mark set m1 1.2 + .t mark set l1 1.2 + .t mark gravity l1 left + .t mark set next 1.6 + .t mark set x 1.6 + .t mark set m2 2.0 + .t mark set m3 2.100 + .t tag add x 1.3 1.8 +} +test btree-10.1 {basic mark facilities} { + msetup + list [lsort [.t mark names]] [.t index m1] [.t index m2] [.t index m3] +} {{current insert l1 m1 m2 m3 next x} 1.2 2.0 2.11} +test btree-10.2 {basic mark facilities} { + msetup + .t mark unset m2 + lsort [.t mark names] +} {current insert l1 m1 m3 next x} +test btree-10.3 {basic mark facilities} { + msetup + .t mark set m2 1.8 + list [lsort [.t mark names]] [.t index m1] [.t index m2] [.t index m3] +} {{current insert l1 m1 m2 m3 next x} 1.2 1.8 2.11} + +test btree-11.1 {marks and inserts} { + msetup + .t insert 1.1 abcde + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.7 1.7 1.11 1.11 2.0 2.11} +test btree-11.2 {marks and inserts} { + msetup + .t insert 1.2 abcde + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.2 1.7 1.11 1.11 2.0 2.11} +test btree-11.3 {marks and inserts} { + msetup + .t insert 1.3 abcde + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.2 1.2 1.11 1.11 2.0 2.11} +test btree-11.4 {marks and inserts} { + msetup + .t insert 1.1 ab\n\ncde + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {3.4 3.4 3.8 3.8 4.0 4.11} +test btree-11.5 {marks and inserts} { + msetup + .t insert 1.4 ab\n\ncde + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.2 1.2 3.5 3.5 4.0 4.11} +test btree-11.6 {marks and inserts} { + msetup + .t insert 1.7 ab\n\ncde + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.2 1.2 1.6 1.6 4.0 4.11} + +test btree-12.1 {marks and deletes} { + msetup + .t delete 1.3 1.5 + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.2 1.2 1.4 1.4 2.0 2.11} +test btree-12.2 {marks and deletes} { + msetup + .t delete 1.3 1.8 + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.2 1.2 1.3 1.3 2.0 2.11} +test btree-12.3 {marks and deletes} { + msetup + .t delete 1.2 1.8 + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.2 1.2 1.2 1.2 2.0 2.11} +test btree-12.4 {marks and deletes} { + msetup + .t delete 1.1 1.8 + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.1 1.1 1.1 1.1 2.0 2.11} +test btree-12.5 {marks and deletes} { + msetup + .t delete 1.5 3.1 + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.2 1.2 1.5 1.5 1.5 1.5} +test btree-12.6 {marks and deletes} { + msetup + .t mark set m2 4.5 + .t delete 1.5 4.1 + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.2 1.2 1.5 1.5 1.9 1.5} +test btree-12.7 {marks and deletes} { + msetup + .t mark set m2 4.5 + .t mark set m3 4.5 + .t mark set m1 4.7 + .t delete 1.5 4.1 + list [.t index l1] [.t index m1] [.t index next] [.t index x] [.t index m2] [.t index m3] +} {1.2 1.11 1.5 1.5 1.9 1.9} + +destroy .t +text .t +test btree-13.1 {tag searching} { + .t delete 1.0 100000.0 + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag next x 2.2 2.1 +} {} +test btree-13.2 {tag searching} { + .t delete 1.0 100000.0 + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 2.2 2.4 + .t tag next x 2.2 2.3 +} {2.2 2.4} +test btree-13.3 {tag searching} { + .t delete 1.0 100000.0 + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 2.2 2.4 + .t tag next x 2.3 2.6 +} {} +test btree-13.4 {tag searching} { + .t delete 1.0 100000.0 + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 2.5 2.8 + .t tag next x 2.1 2.6 +} {2.5 2.8} +test btree-13.5 {tag searching} { + .t delete 1.0 100000.0 + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 2.5 2.8 + .t tag next x 2.1 2.5 +} {} +test btree-13.6 {tag searching} { + .t delete 1.0 100000.0 + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 2.1 2.4 + .t tag next x 2.5 2.8 +} {} +test btree-13.7 {tag searching} { + .t delete 1.0 100000.0 + .t insert 1.0 "Text for first line\nSecond line\n\nLast line of info" + .t tag add x 2.5 2.8 + .t tag next x 2.1 2.4 +} {} +test btree-13.8 {tag searching} { + setup + .t insert 1.2 $bigText2 + .t tag add x 190.3 191.2 + .t tag next x 3.5 +} {190.3 191.2} + +test btree-14.1 {check tag presence} { + setup + .t insert 1.2 $bigText2 + .t tag add x 3.5 3.7 + .t tag add y 133.9 141.5 + .t tag add z 1.5 180.2 + .t tag add q 141.4 142.3 + .t tag add x 130.2 145.1 + .t tag add a 141.0 + .t tag add b 4.3 + .t tag add b 7.5 + .t tag add b 140.3 + for {set i 120} {$i < 160} {incr i} { + .t tag add c $i.4 + } + foreach i {a1 a2 a3 a4 a5 a6 a7 a8 a9 10 a11 a12 a13} { + .t tag add $i 122.2 + } + .t tag add x 141.3 + .t tag names 141.1 +} {x y z} + +test btree-15.1 {rebalance with empty node} { + catch {destroy .t} + text .t + .t debug 1 + .t insert end "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23" + .t delete 6.0 12.0 + .t get 1.0 end +} "1\n2\n3\n4\n5\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n" + +proc setupBig {} { + .t delete 1.0 end + .t tag delete x y + .t tag configure x -foreground blue + .t tag configure y -underline true + # Create a Btree with 2002 lines (2000 + already existing + phantom at end) + # This generates a level 3 node with 9 children + # Most level 2 nodes cover 216 lines and have 6 children, except the last + # level 2 node covers 274 lines and has 7 children. + # Most level 1 nodes cover 36 lines and have 6 children, except the + # rightmost node has 58 lines and 9 children. + # Level 2: 2002 = 8*216 + 274 + # Level 1: 2002 = 54*36 + 58 + # Level 0: 2002 = 332*6 + 10 + for {set i 0} {$i < 2000} {incr i} { + append x "Line $i abcd efgh ijkl\n" + } + .t insert insert $x + .t debug 1 +} + +test btree-16.1 {add tag does not push root above level 0} { + catch {destroy .t} + text .t + setupBig + .t tag add x 1.1 1.10 + .t tag add x 5.1 5.10 + .t tag ranges x +} {1.1 1.10 5.1 5.10} +test btree-16.2 {add tag pushes root up to level 1 node} { + catch {destroy .t} + text .t + .t debug 1 + setupBig + .t tag add x 1.1 1.10 + .t tag add x 8.1 8.10 + .t tag ranges x +} {1.1 1.10 8.1 8.10} +test btree-16.3 {add tag pushes root up to level 2 node} { + .t tag remove x 1.0 end + .t tag add x 8.1 9.10 + .t tag add x 180.1 180.end + .t tag ranges x +} {8.1 9.10 180.1 180.23} +test btree-16.4 {add tag pushes root up to level 3 node} { + .t tag remove x 1.0 end + .t tag add y 1.1 2000.0 + .t tag add x 1.1 8.10 + .t tag add x 180.end 217.0 + list [.t tag ranges x] [.t tag ranges y] +} {{1.1 8.10 180.23 217.0} {1.1 2000.0}} +test btree-16.5 {add tag doesn't push root up} { + .t tag remove x 1.0 end + .t tag add x 1.1 8.10 + .t tag add x 2000.0 2000.3 + .t tag add x 180.end 217.0 + .t tag ranges x +} {1.1 8.10 180.23 217.0 2000.0 2000.3} +test btree-16.6 {two node splits at once pushes root up} { + .t delete 1.0 end + for {set i 1} {$i < 10} {incr i} { + .t insert end "Line $i\n" + } + .t tag add x 8.0 8.end + .t tag add y 9.0 end + set x {} + for {} {$i < 50} {incr i} { + append x "Line $i\n" + } + .t insert end $x y + list [.t tag ranges x] [.t tag ranges y] +} {{8.0 8.6} {9.0 51.0}} +# The following find bugs in the SearchStart procedures +test btree-16.7 {Partial tag remove from before first range} { + .t tag remove x 1.0 end + .t tag add x 2.0 2.6 + .t tag remove x 1.0 2.0 + .t tag ranges x +} {2.0 2.6} +test btree-16.8 {Partial tag remove from before first range} { + .t tag remove x 1.0 end + .t tag add x 2.0 2.6 + .t tag remove x 1.0 2.1 + .t tag ranges x +} {2.1 2.6} +test btree-16.9 {Partial tag remove from before first range} { + .t tag remove x 1.0 end + .t tag add x 2.0 2.6 + .t tag remove x 1.0 2.3 + .t tag ranges x +} {2.3 2.6} +test btree-16.10 {Partial tag remove from before first range} { + .t tag remove x 1.0 end + .t tag add x 1.0 2.6 + .t tag remove x 1.0 2.5 + .t tag ranges x +} {2.5 2.6} +test btree-16.11 {StartSearchBack boundary case} { + .t tag remove x 1.0 end + .t tag add x 1.3 1.4 + .t tag prevr x 2.0 1.4 +} {} +test btree-16.12 {StartSearchBack boundary case} { + .t tag remove x 1.0 end + .t tag add x 1.3 1.4 + .t tag prevr x 2.0 1.3 +} {1.3 1.4} +test btree-16.13 {StartSearchBack boundary case} { + .t tag remove x 1.0 end + .t tag add x 1.0 1.4 + .t tag prevr x 1.3 +} {1.0 1.4} + + +test btree-17.1 {remove tag does not push root down} { + catch {destroy .t} + text .t + .t debug 0 + setupBig + .t tag add x 1.1 5.10 + .t tag remove x 3.1 5.end + .t tag ranges x +} {1.1 3.1} +test btree-17.2 {remove tag pushes root from level 1 to level 0} { + .t tag remove x 1.0 end + .t tag add x 1.1 8.10 + .t tag remove x 3.1 end + .t tag ranges x +} {1.1 3.1} +test btree-17.3 {remove tag pushes root from level 2 to level 1} { + .t tag remove x 1.0 end + .t tag add x 1.1 180.10 + .t tag remove x 35.1 end + .t tag ranges x +} {1.1 35.1} +test btree-17.4 {remove tag doesn't change level 2} { + .t tag remove x 1.0 end + .t tag add x 1.1 180.10 + .t tag remove x 35.1 180.0 + .t tag ranges x +} {1.1 35.1 180.0 180.10} +test btree-17.5 {remove tag pushes root from level 3 to level 0} { + .t tag remove x 1.0 end + .t tag add x 1.1 1.10 + .t tag add x 2000.1 2000.10 + .t tag remove x 1.0 2000.0 + .t tag ranges x +} {2000.1 2000.10} +test btree-17.6 {text deletion pushes root from level 3 to level 0} { + .t tag remove x 1.0 end + .t tag add x 1.1 1.10 + .t tag add x 2000.1 2000.10 + .t delete 1.0 "1000.0 lineend +1 char" + .t tag ranges x +} {1000.1 1000.10} + +catch {destroy .t} +text .t +test btree-18.1 {tag search back, no tag} { + .t insert 1.0 "Line 1 abcd efgh ijkl\n" + .t tag prev x 1.1 1.1 +} {} +test btree-18.2 {tag search back, start at existing range} { + .t tag remove x 1.0 end + .t tag add x 1.1 1.4 + .t tag add x 1.8 1.11 + .t tag add x 1.16 + .t tag prev x 1.1 +} {} +test btree-18.3 {tag search back, end at existing range} { + .t tag remove x 1.0 end + .t tag add x 1.1 1.4 + .t tag add x 1.8 1.11 + .t tag add x 1.16 + .t tag prev x 1.3 1.1 +} {1.1 1.4} +test btree-18.4 {tag search back, start within range} { + .t tag remove x 1.0 end + .t tag add x 1.1 1.4 + .t tag add x 1.8 1.11 + .t tag add x 1.16 + .t tag prev x 1.10 1.0 +} {1.8 1.11} +test btree-18.5 {tag search back, start at end of range} { + .t tag remove x 1.0 end + .t tag add x 1.1 1.4 + .t tag add x 1.8 1.11 + .t tag add x 1.16 + list [.t tag prev x 1.4 1.0] [.t tag prev x 1.11 1.0] +} {{1.1 1.4} {1.8 1.11}} +test btree-18.6 {tag search back, start beyond range, same level 0 node} { + .t tag remove x 1.0 end + .t tag add x 1.1 1.4 + .t tag add x 1.8 1.11 + .t tag add x 1.16 + .t tag prev x 3.0 +} {1.16 1.17} +test btree-18.7 {tag search back, outside any range} { + .t tag remove x 1.0 end + .t tag add x 1.1 1.4 + .t tag add x 1.16 + .t tag prev x 1.8 1.5 +} {} +test btree-18.8 {tag search back, start at start of node boundary} { + setupBig + .t tag remove x 1.0 end + .t tag add x 2.5 2.8 + .t tag prev x 19.0 +} {2.5 2.8} +test btree-18.9 {tag search back, large complex btree spans} { + .t tag remove x 1.0 end + .t tag add x 1.3 1.end + .t tag add x 200.0 220.0 + .t tag add x 500.0 520.0 + list [.t tag prev x end] [.t tag prev x 433.0] +} {{500.0 520.0} {200.0 220.0}} + + +destroy .t diff --git a/tests/textDisp.test b/tests/textDisp.test new file mode 100644 index 0000000..c14f785 --- /dev/null +++ b/tests/textDisp.test @@ -0,0 +1,2868 @@ +# This file is a Tcl script to test the code in the file tkTextDisp.c. +# This file is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) textDisp.test 1.55 97/07/24 15:15:43 + +if {[string compare test [info procs test]] == 1} { + source defs + if {$testConfig(fonts) == 0} { + puts "skipping font-sensitive tests" + } +} + +# The procedure below is used as the scrolling command for the text; +# it just saves the scrolling information in a variable "scrollInfo". + +proc scroll args { + global scrollInfo + set scrollInfo $args +} + +# The procedure below is used to generate errors during scrolling commands. + +proc scrollError args { + error "scrolling error" +} + +# Create entries in the option database to be sure that geometry options +# like border width have predictable values. + +option add *Text.borderWidth 2 +option add *Text.highlightThickness 2 + +# The frame .f is needed to make sure that the overall window is always +# fairly wide, even if the text window is very narrow. This is needed +# because some window managers don't allow the overall width of a window +# to get very narrow. + +foreach i [winfo child .] { + destroy $i +} +frame .f -width 100 -height 20 +pack append . .f left + +if {$tcl_platform(platform) == "windows"} { + set fixedFont {Courier -14} +} else { + set fixedFont {Courier -12} +} +set fixedHeight [font metrics $fixedFont -linespace] +set fixedWidth [font measure $fixedFont m] + +set varFont {Times -14} +set bigFont {Helvetica -24} +text .t -font $fixedFont -width 20 -height 10 -yscrollcommand scroll +pack append . .t {top expand fill} +.t tag configure big -font $bigFont +.t debug on +wm geometry . {} + +# The statements below reset the main window; it's needed if the window +# manager is mwm to make mwm forget about a previous minimum size setting. + +wm withdraw . +wm minsize . 1 1 +wm positionfrom . user +wm deiconify . +update + +# Some window managers (like olwm under SunOS 4.1.3) misbehave in a way +# that tends to march windows off the top and left of the screen. If +# this happens, some tests will fail because parts of the window will +# not need to be displayed (because they're off-screen). To keep this +# from happening, move the window if it's getting near the left or top +# edges of the screen. + +if {([winfo rooty .] < 50) || ([winfo rootx .] < 50)} { + wm geom . +50+50 +} +test textDisp-1.1 {GetStyle procedure, priorities and tab stops} { + .t delete 1.0 end + .t insert 1.0 "x\ty" + .t tag delete x y z + .t tag configure x -tabs {50} + .t tag configure y -foreground black + .t tag configure z -tabs {70} + .t tag add x 1.0 1.end + .t tag add y 1.0 1.end + .t tag add z 1.0 1.end + update idletasks + set x [lindex [.t bbox 1.2] 0] + .t tag configure z -tabs {} + lappend x [lindex [.t bbox 1.2] 0] + .t tag configure z -tabs {30} + .t tag raise x + update idletasks + lappend x [lindex [.t bbox 1.2] 0] +} {75 55 55} +.t tag delete x y z +test textDisp-1.2 {GetStyle procedure, wrapmode} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "abcd\nefg hijkl mnop qrstuv wxyz" + .t tag configure x -wrap word + .t tag configure y -wrap none + .t tag raise y + update + set result [list [.t bbox 2.20]] + .t tag add x 2.0 2.1 + lappend result [.t bbox 2.20] + .t tag add y 1.end 2.2 + lappend result [.t bbox 2.20] +} {{5 31 7 13} {40 31 7 13} {}} +.t tag delete x y + +test textDisp-2.1 {LayoutDLine, basics} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "This is some sample text for testing." + list [.t bbox 1.19] [.t bbox 1.20] +} [list [list [expr 5 + $fixedWidth * 19] 5 $fixedWidth $fixedHeight] [list 5 [expr 5 + $fixedHeight] $fixedWidth $fixedHeight]] +test textDisp-2.2 {LayoutDLine, basics} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "This isx some sample text for testing." + list [.t bbox 1.19] [.t bbox 1.20] +} {{138 5 7 13} {5 18 7 13}} +test textDisp-2.3 {LayoutDLine, basics} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "This isxxx some sample text for testing." + list [.t bbox 1.19] [.t bbox 1.20] +} {{138 5 7 13} {5 18 7 13}} +test textDisp-2.4 {LayoutDLine, word wrap} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "This is some sample text for testing." + list [.t bbox 1.19] [.t bbox 1.20] +} {{138 5 7 13} {5 18 7 13}} +test textDisp-2.5 {LayoutDLine, word wrap} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "This isx some sample text for testing." + list [.t bbox 1.13] [.t bbox 1.14] [.t bbox 1.19] +} {{96 5 49 13} {5 18 7 13} {40 18 7 13}} +test textDisp-2.6 {LayoutDLine, word wrap} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "This isxxx some sample text for testing." + list [.t bbox 1.15] [.t bbox 1.16] +} {{110 5 35 13} {5 18 7 13}} +test textDisp-2.7 {LayoutDLine, marks and tags} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "This isxxx some sample text for testing." + .t tag add foo 1.4 1.6 + .t mark set insert 1.8 + list [.t bbox 1.2] [.t bbox 1.5] [.t bbox 1.11] +} {{19 5 7 13} {40 5 7 13} {82 5 7 13}} +foreach m [.t mark names] { + catch {.t mark unset $m} +} +scan [wm geom .] %dx%d width height +test textDisp-2.8 {LayoutDLine, extra chunk at end of dline} {fonts} { + wm geom . [expr $width+1]x$height + update + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "This isxx some sample text for testing." + .t mark set foo 1.20 + list [.t bbox 1.19] [.t bbox 1.20] +} {{138 5 8 13} {5 18 7 13}} +wm geom . {} +update +test textDisp-2.9 {LayoutDLine, marks and tags} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "This is a very_very_long_word_that_wraps." + list [.t bbox 1.9] [.t bbox 1.10] [.t bbox 1.25] +} {{68 5 77 13} {5 18 7 13} {110 18 7 13}} +test textDisp-2.10 {LayoutDLine, marks and tags} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "This is a very_very_long_word_that_wraps." + .t tag add foo 1.13 + .t tag add foo 1.15 + .t tag add foo 1.17 + .t tag add foo 1.19 + list [.t bbox 1.9] [.t bbox 1.10] [.t bbox 1.25] +} {{68 5 77 13} {5 18 7 13} {110 18 7 13}} +test textDisp-2.11 {LayoutDLine, newline width} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "a\nbb\nccc\ndddd" + list [.t bbox 2.2] [.t bbox 3.3] +} {{19 18 126 13} {26 31 119 13}} +test textDisp-2.12 {LayoutDLine, justification} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "\na\nbb\nccc\ndddd" + .t tag configure x -justify center + .t tag add x 1.0 end + .t tag add y 3.0 3.2 + list [.t bbox 1.0] [.t bbox 2.0] [.t bbox 4.0] [.t bbox 4.2] +} {{75 5 70 13} {71 18 7 13} {64 44 7 13} {78 44 7 13}} +test textDisp-2.13 {LayoutDLine, justification} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "\na\nbb\nccc\ndddd" + .t tag configure x -justify right + .t tag add x 1.0 end + .t tag add y 3.0 3.2 + list [.t bbox 1.0] [.t bbox 2.0] [.t bbox 4.0] [.t bbox 4.2] +} {{145 5 0 13} {138 18 7 13} {124 44 7 13} {138 44 7 13}} +test textDisp-2.14 {LayoutDLine, justification} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "\na\nbb\nccc\ndddd" + .t tag configure x -justify center + .t tag add x 2.0 3.1 + .t tag configure y -justify right + .t tag add y 3.0 4.0 + .t tag raise y + list [.t bbox 2.0] [.t bbox 3.0] [.t bbox 3.end] [.t bbox 4.0] +} {{71 18 7 13} {131 31 7 13} {145 31 0 13} {5 44 7 13}} +test textDisp-2.15 {LayoutDLine, justification} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "\na\nbb\nccc\ndddd" + .t tag configure x -justify center + .t tag add x 2.0 3.1 + .t tag configure y -justify right + .t tag add y 3.0 4.0 + .t tag lower y + list [.t bbox 2.0] [.t bbox 3.0] [.t bbox 3.end] [.t bbox 4.0] +} {{71 18 7 13} {68 31 7 13} {82 31 63 13} {5 44 7 13}} +test textDisp-2.16 {LayoutDLine, justification} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "Lots of long words, enough to force word wrap\nThen\nmore lines" + .t tag configure x -justify center + .t tag add x 1.1 1.20 + .t tag add x 1.21 1.end + list [.t bbox 1.0] [.t bbox 1.20] [.t bbox 1.36] [.t bbox 2.0] +} {{5 5 7 13} {5 18 7 13} {43 31 7 13} {5 44 7 13}} +test textDisp-2.17 {LayoutDLine, justification} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "Lots of long words, enough to force word wrap\nThen\nmore lines" + .t tag configure x -justify center + .t tag add x 1.20 + list [.t bbox 1.0] [.t bbox 1.20] [.t bbox 1.36] [.t bbox 2.0] +} {{5 5 7 13} {19 18 7 13} {5 31 7 13} {5 44 7 13}} +test textDisp-2.18 {LayoutDLine, justification} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "Lots of long words, enough to extend out of the window\n" + .t insert end "Then\nmore lines\nThat are shorter" + .t tag configure x -justify center + .t tag configure y -justify right + .t tag add x 2.0 + .t tag add y 3.0 + .t xview scroll 5 units + list [.t bbox 2.0] [.t bbox 3.0] +} {{26 18 7 13} {40 31 7 13}} +.t tag delete x +.t tag delete y +test textDisp-2.19 {LayoutDLine, margins} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "Lots of long words, enough to force word wrap\nThen\nmore lines" + .t tag configure x -lmargin1 20 -lmargin2 40 -rmargin 15 + .t tag add x 1.0 end + list [.t bbox 1.0] [.t bbox 1.12] [.t bbox 1.13] [.t bbox 2.0] +} {{25 5 7 13} {109 5 36 13} {45 18 7 13} {25 70 7 13}} +test textDisp-2.20 {LayoutDLine, margins} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "Lots of long words, enough to force word wrap\nThen\nmore lines" + .t tag configure x -lmargin1 20 -lmargin2 10 -rmargin 3 + .t tag configure y -lmargin1 15 -lmargin2 5 -rmargin 0 + .t tag raise y + .t tag add x 1.0 end + .t tag add y 1.13 + list [.t bbox 1.0] [.t bbox 1.13] [.t bbox 1.30] [.t bbox 2.0] +} {{25 5 7 13} {10 18 7 13} {15 31 7 13} {25 44 7 13}} +test textDisp-2.21 {LayoutDLine, margins} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "Sample text" + .t tag configure x -lmargin1 80 -lmargin2 80 -rmargin 100 + .t tag add x 1.0 end + list [.t bbox 1.0] [.t bbox 1.1] [.t bbox 1.2] +} {{85 5 60 13} {85 18 60 13} {85 31 60 13}} +.t tag delete x +.t tag delete y +test textDisp-2.22 {LayoutDLine, spacing options} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t tag delete x y + .t insert end "Short line\nLine 2 is long enough " + .t insert end "to wrap around a couple of times" + .t insert end "\nLine 3\nLine 4" + set i [.t dlineinfo 1.0] + set b1 [expr [lindex $i 1] + [lindex $i 4]] + set i [.t dlineinfo 2.0] + set b2 [expr [lindex $i 1] + [lindex $i 4]] + set i [.t dlineinfo 2.end] + set b3 [expr [lindex $i 1] + [lindex $i 4]] + set i [.t dlineinfo 3.0] + set b4 [expr [lindex $i 1] + [lindex $i 4]] + .t configure -spacing1 2 -spacing2 1 -spacing3 3 + set i [.t dlineinfo 1.0] + set b1 [expr [lindex $i 1] + [lindex $i 4] - $b1] + set i [.t dlineinfo 2.0] + set b2 [expr [lindex $i 1] + [lindex $i 4] - $b2] + set i [.t dlineinfo 2.end] + set b3 [expr [lindex $i 1] + [lindex $i 4] - $b3] + set i [.t dlineinfo 3.0] + set b4 [expr [lindex $i 1] + [lindex $i 4] - $b4] + list $b1 $b2 $b3 $b4 +} {2 7 10 15} +.t configure -spacing1 0 -spacing2 0 -spacing3 0 +test textDisp-2.23 {LayoutDLine, spacing options} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t tag delete x y + .t insert end "Short line\nLine 2 is long enough " + .t insert end "to wrap around a couple of times" + .t insert end "\nLine 3\nLine 4" + set i [.t dlineinfo 1.0] + set b1 [expr [lindex $i 1] + [lindex $i 4]] + set i [.t dlineinfo 2.0] + set b2 [expr [lindex $i 1] + [lindex $i 4]] + set i [.t dlineinfo 2.end] + set b3 [expr [lindex $i 1] + [lindex $i 4]] + set i [.t dlineinfo 3.0] + set b4 [expr [lindex $i 1] + [lindex $i 4]] + .t configure -spacing1 4 -spacing2 4 -spacing3 4 + .t tag configure x -spacing1 1 -spacing2 2 -spacing3 3 + .t tag add x 1.0 end + .t tag configure y -spacing1 0 -spacing2 3 + .t tag add y 2.19 end + .t tag raise y + set i [.t dlineinfo 1.0] + set b1 [expr [lindex $i 1] + [lindex $i 4] - $b1] + set i [.t dlineinfo 2.0] + set b2 [expr [lindex $i 1] + [lindex $i 4] - $b2] + set i [.t dlineinfo 2.end] + set b3 [expr [lindex $i 1] + [lindex $i 4] - $b3] + set i [.t dlineinfo 3.0] + set b4 [expr [lindex $i 1] + [lindex $i 4] - $b4] + list $b1 $b2 $b3 $b4 +} {1 5 13 16} +.t configure -spacing1 0 -spacing2 0 -spacing3 0 +test textDisp-2.24 {LayoutDLine, tabs, saving from first chunk} {fonts} { + .t delete 1.0 end + .t tag delete x y + .t tag configure x -tabs 70 + .t tag configure y -tabs 80 + .t insert 1.0 "ab\tcde" + .t tag add x 1.0 end + .t tag add y 1.1 end + lindex [.t bbox 1.3] 0 +} {75} +test textDisp-2.25 {LayoutDLine, tabs, breaking chunks at tabs} {fonts} { + .t delete 1.0 end + .t tag delete x + .t tag configure x -tabs {30 60 90 120} + .t insert 1.0 "a\tb\tc\td\te" + .t mark set dummy1 1.1 + .t mark set dummy2 1.2 + .t tag add x 1.0 end + list [lindex [.t bbox 1.2] 0] [lindex [.t bbox 1.4] 0] \ + [lindex [.t bbox 1.6] 0] [lindex [.t bbox 1.8] 0] +} {35 65 95 125} +test textDisp-2.26 {LayoutDLine, tabs, breaking chunks at tabs} {fonts} { + .t delete 1.0 end + .t tag delete x + .t tag configure x -tabs {30 60 90 120} -justify right + .t insert 1.0 "a\tb\tc\td\te" + .t mark set dummy1 1.1 + .t mark set dummy2 1.2 + .t tag add x 1.0 end + list [lindex [.t bbox 1.2] 0] [lindex [.t bbox 1.4] 0] \ + [lindex [.t bbox 1.6] 0] [lindex [.t bbox 1.8] 0] +} {117 124 131 138} +test textDisp-2.27 {LayoutDLine, tabs, calling AdjustForTab} {fonts} { + .t delete 1.0 end + .t tag delete x + .t tag configure x -tabs {30 60} + .t insert 1.0 "a\tb\tcd" + .t tag add x 1.0 end + list [lindex [.t bbox 1.2] 0] [lindex [.t bbox 1.4] 0] +} {35 65} +test textDisp-2.28 {LayoutDLine, tabs, running out of space in dline} {fonts} { + .t delete 1.0 end + .t insert 1.0 "a\tb\tc\td" + .t bbox 1.6 +} {5 18 7 13} +test textDisp-2.29 {LayoutDLine, tabs, running out of space in dline} {fonts} { + .t delete 1.0 end + .t insert 1.0 "a\tx\tabcd" + .t bbox 1.4 +} {117 5 7 13} +test textDisp-2.30 {LayoutDLine, tabs, running out of space in dline} {fonts} { + .t delete 1.0 end + .t insert 1.0 "a\tx\tabc" + .t bbox 1.4 +} {117 5 7 13} + +test textDisp-3.1 {different character sizes} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert end "Some sample text, including both large\n" + .t insert end "characters and\nsmall\n" + .t insert end "abc\nd\ne\nfghij" + .t tag add big 1.5 1.10 + .t tag add big 2.11 2.14 + list [.t bbox 1.1] [.t bbox 1.6] [.t dlineinfo 1.0] [.t dlineinfo 3.0] +} {{12 17 7 13} {52 5 13 27} {5 5 114 27 22} {5 85 35 13 10}} + +.t configure -wrap char +test textDisp-4.1 {UpdateDisplayInfo, basic} {fonts} { + .t delete 1.0 end + .t insert end "Line 1\nLine 2\nLine 3\n" + update + .t delete 2.0 2.end + .t insert 2.0 "New Line 2" + update + list [.t bbox 1.0] [.t bbox 2.0] [.t bbox 3.0] $tk_textRelayout +} {{5 5 7 13} {5 18 7 13} {5 31 7 13} 2.0} +test textDisp-4.2 {UpdateDisplayInfo, re-use tail of text line} {fonts} { + .t delete 1.0 end + .t insert end "Line 1\nLine 2 is so long that it wraps around\nLine 3" + update + .t mark set x 2.21 + .t delete 2.2 + .t insert 2.0 X + update + list [.t bbox 2.0] [.t bbox x] [.t bbox 3.0] $tk_textRelayout +} {{5 18 7 13} {12 31 7 13} {5 44 7 13} {2.0 2.20}} +test textDisp-4.3 {UpdateDisplayInfo, tail of text line shifts} {fonts} { + .t delete 1.0 end + .t insert end "Line 1\nLine 2 is so long that it wraps around\nLine 3" + update + .t mark set x 2.21 + .t delete 2.2 + update + list [.t bbox 2.0] [.t bbox x] [.t bbox 3.0] $tk_textRelayout +} {{5 18 7 13} {5 31 7 13} {5 44 7 13} {2.0 2.20}} +.t mark unset x +test textDisp-4.4 {UpdateDisplayInfo, wrap-mode "none"} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert end "Line 1\nLine 2 is so long that it wraps around\nLine 3" + update + list [.t bbox 2.0] [.t bbox 2.25] [.t bbox 3.0] $tk_textRelayout +} {{5 18 7 13} {} {5 31 7 13} {1.0 2.0 3.0}} +test textDisp-4.5 {UpdateDisplayInfo, tiny window} {fonts} { + wm geom . 103x$height + update + .t configure -wrap none + .t delete 1.0 end + .t insert end "Line 1\nLine 2 is so long that it wraps around\nLine 3" + update + list [.t bbox 2.0] [.t bbox 2.1] [.t bbox 3.0] $tk_textRelayout +} {{5 18 1 13} {} {5 31 1 13} {1.0 2.0 3.0}} +test textDisp-4.6 {UpdateDisplayInfo, tiny window} { + # This test was failing on Windows because the title bar on . + # was a certain minimum size and it was interfering with the size + # requested. The "overrideredirect" gets rid of the titlebar so + # the toplevel can shrink to the appropriate size. On Unix, setting + # the overrideredirect on "." confuses the window manager and + # causes subsequent tests to fail. + + if {$tcl_platform(platform) == "windows"} { + wm overrideredirect . 1 + } + frame .f2 -width 20 -height 100 + pack before .f .f2 top + wm geom . 103x103 + update + .t configure -wrap none -borderwidth 2 + .t delete 1.0 end + .t insert end "Line 1\nLine 2 is so long that it wraps around\nLine 3" + update + set x [list [.t bbox 1.0] [.t bbox 2.0] $tk_textRelayout] + wm overrideredirect . 0 + update + set x +} {{5 5 1 1} {} 1.0} +catch {destroy .f2} +.t configure -borderwidth 0 -wrap char +wm geom . {} +update +test textDisp-4.7 {UpdateDisplayInfo, filling in extra vertical space} { + # This test was failing on Windows because the title bar on . + # was a certain minimum size and it was interfering with the size + # requested. The "overrideredirect" gets rid of the titlebar so + # the toplevel can shrink to the appropriate size. On Unix, setting + # the overrideredirect on "." confuses the window manager and + # causes subsequent tests to fail. + + if {$tcl_platform(platform) == "windows"} { + wm overrideredirect . 1 + } + .t delete 1.0 end + .t insert end "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17" + .t yview 1.0 + update + .t yview 16.0 + update + set x [list [.t index @0,0] $tk_textRelayout $tk_textRedraw] + wm overrideredirect . 0 + update + set x +} {8.0 {16.0 17.0 15.0 14.0 13.0 12.0 11.0 10.0 9.0 8.0} {8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0 16.0 17.0}} +test textDisp-4.8 {UpdateDisplayInfo, filling in extra vertical space} { + .t delete 1.0 end + .t insert end "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17" + .t yview 16.0 + update + .t delete 5.0 14.0 + update + set x [list [.t index @0,0] $tk_textRelayout $tk_textRedraw] +} {1.0 {5.0 4.0 3.0 2.0 1.0} {1.0 2.0 3.0 4.0 5.0 eof}} +test textDisp-4.9 {UpdateDisplayInfo, filling in extra vertical space} {fonts} { + .t delete 1.0 end + .t insert end "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17" + .t yview 16.0 + update + .t delete 15.0 end + list [.t bbox 7.0] [.t bbox 12.0] +} {{3 29 7 13} {3 94 7 13}} +test textDisp-4.10 {UpdateDisplayInfo, filling in extra vertical space} { + .t delete 1.0 end + .t insert end "1\n2\n3\n4\n5\nLine 6 is such a long line that it wraps around.\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17" + .t yview end + update + .t delete 13.0 end + update + list [.t index @0,0] $tk_textRelayout $tk_textRedraw +} {5.0 {12.0 7.0 6.40 6.20 6.0 5.0} {5.0 6.0 6.20 6.40 7.0 12.0}} +test textDisp-4.11 {UpdateDisplayInfo, filling in extra vertical space} { + .t delete 1.0 end + .t insert end "1\n2\n3\n4\n5\nLine 6 is such a long line that it wraps around, not once but really quite a few times.\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17" + .t yview end + update + .t delete 14.0 end + update + list [.t index @0,0] $tk_textRelayout $tk_textRedraw +} {6.40 {13.0 7.0 6.80 6.60 6.40} {6.40 6.60 6.80 7.0 13.0}} +test textDisp-4.12 {UpdateDisplayInfo, filling in extra vertical space} { + .t delete 1.0 end + .t insert end "1\n2\n3\n4\n5\n7\n8\n9\n10\n11\n12" + button .b -text "Test" -bd 2 -highlightthickness 2 + .t window create 3.end -window .b + .t yview moveto 1 + update + .t yview moveto 0 + update + .t yview moveto 1 + update + winfo ismapped .b +} {0} +.t configure -wrap word +.t delete 1.0 end +.t insert end "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\n" +.t insert end "Line 8\nLine 9\nLine 10\nLine 11\nLine 12\nLine 13\n" +.t insert end "Line 14\nLine 15\nLine 16" +.t tag delete x +.t tag configure x -relief raised -borderwidth 2 -background white +test textDisp-4.13 {UpdateDisplayInfo, special handling for top/bottom lines} { + .t tag add x 1.0 end + .t yview 1.0 + update + .t yview scroll 3 units + update + list $tk_textRelayout $tk_textRedraw +} {{11.0 12.0 13.0} {4.0 10.0 11.0 12.0 13.0}} +test textDisp-4.14 {UpdateDisplayInfo, special handling for top/bottom lines} { + .t tag remove x 1.0 end + .t yview 1.0 + update + .t yview scroll 3 units + update + list $tk_textRelayout $tk_textRedraw +} {{11.0 12.0 13.0} {11.0 12.0 13.0}} +test textDisp-4.15 {UpdateDisplayInfo, special handling for top/bottom lines} { + .t tag add x 1.0 end + .t yview 4.0 + update + .t yview scroll -2 units + update + list $tk_textRelayout $tk_textRedraw +} {{2.0 3.0} {2.0 3.0 4.0 11.0}} +test textDisp-4.16 {UpdateDisplayInfo, special handling for top/bottom lines} { + .t tag remove x 1.0 end + .t yview 4.0 + update + .t yview scroll -2 units + update + list $tk_textRelayout $tk_textRedraw +} {{2.0 3.0} {2.0 3.0}} +test textDisp-4.17 {UpdateDisplayInfo, horizontal scrolling} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert end "Short line 1\nLine 2 is long enough to scroll horizontally" + .t insert end "\nLine 3\nLine 4" + update + .t xview scroll 3 units + update + list $tk_textRelayout $tk_textRedraw [.t bbox 2.0] [.t bbox 2.5] \ + [.t bbox 2.23] +} {{} {1.0 2.0 3.0 4.0} {} {17 16 7 13} {}} +test textDisp-4.18 {UpdateDisplayInfo, horizontal scrolling} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert end "Short line 1\nLine 2 is long enough to scroll horizontally" + .t insert end "\nLine 3\nLine 4" + update + .t xview scroll 100 units + update + list $tk_textRelayout $tk_textRedraw [.t bbox 2.25] +} {{} {1.0 2.0 3.0 4.0} {10 16 7 13}} +test textDisp-4.19 {UpdateDisplayInfo, horizontal scrolling} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert end "Short line 1\nLine 2 is long enough to scroll horizontally" + .t insert end "\nLine 3\nLine 4" + update + .t xview moveto 0 + .t xview scroll -10 units + update + list $tk_textRelayout $tk_textRedraw [.t bbox 2.5] +} {{} {1.0 2.0 3.0 4.0} {38 16 7 13}} +test textDisp-4.20 {UpdateDisplayInfo, horizontal scrolling} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert end "Short line 1\nLine 2 is long enough to scroll horizontally" + .t insert end "\nLine 3\nLine 4" + .t xview moveto 0.0 + .t xview scroll 100 units + update + .t delete 2.30 2.44 + update + list $tk_textRelayout $tk_textRedraw [.t bbox 2.25] +} {2.0 {1.0 2.0 3.0 4.0} {108 16 7 13}} +test textDisp-4.21 {UpdateDisplayInfo, horizontal scrolling} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert end "Short line 1\nLine 2 is long enough to scroll horizontally" + .t insert end "\nLine 3\nLine 4" + .t xview moveto .9 + update + .t xview moveto .6 + update + list $tk_textRelayout $tk_textRedraw +} {{} {}} +test textDisp-4.22 {UpdateDisplayInfo, no horizontal scrolling except for -wrap none} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert end "Short line 1\nLine 2 is long enough to scroll horizontally" + .t insert end "\nLine 3\nLine 4" + .t xview scroll 25 units + update + .t configure -wrap word + list [.t bbox 2.0] [.t bbox 2.16] +} {{3 16 7 13} {10 29 7 13}} +test textDisp-4.23 {UpdateDisplayInfo, no horizontal scrolling except for -wrap none} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert end "Short line 1\nLine 2 is long enough to scroll horizontally" + .t insert end "\nLine 3\nLine 4" + .t xview scroll 25 units + update + .t configure -wrap char + list [.t bbox 2.0] [.t bbox 2.16] +} {{3 16 7 13} {115 16 7 13}} + +test textDisp-5.1 {DisplayDLine, handling of spacing} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "abcdefghijkl\nmnopqrstuvwzyz" + .t tag configure spacing -spacing1 8 -spacing3 2 + .t tag add spacing 1.0 end + frame .t.f1 -width 10 -height 4 -bg black + frame .t.f2 -width 10 -height 4 -bg black + frame .t.f3 -width 10 -height 4 -bg black + frame .t.f4 -width 10 -height 4 -bg black + .t window create 1.3 -window .t.f1 -align top + .t window create 1.7 -window .t.f2 -align center + .t window create 2.1 -window .t.f3 -align bottom + .t window create 2.10 -window .t.f4 -align baseline + update + list [winfo geometry .t.f1] [winfo geometry .t.f2] \ + [winfo geometry .t.f3] [winfo geometry .t.f4] +} {10x4+24+11 10x4+55+15 10x4+10+43 10x4+76+40} +.t tag delete spacing + +# Although the following test produces a useful result, its main +# effect is to produce a core dump if Tk doesn't handle display +# relayout that occurs during redisplay. + +test textDisp-5.2 {DisplayDLine, line resizes during display} { + .t delete 1.0 end + frame .t.f -width 20 -height 20 -bd 2 -relief raised + bind .t.f <Configure> {.t.f configure -width 30 -height 30} + .t window create insert -window .t.f + update + list [winfo width .t.f] [winfo height .t.f] +} {30 30} + +.t configure -wrap char +test textDisp-6.1 {scrolling in DisplayText, scroll up} { + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t delete 2.0 3.0 + update + list $tk_textRelayout $tk_textRedraw +} {{2.0 10.0} {2.0 10.0}} +test textDisp-6.2 {scrolling in DisplayText, scroll down} { + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t insert 2.0 "New Line 2\n" + update + list $tk_textRelayout $tk_textRedraw +} {{2.0 3.0} {2.0 3.0}} +test textDisp-6.3 {scrolling in DisplayText, multiple scrolls} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t insert 2.end "is so long that it wraps" + .t insert 4.end "is so long that it wraps" + update + list $tk_textRelayout $tk_textRedraw +} {{2.0 2.20 4.0 4.20} {2.0 2.20 4.0 4.20}} +test textDisp-6.4 {scrolling in DisplayText, scrolls interfere} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t insert 2.end "is so long that it wraps around, not once but three times" + .t insert 4.end "is so long that it wraps" + update + list $tk_textRelayout $tk_textRedraw +} {{2.0 2.20 2.40 2.60 4.0 4.20} {2.0 2.20 2.40 2.60 4.0 4.20 6.0}} +test textDisp-6.5 {scrolling in DisplayText, scroll source obscured} {nonPortable} { + .t configure -wrap char + frame .f2 -bg red + place .f2 -in .t -relx 0.5 -rely 0.5 -relwidth 0.5 -relheight 0.5 + .t delete 1.0 end + .t insert 1.0 "Line 1 is so long that it wraps around, a couple of times" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t delete 1.6 1.end + update + destroy .f2 + list $tk_textRelayout $tk_textRedraw +} {{1.0 9.0 10.0} {1.0 4.0 5.0 9.0 10.0}} +test textDisp-6.6 {scrolling in DisplayText, Expose events after scroll} {unixOnly nonPortable} { + # this test depends on all of the expose events being handled at once + .t configure -wrap char + frame .f2 -bg #ff0000 + place .f2 -in .t -relx 0.2 -rely 0.5 -relwidth 0.5 -relheight 0.5 + .t configure -bd 2 -relief raised + .t delete 1.0 end + .t insert 1.0 "Line 1 is so long that it wraps around, a couple of times" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t delete 1.6 1.end + destroy .f2 + update + list $tk_textRelayout $tk_textRedraw +} {{1.0 9.0 10.0} {borders 1.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0}} +.t configure -bd 0 +test textDisp-6.7 {DisplayText, vertical scrollbar updates} { + .t configure -wrap char + .t delete 1.0 end + update + set scrollInfo +} {0 1} +test textDisp-6.8 {DisplayText, vertical scrollbar updates} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1" + update + set scrollInfo "unchanged" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13} { + .t insert end "\nLine $i" + } + update + set scrollInfo +} {0 0.769231} +.t configure -yscrollcommand {} -xscrollcommand scroll +test textDisp-6.9 {DisplayText, horizontal scrollbar updates} { + .t configure -wrap none + .t delete 1.0 end + update + set scrollInfo unchanged + .t insert end xxxxxxxxx\n + .t insert end xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n + .t insert end xxxxxxxxxxxxxxxxxxxxxxxxxx + update + set scrollInfo +} {0 0.363636} + +# The following group of tests is marked non-portable because +# they result in a lot of extra redisplay under Ultrix. I don't +# know why this is so. + +.t configure -bd 2 -relief raised -wrap char +.t delete 1.0 end +.t insert 1.0 "Line 1 is so long that it wraps around, a couple of times" +foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" +} +test textDisp-7.1 {TkTextRedrawRegion} {nonPortable} { + frame .f2 -bg #ff0000 + place .f2 -in .t -relx 0.2 -relwidth 0.6 -rely 0.22 -relheight 0.55 + update + destroy .f2 + update + list $tk_textRelayout $tk_textRedraw +} {{} {1.40 2.0 3.0 4.0 5.0 6.0}} +test textDisp-7.2 {TkTextRedrawRegion} {nonPortable} { + frame .f2 -bg #ff0000 + place .f2 -in .t -relx 0 -relwidth 0.5 -rely 0 -relheight 0.5 + update + destroy .f2 + update + list $tk_textRelayout $tk_textRedraw +} {{} {borders 1.0 1.20 1.40 2.0 3.0}} +test textDisp-7.3 {TkTextRedrawRegion} {nonPortable} { + frame .f2 -bg #ff0000 + place .f2 -in .t -relx 0.5 -relwidth 0.5 -rely 0.5 -relheight 0.5 + update + destroy .f2 + update + list $tk_textRelayout $tk_textRedraw +} {{} {borders 4.0 5.0 6.0 7.0 8.0}} +test textDisp-7.4 {TkTextRedrawRegion} {nonPortable} { + frame .f2 -bg #ff0000 + place .f2 -in .t -relx 0.4 -relwidth 0.2 -rely 0 -relheight 0.2 \ + -bordermode ignore + update + destroy .f2 + update + list $tk_textRelayout $tk_textRedraw +} {{} {borders 1.0 1.20}} +test textDisp-7.5 {TkTextRedrawRegion} {nonPortable} { + frame .f2 -bg #ff0000 + place .f2 -in .t -relx 0.4 -relwidth 0.2 -rely 1.0 -relheight 0.2 \ + -anchor s -bordermode ignore + update + destroy .f2 + update + list $tk_textRelayout $tk_textRedraw +} {{} {borders 7.0 8.0}} +test textDisp-7.6 {TkTextRedrawRegion} {nonPortable} { + frame .f2 -bg #ff0000 + place .f2 -in .t -relx 0 -relwidth 0.2 -rely 0.55 -relheight 0.2 \ + -anchor w -bordermode ignore + update + destroy .f2 + update + list $tk_textRelayout $tk_textRedraw +} {{} {borders 3.0 4.0 5.0}} +test textDisp-7.7 {TkTextRedrawRegion} {nonPortable} { + frame .f2 -bg #ff0000 + place .f2 -in .t -relx 1.0 -relwidth 0.2 -rely 0.55 -relheight 0.2 \ + -anchor e -bordermode ignore + update + destroy .f2 + update + list $tk_textRelayout $tk_textRedraw +} {{} {borders 3.0 4.0 5.0}} +test textDisp-7.8 {TkTextRedrawRegion} {nonPortable} { + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\n" + frame .f2 -bg #ff0000 + place .f2 -in .t -relx 0.0 -relwidth 0.4 -rely 0.35 -relheight 0.4 \ + -anchor nw -bordermode ignore + update + destroy .f2 + update + list $tk_textRelayout $tk_textRedraw +} {{} {borders 4.0 5.0 6.0 7.0 eof}} +.t configure -bd 0 + +test textDisp-8.1 {TkTextChanged: redisplay whole lines} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is so long that it wraps around, two times" + foreach i {3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t delete 2.36 2.38 + update + list $tk_textRelayout $tk_textRedraw [.t bbox 2.32] +} {{2.0 2.18 2.38} {2.0 2.18 2.38} {101 29 7 13}} +.t configure -wrap char +test textDisp-8.2 {TkTextChanged, redisplay whole lines} { + .t delete 1.0 end + .t insert 1.0 "Line 1 is so long that it wraps around, two times" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t insert 1.2 xx + update + list $tk_textRelayout $tk_textRedraw +} {{1.0 1.20 1.40} {1.0 1.20 1.40}} +test textDisp-8.3 {TkTextChanged} { + .t delete 1.0 end + .t insert 1.0 "Line 1 is so long that it wraps around, two times" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t insert 2.0 xx + update + list $tk_textRelayout $tk_textRedraw +} {2.0 2.0} +test textDisp-8.4 {TkTextChanged} { + .t delete 1.0 end + .t insert 1.0 "Line 1 is so long that it wraps around, two times" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t delete 1.5 + update + list $tk_textRelayout $tk_textRedraw +} {{1.0 1.20 1.40} {1.0 1.20 1.40}} +test textDisp-8.5 {TkTextChanged} { + .t delete 1.0 end + .t insert 1.0 "Line 1 is so long that it wraps around, two times" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t delete 1.40 1.44 + update + list $tk_textRelayout $tk_textRedraw +} {{1.0 1.20 1.40} {1.0 1.20 1.40}} +test textDisp-8.6 {TkTextChanged} { + .t delete 1.0 end + .t insert 1.0 "Line 1 is so long that it wraps around, two times" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t delete 1.41 1.44 + update + list $tk_textRelayout $tk_textRedraw +} {{1.0 1.20 1.40} {1.0 1.20 1.40}} +test textDisp-8.7 {TkTextChanged} { + .t delete 1.0 end + .t insert 1.0 "Line 1 is so long that it wraps around, two times" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t delete 1.2 1.end + update + list $tk_textRelayout $tk_textRedraw +} {{1.0 9.0 10.0} {1.0 9.0 10.0}} +test textDisp-8.8 {TkTextChanged} { + .t delete 1.0 end + .t insert 1.0 "Line 1 is so long that it wraps around, two times" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t delete 2.2 + update + list $tk_textRelayout $tk_textRedraw +} {2.0 2.0} +test textDisp-8.9 {TkTextChanged} { + .t delete 1.0 end + .t insert 1.0 "Line 1 is so long that it wraps around, two times" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + update + .t delete 2.0 3.0 + update + list $tk_textRelayout $tk_textRedraw +} {{2.0 8.0} {2.0 8.0}} +test textDisp-8.10 {TkTextChanged} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap\nLine 3 is also long enough to wrap\nLine 4" + .t tag add big 2.19 + update + .t delete 2.19 + update + set tk_textRedraw +} {2.0 2.20 eof} +test textDisp-8.11 {TkTextChanged, scrollbar notification when changes are off-screen} { + .t delete 1.0 end + .t insert end "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n" + .t configure -yscrollcommand scroll + update + set scrollInfo "" + .t insert end "a\nb\nc\n" + update + .t configure -yscrollcommand "" + set scrollInfo +} {0 0.625} + +test textDisp-9.1 {TkTextRedrawTag} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap around\nLine 3\nLine 4" + update + .t tag add big 2.2 2.4 + update + list $tk_textRelayout $tk_textRedraw +} {{2.0 2.18} {2.0 2.18}} +test textDisp-9.2 {TkTextRedrawTag} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap around\nLine 3\nLine 4" + update + .t tag add big 1.2 2.4 + update + list $tk_textRelayout $tk_textRedraw +} {{1.0 2.0 2.17} {1.0 2.0 2.17}} +test textDisp-9.3 {TkTextRedrawTag} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap around\nLine 3\nLine 4" + update + .t tag add big 2.2 2.4 + .t tag remove big 1.0 end + update + list $tk_textRelayout $tk_textRedraw +} {2.0 2.0} +test textDisp-9.4 {TkTextRedrawTag} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap around\nLine 3\nLine 4" + update + .t tag add big 2.2 2.20 + .t tag remove big 1.0 end + update + list $tk_textRelayout $tk_textRedraw +} {2.0 2.0} +test textDisp-9.5 {TkTextRedrawTag} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap around\nLine 3\nLine 4" + update + .t tag add big 2.2 2.end + .t tag remove big 1.0 end + update + list $tk_textRelayout $tk_textRedraw +} {{2.0 2.20} {2.0 2.20}} +test textDisp-9.6 {TkTextRedrawTag} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap\nLine 3 is also long enough to wrap\nLine 4" + update + .t tag add big 2.2 3.5 + .t tag remove big 1.0 end + update + list $tk_textRelayout $tk_textRedraw +} {{2.0 2.20 3.0} {2.0 2.20 3.0}} +test textDisp-9.7 {TkTextRedrawTag} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap\nLine 3 is also long enough to wrap\nLine 4" + .t tag add big 2.19 + update + .t tag remove big 2.19 + update + set tk_textRedraw +} {2.0 2.20 eof} +test textDisp-9.8 {TkTextRedrawTag} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap\nLine 3 is also long enough to wrap\nLine 4" + .t tag add big 1.0 2.0 + update + .t tag add big 2.0 2.5 + update + set tk_textRedraw +} {2.0 2.17} +test textDisp-9.9 {TkTextRedrawTag} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap\nLine 3 is also long enough to wrap\nLine 4" + .t tag add big 1.0 2.0 + update + .t tag add big 1.5 2.5 + update + set tk_textRedraw +} {2.0 2.17} +test textDisp-9.10 {TkTextRedrawTag} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap\nLine 3 is also long enough to wrap\nLine 4" + .t tag add big 1.0 2.0 + update + set tk_textRedraw {none} + .t tag add big 1.3 1.5 + update + set tk_textRedraw +} {none} +test textDisp-9.11 {TkTextRedrawTag} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap\nLine 3 is also long enough to wrap\nLine 4" + .t tag add big 1.0 2.0 + update + .t tag add big 1.0 2.0 + update + set tk_textRedraw +} {} + +test textDisp-10.1 {TkTextRelayoutWindow} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2 is long enough to wrap\nLine 3 is also long enough to wrap\nLine 4" + update + .t configure -bg black + update + list $tk_textRelayout $tk_textRedraw +} {{1.0 2.0 2.20 3.0 3.20 4.0} {borders 1.0 2.0 2.20 3.0 3.20 4.0 eof}} +.t configure -bg [lindex [.t configure -bg] 3] +test textDisp-10.2 {TkTextRelayoutWindow} { + toplevel .top -width 300 -height 200 + wm geometry .top +0+0 + text .top.t -font $fixedFont -width 20 -height 10 -relief raised -bd 2 + place .top.t -x 0 -y 0 -width 20 -height 20 + .top.t insert end "First line" + .top.t see insert + tkwait visibility .top.t + place .top.t -width 150 -height 100 + update + .top.t index @0,0 +} {1.0} +catch {destroy .top} + +.t delete 1.0 end +.t insert end "Line 1" +for {set i 2} {$i <= 200} {incr i} { + .t insert end "\nLine $i" +} +update +test textDisp-11.1 {TkTextSetYView} { + .t yview 30.0 + update + .t index @0,0 +} {30.0} +test textDisp-11.2 {TkTextSetYView} { + .t yview 30.0 + update + .t yview 32.0 + update + list [.t index @0,0] $tk_textRedraw +} {32.0 {40.0 41.0}} +test textDisp-11.3 {TkTextSetYView} { + .t yview 30.0 + update + .t yview 28.0 + update + list [.t index @0,0] $tk_textRedraw +} {28.0 {28.0 29.0}} +test textDisp-11.4 {TkTextSetYView} { + .t yview 30.0 + update + .t yview 31.4 + update + list [.t index @0,0] $tk_textRedraw +} {31.0 40.0} +test textDisp-11.5 {TkTextSetYView} { + .t yview 30.0 + update + set tk_textRedraw {} + .t yview -pickplace 31.0 + update + list [.t index @0,0] $tk_textRedraw +} {30.0 {}} +test textDisp-11.6 {TkTextSetYView} { + .t yview 30.0 + update + set tk_textRedraw {} + .t yview -pickplace 28.0 + update + list [.t index @0,0] $tk_textRedraw +} {28.0 {28.0 29.0}} +test textDisp-11.7 {TkTextSetYView} { + .t yview 30.0 + update + set tk_textRedraw {} + .t yview -pickplace 26.0 + update + list [.t index @0,0] $tk_textRedraw +} {22.0 {22.0 23.0 24.0 25.0 26.0 27.0 28.0 29.0}} +test textDisp-11.8 {TkTextSetYView} { + .t yview 30.0 + update + set tk_textRedraw {} + .t yview -pickplace 41.0 + update + list [.t index @0,0] $tk_textRedraw +} {32.0 {40.0 41.0}} +test textDisp-11.9 {TkTextSetYView} { + .t yview 30.0 + update + set tk_textRedraw {} + .t yview -pickplace 43.0 + update + list [.t index @0,0] $tk_textRedraw +} {39.0 {40.0 41.0 42.0 43.0 44.0 45.0 46.0 47.0 48.0}} +test textDisp-11.10 {TkTextSetYView} { + .t yview 30.0 + update + set tk_textRedraw {} + .t yview 10000.0 + update + list [.t index @0,0] $tk_textRedraw +} {191.0 {191.0 192.0 193.0 194.0 195.0 196.0 197.0 198.0 199.0 200.0}} +test textDisp-11.11 {TkTextSetYView} { + .t yview 195.0 + update + set tk_textRedraw {} + .t yview 197.0 + update + list [.t index @0,0] $tk_textRedraw +} {191.0 {191.0 192.0 193.0 194.0 195.0 196.0}} +test textDisp-11.12 {TkTextSetYView, wrapped line is off-screen} { + .t insert 10.0 "Long line with enough text to wrap\n" + .t yview 1.0 + update + set tk_textRedraw {} + .t see 10.30 + update + list [.t index @0,0] $tk_textRedraw +} {2.0 10.20} +.t delete 10.0 11.0 +test textDisp-11.13 {TkTestSetYView, partially-visible last line} { + catch {destroy .top} + toplevel .top + wm geometry .top +0+0 + text .top.t -width 20 -height 5 + pack .top.t + .top.t insert end "Line 1" + for {set i 2} {$i <= 100} {incr i} { + .top.t insert end "\nLine $i" + } + update + scan [wm geometry .top] "%dx%d" w2 h2 + wm geometry .top ${w2}x[expr $h2-2] + update + .top.t yview 1.0 + update + set tk_textRedraw {} + .top.t see 5.0 + update + list [.top.t index @0,0] $tk_textRedraw +} {2.0 {5.0 6.0}} +catch {destroy .top} +toplevel .top +wm geometry .top +0+0 +text .top.t -width 30 -height 3 +pack .top.t +.top.t insert end "Line 1" +for {set i 2} {$i <= 20} {incr i} { + .top.t insert end "\nLine $i" +} +update +test textDisp-11.14 {TkTextSetYView, only a few lines visible} { + .top.t yview 5.0 + update + .top.t see 10.0 + .top.t index @0,0 +} {8.0} +test textDisp-11.15 {TkTextSetYView, only a few lines visible} { + .top.t yview 5.0 + update + .top.t see 11.0 + .top.t index @0,0 +} {10.0} +test textDisp-11.16 {TkTextSetYView, only a few lines visible} { + .top.t yview 8.0 + update + .top.t see 5.0 + .top.t index @0,0 +} {5.0} +test textDisp-11.17 {TkTextSetYView, only a few lines visible} { + .top.t yview 8.0 + update + .top.t see 4.0 + .top.t index @0,0 +} {3.0} +destroy .top + +.t configure -wrap word +.t delete 50.0 51.0 +.t insert 50.0 "This is a long line, one that will wrap around twice.\n" +test textDisp-12.1 {MeasureUp} { + .t yview 100.0 + update + .t yview -pickplace 52.0 + update + .t index @0,0 +} {50.0} +test textDisp-12.2 {MeasureUp} { + .t yview 100.0 + update + .t yview -pickplace 53.0 + update + .t index @0,0 +} {50.15} +test textDisp-12.3 {MeasureUp} { + .t yview 100.0 + update + .t yview -pickplace 50.10 + update + .t index @0,0 +} {46.0} +.t configure -wrap none +test textDisp-12.4 {MeasureUp} { + .t yview 100.0 + update + .t yview -pickplace 53.0 + update + .t index @0,0 +} {49.0} +test textDisp-12.5 {MeasureUp} { + .t yview 100.0 + update + .t yview -pickplace 50.10 + update + .t index @0,0 +} {46.0} + +.t configure -wrap none +.t delete 1.0 end +for {set i 1} {$i < 99} {incr i} { + .t insert end "Line $i\n" +} +.t insert end "Line 100" +.t insert 30.end { is quite long, so that it flows way off the end of the window and we can use it to test out the horizontal positioning features of the "see" command.} +test textDisp-13.1 {TkTextSeeCmd procedure} { + list [catch {.t see} msg] $msg +} {1 {wrong # args: should be ".t see index"}} +test textDisp-13.2 {TkTextSeeCmd procedure} { + list [catch {.t see a b} msg] $msg +} {1 {wrong # args: should be ".t see index"}} +test textDisp-13.3 {TkTextSeeCmd procedure} { + list [catch {.t see badIndex} msg] $msg +} {1 {bad text index "badIndex"}} +test textDisp-13.4 {TkTextSeeCmd procedure} { + .t xview moveto 0 + .t yview moveto 0 + update + .t see 4.2 + .t index @0,0 +} {1.0} +test textDisp-13.5 {TkTextSeeCmd procedure} { + .t configure -wrap char + .t xview moveto 0 + .t yview moveto 0 + update + .t see 12.1 + .t index @0,0 +} {3.0} +test textDisp-13.6 {TkTextSeeCmd procedure} { + .t configure -wrap char + .t xview moveto 0 + .t yview moveto 0 + update + .t see 30.50 + set x [.t index @0,0] + .t configure -wrap none + set x +} {28.0} +test textDisp-13.7 {TkTextSeeCmd procedure} {fonts} { + .t xview moveto 0 + .t yview moveto 0 + .t tag add sel 30.20 + .t tag add sel 30.40 + update + .t see 30.50 + set x [list [.t bbox 30.50]] + .t see 30.39 + lappend x [.t bbox 30.39] + .t see 30.38 + lappend x [.t bbox 30.38] + .t see 30.20 + lappend x [.t bbox 30.20] +} {{73 55 7 13} {3 55 7 13} {3 55 7 13} {73 55 7 13}} +test textDisp-13.8 {TkTextSeeCmd procedure} {fonts} { + .t xview moveto 0 + .t yview moveto 0 + .t tag add sel 30.20 + .t tag add sel 30.50 + update + .t see 30.50 + set x [list [.t bbox 30.50]] + .t see 30.60 + lappend x [.t bbox 30.60] + .t see 30.65 + lappend x [.t bbox 30.65] + .t see 30.90 + lappend x [.t bbox 30.90] +} {{73 55 7 13} {136 55 7 13} {136 55 7 13} {73 55 7 13}} +test textDisp-13.9 {TkTextSeeCmd procedure} {fonts} { + wm geom . [expr $width-2]x$height + .t xview moveto 0 + .t yview moveto 0 + .t tag add sel 30.20 + .t tag add sel 30.50 + update + .t see 30.50 + set x [list [.t bbox 30.50]] + .t see 30.60 + lappend x [.t bbox 30.60] + .t see 30.65 + lappend x [.t bbox 30.65] + .t see 30.90 + lappend x [.t bbox 30.90] +} {{80 55 7 13} {136 55 7 13} {136 55 7 13} {80 55 7 13}} +wm geom . {} + +.t configure -wrap none +test textDisp-14.1 {TkTextXviewCmd procedure} { + .t delete 1.0 end + update + .t insert end xxxxxxxxx\n + .t insert end "xxxxx xxxxxxxxxxx xxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx\n" + .t insert end "xxxx xxxxxxxxx xxxxxxxxxxxxx" + .t xview moveto .5 + .t xview +} {0.5 0.857143} +.t configure -wrap char +test textDisp-14.2 {TkTextXviewCmd procedure} { + .t delete 1.0 end + update + .t insert end xxxxxxxxx\n + .t insert end "xxxxx\n" + .t insert end "xxxx" + .t xview +} {0 1} +.t configure -wrap none +test textDisp-14.3 {TkTextXviewCmd procedure} { + .t delete 1.0 end + update + .t insert end xxxxxxxxx\n + .t insert end "xxxxx\n" + .t insert end "xxxx" + .t xview +} {0 1} +test textDisp-14.4 {TkTextXviewCmd procedure} { + list [catch {.t xview moveto} msg] $msg +} {1 {wrong # args: should be ".t xview moveto fraction"}} +test textDisp-14.5 {TkTextXviewCmd procedure} { + list [catch {.t xview moveto a b} msg] $msg +} {1 {wrong # args: should be ".t xview moveto fraction"}} +test textDisp-14.6 {TkTextXviewCmd procedure} { + list [catch {.t xview moveto a} msg] $msg +} {1 {expected floating-point number but got "a"}} +test textDisp-14.7 {TkTextXviewCmd procedure} { + .t delete 1.0 end + .t insert end xxxxxxxxx\n + .t insert end "xxxxx xxxxxxxxxxx xxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx\n" + .t insert end "xxxx xxxxxxxxx xxxxxxxxxxxxx" + .t xview moveto .3 + .t xview +} {0.303571 0.660714} +test textDisp-14.8 {TkTextXviewCmd procedure} { + .t delete 1.0 end + .t insert end xxxxxxxxx\n + .t insert end "xxxxx xxxxxxxxxxx xxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx\n" + .t insert end "xxxx xxxxxxxxx xxxxxxxxxxxxx" + .t xview moveto -.4 + .t xview +} {0 0.357143} +test textDisp-14.9 {TkTextXviewCmd procedure} { + .t delete 1.0 end + .t insert end xxxxxxxxx\n + .t insert end "xxxxx xxxxxxxxxxx xxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx\n" + .t insert end "xxxx xxxxxxxxx xxxxxxxxxxxxx" + .t xview m 1.4 + .t xview +} {0.642857 1} +test textDisp-14.10 {TkTextXviewCmd procedure} { + list [catch {.t xview scroll a} msg] $msg +} {1 {wrong # args: should be ".t xview scroll number units|pages"}} +test textDisp-14.11 {TkTextXviewCmd procedure} { + list [catch {.t xview scroll a b c} msg] $msg +} {1 {wrong # args: should be ".t xview scroll number units|pages"}} +test textDisp-14.12 {TkTextXviewCmd procedure} { + list [catch {.t xview scroll gorp units} msg] $msg +} {1 {expected integer but got "gorp"}} +test textDisp-14.13 {TkTextXviewCmd procedure} { + .t delete 1.0 end + .t insert end xxxxxxxxx\n + .t insert end "a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9\n" + .t insert end "xxxx xxxxxxxxx xxxxxxxxxxxxx" + .t xview moveto 0 + .t xview scroll 2 p + set x [.t index @0,22] + .t xview scroll -1 p + lappend x [.t index @0,22] + .t xview scroll -2 pages + lappend x [.t index @0,22] +} {2.36 2.18 2.0} +test textDisp-14.14 {TkTextXviewCmd procedure} { + .t delete 1.0 end + .t insert end xxxxxxxxx\n + .t insert end "a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9\n" + .t insert end "xxxx xxxxxxxxx xxxxxxxxxxxxx" + .t xview moveto 0 + .t xview scroll 21 u + set x [.t index @0,22] + .t xview scroll -1 u + lappend x [.t index @0,22] + .t xview scroll 100 units + lappend x [.t index @0,22] + .t xview scroll -15 units + lappend x [.t index @0,22] +} {2.21 2.20 2.99 2.84} +test textDisp-14.15 {TkTextXviewCmd procedure} { + list [catch {.t xview scroll 14 globs} msg] $msg +} {1 {bad argument "globs": must be units or pages}} +test textDisp-14.16 {TkTextXviewCmd procedure} { + list [catch {.t xview flounder} msg] $msg +} {1 {unknown option "flounder": must be moveto or scroll}} + +.t configure -wrap char +.t delete 1.0 end +for {set i 1} {$i < 99} {incr i} { + .t insert end "Line $i\n" +} +.t insert end "Line 100" +.t delete 50.0 51.0 +.t insert 50.0 "This is a long line, one that will wrap around twice.\n" +test textDisp-15.1 {ScrollByLines procedure, scrolling backwards} { + .t yview 45.0 + update + .t yview scroll -3 units + .t index @0,0 +} {42.0} +test textDisp-15.2 {ScrollByLines procedure, scrolling backwards} { + .t yview 51.0 + update + .t yview scroll -2 units + .t index @0,0 +} {50.20} +test textDisp-15.3 {ScrollByLines procedure, scrolling backwards} { + .t yview 51.0 + update + .t yview scroll -4 units + .t index @0,0 +} {49.0} +test textDisp-15.4 {ScrollByLines procedure, scrolling backwards} { + .t yview 50.20 + update + .t yview scroll -2 units + .t index @0,0 +} {49.0} +test textDisp-15.5 {ScrollByLines procedure, scrolling backwards} { + .t yview 50.40 + update + .t yview scroll -2 units + .t index @0,0 +} {50.0} +test textDisp-15.6 {ScrollByLines procedure, scrolling backwards} { + .t yview 3.2 + update + .t yview scroll -5 units + .t index @0,0 +} {1.0} +test textDisp-15.7 {ScrollByLines procedure, scrolling forwards} { + .t yview 48.0 + update + .t yview scroll 4 units + .t index @0,0 +} {50.40} + +.t configure -wrap char +.t delete 1.0 end +.t insert insert "Line 1" +for {set i 2} {$i <= 200} {incr i} { + .t insert end "\nLine $i" +} +.t tag add big 100.0 105.0 +.t insert 151.end { has a lot of extra text, so that it wraps around on the screen several times over.} +.t insert 153.end { also has enoug extra text to wrap.} +update +test textDisp-16.1 {TkTextYviewCmd procedure} { + .t yview 21.0 + set x [.t yview] + .t yview 1.0 + set x +} {0.1 0.15} +test textDisp-16.2 {TkTextYviewCmd procedure} { + list [catch {.t yview 2 3} msg] $msg +} {1 {unknown option "2": must be moveto or scroll}} +test textDisp-16.3 {TkTextYviewCmd procedure} { + list [catch {.t yview -pickplace} msg] $msg +} {1 {wrong # args: should be ".t yview -pickplace lineNum|index"}} +test textDisp-16.4 {TkTextYviewCmd procedure} { + list [catch {.t yview -pickplace 2 3} msg] $msg +} {1 {wrong # args: should be ".t yview -pickplace lineNum|index"}} +test textDisp-16.5 {TkTextYviewCmd procedure} { + list [catch {.t yview -bogus 2} msg] $msg +} {1 {unknown option "-bogus": must be moveto or scroll}} +test textDisp-16.6 {TkTextYviewCmd procedure, integer position} { + .t yview 100.0 + update + .t yview 98 + .t index @0,0 +} {99.0} +test textDisp-16.7 {TkTextYviewCmd procedure} { + .t yview 2.0 + .t yv -pickplace 13.0 + .t index @0,0 +} {4.0} +test textDisp-16.8 {TkTextYviewCmd procedure} { + list [catch {.t yview bad_mark_name} msg] $msg +} {1 {bad text index "bad_mark_name"}} +test textDisp-16.9 {TkTextYviewCmd procedure, "moveto" option} { + list [catch {.t yview moveto a b} msg] $msg +} {1 {wrong # args: should be ".t yview moveto fraction"}} +test textDisp-16.10 {TkTextYviewCmd procedure, "moveto" option} { + list [catch {.t yview moveto gorp} msg] $msg +} {1 {expected floating-point number but got "gorp"}} +test textDisp-16.11 {TkTextYviewCmd procedure, "moveto" option} { + .t yview moveto 0.5 + .t index @0,0 +} {101.0} +test textDisp-16.12 {TkTextYviewCmd procedure, "moveto" option} { + .t yview moveto -1 + .t index @0,0 +} {1.0} +test textDisp-16.13 {TkTextYviewCmd procedure, "moveto" option} { + .t yview moveto 1.1 + .t index @0,0 +} {191.0} +test textDisp-16.14 {TkTextYviewCmd procedure, "moveto" option} { + .t yview moveto .75 + .t index @0,0 +} {151.0} +test textDisp-16.15 {TkTextYviewCmd procedure, "moveto" option} { + .t yview moveto .752 + .t index @0,0 +} {151.20} +test textDisp-16.16 {TkTextYviewCmd procedure, "moveto" option} { + .t yview moveto .754 + .t index @0,0 +} {151.60} +test textDisp-16.17 {TkTextYviewCmd procedure, "moveto" option} { + .t yview moveto .755 + .t index @0,0 +} {152.0} +test textDisp-16.18 {TkTextYviewCmd procedure, "moveto" roundoff} {fonts} { + catch {destroy .top1} + toplevel .top1 + wm geometry .top1 +0+0 + text .top1.t -height 3 -width 4 -wrap none -setgrid 1 -padx 6 \ + -spacing3 6 + .top1.t insert end "1\n2\n3\n4\n5\n6" + pack .top1.t + update + .top1.t yview moveto 0.3333 + set result [.top1.t yview] + destroy .top1 + set result +} {0.333333 0.833333} +test textDisp-16.19 {TkTextYviewCmd procedure, "scroll" option} { + list [catch {.t yview scroll a} msg] $msg +} {1 {wrong # args: should be ".t yview scroll number units|pages"}} +test textDisp-16.20 {TkTextYviewCmd procedure, "scroll" option} { + list [catch {.t yview scroll a b c} msg] $msg +} {1 {wrong # args: should be ".t yview scroll number units|pages"}} +test textDisp-16.21 {TkTextYviewCmd procedure, "scroll" option} { + list [catch {.t yview scroll badInt bogus} msg] $msg +} {1 {expected integer but got "badInt"}} +test textDisp-16.22 {TkTextYviewCmd procedure, "scroll" option, back pages} { + .t yview 50.0 + update + .t yview scroll -1 pages + .t index @0,0 +} {42.0} +test textDisp-16.23 {TkTextYviewCmd procedure, "scroll" option, back pages} { + .t yview 50.0 + update + .t yview scroll -3 p + .t index @0,0 +} {26.0} +test textDisp-16.24 {TkTextYviewCmd procedure, "scroll" option, back pages} { + .t yview 5.0 + update + .t yview scroll -3 p + .t index @0,0 +} {1.0} +test textDisp-16.25 {TkTextYviewCmd procedure, "scroll" option, back pages} { + .t configure -height 1 + update + .t yview 50.0 + update + .t yview scroll -1 pages + set x [.t index @0,0] + .t configure -height 10 + update + set x +} {49.0} +test textDisp-16.26 {TkTextYviewCmd procedure, "scroll" option, forward pages} { + .t yview 50.0 + update + .t yview scroll 1 pages + .t index @0,0 +} {58.0} +test textDisp-16.27 {TkTextYviewCmd procedure, "scroll" option, forward pages} { + .t yview 50.0 + update + .t yview scroll 2 pages + .t index @0,0 +} {66.0} +test textDisp-16.28 {TkTextYviewCmd procedure, "scroll" option, forward pages} {fonts} { + .t yview 98.0 + update + .t yview scroll 1 page + .t index @0,0 +} {103.0} +test textDisp-16.29 {TkTextYviewCmd procedure, "scroll" option, forward pages} { + .t configure -height 1 + update + .t yview 50.0 + update + .t yview scroll 1 pages + set x [.t index @0,0] + .t configure -height 10 + update + set x +} {51.0} +test textDisp-16.30 {TkTextYviewCmd procedure, "scroll units" option} { + .t yview 45.0 + update + .t yview scroll -3 units + .t index @0,0 +} {42.0} +test textDisp-16.31 {TkTextYviewCmd procedure, "scroll units" option} { + .t yview 149.0 + update + .t yview scroll 4 units + .t index @0,0 +} {151.40} +test textDisp-16.32 {TkTextYviewCmd procedure} { + list [catch {.t yview scroll 12 bogoids} msg] $msg +} {1 {bad argument "bogoids": must be units or pages}} +test textDisp-16.33 {TkTextYviewCmd procedure} { + list [catch {.t yview bad_arg 1 2} msg] $msg +} {1 {unknown option "bad_arg": must be moveto or scroll}} + +.t delete 1.0 end +foreach i {a b c d e f g h i j k l m n o p q r s t u v w x y z} { + .t insert end "\nLine $i 11111 $i 22222 $i 33333 $i 44444 $i 55555" + .t insert end " $i 66666 $i 77777 $i 88888 $i" +} +.t configure -wrap none +test textDisp-17.1 {TkTextScanCmd procedure} { + list [catch {.t scan a b} msg] $msg +} {1 {wrong # args: should be ".t scan mark|dragto x y"}} +test textDisp-17.2 {TkTextScanCmd procedure} { + list [catch {.t scan a b c d} msg] $msg +} {1 {wrong # args: should be ".t scan mark|dragto x y"}} +test textDisp-17.3 {TkTextScanCmd procedure} { + list [catch {.t scan stupid b 20} msg] $msg +} {1 {expected integer but got "b"}} +test textDisp-17.4 {TkTextScanCmd procedure} { + list [catch {.t scan stupid -2 bogus} msg] $msg +} {1 {expected integer but got "bogus"}} +test textDisp-17.5 {TkTextScanCmd procedure} { + list [catch {.t scan stupid 123 456} msg] $msg +} {1 {bad scan option "stupid": must be mark or dragto}} +test textDisp-17.6 {TkTextScanCmd procedure} {fonts} { + .t yview 1.0 + .t xview moveto 0 + .t scan mark 40 60 + .t scan dragto 35 55 + .t index @0,0 +} {4.7} +test textDisp-17.7 {TkTextScanCmd procedure} {fonts} { + .t yview 10.0 + .t xview moveto 0 + .t xview scroll 20 units + .t scan mark -10 60 + .t scan dragto -5 65 + .t index @0,0 + set x [.t index @0,0] + .t scan dragto 0 70 + list $x [.t index @0,0] +} {7.13 3.6} +test textDisp-17.8 {TkTextScanCmd procedure} {fonts} { + .t yview 1.0 + .t xview moveto 0 + .t scan mark 0 60 + .t scan dragto 30 100 + .t scan dragto 25 95 + .t index @0,0 +} {4.7} +test textDisp-17.9 {TkTextScanCmd procedure} {fonts} { + .t yview end + .t xview moveto 0 + .t xview scroll 100 units + .t scan mark 90 60 + .t scan dragto 10 0 + .t scan dragto 15 5 + .t index @0,0 +} {18.44} +.t configure -wrap word +test textDisp-17.10 {TkTextScanCmd procedure, word wrapping} {fonts} { + .t yview 10.0 + .t scan mark -10 60 + .t scan dragto -5 65 + set x [.t index @0,0] + .t scan dragto 0 70 + list $x [.t index @0,0] +} {9.31 8.47} + +.t configure -xscrollcommand scroll -yscrollcommand {} +test textDisp-18.1 {GetXView procedure} { + .t configure -wrap none + .t delete 1.0 end + .t insert end xxxxxxxxx\n + .t insert end xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n + .t insert end xxxxxxxxxxxxxxxxxxxxxxxxxx + update + set scrollInfo +} {0 0.363636} +test textDisp-18.2 {GetXView procedure} { + .t configure -wrap char + .t delete 1.0 end + .t insert end xxxxxxxxx\n + .t insert end xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n + .t insert end xxxxxxxxxxxxxxxxxxxxxxxxxx + update + set scrollInfo +} {0 1} +test textDisp-18.3 {GetXView procedure} { + .t configure -wrap none + .t delete 1.0 end + update + set scrollInfo +} {0 1} +test textDisp-18.4 {GetXView procedure} { + .t configure -wrap none + .t delete 1.0 end + .t insert end xxxxxxxxx\n + .t insert end xxxxxx\n + .t insert end xxxxxxxxxxxxxxxxx + update + set scrollInfo +} {0 1} +test textDisp-18.5 {GetXView procedure} { + .t configure -wrap none + .t delete 1.0 end + .t insert end xxxxxxxxx\n + .t insert end xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n + .t insert end xxxxxxxxxxxxxxxxxxxxxxxxxx + .t xview scroll 31 units + update + set scrollInfo +} {0.563636 0.927273} +test textDisp-18.6 {GetXView procedure} { + .t configure -wrap none + .t delete 1.0 end + .t insert end xxxxxxxxx\n + .t insert end "xxxxx xxxxxxxxxxx xxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx\n" + .t insert end "xxxx xxxxxxxxx xxxxxxxxxxxxx" + .t xview moveto 0 + .t xview scroll 31 units + update + set x {} + lappend x $scrollInfo + .t configure -wrap char + update + lappend x $scrollInfo + .t configure -wrap word + update + lappend x $scrollInfo + .t configure -wrap none + update + lappend x $scrollInfo +} {{0.553571 0.910714} {0 1} {0 1} {0 0.357143}} +test textDisp-18.7 {GetXView procedure} { + .t configure -wrap none + .t delete 1.0 end + update + set scrollInfo unchanged + .t insert end xxxxxx\n + .t insert end xxx + update + set scrollInfo +} {unchanged} +test textDisp-18.8 {GetXView procedure} { + proc bgerror msg { + global x errorInfo + set x [list $msg $errorInfo] + } + proc bogus args { + error "bogus scroll proc" + } + .t configure -wrap none + .t delete 1.0 end + .t insert end xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n + update + .t delete 1.0 end + .t configure -xscrollcommand scrollError + update + set x +} {{scrolling error} {scrolling error + while executing +"error "scrolling error"" + (procedure "scrollError" line 2) + invoked from within +"scrollError 0 1" + (horizontal scrolling command executed by text)}} +catch {rename bgerror {}} +catch {rename bogus {}} +.t configure -xscrollcommand {} -yscrollcommand scroll + +.t configure -xscrollcommand {} -yscrollcommand scroll +test textDisp-19.1 {GetYView procedure} { + .t configure -wrap char + .t delete 1.0 end + update + set scrollInfo +} {0 1} +test textDisp-19.2 {GetYView procedure} { + .t configure -wrap char + .t delete 1.0 end + update + set scrollInfo "unchanged" + .t insert 1.0 "Line1\nLine2" + update + set scrollInfo +} {unchanged} +test textDisp-19.3 {GetYView procedure} { + .t configure -wrap char + .t delete 1.0 end + update + set scrollInfo "unchanged" + .t insert 1.0 "Line 1\nLine 2 is so long that it wraps around\nLine 3" + update + set scrollInfo +} {unchanged} +test textDisp-19.4 {GetYView procedure} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1" + update + set scrollInfo "unchanged" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13} { + .t insert end "\nLine $i" + } + update + set scrollInfo +} {0 0.769231} +test textDisp-19.5 {GetYView procedure} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13} { + .t insert end "\nLine $i" + } + .t insert 2.end " is really quite long; in fact it's so long that it wraps three times" + update + set x $scrollInfo +} {0 0.538462} +test textDisp-19.6 {GetYView procedure} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13} { + .t insert end "\nLine $i" + } + .t insert 2.end " is really quite long; in fact it's so long that it wraps three times" + .t yview 4.0 + update + set x $scrollInfo +} {0.230769 1} +test textDisp-19.7 {GetYView procedure} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13} { + .t insert end "\nLine $i" + } + .t insert 2.end " is really quite long; in fact it's so long that it wraps three times" + .t yview 2.26 + update + set x $scrollInfo +} {0.097166 0.692308} +test textDisp-19.8 {GetYView procedure} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13} { + .t insert end "\nLine $i" + } + .t insert 10.end " is really quite long; in fact it's so long that it wraps three times" + .t yview 2.0 + update + set x $scrollInfo +} {0.0769231 0.732268} +test textDisp-19.9 {GetYView procedure} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + .t yview 3.0 + update + set scrollInfo +} {0.133333 0.8} +test textDisp-19.10 {GetYView procedure} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + .t yview 11.0 + update + set scrollInfo +} {0.333333 1} +test textDisp-19.11 {GetYView procedure} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + .t insert end "\nThis last line wraps around four " + .t insert end "times with a bit left on the last line." + .t yview insert + update + set scrollInfo +} {0.625 1} +test textDisp-19.12 {GetYView procedure, partially visible last line} { + catch {destroy .top} + toplevel .top + wm geometry .top +0+0 + text .top.t -width 40 -height 5 + pack .top.t -expand yes -fill both + .top.t insert end "Line 1\nLine 2\nLine 3\nLine 4\nLine 5" + update + scan [wm geom .top] %dx%d twidth theight + wm geom .top ${twidth}x[expr $theight - 3] + update + .top.t yview +} {0 0.8} +test textDisp-19.13 {GetYView procedure, partially visible last line} {fonts} { + catch {destroy .top} + toplevel .top + wm geometry .top +0+0 + text .top.t -width 40 -height 5 + pack .top.t -expand yes -fill both + .top.t insert end "Line 1\nLine 2\nLine 3\nLine 4 has enough text to wrap around at least once" + update + scan [wm geom .top] %dx%d twidth theight + wm geom .top ${twidth}x[expr $theight - 3] + update + .top.t yview +} {0 0.942308} +catch {destroy .top} +test textDisp-19.14 {GetYView procedure} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + .t insert end "\nThis last line wraps around four " + .t insert end "times with a bit left on the last line." + update + set scrollInfo "unchanged" + .t mark set insert 3.0 + .t tag configure x -background red + .t tag add x 1.0 5.0 + update + .t tag delete x + set scrollInfo +} {unchanged} +test textDisp-19.15 {GetYView procedure} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "Line 1" + foreach i {2 3 4 5 6 7 8 9 10 11 12 13 14 15} { + .t insert end "\nLine $i" + } + .t insert end "\nThis last line wraps around four " + .t insert end "times with a bit left on the last line." + update + .t configure -yscrollcommand scrollError + proc bgerror args { + global x errorInfo errorCode + set x [list $args $errorInfo $errorCode] + } + .t delete 1.0 end + update + rename bgerror {} + .t configure -yscrollcommand scroll + set x +} {{{scrolling error}} {scrolling error + while executing +"error "scrolling error"" + (procedure "scrollError" line 2) + invoked from within +"scrollError 0 1" + (vertical scrolling command executed by text)} NONE} + +.t delete 1.0 end +.t insert end "Line 1" +for {set i 2} {$i <= 200} {incr i} { + .t insert end "\nLine $i" +} +.t configure -wrap word +.t delete 50.0 51.0 +.t insert 50.0 "This is a long line, one that will wrap around twice.\n" +test textDisp-20.1 {FindDLine} {fonts} { + .t yview 48.0 + list [.t dlineinfo 46.0] [.t dlineinfo 47.0] [.t dlineinfo 49.0] \ + [.t dlineinfo 58.0] +} {{} {} {3 16 49 13 10} {}} +test textDisp-20.2 {FindDLine} {fonts} { + .t yview 100.0 + .t yview -pickplace 53.0 + list [.t dlineinfo 50.0] [.t dlineinfo 50.14] [.t dlineinfo 50.15] +} {{} {} {3 3 140 13 10}} +test textDisp-20.3 {FindDLine} {fonts} { + .t yview 100.0 + .t yview 49.0 + list [.t dlineinfo 50.0] [.t dlineinfo 50.20] [.t dlineinfo 57.0] +} {{3 16 105 13 10} {3 29 140 13 10} {}} +test textDisp-20.4 {FindDLine} {fonts} { + .t yview 100.0 + .t yview 42.0 + list [.t dlineinfo 50.0] [.t dlineinfo 50.20] [.t dlineinfo 50.40] +} {{3 107 105 13 10} {3 120 140 13 10} {}} +.t config -wrap none +test textDisp-20.5 {FindDLine} {fonts} { + .t yview 100.0 + .t yview 48.0 + list [.t dlineinfo 50.0] [.t dlineinfo 50.20] [.t dlineinfo 50.40] +} {{3 29 371 13 10} {3 29 371 13 10} {3 29 371 13 10}} + +.t config -wrap word +test textDisp-21.1 {TkTextPixelIndex} {fonts} { + .t yview 48.0 + list [.t index @-10,-10] [.t index @6,6] [.t index @22,6] \ + [.t index @102,6] [.t index @38,55] [.t index @44,67] +} {48.0 48.0 48.2 48.7 50.40 50.40} +.t insert end \n +test textDisp-21.2 {TkTextPixelIndex} {fonts} { + .t yview 195.0 + list [.t index @11,70] [.t index @11,84] [.t index @11,102] \ + [.t index @11,1002] +} {197.1 198.1 199.1 201.0} +test textDisp-21.3 {TkTextPixelIndex, horizontal scrolling} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert end "12345\n" + .t insert end "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + .t xview scroll 2 units + list [.t index @-5,7] [.t index @5,7] [.t index @33,20] +} {1.2 1.2 2.6} + +.t delete 1.0 end +.t insert end "Line 1" +for {set i 2} {$i <= 200} {incr i} { + .t insert end "\nLine $i" +} +.t configure -wrap word +.t delete 50.0 51.0 +.t insert 50.0 "This is a long line, one that will wrap around twice.\n" +update +.t tag add x 50.1 +test textDisp-22.1 {TkTextCharBbox} {fonts} { + .t config -wrap word + .t yview 48.0 + list [.t bbox 47.2] [.t bbox 48.0] [.t bbox 50.5] [.t bbox 50.40] \ + [.t bbox 58.0] +} {{} {3 3 7 13} {38 29 7 13} {38 55 7 13} {}} +test textDisp-22.2 {TkTextCharBbox} {fonts} { + .t config -wrap none + .t yview 48.0 + list [.t bbox 50.5] [.t bbox 50.40] [.t bbox 57.0] +} {{38 29 7 13} {} {3 120 7 13}} +test textDisp-22.3 {TkTextCharBbox, cut-off lines} {fonts} { + .t config -wrap char + .t yview 10.0 + wm geom . ${width}x[expr $height-1] + update + list [.t bbox 19.1] [.t bbox 20.1] +} {{10 120 7 13} {10 133 7 3}} +test textDisp-22.4 {TkTextCharBbox, cut-off lines} {fonts} { + .t config -wrap char + .t yview 10.0 + wm geom . ${width}x[expr $height+1] + update + list [.t bbox 19.1] [.t bbox 20.1] +} {{10 120 7 13} {10 133 7 5}} +test textDisp-22.5 {TkTextCharBbox, cut-off char} {fonts} { + .t config -wrap none + .t yview 10.0 + wm geom . [expr $width-95]x$height + update + .t bbox 15.6 +} {45 68 7 13} +test textDisp-22.6 {TkTextCharBbox, line visible but not char} {fonts} { + .t config -wrap char + .t yview 10.0 + .t tag add big 20.2 20.5 + wm geom . ${width}x[expr $height+3] + update + list [.t bbox 19.1] [.t bbox 20.1] [.t bbox 20.2] +} {{10 120 7 13} {} {17 133 14 7}} +wm geom . {} +update +test textDisp-22.7 {TkTextCharBbox, different character sizes} {fonts} { + .t config -wrap char + .t yview 10.0 + .t tag add big 12.2 12.5 + update + list [.t bbox 12.1] [.t bbox 12.2] +} {{10 41 7 13} {17 29 14 27}} +.t tag remove big 1.0 end +test textDisp-22.8 {TkTextCharBbox, horizontal scrolling} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert end "12345\n" + .t insert end "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + .t xview scroll 4 units + list [.t bbox 1.3] [.t bbox 1.4] [.t bbox 2.3] [.t bbox 2.4] \ + [.t bbox 2.23] [.t bbox 2.24] +} {{} {3 3 7 13} {} {3 16 7 13} {136 16 7 13} {}} +test textDisp-22.9 {TkTextCharBbox, handling of spacing} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "abcdefghijkl\nmnopqrstuvwzyz" + .t tag configure spacing -spacing1 8 -spacing3 2 + .t tag add spacing 1.0 end + frame .t.f1 -width 10 -height 4 -bg black + frame .t.f2 -width 10 -height 4 -bg black + frame .t.f3 -width 10 -height 4 -bg black + frame .t.f4 -width 10 -height 4 -bg black + .t window create 1.3 -window .t.f1 -align top + .t window create 1.7 -window .t.f2 -align center + .t window create 2.1 -window .t.f3 -align bottom + .t window create 2.10 -window .t.f4 -align baseline + update + list [.t bbox .t.f1] [.t bbox .t.f2] [.t bbox .t.f3] [.t bbox .t.f4] \ + [.t bbox 1.1] [.t bbox 2.9] +} {{24 11 10 4} {55 15 10 4} {10 43 10 4} {76 40 10 4} {10 11 7 13} {69 34 7 13}} +.t tag delete spacing + +.t delete 1.0 end +.t insert end "Line 1" +for {set i 2} {$i <= 200} {incr i} { + .t insert end "\nLine $i" +} +.t configure -wrap word +.t delete 50.0 51.0 +.t insert 50.0 "This is a long line, one that will wrap around twice.\n" +update +test textDisp-23.1 {TkTextDLineInfo} {fonts} { + .t config -wrap word + .t yview 48.0 + list [.t dlineinfo 47.3] [.t dlineinfo 48.0] [.t dlineinfo 50.40] \ + [.t dlineinfo 56.0] +} {{} {3 3 49 13 10} {3 55 126 13 10} {}} +test textDisp-23.2 {TkTextDLineInfo} {fonts} { + .t config -bd 4 -wrap word + update + .t yview 48.0 + .t dlineinfo 50.40 +} {7 59 126 13 10} +.t config -bd 0 +test textDisp-23.3 {TkTextDLineInfo} {fonts} { + .t config -wrap none + update + .t yview 48.0 + list [.t dlineinfo 50.40] [.t dlineinfo 57.3] +} {{3 29 371 13 10} {3 120 49 13 10}} +test textDisp-23.4 {TkTextDLineInfo, cut-off lines} {fonts} { + .t config -wrap char + .t yview 10.0 + wm geom . ${width}x[expr $height-1] + update + list [.t dlineinfo 19.0] [.t dlineinfo 20.0] +} {{3 120 49 13 10} {3 133 49 3 10}} +test textDisp-23.5 {TkTextDLineInfo, cut-off lines} {fonts} { + .t config -wrap char + .t yview 10.0 + wm geom . ${width}x[expr $height+1] + update + list [.t dlineinfo 19.0] [.t dlineinfo 20.0] +} {{3 120 49 13 10} {3 133 49 5 10}} +wm geom . {} +update +test textDisp-23.6 {TkTextDLineInfo, horizontal scrolling} {fonts} { + .t config -wrap none + .t delete 1.0 end + .t insert end "First line\n" + .t insert end "Second line is a very long one that doesn't all fit.\n" + .t insert end "Third" + .t xview scroll 6 units + update + list [.t dlineinfo 1.0] [.t dlineinfo 2.0] [.t dlineinfo 3.0] +} {{-39 3 70 13 10} {-39 16 364 13 10} {-39 29 35 13 10}} +.t xview moveto 0 +test textDisp-23.7 {TkTextDLineInfo, centering} {fonts} { + .t config -wrap word + .t delete 1.0 end + .t insert end "First line\n" + .t insert end "Second line is a very long one that doesn't all fit.\n" + .t insert end "Third" + .t tag configure x -justify center + .t tag configure y -justify right + .t tag add x 1.0 + .t tag add y 3.0 + list [.t dlineinfo 1.0] [.t dlineinfo 2.0] [.t dlineinfo 3.0] +} {{38 3 70 13 10} {3 16 119 13 10} {108 55 35 13 10}} +.t tag delete x y + +test textDisp-24.1 {TkTextCharLayoutProc} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "abcdefghijklmnopqrstuvwxyz" + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 7 13} {3 16 7 13}} +test textDisp-24.2 {TkTextCharLayoutProc} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "abcdefghijklmnopqrstuvwxyz" + wm geom . [expr $width+1]x$height + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 12 13} {3 16 7 13}} +test textDisp-24.3 {TkTextCharLayoutProc} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "abcdefghijklmnopqrstuvwxyz" + wm geom . [expr $width-1]x$height + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 10 13} {3 16 7 13}} +test textDisp-24.4 {TkTextCharLayoutProc, newline not visible} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 01234567890123456789\n012345678901234567890 + wm geom . {} + update + list [.t bbox 1.19] [.t bbox 1.20] [.t bbox 2.20] +} {{136 3 7 13} {143 3 0 13} {3 29 7 13}} +test textDisp-24.5 {TkTextCharLayoutProc, char doesn't fit, newline not visible} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 0\n1\n + wm geom . 110x$height + update + list [.t bbox 1.0] [.t bbox 1.1] [.t bbox 2.0] +} {{3 3 4 13} {7 3 0 13} {3 16 4 13}} +test textDisp-24.6 {TkTextCharLayoutProc, line ends with space} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "a b c d e f g h i j k l m n o p" + wm geom . {} + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 7 13} {3 16 7 13}} +test textDisp-24.7 {TkTextCharLayoutProc, line ends with space} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "a b c d e f g h i j k l m n o p" + wm geom . [expr $width+1]x$height + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 12 13} {3 16 7 13}} +test textDisp-24.8 {TkTextCharLayoutProc, line ends with space} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "a b c d e f g h i j k l m n o p" + wm geom . [expr $width-1]x$height + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 10 13} {3 16 7 13}} +test textDisp-24.9 {TkTextCharLayoutProc, line ends with space} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "a b c d e f g h i j k l m n o p" + wm geom . [expr $width-6]x$height + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 5 13} {3 16 7 13}} +test textDisp-24.10 {TkTextCharLayoutProc, line ends with space} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "a b c d e f g h i j k l m n o p" + wm geom . [expr $width-7]x$height + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 4 13} {3 16 7 13}} +test textDisp-24.11 {TkTextCharLayoutProc, line ends with space that doesn't quite fit} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "01234567890123456789 \nabcdefg" + wm geom . [expr $width-2]x$height + update + set result {} + lappend result [.t bbox 1.21] [.t bbox 2.0] + .t mark set insert 1.21 + lappend result [.t bbox 1.21] [.t bbox 2.0] +} {{145 3 0 13} {3 16 7 13} {145 3 0 13} {3 16 7 13}} +test textDisp-24.12 {TkTextCharLayoutProc, tab causes wrap} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "abcdefghi" + .t mark set insert 1.4 + .t insert insert \t\t\t + list [.t bbox {insert -1c}] [.t bbox insert] +} {{115 3 30 13} {3 16 7 13}} +test textDisp-24.13 {TkTextCharLayoutProc, -wrap none} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "abcdefghijklmnopqrstuvwxyz" + wm geom . {} + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 7 13} {}} +test textDisp-24.14 {TkTextCharLayoutProc, -wrap none} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "abcdefghijklmnopqrstuvwxyz" + wm geom . [expr $width+1]x$height + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 7 13} {143 3 5 13}} +test textDisp-24.15 {TkTextCharLayoutProc, -wrap none} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "abcdefghijklmnopqrstuvwxyz" + wm geom . [expr $width-1]x$height + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 7 13} {143 3 3 13}} +test textDisp-24.16 {TkTextCharLayoutProc, no chars fit} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "abcdefghijklmnopqrstuvwxyz" + wm geom . 103x$height + update + list [.t bbox 1.0] [.t bbox 1.1] [.t bbox 1.2] +} {{3 3 1 13} {3 16 1 13} {3 29 1 13}} +test textDisp-24.17 {TkTextCharLayoutProc, -wrap word} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "This is a line that wraps around" + wm geom . {} + update + list [.t bbox 1.19] [.t bbox 1.20] +} {{136 3 7 13} {3 16 7 13}} +test textDisp-24.18 {TkTextCharLayoutProc, -wrap word} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "xThis is a line that wraps around" + wm geom . {} + update + list [.t bbox 1.14] [.t bbox 1.15] [.t bbox 1.16] +} {{101 3 7 13} {108 3 35 13} {3 16 7 13}} +test textDisp-24.19 {TkTextCharLayoutProc, -wrap word} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "xxThis is a line that wraps around" + wm geom . {} + update + list [.t bbox 1.14] [.t bbox 1.15] [.t bbox 1.16] +} {{101 3 7 13} {108 3 7 13} {115 3 28 13}} +test textDisp-24.20 {TkTextCharLayoutProc, vertical offset} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "Line 1\nLine 2\nLine 3" + set result {} + lappend result [.t bbox 2.1] [.t dlineinfo 2.1] + .t tag configure up -offset 6 + .t tag add up 2.1 + lappend result [.t bbox 2.1] [.t dlineinfo 2.1] + .t tag configure up -offset -2 + lappend result [.t bbox 2.1] [.t dlineinfo 2.1] + .t tag delete up + set result +} {{10 16 7 13} {3 16 42 13 10} {10 16 7 13} {3 16 42 19 16} {10 18 7 13} {3 16 42 15 10}} +.t configure -width 30 +update +test textDisp-24.21 {TkTextCharLayoutProc, word breaks} {fonts} { + .t configure -wrap word + .t delete 1.0 end + .t insert 1.0 "Sample text xxxxxxx yyyyy zzzzzzz qqqqq rrrr ssss tt u vvvvv" + frame .t.f -width 30 -height 20 -bg black + .t window create 1.36 -window .t.f + .t bbox 1.26 +} {3 19 7 13} +test textDisp-24.22 {TkTextCharLayoutProc, word breaks} {fonts} { + .t configure -wrap word + .t delete 1.0 end + frame .t.f -width 30 -height 20 -bg black + .t insert 1.0 "Sample text xxxxxxx yyyyyyy" + .t window create end -window .t.f + .t insert end "zzzzzzz qqqqq rrrr ssss tt u vvvvv" + .t bbox 1.28 +} {33 19 7 13} +test textDisp-24.23 {TkTextCharLayoutProc, word breaks} {fonts} { + .t configure -wrap word + .t delete 1.0 end + frame .t.f -width 30 -height 20 -bg black + .t insert 1.0 "Sample text xxxxxxx yyyyyyy " + .t insert end "zzzzzzz qqqqq rrrr ssss tt" + .t window create end -window .t.f + .t insert end "u vvvvv" + .t bbox .t.f +} {3 29 30 20} +catch {destroy .t.f} +.t configure -width 20 +update +test textDisp-24.24 {TkTextCharLayoutProc, justification and tabs} {fonts} { + .t delete 1.0 end + .t tag configure x -justify center + .t insert 1.0 aa\tbb\tcc\tdd\t + .t tag add x 1.0 end + list [.t bbox 1.0] [.t bbox 1.10] +} {{45 3 7 13} {94 3 7 13}} + +.t configure -width 40 -bd 0 -relief flat -highlightthickness 0 -padx 0 \ + -tabs 100 +update +test textDisp-25.1 {CharBboxProc procedure, check tab width} {fonts} { + .t delete 1.0 end + .t insert 1.0 abc\td\tfgh + list [.t bbox 1.3] [.t bbox 1.5] [.t bbox 1.6] +} {{21 1 79 13} {107 1 93 13} {200 1 7 13}} + +.t configure -width 40 -bd 0 -relief flat -highlightthickness 0 -padx 0 \ + -tabs {} +update +test textDisp-26.1 {AdjustForTab procedure, no tabs} {fonts} { + .t delete 1.0 end + .t insert 1.0 a\tbcdefghij\tc\td + list [lindex [.t bbox 1.2] 0] [lindex [.t bbox 1.12] 0] \ + [lindex [.t bbox 1.14] 0] +} {56 168 224} +test textDisp-26.2 {AdjustForTab procedure, not enough tabs specified} { + .t delete 1.0 end + .t insert 1.0 a\tb\tc\td + .t tag delete x + .t tag configure x -tabs 40 + .t tag add x 1.0 end + list [lindex [.t bbox 1.2] 0] [lindex [.t bbox 1.4] 0] \ + [lindex [.t bbox 1.6] 0] +} {40 80 120} +test textDisp-26.3 {AdjustForTab procedure, not enough tabs specified} { + .t delete 1.0 end + .t insert 1.0 a\tb\tc\td\te + .t tag delete x + .t tag configure x -tabs {40 70 right} + .t tag add x 1.0 end + list [lindex [.t bbox 1.2] 0] \ + [expr [lindex [.t bbox 1.4] 0] + [lindex [.t bbox 1.4] 2]] \ + [expr [lindex [.t bbox 1.6] 0] + [lindex [.t bbox 1.6] 2]] \ + [expr [lindex [.t bbox 1.8] 0] + [lindex [.t bbox 1.8] 2]] +} {40 70 100 130} +test textDisp-26.4 {AdjustForTab procedure, different alignments} { + .t delete 1.0 end + .t insert 1.0 a\tbc\tde\tfg\thi + .t tag delete x + .t tag configure x -tabs {40 center 80 left 130 right} + .t tag add x 1.0 end + .t tag add y 1.2 + .t tag add y 1.5 + .t tag add y 1.8 + list [lindex [.t bbox 1.3] 0] [lindex [.t bbox 1.5] 0] \ + [lindex [.t bbox 1.10] 0] +} {40 80 130} +test textDisp-26.5 {AdjustForTab procedure, numeric alignment} { + .t delete 1.0 end + .t insert 1.0 a\t1.234 + .t tag delete x + .t tag configure x -tabs {120 numeric} + .t tag add x 1.0 end + .t tag add y 1.2 + .t tag add y 1.5 + lindex [.t bbox 1.3] 0 +} {120} +test textDisp-26.6 {AdjustForTab procedure, numeric alignment} { + .t delete 1.0 end + .t insert 1.0 a\t1,456.234 + .t tag delete x + .t tag configure x -tabs {120 numeric} + .t tag add x 1.0 end + .t tag add y 1.2 + lindex [.t bbox 1.7] 0 +} {120} +test textDisp-26.7 {AdjustForTab procedure, numeric alignment} { + .t delete 1.0 end + .t insert 1.0 a\t1.456.234,7 + .t tag delete x + .t tag configure x -tabs {120 numeric} + .t tag add x 1.0 end + .t tag add y 1.2 + lindex [.t bbox 1.11] 0 +} {120} +test textDisp-26.8 {AdjustForTab procedure, numeric alignment} { + .t delete 1.0 end + .t insert 1.0 a\ttest + .t tag delete x + .t tag configure x -tabs {120 numeric} + .t tag add x 1.0 end + .t tag add y 1.2 + lindex [.t bbox 1.6] 0 +} {120} +test textDisp-26.9 {AdjustForTab procedure, numeric alignment} { + .t delete 1.0 end + .t insert 1.0 a\t1234 + .t tag delete x + .t tag configure x -tabs {120 numeric} + .t tag add x 1.0 end + .t tag add y 1.2 + lindex [.t bbox 1.6] 0 +} {120} +test textDisp-26.10 {AdjustForTab procedure, numeric alignment} { + .t delete 1.0 end + .t insert 1.0 a\t1.234567 + .t tag delete x + .t tag configure x -tabs {120 numeric} + .t tag add x 1.0 end + .t tag add y 1.5 + lindex [.t bbox 1.3] 0 +} {120} +test textDisp-26.11 {AdjustForTab procedure, numeric alignment} { + .t delete 1.0 end + .t insert 1.0 a\tx=1.234567 + .t tag delete x + .t tag configure x -tabs {120 numeric} + .t tag add x 1.0 end + .t tag add y 1.7 + .t tag add y 1.9 + lindex [.t bbox 1.5] 0 +} {120} +test textDisp-26.12 {AdjustForTab procedure, adjusting chunks} { + .t delete 1.0 end + .t insert 1.0 a\tx1.234567 + .t tag delete x + .t tag configure x -tabs {120 numeric} + .t tag add x 1.0 end + .t tag add y 1.7 + .t tag add y 1.9 + button .b -text "=" + .t window create 1.3 -window .b + update + lindex [.t bbox 1.5] 0 +} {120} +test textDisp-26.13 {AdjustForTab procedure, not enough space} {fonts} { + .t delete 1.0 end + .t insert 1.0 "abc\txyz\tqrs\txyz\t0" + .t tag delete x + .t tag configure x -tabs {10 30 center 50 right 120} + .t tag add x 1.0 end + list [lindex [.t bbox 1.4] 0] [lindex [.t bbox 1.8] 0] \ + [lindex [.t bbox 1.12] 0] [lindex [.t bbox 1.16] 0] +} {28 56 84 120} + +.t configure -width 20 -bd 2 -highlightthickness 2 -relief sunken -tabs {} \ + -wrap char +update +test textDisp-27.1 {SizeOfTab procedure, old-style tabs} {fonts} { + .t delete 1.0 end + .t insert 1.0 a\tbcdefghij\tc\td + list [.t bbox 1.2] [.t bbox 1.10] [.t bbox 1.12] +} {{60 5 7 13} {116 5 7 13} {4 18 7 13}} +test textDisp-27.2 {SizeOfTab procedure, choosing tabX and alignment} {fonts} { + .t delete 1.0 end + .t insert 1.0 a\tbcd + .t tag delete x + .t tag configure x -tabs 120 + .t tag add x 1.0 end + list [.t bbox 1.3] [.t bbox 1.4] +} {{131 5 13 13} {4 18 7 13}} +test textDisp-27.3 {SizeOfTab procedure, choosing tabX and alignment} {fonts} { + .t delete 1.0 end + .t insert 1.0 a\t\t\tbcd + .t tag delete x + .t tag configure x -tabs 40 + .t tag add x 1.0 end + list [.t bbox 1.5] [.t bbox 1.6] +} {{131 5 13 13} {4 18 7 13}} +test textDisp-27.4 {SizeOfTab procedure, choosing tabX and alignment} {fonts} { + .t delete 1.0 end + .t insert 1.0 a\t\t\tbcd + .t tag delete x + .t tag configure x -tabs {20 center 70 left} + .t tag add x 1.0 end + list [.t bbox 1.5] [.t bbox 1.6] +} {{131 5 13 13} {4 18 7 13}} +test textDisp-27.5 {SizeOfTab procedure, center alignment} {fonts} { + .t delete 1.0 end + .t insert 1.0 a\txyzzyabc + .t tag delete x + .t tag configure x -tabs {120 center} + .t tag add x 1.0 end + list [.t bbox 1.6] [.t bbox 1.7] +} {{135 5 9 13} {4 18 7 13}} +test textDisp-27.6 {SizeOfTab procedure, center alignment} {fonts} { + .t delete 1.0 end + .t insert 1.0 a\txyzzyabc + .t tag delete x + .t tag configure x -tabs {150 center} + .t tag add x 1.0 end + list [.t bbox 1.6] [.t bbox 1.7] +} {{32 18 7 13} {39 18 7 13}} +test textDisp-27.7 {SizeOfTab procedure, center alignment, wrap -none (potential numerical problems)} {fonts} { + .t delete 1.0 end + .t configure -tabs {1c 2c center 3c 4c} -wrap none -width 40 + .t insert 1.0 a\tb\tc\td\te\n012345678934567890a\tbb\tcc\tdd + update + .t bbox 2.24 +} {172 18 7 13} +.t configure -wrap char -tabs {} -width 20 +update +test textDisp-27.8 {SizeOfTab procedure, right alignment} {fonts} { + .t delete 1.0 end + .t insert 1.0 a\t\txyzzyabc + .t tag delete x + .t tag configure x -tabs {100 left 140 right} + .t tag add x 1.0 end + list [.t bbox 1.6] [.t bbox 1.7] +} {{137 5 7 13} {4 18 7 13}} +test textDisp-27.9 {SizeOfTab procedure, left alignment} {fonts} { + .t delete 1.0 end + .t insert 1.0 a\txyzzyabc + .t tag delete x + .t tag configure x -tabs {120} + .t tag add x 1.0 end + list [.t bbox 1.3] [.t bbox 1.4] +} {{131 5 13 13} {4 18 7 13}} +test textDisp-27.10 {SizeOfTab procedure, numeric alignment} {fonts} { + .t delete 1.0 end + .t insert 1.0 a\t123.4 + .t tag delete x + .t tag configure x -tabs {120 numeric} + .t tag add x 1.0 end + list [.t bbox 1.3] [.t bbox 1.4] +} {{117 5 27 13} {4 18 7 13}} +test textDisp-27.11 {SizeOfTab procedure, making tabs at least as wide as a space} {fonts} { + .t delete 1.0 end + .t insert 1.0 abc\tdefghijklmnopqrst + .t tag delete x + .t tag configure x -tabs {120} + .t tag add x 1.0 end + list [.t bbox 1.5] [.t bbox 1.6] +} {{131 5 13 13} {4 18 7 13}} + +proc bizarre_scroll args { + .t2.t delete 5.0 end +} +test textDisp-28.1 {"yview" option with bizarre scroll command} { + catch {destroy .t2} + toplevel .t2 + text .t2.t -width 40 -height 4 + .t2.t insert end "1\n2\n3\n4\n5\n6\n7\n8\n" + pack .t2.t + wm geometry .t2 +0+0 + update + .t2.t configure -yscrollcommand bizarre_scroll + .t2.t yview 100.0 + set result [.t2.t index @0,0] + update + lappend result [.t2.t index @0,0] +} {6.0 1.0} + +test textDisp-29.1 {miscellaneous: lines wrap but are still too long} {fonts} { + catch {destroy .t2} + toplevel .t2 + wm geometry .t2 +0+0 + text .t2.t -width 20 -height 10 -font $fixedFont \ + -wrap char -xscrollcommand ".t2.s set" + pack .t2.t -side top + scrollbar .t2.s -orient horizontal -command ".t2.t xview" + pack .t2.s -side bottom -fill x + .t2.t insert end 123 + frame .t2.t.f -width 300 -height 50 -bd 2 -relief raised + .t2.t window create 1.1 -window .t2.t.f + update + list [.t2.t xview] [winfo geom .t2.t.f] [.t2.t bbox 1.3] +} {{0 0.466667} 300x50+5+18 {12 68 7 13}} +test textDisp-29.2 {miscellaneous: lines wrap but are still too long} {fonts} { + catch {destroy .t2} + toplevel .t2 + wm geometry .t2 +0+0 + text .t2.t -width 20 -height 10 -font $fixedFont \ + -wrap char -xscrollcommand ".t2.s set" + pack .t2.t -side top + scrollbar .t2.s -orient horizontal -command ".t2.t xview" + pack .t2.s -side bottom -fill x + .t2.t insert end 123 + frame .t2.t.f -width 300 -height 50 -bd 2 -relief raised + .t2.t window create 1.1 -window .t2.t.f + .t2.t xview scroll 1 unit + update + list [.t2.t xview] [winfo geom .t2.t.f] [.t2.t bbox 1.3] +} {{0.0233333 0.49} 300x50+-2+18 {5 68 7 13}} +test textDisp-29.3 {miscellaneous: lines wrap but are still too long} {fonts} { + catch {destroy .t2} + toplevel .t2 + wm geometry .t2 +0+0 + text .t2.t -width 20 -height 10 -font $fixedFont \ + -wrap char -xscrollcommand ".t2.s set" + pack .t2.t -side top + scrollbar .t2.s -orient horizontal -command ".t2.t xview" + pack .t2.s -side bottom -fill x + .t2.t insert end 123 + frame .t2.t.f -width 300 -height 50 -bd 2 -relief raised + .t2.t window create 1.1 -window .t2.t.f + update + .t2.t xview scroll 200 units + update + list [.t2.t xview] [winfo geom .t2.t.f] [.t2.t bbox 1.3] +} {{0.536667 1} 300x50+-156+18 {}} + +foreach i [winfo children .] { + catch {destroy $i} +} +option clear diff --git a/tests/textImage.test b/tests/textImage.test new file mode 100644 index 0000000..80d083c --- /dev/null +++ b/tests/textImage.test @@ -0,0 +1,353 @@ +# SCCS: @(#) textImage.test 1.8 97/07/01 18:11:54 + +if {[string compare test [info procs test]] == 1} then \ + {source ../tests/defs} + +# Test Arguments: +# name - Name of test, in the form foo-1.2. +# description - Short textual description of the test, to +# help humans understand what it does. +# constraints - A list of one or more keywords, each of +# which must be the name of an element in +# the array "testConfig". If any of these +# elements is zero, the test is skipped. +# This argument may be omitted. +# script - Script to run to carry out the test. It must +# return a result that can be checked for +# correctness. +# answer - Expected result from script. + +# One time setup. Create a font to insure the tests are font metric invariant. + +wm geometry . {} +catch {destroy .t} +font create test_font -family courier -size 14 +text .t -font test_font +destroy .t + +test textImage-1.1 {basic argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image} msg] $msg +} {1 {wrong # args: should be ".t image option ?arg arg ...?"}} + +test textImage-1.2 {basic argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image c} msg] $msg +} {1 {bad image option "c": must be cget, configure, create, or names}} + +test textImage-1.3 {cget argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image cget} msg] $msg +} {1 {wrong # args: should be ".t image cget index option"}} + +test textImage-1.4 {cget argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image cget blurf -flurp} msg] $msg +} {1 {bad text index "blurf"}} + +test textImage-1.5 {cget argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image cget 1.1 -flurp} msg] $msg +} {1 {no embedded image at index "1.1"}} + +test textImage-1.6 {configure argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image configure } msg] $msg +} {1 {wrong # args: should be ".t image configure index ?option value ...?"}} + +test textImage-1.7 {configure argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image configure blurf } msg] $msg +} {1 {bad text index "blurf"}} + +test textImage-1.8 {configure argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image configure 1.1 } msg] $msg +} {1 {no embedded image at index "1.1"}} + +test textImage-1.9 {create argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image create} msg] $msg +} {1 {wrong # args: should be ".t image create index ?option value ...?"}} + +test textImage-1.10 {create argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image create blurf } msg] $msg +} {1 {bad text index "blurf"}} + +test textImage-1.11 {basic argument checking} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image create 1000.1000 -image small} msg] $msg +} {0 small} + +test textImage-1.12 {names argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image names dates places} msg] $msg +} {1 {wrong # args: should be ".t image names"}} + + +test textImage-1.13 {names argument checking} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + set result "" + lappend result [.t image names] + .t image create insert -image small + lappend result [.t image names] + .t image create insert -image small + lappend result [.t image names] + .t image create insert -image small -name little + lappend result [.t image names] +} {{} small {small#1 small} {small#1 small little}} + +test textImage-1.14 {basic argument checking} { + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image huh} msg] $msg +} {1 {bad image option "huh": must be cget, configure, create, or names}} + +test textImage-1.15 {align argument checking} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + list [catch {.t image create end -image small -align wrong} msg] $msg +} {1 {bad alignment "wrong": must be baseline, bottom, center, or top}} + +test textImage-1.16 {configure} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + .t image create end -image small + .t image configure small +} {{-align {} {} center center} {-padx {} {} 0 0} {-pady {} {} 0 0} {-image {} {} {} small} {-name {} {} {} {}}} + +test textImage-1.17 {basic cget options} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + .t image create end -image small + set result "" + foreach i {align padx pady image name} { + lappend result $i:[.t image cget small -$i] + } + set result +} {align:center padx:0 pady:0 image:small name:} + +test textImage-1.18 {basic configure options} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + image create photo large -width 50 -height 50 + large put green -to 0 0 50 50 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + .t image create end -image small + set result "" + foreach {option value} {align top padx 5 pady 7 image large name none} { + .t image configure small -$option $value + } + update + .t image configure small +} {{-align {} {} center top} {-padx {} {} 0 5} {-pady {} {} 0 7} {-image {} {} {} large} {-name {} {} {} none}} + +test textImage-1.19 {basic image naming} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + .t image create end -image small + .t image create end -image small -name small + .t image create end -image small -name small#6342 + .t image create end -image small -name small + lsort [.t image names] +} {small small#1 small#6342 small#6343} + +test textImage-2.1 {debug} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + .t debug 1 + .t insert end front + .t image create end -image small + .t insert end back + .t delete small + .t image names + .t debug 0 +} {} + +test textImage-3.1 {image change propagation} { + catch { + image create photo vary -width 5 -height 5 + small put red -to 0 0 4 4 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + .t image create end -image vary -align top + update + set result "" + lappend result base:[.t bbox vary] + foreach i {10 20 40} { + vary configure -width $i -height $i + update + lappend result $i:[.t bbox vary] + } + set result +} {{base:0 0 5 5} {10:0 0 10 10} {20:0 0 20 20} {40:0 0 40 40}} + +test textImage-3.2 {delayed image management} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + .t image create end -name test + update + set result "" + lappend result [.t bbox test] + .t image configure test -image small -align top + update + lappend result [.t bbox test] +} {{} {0 0 5 5}} + +# some temporary random tests + +test textImage-4.1 {alignment checking - except baseline} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + image create photo large -width 50 -height 50 + large put green -to 0 0 50 50 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + .t image create end -image large + .t image create end -image small + .t insert end test + update + set result "" + lappend result default:[.t bbox small] + foreach i {top bottom center} { + .t image configure small -align $i + update + lappend result [.t image cget small -align]:[.t bbox small] + } + set result +} {{default:50 22 5 5} {top:50 0 5 5} {bottom:50 45 5 5} {center:50 22 5 5}} + +test textImage-4.2 {alignment checking - baseline} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + image create photo large -width 50 -height 50 + large put green -to 0 0 50 50 + } + catch {destroy .t} + font create test_font2 -size 5 + text .t -font test_font2 -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + .t image create end -image large + .t image create end -image small -align baseline + .t insert end test + set result "" + foreach size {10 15 20 30} { + font configure test_font2 -size $size + array set Metrics [font metrics test_font2] + update + foreach {x y w h} [.t bbox small] {} + set norm [expr { + (([image height large] - $Metrics(-linespace))/2 + + $Metrics(-ascent) - [image height small] - $y) + }] + lappend result "$size $norm" + } + font delete test_font2 + unset Metrics + set result +} {{10 0} {15 0} {20 0} {30 0}} + +test textImage-4.3 {alignment and padding checking} {fonts} { + catch { + image create photo small -width 5 -height 5 + small put red -to 0 0 4 4 + image create photo large -width 50 -height 50 + large put green -to 0 0 50 50 + } + catch {destroy .t} + text .t -font test_font -bd 0 -highlightthickness 0 -padx 0 -pady 0 + pack .t + .t image create end -image large + .t image create end -image small -padx 5 -pady 10 + .t insert end test + update + set result "" + lappend result default:[.t bbox small] + foreach i {top bottom center baseline} { + .t image configure small -align $i + update + lappend result $i:[.t bbox small] + } + set result +} {{default:55 22 5 5} {top:55 10 5 5} {bottom:55 35 5 5} {center:55 22 5 5} {baseline:55 22 5 5}} +# cleanup + +catch {destroy .t} +foreach image [image names] {image delete $image} +font delete test_font diff --git a/tests/textIndex.test b/tests/textIndex.test new file mode 100644 index 0000000..df30951 --- /dev/null +++ b/tests/textIndex.test @@ -0,0 +1,349 @@ +# This file is a Tcl script to test the code in the file tkTextIndex.c. +# This file is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) textIndex.test 1.9 96/06/24 16:46:55 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +catch {destroy .t} +if [catch {text .t -font {Courier 12} -width 20 -height 10}] { + puts "The font needed by these tests isn't available, so I'm" + puts "going to skip the tests." + return +} +pack append . .t {top expand fill} +update +.t debug on +wm geometry . {} + +# The statements below reset the main window; it's needed if the window +# manager is mwm to make mwm forget about a previous minimum size setting. + +wm withdraw . +wm minsize . 1 1 +wm positionfrom . user +wm deiconify . + +.t insert 1.0 "Line 1 +abcdefghijklm +12345 +Line 4 +bOy GIrl .#@? x_yz +!@#$% +Line 7" + +test textIndex-1.1 {TkTextMakeIndex} { + .t index -1.3 +} 1.0 +test textIndex-1.2 {TkTextMakeIndex} { + .t index 0.3 +} 1.0 +test textIndex-1.3 {TkTextMakeIndex} { + .t index 1.3 +} 1.3 +test textIndex-1.4 {TkTextMakeIndex} { + .t index 3.-1 +} 3.0 +test textIndex-1.5 {TkTextMakeIndex} { + .t index 3.3 +} 3.3 +test textIndex-1.6 {TkTextMakeIndex} { + .t index 3.5 +} 3.5 +test textIndex-1.7 {TkTextMakeIndex} { + .t index 3.6 +} 3.5 +test textIndex-1.8 {TkTextMakeIndex} { + .t index 3.7 +} 3.5 +test textIndex-1.9 {TkTextMakeIndex} { + .t index 7.2 +} 7.2 +test textIndex-1.10 {TkTextMakeIndex} { + .t index 8.0 +} 8.0 +test textIndex-1.11 {TkTextMakeIndex} { + .t index 8.1 +} 8.0 +test textIndex-1.12 {TkTextMakeIndex} { + .t index 9.0 +} 8.0 + +.t tag add x 2.3 2.6 +test textIndex-2.1 {TkTextIndexToSeg} { + .t get 2.0 +} a +test textIndex-2.2 {TkTextIndexToSeg} { + .t get 2.2 +} c +test textIndex-2.3 {TkTextIndexToSeg} { + .t get 2.3 +} d +test textIndex-2.4 {TkTextIndexToSeg} { + .t get 2.6 +} g +test textIndex-2.5 {TkTextIndexToSeg} { + .t get 2.7 +} h +test textIndex-2.6 {TkTextIndexToSeg} { + .t get 2.12 +} m +test textIndex-2.7 {TkTextIndexToSeg} { + .t get 2.13 +} \n +test textIndex-2.8 {TkTextIndexToSeg} { + .t get 2.14 +} \n +.t tag delete x + +.t mark set foo 3.2 +.t tag add x 2.8 2.11 +.t tag add x 6.0 6.2 +set weirdTag "funny . +- 22.1\n\t{" +.t tag add $weirdTag 2.1 2.6 +set weirdMark "asdf \n{-+ 66.2\t" +.t mark set $weirdMark 4.0 +.t tag config y -relief raised +test textIndex-3.1 {TkTextGetIndex, weird mark names} { + list [catch {.t index $weirdMark} msg] $msg +} {0 4.0} + +test textIndex-4.1 {TkTextGetIndex, tags} { + list [catch {.t index x.first} msg] $msg +} {0 2.8} +test textIndex-4.2 {TkTextGetIndex, tags} { + list [catch {.t index x.last} msg] $msg +} {0 6.2} +test textIndex-4.3 {TkTextGetIndex, weird tags} { + list [.t index $weirdTag.first+1c] [.t index $weirdTag.last+2c] +} {2.2 2.8} +test textIndex-4.4 {TkTextGetIndex, tags} { + list [catch {.t index x.gorp} msg] $msg +} {1 {bad text index "x.gorp"}} +test textIndex-4.5 {TkTextGetIndex, tags} { + list [catch {.t index foo.last} msg] $msg +} {1 {bad text index "foo.last"}} +test textIndex-4.6 {TkTextGetIndex, tags} { + list [catch {.t index y.first} msg] $msg +} {1 {text doesn't contain any characters tagged with "y"}} +test textIndex-4.7 {TkTextGetIndex, tags} { + list [catch {.t index x.last,} msg] $msg +} {1 {bad text index "x.last,"}} +test textIndex-4.8 {TkTextGetIndex, tags} { + .t tag add z 1.0 + set result [list [.t index z.first] [.t index z.last]] + .t tag delete z + set result +} {1.0 1.1} + +test textIndex-5.1 {TkTextGetIndex, "@"} {fonts} { + .t index @12,9 +} 1.1 +test textIndex-5.2 {TkTextGetIndex, "@"} {fonts} { + .t index @-2,7 +} 1.0 +test textIndex-5.3 {TkTextGetIndex, "@"} {fonts} { + .t index @10,-7 +} 1.0 +test textIndex-5.4 {TkTextGetIndex, "@"} {fonts} { + list [catch {.t index @x} msg] $msg +} {1 {bad text index "@x"}} +test textIndex-5.5 {TkTextGetIndex, "@"} {fonts} { + list [catch {.t index @10q} msg] $msg +} {1 {bad text index "@10q"}} +test textIndex-5.6 {TkTextGetIndex, "@"} {fonts} { + list [catch {.t index @10,} msg] $msg +} {1 {bad text index "@10,"}} +test textIndex-5.7 {TkTextGetIndex, "@"} {fonts} { + list [catch {.t index @10,a} msg] $msg +} {1 {bad text index "@10,a"}} +test textIndex-5.8 {TkTextGetIndex, "@"} {fonts} { + list [catch {.t index @10,9,} msg] $msg +} {1 {bad text index "@10,9,"}} + +test textIndex-6.1 {TkTextGetIndex, numeric} { + list [catch {.t index 2.3} msg] $msg +} {0 2.3} +test textIndex-6.2 {TkTextGetIndex, numeric} { + list [catch {.t index -} msg] $msg +} {1 {bad text index "-"}} +test textIndex-6.3 {TkTextGetIndex, numeric} { + list [catch {.t index 2.end} msg] $msg +} {0 2.13} +test textIndex-6.4 {TkTextGetIndex, numeric} { + list [catch {.t index 2.x} msg] $msg +} {1 {bad text index "2.x"}} +test textIndex-6.5 {TkTextGetIndex, numeric} { + list [catch {.t index 2.3x} msg] $msg +} {1 {bad text index "2.3x"}} + +test textIndex-7.1 {TkTextGetIndex, miscellaneous other bases} { + list [catch {.t index end} msg] $msg +} {0 8.0} +test textIndex-7.2 {TkTextGetIndex, miscellaneous other bases} { + list [catch {.t index foo} msg] $msg +} {0 3.2} +test textIndex-7.3 {TkTextGetIndex, miscellaneous other bases} { + list [catch {.t index foo+1c} msg] $msg +} {0 3.3} + +test textIndex-8.1 {TkTextGetIndex, modifiers} { + list [catch {.t index 2.1+1char} msg] $msg +} {0 2.2} +test textIndex-8.2 {TkTextGetIndex, modifiers} { + list [catch {.t index "2.1 +1char"} msg] $msg +} {0 2.2} +test textIndex-8.3 {TkTextGetIndex, modifiers} { + list [catch {.t index 2.1-1char} msg] $msg +} {0 2.0} +test textIndex-8.4 {TkTextGetIndex, modifiers} { + list [catch {.t index {2.1 }} msg] $msg +} {0 2.1} +test textIndex-8.5 {TkTextGetIndex, modifiers} { + list [catch {.t index {2.1+foo bar}} msg] $msg +} {1 {bad text index "2.1+foo bar"}} +test textIndex-8.6 {TkTextGetIndex, modifiers} { + list [catch {.t index {2.1 foo bar}} msg] $msg +} {1 {bad text index "2.1 foo bar"}} + +test textIndex-9.1 {TkTextIndexCmp} { + list [.t compare 3.1 < 3.2] [.t compare 3.1 == 3.2] +} {1 0} +test textIndex-9.2 {TkTextIndexCmp} { + list [.t compare 3.2 < 3.2] [.t compare 3.2 == 3.2] +} {0 1} +test textIndex-9.3 {TkTextIndexCmp} { + list [.t compare 3.3 < 3.2] [.t compare 3.3 == 3.2] +} {0 0} +test textIndex-9.4 {TkTextIndexCmp} { + list [.t compare 2.1 < 3.2] [.t compare 2.1 == 3.2] +} {1 0} +test textIndex-9.5 {TkTextIndexCmp} { + list [.t compare 4.1 < 3.2] [.t compare 4.1 == 3.2] +} {0 0} + +test textIndex-10.1 {ForwBack} { + list [catch {.t index {2.3 + x}} msg] $msg +} {1 {bad text index "2.3 + x"}} +test textIndex-10.2 {ForwBack} { + list [catch {.t index {2.3 + 2 chars}} msg] $msg +} {0 2.5} +test textIndex-10.3 {ForwBack} { + list [catch {.t index {2.3 + 2c}} msg] $msg +} {0 2.5} +test textIndex-10.4 {ForwBack} { + list [catch {.t index {2.3 - 3ch}} msg] $msg +} {0 2.0} +test textIndex-10.5 {ForwBack} { + list [catch {.t index {2.3 + 3 lines}} msg] $msg +} {0 5.3} +test textIndex-10.6 {ForwBack} { + list [catch {.t index {2.3 -1l}} msg] $msg +} {0 1.3} +test textIndex-10.7 {ForwBack} { + list [catch {.t index {2.3 -1 gorp}} msg] $msg +} {1 {bad text index "2.3 -1 gorp"}} +test textIndex-10.8 {ForwBack} { + list [catch {.t index {2.3 - 4 lines}} msg] $msg +} {0 1.3} + +test textIndex-11.1 {TkTextIndexForwChars} { + .t index {2.3 + -7 chars} +} 1.3 +test textIndex-11.2 {TkTextIndexForwChars} { + .t index {2.3 + 5 chars} +} 2.8 +test textIndex-11.3 {TkTextIndexForwChars} { + .t index {2.3 + 10 chars} +} 2.13 +test textIndex-11.4 {TkTextIndexForwChars} { + .t index {2.3 + 11 chars} +} 3.0 +test textIndex-11.5 {TkTextIndexForwChars} { + .t index {2.3 + 55 chars} +} 7.6 +test textIndex-11.6 {TkTextIndexForwChars} { + .t index {2.3 + 56 chars} +} 8.0 +test textIndex-11.7 {TkTextIndexForwChars} { + .t index {2.3 + 57 chars} +} 8.0 + +test textIndex-12.1 {TkTextIndexBackChars} { + .t index {3.2 - -10 chars} +} 4.6 +test textIndex-12.2 {TkTextIndexBackChars} { + .t index {3.2 - 2 chars} +} 3.0 +test textIndex-12.3 {TkTextIndexBackChars} { + .t index {3.2 - 3 chars} +} 2.13 +test textIndex-12.4 {TkTextIndexBackChars} { + .t index {3.2 - 22 chars} +} 1.1 +test textIndex-12.5 {TkTextIndexBackChars} { + .t index {3.2 - 23 chars} +} 1.0 +test textIndex-12.6 {TkTextIndexBackChars} { + .t index {3.2 - 24 chars} +} 1.0 + +proc getword index { + .t get [.t index "$index wordstart"] [.t index "$index wordend"] +} +test textIndex-13.1 {StartEnd} { + list [catch {.t index {2.3 lineend}} msg] $msg +} {0 2.13} +test textIndex-13.2 {StartEnd} { + list [catch {.t index {2.3 linee}} msg] $msg +} {0 2.13} +test textIndex-13.3 {StartEnd} { + list [catch {.t index {2.3 line}} msg] $msg +} {1 {bad text index "2.3 line"}} +test textIndex-13.4 {StartEnd} { + list [catch {.t index {2.3 linestart}} msg] $msg +} {0 2.0} +test textIndex-13.5 {StartEnd} { + list [catch {.t index {2.3 lines}} msg] $msg +} {0 2.0} +test textIndex-13.6 {StartEnd} { + getword 5.3 +} { } +test textIndex-13.7 {StartEnd} { + getword 5.4 +} GIrl +test textIndex-13.8 {StartEnd} { + getword 5.7 +} GIrl +test textIndex-13.9 {StartEnd} { + getword 5.8 +} { } +test textIndex-13.10 {StartEnd} { + getword 5.14 +} x_yz +test textIndex-13.11 {StartEnd} { + getword 6.2 +} # +test textIndex-13.12 {StartEnd} { + getword 3.4 +} 12345 +.t tag add x 2.8 2.11 +test textIndex-13.13 {StartEnd} { + list [catch {.t index {2.2 worde}} msg] $msg +} {0 2.13} +test textIndex-13.14 {StartEnd} { + list [catch {.t index {2.12 words}} msg] $msg +} {0 2.0} +test textIndex-13.15 {StartEnd} { + list [catch {.t index {2.12 word}} msg] $msg +} {1 {bad text index "2.12 word"}} + +catch {destroy .t} +concat diff --git a/tests/textMark.test b/tests/textMark.test new file mode 100644 index 0000000..39a0961 --- /dev/null +++ b/tests/textMark.test @@ -0,0 +1,222 @@ +# This file is a Tcl script to test the code in the file tkTextMark.c. +# This file is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) textMark.test 1.8 97/10/20 11:13:00 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +catch {destroy .t} +if [catch {text .t -font {Courier 12} -width 20 -height 10}] { + puts "The font needed by these tests isn't available, so I'm" + puts "going to skip the tests." + return +} +pack append . .t {top expand fill} +update +.t debug on +wm geometry . {} + +# The statements below reset the main window; it's needed if the window +# manager is mwm to make mwm forget about a previous minimum size setting. + +wm withdraw . +wm minsize . 1 1 +wm positionfrom . user +wm deiconify . + +entry .t.e +.t insert 1.0 "Line 1 +abcdefghijklm +12345 +Line 4 +bOy GIrl .#@? x_yz +!@#$% +Line 7" + +test textMark-1.1 {TkTextMarkCmd - missing option} { + list [catch {.t mark} msg] $msg +} {1 {wrong # args: should be ".t mark option ?arg arg ...?"}} +test textMark-1.2 {TkTextMarkCmd - bogus option} { + list [catch {.t mark gorp} msg] $msg +} {1 {bad mark option "gorp": must be gravity, names, next, previous, set, or unset}} +test textMark-1.3 {TkTextMarkCmd - "gravity" option} { + list [catch {.t mark gravity foo} msg] $msg +} {1 {there is no mark named "foo"}} +test textMark-1.4 {TkTextMarkCmd - "gravity" option} { + .t mark unset x + .t mark set x 1.3 + .t insert 1.3 x + list [.t mark gravity x] [.t index x] +} {right 1.4} +test textMark-1.5 {TkTextMarkCmd - "gravity" option} { + .t mark unset x + .t mark set x 1.3 + .t mark g x left + .t insert 1.3 x + list [.t mark gravity x] [.t index x] +} {left 1.3} +test textMark-1.6 {TkTextMarkCmd - "gravity" option} { + .t mark unset x + .t mark set x 1.3 + .t mark gravity x right + .t insert 1.3 x + list [.t mark gravity x] [.t index x] +} {right 1.4} +test textMark-1.7 {TkTextMarkCmd - "gravity" option} { + list [catch {.t mark gravity x gorp} msg] $msg +} {1 {bad mark gravity "gorp": must be left or right}} +test textMark-1.8 {TkTextMarkCmd - "gravity" option} { + list [catch {.t mark gravity} msg] $msg +} {1 {wrong # args: should be ".t mark gravity markName ?gravity?"}} + +test textMark-2.1 {TkTextMarkCmd - "names" option} { + list [catch {.t mark names 2} msg] $msg +} {1 {wrong # args: should be ".t mark names"}} +.t mark unset x +test textMark-2.2 {TkTextMarkCmd - "names" option} { + lsort [.t mark n] +} {current insert} +test textMark-2.3 {TkTextMarkCmd - "names" option} { + .t mark set a 1.1 + .t mark set "b c" 2.3 + lsort [.t mark names] +} {a {b c} current insert} + +test textMark-3.1 {TkTextMarkCmd - "set" option} { + list [catch {.t mark set a} msg] $msg +} {1 {wrong # args: should be ".t mark set markName index"}} +test textMark-3.2 {TkTextMarkCmd - "set" option} { + list [catch {.t mark s a b c} msg] $msg +} {1 {wrong # args: should be ".t mark set markName index"}} +test textMark-3.3 {TkTextMarkCmd - "set" option} { + list [catch {.t mark set a @x} msg] $msg +} {1 {bad text index "@x"}} +test textMark-3.4 {TkTextMarkCmd - "set" option} { + .t mark set a 1.2 + .t index a +} 1.2 +test textMark-3.5 {TkTextMarkCmd - "set" option} { + .t mark set a end + .t index a +} {8.0} + +test textMark-4.1 {TkTextMarkCmd - "unset" option} { + list [catch {.t mark unset} msg] $msg +} {0 {}} +test textMark-4.2 {TkTextMarkCmd - "unset" option} { + .t mark set a 1.2 + .t mark set b 2.3 + .t mark unset a b + list [catch {.t index a} msg] $msg [catch {.t index b} msg2] $msg2 +} {1 {bad text index "a"} 1 {bad text index "b"}} +test textMark-4.3 {TkTextMarkCmd - "unset" option} { + .t mark set a 1.2 + .t mark set b 2.3 + .t mark set 49ers 3.1 + eval .t mark unset [.t mark names] + lsort [.t mark names] +} {current insert} + +test textMark-5.1 {TkTextMarkCmd - miscellaneous} { + list [catch {.t mark} msg] $msg +} {1 {wrong # args: should be ".t mark option ?arg arg ...?"}} +test textMark-5.2 {TkTextMarkCmd - miscellaneous} { + list [catch {.t mark foo} msg] $msg +} {1 {bad mark option "foo": must be gravity, names, next, previous, set, or unset}} + +test textMark-6.1 {TkTextMarkSegToIndex} { + .t mark set a 1.2 + .t mark set b 1.2 + .t mark set c 1.2 + .t mark set d 1.4 + list [.t index a] [.t index b] [.t index c ] [.t index d] +} {1.2 1.2 1.2 1.4} + +catch {eval {.t mark unset} [.t mark names]} +test textMark-7.1 {MarkFindNext - invalid mark name} { + catch {.t mark next bogus} x + set x +} {bad text index "bogus"} +test textMark-7.2 {MarkFindNext - marks at same location} { + .t mark set insert 2.0 + .t mark set current 2.0 + .t mark next current +} {insert} +test textMark-7.3 {MarkFindNext - numerical starting mark} { + .t mark set current 1.0 + .t mark set insert 1.0 + .t mark next 1.0 +} {insert} +test textMark-7.4 {MarkFindNext - mark on the same line} { + .t mark set current 1.0 + .t mark set insert 1.1 + .t mark next current +} {insert} +test textMark-7.5 {MarkFindNext - mark on the next line} { + .t mark set current 1.end + .t mark set insert 2.0 + .t mark next current +} {insert} +test textMark-7.6 {MarkFindNext - mark far away} { + .t mark set current 1.2 + .t mark set insert 7.0 + .t mark next current +} {insert} +test textMark-7.7 {MarkFindNext - mark on top of end} { + .t mark set current end + .t mark next end +} {current} +test textMark-7.8 {MarkFindNext - no next mark} { + .t mark set current 1.0 + .t mark set insert 3.0 + .t mark next insert +} {} +test textMark-8.1 {MarkFindPrev - invalid mark name} { + catch {.t mark prev bogus} x + set x +} {bad text index "bogus"} +test textMark-8.2 {MarkFindPrev - marks at same location} { + .t mark set insert 2.0 + .t mark set current 2.0 + .t mark prev insert +} {current} +test textMark-8.3 {MarkFindPrev - numerical starting mark} { + .t mark set current 1.0 + .t mark set insert 1.0 + .t mark prev 1.1 +} {current} +test textMark-8.4 {MarkFindPrev - mark on the same line} { + .t mark set current 1.0 + .t mark set insert 1.1 + .t mark prev insert +} {current} +test textMark-8.5 {MarkFindPrev - mark on the previous line} { + .t mark set current 1.end + .t mark set insert 2.0 + .t mark prev insert +} {current} +test textMark-8.6 {MarkFindPrev - mark far away} { + .t mark set current 1.2 + .t mark set insert 7.0 + .t mark prev insert +} {current} +test textMark-8.7 {MarkFindPrev - mark on top of end} { + .t mark set insert 3.0 + .t mark set current end + .t mark prev end +} {insert} +test textMark-8.8 {MarkFindPrev - no previous mark} { + .t mark set current 1.0 + .t mark set insert 3.0 + .t mark prev current +} {} + +catch {destroy .t} +concat {} diff --git a/tests/textTag.test b/tests/textTag.test new file mode 100644 index 0000000..ae0d33a --- /dev/null +++ b/tests/textTag.test @@ -0,0 +1,756 @@ +# This file is a Tcl script to test the code in the file tkTextTag.c. +# This file is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) textTag.test 1.30 97/11/06 16:57:02 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +catch {destroy .t} +if [catch {text .t -font {Courier 12} -width 20 -height 10}] { + puts "The font needed by these tests isn't available, so I'm" + puts "going to skip the tests." + return +} +pack append . .t {top expand fill} +update +.t debug on +wm geometry . {} +set bigFont {Helvetica 24} + +# The statements below reset the main window; it's needed if the window +# manager is mwm, to make mwm forget about a previous minimum size setting. + +wm withdraw . +wm minsize . 1 1 +wm positionfrom . user +wm deiconify . + +entry .t.e +.t.e insert 0 "Text" + +.t insert 1.0 "Line 1 +abcdefghijklm +12345 +Line 4 +bOy GIrl .#@? x_yz +!@#$% +Line 7" + + +set i 1 +foreach test { + {-background #012345 #012345 non-existent + {unknown color name "non-existent"}} + {-bgstipple gray50 gray50 badStipple + {bitmap "badStipple" not defined}} + {-borderwidth 2 2 46q + {bad screen distance "46q"}} + {-fgstipple gray25 gray25 bogus + {bitmap "bogus" not defined}} + {-font fixed fixed {} + {font "" doesn't exist}} + {-foreground #001122 #001122 {silly color} + {unknown color name "silly color"}} + {-justify left left middle + {bad justification "middle": must be left, right, or center}} + {-lmargin1 10 10 bad + {bad screen distance "bad"}} + {-lmargin2 10 10 bad + {bad screen distance "bad"}} + {-offset 2 2 100xyz + {bad screen distance "100xyz"}} + {-overstrike on on stupid + {expected boolean value but got "stupid"}} + {-relief raised raised stupid + {bad relief type "stupid": must be flat, groove, raised, ridge, solid, or sunken}} + {-rmargin 10 10 bad + {bad screen distance "bad"}} + {-spacing1 10 10 bad + {bad screen distance "bad"}} + {-spacing2 10 10 bad + {bad screen distance "bad"}} + {-spacing3 10 10 bad + {bad screen distance "bad"}} + {-tabs {10 20 30} {10 20 30} {10 fork} + {bad tab alignment "fork": must be left, right, center, or numeric}} + {-underline no no stupid + {expected boolean value but got "stupid"}} +} { + set name [lindex $test 0] + test textTag-1.$i {tag configuration options} { + .t tag configure x $name [lindex $test 1] + .t tag cget x $name + } [lindex $test 2] + incr i + if {[lindex $test 3] != ""} { + test textTag-1.$i {configuration options} { + list [catch {.t tag configure x $name [lindex $test 3]} msg] $msg + } [list 1 [lindex $test 4]] + } + .t tag configure x $name [lindex [.t tag configure x $name] 3] + incr i +} +test textTag-2.1 {TkTextTagCmd - "add" option} { + list [catch {.t tag} msg] $msg +} {1 {wrong # args: should be ".t tag option ?arg arg ...?"}} +test textTag-2.2 {TkTextTagCmd - "add" option} { + list [catch {.t tag gorp} msg] $msg +} {1 {bad tag option "gorp": must be add, bind, cget, configure, delete, lower, names, nextrange, raise, ranges, or remove}} +test textTag-2.3 {TkTextTagCmd - "add" option} { + list [catch {.t tag add foo} msg] $msg +} {1 {wrong # args: should be ".t tag add tagName index1 ?index2 index1 index2 ...?"}} +test textTag-2.4 {TkTextTagCmd - "add" option} { + list [catch {.t tag add x gorp} msg] $msg +} {1 {bad text index "gorp"}} +test textTag-2.5 {TkTextTagCmd - "add" option} { + list [catch {.t tag add x 1.2 gorp} msg] $msg +} {1 {bad text index "gorp"}} +test textTag-2.6 {TkTextTagCmd - "add" option} { + .t tag add sel 3.2 3.4 + .t tag add sel 3.2 3.0 + .t tag ranges sel +} {3.2 3.4} +test textTag-2.7 {TkTextTagCmd - "add" option} { + .t tag add x 1.0 1.end + .t tag ranges x +} {1.0 1.6} +test textTag-2.8 {TkTextTagCmd - "add" option} { + .t tag remove x 1.0 end + .t tag add x 1.2 + .t tag ranges x +} {1.2 1.3} +test textTag-2.9 {TkTextTagCmd - "add" option} { + .t.e select from 0 + .t.e select to 4 + .t tag add sel 3.2 3.4 + selection get +} 34 +test textTag-2.11 {TkTextTagCmd - "add" option} { + .t.e select from 0 + .t.e select to 4 + .t configure -exportselection 0 + .t tag add sel 3.2 3.4 + selection get +} Text +test textTag-2.12 {TkTextTagCmd - "add" option} { + .t tag remove sel 1.0 end + .t tag add sel 1.1 1.5 2.4 3.1 4.2 4.4 + .t tag ranges sel +} {1.1 1.5 2.4 3.1 4.2 4.4} +test textTag-2.13 {TkTextTagCmd - "add" option} { + .t tag remove sel 1.0 end + .t tag add sel 1.1 1.5 2.4 + .t tag ranges sel +} {1.1 1.5 2.4 2.5} + +catch {.t tag delete x} +test textTag-3.1 {TkTextTagCmd - "bind" option} { + list [catch {.t tag bind} msg] $msg +} {1 {wrong # args: should be ".t tag bind tagName ?sequence? ?command?"}} +test textTag-3.2 {TkTextTagCmd - "bind" option} { + list [catch {.t tag bind 1 2 3 4} msg] $msg +} {1 {wrong # args: should be ".t tag bind tagName ?sequence? ?command?"}} +test textTag-3.3 {TkTextTagCmd - "bind" option} { + .t tag bind x <Enter> script1 + .t tag bind x <Enter> +} script1 +test textTag-3.4 {TkTextTagCmd - "bind" option} { + list [catch {.t tag bind x <Gorp> script2} msg] $msg +} {1 {bad event type or keysym "Gorp"}} +test textTag-3.5 {TkTextTagCmd - "bind" option} { + .t tag delete x + .t tag bind x <Enter> script1 + list [catch {.t tag bind x <FocusIn> script2} msg] $msg [.t tag bind x] +} {1 {requested illegal events; only key, button, motion, enter, leave, and virtual events may be used} <Enter>} +test textTag-3.6 {TkTextTagCmd - "bind" option} { + .t tag delete x + .t tag bind x <Enter> script1 + .t tag bind x <Leave> script2 + .t tag bind x a xyzzy + list [lsort [.t tag bind x]] [.t tag bind x <Enter>] [.t tag bind x a] +} {{<Enter> <Leave> a} script1 xyzzy} +test textTag-3.7 {TkTextTagCmd - "bind" option} { + .t tag delete x + .t tag bind x <Enter> script1 + .t tag bind x <Enter> +script2 + .t tag bind x <Enter> +} {script1 +script2} + + +test textTag-4.1 {TkTextTagCmd - "cget" option} { + list [catch {.t tag cget a} msg] $msg +} {1 {wrong # args: should be ".t tag cget tagName option"}} +test textTag-4.2 {TkTextTagCmd - "cget" option} { + list [catch {.t tag cget a b c} msg] $msg +} {1 {wrong # args: should be ".t tag cget tagName option"}} +test textTag-4.3 {TkTextTagCmd - "cget" option} { + .t tag delete foo + list [catch {.t tag cget foo bar} msg] $msg +} {1 {tag "foo" isn't defined in text widget}} +test textTag-4.4 {TkTextTagCmd - "cget" option} { + list [catch {.t tag cget sel bogus} msg] $msg +} {1 {unknown option "bogus"}} +test textTag-4.5 {TkTextTagCmd - "cget" option} { + .t tag delete x + .t tag configure x -background red + list [catch {.t tag cget x -background} msg] $msg +} {0 red} + +test textTag-5.1 {TkTextTagCmd - "configure" option} { + list [catch {.t tag configure} msg] $msg +} {1 {wrong # args: should be ".t tag configure tagName ?option? ?value? ?option value ...?"}} +test textTag-5.2 {TkTextTagCmd - "configure" option} { + list [catch {.t tag configure x -foo} msg] $msg +} {1 {unknown option "-foo"}} +test textTag-5.3 {TkTextTagCmd - "configure" option} { + list [catch {.t tag configure x -background red -underline} msg] $msg +} {1 {value for "-underline" missing}} +test textTag-5.4 {TkTextTagCmd - "configure" option} { + .t tag delete x + .t tag configure x -underline yes + .t tag configure x -underline +} {-underline {} {} {} yes} +test textTag-5.5 {TkTextTagCmd - "configure" option} { + .t tag delete x + .t tag configure x -overstrike on + .t tag cget x -overstrike +} {on} +test textTag-5.6 {TkTextTagCmd - "configure" option} { + list [catch {.t tag configure x -overstrike foo} msg] $msg +} {1 {expected boolean value but got "foo"}} +test textTag-5.7 {TkTextTagCmd - "configure" option} { + .t tag delete x + list [catch {.t tag configure x -underline stupid} msg] $msg +} {1 {expected boolean value but got "stupid"}} +test textTag-5.8 {TkTextTagCmd - "configure" option} { + .t tag delete x + .t tag configure x -justify left + .t tag configure x -justify +} {-justify {} {} {} left} +test textTag-5.9 {TkTextTagCmd - "configure" option} { + .t tag delete x + list [catch {.t tag configure x -justify bogus} msg] $msg +} {1 {bad justification "bogus": must be left, right, or center}} +test textTag-5.10 {TkTextTagCmd - "configure" option} { + .t tag delete x + list [catch {.t tag configure x -justify fill} msg] $msg +} {1 {bad justification "fill": must be left, right, or center}} +test textTag-5.11 {TkTextTagCmd - "configure" option} { + .t tag delete x + .t tag configure x -offset 2 + .t tag configure x -offset +} {-offset {} {} {} 2} +test textTag-5.12 {TkTextTagCmd - "configure" option} { + .t tag delete x + list [catch {.t tag configure x -offset 1.0q} msg] $msg +} {1 {bad screen distance "1.0q"}} +test textTag-5.13 {TkTextTagCmd - "configure" option} { + .t tag delete x + .t tag configure x -lmargin1 2 -lmargin2 4 -rmargin 5 + list [.t tag configure x -lmargin1] [.t tag configure x -lmargin2] \ + [.t tag configure x -rmargin] +} {{-lmargin1 {} {} {} 2} {-lmargin2 {} {} {} 4} {-rmargin {} {} {} 5}} +test textTag-5.14 {TkTextTagCmd - "configure" option} { + .t tag delete x + list [catch {.t tag configure x -lmargin1 2.0x} msg] $msg +} {1 {bad screen distance "2.0x"}} +test textTag-5.15 {TkTextTagCmd - "configure" option} { + .t tag delete x + list [catch {.t tag configure x -lmargin2 gorp} msg] $msg +} {1 {bad screen distance "gorp"}} +test textTag-5.16 {TkTextTagCmd - "configure" option} { + .t tag delete x + list [catch {.t tag configure x -rmargin 140.1.1} msg] $msg +} {1 {bad screen distance "140.1.1"}} +.t tag delete x +test textTag-5.17 {TkTextTagCmd - "configure" option} { + .t tag delete x + .t tag configure x -spacing1 2 -spacing2 4 -spacing3 6 + list [.t tag configure x -spacing1] [.t tag configure x -spacing2] \ + [.t tag configure x -spacing3] +} {{-spacing1 {} {} {} 2} {-spacing2 {} {} {} 4} {-spacing3 {} {} {} 6}} +test textTag-5.18 {TkTextTagCmd - "configure" option} { + .t tag delete x + list [catch {.t tag configure x -spacing1 2.0x} msg] $msg +} {1 {bad screen distance "2.0x"}} +test textTag-5.19 {TkTextTagCmd - "configure" option} { + .t tag delete x + list [catch {.t tag configure x -spacing1 lousy} msg] $msg +} {1 {bad screen distance "lousy"}} +test textTag-5.20 {TkTextTagCmd - "configure" option} { + .t tag delete x + list [catch {.t tag configure x -spacing1 4.2.3} msg] $msg +} {1 {bad screen distance "4.2.3"}} +test textTag-5.21 {TkTextTagCmd - "configure" option} { + .t configure -selectborderwidth 2 -selectforeground blue \ + -selectbackground black + .t tag configure sel -borderwidth 4 -foreground green -background yellow + set x {} + foreach i {-selectborderwidth -selectforeground -selectbackground} { + lappend x [lindex [.t configure $i] 4] + } + set x +} {4 green yellow} +test textTag-5.22 {TkTextTagCmd - "configure" option} { + .t configure -selectborderwidth 20 + .t tag configure sel -borderwidth {} + .t cget -selectborderwidth +} {} + +test textTag-6.1 {TkTextTagCmd - "delete" option} { + list [catch {.t tag delete} msg] $msg +} {1 {wrong # args: should be ".t tag delete tagName tagName ..."}} +test textTag-6.2 {TkTextTagCmd - "delete" option} { + list [catch {.t tag delete zork} msg] $msg +} {0 {}} +test textTag-6.3 {TkTextTagCmd - "delete" option} { + .t tag delete x + .t tag config x -background black + .t tag config y -foreground white + .t tag config z -background black + .t tag delete y z + lsort [.t tag names] +} {sel x} +test textTag-6.4 {TkTextTagCmd - "delete" option} { + .t tag config x -background black + .t tag config y -foreground white + .t tag config z -background black + eval .t tag delete [.t tag names] + .t tag names +} {sel} +test textTag-6.5 {TkTextTagCmd - "delete" option} { + .t tag bind x <Enter> foo + .t tag delete x + .t tag configure x -background black + .t tag bind x +} {} + +proc tagsetup {} { + .t tag delete x y z a b c d + .t tag remove sel 1.0 end + foreach i {a b c d} { + .t tag configure $i -background black + } +} +test textTag-7.1 {TkTextTagCmd - "lower" option} { + list [catch {.t tag lower} msg] $msg +} {1 {wrong # args: should be ".t tag lower tagName ?belowThis?"}} +test textTag-7.2 {TkTextTagCmd - "lower" option} { + list [catch {.t tag lower foo} msg] $msg +} {1 {tag "foo" isn't defined in text widget}} +test textTag-7.3 {TkTextTagCmd - "lower" option} { + list [catch {.t tag lower sel bar} msg] $msg +} {1 {tag "bar" isn't defined in text widget}} +test textTag-7.4 {TkTextTagCmd - "lower" option} { + tagsetup + .t tag lower c + .t tag names +} {c sel a b d} +test textTag-7.5 {TkTextTagCmd - "lower" option} { + tagsetup + .t tag lower d b + .t tag names +} {sel a d b c} +test textTag-7.6 {TkTextTagCmd - "lower" option} { + tagsetup + .t tag lower a c + .t tag names +} {sel b a c d} + +test textTag-8.1 {TkTextTagCmd - "names" option} { + list [catch {.t tag names a b} msg] $msg +} {1 {wrong # args: should be ".t tag names ?index?"}} +test textTag-8.2 {TkTextTagCmd - "names" option} { + tagsetup + .t tag names +} {sel a b c d} +test textTag-8.3 {TkTextTagCmd - "names" option} { + tagsetup + .t tag add "a b" 2.1 2.6 + .t tag add c 2.4 2.7 + .t tag names 2.5 +} {c {a b}} + +.t tag delete x y z a b c d {a b} +.t tag add x 2.3 2.5 +.t tag add x 2.9 3.1 +.t tag add x 7.2 +test textTag-9.1 {TkTextTagCmd - "nextrange" option} { + list [catch {.t tag nextrange x} msg] $msg +} {1 {wrong # args: should be ".t tag nextrange tagName index1 ?index2?"}} +test textTag-9.2 {TkTextTagCmd - "nextrange" option} { + list [catch {.t tag nextrange x 1 2 3} msg] $msg +} {1 {wrong # args: should be ".t tag nextrange tagName index1 ?index2?"}} +test textTag-9.3 {TkTextTagCmd - "nextrange" option} { + list [catch {.t tag nextrange foo 1.0} msg] $msg +} {0 {}} +test textTag-9.4 {TkTextTagCmd - "nextrange" option} { + list [catch {.t tag nextrange x foo} msg] $msg +} {1 {bad text index "foo"}} +test textTag-9.5 {TkTextTagCmd - "nextrange" option} { + list [catch {.t tag nextrange x 1.0 bar} msg] $msg +} {1 {bad text index "bar"}} +test textTag-9.6 {TkTextTagCmd - "nextrange" option} { + .t tag nextrange x 1.0 +} {2.3 2.5} +test textTag-9.7 {TkTextTagCmd - "nextrange" option} { + .t tag nextrange x 2.2 +} {2.3 2.5} +test textTag-9.8 {TkTextTagCmd - "nextrange" option} { + .t tag nextrange x 2.3 +} {2.3 2.5} +test textTag-9.9 {TkTextTagCmd - "nextrange" option} { + .t tag nextrange x 2.4 +} {2.9 3.1} +test textTag-9.10 {TkTextTagCmd - "nextrange" option} { + .t tag nextrange x 2.4 2.9 +} {} +test textTag-9.11 {TkTextTagCmd - "nextrange" option} { + .t tag nextrange x 2.4 2.10 +} {2.9 3.1} +test textTag-9.12 {TkTextTagCmd - "nextrange" option} { + .t tag nextrange x 2.4 2.11 +} {2.9 3.1} +test textTag-9.13 {TkTextTagCmd - "nextrange" option} { + .t tag nextrange x 7.0 +} {7.2 7.3} +test textTag-9.14 {TkTextTagCmd - "nextrange" option} { + .t tag nextrange x 7.3 +} {} + +test textTag-10.1 {TkTextTagCmd - "prevrange" option} { + list [catch {.t tag prevrange x} msg] $msg +} {1 {wrong # args: should be ".t tag prevrange tagName index1 ?index2?"}} +test textTag-10.2 {TkTextTagCmd - "prevrange" option} { + list [catch {.t tag prevrange x 1 2 3} msg] $msg +} {1 {wrong # args: should be ".t tag prevrange tagName index1 ?index2?"}} +test textTag-10.3 {TkTextTagCmd - "prevrange" option} { + list [catch {.t tag prevrange foo end} msg] $msg +} {0 {}} +test textTag-10.4 {TkTextTagCmd - "prevrange" option} { + list [catch {.t tag prevrange x foo} msg] $msg +} {1 {bad text index "foo"}} +test textTag-10.5 {TkTextTagCmd - "prevrange" option} { + list [catch {.t tag prevrange x end bar} msg] $msg +} {1 {bad text index "bar"}} +test textTag-10.6 {TkTextTagCmd - "prevrange" option} { + .t tag prevrange x end +} {7.2 7.3} +test textTag-10.7 {TkTextTagCmd - "prevrange" option} { + .t tag prevrange x 2.4 +} {2.3 2.5} +test textTag-10.8 {TkTextTagCmd - "prevrange" option} { + .t tag prevrange x 2.5 +} {2.3 2.5} +test textTag-10.9 {TkTextTagCmd - "prevrange" option} { + .t tag prevrange x 2.9 +} {2.3 2.5} +test textTag-10.10 {TkTextTagCmd - "prevrange" option} { + .t tag prevrange x 2.9 2.6 +} {} +test textTag-10.11 {TkTextTagCmd - "prevrange" option} { + .t tag prevrange x 2.9 2.5 +} {} +test textTag-10.12 {TkTextTagCmd - "prevrange" option} { + .t tag prevrange x 2.9 2.3 +} {2.3 2.5} +test textTag-10.13 {TkTextTagCmd - "prevrange" option} { + .t tag prevrange x 7.0 +} {2.9 3.1} +test textTag-10.14 {TkTextTagCmd - "prevrange" option} { + .t tag prevrange x 2.3 +} {} + +test textTag-11.1 {TkTextTagCmd - "raise" option} { + list [catch {.t tag raise} msg] $msg +} {1 {wrong # args: should be ".t tag raise tagName ?aboveThis?"}} +test textTag-11.2 {TkTextTagCmd - "raise" option} { + list [catch {.t tag raise foo} msg] $msg +} {1 {tag "foo" isn't defined in text widget}} +test textTag-11.3 {TkTextTagCmd - "raise" option} { + list [catch {.t tag raise sel bar} msg] $msg +} {1 {tag "bar" isn't defined in text widget}} +test textTag-11.4 {TkTextTagCmd - "raise" option} { + tagsetup + .t tag raise c + .t tag names +} {sel a b d c} +test textTag-11.5 {TkTextTagCmd - "raise" option} { + tagsetup + .t tag raise d b + .t tag names +} {sel a b d c} +test textTag-11.6 {TkTextTagCmd - "raise" option} { + tagsetup + .t tag raise a c + .t tag names +} {sel b c a d} + +test textTag-12.1 {TkTextTagCmd - "ranges" option} { + list [catch {.t tag ranges} msg] $msg +} {1 {wrong # args: should be ".t tag ranges tagName"}} +test textTag-12.2 {TkTextTagCmd - "ranges" option} { + .t tag delete x + .t tag ranges x +} {} +test textTag-12.3 {TkTextTagCmd - "ranges" option} { + .t tag delete x + .t tag add x 2.2 + .t tag add x 2.7 4.15 + .t tag add x 5.2 5.5 + .t tag ranges x +} {2.2 2.3 2.7 4.6 5.2 5.5} +test textTag-12.4 {TkTextTagCmd - "ranges" option} { + .t tag delete x + .t tag add x 1.0 3.0 + .t tag add x 4.0 end + .t tag ranges x +} {1.0 3.0 4.0 8.0} + +test textTag-13.1 {TkTextTagCmd - "remove" option} { + list [catch {.t tag remove} msg] $msg +} {1 {wrong # args: should be ".t tag remove tagName index1 ?index2 index1 index2 ...?"}} +test textTag-13.2 {TkTextTagCmd - "remove" option} { + .t tag delete x + .t tag add x 2.2 2.11 + .t tag remove x 2.3 2.7 + .t tag ranges x +} {2.2 2.3 2.7 2.11} +test textTag-13.3 {TkTextTagCmd - "remove" option} { + .t configure -exportselection 1 + .t tag remove sel 1.0 end + .t tag add sel 2.4 3.3 + .t.e select to 4 + .t tag remove sel 2.7 3.1 + selection get +} Text + +.t tag delete x a b c d +test textTag-14.1 {SortTags} { + foreach i {a b c d} { + .t tag add $i 2.0 2.2 + } + .t tag names 2.1 +} {a b c d} +.t tag delete a b c d +test textTag-14.2 {SortTags} { + foreach i {a b c d} { + .t tag configure $i -background black + } + foreach i {d c b a} { + .t tag add $i 2.0 2.2 + } + .t tag names 2.1 +} {a b c d} +.t tag delete x a b c d +test textTag-14.3 {SortTags} { + for {set i 0} {$i < 30} {incr i} { + .t tag add x$i 2.0 2.2 + } + .t tag names 2.1 +} {x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29} +test textTag-14.4 {SortTags} { + for {set i 0} {$i < 30} {incr i} { + .t tag configure x$i -background black + } + for {set i 29} {$i >= 0} {incr i -1} { + .t tag add x$i 2.0 2.2 + } + .t tag names 2.1 +} {x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29} + +foreach tag [.t tag names] { + catch {.t tag delete $tag} +} +set c [.t bbox 2.1] +set x1 [expr [lindex $c 0] + [lindex $c 2]/2] +set y1 [expr [lindex $c 1] + [lindex $c 3]/2] +set c [.t bbox 3.2] +set x2 [expr [lindex $c 0] + [lindex $c 2]/2] +set y2 [expr [lindex $c 1] + [lindex $c 3]/2] +set c [.t bbox 4.3] +set x3 [expr [lindex $c 0] + [lindex $c 2]/2] +set y3 [expr [lindex $c 1] + [lindex $c 3]/2] + +test textTag-15.1 {TkTextBindProc} { + bind .t <ButtonRelease> {lappend x up} + .t tag bind x <ButtonRelease> {lappend x x-up} + .t tag bind y <ButtonRelease> {lappend x y-up} + set x {} + .t tag add x 2.0 2.4 + .t tag add y 4.3 + event gen .t <Motion> -x $x1 -y $y1 + event gen .t <ButtonRelease> -x $x1 -y $y1 + event gen .t <Motion> -x $x2 -y $y2 + event gen .t <ButtonRelease> -x $x2 -y $y2 + event gen .t <Motion> -x $x3 -y $y3 + event gen .t <ButtonRelease> -x $x3 -y $y3 + bind .t <ButtonRelease> {} + set x +} {x-up up up y-up up} +test textTag-15.2 {TkTextBindProc} { + catch {.t tag delete x} + catch {.t tag delete y} + .t tag bind x <Enter> {lappend x x-enter} + .t tag bind x <ButtonPress> {lappend x x-down} + .t tag bind x <ButtonRelease> {lappend x x-up} + .t tag bind x <Leave> {lappend x x-leave} + .t tag bind y <Enter> {lappend x y-enter} + .t tag bind y <ButtonPress> {lappend x y-down} + .t tag bind y <ButtonRelease> {lappend x y-up} + .t tag bind y <Leave> {lappend x y-leave} + event gen .t <Motion> -x 0 -y 0 + set x {} + .t tag add x 2.0 2.4 + .t tag add y 4.3 + event gen .t <Motion> -x $x1 -y $y1 + lappend x | + event gen .t <Button> -x $x1 -y $y1 + lappend x | + event gen .t <Motion> -x $x3 -y $y3 -state 0x100 + lappend x | + event gen .t <ButtonRelease> -x $x3 -y $y3 + set x +} {x-enter | x-down | | x-up x-leave y-enter} +test textTag-15.3 {TkTextBindProc} { + catch {.t tag delete x} + catch {.t tag delete y} + .t tag bind x <Enter> {lappend x x-enter} + .t tag bind x <Any-ButtonPress-1> {lappend x x-down} + .t tag bind x <Any-ButtonRelease-1> {lappend x x-up} + .t tag bind x <Leave> {lappend x x-leave} + .t tag bind y <Enter> {lappend x y-enter} + .t tag bind y <Any-ButtonPress-1> {lappend x y-down} + .t tag bind y <Any-ButtonRelease-1> {lappend x y-up} + .t tag bind y <Leave> {lappend x y-leave} + event gen .t <Motion> -x 0 -y 0 + set x {} + .t tag add x 2.0 2.4 + .t tag add y 4.3 + event gen .t <Motion> -x $x1 -y $y1 + lappend x | + event gen .t <Button-1> -x $x1 -y $y1 + lappend x | + event gen .t <Button-2> -x $x1 -y $y1 -state 0x100 + lappend x | + event gen .t <Motion> -x $x3 -y $y3 -state 0x300 + lappend x | + event gen .t <ButtonRelease-1> -x $x3 -y $y3 -state 0x300 + lappend x | + event gen .t <ButtonRelease-2> -x $x3 -y $y3 -state 0x200 + set x +} {x-enter | x-down | | | x-up | x-leave y-enter} + +foreach tag [.t tag names] { + catch {.t tag delete $tag} +} +.t tag configure big -font $bigFont +test textTag-16.1 {TkTextPickCurrent procedure} { + event gen .t <ButtonRelease-1> -state 0x100 -x $x1 -y $y1 + set x [.t index current] + event gen .t <Motion> -x $x2 -y $y2 + lappend x [.t index current] + event gen .t <Button-1> -x $x2 -y $y2 + lappend x [.t index current] + event gen .t <Motion> -x $x3 -y $y3 -state 0x100 + lappend x [.t index current] + event gen .t <Button-3> -state 0x100 -x $x3 -y $y3 + lappend x [.t index current] + event gen .t <ButtonRelease-3> -state 0x300 -x $x3 -y $y3 + lappend x [.t index current] + event gen .t <ButtonRelease-1> -state 0x100 -x $x3 -y $y3 + lappend x [.t index current] +} {2.1 3.2 3.2 3.2 3.2 3.2 4.3} +test textTag-16.2 {TkTextPickCurrent procedure} { + event gen .t <ButtonRelease-1> -state 0x100 -x $x1 -y $y1 + event gen .t <Motion> -x $x2 -y $y2 + set x [.t index current] + .t tag add big 3.0 + update + lappend x [.t index current] +} {3.2 3.1} +.t tag remove big 1.0 end +foreach i {a b c d} { + .t tag bind $i <Enter> "lappend x enter-$i" + .t tag bind $i <Leave> "lappend x leave-$i" +} +test textTag-16.3 {TkTextPickCurrent procedure} { + foreach i {a b c d} { + .t tag remove $i 1.0 end + } + .t tag lower b + .t tag lower a + set x {} + event gen .t <Motion> -x $x1 -y $y1 + .t tag add a 2.1 3.3 + .t tag add b 2.1 + .t tag add c 3.2 + update + lappend x | + event gen .t <Motion> -x $x2 -y $y2 + lappend x | + event gen .t <Motion> -x $x3 -y $y3 + set x +} {enter-a enter-b | leave-b enter-c | leave-a leave-c} +test textTag-16.4 {TkTextPickCurrent procedure} { + foreach i {a b c d} { + .t tag remove $i 1.0 end + } + .t tag lower b + .t tag lower a + set x {} + event gen .t <Motion> -x $x1 -y $y1 + .t tag add a 2.1 3.3 + .t tag add b 2.1 + .t tag add c 2.1 + update + lappend x | + .t tag lower c + event gen .t <Motion> -x $x2 -y $y2 + set x +} {enter-a enter-b enter-c | leave-c leave-b} +foreach i {a b c d} { + .t tag delete $i +} +test textTag-16.5 {TkTextPickCurrent procedure} { + foreach i {a b c d} { + .t tag remove $i 1.0 end + } + event gen .t <Motion> -x $x1 -y $y1 + .t tag bind a <Enter> {.t tag add big 3.0 3.2} + .t tag add a 3.2 + event gen .t <Motion> -x $x2 -y $y2 + .t index current +} {3.2} +test textTag-16.6 {TkTextPickCurrent procedure} { + foreach i {a b c d} { + .t tag remove $i 1.0 end + } + event gen .t <Motion> -x $x1 -y $y1 + .t tag bind a <Enter> {.t tag add big 3.0 3.2} + .t tag add a 3.2 + event gen .t <Motion> -x $x2 -y $y2 + update + .t index current +} {3.1} +test textTag-16.7 {TkTextPickCurrent procedure} { + foreach i {a b c d} { + .t tag remove $i 1.0 end + } + event gen .t <Motion> -x $x1 -y $y1 + .t tag bind a <Leave> {.t tag add big 3.0 3.2} + .t tag add a 2.1 + event gen .t <Motion> -x $x2 -y $y2 + .t index current +} {3.1} + +catch {destroy .t} +concat {} diff --git a/tests/textWind.test b/tests/textWind.test new file mode 100644 index 0000000..c639dab --- /dev/null +++ b/tests/textWind.test @@ -0,0 +1,826 @@ +# This file is a Tcl script to test the code in the file tkTextWind.c. +# This file is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) textWind.test 1.25 97/07/01 18:16:38 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +foreach i [winfo child .] { + catch {destroy $i} +} + + +# Create entries in the option database to be sure that geometry options +# like border width have predictable values. + +option add *Text.borderWidth 2 +option add *Text.highlightThickness 2 +if {$tcl_platform(platform) == "windows"} { + option add *Text.font {Courier -14} +} else { + option add *Text.font {Courier -12} +} + +text .t -width 30 -height 6 -bd 2 -highlightthickness 2 +pack append . .t {top expand fill} +update +.t debug on +wm geometry . {} +if {[winfo depth .t] > 1} { + set color green +} else { + set color black +} + +# The statements below reset the main window; it's needed if the window +# manager is mwm to make mwm forget about a previous minimum size setting. + +wm withdraw . +wm minsize . 1 1 +wm positionfrom . user +wm deiconify . + +test textWind-1.1 {basic tests of options} {fonts} { + .t delete 1.0 end + .t insert end "This is the first line" + .t insert end "\nAnd this is a second line, which wraps around" + frame .f -width 3 -height 3 -bg $color + .t window create 2.2 -window .f + update + list [winfo ismapped .f] [winfo geom .f] [.t bbox .f] \ + [.t window configure .f -window] +} {1 3x3+19+23 {19 23 3 3} {-window {} {} {} .f}} +test textWind-1.2 {basic tests of options} {fonts} { + .t delete 1.0 end + .t insert end "This is the first line" + .t insert end "\nAnd this is a second line, which wraps around" + frame .f -width 3 -height 3 -bg $color + .t window create 2.2 -window .f -align top + update + list [winfo ismapped .f] [winfo geom .f] [.t bbox .f] \ + [.t window configure .f -align] +} {1 3x3+19+18 {19 18 3 3} {-align {} {} center top}} +test textWind-1.3 {basic tests of options} { + .t delete 1.0 end + .t insert end "This is the first line" + .t insert end "\nAnd this is a second line, which wraps around" + .t window create 2.2 -create "Test script" + .t window configure 2.2 -create +} {-create {} {} {} {Test script}} +test textWind-1.4 {basic tests of options} {fonts} { + .t delete 1.0 end + .t insert end "This is the first line" + .t insert end "\nAnd this is a second line, which wraps around" + frame .f -width 10 -height 20 -bg $color + .t window create 2.2 -window .f -padx 5 + update + list [winfo geom .f] [.t window configure .f -padx] [.t bbox 2.3] +} {10x20+24+18 {-padx {} {} 0 5} {39 21 7 13}} +test textWind-1.5 {basic tests of options} {fonts} { + .t delete 1.0 end + .t insert end "This is the first line" + .t insert end "\nAnd this is a second line, which wraps around" + frame .f -width 10 -height 20 -bg $color + .t window create 2.2 -window .f -pady 4 + update + list [winfo geom .f] [.t window configure .f -pady] [.t bbox 2.31] +} {10x20+19+22 {-pady {} {} 0 4} {19 46 7 13}} +test textWind-1.6 {basic tests of options} {fonts} { + .t delete 1.0 end + .t insert end "This is the first line" + .t insert end "\nAnd this is a second line, which wraps around" + frame .f -width 5 -height 5 -bg $color + .t window create 2.2 -window .f -stretch 1 + update + list [winfo geom .f] [.t window configure .f -stretch] +} {5x13+19+18 {-stretch {} {} 0 1}} + +.t delete 1.0 end +.t insert end "This is the first line" +frame .f -width 10 -height 6 -bg $color +.t window create 1.3 -window .f -padx 1 -pady 2 +test textWind-2.1 {TkTextWindowCmd procedure} { + list [catch {.t window} msg] $msg +} {1 {wrong # args: should be ".t window option ?arg arg ...?"}} +test textWind-2.2 {TkTextWindowCmd procedure, "cget" option} { + list [catch {.t window cget} msg] $msg +} {1 {wrong # args: should be ".t window cget index option"}} +test textWind-2.3 {TkTextWindowCmd procedure, "cget" option} { + list [catch {.t window cget a b c} msg] $msg +} {1 {wrong # args: should be ".t window cget index option"}} +test textWind-2.4 {TkTextWindowCmd procedure, "cget" option} { + list [catch {.t window cget gorp -padx} msg] $msg +} {1 {bad text index "gorp"}} +test textWind-2.5 {TkTextWindowCmd procedure, "cget" option} { + list [catch {.t window cget 1.2 -padx} msg] $msg +} {1 {no embedded window at index "1.2"}} +test textWind-2.6 {TkTextWindowCmd procedure, "cget" option} { + list [catch {.t window cget .f -bogus} msg] $msg +} {1 {unknown option "-bogus"}} +test textWind-2.7 {TkTextWindowCmd procedure, "cget" option} { + list [catch {.t window cget .f -pady} msg] $msg +} {0 2} +test textWind-2.8 {TkTextWindowCmd procedure} { + list [catch {.t window co} msg] $msg +} {1 {wrong # args: should be ".t window configure index ?option value ...?"}} +test textWind-2.9 {TkTextWindowCmd procedure} { + list [catch {.t window configure gorp} msg] $msg +} {1 {bad text index "gorp"}} +test textWind-2.10 {TkTextWindowCmd procedure} { + .t delete 1.0 end + list [catch {.t window configure 1.0} msg] $msg +} {1 {no embedded window at index "1.0"}} +test textWind-2.11 {TkTextWindowCmd procedure} { + .t delete 1.0 end + .t insert end "This is the first line" + .t insert end "\nAnd this is a second line, which wraps around" + frame .f -width 10 -height 6 -bg $color + .t window create 2.2 -window .f -align baseline -padx 1 -pady 2 -create foo + update + list [catch {.t window configure .f} msg] $msg +} {0 {{-align {} {} center baseline} {-create {} {} {} foo} {-padx {} {} 0 1} {-pady {} {} 0 2} {-stretch {} {} 0 0} {-window {} {} {} .f}}} +test textWind-2.12 {TkTextWindowCmd procedure} { + .t delete 1.0 end + .t insert end "This is the first line" + .t insert end "\nAnd this is a second line, which wraps around" + frame .f -width 10 -height 6 -bg $color + .t window create 2.2 -window .f -align baseline -padx 1 -pady 2 -create foo + update + list [.t window configure .f -padx 33] [.t window configure .f -padx] +} {{} {-padx {} {} 0 33}} +test textWind-2.13 {TkTextWindowCmd procedure} { + .t delete 1.0 end + .t insert end "This is the first line" + .t insert end "\nAnd this is a second line, which wraps around" + frame .f -width 10 -height 6 -bg $color + .t window create 2.2 -window .f -align baseline -padx 1 -pady 2 + update + list [.t window configure .f -padx 14 -pady 15] \ + [.t window configure .f -padx] [.t window configure .f -pady] +} {{} {-padx {} {} 0 14} {-pady {} {} 0 15}} +test textWind-2.14 {TkTextWindowCmd procedure} { + list [catch {.t window create} msg] $msg +} {1 {wrong # args: should be ".t window create index ?option value ...?"}} +test textWind-2.15 {TkTextWindowCmd procedure} { + list [catch {.t window create gorp} msg] $msg +} {1 {bad text index "gorp"}} +test textWind-2.16 {TkTextWindowCmd procedure, don't insert after end} { + .t delete 1.0 end + .t insert end "Line 1\nLine 2" + frame .f -width 20 -height 10 -bg $color + .t window create end -window .f + .t index .f +} {2.6} +test textWind-2.17 {TkTextWindowCmd procedure} { + .t delete 1.0 end + list [catch {.t window create 1.0} msg] $msg [.t window configure 1.0] +} {0 {} {{-align {} {} center center} {-create {} {} {} {}} {-padx {} {} 0 0} {-pady {} {} 0 0} {-stretch {} {} 0 0} {-window {} {} {} {}}}} +test textWind-2.18 {TkTextWindowCmd procedure} { + .t delete 1.0 end + frame .f -width 10 -height 6 -bg $color + list [catch {.t window create 1.0 -window .f -gorp stupid} msg] $msg \ + [winfo exists .f] [.t index 1.end] [catch {.t index .f}] +} {1 {unknown option "-gorp"} 0 1.0 1} +test textWind-2.19 {TkTextWindowCmd procedure} { + .t delete 1.0 end + frame .f -width 10 -height 6 -bg $color + list [catch {.t window create 1.0 -gorp -window .f stupid} msg] $msg \ + [winfo exists .f] [.t index 1.end] [catch {.t index .f}] +} {1 {unknown option "-gorp"} 1 1.0 1} +test textWind-2.20 {TkTextWindowCmd procedure} { + list [catch {.t window c} msg] $msg +} {1 {bad window option "c": must be cget, configure, create, or names}} +destroy .f +test textWind-2.21 {TkTextWindowCmd procedure, "names" option} { + list [catch {.t window names foo} msg] $msg +} {1 {wrong # args: should be ".t window names"}} +test textWind-2.22 {TkTextWindowCmd procedure, "names" option} { + .t delete 1.0 end + .t window names +} {} +test textWind-2.23 {TkTextWindowCmd procedure, "names" option} { + .t delete 1.0 end + foreach i {.f .f2 .t.f .t.f2} { + frame $i -width 20 -height 20 + .t window create end -window $i + } + set result [.t window names] + destroy .f .f2 .t.f .t.f2 + lsort $result +} {.f .f2 .t.f .t.f2} + +test textWind-3.1 {EmbWinConfigure procedure} { + .t delete 1.0 end + frame .f -width 10 -height 6 -bg $color + .t window create 1.0 -window .f + list [catch {.t window configure 1.0 -foo bar} msg] $msg +} {1 {unknown option "-foo"}} +test textWind-3.2 {EmbWinConfigure procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 10 -height 20 -bg $color + .t window create 1.3 -window .f + update + .t window configure 1.3 -window {} + update + list [catch {.t index .f} msg] $msg [winfo ismapped .f] [.t bbox 1.4] +} {1 {bad text index ".f"} 0 {26 5 7 13}} +catch {destroy .f} +test textWind-3.3 {EmbWinConfigure procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .t.f -width 10 -height 20 -bg $color + .t window create 1.3 -window .t.f + update + .t window configure 1.3 -window {} + update + list [catch {.t index .t.f} msg] $msg [winfo ismapped .t.f] [.t bbox 1.4] +} {1 {bad text index ".t.f"} 0 {26 5 7 13}} +catch {destroy .t.f} +test textWind-3.4 {EmbWinConfigure procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 10 -height 20 -bg $color + .t window create 1.3 + update + .t window configure 1.3 -window .f + update + list [catch {.t index .f} msg] $msg [winfo ismapped .f] [.t bbox 1.4] +} {0 1.3 1 {36 8 7 13}} +test textWind-3.5 {EmbWinConfigure procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f + frame .f.f -width 15 -height 20 -bg $color + pack .f.f + list [catch {.t window create 1.3 -window .f.f} msg] $msg +} {1 {can't embed .f.f in .t}} +catch {destroy .f} +test textWind-3.6 {EmbWinConfigure procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + toplevel .t2 -width 20 -height 10 -bg $color + .t window create 1.3 + list [catch {.t window configure 1.3 -window .t2} msg] $msg \ + [.t window configure 1.3 -window] +} {1 {can't embed .t2 in .t} {-window {} {} {} {}}} +catch {destroy .t2} +test textWind-3.7 {EmbWinConfigure procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + .t window create 1.3 + list [catch {.t window configure 1.3 -window .t} msg] $msg +} {1 {can't embed .t in .t}} +test textWind-3.8 {EmbWinConfigure procedure} { + # This test checks for various errors when the text claims + # a window away from itself. + .t delete 1.0 end + .t insert 1.0 "Some sample text" + button .t.b -text "Hello!" + .t window create 1.4 -window .t.b + .t window create 1.6 -window .t.b + update + .t index .t.b +} {1.6} + +.t delete 1.0 end +frame .f -width 10 -height 20 -bg $color +.t window create 1.0 -window .f +test textWind-4.1 {AlignParseProc and AlignPrintProc procedures} { + .t window configure 1.0 -align baseline + .t window configure 1.0 -align +} {-align {} {} center baseline} +test textWind-4.2 {AlignParseProc and AlignPrintProc procedures} { + .t window configure 1.0 -align bottom + .t window configure 1.0 -align +} {-align {} {} center bottom} +test textWind-4.3 {AlignParseProc and AlignPrintProc procedures} { + .t window configure 1.0 -align center + .t window configure 1.0 -align +} {-align {} {} center center} +test textWind-4.4 {AlignParseProc and AlignPrintProc procedures} { + .t window configure 1.0 -align top + .t window configure 1.0 -align +} {-align {} {} center top} +test textWind-4.5 {AlignParseProc and AlignPrintProc procedures} { + .t window configure 1.0 -align top + list [catch {.t window configure 1.0 -align gorp} msg] $msg \ + [.t window configure 1.0 -align] +} {1 {bad alignment "gorp": must be baseline, bottom, center, or top} {-align {} {} center top}} + +test textWind-5.1 {EmbWinStructureProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 10 -height 20 -bg $color + .t window create 1.2 -window .f + update + destroy .f + list [catch {.t index .f} msg] $msg [.t bbox 1.2] [.t bbox 1.3] +} {1 {bad text index ".f"} {19 11 0 0} {19 5 7 13}} +test textWind-5.2 {EmbWinStructureProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 10 -height 20 -bg $color + .t window create 1.2 -align bottom + .t window configure 1.2 -window .f + update + destroy .f + list [catch {.t index .f} msg] $msg [.t bbox 1.2] [.t bbox 1.3] +} {1 {bad text index ".f"} {19 18 0 0} {19 5 7 13}} +test textWind-5.3 {EmbWinStructureProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + .t window create 1.2 -create {frame .f -width 10 -height 20 -bg $color} + update + .t window configure 1.2 -create {frame .f -width 20 -height 10 -bg $color} + destroy .f + update + list [catch {.t index .f} msg] $msg [.t bbox 1.2] [.t bbox 1.3] +} {0 1.2 {19 6 20 10} {39 5 7 13}} + +test textWind-6.1 {EmbWinRequestProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 10 -height 20 -bg $color + .t window create 1.2 -window .f + set result {} + lappend result [.t bbox 1.2] [.t bbox 1.3] + .f configure -width 25 -height 30 + lappend result [.t bbox 1.2] [.t bbox 1.3] +} {{19 5 10 20} {29 8 7 13} {19 5 25 30} {44 13 7 13}} + +test textWind-7.1 {EmbWinLostSlaveProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 10 -height 20 -bg $color + .t window create 1.2 -window .f + update + place .f -in .t -x 100 -y 50 + update + list [winfo geom .f] [.t bbox 1.2] +} {10x20+104+54 {19 11 0 0}} +test textWind-7.2 {EmbWinLostSlaveProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .t.f -width 10 -height 20 -bg $color + .t window create 1.2 -window .t.f + update + place .t.f -x 100 -y 50 + update + list [winfo geom .t.f] [.t bbox 1.2] +} {10x20+104+54 {19 11 0 0}} +catch {destroy .f} +catch {destroy .t.f} + +test textWind-8.1 {EmbWinDeleteProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 10 -height 20 -bg $color + .t window create 1.2 -window .f + bind .f <Destroy> {set x destroyed} + set x XXX + .t delete 1.2 + list $x [.t bbox 1.2] [.t bbox 1.3] [catch {.t index .f} msg] $msg \ + [winfo exists .f] +} {destroyed {19 5 7 13} {26 5 7 13} 1 {bad text index ".f"} 0} + +test textWind-9.1 {EmbWinCleanupProc procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text\nA second line." + frame .f -width 10 -height 20 -bg $color + .t window create 2.3 -window .f + .t delete 1.5 2.1 + .t index .f +} 1.7 + +proc bgerror args { + global msg + set msg $args +} + +test textWind-10.1 {EmbWinLayoutProc procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + .t window create 1.5 -create { + frame .f -width 10 -height 20 -bg $color + } + update + list [winfo exists .f] [winfo geom .f] [.t index .f] +} {1 10x20+40+5 1.5} +test textWind-10.2 {EmbWinLayoutProc procedure, error in creating window} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + .t window create 1.5 -create { + error "couldn't create window" + } + set msg xyzzy + update + list $msg [.t bbox 1.5] +} {{{couldn't create window}} {40 11 0 0}} +test textWind-10.3 {EmbWinLayoutProc procedure, error in creating window} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + .t window create 1.5 -create { + concat gorp + } + set msg xyzzy + update + list $msg [.t bbox 1.5] +} {{{bad window path name "gorp"}} {40 11 0 0}} +test textWind-10.4 {EmbWinLayoutProc procedure, error in creating window} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + .t window create 1.5 -create { + frame .t.f + frame .t.f.f -width 10 -height 20 -bg $color + } + set msg xyzzy + update + list $msg [.t bbox 1.5] [winfo exists .t.f.f] +} {{{can't embed .t.f.f relative to .t}} {40 11 0 0} 1} +catch {destroy .t.f} +test textWind-10.5 {EmbWinLayoutProc procedure, error in creating window} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + .t window create 1.5 -create { + concat .t + } + set msg xyzzy + update + list $msg [.t bbox 1.5] +} {{{can't embed .t relative to .t}} {40 11 0 0}} +test textWind-10.6 {EmbWinLayoutProc procedure, error in creating window} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + .t window create 1.5 -create { + toplevel .t2 -width 100 -height 150 + wm geom .t2 +0+0 + concat .t2 + } + set msg xyzzy + update + list $msg [.t bbox 1.5] +} {{{can't embed .t2 relative to .t}} {40 11 0 0}} +test textWind-10.7 {EmbWinLayoutProc procedure, steal window from self} { + .t delete 1.0 end + .t insert 1.0 ABCDEFGHIJKLMNOP + button .t.b -text "Hello!" + .t window create 1.5 -window .t.b + update + .t window create 1.3 -create {concat .t.b} + update + .t index .t.b +} {1.3} +catch {destroy .t2} +test textWind-10.8 {EmbWinLayoutProc procedure, doesn't fit on line} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 125 -height 20 -bg $color -bd 2 -relief raised + .t window create 1.12 -window .f + list [.t bbox .f] [.t bbox 1.13] +} {{89 5 126 20} {5 25 7 13}} +test textWind-10.9 {EmbWinLayoutProc procedure, doesn't fit on line} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 126 -height 20 -bg $color -bd 2 -relief raised + .t window create 1.12 -window .f + update + list [.t bbox .f] [.t bbox 1.13] +} {{89 5 126 20} {5 25 7 13}} +test textWind-10.10 {EmbWinLayoutProc procedure, doesn't fit on line} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 127 -height 20 -bg $color -bd 2 -relief raised + .t window create 1.12 -window .f + update + list [.t bbox .f] [.t bbox 1.13] +} {{5 18 127 20} {132 21 7 13}} +test textWind-10.11 {EmbWinLayoutProc procedure, doesn't fit on line} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 130 -height 20 -bg $color -bd 2 -relief raised + .t window create 1.12 -window .f + update + list [.t bbox .f] [.t bbox 1.13] +} {{89 5 126 20} {}} +test textWind-10.12 {EmbWinLayoutProc procedure, doesn't fit on line} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 130 -height 220 -bg $color -bd 2 -relief raised + .t window create 1.12 -window .f + update + list [.t bbox .f] [.t bbox 1.13] +} {{89 5 126 78} {}} +test textWind-10.13 {EmbWinLayoutProc procedure, doesn't fit on line} {fonts} { + .t configure -wrap char + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 250 -height 220 -bg $color -bd 2 -relief raised + .t window create 1.12 -window .f + update + list [.t bbox .f] [.t bbox 1.13] +} {{5 18 210 65} {}} + +test textWind-11.1 {EmbWinDisplayProc procedure, geometry transforms} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + pack forget .t + place .t -x 30 -y 50 + frame .f -width 30 -height 20 -bg $color + .t window create 1.12 -window .f + update + winfo geom .f +} {30x20+119+55} +place forget .t +pack .t +test textWind-11.2 {EmbWinDisplayProc procedure, geometry transforms} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + pack forget .t + place .t -x 30 -y 50 + frame .t.f -width 30 -height 20 -bg $color + .t window create 1.12 -window .t.f + update + winfo geom .t.f +} {30x20+89+5} +place forget .t +pack .t +test textWind-11.3 {EmbWinDisplayProc procedure, configuration optimization} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 30 -height 20 -bg $color + .t window create 1.12 -window .f + update + bind .f <Configure> {set x ".f configured"} + set x {no configures} + .t delete 1.0 + .t insert 1.0 "X" + update + set x +} {no configures} +test textWind-11.4 {EmbWinDisplayProc procedure, horizontal scrolling} {fonts} { + .t delete 1.0 end + .t insert 1.0 "xyzzy\nFirst window here: " + .t configure -wrap none + frame .f -width 30 -height 20 -bg $color + .t window create end -window .f + .t insert end " and second here: " + frame .f2 -width 40 -height 10 -bg $color + .t window create end -window .f2 + .t insert end " with junk after it." + .t xview moveto 0 + .t xview scroll 5 units + update + list [winfo ismapped .f] [winfo geom .f] [.t bbox .f] [winfo ismapped .f2] +} {1 30x20+103+18 {103 18 30 20} 0} +test textWind-11.5 {EmbWinDisplayProc procedure, horizontal scrolling} {fonts} { + .t delete 1.0 end + .t insert 1.0 "xyzzy\nFirst window here: " + .t configure -wrap none + frame .f -width 30 -height 20 -bg $color + .t window create end -window .f + .t insert end " and second here: " + frame .f2 -width 40 -height 10 -bg $color + .t window create end -window .f2 + .t insert end " with junk after it." + update + .t xview moveto 0 + .t xview scroll 25 units + update + list [winfo ismapped .f] [winfo ismapped .f2] [winfo geom .f2] [.t bbox .f2] +} {0 1 40x10+119+23 {119 23 40 10}} +.t configure -wrap char + +test textWind-12.1 {EmbWinUndisplayProc procedure, mapping/unmapping} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 30 -height 20 -bg $color + .t window create 1.2 -window .f + bind .f <Map> {lappend x mapped} + bind .f <Unmap> {lappend x unmapped} + set x created + update + lappend x modified + .t delete 1.0 + update + lappend x replaced + .t window configure .f -window {} + .t delete 1.1 + .t window create 1.4 -window .f + update + lappend x off-screen + .t configure -wrap none + .t insert 1.0 "Enough text to make the line run off-screen" + update + set x +} {created mapped modified replaced unmapped mapped off-screen unmapped} + +test textWind-13.1 {EmbWinBboxProc procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 5 -height 5 -bg $color + .t window create 1.2 -window .f -align top -padx 2 -pady 1 + update + list [winfo geom .f] [.t bbox .f] +} {5x5+21+6 {21 6 5 5}} +test textWind-13.2 {EmbWinBboxProc procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 5 -height 5 -bg $color + .t window create 1.2 -window .f -align center -padx 2 -pady 1 + update + list [winfo geom .f] [.t bbox .f] +} {5x5+21+9 {21 9 5 5}} +test textWind-13.3 {EmbWinBboxProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 5 -height 5 -bg $color + .t window create 1.2 -window .f -align baseline -padx 2 -pady 1 + update + list [winfo geom .f] [.t bbox .f] +} {5x5+21+10 {21 10 5 5}} +test textWind-13.4 {EmbWinBboxProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 5 -height 5 -bg $color + .t window create 1.2 -window .f -align bottom -padx 2 -pady 1 + update + list [winfo geom .f] [.t bbox .f] +} {5x5+21+12 {21 12 5 5}} +test textWind-13.5 {EmbWinBboxProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 5 -height 5 -bg $color + .t window create 1.2 -window .f -align top -padx 2 -pady 1 -stretch 1 + update + list [winfo geom .f] [.t bbox .f] +} {5x11+21+6 {21 6 5 11}} +test textWind-13.6 {EmbWinBboxProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 5 -height 5 -bg $color + .t window create 1.2 -window .f -align center -padx 2 -pady 1 -stretch 1 + update + list [winfo geom .f] [.t bbox .f] +} {5x11+21+6 {21 6 5 11}} +test textWind-13.7 {EmbWinBboxProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 5 -height 5 -bg $color + .t window create 1.2 -window .f -align baseline -padx 2 -pady 1 -stretch 1 + update + list [winfo geom .f] [.t bbox .f] +} {5x9+21+6 {21 6 5 9}} +test textWind-13.8 {EmbWinBboxProc procedure} {fonts} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 5 -height 5 -bg $color + .t window create 1.2 -window .f -align bottom -padx 2 -pady 1 -stretch 1 + update + list [winfo geom .f] [.t bbox .f] +} {5x11+21+6 {21 6 5 11}} +test textWind-13.9 {EmbWinBboxProc procedure, spacing options} { + .t configure -spacing1 5 -spacing3 2 + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 5 -height 5 -bg $color + .t window create 1.2 -window .f -align center -padx 2 -pady 1 + update + list [winfo geom .f] [.t bbox .f] +} {5x5+21+14 {21 14 5 5}} +.t configure -spacing1 0 -spacing2 0 -spacing3 0 + +test textWind-14.1 {EmbWinDelayedUnmap procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 30 -height 20 -bg $color + .t window create 1.2 -window .f + update + bind .f <Unmap> {lappend x unmapped} + set x modified + .t insert 1.0 x + lappend x removed + .t window configure .f -window {} + lappend x updated + update + set x +} {modified removed unmapped updated} +catch {destroy .f} +test textWind-14.2 {EmbWinDelayedUnmap procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 30 -height 20 -bg $color + .t window create 1.2 -window .f + update + bind .f <Unmap> {lappend x unmapped} + set x modified + .t insert 1.0 x + lappend x deleted + .t delete .f + lappend x updated + update + set x +} {modified deleted updated} +test textWind-14.3 {EmbWinDelayedUnmap procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text\nAnother line\n3\n4\n5\n6\n7\n8\n9" + frame .f -width 30 -height 20 -bg $color + .t window create 1.2 -window .f + update + .t yview 2.0 + set result [winfo ismapped .f] + update + list $result [winfo ismapped .f] +} {1 0} +test textWind-14.4 {EmbWinDelayedUnmap procedure} { + .t delete 1.0 end + .t insert 1.0 "Some sample text\nAnother line\n3\n4\n5\n6\n7\n8\n9" + frame .t.f -width 30 -height 20 -bg $color + .t window create 1.2 -window .t.f + update + .t yview 2.0 + set result [winfo ismapped .t.f] + update + list $result [winfo ismapped .t.f] +} {1 0} +catch {destroy .t.f} +catch {destroy .f} + +test textWind-15.1 {TkTextWindowIndex procedure} { + list [catch {.t index .foo} msg] $msg +} {1 {bad text index ".foo"}} +test textWind-15.2 {TkTextWindowIndex procedure} {fonts} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 30 -height 20 -bg $color + .t window create 1.6 -window .f + .t tag add a 1.1 + .t tag add a 1.3 + list [.t index .f] [.t bbox 1.7] +} {1.6 {77 8 7 13}} + +test textWind-16.1 {EmbWinTextStructureProc procedure} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 30 -height 20 -bg $color + .t window create 1.6 -window .f + update + pack forget .t + update + winfo ismapped .f +} 0 +pack .t +test textWind-16.2 {EmbWinTextStructureProc procedure} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .f -width 30 -height 20 -bg $color + .t window create 1.6 -window .f + update + set result {} + lappend result [winfo geom .f] [.t bbox .f] + frame .f2 -width 150 -height 30 -bd 2 -relief raised + pack .f2 -before .t + update + lappend result [winfo geom .f] [.t bbox .f] +} {30x20+47+5 {47 5 30 20} 30x20+47+35 {47 5 30 20}} +catch {destroy .f2} +test textWind-16.3 {EmbWinTextStructureProc procedure} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "Some sample text" + .t window create 1.6 + update + pack forget .t + update +} {} +pack .t +test textWind-16.4 {EmbWinTextStructureProc procedure} { + .t configure -wrap none + .t delete 1.0 end + .t insert 1.0 "Some sample text" + frame .t.f -width 30 -height 20 -bg $color + .t window create 1.6 -window .t.f + update + pack forget .t + update + list [winfo ismapped .t.f] [.t bbox .t.f] +} {1 {47 5 30 20}} +pack .t + +catch {destroy .t} +option clear diff --git a/tests/tk.test b/tests/tk.test new file mode 100644 index 0000000..94cec66 --- /dev/null +++ b/tests/tk.test @@ -0,0 +1,80 @@ +# This file is a Tcl script to test the tk command. +# It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) tk.test 1.3 97/05/20 15:17:44 + +if {[info commands test] == ""} { + source defs +} + +test tk-1.1 {tk command: general} { + list [catch {tk} msg] $msg +} {1 {wrong # args: should be "tk option ?arg?"}} +test tk-1.2 {tk command: general} { + list [catch {tk xyz} msg] $msg +} {1 {bad option "xyz": must be appname, or scaling}} + +set appname [tk appname] +test tk-2.1 {tk command: appname} { + list [catch {tk appname xyz abc} msg] $msg +} {1 {wrong # args: should be "tk appname ?newName?"}} +test tk-2.2 {tk command: appname} { + tk appname foobazgarply +} {foobazgarply} +test tk-2.3 {tk command: appname} {unixOnly} { + tk appname bazfoogarply + expr {[lsearch -exact [winfo interps] [tk appname]] >= 0} +} {1} +test tk-2.4 {tk command: appname} { + tk appname $appname +} $appname +tk appname $appname + +set scaling [tk scaling] +test tk-3.1 {tk command: scaling} { + list [catch {tk scaling -displayof} msg] $msg +} {1 {value for "-displayof" missing}} +test tk-3.2 {tk command: scaling: get current} { + tk scaling 1 + format %.2g [tk scaling] +} 1 +test tk-3.3 {tk command: scaling: get current} { + tk scaling -displayof . 1.25 + format %.3g [tk scaling] +} 1.25 +test tk-3.4 {tk command: scaling: set new} { + list [catch {tk scaling xyz} msg] $msg +} {1 {expected floating-point number but got "xyz"}} +test tk-3.5 {tk command: scaling: set new} { + list [catch {tk scaling -displayof . xyz} msg] $msg +} {1 {expected floating-point number but got "xyz"}} +test tk-3.6 {tk command: scaling: set new} { + tk scaling 1 + format %.2g [tk scaling] +} 1 +test tk-3.7 {tk command: scaling: set new} { + tk scaling -displayof . 1.25 + format %.3g [tk scaling] +} 1.25 +test tk-3.8 {tk command: scaling: negative} { + tk scaling -1 + expr {[tk scaling] > 0} +} {1} +test tk-3.9 {tk command: scaling: too big} { + tk scaling 1000000 + expr {[tk scaling] < 10000} +} {1} +test tk-3.10 {tk command: scaling: widthmm} { + tk scaling 1.25 + expr {int((25.4*[winfo screenwidth .])/(72*1.25)+0.5)-[winfo screenmmwidth .]} +} {0} +test tk-3.11 {tk command: scaling: heightmm} { + tk scaling 1.25 + expr {int((25.4*[winfo screenheight .])/(72*1.25)+0.5)-[winfo screenmmheight .]} +} {0} +tk scaling $scaling diff --git a/tests/unixButton.test b/tests/unixButton.test new file mode 100644 index 0000000..a4c67d5 --- /dev/null +++ b/tests/unixButton.test @@ -0,0 +1,182 @@ +# This file is a Tcl script to test the Unix specific behavior of +# labels, buttons, checkbuttons, and radiobuttons in Tk (i.e., all the +# widgets defined in tkUnixButton.c). It is organized in the standard +# fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) unixButton.test 1.6 97/07/01 18:11:30 + +if {$tcl_platform(platform)!="unix"} { + return +} + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\"" + puts "image, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +# Create entries in the option database to be sure that geometry options +# like border width have predictable values. + +option add *Label.borderWidth 2 +option add *Label.highlightThickness 0 +option add *Label.font {Helvetica -12 bold} +option add *Button.borderWidth 2 +option add *Button.highlightThickness 2 +option add *Button.font {Helvetica -12 bold} +option add *Checkbutton.borderWidth 2 +option add *Checkbutton.highlightThickness 2 +option add *Checkbutton.font {Helvetica -12 bold} +option add *Radiobutton.borderWidth 2 +option add *Radiobutton.highlightThickness 2 +option add *Radiobutton.font {Helvetica -12 bold} + + +proc bogusTrace args { + error "trace aborted" +} +catch {unset value} +catch {unset value2} + +eval image delete [image names] +image create test image1 +label .l -text Label +button .b -text Button +checkbutton .c -text Checkbutton +radiobutton .r -text Radiobutton +pack .l .b .c .r +update + +test unixbutton-1.1 {TkpComputeButtonGeometry procedure} { + eval destroy [winfo children .] + image create test image1 + image1 changed 0 0 0 0 60 40 + label .b1 -image image1 -bd 4 -padx 0 -pady 2 + button .b2 -image image1 -bd 4 -padx 0 -pady 2 + checkbutton .b3 -image image1 -bd 4 -padx 1 -pady 1 + radiobutton .b4 -image image1 -bd 4 -padx 2 -pady 0 + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {68 48 74 54 112 52 112 52} +test unixbutton-1.2 {TkpComputeButtonGeometry procedure} { + eval destroy [winfo children .] + label .b1 -bitmap question -bd 3 -padx 0 -pady 2 + button .b2 -bitmap question -bd 3 -padx 0 -pady 2 + checkbutton .b3 -bitmap question -bd 3 -padx 1 -pady 1 + radiobutton .b4 -bitmap question -bd 3 -padx 2 -pady 0 + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {23 33 29 39 54 37 54 37} +test unixbutton-1.3 {TkpComputeButtonGeometry procedure} { + eval destroy [winfo children .] + label .b1 -bitmap question -bd 3 -highlightthickness 4 + button .b2 -bitmap question -bd 3 -highlightthickness 0 + checkbutton .b3 -bitmap question -bd 3 -highlightthickness 1 \ + -indicatoron 0 + radiobutton .b4 -bitmap question -bd 3 -highlightthickness 1 \ + -indicatoron false + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {31 41 25 35 25 35 25 35} +test unixbutton-1.4 {TkpComputeButtonGeometry procedure} {nonPortable fonts} { + eval destroy [winfo children .] + label .b1 -text Xagqpim -padx 0 -pady 2 -font {Helvetica -18 bold} + button .b2 -text Xagqpim -padx 0 -pady 2 -font {Helvetica -18 bold} + checkbutton .b3 -text Xagqpim -padx 1 -pady 1 -font {Helvetica -18 bold} + radiobutton .b4 -text Xagqpim -padx 2 -pady 0 -font {Helvetica -18 bold} + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {82 29 88 35 114 31 121 29} +test unixbutton-1.5 {TkpComputeButtonGeometry procedure} {nonPortable fonts} { + eval destroy [winfo children .] + label .l1 -text "This is a long string that will wrap around on several lines.\n\nIt also has a blank line (above)." -wraplength 1.5i -padx 0 -pady 0 + pack .l1 + update + list [winfo reqwidth .l1] [winfo reqheight .l1] +} {136 88} +test unixbutton-1.6 {TkpComputeButtonGeometry procedure} {nonPortable fonts} { + eval destroy [winfo children .] + label .l1 -text "This is a long string without wrapping.\n\nIt also has a blank line (above)." -padx 0 -pady 0 + pack .l1 + update + list [winfo reqwidth .l1] [winfo reqheight .l1] +} {231 46} +test unixbutton-1.7 {TkpComputeButtonGeometry procedure} {nonPortable fonts} { + eval destroy [winfo children .] + label .b1 -text Xagqpim -bd 2 -padx 0 -pady 2 -width 10 + button .b2 -text Xagqpim -bd 2 -padx 0 -pady 2 -height 5 + checkbutton .b3 -text Xagqpim -bd 2 -padx 1 -pady 1 -width 20 -height 2 + radiobutton .b4 -text Xagqpim -bd 2 -padx 2 -pady 0 -width 4 + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {74 22 60 84 168 38 61 22} +test unixbutton-1.8 {TkpComputeButtonGeometry procedure} {nonPortable fonts} { + eval destroy [winfo children .] + label .b1 -text Xagqpim -bd 2 -padx 0 -pady 2 \ + -highlightthickness 4 + button .b2 -text Xagqpim -bd 2 -padx 0 -pady 2 \ + -highlightthickness 0 + checkbutton .b3 -text Xagqpim -bd 2 -padx 1 -pady 1 \ + -highlightthickness 1 -indicatoron no + radiobutton .b4 -text Xagqpim -bd 2 -padx 2 -pady 0 -indicatoron 0 + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {62 30 56 24 58 22 62 22} +test unixbutton-1.9 {TkpComputeButtonGeometry procedure} { + eval destroy [winfo children .] + button .b2 -bitmap question -default active + list [winfo reqwidth .b2] [winfo reqheight .b2] +} {37 47} +test unixbutton-1.10 {TkpComputeButtonGeometry procedure} { + eval destroy [winfo children .] + button .b2 -bitmap question -default normal + list [winfo reqwidth .b2] [winfo reqheight .b2] +} {37 47} +test unixbutton-1.11 {TkpComputeButtonGeometry procedure} { + eval destroy [winfo children .] + button .b2 -bitmap question -default disabled + list [winfo reqwidth .b2] [winfo reqheight .b2] +} {27 37} + +eval destroy [winfo children .] diff --git a/tests/unixEmbed.test b/tests/unixEmbed.test new file mode 100644 index 0000000..ef8ecb9 --- /dev/null +++ b/tests/unixEmbed.test @@ -0,0 +1,620 @@ +# This file is a Tcl script to test out the procedures in the file +# tkUnixEmbed.c. It is organized in the standard fashion for Tcl +# tests. +# +# Copyright (c) 1996-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) unixEmbed.test 1.7 97/08/13 11:13:21 + +if {$tcl_platform(platform) != "unix"} { + return +} + +if {[info procs test] != "test"} { + source defs +} + +eval destroy [winfo children .] +wm geometry . {} +raise . + +setupbg +dobg {wm withdraw .} + +# eatColors -- +# Creates a toplevel window and allocates enough colors in it to +# use up all the slots in the colormap. +# +# Arguments: +# w - Name of toplevel window to create. + +proc eatColors {w} { + catch {destroy $w} + toplevel $w + wm geom $w +0+0 + canvas $w.c -width 400 -height 200 -bd 0 + pack $w.c + for {set y 0} {$y < 8} {incr y} { + for {set x 0} {$x < 40} {incr x} { + set color [format #%02x%02x%02x [expr $x*6] [expr $y*30] 0] + $w.c create rectangle [expr 10*$x] [expr 20*$y] \ + [expr 10*$x + 10] [expr 20*$y + 20] -outline {} \ + -fill $color + } + } + update +} + +# colorsFree -- +# +# Returns 1 if there appear to be free colormap entries in a window, +# 0 otherwise. +# +# Arguments: +# w - Name of window in which to check. +# red, green, blue - Intensities to use in a trial color allocation +# to see if there are colormap entries free. + +proc colorsFree {w {red 31} {green 245} {blue 192}} { + set vals [winfo rgb $w [format #%02x%02x%02x $red $green $blue]] + expr ([lindex $vals 0]/256 == $red) && ([lindex $vals 1]/256 == $green) \ + && ([lindex $vals 2]/256 == $blue) +} + +test unixEmbed-1.1 {TkpUseWindow procedure, bad window identifier} { + catch {destroy .t} + list [catch {toplevel .t -use xyz} msg] $msg +} {1 {expected integer but got "xyz"}} +test unixEmbed-1.2 {TkpUseWindow procedure, bad window identifier} { + catch {destroy .t} + list [catch {toplevel .t -use 47} msg] $msg +} {1 {couldn't create child of window "47"}} +test unixEmbed-1.3 {TkpUseWindow procedure, inheriting colormap} { + catch {destroy .t} + catch {destroy .x} + toplevel .t -colormap new + wm geometry .t +0+0 + eatColors .t.t + frame .t.f -container 1 + toplevel .x -use [winfo id .t.f] + set result [colorsFree .x] + destroy .t + set result +} {0} +test unixEmbed-1.4 {TkpUseWindow procedure, inheriting colormap} { + catch {destroy .t} + catch {destroy .t2} + catch {destroy .x} + toplevel .t -container 1 -colormap new + wm geometry .t +0+0 + eatColors .t2 + toplevel .x -use [winfo id .t] + set result [colorsFree .x] + destroy .t + set result +} {1} +test unixEmbed-1.5 {TkpUseWindow procedure, creating Container records} { + eval destroy [winfo child .] + frame .f1 -container 1 -width 200 -height 50 + frame .f2 -container 1 -width 200 -height 50 + pack .f1 .f2 + dobg "set w [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t -use $w + list [testembed] [expr [lindex [lindex [testembed all] 0] 0] - $w] + } +} {{{XXX {} {} .t}} 0} +test unixEmbed-1.6 {TkpUseWindow procedure, creating Container records} { + eval destroy [winfo child .] + frame .f1 -container 1 -width 200 -height 50 + frame .f2 -container 1 -width 200 -height 50 + pack .f1 .f2 + dobg "set w1 [winfo id .f1]" + dobg "set w2 [winfo id .f2]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + toplevel .t2 -use $w2 + testembed + } +} {{XXX {} {} .t2} {XXX {} {} .t1}} +test unixEmbed-1.7 {TkpUseWindow procedure, container and embedded in same app} { + eval destroy [winfo child .] + frame .f1 -container 1 -width 200 -height 50 + frame .f2 -container 1 -width 200 -height 50 + pack .f1 .f2 + toplevel .t1 -use [winfo id .f1] + toplevel .t2 -use [winfo id .f2] + testembed +} {{XXX .f2 {} .t2} {XXX .f1 {} .t1}} + +# Can't think of any way to test the procedures TkpMakeWindow, +# TkpMakeContainer, or EmbedErrorProc. + +test unixEmbed-2.1 {EmbeddedEventProc procedure} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + testembed + } + destroy .f1 + update + dobg { + testembed + } +} {} +test unixEmbed-2.2 {EmbeddedEventProc procedure} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + testembed + destroy .t1 + testembed + } +} {} +test unixEmbed-2.3 {EmbeddedEventProc procedure} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + toplevel .t1 -use [winfo id .f1] + update + destroy .f1 + testembed +} {} +test unixEmbed-2.4 {EmbeddedEventProc procedure} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + toplevel .t1 -use [winfo id .f1] + update + destroy .t1 + set x [testembed] + update + list $x [testembed] +} {{{XXX .f1 {} {}}} {}} + +test unixEmbed-3.1 {ContainerEventProc procedure, detect creation} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + set x [testembed] + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + wm withdraw .t1 + } + list $x [testembed] +} {{{XXX .f1 {} {}}} {{XXX .f1 XXX {}}}} +test unixEmbed-3.2 {ContainerEventProc procedure, set size on creation} { + foreach w [winfo child .] { + catch {destroy $w} + } + toplevel .t1 -container 1 + wm geometry .t1 +0+0 + toplevel .t2 -use [winfo id .t1] -bg red + update + wm geometry .t2 +} {200x200+0+0} +test unixEmbed-3.2 {ContainerEventProc procedure, disallow position changes} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 -bd 2 -relief raised + update + wm geometry .t1 +30+40 + } + update + dobg { + wm geometry .t1 + } +} {200x200+0+0} +test unixEmbed-3.3 {ContainerEventProc procedure, disallow position changes} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + update + wm geometry .t1 300x100+30+40 + } + update + dobg { + wm geometry .t1 + } +} {300x100+0+0} +test unixEmbed-3.4 {ContainerEventProc procedure, geometry requests} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + } + update + dobg { + .t1 configure -width 300 -height 80 + } + update + list [winfo width .f1] [winfo height .f1] [dobg {wm geometry .t1}] +} {300 80 300x80+0+0} +test unixEmbed-3.5 {ContainerEventProc procedure, map requests} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + set x unmapped + bind .t1 <Map> {set x mapped} + } + update + dobg { + after 100 + update + set x + } +} {mapped} +test unixEmbed-3.6 {ContainerEventProc procedure, destroy events} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + bind .f1 <Destroy> {set x dead} + set x alive + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + } + update + dobg { + destroy .t1 + } + update + list $x [winfo exists .f1] +} {dead 0} + +test unixEmbed-4.1 {EmbedStructureProc procedure, configure events} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + } + update + dobg { + .t1 configure -width 180 -height 100 + } + update + dobg { + winfo geometry .t1 + } +} {180x100+0+0} +test unixEmbed-4.2 {EmbedStructureProc procedure, destroy events} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + } + update + set x [testembed] + destroy .f1 + list $x [testembed] +} {{{XXX .f1 XXX {}}} {}} + +test unixEmbed-5.1 {EmbedFocusProc procedure, FocusIn events} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + bind .t1 <FocusIn> {lappend x "focus in %W"} + bind .t1 <FocusOut> {lappend x "focus out %W"} + set x {} + } + focus -force .f1 + update + dobg {set x} +} {{focus in .t1}} +test unixEmbed-5.2 {EmbedFocusProc procedure, focusing on dead window} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + } + update + dobg { + after 200 {destroy .t1} + } + after 400 + focus -force .f1 + update +} {} +test unixEmbed-5.3 {EmbedFocusProc procedure, FocusOut events} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + bind .t1 <FocusIn> {lappend x "focus in %W"} + bind .t1 <FocusOut> {lappend x "focus out %W"} + set x {} + } + focus -force .f1 + update + set x [dobg {update; set x}] + focus . + update + list $x [dobg {update; set x}] +} {{{focus in .t1}} {{focus in .t1} {focus out .t1}}} + +test unixEmbed-6.1 {EmbedGeometryRequest procedure, window changes size} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + } + update + dobg { + bind .t1 <Configure> {lappend x {configure .t1 %w %h}} + set x {} + .t1 configure -width 300 -height 120 + update + list $x [winfo geom .t1] + } +} {{{configure .t1 300 120}} 300x120+0+0} +test unixEmbed-6.2 {EmbedGeometryRequest procedure, window changes size} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + place .f1 -width 200 -height 200 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + } + after 300 {set x done} + vwait x + dobg { + bind .t1 <Configure> {lappend x {configure .t1 %w %h}} + set x {} + .t1 configure -width 300 -height 120 + update + list $x [winfo geom .t1] + } +} {{{configure .t1 200 200}} 200x200+0+0} + +# Can't think up any tests for TkpGetOtherWindow procedure. + +test unixEmbed-7.1 {TkpRedirectKeyEvent procedure, forward keystroke} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + } + focus -force . + bind . <KeyPress> {lappend x {key %A %E}} + set x {} + set y [dobg { + update + bind .t1 <KeyPress> {lappend y {key %A}} + set y {} + event generate .t1 <KeyPress> -keysym a + set y + }] + update + bind . <KeyPress> {} + list $x $y +} {{{key a 1}} {}} +test unixEmbed-7.2 {TkpRedirectKeyEvent procedure, don't forward keystroke width} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 + } + update + focus -force .f1 + update + bind . <KeyPress> {lappend x {key %A}} + set x {} + set y [dobg { + update + bind .t1 <KeyPress> {lappend y {key %A}} + set y {} + event generate .t1 <KeyPress> -keysym b + set y + }] + update + bind . <KeyPress> {} + list $x $y +} {{} {{key b}}} + +test unixEmbed-8.1 {TkpClaimFocus procedure} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + frame .f2 -width 200 -height 50 + pack .f1 .f2 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 -highlightthickness 2 -bd 2 -relief sunken + } + focus -force .f2 + update + list [dobg { + focus .t1 + set x [list [focus]] + update + after 500 + update + lappend x [focus] + }] [focus] +} {{{} .t1} .f1} +test unixEmbed-8.2 {TkpClaimFocus procedure} { + catch {interp delete child} + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + frame .f2 -width 200 -height 50 + pack .f1 .f2 + interp create child + child eval "set argv {-use [winfo id .f1]}" + load {} tk child + child eval { + . configure -bd 2 -highlightthickness 2 -relief sunken + } + focus -force .f2 + update + list [child eval { + focus . + set x [list [focus]] + update + lappend x [focus] + }] [focus] +} {{{} .} .f1} +catch {interp delete child} + +test unixEmbed-9.1 {EmbedWindowDeleted procedure, check parentPtr} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + frame .f2 -container 1 -width 200 -height 50 + frame .f3 -container 1 -width 200 -height 50 + frame .f4 -container 1 -width 200 -height 50 + pack .f1 .f2 .f3 .f4 + set x {} + lappend x [testembed] + foreach w {.f3 .f4 .f1 .f2} { + destroy $w + lappend x [testembed] + } + set x +} {{{XXX .f4 {} {}} {XXX .f3 {} {}} {XXX .f2 {} {}} {XXX .f1 {} {}}} {{XXX .f4 {} {}} {XXX .f2 {} {}} {XXX .f1 {} {}}} {{XXX .f2 {} {}} {XXX .f1 {} {}}} {{XXX .f2 {} {}}} {}} +test unixEmbed-9.2 {EmbedWindowDeleted procedure, check embeddedPtr} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + dobg "set w1 [winfo id .f1]" + dobg { + eval destroy [winfo child .] + toplevel .t1 -use $w1 -highlightthickness 2 -bd 2 -relief sunken + set x {} + lappend x [testembed] + destroy .t1 + lappend x [testembed] + } +} {{{XXX {} {} .t1}} {}} + +test unixEmbed-10.1 {geometry propagation in tkUnixWm.c/UpdateGeometryInfo} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + toplevel .t1 -use [winfo id .f1] -width 150 -height 80 + update + wm geometry .t1 +40+50 + update + wm geometry .t1 +} {150x80+0+0} +test unixEmbed-10.2 {geometry propagation in tkUnixWm.c/UpdateGeometryInfo} { + foreach w [winfo child .] { + catch {destroy $w} + } + frame .f1 -container 1 -width 200 -height 50 + pack .f1 + toplevel .t1 -use [winfo id .f1] -width 150 -height 80 + update + wm geometry .t1 70x300+10+20 + update + wm geometry .t1 +} {70x300+0+0} + + +foreach w [winfo child .] { + catch {destroy $w} +} +cleanupbg diff --git a/tests/unixFont.test b/tests/unixFont.test new file mode 100644 index 0000000..edcce42 --- /dev/null +++ b/tests/unixFont.test @@ -0,0 +1,293 @@ +# This file is a Tcl script to test out the procedures in tkUnixFont.c. +# It is organized in the standard fashion for Tcl tests. +# +# Many of these tests are visually oriented and cannot be checked +# programmatically (such as "does an underlined font appear to be +# underlined?"); these tests attempt to exercise the code in question, +# but there are no results that can be checked. Some tests depend on the +# fonts having or not having certain properties, which may not be valid +# at all sites. +# +# Copyright (c) 1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) unixFont.test 1.7 97/06/24 13:34:24 + +if {$tcl_platform(platform)!="unix"} { + return +} + +if {[string compare test [info procs test]] != 0} { + source defs +} + +catch {destroy .b} +toplevel .b +wm geom .b +0+0 +update idletasks + +# Font should be fixed width and have chars missing below char 32, so can +# test control char expansion and missing character code. + +set courier {Courier -10} +set cx [font measure $courier 0] + +label .b.l -padx 0 -pady 0 -bd 0 -highlightthickness 0 -justify left -text "0" -font fixed +pack .b.l +canvas .b.c -closeenough 0 + +set t [.b.c create text 0 0 -anchor nw -just left -font $courier] +pack .b.c +update + +set ax [winfo reqwidth .b.l] +set ay [winfo reqheight .b.l] +proc getsize {} { + update + return "[winfo reqwidth .b.l] [winfo reqheight .b.l]" +} + +test unixfont-1.1 {TkpGetNativeFont procedure: not native} { + list [catch {font measure {} xyz} msg] $msg +} {1 {font "" doesn't exist}} +test unixfont-1.2 {TkpGetNativeFont procedure: native} { + font measure fixed 0 +} {6} + +test unixfont-2.1 {TkpGetFontFromAttributes procedure: no family} { + font actual {-size 10} + set x {} +} {} +test unixfont-2.2 {TkpGetFontFromAttributes procedure: Times relatives} { + set x {} + lappend x [lindex [font actual {-family "Times New Roman"}] 1] + lappend x [lindex [font actual {-family "New York"}] 1] + lappend x [lindex [font actual {-family "Times"}] 1] +} {times times times} +test unixfont-2.3 {TkpGetFontFromAttributes procedure: Courier relatives} { + set x {} + lappend x [lindex [font actual {-family "Courier New"}] 1] + lappend x [lindex [font actual {-family "Monaco"}] 1] + lappend x [lindex [font actual {-family "Courier"}] 1] +} {courier courier courier} +test unixfont-2.4 {TkpGetFontFromAttributes procedure: Helvetica relatives} { + set x {} + lappend x [lindex [font actual {-family "Arial"}] 1] + lappend x [lindex [font actual {-family "Geneva"}] 1] + lappend x [lindex [font actual {-family "Helvetica"}] 1] +} {helvetica helvetica helvetica} +test unixfont-2.5 {TkpGetFontFromAttributes procedure: fallback} { + font actual {-xyz-xyz-*-*-*-*-*-*-*-*-*-*-*-*} + set x {} +} {} +test unixfont-2.6 {TkpGetFontFromAttributes: fallback to fixed family} { + lindex [font actual {-family fixed -size 10}] 1 +} {fixed} +test unixfont-2.7 {TkpGetFontFromAttributes: fixed family not available!} { + # no test available +} {} +test unixfont-2.8 {TkpGetFontFromAttributes: loop over returned font names} { + lindex [font actual {-family fixed -size 31}] 1 +} {fixed} +test unixfont-2.9 {TkpGetFontFromAttributes: reject adobe courier if possible} { + lindex [font actual {-family courier}] 1 +} {courier} +test unixfont-2.10 {TkpGetFontFromAttributes: scalable font found} { + lindex [font actual {-family courier -size 37}] 3 +} {37} +test unixfont-2.11 {TkpGetFontFromAttributes: font cannot be loaded} { + # On Linux, XListFonts() was returning names for fonts that do not + # actually exist, causing the subsequent XLoadQueryFont() to fail + # unexpectedly. Now falls back to another font if that happens. + + font actual {-size 14} + set x {} +} {} + +test unixfont-3.1 {TkpDeleteFont procedure} { + font actual {-family xyz} + set x {} +} {} + +test unixfont-4.1 {TkpGetFontFamilies procedure} { + font families + set x {} +} {} + +test unixfont-5.1 {Tk_MeasureChars procedure: no chars to be measured} { + .b.l config -text "000000" -wrap [expr $ax*3] + .b.l config -wrap 0 +} {} +test unixfont-5.2 {Tk_MeasureChars procedure: no right margin} { + .b.l config -text "000000" +} {} +test unixfont-5.3 {Tk_MeasureChars procedure: loop over chars} { + .b.l config -text "0" + .b.l config -text "\377" + .b.l config -text "0\3770\377" + .b.l config -text "000000000000000" +} {} +.b.l config -wrap [expr $ax*10] +test unixfont-5.4 {Tk_MeasureChars procedure: reached right edge} { + .b.l config -text "0000000000000" + getsize +} "[expr $ax*10] [expr $ay*2]" +test unixfont-5.5 {Tk_MeasureChars procedure: ran out of chars} { + .b.l config -text "000000" + getsize +} "[expr $ax*6] $ay" +test unixfont-5.6 {Tk_MeasureChars procedure: find last word} { + .b.l config -text "000000 00000" + getsize +} "[expr $ax*6] [expr $ay*2]" +test unixfont-5.7 {Tk_MeasureChars procedure: already saw space in line} { + .b.l config -text "000000 00000" + getsize +} "[expr $ax*6] [expr $ay*2]" +test unixfont-5.8 {Tk_MeasureChars procedure: internal spaces significant} { + .b.l config -text "00 000 00000" + getsize +} "[expr $ax*7] [expr $ay*2]" +test unixfont-5.9 {Tk_MeasureChars procedure: TK_PARTIAL_OK} { + .b.c dchars $t 0 end + .b.c insert $t 0 "0000" + .b.c index $t @[expr int($ax*2.5)],1 +} {2} +test unixfont-5.10 {Tk_MeasureChars procedure: TK_AT_LEAST_ONE} { + .b.l config -text "000000000000" + getsize +} "[expr $ax*10] [expr $ay*2]" +test unixfont-5.11 {Tk_MeasureChars: TK_AT_LEAST_ONE + not even one char fit!} { + set a [.b.l cget -wrap] + .b.l config -text "000000" -wrap 1 + set x [getsize] + .b.l config -wrap $a + set x +} "$ax [expr $ay*6]" +test unixfont-5.12 {Tk_MeasureChars procedure: include eol spaces} { + .b.l config -text "000 \n000" + getsize +} "[expr $ax*6] [expr $ay*2]" + +test unixfont-6.1 {Tk_DrawChars procedure: loop test} { + .b.l config -text "a" + update +} {} +test unixfont-6.2 {Tk_DrawChars procedure: loop test} { + .b.l config -text "abcd" + update +} {} +test unixfont-6.3 {Tk_DrawChars procedure: special char} { + .b.l config -text "\001" + update +} {} +test unixfont-6.4 {Tk_DrawChars procedure: normal then special} { + .b.l config -text "ab\001" + update +} {} +test unixfont-6.5 {Tk_DrawChars procedure: ends with special} { + .b.l config -text "ab\001" + update +} {} +test unixfont-6.6 {Tk_DrawChars procedure: more normal chars at end} { + .b.l config -text "ab\001def" + update +} {} + +test unixfont-7.1 {DrawChars procedure: no effects} { + .b.l config -text "abc" + update +} {} +test unixfont-7.2 {DrawChars procedure: underlining} { + set f [.b.l cget -font] + .b.l config -text "abc" -font "courier 10 underline" + update + .b.l config -font $f +} {} +test unixfont-7.3 {DrawChars procedure: overstrike} { + set f [.b.l cget -font] + .b.l config -text "abc" -font "courier 10 overstrike" + update + .b.l config -font $f +} {} + +test unixfont-8.1 {AllocFont procedure: use old font} { + font create xyz + button .c -font xyz + font configure xyz -family times + update + destroy .c + font delete xyz +} {} +test unixfont-8.2 {AllocFont procedure: parse information from XLFD} { + expr [lindex [font actual {-family times -size 0}] 3]==0 +} {0} +test unixfont-8.3 {AllocFont procedure: can't parse info from name} { + if [catch {set a [font actual a12biluc]}]==0 { + string compare $a "-family a12biluc -size 0 -weight normal -slant roman -underline 0 -overstrike 0" + } else { + set a 0 + } +} {0} +test unixfont-8.4 {AllocFont procedure: classify characters} { + set x 0 + incr x [font measure $courier "\001"] ;# 4 + incr x [font measure $courier "\002"] ;# 4 + incr x [font measure $courier "\012"] ;# 2 + incr x [font measure $courier "\101"] ;# 1 + set x +} [expr $cx*11] +test unixfont-8.5 {AllocFont procedure: setup widths of normal chars} { + font metrics $courier -fixed +} {1} +test unixfont-8.6 {AllocFont procedure: setup widths of special chars} { + set x 0 + incr x [font measure $courier "\001"] ;# 4 + incr x [font measure $courier "\002"] ;# 4 + incr x [font measure $courier "\012"] ;# 2 + set x +} [expr $cx*10] +test unixfont-8.7 {AllocFont procedure: XA_UNDERLINE_POSITION} { + catch {font actual -adobe-courier-bold-i-normal--0-0-0-0-m-0-iso8859-1} + set x {} +} {} +test unixfont-8.8 {AllocFont procedure: no XA_UNDERLINE_POSITION} { + catch {font actual --symbol-medium-r-normal--0-0-0-0-p-0-sun-fontspecific} + set x {} +} {} +test unixfont-8.9 {AllocFont procedure: XA_UNDERLINE_THICKNESS} { + catch {font actual -adobe-courier-bold-i-normal--0-0-0-0-m-0-iso8859-1} + set x {} +} {} +test unixfont-8.10 {AllocFont procedure: no XA_UNDERLINE_THICKNESS} { + catch {font actual --symbol-medium-r-normal--0-0-0-0-p-0-sun-fontspecific} + set x {} +} {} +test unixfont-8.11 {AllocFont procedure: XA_UNDERLINE_POSITION was 0} { + catch {font actual -adobe-courier-bold-i-normal--0-0-0-0-m-0-iso8859-1} + set x {} +} {} + +test unixfont-9.1 {GetControlCharSubst procedure: 2 chars subst} { + .b.c dchars $t 0 end + .b.c insert $t 0 "0\a0" + set x {} + lappend x [.b.c index $t @[expr $ax*0],0] + lappend x [.b.c index $t @[expr $ax*1],0] + lappend x [.b.c index $t @[expr $ax*2],0] + lappend x [.b.c index $t @[expr $ax*3],0] +} {0 1 1 2} +test unixfont-9.2 {GetControlCharSubst procedure: 4 chars subst} { + .b.c dchars $t 0 end + .b.c insert $t 0 "0\1770" + set x {} + lappend x [.b.c index $t @[expr $ax*0],0] + lappend x [.b.c index $t @[expr $ax*1],0] + lappend x [.b.c index $t @[expr $ax*2],0] + lappend x [.b.c index $t @[expr $ax*3],0] + lappend x [.b.c index $t @[expr $ax*4],0] + lappend x [.b.c index $t @[expr $ax*5],0] +} {0 1 1 1 1 2} + diff --git a/tests/unixMenu.test b/tests/unixMenu.test new file mode 100644 index 0000000..dfcf252 --- /dev/null +++ b/tests/unixMenu.test @@ -0,0 +1,969 @@ +# This file is a Tcl script to test menus in Tk. It is +# organized in the standard fashion for Tcl tests. This +# file tests the Macintosh-specific features of the menu +# system. +# +# Copyright (c) 1995-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) unixMenu.test 1.9 97/06/24 13:52:38 + +if {$tcl_platform(platform) != "unix"} { + return +} + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\" image" + puts "type, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +proc deleteWindows {} { + foreach i [winfo children .] { + catch [destroy $i] + } +} + +deleteWindows +wm geometry . {} +raise . + +test unixMenu-1.1 {TkpNewMenu - normal menu} { + catch {destroy .m1} + list [catch {menu .m1} msg] $msg [destroy .m1] +} {0 .m1 {}} +test unixMenu-1.2 {TkpNewMenu - help menu} { + catch {destroy .m1} + menu .m1 -tearoff 0 + . configure -menu .m1 + .m1 add cascade -label Help -menu .m1.help + list [catch {menu .m1.help} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 .m1.help {} {}} + +test unixMenu-2.1 {TkpDestroyMenu - nothing to do} {} {} +test unixMenu-3.1 {TkpDestroymenuEntry - nothing to do} {} {} + +test unixMenu-4.1 {TkpConfigureMenuEntry - non-cascade entry} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label test + list [catch {.m1 entryconfigure test -label foo} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-4.2 {TkpConfigureMenuEntry - cascade entry} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -menu .m2 -label test + menu .m1.foo -tearoff 0 + list [catch {.m1 entryconfigure test -menu .m1.foo} msg] $msg [destroy .m1] +} {0 {} {}} + +test unixMenu-5.1 {TkpMenuNewEntry - nothing to do} {} {} + +test unixMenu-6.1 {TkpSetWindowMenuBar - null menu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + . configure -menu .m1 + list [catch {. configure -menu ""} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-6.2 {TkpSetWindowMenuBar - menu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} + +test unixMenu-7.1 {TkpSetMainMenubar - nothing to do} {} {} + +test unixMenu-8.1 {GetMenuIndicatorGeometry - indicator off} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo -indicatoron 0 + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test unixMenu-8.2 {GetMenuIndicatorGeometry - not checkbutton or radio} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test unixMenu-8.3 {GetMenuIndicatorGeometry - checkbutton image} { + catch {destroy .m1} + catch {image delete image1} + menu .m1 + image create test image1 + .m1 add checkbutton -image image1 -label foo + .m1 invoke foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] [image delete image1] +} {0 {} {}} +test unixMenu-8.4 {GetMenuIndicatorGeometry - checkbutton bitmap} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -bitmap questhead -label foo + .m1 invoke foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test unixMenu-8.5 {GetMenuIndicatorGeometry - checkbutton} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + .m1 invoke foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test unixMenu-8.6 {GetMenuIndicatorGeometry - radiobutton image} { + catch {destroy .m1} + catch {image delete image1} + menu .m1 + image create test image1 + .m1 add radiobutton -image image1 -label foo + .m1 invoke foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] [image delete image1] +} {0 {} {}} +test unixMenu-8.7 {GetMenuIndicatorGeometry - radiobutton bitmap} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -bitmap questhead -label foo + .m1 invoke foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test unixMenu-8.8 {GetMenuIndicatorGeometry - radiobutton} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label foo + .m1 invoke foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test unixMenu-8.9 {GetMenuIndicatorGeometry - hideMargin} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label foo -hidemargin 1 + .m1 invoke foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} + +test unixMenu-9.1 {GetMenuAccelGeometry - cascade entry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test unixMenu-9.2 {GetMenuAccelGeometry - non-null label} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Ctrl+S" + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test unixMenu-9.3 {GetMenuAccelGeometry - null label} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} + +test unixMenu-10.1 {DrawMenuEntryBackground - active menubar} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + . configure -menu .m1 + .m1 activate 1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-10.2 {DrawMenuEntryBackground - active} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + $tearoff activate 0 + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-10.3 {DrawMenuEntryBackground - non-active} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +test unixMenu-11.1 {DrawMenuEntryAccelerator - menubar} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Ctrl+U" + . configure -menu .m1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +# drawArrow parameter is never false under Unix +test unixMenu-11.2 {DrawMenuEntryAccelerator - cascade entry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-11.3 {DrawMenuEntryAccelerator - normal entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Ctrl+U" + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-11.4 {DrawMenuEntryAccelerator - null entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +test unixMenu-12.1 {DrawMenuEntryIndicator - non-check or radio} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-12.2 {DrawMenuEntryIndicator - checkbutton - indicator off} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo -indicatoron 0 + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-12.3 {DrawMenuEntryIndicator - checkbutton - not selected} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-12.4 {DrawMenuEntryIndicator - checkbutton - selected} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-12.5 {DrawMenuEntryIndicator - radiobutton - indicator off} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label foo -indicatoron 0 + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-12.6 {DrawMenuEntryIndicator - radiobutton - not selected} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} +test unixMenu-12.7 {DrawMenuEntryIndicator - radiobutton - selected} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label foo + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +test unixMenu-13.1 {DrawMenuSeparator - menubar case} { + catch {destroy .m1} + menu .m1 + .m1 add separator + . configure -menu .m1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-13.2 {DrawMenuSepartor - normal menu} { + catch {destroy .m1} + menu .m1 + .m1 add separator + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +test unixMenu-14.1 {DrawMenuEntryLabel} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +test unixMenu-15.1 {DrawMenuUnderline - menubar} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -underline 0 + . configure -menu .m1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-15.2 {DrawMenuUnderline - no menubar} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -underline 0 + set tearoff [tkTearOffMenu .m1 40 40] + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +test unixMenu-16.1 {TkpPostMenu} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} + +test unixMenu-17.1 {GetMenuSeparatorGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add separator + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} + +test unixMenu-18.1 {GetTearoffEntryGeometry} { + catch {destroy .m1} + menubutton .mb -text "test" -menu .mb.m + menu .mb.m + .mb.m add command -label test + pack .mb + raise . + list [catch {tkMbPost .mb} msg] $msg [destroy .mb] +} {0 {} {}} + +# Don't know how to reproduce the case where the tkwin has been deleted. +test unixMenu-19.1 {TkpComputeMenubarGeometry - zero entries} { + catch {destroy .m1} + menu .m1 + . configure -menu .m1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +# Don't know how to generate one width windows +test unixMenu-19.2 {TkpComputeMenubarGeometry - one entry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label File + . configure -menu .m1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.3 {TkpComputeMenubarGeometry - entry with different font} { + catch {destroy .m1} + menu .m1 -font "Courier 24" + .m1 add cascade -label File -font "Helvetica 18" + . configure -menu .m1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.4 {TkpComputeMenubarGeometry - separator} { + catch {destroy .m1} + menu .m1 + .m1 add separator + . configure -menu .m1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.5 {TkpComputeMenubarGeometry - First entry} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label File + . configure -menu .m1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.6 {TkpComputeMenubarGeometry - First entry too wide} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label File -font "Times 72" + . configure -menu .m1 + wm geometry . 10x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.7 {TkpComputeMenubarGeometry - two entries fit} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label File + .m1 add cascade -label Edit + . configure -menu .m1 + wm geometry . 200x200 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.8 {TkpComputeMenubarGeometry - two entries; 2nd don't fit} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label File + .m1 add cascade -label Edit -font "Times 72" + . configure -menu .m1 + wm geometry . 100x100 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.9 {TkpComputeMenubarGeometry - two entries; 1st dont fit} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label File -font "Times 72" + .m1 add cascade -label Edit + . configure -menu .m1 + wm geometry . 100x100 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.10 {TkpComputeMenubarGeometry - two entries; neither fit} { + catch {destroy .m1} + menu .m1 -tearoff 0 -font "Times 72" + .m1 add cascade -label File + .m1 add cascade -label Edit + . configure -menu .m1 + wm geometry . 10x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +# ABC notation; capital A means first window fits, small a means it +# does not. capital B menu means second window fist, etc. +test unixMenu-19.11 {TkpComputeMenubarGeometry - abc} { + catch {destroy .m1} + menu .m1 -tearoff 0 -font "Times 72" + .m1 add cascade -label "aaaaa" + .m1 add cascade -label "bbbbb" + .m1 add cascade -label "ccccc" + . configure -menu .m1 + wm geometry . 10x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.12 {TkpComputeMenubarGeometry - abC} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label "aaaaa" -font "Times 72" + .m1 add cascade -label "bbbbb" -font "Times 72" + .m1 add cascade -label "C" + . configure -menu .m1 + wm geometry . 10x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.13 {TkpComputeMenubarGeometry - aBc} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label "aaaaa" -font "Times 72" + .m1 add cascade -label "B" + .m1 add cascade -label "ccccc" -font "Times 72" + . configure -menu .m1 + wm geometry . 10x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.14 {TkpComputeMenubarGeometry - aBC} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label "aaaaa" -font "Times 72" + .m1 add cascade -label "B" + .m1 add cascade -label "C" + . configure -menu .m1 + wm geometry . 60x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.15 {TkpComputeMenubarGeometry - Abc} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label "A" + .m1 add cascade -label "bbbbb" -font "Times 72" + .m1 add cascade -label "ccccc" -font "Times 72" + . configure -menu .m1 + wm geometry . 60x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.16 {TkpComputeMenubarGeometry - AbC} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label "A" + .m1 add cascade -label "bbbbb" -font "Times 72" + .m1 add cascade -label "C" + . configure -menu .m1 + wm geometry . 60x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.17 {TkpComputeMenubarGeometry - ABc} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label "A" + .m1 add cascade -label "B" + .m1 add cascade -label "ccccc" -font "Times 72" + . configure -menu .m1 + wm geometry . 60x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.18 {TkpComputeMenubarGeometry - ABC} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label "A" + .m1 add cascade -label "B" + .m1 add cascade -label "C" + . configure -menu .m1 + wm geometry . 100x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.19 {TkpComputeMenubarGeometry - help menu in first position} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label Help -menu .m1.help + menu .m1.help -tearoff 0 + .m1 add cascade -label File -menu .m1.file + menu .m1.file -tearoff 0 + .m1 add cascade -label Edit -menu .m1.edit + menu .m1.edit -tearoff 0 + . configure -menu .m1 + wm geometry . 100x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.20 {TkpComputeMenubarGeometry - help menu in middle} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label Edit -menu .m1.edit + menu .m1.edit -tearoff 0 + .m1 add cascade -label Help -menu .m1.help + menu .m1.help -tearoff 0 + .m1 add cascade -label File -menu .m1.file + menu .m1.file -tearoff 0 + . configure -menu .m1 + wm geometry . 100x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.21 {TkpComputeMenubarGeometry - help menu in first position} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label File -menu .m1.file + menu .m1.file -tearoff 0 + .m1 add cascade -label Edit -menu .m1.edit + menu .m1.edit -tearoff 0 + .m1 add cascade -label Help -menu .m1.help + menu .m1.help -tearoff 0 + . configure -menu .m1 + wm geometry . 100x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.22 {TkpComputeMenubarGeometry - help item fits} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label File -menu .m1.file + menu .m1.file -tearoff 0 + .m1 add cascade -label Help -menu .m1.help + menu .m1.help -tearoff 0 + . configure -menu .m1 + wm geometry . 100x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.23 {TkpComputeMenubarGeometry - help item does not fit} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label File -menu .m1.file + menu .m1.file -tearoff 0 + .m1 add cascade -label Help -menu .m1.help -font "Helvetica 72" + menu .m1.help -tearoff 0 + . configure -menu .m1 + wm geometry . 100x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-19.24 {TkpComputeMenubarGeometry - help item only one} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label Help -menu .m1.help + menu .m1.help -tearoff 0 + . configure -menu .m1 + wm geometry . 100x10 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} + +test unixMenu-20.1 {DrawTearoffEntry - menubar} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label File + . configure -menu .m1 + list [catch {update} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test unixMenu-20.2 {DrawTearoffEntry - non-menubar} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + .m1 post 40 40 + list [catch {update} msg] $msg [destroy .m1] +} {0 {} {}} + +test unixMenu-21.1 {TkpInitializeMenuBindings - nothing to do} {} {} + +test unixMenu-22.1 {SetHelpMenu - no menubars} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label test -menu .m1.test + list [catch {menu .m1.test} msg] $msg [destroy .m1] +} {0 .m1.test {}} +# Don't know how to automate missing tkwins +test unixMenu-22.2 {SetHelpMenu - menubar but no help menu} { + catch {destroy .m1} + menu .m1 -tearoff 0 + . configure -menu .m1 + .m1 add cascade -label .m1.file + list [catch {menu .m1.file} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 .m1.file {} {}} +test unixMenu-22.3 {SetHelpMenu - menubar with help menu} { + catch {destroy .m1} + menu .m1 -tearoff 0 + . configure -menu .m1 + .m1 add cascade -label .m1.help + list [catch {menu .m1.help} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 .m1.help {} {}} +test unixMenu-22.4 {SetHelpMenu - multiple menubars with same help menu} { + catch {destroy .m1} + catch {destroy .t2} + toplevel .t2 + wm geometry .t2 +40+40 + menu .m1 -tearoff 0 + . configure -menu .m1 + .t2 configure -menu .m1 + .m1 add cascade -label .m1.help + list [catch {menu .m1.help} msg] $msg [. configure -menu ""] [destroy .m1] [destroy .t2] +} {0 .m1.help {} {} {}} + +test unixMenu-23.1 {TkpDrawMenuEntry - gc for active and not strict motif} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.2 {TkpDrawMenuEntry - gc for active menu item with its own gc} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -activeforeground red + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.3 {TkpDrawMenuEntry - gc for active and strict motif} { + catch {destroy .m1} + menu .m1 + set tk_strictMotif 1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] [set tk_strictMotif 0] +} {{} {} 0} +test unixMenu-23.4 {TkpDrawMenuEntry - gc for disabled with disabledfg and custom entry} { + catch {destroy .m1} + menu .m1 -disabledforeground blue + .m1 add command -label foo -state disabled -background red + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.5 {TkpDrawMenuEntry - gc for disabled with disabledFg} { + catch {destroy .m1} + menu .m1 -disabledforeground blue + .m1 add command -label foo -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.6 {TkpDrawMenuEntry - gc for disabled - no disabledFg} { + catch {destroy .m1} + menu .m1 -disabledforeground "" + .m1 add command -label foo -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.7 {TkpDrawMenuEntry - gc for normal - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -foreground red + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.8 {TkpDrawMenuEntry - gc for normal} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.9 {TkpDrawMenuEntry - gc for indicator - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo -selectcolor orange + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.10 {TkpDrawMenuEntry - gc for indicator} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.11 {TkpDrawMenuEntry - border - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -activebackground green + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.12 {TkpDrawMenuEntry - border} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.13 {TkpDrawMenuEntry - active border - strict motif} { + catch {destroy .m1} + set tk_strictMotif 1 + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] [set tk_strictMotif 0] +} {{} {} 0} +test unixMenu-23.14 {TkpDrawMenuEntry - active border - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -activeforeground yellow + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.15 {TkpDrawMenuEntry - active border} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.16 {TkpDrawMenuEntry - font - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -font "Helvectica 72" + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.17 {TkpDrawMenuEntry - font} { + catch {destroy .m1} + menu .m1 -font "Courier 72" + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.18 {TkpDrawMenuEntry - separator} { + catch {destroy .m1} + menu .m1 + .m1 add separator + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.19 {TkpDrawMenuEntry - standard} { + catch {destroy .mb} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.20 {TkpDrawMenuEntry - disabled cascade item} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label File -menu .m1.file + menu .m1.file + .m1.file add command -label foo + .m1 entryconfigure File -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.21 {TkpDrawMenuEntry - indicator} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label Foo + .m1 invoke Foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test unixMenu-23.22 {TkpDrawMenuEntry - hide margin} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label Foo -hidemargin 1 + .m1 invoke Foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} + +test unixMenu-24.1 {GetMenuLabelGeometry - image} { + catch {destroy .m1} + catch {image delete image1} + menu .m1 + image create test image1 + .m1 add command -image image1 + list [update idletasks] [destroy .m1] [image delete image1] +} {{} {} {}} +test unixMenu-24.2 {GetMenuLabelGeometry - bitmap} { + catch {destroy .m1} + menu .m1 + .m1 add command -bitmap questhead + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-24.3 {GetMenuLabelGeometry - no text} { + catch {destroy .m1} + menu .m1 + .m1 add command + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-24.4 {GetMenuLabelGeometry - text} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "This is a test." + list [update idletasks] [destroy .m1] +} {{} {}} + +test unixMenu-25.1 {TkpComputeStandardMenuGeometry - no entries} { + catch {destroy .m1} + menu .m1 + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.2 {TkpComputeStandardMenuGeometry - one entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.3 {TkpComputeStandardMenuGeometry - more than one entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + .m1 add command -label "two" + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.4 {TkpComputeStandardMenuGeometry - separator} { + catch {destroy .m1} + menu .m1 + .m1 add separator + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.5 {TkpComputeStandardMenuGeometry - tearoff entry} {unixOnly} { + catch {destroy .m1} + menubutton .mb -text "test" -menu .mb.m + menu .mb.m + .mb.m add command -label test + pack .mb + catch {tkMbPost .mb} + list [update] [destroy .mb] +} {{} {}} +test unixMenu-25.6 {TkpComputeStandardMenuGeometry - standard label geometry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.7 {TkpComputeStandardMenuGeometry - different font for entry} { + catch {destroy .m1} + menu .m1 -font "Helvetica 12" + .m1 add command -label "test" -font "Courier 12" + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.8 {TkpComputeStandardMenuGeometry - second entry larger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add command -label "test test" + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.9 {TkpComputeStandardMenuGeometry - first entry larger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test test" + .m1 add command -label "test" + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.10 {TkpComputeStandardMenuGeometry - accelerator} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" -accel "Ctrl+S" + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.11 {TkpComputeStandardMenuGeometry - second accel larger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" -accel "1" + .m1 add command -label "test" -accel "1 1" + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.12 {TkpComputeStandardMenuGeometry - second accel smaller} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" -accel "1 1" + .m1 add command -label "test" -accel "1" + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.13 {TkpComputeStandardMenuGeometry - indicator} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label test + .m1 invoke 1 + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.14 {TkpComputeStandardMenuGeometry - second indicator less or equal } { + catch {destroy .m1} + catch {image delete image1} + image create test image1 + menu .m1 + .m1 add checkbutton -image image1 + .m1 invoke 1 + .m1 add checkbutton -label test + .m1 invoke 2 + list [update idletasks] [destroy .m1] [image delete image1] +} {{} {} {}} +test unixMenu-25.15 {TkpComputeStandardMenuGeometry - second indicator larger } {unixOnly} { + catch {destroy .m1} + catch {image delete image1} + image create test image1 + menu .m1 + .m1 add checkbutton -image image1 + .m1 invoke 1 + .m1 add checkbutton -label test + .m1 invoke 2 + list [update idletasks] [destroy .m1] [image delete image1] +} {{} {} {}} +test unixMenu-25.16 {TkpComputeStandardMenuGeometry - zero sized menus} { + catch {destroy .m1} + menu .m1 -tearoff 0 + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.17 {TkpComputeStandardMenuGeometry - first column bigger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label one + .m1 add command -label two + .m1 add command -label three -columnbreak 1 + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.18 {TkpComputeStandardMenuGeometry - second column bigger} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label one + .m1 add command -label two -columnbreak 1 + .m1 add command -label three + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.19 {TkpComputeStandardMenuGeometry - three columns} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label one + .m1 add command -label two -columnbreak 1 + .m1 add command -label three + .m1 add command -label four + .m1 add command -label five -columnbreak 1 + .m1 add command -label six + list [update idletasks] [destroy .m1] +} {{} {}} +test unixMenu-25.20 {TkpComputeStandardMenuGeometry - hide margin} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add checkbutton -label one -hidemargin 1 + list [update idletasks] [destroy .m1] +} {{} {}} + +test unixMenu-26.1 {TkpMenuInit - nothing to do} {} {} + +deleteWindows diff --git a/tests/unixWm.test b/tests/unixWm.test new file mode 100644 index 0000000..b165826 --- /dev/null +++ b/tests/unixWm.test @@ -0,0 +1,2352 @@ +# This file is a Tcl script to test out Tk's interactions with +# the window manager, including the "wm" command. It is organized +# in the standard fashion for Tcl tests. +# +# Copyright (c) 1992-1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) unixWm.test 1.46 97/10/27 16:15:36 + +if {$tcl_platform(platform) != "unix"} { + return +} + +if {[string compare test [info procs test]] == 1} { + source defs +} + +proc sleep ms { + global x + after $ms {set x 1} + vwait x +} + +# Procedure to set up a collection of top-level windows + +proc makeToplevels {} { + foreach i [winfo child .] { + destroy $i + } + foreach i {.raise1 .raise2 .raise3} { + toplevel $i + wm geom $i 150x100+0+0 + update + } +} + +set i 1 +foreach geom {+20+80 +80+20 +0+0} { + catch {destroy .t} + test unixWm-1.$i {initial window position} { + toplevel .t -width 200 -height 150 + wm geom .t $geom + update + wm geom .t + } 200x150$geom + incr i +} + +# The tests below are tricky because window managers don't all move +# windows correctly. Try one motion and compute the window manager's +# error, then factor this error into the actual tests. In other words, +# this just makes sure that things are consistent between moves. + +set i 1 +catch {destroy .t} +toplevel .t -width 100 -height 150 +wm geom .t +200+200 +update +wm geom .t +150+150 +update +scan [wm geom .t] %dx%d+%d+%d width height x y +set xerr [expr 150-$x] +set yerr [expr 150-$y] +foreach geom {+20+80 +80+20 +0+0 -0-0 +0-0 -0+0 -10-5 -10+5 +10-5} { + test unixWm-2.$i {moving window while mapped} { + wm geom .t $geom + update + scan [wm geom .t] %dx%d%1s%d%1s%d width height xsign x ysign y + format "%s%d%s%d" $xsign [eval expr $x$xsign$xerr] $ysign \ + [eval expr $y$ysign$yerr] + } $geom + incr i +} + +set i 1 +foreach geom {+20+80 +80+20 +0+0 -0-0 +0-0 -0+0 -10-5 -10+5 +10-5} { + test unixWm-3.$i {moving window while iconified} { + wm iconify .t + sleep 200 + wm geom .t $geom + update + wm deiconify .t + scan [wm geom .t] %dx%d%1s%d%1s%d width height xsign x ysign y + format "%s%d%s%d" $xsign [eval expr $x$xsign$xerr] $ysign \ + [eval expr $y$ysign$yerr] + } $geom + incr i +} + +set i 1 +foreach geom {+20+80 +100+40 +0+0} { + test unixWm-4.$i {moving window while withdrawn} { + wm withdraw .t + sleep 200 + wm geom .t $geom + update + wm deiconify .t + wm geom .t + } 100x150$geom + incr i +} + +test unixWm-5.1 {compounded state changes} {nonPortable} { + catch {destroy .t} + toplevel .t -width 200 -height 100 + wm geometry .t +100+100 + update + wm withdraw .t + wm deiconify .t + list [winfo ismapped .t] [wm state .t] +} {1 normal} +test unixWm-5.2 {compounded state changes} {nonPortable} { + catch {destroy .t} + toplevel .t -width 200 -height 100 + wm geometry .t +100+100 + update + wm withdraw .t + wm deiconify .t + wm withdraw .t + list [winfo ismapped .t] [wm state .t] +} {0 withdrawn} +test unixWm-5.3 {compounded state changes} {nonPortable} { + catch {destroy .t} + toplevel .t -width 200 -height 100 + wm geometry .t +100+100 + update + wm iconify .t + wm deiconify .t + wm iconify .t + wm deiconify .t + list [winfo ismapped .t] [wm state .t] +} {1 normal} +test unixWm-5.4 {compounded state changes} {nonPortable} { + catch {destroy .t} + toplevel .t -width 200 -height 100 + wm geometry .t +100+100 + update + wm iconify .t + wm deiconify .t + wm iconify .t + list [winfo ismapped .t] [wm state .t] +} {0 iconic} +test unixWm-5.5 {compounded state changes} {nonPortable} { + catch {destroy .t} + toplevel .t -width 200 -height 100 + wm geometry .t +100+100 + update + wm iconify .t + wm withdraw .t + list [winfo ismapped .t] [wm state .t] +} {0 withdrawn} +test unixWm-5.6 {compounded state changes} {nonPortable} { + catch {destroy .t} + toplevel .t -width 200 -height 100 + wm geometry .t +100+100 + update + wm iconify .t + wm withdraw .t + wm deiconify .t + list [winfo ismapped .t] [wm state .t] +} {1 normal} +test unixWm-5.7 {compounded state changes} {nonPortable} { + catch {destroy .t} + toplevel .t -width 200 -height 100 + wm geometry .t +100+100 + update + wm withdraw .t + wm iconify .t + list [winfo ismapped .t] [wm state .t] +} {0 iconic} + +catch {destroy .t} +toplevel .t -width 200 -height 100 +wm geom .t +10+10 +wm minsize .t 1 1 +update +test unixWm-6.1 {size changes} { + .t config -width 180 -height 150 + update + wm geom .t +} 180x150+10+10 +test unixWm-6.2 {size changes} { + wm geom .t 250x60 + .t config -width 170 -height 140 + update + wm geom .t +} 250x60+10+10 +test unixWm-6.3 {size changes} { + wm geom .t 250x60 + .t config -width 170 -height 140 + wm geom .t {} + update + wm geom .t +} 170x140+10+10 +test unixWm-6.4 {size changes} {nonPortable} { + wm minsize .t 1 1 + update + puts stdout "Please resize window \"t\" with the mouse (but don't move it!)," + puts -nonewline stdout "then hit return: " + flush stdout + gets stdin + update + set width [winfo width .t] + set height [winfo height .t] + .t config -width 230 -height 110 + update + incr width -[winfo width .t] + incr height -[winfo height .t] + wm geom .t {} + update + set w2 [winfo width .t] + set h2 [winfo height .t] + .t config -width 114 -height 261 + update + list $width $height $w2 $h2 [wm geom .t] +} {0 0 230 110 114x261+10+10} + +# I don't know why the wait below is needed, but without it the test +# fails under twm. +sleep 200 + +test unixWm-6.5 {window initially iconic} {nonPortable} { + catch {destroy .t} + toplevel .t -width 100 -height 30 + wm geometry .t +0+0 + wm title .t 2 + wm iconify .t + update idletasks + wm withdraw .t + wm deiconify .t + list [winfo ismapped .t] [wm state .t] +} {1 normal} + +catch {destroy .m} +toplevel .m +wm overrideredirect .m 1 +foreach i {{Test label} Another {Yet another} {Last label}} j {1 2 3} { + label .m.$j -text $i +} +wm geometry .m +[expr 100 - [winfo vrootx .]]+[expr 200 - [winfo vrooty .]] +update +test unixWm-7.1 {override_redirect and Tk_MoveTopLevelWindow} { + list [winfo ismapped .m] [wm state .m] [winfo x .m] [winfo y .m] +} {1 normal 100 200} +wm geometry .m +[expr 150 - [winfo vrootx .]]+[expr 210 - [winfo vrooty .]] +update +test unixWm-7.2 {override_redirect and Tk_MoveTopLevelWindow} { + list [winfo ismapped .m] [wm state .m] [winfo x .m] [winfo y .m] +} {1 normal 150 210} +wm withdraw .m +test unixWm-7.3 {override_redirect and Tk_MoveTopLevelWindow} { + list [winfo ismapped .m] +} 0 +destroy .m +catch {destroy .t} + +test unixWm-8.1 {icon windows} { + catch {destroy .t} + catch {destroy .icon} + toplevel .t -width 100 -height 30 + wm geometry .t +0+0 + toplevel .icon -width 50 -height 50 -bg red + wm iconwindow .t .icon + list [catch {wm withdraw .icon} msg] $msg +} {1 {can't withdraw .icon: it is an icon for .t}} +test unixWm-8.2 {icon windows} { + catch {destroy .t} + toplevel .t -width 100 -height 30 + list [catch {wm iconwindow} msg] $msg +} {1 {wrong # args: should be "wm option window ?arg ...?"}} +test unixWm-8.3 {icon windows} { + catch {destroy .t} + toplevel .t -width 100 -height 30 + list [catch {wm iconwindow .t b c} msg] $msg +} {1 {wrong # arguments: must be "wm iconwindow window ?pathName?"}} +test unixWm-8.4 {icon windows} { + catch {destroy .t} + catch {destroy .icon} + toplevel .t -width 100 -height 30 + wm geom .t +0+0 + set result [wm iconwindow .t] + toplevel .icon -width 50 -height 50 -bg red + wm iconwindow .t .icon + lappend result [wm iconwindow .t] [wm state .icon] + wm iconwindow .t {} + lappend result [wm iconwindow .t] [wm state .icon] + update + lappend result [winfo ismapped .t] [winfo ismapped .icon] + wm iconify .t + update + lappend result [winfo ismapped .t] [winfo ismapped .icon] +} {.icon icon {} withdrawn 1 0 0 0} +test unixWm-8.5 {icon windows} { + catch {destroy .t} + toplevel .t -width 100 -height 30 + list [catch {wm iconwindow .t .gorp} msg] $msg +} {1 {bad window path name ".gorp"}} +test unixWm-8.6 {icon windows} { + catch {destroy .t} + toplevel .t -width 100 -height 30 + frame .t.icon -width 50 -height 50 -bg red + list [catch {wm iconwindow .t .t.icon} msg] $msg +} {1 {can't use .t.icon as icon window: not at top level}} +test unixWm-8.7 {icon windows} { + catch {destroy .t} + catch {destroy .icon} + toplevel .t -width 100 -height 30 + wm geom .t +0+0 + toplevel .icon -width 50 -height 50 -bg red + toplevel .icon2 -width 50 -height 50 -bg green + wm iconwindow .t .icon + set result "[wm iconwindow .t] [wm state .icon] [wm state .icon2]" + wm iconwindow .t .icon2 + lappend result [wm iconwindow .t] [wm state .icon] [wm state .icon2] +} {.icon icon normal .icon2 withdrawn icon} +catch {destroy .icon2} +test unixWm-8.8 {icon windows} { + catch {destroy .t} + catch {destroy .icon} + toplevel .icon -width 50 -height 50 -bg red + wm geom .icon +0+0 + update + set result [winfo ismapped .icon] + toplevel .t -width 100 -height 30 + wm geom .t +0+0 + tkwait visibility .t ;# Needed to keep tvtwm happy. + wm iconwindow .t .icon + sleep 500 + lappend result [winfo ismapped .t] [winfo ismapped .icon] +} {1 1 0} +test unixWm-8.9 {icon windows} {nonPortable} { + # This test is non-portable because some window managers will + # destroy an icon window when it's associated window is destroyed. + + catch {destroy .t} + catch {destroy .icon} + toplevel .t -width 100 -height 30 + toplevel .icon -width 50 -height 50 -bg red + wm geom .t +0+0 + wm iconwindow .t .icon + update + set result "[wm state .icon] [winfo ismapped .t] [winfo ismapped .icon]" + destroy .t + wm geom .icon +0+0 + update + lappend result [winfo ismapped .icon] [wm state .icon] + wm deiconify .icon + update + lappend result [winfo ismapped .icon] [wm state .icon] +} {icon 1 0 0 withdrawn 1 normal} + +test unixWm-9.1 {TkWmMapWindow procedure, client property} {unixOnly} { + catch {destroy .t} + toplevel .t -width 100 -height 50 + wm geom .t +0+0 + wm client .t Test_String + update + testprop [testwrapper .t] WM_CLIENT_MACHINE +} {Test_String} +test unixWm-9.2 {TkWmMapWindow procedure, command property} {unixOnly} { + catch {destroy .t} + toplevel .t -width 100 -height 50 + wm geom .t +0+0 + wm command .t "test command" + update + testprop [testwrapper .t] WM_COMMAND +} {test +command +} +test unixWm-9.3 {TkWmMapWindow procedure, iconic windows} { + catch {destroy .t} + toplevel .t -width 100 -height 300 -bg blue + wm geom .t +0+0 + wm iconify .t + sleep 500 + winfo ismapped .t +} {0} +test unixWm-9.4 {TkWmMapWindow procedure, icon windows} { + catch {destroy .t} + sleep 500 + toplevel .t -width 100 -height 50 -bg blue + wm iconwindow . .t + update + set result [winfo ismapped .t] +} {0} +test unixWm-9.5 {TkWmMapWindow procedure, normal windows} { + catch {destroy .t} + toplevel .t -width 200 -height 20 + wm geom .t +0+0 + update + winfo ismapped .t +} {1} + +test unixWm-10.1 {TkWmDeadWindow procedure, canceling UpdateGeometry idle handler} { + catch {destroy .t} + toplevel .t -width 100 -height 50 + wm geom .t +0+0 + update + .t configure -width 200 -height 100 + destroy .t +} {} +test unixWm-10.2 {TkWmDeadWindow procedure, destroying menubar} {unixOnly} { + catch {destroy .t} + catch {destroy .f} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + wm geom .t +0+0 + update + frame .f -width 400 -height 30 -bd 2 -relief raised -bg green + bind .f <Destroy> {lappend result destroyed} + testmenubar window .t .f + update + set result {} + destroy .t + lappend result [winfo exists .f] +} {destroyed 0} + +test unixWm-11.1 {Tk_WmCmd procedure, miscellaneous errors} { + list [catch {wm} msg] $msg +} {1 {wrong # args: should be "wm option window ?arg ...?"}} +test unixWm-11.2 {Tk_WmCmd procedure, miscellaneous errors} { + list [catch {wm foo} msg] $msg +} {1 {wrong # args: should be "wm option window ?arg ...?"}} +test unixWm-11.3 {Tk_WmCmd procedure, miscellaneous errors} { + list [catch {wm foo bogus} msg] $msg +} {1 {bad window path name "bogus"}} +test unixWm-11.4 {Tk_WmCmd procedure, miscellaneous errors} { + catch {destroy .b} + button .b -text hello + list [catch {wm geometry .b} msg] $msg +} {1 {window ".b" isn't a top-level window}} + +catch {destroy .t} +catch {destroy .icon} + +toplevel .t -width 100 -height 50 +wm geom .t +0+0 +update + +test unixWm-12.1 {Tk_WmCmd procedure, "aspect" option} { + list [catch {wm aspect .t 12} msg] $msg +} {1 {wrong # arguments: must be "wm aspect window ?minNumer minDenom maxNumer maxDenom?"}} +test unixWm-12.2 {Tk_WmCmd procedure, "aspect" option} { + list [catch {wm aspect .t 12 13 14 15 16} msg] $msg +} {1 {wrong # arguments: must be "wm aspect window ?minNumer minDenom maxNumer maxDenom?"}} +test unixWm-12.3 {Tk_WmCmd procedure, "aspect" option} { + set result {} + lappend result [wm aspect .t] + wm aspect .t 3 4 10 2 + lappend result [wm aspect .t] + wm aspect .t {} {} {} {} + lappend result [wm aspect .t] +} {{} {3 4 10 2} {}} +test unixWm-12.4 {Tk_WmCmd procedure, "aspect" option} { + list [catch {wm aspect .t bad 14 15 16} msg] $msg +} {1 {expected integer but got "bad"}} +test unixWm-12.5 {Tk_WmCmd procedure, "aspect" option} { + list [catch {wm aspect .t 13 foo 15 16} msg] $msg +} {1 {expected integer but got "foo"}} +test unixWm-12.6 {Tk_WmCmd procedure, "aspect" option} { + list [catch {wm aspect .t 13 14 bar 16} msg] $msg +} {1 {expected integer but got "bar"}} +test unixWm-12.7 {Tk_WmCmd procedure, "aspect" option} { + list [catch {wm aspect .t 13 14 15 baz} msg] $msg +} {1 {expected integer but got "baz"}} +test unixWm-12.8 {Tk_WmCmd procedure, "aspect" option} { + list [catch {wm aspect .t 0 14 15 16} msg] $msg +} {1 {aspect number can't be <= 0}} +test unixWm-12.9 {Tk_WmCmd procedure, "aspect" option} { + list [catch {wm aspect .t 13 0 15 16} msg] $msg +} {1 {aspect number can't be <= 0}} +test unixWm-12.10 {Tk_WmCmd procedure, "aspect" option} { + list [catch {wm aspect .t 13 14 0 16} msg] $msg +} {1 {aspect number can't be <= 0}} +test unixWm-12.11 {Tk_WmCmd procedure, "aspect" option} { + list [catch {wm aspect .t 13 14 15 0} msg] $msg +} {1 {aspect number can't be <= 0}} + +test unixWm-13.1 {Tk_WmCmd procedure, "client" option} { + list [catch {wm client .t x y} msg] $msg +} {1 {wrong # arguments: must be "wm client window ?name?"}} +test unixWm-13.2 {Tk_WmCmd procedure, "client" option} {unixOnly} { + set result {} + lappend result [wm client .t] + wm client .t Test_String + lappend result [testprop [testwrapper .t] WM_CLIENT_MACHINE] + wm client .t New + lappend result [wm client .t] + wm client .t {} + lappend result [wm client .t] [testprop [testwrapper .t] WM_CLIENT_MACHINE] +} {{} Test_String New {} {}} +test unixWm-13.3 {Tk_WmCmd procedure, "client" option, unmapped window} { + catch {destroy .t2} + toplevel .t2 + wm client .t2 Test_String + wm client .t2 {} + wm client .t2 Test_String + destroy .t2 +} {} + +test unixWm-14.1 {Tk_WmCmd procedure, "colormapwindows" option} { + list [catch {wm colormapwindows .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm colormapwindows window ?windowList?"}} +test unixWm-14.2 {Tk_WmCmd procedure, "colormapwindows" option} { + catch {destroy .t2} + toplevel .t2 -width 200 -height 200 -colormap new + wm geom .t2 +0+0 + frame .t2.a -width 100 -height 30 + frame .t2.b -width 100 -height 30 -colormap new + pack .t2.a .t2.b -side top + update + set x [wm colormapwindows .t2] + frame .t2.c -width 100 -height 30 -colormap new + pack .t2.c -side top + update + list $x [wm colormapwindows .t2] +} {{.t2.b .t2} {.t2.b .t2.c .t2}} +test unixWm-14.3 {Tk_WmCmd procedure, "colormapwindows" option} { + list [catch {wm col . "a \{"} msg] $msg +} {1 {unmatched open brace in list}} +test unixWm-14.4 {Tk_WmCmd procedure, "colormapwindows" option} { + list [catch {wm colormapwindows . foo} msg] $msg +} {1 {bad window path name "foo"}} +test unixWm-14.5 {Tk_WmCmd procedure, "colormapwindows" option} { + catch {destroy .t2} + toplevel .t2 -width 200 -height 200 -colormap new + wm geom .t2 +0+0 + frame .t2.a -width 100 -height 30 + frame .t2.b -width 100 -height 30 + frame .t2.c -width 100 -height 30 + pack .t2.a .t2.b .t2.c -side top + wm colormapwindows .t2 {.t2.c .t2 .t2.a} + wm colormapwindows .t2 +} {.t2.c .t2 .t2.a} +test unixWm-14.6 {Tk_WmCmd procedure, "colormapwindows" option} { + catch {destroy .t2} + toplevel .t2 -width 200 -height 200 + wm geom .t2 +0+0 + frame .t2.a -width 100 -height 30 + frame .t2.b -width 100 -height 30 + frame .t2.c -width 100 -height 30 + pack .t2.a .t2.b .t2.c -side top + wm colormapwindows .t2 {.t2.b .t2.a} + wm colormapwindows .t2 +} {.t2.b .t2.a} +test unixWm-14.7 {Tk_WmCmd procedure, "colormapwindows" option} { + catch {destroy .t2} + toplevel .t2 -width 200 -height 200 -colormap new + wm geom .t2 +0+0 + set x [wm colormapwindows .t2] + wm colormapwindows .t2 {} + list $x [wm colormapwindows .t2] +} {{} {}} +catch {destroy .t2} + +test unixWm-15.1 {Tk_WmCmd procedure, "command" option} { + list [catch {wm command .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm command window ?value?"}} +test unixWm-15.2 {Tk_WmCmd procedure, "command" option} { + list [catch {wm command .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm command window ?value?"}} +test unixWm-15.3 {Tk_WmCmd procedure, "command" option} {unixOnly} { + set result {} + lappend result [wm command .t] + wm command .t "test command" + lappend result [testprop [testwrapper .t] WM_COMMAND] + wm command .t "new command" + lappend result [wm command .t] + wm command .t {} + lappend result [wm command .t] [testprop [testwrapper .t] WM_COMMAND] +} {{} {test +command +} {new command} {} {}} +test unixWm-15.4 {Tk_WmCmd procedure, "command" option, window not mapped} { + catch {destroy .t2} + toplevel .t2 + wm geom .t2 +0+0 + wm command .t2 "test command" + wm command .t2 "new command" + wm command .t2 {} + destroy .t2 +} {} +test unixWm-15.5 {Tk_WmCmd procedure, "command" option} { + list [catch {wm command .t "a \{b"} msg] $msg +} {1 {unmatched open brace in list}} + +test unixWm-16.1 {Tk_WmCmd procedure, "deiconify" option} { + list [catch {wm deiconify .t 12} msg] $msg +} {1 {wrong # arguments: must be "wm deiconify window"}} +test unixWm-16.2 {Tk_WmCmd procedure, "deiconify" option} { + catch {destroy .icon} + toplevel .icon -width 50 -height 50 -bg red + wm iconwindow .t .icon + set result [list [catch {wm deiconify .icon} msg] $msg] + destroy .icon + set result +} {1 {can't deiconify .icon: it is an icon for .t}} +test unixWm-16.3 {Tk_WmCmd procedure, "deiconify" option} { + wm iconify .t + set result {} + lappend result [winfo ismapped .t] [wm state .t] + wm deiconify .t + lappend result [winfo ismapped .t] [wm state .t] +} {0 iconic 1 normal} + +test unixWm-17.1 {Tk_WmCmd procedure, "focusmodel" option} { + list [catch {wm focusmodel .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm focusmodel window ?active|passive?"}} +test unixWm-17.2 {Tk_WmCmd procedure, "focusmodel" option} { + list [catch {wm focusmodel .t bogus} msg] $msg +} {1 {bad argument "bogus": must be active or passive}} +test unixWm-17.3 {Tk_WmCmd procedure, "focusmodel" option} { + set result {} + lappend result [wm focusmodel .t] + wm focusmodel .t active + lappend result [wm focusmodel .t] + wm focusmodel .t passive + lappend result [wm focusmodel .t] + set result +} {passive active passive} + +test unixWm-18.1 {Tk_WmCmd procedure, "frame" option} { + list [catch {wm frame .t 12} msg] $msg +} {1 {wrong # arguments: must be "wm frame window"}} +test unixWm-18.2 {Tk_WmCmd procedure, "frame" option} nonPortable { + expr [wm frame .t] == [winfo id .t] +} {0} +test unixWm-18.3 {Tk_WmCmd procedure, "frame" option} nonPortable { + catch {destroy .t2} + toplevel .t2 + wm geom .t2 +0+0 + wm overrideredirect .t2 1 + update + set result [expr [wm frame .t2] == [winfo id .t2]] + destroy .t2 + set result +} {1} + +test unixWm-19.1 {Tk_WmCmd procedure, "geometry" option} { + list [catch {wm geometry .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm geometry window ?newGeometry?"}} +test unixWm-19.2 {Tk_WmCmd procedure, "geometry" option} nonPortable { + wm geometry .t -1+5 + update + wm geometry .t +} {100x50-1+5} +test unixWm-19.3 {Tk_WmCmd procedure, "geometry" option} nonPortable { + wm geometry .t +10-4 + update + wm geometry .t +} {100x50+10-4} +test unixWm-19.4 {Tk_WmCmd procedure, "geometry" option} nonPortable { + catch {destroy .t2} + toplevel .t2 + wm geom .t2 -5+10 + listbox .t2.l -width 30 -height 12 -setgrid 1 + pack .t2.l + update + set result [wm geometry .t2] + destroy .t2 + set result +} {30x12-5+10} +test unixWm-19.5 {Tk_WmCmd procedure, "geometry" option} nonPortable { + wm geometry .t 150x300+5+6 + update + set result {} + lappend result [wm geometry .t] + wm geometry .t {} + update + lappend result [wm geometry .t] +} {150x300+5+6 100x50+5+6} +test unixWm-19.6 {Tk_WmCmd procedure, "geometry" option} { + list [catch {wm geometry .t qrs} msg] $msg +} {1 {bad geometry specifier "qrs"}} + +test unixWm-20.1 {Tk_WmCmd procedure, "grid" option} { + list [catch {wm grid .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm grid window ?baseWidth baseHeight widthInc heightInc?"}} +test unixWm-20.2 {Tk_WmCmd procedure, "grid" option} { + list [catch {wm grid .t 12 13 14 15 16} msg] $msg +} {1 {wrong # arguments: must be "wm grid window ?baseWidth baseHeight widthInc heightInc?"}} +test unixWm-20.3 {Tk_WmCmd procedure, "grid" option} { + set result {} + lappend result [wm grid .t] + wm grid .t 5 6 20 10 + lappend result [wm grid .t] + wm grid .t {} {} {} {} + lappend result [wm grid .t] +} {{} {5 6 20 10} {}} +test unixWm-20.4 {Tk_WmCmd procedure, "grid" option} { + list [catch {wm grid .t bad 10 11 12} msg] $msg +} {1 {expected integer but got "bad"}} +test unixWm-20.5 {Tk_WmCmd procedure, "grid" option} { + list [catch {wm grid .t -1 11 12 13} msg] $msg +} {1 {baseWidth can't be < 0}} +test unixWm-20.6 {Tk_WmCmd procedure, "grid" option} { + list [catch {wm grid .t 10 foo 12 13} msg] $msg +} {1 {expected integer but got "foo"}} +test unixWm-20.7 {Tk_WmCmd procedure, "grid" option} { + list [catch {wm grid .t 10 -11 12 13} msg] $msg +} {1 {baseHeight can't be < 0}} +test unixWm-20.8 {Tk_WmCmd procedure, "grid" option} { + list [catch {wm grid .t 10 11 bar 13} msg] $msg +} {1 {expected integer but got "bar"}} +test unixWm-20.9 {Tk_WmCmd procedure, "grid" option} { + list [catch {wm grid .t 10 11 -2 13} msg] $msg +} {1 {widthInc can't be < 0}} +test unixWm-20.10 {Tk_WmCmd procedure, "grid" option} { + list [catch {wm grid .t 10 11 12 bogus} msg] $msg +} {1 {expected integer but got "bogus"}} +test unixWm-20.11 {Tk_WmCmd procedure, "grid" option} { + list [catch {wm grid .t 10 11 12 -1} msg] $msg +} {1 {heightInc can't be < 0}} + +catch {destroy .t} +catch {destroy .icon} +toplevel .t -width 100 -height 50 +wm geom .t +0+0 +update + +test unixWm-21.1 {Tk_WmCmd procedure, "group" option} { + list [catch {wm group .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm group window ?pathName?"}} +test unixWm-21.2 {Tk_WmCmd procedure, "group" option} { + list [catch {wm group .t bogus} msg] $msg +} {1 {bad window path name "bogus"}} +test unixWm-21.3 {Tk_WmCmd procedure, "group" option} {unixOnly} { + set result {} + lappend result [wm group .t] + wm group .t . + set bit [format 0x%x [expr 0x40 & [lindex [testprop [testwrapper .t] \ + WM_HINTS] 0]]] + lappend result [wm group .t] $bit + wm group .t {} + set bit [format 0x%x [expr 0x40 & [lindex [testprop [testwrapper .t] \ + WM_HINTS] 0]]] + lappend result [wm group .t] $bit +} {{} . 0x40 {} 0x0} +test unixWm-21.4 {Tk_WmCmd procedure, "group" option, make window exist} {unixOnly} { + catch {destroy .t2} + toplevel .t2 + wm geom .t2 +0+0 + wm group .t .t2 + set hints [testprop [testwrapper .t] WM_HINTS] + set result [expr [testwrapper .t2] - [lindex $hints 8]] + destroy .t2 + set result +} {0} +test unixWm-21.5 {Tk_WmCmd procedure, "group" option, create leader wrapper} {unixOnly} { + catch {destroy .t2} + catch {destroy .t3} + toplevel .t2 -width 120 -height 300 + wm geometry .t2 +0+0 + toplevel .t3 -width 120 -height 300 + wm geometry .t2 +0+0 + set result [list [testwrapper .t2]] + wm group .t3 .t2 + lappend result [expr {[testwrapper .t2] == ""}] + destroy .t2 .t3 + set result +} {{} 0} + +test unixWm-22.1 {Tk_WmCmd procedure, "iconbitmap" option} { + list [catch {wm iconbitmap .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm iconbitmap window ?bitmap?"}} +test unixWm-22.2 {Tk_WmCmd procedure, "iconbitmap" option} {unixOnly} { + set result {} + lappend result [wm iconbitmap .t] + wm iconbitmap .t questhead + set bit [format 0x%x [expr 0x4 & [lindex [testprop [testwrapper .t] \ + WM_HINTS] 0]]] + lappend result [wm iconbitmap .t] $bit + wm iconbitmap .t {} + set bit [format 0x%x [expr 0x4 & [lindex [testprop [testwrapper .t] \ + WM_HINTS] 0]]] + lappend result [wm iconbitmap .t] $bit +} {{} questhead 0x4 {} 0x0} +test unixWm-22.3 {Tk_WmCmd procedure, "iconbitmap" option} { + list [catch {wm iconbitmap .t bad-bitmap} msg] $msg +} {1 {bitmap "bad-bitmap" not defined}} + +test unixWm-23.1 {Tk_WmCmd procedure, "iconify" option} { + list [catch {wm iconify .t 12} msg] $msg +} {1 {wrong # arguments: must be "wm iconify window"}} +test unixWm-23.2 {Tk_WmCmd procedure, "iconify" option} { + catch {destroy .t2} + toplevel .t2 + wm overrideredirect .t2 1 + set result [list [catch {wm iconify .t2} msg] $msg] + destroy .t2 + set result +} {1 {can't iconify ".t2": override-redirect flag is set}} +test unixWm-23.3 {Tk_WmCmd procedure, "iconify" option} { + catch {destroy .t2} + toplevel .t2 + wm geom .t2 +0+0 + wm transient .t2 .t + set result [list [catch {wm iconify .t2} msg] $msg] + destroy .t2 + set result +} {1 {can't iconify ".t2": it is a transient}} +test unixWm-23.4 {Tk_WmCmd procedure, "iconify" option} { + catch {destroy .t2} + toplevel .t2 + wm geom .t2 +0+0 + wm iconwindow .t .t2 + set result [list [catch {wm iconify .t2} msg] $msg] + destroy .t2 + set result +} {1 {can't iconify .t2: it is an icon for .t}} +test unixWm-23.5 {Tk_WmCmd procedure, "iconify" option} { + catch {destroy .t2} + toplevel .t2 + wm geom .t2 +0+0 + wm iconify .t2 + update + set result [winfo ismapped .t2] + destroy .t2 + set result +} {0} +test unixWm-23.6 {Tk_WmCmd procedure, "iconify" option} { + catch {destroy .t2} + toplevel .t2 + wm geom .t2 -0+0 + update + set result [winfo ismapped .t2] + wm iconify .t2 + lappend result [winfo ismapped .t2] + destroy .t2 + set result +} {1 0} + +test unixWm-24.1 {Tk_WmCmd procedure, "iconmask" option} { + list [catch {wm iconmask .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm iconmask window ?bitmap?"}} +test unixWm-24.2 {Tk_WmCmd procedure, "iconmask" option} {unixOnly} { + set result {} + lappend result [wm iconmask .t] + wm iconmask .t questhead + set bit [format 0x%x [expr 0x20 & [lindex [testprop [testwrapper .t] \ + WM_HINTS] 0]]] + lappend result [wm iconmask .t] $bit + wm iconmask .t {} + set bit [format 0x%x [expr 0x20 & [lindex [testprop [testwrapper .t] \ + WM_HINTS] 0]]] + lappend result [wm iconmask .t] $bit +} {{} questhead 0x20 {} 0x0} +test unixWm-24.3 {Tk_WmCmd procedure, "iconmask" option} { + list [catch {wm iconmask .t bogus} msg] $msg +} {1 {bitmap "bogus" not defined}} + +test unixWm-25.1 {Tk_WmCmd procedure, "iconname" option} { + list [catch {wm icon .t} msg] $msg +} {1 {unknown or ambiguous option "icon": must be aspect, client, command, deiconify, focusmodel, frame, geometry, grid, group, iconbitmap, iconify, iconmask, iconname, iconposition, iconwindow, maxsize, minsize, overrideredirect, positionfrom, protocol, resizable, sizefrom, state, title, transient, or withdraw}} +test unixWm-25.2 {Tk_WmCmd procedure, "iconname" option} { + list [catch {wm iconname .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm iconname window ?newName?"}} +test unixWm-25.3 {Tk_WmCmd procedure, "iconname" option} {unixOnly} { + set result {} + lappend result [wm iconname .t] + wm iconname .t test_name + lappend result [wm iconname .t] [testprop [testwrapper .t] WM_ICON_NAME] + wm iconname .t {} + lappend result [wm iconname .t] [testprop [testwrapper .t] WM_ICON_NAME] +} {{} test_name test_name {} {}} + +test unixWm-26.1 {Tk_WmCmd procedure, "iconposition" option} { + list [catch {wm iconposition .t 12} msg] $msg +} {1 {wrong # arguments: must be "wm iconposition window ?x y?"}} +test unixWm-26.2 {Tk_WmCmd procedure, "iconposition" option} { + list [catch {wm iconposition .t 12 13 14} msg] $msg +} {1 {wrong # arguments: must be "wm iconposition window ?x y?"}} +test unixWm-26.3 {Tk_WmCmd procedure, "iconposition" option} {unixOnly} { + set result {} + lappend result [wm iconposition .t] + wm iconposition .t 10 15 + set prop [testprop [testwrapper .t] WM_HINTS] + lappend result [wm iconposition .t] [lindex $prop 5] [lindex $prop 6] + lappend result [format 0x%x [expr 0x10 & [lindex $prop 0]]] + wm iconposition .t {} {} + set bit [format 0x%x [expr 0x10 & [lindex [testprop [testwrapper .t] \ + WM_HINTS] 0]]] + lappend result [wm iconposition .t] $bit +} {{} {10 15} 0xa 0xf 0x10 {} 0x0} +test unixWm-26.4 {Tk_WmCmd procedure, "iconposition" option} { + list [catch {wm iconposition .t bad 13} msg] $msg +} {1 {expected integer but got "bad"}} +test unixWm-26.5 {Tk_WmCmd procedure, "iconposition" option} { + list [catch {wm iconposition .t 13 lousy} msg] $msg +} {1 {expected integer but got "lousy"}} + +test unixWm-27.1 {Tk_WmCmd procedure, "iconwindow" option} { + list [catch {wm iconwindow .t 12 13} msg] $msg +} {1 {wrong # arguments: must be "wm iconwindow window ?pathName?"}} +test unixWm-27.2 {Tk_WmCmd procedure, "iconwindow" option} {unixOnly} { + catch {destroy .icon} + toplevel .icon -width 50 -height 50 -bg green + set result {} + lappend result [wm iconwindow .t] + wm iconwindow .t .icon + set prop [testprop [testwrapper .t] WM_HINTS] + lappend result [wm iconwindow .t] [wm state .icon] + lappend result [format 0x%x [expr 0x8 & [lindex $prop 0]]] + lappend result [expr [testwrapper .icon] == [lindex $prop 4]] + wm iconwindow .t {} + set bit [format 0x%x [expr 0x8 & [lindex [testprop [testwrapper .t] \ + WM_HINTS] 0]]] + lappend result [wm iconwindow .t] [wm state .icon] $bit + destroy .icon + set result +} {{} .icon icon 0x8 1 {} withdrawn 0x0} +test unixWm-27.3 {Tk_WmCmd procedure, "iconwindow" option} { + list [catch {wm iconwindow .t bogus} msg] $msg +} {1 {bad window path name "bogus"}} +test unixWm-27.4 {Tk_WmCmd procedure, "iconwindow" option} { + catch {destroy .b} + button .b -text Help + set result [list [catch {wm iconwindow .t .b} msg] $msg] + destroy .b + set result +} {1 {can't use .b as icon window: not at top level}} +test unixWm-27.5 {Tk_WmCmd procedure, "iconwindow" option} { + catch {destroy .icon} + toplevel .icon -width 50 -height 50 -bg green + catch {destroy .t2} + toplevel .t2 + wm geom .t2 -0+0 + wm iconwindow .t2 .icon + set result [list [catch {wm iconwindow .t .icon} msg] $msg] + destroy .t2 + destroy .icon + set result +} {1 {.icon is already an icon for .t2}} +test unixWm-27.6 {Tk_WmCmd procedure, "iconwindow" option, changing icons} { + catch {destroy .icon} + catch {destroy .icon2} + toplevel .icon -width 50 -height 50 -bg green + toplevel .icon2 -width 50 -height 50 -bg red + set result {} + wm iconwindow .t .icon + lappend result [wm state .icon] [wm state .icon2] + wm iconwindow .t .icon2 + lappend result [wm state .icon] [wm state .icon2] + destroy .icon .icon2 + set result +} {icon normal withdrawn icon} +test unixWm-27.7 {Tk_WmCmd procedure, "iconwindow" option, withdrawing icon} { + catch {destroy .icon} + toplevel .icon -width 50 -height 50 -bg green + wm geometry .icon +0+0 + update + set result {} + lappend result [wm state .icon] [winfo viewable .icon] + wm iconwindow .t .icon + lappend result [wm state .icon] [winfo viewable .icon] + destroy .icon + set result +} {normal 1 icon 0} + +test unixWm-28.1 {Tk_WmCmd procedure, "maxsize" option} { + list [catch {wm maxsize} msg] $msg +} {1 {wrong # args: should be "wm option window ?arg ...?"}} +test unixWm-28.2 {Tk_WmCmd procedure, "maxsize" option} { + list [catch {wm maxsize . a} msg] $msg +} {1 {wrong # arguments: must be "wm maxsize window ?width height?"}} +test unixWm-28.3 {Tk_WmCmd procedure, "maxsize" option} { + list [catch {wm maxsize . a b c} msg] $msg +} {1 {wrong # arguments: must be "wm maxsize window ?width height?"}} +test unixWm-28.4 {Tk_WmCmd procedure, "maxsize" option} {nonPortable} { + wm maxsize .t +} {1137 870} +test unixWm-28.5 {Tk_WmCmd procedure, "maxsize" option} { + list [catch {wm maxsize . x 100} msg] $msg +} {1 {expected integer but got "x"}} +test unixWm-28.6 {Tk_WmCmd procedure, "maxsize" option} { + list [catch {wm maxsize . 100 bogus} msg] $msg +} {1 {expected integer but got "bogus"}} +test unixWm-28.7 {Tk_WmCmd procedure, "maxsize" option} { + wm maxsize .t 200 150 + wm maxsize .t +} {200 150} +test unixWm-28.8 {Tk_WmCmd procedure, "maxsize" option} {nonPortable} { + # Not portable, because some window managers let applications override + # minsize and maxsize. + + wm maxsize .t 200 150 + wm geom .t 300x200 + update + list [winfo width .t] [winfo height .t] +} {200 150} + +catch {destroy .t} +catch {destroy .icon} +toplevel .t -width 100 -height 50 +wm geom .t +0+0 +update + +test unixWm-29.1 {Tk_WmCmd procedure, "minsize" option} { + list [catch {wm minsize} msg] $msg +} {1 {wrong # args: should be "wm option window ?arg ...?"}} +test unixWm-29.2 {Tk_WmCmd procedure, "minsize" option} { + list [catch {wm minsize . a} msg] $msg +} {1 {wrong # arguments: must be "wm minsize window ?width height?"}} +test unixWm-29.3 {Tk_WmCmd procedure, "minsize" option} { + list [catch {wm minsize . a b c} msg] $msg +} {1 {wrong # arguments: must be "wm minsize window ?width height?"}} +test unixWm-29.4 {Tk_WmCmd procedure, "minsize" option} { + wm minsize .t +} {1 1} +test unixWm-29.5 {Tk_WmCmd procedure, "minsize" option} { + list [catch {wm minsize . x 100} msg] $msg +} {1 {expected integer but got "x"}} +test unixWm-29.6 {Tk_WmCmd procedure, "minsize" option} { + list [catch {wm minsize . 100 bogus} msg] $msg +} {1 {expected integer but got "bogus"}} +test unixWm-29.7 {Tk_WmCmd procedure, "minsize" option} { + wm minsize .t 200 150 + wm minsize .t +} {200 150} +test unixWm-29.8 {Tk_WmCmd procedure, "minsize" option} {nonPortable} { + # Not portable, because some window managers let applications override + # minsize and maxsize. + + wm minsize .t 150 100 + wm geom .t 50x50 + update + list [winfo width .t] [winfo height .t] +} {150 100} + +catch {destroy .t} +catch {destroy .icon} +toplevel .t -width 100 -height 50 +wm geom .t +0+0 +update + +test unixWm-30.1 {Tk_WmCmd procedure, "overrideredirect" option} { + list [catch {wm overrideredirect .t 1 2} msg] $msg +} {1 {wrong # arguments: must be "wm overrideredirect window ?boolean?"}} +test unixWm-30.2 {Tk_WmCmd procedure, "overrideredirect" option} { + list [catch {wm overrideredirect .t boo} msg] $msg +} {1 {expected boolean value but got "boo"}} +test unixWm-30.3 {Tk_WmCmd procedure, "overrideredirect" option} { + set result {} + lappend result [wm overrideredirect .t] + wm overrideredirect .t true + lappend result [wm overrideredirect .t] + wm overrideredirect .t off + lappend result [wm overrideredirect .t] +} {0 1 0} + +test unixWm-31.1 {Tk_WmCmd procedure, "positionfrom" option} { + list [catch {wm positionfrom .t 1 2} msg] $msg +} {1 {wrong # arguments: must be "wm positionfrom window ?user/program?"}} +test unixWm-31.2 {Tk_WmCmd procedure, "positionfrom" option} {unixOnly} { + set result {} + lappend result [wm positionfrom .t] + wm positionfrom .t program + update + set bit [format 0x%x [expr 0x5 & [lindex [testprop [testwrapper .t] \ + WM_NORMAL_HINTS] 0]]] + lappend result [wm positionfrom .t] $bit + wm positionfrom .t user + update + set bit [format 0x%x [expr 0x5 & [lindex [testprop [testwrapper .t] \ + WM_NORMAL_HINTS] 0]]] + lappend result [wm positionfrom .t] $bit +} {user program 0x4 user 0x1} +test unixWm-31.3 {Tk_WmCmd procedure, "positionfrom" option} { + list [catch {wm positionfrom .t none} msg] $msg +} {1 {bad argument "none": must be program or user}} + +test unixWm-32.1 {Tk_WmCmd procedure, "protocol" option} { + list [catch {wm protocol .t 1 2 3} msg] $msg +} {1 {wrong # arguments: must be "wm protocol window ?name? ?command?"}} +test unixWm-32.2 {Tk_WmCmd procedure, "protocol" option} { + wm protocol .t {foo a} {a b c} + wm protocol .t bar {test script for bar} + set result [wm protocol .t] + wm protocol .t {foo a} {} + wm protocol .t bar {} + set result +} {bar {foo a}} +test unixWm-32.3 {Tk_WmCmd procedure, "protocol" option} {unixOnly} { + set result {} + lappend result [wm protocol .t] + set x {} + foreach i [testprop [testwrapper .t] WM_PROTOCOLS] { + lappend x [winfo atomname $i] + } + lappend result $x + wm protocol .t foo {test script} + wm protocol .t bar {test script} + set x {} + foreach i [testprop [testwrapper .t] WM_PROTOCOLS] { + lappend x [winfo atomname $i] + } + lappend result [wm protocol .t] $x + wm protocol .t foo {} + wm protocol .t bar {} + set x {} + foreach i [testprop [testwrapper .t] WM_PROTOCOLS] { + lappend x [winfo atomname $i] + } + lappend result [wm protocol .t] $x +} {{} WM_DELETE_WINDOW {bar foo} {WM_DELETE_WINDOW bar foo} {} WM_DELETE_WINDOW} +test unixWm-32.4 {Tk_WmCmd procedure, "protocol" option} { + set result {} + wm protocol .t foo {a b c} + wm protocol .t bar {test script for bar} + lappend result [wm protocol .t foo] [wm protocol .t bar] + wm protocol .t foo {} + wm protocol .t bar {} + lappend result [wm protocol .t foo] [wm protocol .t bar] +} {{a b c} {test script for bar} {} {}} +test unixWm-32.5 {Tk_WmCmd procedure, "protocol" option} { + wm protocol .t foo {a b c} + wm protocol .t foo {test script} + set result [wm protocol .t foo] + wm protocol .t foo {} + set result +} {test script} + +test unixWm-33.1 {Tk_WmCmd procedure, "resizable" option} { + list [catch {wm resizable . a} msg] $msg +} {1 {wrong # arguments: must be "wm resizable window ?width height?"}} +test unixWm-33.2 {Tk_WmCmd procedure, "resizable" option} { + list [catch {wm resizable . a b c} msg] $msg +} {1 {wrong # arguments: must be "wm resizable window ?width height?"}} +test unixWm-33.3 {Tk_WmCmd procedure, "resizable" option} { + list [catch {wm resizable .foo a b c} msg] $msg +} {1 {bad window path name ".foo"}} +test unixWm-33.4 {Tk_WmCmd procedure, "resizable" option} { + list [catch {wm resizable . x 1} msg] $msg +} {1 {expected boolean value but got "x"}} +test unixWm-33.5 {Tk_WmCmd procedure, "resizable" option} { + list [catch {wm resizable . 0 gorp} msg] $msg +} {1 {expected boolean value but got "gorp"}} +test unixWm-33.6 {Tk_WmCmd procedure, "resizable" option} { + catch {destroy .t2} + toplevel .t2 -width 200 -height 100 + wm geom .t2 +0+0 + set result "" + lappend result [wm resizable .t2] + wm resizable .t2 1 0 + lappend result [wm resizable .t2] + wm resizable .t2 no off + lappend result [wm resizable .t2] + wm resizable .t2 false true + lappend result [wm resizable .t2] + destroy .t2 + set result +} {{1 1} {1 0} {0 0} {0 1}} + +test unixWm-34.1 {Tk_WmCmd procedure, "sizefrom" option} { + list [catch {wm sizefrom .t 1 2} msg] $msg +} {1 {wrong # arguments: must be "wm sizefrom window ?user|program?"}} +test unixWm-34.2 {Tk_WmCmd procedure, "sizefrom" option} {unixOnly} { + set result {} + lappend result [wm sizefrom .t] + wm sizefrom .t program + update + set bit [format 0x%x [expr 0xa & [lindex [testprop [testwrapper .t] \ + WM_NORMAL_HINTS] 0]]] + lappend result [wm sizefrom .t] $bit + wm sizefrom .t user + update + set bit [format 0x%x [expr 0xa & [lindex [testprop [testwrapper .t] \ + WM_NORMAL_HINTS] 0]]] + lappend result [wm sizefrom .t] $bit +} {{} program 0x8 user 0x2} +test unixWm-34.3 {Tk_WmCmd procedure, "sizefrom" option} { + list [catch {wm sizefrom .t none} msg] $msg +} {1 {bad argument "none": must be program or user}} + +test unixWm-35.1 {Tk_WmCmd procedure, "state" option} { + list [catch {wm state .t 1} msg] $msg +} {1 {wrong # arguments: must be "wm state window"}} +test unixWm-35.2 {Tk_WmCmd procedure, "state" option} { + set result {} + catch {destroy .t2} + toplevel .t2 -width 120 -height 300 + wm geometry .t2 +0+0 + lappend result [wm state .t2] + update + lappend result [wm state .t2] + wm withdraw .t2 + lappend result [wm state .t2] + wm iconify .t2 + lappend result [wm state .t2] + wm deiconify .t2 + lappend result [wm state .t2] + destroy .t2 + set result +} {normal normal withdrawn iconic normal} + +test unixWm-36.1 {Tk_WmCmd procedure, "title" option} { + list [catch {wm title .t 1 2} msg] $msg +} {1 {wrong # arguments: must be "wm title window ?newTitle?"}} +test unixWm-36.2 {Tk_WmCmd procedure, "title" option} {unixOnly} { + set result {} + lappend result [wm title .t] [testprop [testwrapper .t] WM_NAME] + wm title .t "Test window" + set bit [format 0x%x [expr 0xa & [lindex [testprop [testwrapper .t] \ + WM_NORMAL_HINTS] 0]]] + lappend result [wm title .t] [testprop [testwrapper .t] WM_NAME] +} {t t {Test window} {Test window}} + +test unixWm-37.1 {Tk_WmCmd procedure, "transient" option} { + list [catch {wm transient .t 1 2} msg] $msg +} {1 {wrong # arguments: must be "wm transient window ?master?"}} +test unixWm-37.2 {Tk_WmCmd procedure, "transient" option} { + list [catch {wm transient .t foo} msg] $msg +} {1 {bad window path name "foo"}} +test unixWm-37.3 {Tk_WmCmd procedure, "transient" option} {unixOnly} { + set result {} + catch {destroy .t2} + toplevel .t2 -width 120 -height 300 + wm geometry .t2 +0+0 + update + lappend result [wm transient .t2] \ + [testprop [testwrapper .t2] WM_TRANSIENT_FOR] + wm transient .t2 .t + set transient [testprop [testwrapper .t2] WM_TRANSIENT_FOR] + lappend result [wm transient .t2] [expr [testwrapper .t] - $transient] + wm transient .t2 {} + lappend result [wm transient .t2] \ + [testprop [testwrapper .t2] WM_TRANSIENT_FOR] + destroy .t2 + set result +} {{} {} .t 0 {} 0x0} +test unixWm-37.4 {Tk_WmCmd procedure, "transient" option, create master wrapper} {unixOnly} { + catch {destroy .t2} + catch {destroy .t3} + toplevel .t2 -width 120 -height 300 + wm geometry .t2 +0+0 + toplevel .t3 -width 120 -height 300 + wm geometry .t2 +0+0 + set result [list [testwrapper .t2]] + wm transient .t3 .t2 + lappend result [expr {[testwrapper .t2] == ""}] + destroy .t2 .t3 + set result +} {{} 0} + +test unixWm-38.1 {Tk_WmCmd procedure, "withdraw" option} { + list [catch {wm withdraw .t 1} msg] $msg +} {1 {wrong # arguments: must be "wm withdraw window"}} +test unixWm-38.2 {Tk_WmCmd procedure, "withdraw" option} { + catch {destroy .t2} + toplevel .t2 -width 120 -height 300 + wm geometry .t2 +0+0 + wm iconwindow .t .t2 + set result [list [catch {wm withdraw .t2} msg] $msg] + destroy .t2 + set result +} {1 {can't withdraw .t2: it is an icon for .t}} +test unixWm-38.3 {Tk_WmCmd procedure, "withdraw" option} { + set result {} + wm withdraw .t + lappend result [wm state .t] [winfo ismapped .t] + wm deiconify .t + lappend result [wm state .t] [winfo ismapped .t] +} {withdrawn 0 normal 1} + +test unixWm-39.1 {Tk_WmCmd procedure, miscellaneous} { + list [catch {wm unknown .t} msg] $msg +} {1 {unknown or ambiguous option "unknown": must be aspect, client, command, deiconify, focusmodel, frame, geometry, grid, group, iconbitmap, iconify, iconmask, iconname, iconposition, iconwindow, maxsize, minsize, overrideredirect, positionfrom, protocol, resizable, sizefrom, state, title, transient, or withdraw}} + +catch {destroy .t} +catch {destroy .icon} + +test unixWm-40.1 {Tk_SetGrid procedure, set grid dimensions before turning on grid} {nonPortable} { + catch {destroy .t} + toplevel .t + wm geometry .t 30x10+0+0 + listbox .t.l -height 20 -width 20 -setgrid 1 + pack .t.l -fill both -expand 1 + update + wm geometry .t +} {30x10+0+0} +test unixWm-40.2 {Tk_SetGrid procedure, turning on grid when dimensions already set} { + catch {destroy .t} + toplevel .t + wm geometry .t 200x100+0+0 + listbox .t.l -height 20 -width 20 + pack .t.l -fill both -expand 1 + update + .t.l configure -setgrid 1 + update + wm geometry .t +} {20x20+0+0} + +test unixWm-41.1 {ConfigureEvent procedure, internally generated size changes} { + catch {destroy .t} + toplevel .t -width 400 -height 150 + wm geometry .t +0+0 + tkwait visibility .t + set result {} + lappend result [winfo width .t] [winfo height .t] + .t configure -width 200 -height 300 + sleep 500 + lappend result [winfo width .t] [winfo height .t] +} {400 150 200 300} +test unixWm-41.2 {ConfigureEvent procedure, menubars} {unixOnly} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + wm geom .t +0+0 + update + set x [winfo rootx .t] + set y [winfo rooty .t] + frame .t.m -bd 2 -relief raised -height 20 + testmenubar window .t .t.m + update + set result {} + bind .t <Configure> { + if {"%W" == ".t"} { + lappend result "%W: %wx%h" + } + } + bind .t.m <Configure> {lappend result "%W: %wx%h"} + wm geometry .t 200x300 + update + lappend result [expr [winfo rootx .t.m] - $x] \ + [expr [winfo rooty .t.m] - $y] \ + [winfo width .t.m] [winfo height .t.m] \ + [expr [winfo rootx .t] - $x] [expr [winfo rooty .t] - $y] \ + [winfo width .t] [winfo height .t] +} {{.t.m: 200x20} {.t: 200x300} 0 0 200 20 0 20 200 300} +test unixWm-41.3 {ConfigureEvent procedure, synthesized Configure events} { + catch {destroy .t} + toplevel .t -width 400 -height 150 + wm geometry .t +0+0 + tkwait visibility .t + set result {no event} + bind .t <Configure> {set result "configured: %w %h"} + wm geometry .t +10+20 + update + set result +} {configured: 400 150} +test unixWm-41.4 {ConfigureEvent procedure, synthesized Configure events} { + catch {destroy .t} + toplevel .t -width 400 -height 150 + wm geometry .t +0+0 + tkwait visibility .t + set result {no event} + bind .t <Configure> {set result "configured: %w %h"} + wm geometry .t 130x200 + update + set result +} {configured: 130 200} + +# No tests for ReparentEvent or ComputeReparentGeometry; I can't figure +# out how to exercise these procedures reliably. + +test unixWm-42.1 {WrapperEventProc procedure, map and unmap events} { + catch {destroy .t} + toplevel .t -width 400 -height 150 + wm geometry .t +0+0 + tkwait visibility .t + set result {} + bind .t <Map> {set x "mapped"} + bind .t <Unmap> {set x "unmapped"} + set x {no event} + wm iconify .t + lappend result $x [winfo ismapped .t] + set x {no event} + wm deiconify .t + lappend result $x [winfo ismapped .t] +} {unmapped 0 mapped 1} + +test unixWm-43.1 {TopLevelReqProc procedure, embedded in same process} { + catch {destroy .t} + toplevel .t -width 200 -height 200 + wm geom .t +0+0 + frame .t.f -container 1 -bd 2 -relief raised + place .t.f -x 20 -y 10 + tkwait visibility .t.f + toplevel .t2 -use [winfo id .t.f] -width 30 -height 20 -bg blue + tkwait visibility .t2 + set result {} + .t2 configure -width 70 -height 120 + update + lappend result [winfo reqwidth .t.f] [winfo reqheight .t.f] + lappend result [winfo width .t2] [winfo height .t2] + # destroy .t2 + set result +} {70 120 70 120} +test unixWm-43.2 {TopLevelReqProc procedure, resize causes window to move} \ + {nonPortable} { + catch {destroy .t} + toplevel .t -width 200 -height 200 + wm geom .t +0+0 + update + wm geom .t -0-0 + update + set x [winfo x .t] + set y [winfo y .t] + .t configure -width 300 -height 150 + update + list [expr [winfo x .t] - $x] [expr [winfo y .t] - $y] \ + [winfo width .t] [winfo height .t] +} {-100 50 300 150} + +test unixWm-44.1 {UpdateGeometryInfo procedure, width/height computation} { + catch {destroy .t} + toplevel .t -width 100 -height 200 + wm geometry .t +30+40 + wm overrideredirect .t 1 + tkwait visibility .t + .t configure -width 180 -height 20 + update + list [winfo width .t] [winfo height .t] +} {180 20} +test unixWm-44.2 {UpdateGeometryInfo procedure, width/height computation} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + wm grid .t 5 4 10 12 + wm geometry .t +30+40 + wm overrideredirect .t 1 + tkwait visibility .t + wm geometry .t 10x2 + update + list [winfo width .t] [winfo height .t] +} {130 36} +test unixWm-44.3 {UpdateGeometryInfo procedure, width/height computation} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + wm grid .t 5 4 10 12 + wm geometry .t +30+40 + wm overrideredirect .t 1 + tkwait visibility .t + wm geometry .t 1x10 + update + list [winfo width .t] [winfo height .t] +} {40 132} +test unixWm-44.4 {UpdateGeometryInfo procedure, width/height computation} { + catch {destroy .t} + toplevel .t -width 100 -height 200 + wm geometry .t +30+40 + wm overrideredirect .t 1 + tkwait visibility .t + wm geometry .t 300x150 + update + list [winfo width .t] [winfo height .t] +} {300 150} +test unixWm-44.5 {UpdateGeometryInfo procedure, negative width} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + wm grid .t 18 7 10 12 + wm geometry .t +30+40 + wm overrideredirect .t 1 + tkwait visibility .t + wm geometry .t 5x8 + update + list [winfo width .t] [winfo height .t] +} {1 72} +test unixWm-44.6 {UpdateGeometryInfo procedure, negative height} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + wm grid .t 18 7 10 12 + wm geometry .t +30+40 + wm overrideredirect .t 1 + tkwait visibility .t + wm geometry .t 20x1 + update + list [winfo width .t] [winfo height .t] +} {100 1} +test unixWm-44.7 {UpdateGeometryInfo procedure, computing position} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + wm geometry .t +5-10 + wm overrideredirect .t 1 + tkwait visibility .t + list [winfo x .t] [winfo y .t] +} "5 [expr [winfo screenheight .t] - 70]" +test unixWm-44.8 {UpdateGeometryInfo procedure, computing position} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + wm geometry .t -30+2 + wm overrideredirect .t 1 + tkwait visibility .t + list [winfo x .t] [winfo y .t] +} "[expr [winfo screenwidth .t] - 110] 2" +test unixWm-44.9 {UpdateGeometryInfo procedure, updating fixed dimensions} {unixOnly} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + wm resizable .t 0 0 + wm geometry .t +0+0 + tkwait visibility .t + .t configure -width 180 -height 20 + update + set property [testprop [testwrapper .t] WM_NORMAL_HINTS] + list [expr [lindex $property 5]] [expr [lindex $property 6]] \ + [expr [lindex $property 7]] [expr [lindex $property 8]] +} {180 20 180 20} +test unixWm-44.10 {UpdateGeometryInfo procedure, menubar changing} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + wm resizable .t 0 0 + wm geometry .t +0+0 + tkwait visibility .t + .t configure -width 180 -height 50 + frame .t.m -bd 2 -relief raised -width 100 -height 50 + testmenubar window .t .t.m + update + .t configure -height 70 + .t.m configure -height 30 + list [update] [destroy .t] +} {{} {}} + +test unixWm-45.1 {UpdateSizeHints procedure, grid information} {unixOnly} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + wm grid .t 6 10 10 5 + wm minsize .t 2 4 + wm maxsize .t 30 40 + wm geometry .t +0+0 + tkwait visibility .t + set property [testprop [testwrapper .t] WM_NORMAL_HINTS] + list [expr [lindex $property 5]] [expr [lindex $property 6]] \ + [expr [lindex $property 7]] [expr [lindex $property 8]] \ + [expr [lindex $property 9]] [expr [lindex $property 10]] +} {40 30 320 210 10 5} +test unixWm-45.2 {UpdateSizeHints procedure} {unixOnly} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + wm minsize .t 30 40 + wm maxsize .t 200 500 + wm geometry .t +0+0 + tkwait visibility .t + set property [testprop [testwrapper .t] WM_NORMAL_HINTS] + list [expr [lindex $property 5]] [expr [lindex $property 6]] \ + [expr [lindex $property 7]] [expr [lindex $property 8]] \ + [expr [lindex $property 9]] [expr [lindex $property 10]] +} {30 40 200 500 1 1} +test unixWm-45.3 {UpdateSizeHints procedure, grid with menu} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + frame .t.menu -height 23 -width 50 + testmenubar window .t .t.menu + wm grid .t 6 10 10 5 + wm minsize .t 2 4 + wm maxsize .t 30 40 + wm geometry .t +0+0 + tkwait visibility .t + set property [testprop [testwrapper .t] WM_NORMAL_HINTS] + list [winfo height .t] \ + [expr [lindex $property 5]] [expr [lindex $property 6]] \ + [expr [lindex $property 7]] [expr [lindex $property 8]] \ + [expr [lindex $property 9]] [expr [lindex $property 10]] +} {60 40 53 320 233 10 5} +test unixWm-45.4 {UpdateSizeHints procedure, not resizable with menu} { + catch {destroy .t} + toplevel .t -width 80 -height 60 + frame .t.menu -height 23 -width 50 + testmenubar window .t .t.menu + wm resizable .t 0 0 + wm geometry .t +0+0 + tkwait visibility .t + set property [testprop [testwrapper .t] WM_NORMAL_HINTS] + list [winfo height .t] \ + [expr [lindex $property 5]] [expr [lindex $property 6]] \ + [expr [lindex $property 7]] [expr [lindex $property 8]] \ + [expr [lindex $property 9]] [expr [lindex $property 10]] +} {60 80 83 80 83 1 1} + +# I don't know how to test WaitForConfigureNotify. + +test unixWm-46.1 {WaitForEvent procedure, use of modal timeout} { + catch {destroy .t} + toplevel .t -width 200 -height 200 + wm geom .t +0+0 + update + wm iconify .t + set x no + after 0 {set x yes} + wm deiconify .t + set result $x + update + list $result $x +} {no yes} + +test unixWm-47.1 {WaitRestrictProc procedure} { + catch {destroy .t} + toplevel .t -width 300 -height 200 + frame .t.f -bd 2 -relief raised + place .t.f -x 20 -y 30 -width 100 -height 20 + wm geometry .t +0+0 + tkwait visibility .t + set result {} + bind .t.f <Configure> {lappend result {configure on .t.f}} + bind .t <Map> {lappend result {map on .t}} + bind .t <Unmap> {lappend result {unmap on .t}; bind .t <Unmap> {}} + bind .t <Button> {lappend result {button %b on .t}} + event generate .t.f <Configure> -when tail + event generate .t <Configure> -when tail + event generate .t <Button> -button 3 -when tail + event generate .t <Map> -when tail + lappend result iconify + wm iconify .t + lappend result done + update + set result +} {iconify {unmap on .t} done {configure on .t.f} {button 3 on .t} {map on .t}} + +# I don't know how to test WaitTimeoutProc, WaitForMapNotify, or UpdateHints. + +catch {destroy .t} +toplevel .t -width 300 -height 200 +wm geometry .t +0+0 +tkwait visibility .t + +test unixWm-48.1 {ParseGeometry procedure} { + wm geometry .t =100x120 + update + list [winfo width .t] [winfo height .t] +} {100 120} +test unixWm-48.2 {ParseGeometry procedure} { + list [catch {wm geometry .t =10zx120} msg] $msg +} {1 {bad geometry specifier "=10zx120"}} +test unixWm-48.3 {ParseGeometry procedure} { + list [catch {wm geometry .t x120} msg] $msg +} {1 {bad geometry specifier "x120"}} +test unixWm-48.4 {ParseGeometry procedure} { + list [catch {wm geometry .t =100x120a} msg] $msg +} {1 {bad geometry specifier "=100x120a"}} +test unixWm-48.5 {ParseGeometry procedure} { + list [catch {wm geometry .t z} msg] $msg +} {1 {bad geometry specifier "z"}} +test unixWm-48.6 {ParseGeometry procedure} { + list [catch {wm geometry .t +20&} msg] $msg +} {1 {bad geometry specifier "+20&"}} +test unixWm-48.7 {ParseGeometry procedure} { + list [catch {wm geometry .t +-} msg] $msg +} {1 {bad geometry specifier "+-"}} +test unixWm-48.8 {ParseGeometry procedure} { + list [catch {wm geometry .t +20a} msg] $msg +} {1 {bad geometry specifier "+20a"}} +test unixWm-48.9 {ParseGeometry procedure} { + list [catch {wm geometry .t +20-} msg] $msg +} {1 {bad geometry specifier "+20-"}} +test unixWm-48.10 {ParseGeometry procedure} { + list [catch {wm geometry .t +20+10z} msg] $msg +} {1 {bad geometry specifier "+20+10z"}} +test unixWm-48.11 {ParseGeometry procedure} { + catch {wm geometry .t +-10+20} +} {0} +test unixWm-48.12 {ParseGeometry procedure} { + catch {wm geometry .t +30+-10} +} {0} +test unixWm-48.13 {ParseGeometry procedure, resize causes window to move} { + catch {destroy .t} + toplevel .t -width 200 -height 200 + wm geom .t +0+0 + update + wm geom .t -0-0 + update + set x [winfo x .t] + set y [winfo y .t] + wm geometry .t 150x300 + update + list [expr [winfo x .t] - $x] [expr [winfo y .t] - $y] \ + [winfo width .t] [winfo height .t] +} {50 -100 150 300} + +test unixWm-49.1 {Tk_GetRootCoords procedure} { + catch {destroy .t} + toplevel .t -width 300 -height 200 + frame .t.f -width 150 -height 100 -bd 2 -relief raised + place .t.f -x 150 -y 120 + frame .t.f.f -width 20 -height 20 -bd 2 -relief raised + place .t.f.f -x 10 -y 20 + wm overrideredirect .t 1 + wm geometry .t +40+50 + tkwait visibility .t + list [winfo rootx .t.f.f] [winfo rooty .t.f.f] +} {202 192} +test unixWm-49.2 {Tk_GetRootCoords procedure, menubars} {unixOnly} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + wm geom .t +0+0 + update + set x [winfo rootx .t] + set y [winfo rooty .t] + frame .t.m -bd 2 -relief raised -width 100 -height 30 + frame .t.m.f -width 20 -height 10 -bd 2 -relief raised + place .t.m.f -x 50 -y 5 + frame .t.f -width 20 -height 30 -bd 2 -relief raised + place .t.f -x 10 -y 30 + testmenubar window .t .t.m + update + list [expr [winfo rootx .t.m.f] - $x] [expr [winfo rooty .t.m.f] - $y] \ + [expr [winfo rootx .t.f] - $x] [expr [winfo rooty .t.f] - $y] +} {52 7 12 62} + +foreach w [winfo children .] { + catch {destroy $w} +} +wm iconify . +test unixWm-50.1 {Tk_CoordsToWindow procedure, finding a toplevel, x-coords} { + eval destroy [winfo children .] + toplevel .t -width 300 -height 400 -bg green + wm geom .t +40+0 + tkwait visibility .t + toplevel .t2 -width 100 -height 80 -bg red + wm geom .t2 +140+200 + tkwait visibility .t2 + raise .t2 + set x [winfo rootx .t] + set y [winfo rooty .t] + list [winfo containing [expr $x - 30] [expr $y + 250]] \ + [winfo containing [expr $x - 1] [expr $y + 250]] \ + [winfo containing $x [expr $y + 250]] \ + [winfo containing [expr $x + 99] [expr $y + 250]] \ + [winfo containing [expr $x + 100] [expr $y + 250]] \ + [winfo containing [expr $x + 199] [expr $y + 250]] \ + [winfo containing [expr $x + 200] [expr $y + 250]] \ + [winfo containing [expr $x + 220] [expr $y + 250]] +} {{} {} .t {} .t2 .t2 {} .t} +test unixWm-50.2 {Tk_CoordsToWindow procedure, finding a toplevel, y-coords and overrideredirect} { + eval destroy [winfo children .] + toplevel .t -width 300 -height 400 -bg yellow + wm geom .t +0+50 + tkwait visibility .t + toplevel .t2 -width 100 -height 80 -bg blue + wm overrideredirect .t2 1 + wm geom .t2 +100+200 + tkwait visibility .t2 + raise .t2 + set x [winfo rootx .t] + set y [winfo rooty .t] + set y2 [winfo rooty .t2] + list [winfo containing [expr $x +150] 10] \ + [winfo containing [expr $x +150] [expr $y - 1]] \ + [winfo containing [expr $x +150] $y] \ + [winfo containing [expr $x +150] [expr $y2 - 1]] \ + [winfo containing [expr $x +150] $y2] \ + [winfo containing [expr $x +150] [expr $y2 + 79]] \ + [winfo containing [expr $x +150] [expr $y2 + 80]] \ + [winfo containing [expr $x +150] [expr $y + 450]] +} {{} {} .t .t .t2 .t2 .t {}} +test unixWm-50.3 {Tk_CoordsToWindow procedure, finding a toplevel with embedding} { + eval destroy [winfo children .] + toplevel .t -width 300 -height 400 -bg blue + wm geom .t +0+50 + frame .t.f -container 1 + place .t.f -x 150 -y 50 + tkwait visibility .t.f + setupbg + dobg " + wm withdraw . + toplevel .x -width 100 -height 80 -use [winfo id .t.f] -bg yellow + tkwait visibility .x" + set result [dobg { + set x [winfo rootx .x] + set y [winfo rooty .x] + list [winfo containing [expr $x - 1] [expr $y + 50]] \ + [winfo containing $x [expr $y +50]] + }] + set x [winfo rootx .t] + set y [winfo rooty .t] + lappend result [winfo containing [expr $x + 200] [expr $y + 49]] \ + [winfo containing [expr $x + 200] [expr $y +50]] +} {{} .x .t .t.f} +cleanupbg +test unixWm-50.4 {Tk_CoordsToWindow procedure, window in other application} { + catch {destroy .t} + catch {interp delete slave} + toplevel .t -width 200 -height 200 -bg green + wm geometry .t +0+0 + tkwait visibility .t + interp create slave + load {} tk slave + slave eval {wm geometry . 200x200+0+0; tkwait visibility .} + set result [list [winfo containing 100 100] \ + [slave eval {winfo containing 100 100}]] + interp delete slave + set result +} {{} .} +test unixWm-50.5 {Tk_CoordsToWindow procedure, handling menubars} {unixOnly} { + eval destroy [winfo children .] + toplevel .t -width 300 -height 400 -bd 2 -relief raised + frame .t.f -width 150 -height 120 -bg green + place .t.f -x 10 -y 150 + wm geom .t +0+50 + frame .t.menu -width 100 -height 30 -bd 2 -relief raised + frame .t.menu.f -width 40 -height 20 -bg purple + place .t.menu.f -x 30 -y 10 + testmenubar window .t .t.menu + tkwait visibility .t.menu + update + set x [winfo rootx .t] + set y [winfo rooty .t] + list [winfo containing $x [expr $y - 31]] \ + [winfo containing $x [expr $y - 30]] \ + [winfo containing [expr $x + 50] [expr $y - 19]] \ + [winfo containing [expr $x + 50] [expr $y - 18]] \ + [winfo containing [expr $x + 50] $y] \ + [winfo containing [expr $x + 11] [expr $y + 152]] \ + [winfo containing [expr $x + 12] [expr $y + 152]] +} {{} .t.menu .t.menu .t.menu.f .t .t .t.f} +test unixWm-50.6 {Tk_CoordsToWindow procedure, embedding within one app.} { + eval destroy [winfo children .] + toplevel .t -width 300 -height 400 -bg orange + wm geom .t +0+50 + frame .t.f -container 1 + place .t.f -x 150 -y 50 + tkwait visibility .t.f + toplevel .t2 -width 100 -height 80 -bg green -use [winfo id .t.f] + tkwait visibility .t2 + update + set x [winfo rootx .t] + set y [winfo rooty .t] + list [winfo containing [expr $x +149] [expr $y + 80]] \ + [winfo containing [expr $x +150] [expr $y +80]] \ + [winfo containing [expr $x +249] [expr $y +80]] \ + [winfo containing [expr $x +250] [expr $y +80]] +} {.t .t2 .t2 .t} +test unixWm-50.7 {Tk_CoordsToWindow procedure, more basics} { + catch {destroy .t} + toplevel .t -width 300 -height 400 -bg green + wm geom .t +0+0 + frame .t.f -width 100 -height 200 -bd 2 -relief raised + place .t.f -x 100 -y 100 + frame .t.f.f -width 100 -height 200 -bd 2 -relief raised + place .t.f.f -x 0 -y 100 + tkwait visibility .t.f.f + set x [expr [winfo rootx .t] + 150] + set y [winfo rooty .t] + list [winfo containing $x [expr $y + 50]] \ + [winfo containing $x [expr $y + 150]] \ + [winfo containing $x [expr $y + 250]] \ + [winfo containing $x [expr $y + 350]] \ + [winfo containing $x [expr $y + 450]] +} {.t .t.f .t.f.f .t {}} +test unixWm-50.8 {Tk_CoordsToWindow procedure, more basics} { + catch {destroy .t} + toplevel .t -width 400 -height 300 -bg green + wm geom .t +0+0 + frame .t.f -width 200 -height 100 -bd 2 -relief raised + place .t.f -x 100 -y 100 + frame .t.f.f -width 200 -height 100 -bd 2 -relief raised + place .t.f.f -x 100 -y 0 + update + set x [winfo rooty .t] + set y [expr [winfo rooty .t] + 150] + list [winfo containing [expr $x + 50] $y] \ + [winfo containing [expr $x + 150] $y] \ + [winfo containing [expr $x + 250] $y] \ + [winfo containing [expr $x + 350] $y] \ + [winfo containing [expr $x + 450] $y] +} {.t .t.f .t.f.f .t {}} +test unixWm-50.9 {Tk_CoordsToWindow procedure, unmapped windows} { + catch {destroy .t} + catch {destroy .t2} + sleep 500 ;# Give window manager time to catch up. + toplevel .t -width 200 -height 200 -bg green + wm geometry .t +0+0 + tkwait visibility .t + toplevel .t2 -width 200 -height 200 -bg red + wm geometry .t2 +0+0 + tkwait visibility .t2 + set result [list [winfo containing 100 100]] + wm iconify .t2 + lappend result [winfo containing 100 100] +} {.t2 .t} +test unixWm-50.10 {Tk_CoordsToWindow procedure, unmapped windows} { + catch {destroy .t} + toplevel .t -width 200 -height 200 -bg green + wm geometry .t +0+0 + frame .t.f -width 150 -height 150 -bd 2 -relief raised + place .t.f -x 25 -y 25 + tkwait visibility .t.f + set result [list [winfo containing 100 100]] + place forget .t.f + update + lappend result [winfo containing 100 100] +} {.t.f .t} +eval destroy [winfo children .] +wm deiconify . + +# No tests for UpdateVRootGeometry, Tk_GetVRootGeometry, +# Tk_MoveToplevelWindow, UpdateWmProtocols, or TkWmProtocolEventProc. + +test unixWm-51.1 {TkWmRestackToplevel procedure, basic tests} {nonPortable} { + makeToplevels + update + raise .raise1 + winfo containing [winfo rootx .raise1] [winfo rooty .raise1] +} .raise1 +test unixWm-51.2 {TkWmRestackToplevel procedure, basic tests} {nonPortable} { + makeToplevels + update + raise .raise2 + winfo containing [winfo rootx .raise1] [winfo rooty .raise1] +} .raise2 +test unixWm-51.3 {TkWmRestackToplevel procedure, basic tests} {nonPortable} { + makeToplevels + update + raise .raise3 + raise .raise2 + raise .raise1 .raise3 + set result [winfo containing [winfo rootx .raise1] \ + [winfo rooty .raise1]] + destroy .raise2 + sleep 500 + list $result [winfo containing [winfo rootx .raise1] \ + [winfo rooty .raise1]] +} {.raise2 .raise1} +test unixWm-51.4 {TkWmRestackToplevel procedure, basic tests} {nonPortable} { + makeToplevels + raise .raise2 + raise .raise1 + lower .raise3 .raise1 + set result [winfo containing 100 100] + destroy .raise1 + sleep 500 + lappend result [winfo containing 100 100] +} {.raise1 .raise3} +test unixWm-51.5 {TkWmRestackToplevel procedure, basic tests} {nonPortable} { + makeToplevels + update + raise .raise2 + raise .raise1 + raise .raise3 + frame .raise1.f1 + frame .raise1.f1.f2 + lower .raise3 .raise1.f1.f2 + set result [winfo containing [winfo rootx .raise1] \ + [winfo rooty .raise1]] + destroy .raise1 + sleep 500 + list $result [winfo containing [winfo rootx .raise2] \ + [winfo rooty .raise2]] +} {.raise1 .raise3} +foreach w [winfo children .] { + catch {destroy $w} +} +test unixWm-51.6 {TkWmRestackToplevel procedure, window to be stacked isn't mapped} { + catch {destroy .t} + toplevel .t -width 200 -height 200 -bg green + wm geometry .t +0+0 + tkwait visibility .t + catch {destroy .t2} + toplevel .t2 -width 200 -height 200 -bg red + wm geometry .t2 +0+0 + winfo containing 100 100 +} {.t} +test unixWm-51.7 {TkWmRestackToplevel procedure, other window isn't mapped} { + foreach w {.t .t2 .t3} { + catch {destroy $w} + toplevel $w -width 200 -height 200 -bg green + wm geometry $w +0+0 + } + raise .t .t2 + update + set result [list [winfo containing 100 100]] + lower .t3 + lappend result [winfo containing 100 100] +} {.t3 .t} +test unixWm-51.8 {TkWmRestackToplevel procedure, overrideredirect windows} { + catch {destroy .t} + toplevel .t -width 200 -height 200 -bg green + wm overrideredirect .t 1 + wm geometry .t +0+0 + tkwait visibility .t + catch {destroy .t2} + toplevel .t2 -width 200 -height 200 -bg red + wm overrideredirect .t2 1 + wm geometry .t2 +0+0 + tkwait visibility .t2 + + # Need to use vrootx and vrooty to make tests work correctly with + # virtual root window measures managers: overrideredirect windows + # come up at (0,0) in display coordinates, not virtual root + # coordinates. + + set x [expr 100-[winfo vrootx .]] + set y [expr 100-[winfo vrooty .]] + set result [list [winfo containing $x $y]] + raise .t + lappend result [winfo containing $x $y] + raise .t2 + lappend result [winfo containing $x $y] +} {.t2 .t .t2} +test unixWm-51.9 {TkWmRestackToplevel procedure, other window overrideredirect} { + foreach w {.t .t2 .t3} { + catch {destroy $w} + toplevel $w -width 200 -height 200 -bg green + wm overrideredirect $w 1 + wm geometry $w +0+0 + tkwait visibility $w + } + lower .t3 .t2 + update + + # Need to use vrootx and vrooty to make tests work correctly with + # virtual root window measures managers: overrideredirect windows + # come up at (0,0) in display coordinates, not virtual root + # coordinates. + + set x [expr 100-[winfo vrootx .]] + set y [expr 100-[winfo vrooty .]] + set result [list [winfo containing $x $y]] + lower .t2 + lappend result [winfo containing $x $y] +} {.t2 .t3} +test unixWm-51.10 {TkWmRestackToplevel procedure, don't move window that's already in the right place} { + makeToplevels + raise .raise1 + set time [lindex [time {raise .raise1}] 0] + expr {$time < 2000000} +} 1 +test unixWm-51.11 {TkWmRestackToplevel procedure, don't move window that's already in the right place} { + makeToplevels + set time [lindex [time {lower .raise1}] 0] + expr {$time < 2000000} +} 1 +test unixWm-51.12 {TkWmRestackToplevel procedure, don't move window that's already in the right place} { + makeToplevels + set time [lindex [time {raise .raise3 .raise2}] 0] + expr {$time < 2000000} +} 1 +test unixWm-51.13 {TkWmRestackToplevel procedure, don't move window that's already in the right place} { + makeToplevels + set time [lindex [time {lower .raise1 .raise2}] 0] + expr {$time < 2000000} +} 1 + +test unixWm-52.1 {TkWmAddToColormapWindows procedure} { + catch {destroy .t} + toplevel .t -width 200 -height 200 -colormap new -relief raised -bd 2 + wm geom .t +0+0 + update + wm colormap .t +} {} +test unixWm-52.2 {TkWmAddToColormapWindows procedure} { + catch {destroy .t} + toplevel .t -colormap new -relief raised -bd 2 + wm geom .t +0+0 + frame .t.f -width 100 -height 100 -colormap new -relief sunken -bd 2 + pack .t.f + update + wm colormap .t +} {.t.f .t} +test unixWm-52.3 {TkWmAddToColormapWindows procedure} { + catch {destroy .t} + toplevel .t -colormap new + wm geom .t +0+0 + frame .t.f -width 100 -height 100 -colormap new -relief sunken -bd 2 + pack .t.f + frame .t.f2 -width 100 -height 100 -colormap new -relief sunken -bd 2 + pack .t.f2 + update + wm colormap .t +} {.t.f .t.f2 .t} +test unixWm-52.4 {TkWmAddToColormapWindows procedure} { + catch {destroy .t} + toplevel .t -colormap new + wm geom .t +0+0 + frame .t.f -width 100 -height 100 -colormap new -relief sunken -bd 2 + pack .t.f + update + wm colormapwindows .t .t.f + frame .t.f2 -width 100 -height 100 -colormap new -relief sunken -bd 2 + pack .t.f2 + update + wm colormapwindows .t +} {.t.f} + +test unixWm-53.1 {TkWmRemoveFromColormapWindows procedure} { + catch {destroy .t} + toplevel .t -colormap new + wm geom .t +0+0 + frame .t.f -width 100 -height 100 -colormap new -relief sunken -bd 2 + pack .t.f + frame .t.f2 -width 100 -height 100 -colormap new -relief sunken -bd 2 + pack .t.f2 + update + destroy .t.f2 + wm colormap .t +} {.t.f .t} +test unixWm-53.2 {TkWmRemoveFromColormapWindows procedure} { + catch {destroy .t} + toplevel .t -colormap new + wm geom .t +0+0 + frame .t.f -width 100 -height 100 -colormap new -relief sunken -bd 2 + pack .t.f + frame .t.f2 -width 100 -height 100 -colormap new -relief sunken -bd 2 + pack .t.f2 + update + wm colormapwindows .t .t.f2 + destroy .t.f2 + wm colormap .t +} {} + +test unixWm-54.1 {TkpMakeMenuWindow procedure, setting save_under} { + catch {destroy .t} + catch {destroy .m} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + bind .t <Expose> {set x exposed} + wm geom .t +0+0 + update + menu .m + .m add command -label First + .m add command -label Second + .m add command -label Third + .m post 30 30 + update + set x {no event} + destroy .m + set x +} {no event} +test unixWm-54.2 {TkpMakeMenuWindow procedure, setting override_redirect} { + catch {destroy .m} + menu .m + .m add command -label First + .m add command -label Second + .m add command -label Third + .m post 30 30 + update + set result [wm overrideredirect .m] + destroy .m + set result +} {1} + +# No tests for TkGetPointerCoords, CreateWrapper, or GetMaxSize. + +test unixWm-55.1 {TkUnixSetMenubar procedure} {unixOnly} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + wm geom .t +0+0 + update + frame .t.f -width 400 -height 30 -bd 2 -relief raised -bg green + testmenubar window .t .t.f + update + list [winfo ismapped .t.f] [winfo geometry .t.f] \ + [expr [winfo rootx .t] - [winfo rootx .t.f]] \ + [expr [winfo rooty .t] - [winfo rooty .t.f]] +} {1 300x30+0+0 0 30} +test unixWm-55.2 {TkUnixSetMenubar procedure, removing menubar} {unixOnly} { + catch {destroy .t} + catch {destroy .f} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + wm geom .t +0+0 + update + set x [winfo rootx .t] + set y [winfo rooty .t] + frame .f -width 400 -height 30 -bd 2 -relief raised -bg green + testmenubar window .t .f + update + testmenubar window .t {} + update + list [winfo ismapped .f] [winfo geometry .f] \ + [expr [winfo rootx .t] - $x] \ + [expr [winfo rooty .t] - $y] \ + [expr [winfo rootx .] - [winfo rootx .f]] \ + [expr [winfo rooty .] - [winfo rooty .f]] +} {0 300x30+0+0 0 0 0 0} +test unixWm-55.3 {TkUnixSetMenubar procedure, removing geometry manager} {unixOnly} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + wm geom .t +0+0 + update + set x [winfo rootx .t] + set y [winfo rooty .t] + frame .t.f -width 400 -height 30 -bd 2 -relief raised -bg green + testmenubar window .t .t.f + update + testmenubar window .t {} + update + set result "[expr [winfo rootx .t] - $x] [expr [winfo rooty .t] - $y]" + .t.f configure -height 100 + update + lappend result [expr [winfo rootx .t] - $x] [expr [winfo rooty .t] - $y] +} {0 0 0 0} +test unixWm-55.4 {TkUnixSetMenubar procedure, toplevel not yet created} {unixOnly} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + frame .t.f -width 400 -height 30 -bd 2 -relief raised -bg green + testmenubar window .t .t.f + wm geom .t +0+0 + update + list [winfo ismapped .t.f] [winfo geometry .t.f] \ + [expr [winfo rootx .t] - [winfo rootx .t.f]] \ + [expr [winfo rooty .t] - [winfo rooty .t.f]] +} {1 300x30+0+0 0 30} +test unixWm-55.5 {TkUnixSetMenubar procedure, changing menubar} {unixOnly} { + catch {destroy .t} + catch {destroy .f} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + frame .t.f -width 400 -height 30 -bd 2 -relief raised -bg green + wm geom .t +0+0 + update + set y [winfo rooty .t] + frame .f -width 400 -height 50 -bd 2 -relief raised -bg green + testmenubar window .t .t.f + update + set result {} + lappend result [winfo ismapped .f] [winfo ismapped .t.f] + lappend result [expr [winfo rooty .t.f] - $y] + testmenubar window .t .f + update + lappend result [winfo ismapped .f] [winfo ismapped .t.f] + lappend result [expr [winfo rooty .f] - $y] +} {0 1 0 1 0 0} +test unixWm-55.6 {TkUnixSetMenubar procedure, changing menubar to self} {unixOnly} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + frame .t.f -width 400 -height 30 -bd 2 -relief raised -bg green + testmenubar window .t .t.f + wm geom .t +0+0 + update + testmenubar window .t .t.f + update + list [winfo ismapped .t.f] [winfo geometry .t.f] \ + [expr [winfo rootx .t] - [winfo rootx .t.f]] \ + [expr [winfo rooty .t] - [winfo rooty .t.f]] +} {1 300x30+0+0 0 30} +test unixWm-55.7 {TkUnixSetMenubar procedure, unsetting event handler} {unixOnly} { + catch {destroy .t} + catch {destroy .f} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + frame .t.f -width 400 -height 30 -bd 2 -relief raised -bg green + frame .f -width 400 -height 40 -bd 2 -relief raised -bg blue + wm geom .t +0+0 + update + set y [winfo rooty .t] + testmenubar window .t .t.f + update + set result [expr [winfo rooty .t] - $y] + testmenubar window .t .f + update + lappend result [expr [winfo rooty .t] - $y] + destroy .t.f + update + lappend result [expr [winfo rooty .t] - $y] +} {30 40 40} + +test unixWm-56.1 {MenubarDestroyProc procedure} {unixOnly} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + wm geom .t +0+0 + update + set y [winfo rooty .t] + frame .t.f -width 400 -height 30 -bd 2 -relief raised -bg green + testmenubar window .t .t.f + update + set result [expr [winfo rooty .t] - $y] + destroy .t.f + update + lappend result [expr [winfo rooty .t] - $y] +} {30 0} + +test unixWm-57.1 {MenubarReqProc procedure} {unixOnly} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + wm geom .t +0+0 + update + set x [winfo rootx .t] + set y [winfo rooty .t] + frame .t.f -width 400 -height 10 -bd 2 -relief raised -bg green + testmenubar window .t .t.f + update + set result "[expr [winfo rootx .t] - $x] [expr [winfo rooty .t] - $y]" + .t.f configure -height 100 + update + lappend result [expr [winfo rootx .t] - $x] [expr [winfo rooty .t] - $y] +} {0 10 0 100} +test unixWm-57.2 {MenubarReqProc procedure} {unixOnly} { + catch {destroy .t} + toplevel .t -width 300 -height 200 -bd 2 -relief raised + wm geom .t +0+0 + update + set x [winfo rootx .t] + set y [winfo rooty .t] + frame .t.f -width 400 -height 20 -bd 2 -relief raised -bg green + testmenubar window .t .t.f + update + set result "[expr [winfo rootx .t] - $x] [expr [winfo rooty .t] - $y]" + .t.f configure -height 0 + update + lappend result [expr [winfo rootx .t] - $x] [expr [winfo rooty .t] - $y] +} {0 20 0 1} + +# Test exit processing and cleanup: + +test unixWm-58.1 {exit processing} { + catch {removeFile script} + set fd [open script w] + puts $fd { + update + exit + } + close $fd + if {[catch {exec $tktest script -geometry 10x10+0+0} msg]} { + set error 1 + } else { + set error 0 + } + list $error $msg +} {0 {}} +test unixWm-58.2 {exit processing} { + catch {removeFile script} + set fd [open script w] + puts $fd { + interp create x + x eval {set argc 2} + x eval {set argv "-geometry 10x10+0+0"} + x eval {load {} Tk} + update + exit + } + close $fd + if {[catch {exec $tktest script -geometry 10x10+0+0} msg]} { + set error 1 + } else { + set error 0 + } + list $error $msg +} {0 {}} +test unixWm-58.3 {exit processing} { + catch {removeFile script} + set fd [open script w] + puts $fd { + interp create x + x eval {set argc 2} + x eval {set argv "-geometry 10x10+0+0"} + x eval {load {} Tk} + x eval { + button .b -text hello + bind .b <Destroy> foo + } + x alias foo destroy_x + proc destroy_x {} {interp delete x} + update + exit + } + close $fd + if {[catch {exec $tktest script -geometry 10x10+0+0} msg]} { + set error 1 + } else { + set error 0 + } + list $error $msg +} {0 {}} + + +catch {destroy .t} +concat {} diff --git a/tests/util.test b/tests/util.test new file mode 100644 index 0000000..3b41e49 --- /dev/null +++ b/tests/util.test @@ -0,0 +1,70 @@ +# This file is a Tcl script to test out the procedures in the file +# tkUtil.c. It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) util.test 1.4 96/02/16 10:55:50 + +if {[string compare test [info procs test]] == 1} then \ + {source defs} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +listbox .l -width 20 -height 5 -relief sunken -bd 2 +pack .l +.l insert 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 +update +test util-1.1 {Tk_GetScrollInfo procedure} { + list [catch {.l yview moveto a b} msg] $msg +} {1 {wrong # args: should be ".l yview moveto fraction"}} +test util-1.2 {Tk_GetScrollInfo procedure} { + list [catch {.l yview moveto xyz} msg] $msg +} {1 {expected floating-point number but got "xyz"}} +test util-1.3 {Tk_GetScrollInfo procedure} { + .l yview 0 + .l yview moveto .5 + .l yview +} {0.5 0.75} +test util-1.4 {Tk_GetScrollInfo procedure} { + list [catch {.l yview scroll a} msg] $msg +} {1 {wrong # args: should be ".l yview scroll number units|pages"}} +test util-1.5 {Tk_GetScrollInfo procedure} { + list [catch {.l yview scroll a b c} msg] $msg +} {1 {wrong # args: should be ".l yview scroll number units|pages"}} +test util-1.6 {Tk_GetScrollInfo procedure} { + list [catch {.l yview scroll xyz units} msg] $msg +} {1 {expected integer but got "xyz"}} +test util-1.7 {Tk_GetScrollInfo procedure} { + .l yview 0 + .l yview scroll 2 pages + .l nearest 0 +} {6} +test util-1.8 {Tk_GetScrollInfo procedure} { + .l yview 15 + .l yview scroll -2 pages + .l nearest 0 +} {9} +test util-1.9 {Tk_GetScrollInfo procedure} { + .l yview 0 + .l yview scroll 2 units + .l nearest 0 +} {2} +test util-1.10 {Tk_GetScrollInfo procedure} { + .l yview 15 + .l yview scroll -2 units + .l nearest 0 +} {13} +test util-1.11 {Tk_GetScrollInfo procedure} { + list [catch {.l yview scroll 3 zips} msg] $msg +} {1 {bad argument "zips": must be units or pages}} +test util-1.12 {Tk_GetScrollInfo procedure} { + list [catch {.l yview dropdead 3 times} msg] $msg +} {1 {unknown option "dropdead": must be moveto or scroll}} diff --git a/tests/visual b/tests/visual new file mode 100644 index 0000000..90e8558 --- /dev/null +++ b/tests/visual @@ -0,0 +1,81 @@ +#!/usr/local/bin/wish -f +# +# This script displays provides visual tests for many of Tk's features. +# Each test displays a window with various information in it, along +# with instructions about how the window should appear. You can look +# at the window to make sure it appears as expected. Individual tests +# are kept in separate ".tcl" files in this directory. +# +# SCCS: @(#) visual 1.5 97/06/13 16:37:29 + +set auto_path ". $auto_path" +wm title . "Visual Tests for Tk" + +#------------------------------------------------------- +# The code below create the main window, consisting of a +# menu bar and a message explaining the basic operation +# of the program. +#------------------------------------------------------- + +frame .menu -relief raised -borderwidth 1 +message .msg -font {Times 18} -relief raised -width 4i \ + -borderwidth 1 -text "This application provides a collection of visual tests for the Tk toolkit. Each menu entry invokes a test, which displays information on the screen. You can then verify visually that the information is being displayed in the correct way. The tests under the \"Postscript\" menu exercise the Postscript-generation capabilities of canvas widgets." + +pack .menu -side top -fill x +pack .msg -side bottom -expand yes -fill both + +#------------------------------------------------------- +# The code below creates all the menus, which invoke procedures +# to create particular demonstrations of various widgets. +#------------------------------------------------------- + +menubutton .menu.file -text "File" -menu .menu.file.m +menu .menu.file.m +.menu.file.m add command -label "Quit" -command exit + +menubutton .menu.group1 -text "Group 1" -menu .menu.group1.m +menu .menu.group1.m +.menu.group1.m add command -label "Canvas arcs" -command {source arc.tcl} +.menu.group1.m add command -label "Beveled borders in text widgets" \ + -command {source bevel.tcl} +.menu.group1.m add command -label "Colormap management" \ + -command {source cmap.tcl} +.menu.group1.m add command -label "Label/button geometry" \ + -command {source butGeom.tcl} +.menu.group1.m add command -label "Label/button colors" \ + -command {source butGeom2.tcl} + +menubutton .menu.ps -text "Canvas Postscript" -menu .menu.ps.m +menu .menu.ps.m +.menu.ps.m add command -label "Rectangles and other graphics" \ + -command {source canvPsGrph.tcl} +.menu.ps.m add command -label "Text" \ + -command {source canvPsText.tcl} +.menu.ps.m add command -label "Bitmaps" \ + -command {source canvPsBmap.tcl} +.menu.ps.m add command -label "Arcs" \ + -command {source canvPsArc.tcl} + +pack .menu.file .menu.group1 .menu.ps -side left -padx 1m + +# Set up for keyboard-based menu traversal + +bind . <Any-FocusIn> { + if {("%d" == "NotifyVirtual") && ("%m" == "NotifyNormal")} { + focus .menu + } +} +tk_menuBar .menu .menu.file .menu.group1 .menu.ps + +# The following procedure is invoked to print the contents of a canvas: + +proc lpr c { + exec rm -f tmp.ps + $c postscript -file tmp.ps + exec lpr tmp.ps +} + +# Set up a class binding to allow objects to be deleted from a canvas +# by clicking with mouse button 1: + +bind Canvas <1> {%W delete [%W find closest %x %y]} diff --git a/tests/visual.test b/tests/visual.test new file mode 100644 index 0000000..853554e --- /dev/null +++ b/tests/visual.test @@ -0,0 +1,312 @@ +# This file is a Tcl script to test the visual- and colormap-handling +# procedures in the file tkVisual.c. It is organized in the standard +# fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) visual.test 1.11 96/02/16 10:55:34 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . +update + +# eatColors -- +# Creates a toplevel window and allocates enough colors in it to +# use up all the slots in the colormap. +# +# Arguments: +# w - Name of toplevel window to create. + +proc eatColors {w} { + catch {destroy $w} + toplevel $w + wm geom $w +0+0 + canvas $w.c -width 400 -height 200 -bd 0 + pack $w.c + for {set y 0} {$y < 8} {incr y} { + for {set x 0} {$x < 40} {incr x} { + set color [format #%02x%02x%02x [expr $x*6] [expr $y*30] 0] + $w.c create rectangle [expr 10*$x] [expr 20*$y] \ + [expr 10*$x + 10] [expr 20*$y + 20] -outline {} \ + -fill $color + } + } + update +} + +# colorsFree -- +# +# Returns 1 if there appear to be free colormap entries in a window, +# 0 otherwise. +# +# Arguments: +# w - Name of window in which to check. +# red, green, blue - Intensities to use in a trial color allocation +# to see if there are colormap entries free. + +proc colorsFree {w {red 31} {green 245} {blue 192}} { + set vals [winfo rgb $w [format #%02x%02x%02x $red $green $blue]] + expr ([lindex $vals 0]/256 == $red) && ([lindex $vals 1]/256 == $green) \ + && ([lindex $vals 2]/256 == $blue) +} + +# If more than one visual type is available for the screen, pick one +# that is *not* the default. + +set default "[winfo visual .] [winfo depth .]" +set avail [winfo visualsavailable .] +set other {} +if {[llength $avail] > 1} { + foreach visual $avail { + if {$visual != $default} { + set other $visual + break + } + } +} + +test visual-1.1 {Tk_GetVisual, copying from other window} { + list [catch {toplevel .t -visual .foo.bar} msg] $msg +} {1 {bad window path name ".foo.bar"}} +if {$other != ""} { + test visual-1.2 {Tk_GetVisual, copying from other window} {nonPortable} { + catch {destroy .t1} + catch {destroy .t2} + toplevel .t1 -width 250 -height 100 -visual $other + wm geom .t1 +0+0 + toplevel .t2 -width 200 -height 80 -visual .t1 + wm geom .t2 +5+5 + concat "[winfo visual .t2] [winfo depth .t2]" + } $other + test visual-1.3 {Tk_GetVisual, copying from other window} { + catch {destroy .t1} + catch {destroy .t2} + toplevel .t1 -width 250 -height 100 -visual $other + wm geom .t1 +0+0 + toplevel .t2 -width 200 -height 80 -visual . + wm geom .t2 +5+5 + concat "[winfo visual .t2] [winfo depth .t2]" + } $default + + # Make sure reference count is incremented when copying visual (the + # following test will cause the colormap to be freed prematurely if + # the reference count isn't incremented). + test visual-1.4 {Tk_GetVisual, colormap reference count} { + catch {destroy .t1} + catch {destroy .t2} + toplevel .t1 -width 250 -height 100 -visual $other + wm geom .t1 +0+0 + set result [list [catch {toplevel .t2 -gorp 80 -visual .t1} msg] $msg] + update + set result + } {1 {unknown option "-gorp"}} +} +test visual-1.5 {Tk_GetVisual, default colormap} { + catch {destroy .t1} + toplevel .t1 -width 250 -height 100 -visual default + wm geometry .t1 +0+0 + update + concat "[winfo visual .t1] [winfo depth .t1]" +} $default + +set i 1 +foreach visual $avail { + test visual-2.$i {Tk_GetVisual, different visual types} {nonPortable} { + catch {destroy .t1} + toplevel .t1 -width 250 -height 100 -visual $visual + wm geometry .t1 +0+0 + update + concat "[winfo visual .t1] [winfo depth .t1]" + } $visual + incr i +} + +test visual-3.1 {Tk_GetVisual, parsing visual string} { + catch {destroy .t1} + toplevel .t1 -width 250 -height 100 \ + -visual "[winfo visual .][winfo depth .]" + wm geometry .t1 +0+0 + update + concat "[winfo visual .t1] [winfo depth .t1]" +} $default +test visual-3.2 {Tk_GetVisual, parsing visual string} { + catch {destroy .t1} + list [catch { + toplevel .t1 -width 250 -height 100 -visual goop20 + wm geometry .t1 +0+0 + } msg] $msg +} {1 {unknown or ambiguous visual name "goop20": class must be best, directcolor, grayscale, greyscale, pseudocolor, staticcolor, staticgray, staticgrey, truecolor, or default}} +test visual-3.3 {Tk_GetVisual, parsing visual string} { + catch {destroy .t1} + list [catch { + toplevel .t1 -width 250 -height 100 -visual d + wm geometry .t1 +0+0 + } msg] $msg +} {1 {unknown or ambiguous visual name "d": class must be best, directcolor, grayscale, greyscale, pseudocolor, staticcolor, staticgray, staticgrey, truecolor, or default}} +test visual-3.4 {Tk_GetVisual, parsing visual string} { + catch {destroy .t1} + list [catch { + toplevel .t1 -width 250 -height 100 -visual static + wm geometry .t1 +0+0 + } msg] $msg +} {1 {unknown or ambiguous visual name "static": class must be best, directcolor, grayscale, greyscale, pseudocolor, staticcolor, staticgray, staticgrey, truecolor, or default}} +test visual-3.5 {Tk_GetVisual, parsing visual string} { + catch {destroy .t1} + list [catch { + toplevel .t1 -width 250 -height 100 -visual "pseudocolor 48x" + wm geometry .t1 +0+0 + } msg] $msg +} {1 {expected integer but got "48x"}} + +if {$other != ""} { + catch {destroy .t1} + catch {destroy .t2} + catch {destroy .t3} + toplevel .t1 -width 250 -height 100 -visual $other + wm geom .t1 +0+0 + toplevel .t2 -width 200 -height 80 -visual [winfo visual .] + wm geom .t2 +5+5 + toplevel .t3 -width 150 -height 250 -visual [winfo visual .t1] + wm geom .t3 +10+10 + test visual-4.1 {Tk_GetVisual, numerical visual id} nonPortable { + list [winfo visualid .t2] [winfo visualid .t3] + } [list [winfo visualid .] [winfo visualid .t1]] + destroy .t1 .t2 .t3 +} +test visual-4.2 {Tk_GetVisual, numerical visual id} { + catch {destroy .t1} + list [catch {toplevel .t1 -visual 12xyz} msg] $msg +} {1 {bad X identifier for visual: 12xyz"}} +test visual-4.3 {Tk_GetVisual, numerical visual id} { + catch {destroy .t1} + list [catch {toplevel .t1 -visual 1291673} msg] $msg +} {1 {couldn't find an appropriate visual}} + +if ![string match *pseudocolor* $avail] { + test visual-5.1 {Tk_GetVisual, no matching visual} { + catch {destroy .t1} + list [catch { + toplevel .t1 -width 250 -height 100 -visual "pseudocolor 8" + wm geometry .t1 +0+0 + } msg] $msg + } {1 {couldn't find an appropriate visual}} +} + +if {[string match *pseudocolor* $avail] && ([llength $avail] > 1)} { + test visual-6.1 {Tk_GetVisual, no matching visual} {nonPortable} { + catch {destroy .t1} + toplevel .t1 -width 250 -height 100 -visual "best" + wm geometry .t1 +0+0 + update + winfo visual .t1 + } {pseudocolor} +} + +# These tests are non-portable due to variations in how many colors +# are already in use on the screen. + +if {([winfo visual .] == "pseudocolor") && ([winfo depth .] == 8)} { + eatColors .t1 + test visual-7.1 {Tk_GetColormap, "new"} {nonPortable} { + toplevel .t2 -width 30 -height 20 + wm geom .t2 +0+0 + update + colorsFree .t2 + } {0} + test visual-7.2 {Tk_GetColormap, "new"} {nonPortable} { + catch {destroy .t2} + toplevel .t2 -width 30 -height 20 -colormap new + wm geom .t2 +0+0 + update + colorsFree .t2 + } {1} + test visual-7.3 {Tk_GetColormap, copy from other window} {nonPortable} { + catch {destroy .t2} + toplevel .t3 -width 400 -height 50 -colormap new + wm geom .t3 +0+0 + catch {destroy .t2} + toplevel .t2 -width 30 -height 20 -colormap .t3 + wm geom .t2 +0+0 + update + destroy .t3 + colorsFree .t2 + } {1} + test visual-7.4 {Tk_GetColormap, copy from other window} {nonPortable} { + catch {destroy .t2} + toplevel .t3 -width 400 -height 50 -colormap new + wm geom .t3 +0+0 + catch {destroy .t2} + toplevel .t2 -width 30 -height 20 -colormap . + wm geom .t2 +0+0 + update + destroy .t3 + colorsFree .t2 + } {0} + test visual-7.5 {Tk_GetColormap, copy from other window} {nonPortable} { + catch {destroy .t1} + list [catch {toplevel .t1 -width 400 -height 50 \ + -colormap .choke.lots} msg] $msg + } {1 {bad window path name ".choke.lots"}} + if {$other != {}} { + test visual-7.6 {Tk_GetColormap, copy from other window} {nonPortable} { + catch {destroy .t1} + catch {destroy .t2} + toplevel .t1 -width 300 -height 150 -visual $other + wm geometry .t1 +0+0 + list [catch {toplevel .t2 -width 400 -height 50 \ + -colormap .t1} msg] $msg + } {1 {can't use colormap for .t1: incompatible visuals}} + } + catch {destroy .t1} + catch {destroy .t2} +} + +test visual-8.1 {Tk_FreeColormap procedure} { + foreach w [winfo child .] { + destroy $w + } + toplevel .t1 -width 300 -height 180 -colormap new + wm geometry .t1 +0+0 + foreach i {.t2 .t3 .t4} { + toplevel $i -width 250 -height 150 -colormap .t1 + wm geometry $i +0+0 + } + destroy .t1 + destroy .t3 + destroy .t4 + update +} {} +if {$other != {}} { + test visual-8.2 {Tk_FreeColormap procedure} { + foreach w [winfo child .] { + destroy $w + } + toplevel .t1 -width 300 -height 180 -visual $other + wm geometry .t1 +0+0 + foreach i {.t2 .t3 .t4} { + toplevel $i -width 250 -height 150 -visual $other + wm geometry $i +0+0 + } + destroy .t2 + destroy .t3 + destroy .t4 + update + } {} +} + +foreach w [winfo child .] { + destroy $w +} +rename eatColors {} +rename colorsFree {} diff --git a/tests/winButton.test b/tests/winButton.test new file mode 100644 index 0000000..7125aa5 --- /dev/null +++ b/tests/winButton.test @@ -0,0 +1,154 @@ +# This file is a Tcl script to test the Windows specific behavior of +# labels, buttons, checkbuttons, and radiobuttons in Tk (i.e., all the +# widgets defined in tkWinButton.c). It is organized in the standard +# fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) winButton.test 1.3 97/07/01 18:11:44 + +if {$tcl_platform(platform)!="windows"} { + return +} + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\"" + puts "image, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . + +proc bogusTrace args { + error "trace aborted" +} +catch {unset value} +catch {unset value2} + +eval image delete [image names] +image create test image1 +label .l -text Label +button .b -text Button +checkbutton .c -text Checkbutton +radiobutton .r -text Radiobutton +pack .l .b .c .r +update + +test winbutton-1.1 {TkpComputeButtonGeometry procedure} { + eval destroy [winfo children .] + image create test image1 + image1 changed 0 0 0 0 60 40 + label .b1 -image image1 -bd 4 -padx 0 -pady 2 + button .b2 -image image1 -bd 4 -padx 0 -pady 2 + checkbutton .b3 -image image1 -bd 4 -padx 1 -pady 1 + radiobutton .b4 -image image1 -bd 4 -padx 2 -pady 0 + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {68 48 71 51 96 50 96 50} +test winbutton-1.2 {TkpComputeButtonGeometry procedure} { + eval destroy [winfo children .] + label .b1 -bitmap question -bd 3 -padx 0 -pady 2 + button .b2 -bitmap question -bd 3 -padx 0 -pady 2 + checkbutton .b3 -bitmap question -bd 3 -padx 1 -pady 1 + radiobutton .b4 -bitmap question -bd 3 -padx 2 -pady 0 + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {23 33 26 36 51 35 51 35} +test winbutton-1.3 {TkpComputeButtonGeometry procedure} { + eval destroy [winfo children .] + label .b1 -bitmap question -bd 3 -highlightthickness 4 + button .b2 -bitmap question -bd 3 -highlightthickness 0 + checkbutton .b3 -bitmap question -bd 3 -highlightthickness 1 \ + -indicatoron 0 + radiobutton .b4 -bitmap question -bd 3 -indicatoron false + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {31 41 24 34 26 36 26 36} +test winbutton-1.4 {TkpComputeButtonGeometry procedure} {nonPortable} { + eval destroy [winfo children .] + label .b1 -text Xagqpim -bd 2 -padx 0 -pady 2 -font {{MS Sans Serif} 8} + button .b2 -text Xagqpim -bd 2 -padx 0 -pady 2 -font {{MS Sans Serif} 8} + checkbutton .b3 -text Xagqpim -bd 2 -padx 1 -pady 1 -font {{MS Sans Serif} 8} + radiobutton .b4 -text Xagqpim -bd 2 -padx 2 -pady 0 -font {{MS Sans Serif} 8} + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {45 21 54 30 74 27 76 25} +test winbutton-1.5 {TkpComputeButtonGeometry procedure} {nonPortable} { + eval destroy [winfo children .] + label .l1 -text "This is a long string that will wrap around on several lines.\n\nIt also has a blank line (above)." -wraplength 1.5i -padx 0 -pady 0 + pack .l1 + update + list [winfo reqwidth .l1] [winfo reqheight .l1] +} {142 69} +test winbutton-1.6 {TkpComputeButtonGeometry procedure} {nonPortable} { + eval destroy [winfo children .] + label .l1 -text "This is a long string without wrapping.\n\nIt also has a blank line (above)." -padx 0 -pady 0 + pack .l1 + update + list [winfo reqwidth .l1] [winfo reqheight .l1] +} {180 43} +test winbutton-1.7 {TkpComputeButtonGeometry procedure} {nonPortable} { + eval destroy [winfo children .] + label .b1 -text Xagqpim -bd 2 -padx 0 -pady 2 -width 10 + button .b2 -text Xagqpim -bd 2 -padx 0 -pady 2 -height 5 + checkbutton .b3 -text Xagqpim -bd 2 -padx 1 -pady 1 -width 20 -height 2 + radiobutton .b4 -text Xagqpim -bd 2 -padx 2 -pady 0 -width 4 + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {64 21 54 82 153 40 59 25} +test winbutton-1.8 {TkpComputeButtonGeometry procedure} {nonPortable} { + eval destroy [winfo children .] + label .b1 -text Xagqpim -bd 2 -padx 0 -pady 2 \ + -highlightthickness 4 + button .b2 -text Xagqpim -bd 2 -padx 0 -pady 2 \ + -highlightthickness 0 + checkbutton .b3 -text Xagqpim -bd 2 -padx 1 -pady 1 \ + -highlightthickness 1 -indicatoron no + radiobutton .b4 -text Xagqpim -bd 2 -padx 2 -pady 0 -indicatoron 0 + pack .b1 .b2 .b3 .b4 + update + list [winfo reqwidth .b1] [winfo reqheight .b1] \ + [winfo reqwidth .b2] [winfo reqheight .b2] \ + [winfo reqwidth .b3] [winfo reqheight .b3] \ + [winfo reqwidth .b4] [winfo reqheight .b4] +} {53 29 52 28 56 28 58 26} +test winbutton-1.9 {TkpComputeButtonGeometry procedure} { + eval destroy [winfo children .] + button .b2 -bitmap question -default normal + list [winfo reqwidth .b2] [winfo reqheight .b2] +} {24 34} + +eval destroy [winfo children .] diff --git a/tests/winClipboard.test b/tests/winClipboard.test new file mode 100644 index 0000000..222c23f --- /dev/null +++ b/tests/winClipboard.test @@ -0,0 +1,44 @@ +# This file is a Tcl script to test out Tk's Windows specific +# clipboard code. It is organized in the standard fashion for Tcl +# tests. +# +# This file contains a collection of tests for one or more of the Tcl +# built-in commands. Sourcing this file into Tcl runs the tests and +# generates output for errors. No output means no errors were found. +# +# Copyright (c) 1997 by Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) winClipboard.test 1.3 97/07/01 18:10:37 + +if {$tcl_platform(platform)!="windows"} { + return +} + +if {[string compare test [info procs test]] == 1} { + source defs +} + +test winClipboard-1.1 {TkSelGetSelection} { + clipboard clear + catch {selection get -selection CLIPBOARD} msg + set msg +} {CLIPBOARD selection doesn't exist or form "STRING" not defined} +test winClipboard-1.2 {TkSelGetSelection} { + clipboard clear + clipboard append {} + list [selection get -selection CLIPBOARD] [testclipboard] +} {{} {}} +test winClipboard-1.3 {TkSelGetSelection & TkWinClipboardRender} { + clipboard clear + clipboard append abcd + list [selection get -selection CLIPBOARD] [testclipboard] +} {abcd abcd} +test winClipboard-1.4 {TkSelGetSelection & TkWinClipboardRender} { + clipboard clear + clipboard append "line 1\nline 2" + list [selection get -selection CLIPBOARD] [testclipboard] +} [list "line 1\nline 2" "line 1\r\nline 2"] + diff --git a/tests/winFont.test b/tests/winFont.test new file mode 100644 index 0000000..a047108 --- /dev/null +++ b/tests/winFont.test @@ -0,0 +1,177 @@ +# This file is a Tcl script to test out the procedures in tkWinFont.c. +# It is organized in the standard fashion for Tcl tests. +# +# Many of these tests are visually oriented and cannot be checked +# programmatically (such as "does an underlined font appear to be +# underlined?"); these tests attempt to exercise the code in question, +# but there are no results that can be checked. +# +# Copyright (c) 1996-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) winFont.test 1.7 97/04/25 16:55:00 + +if {$tcl_platform(platform)!="windows"} { + return +} + +if {[string compare test [info procs test]] != 0} { + source defs +} + +catch {destroy .b} +catch {font delete xyz} + +toplevel .b +update idletasks + +set courier {Courier 14} +set cx [font measure $courier 0] + +label .b.l -padx 0 -pady 0 -bd 0 -highlightthickness 0 -justify left -text "0" -font systemfixed +pack .b.l +canvas .b.c -closeenough 0 + +set t [.b.c create text 0 0 -anchor nw -just left -font $courier] +pack .b.c +update + +set ax [winfo reqwidth .b.l] +set ay [winfo reqheight .b.l] +proc getsize {} { + update + return "[winfo reqwidth .b.l] [winfo reqheight .b.l]" +} + +test winfont-1.1 {TkpGetNativeFont procedure: not native} { + list [catch {font measure {} xyz} msg] $msg +} {1 {font "" doesn't exist}} +test winfont-1.2 {TkpGetNativeFont procedure: native} { + font measure ansifixed 0 + font measure ansi 0 + font measure device 0 + font measure oemfixed 0 + font measure systemfixed 0 + font measure system 0 + set x {} +} {} + +test winfont-2.1 {TkpGetFontFromAttributes procedure: pointsize} { + expr [font actual {-size -10} -size]>0 +} {1} +test winfont-2.2 {TkpGetFontFromAttributes procedure: pointsize} { + expr [font actual {-family Arial} -size]>0 +} {1} +test winfont-2.3 {TkpGetFontFromAttributes procedure: normal weight} { + font actual {-weight normal} -weight +} {normal} +test winfont-2.4 {TkpGetFontFromAttributes procedure: bold weight} { + font actual {-weight bold} -weight +} {bold} +test winfont-2.5 {TkpGetFontFromAttributes procedure: no family} { + catch {expr {[font actual {-size 10} -size]}} +} 0 +test winfont-2.6 {TkpGetFontFromAttributes procedure: family} { + font actual {-family Arial} -family +} {Arial} +test winfont-2.7 {TkpGetFontFromAttributes procedure: Times fonts} { + set x {} + lappend x [font actual {-family "Times"} -family] + lappend x [font actual {-family "New York"} -family] + lappend x [font actual {-family "Times New Roman"} -family] +} {{Times New Roman} {Times New Roman} {Times New Roman}} +test winfont-2.8 {TkpGetFontFromAttributes procedure: Courier fonts} { + set x {} + lappend x [font actual {-family "Courier"} -family] + lappend x [font actual {-family "Monaco"} -family] + lappend x [font actual {-family "Courier New"} -family] +} {{Courier New} {Courier New} {Courier New}} +test winfont-2.9 {TkpGetFontFromAttributes procedure: Helvetica fonts} { + set x {} + lappend x [font actual {-family "Helvetica"} -family] + lappend x [font actual {-family "Geneva"} -family] + lappend x [font actual {-family "Arial"} -family] +} {Arial Arial Arial} +test winfont-2.10 {TkpGetFontFromAttributes procedure: fallback} { + # No way to get it to fail! Any font name is acceptable. +} {} + +test winfont-3.1 {TkpDeleteFont procedure} { + font actual {-family xyz} + set x {} +} {} + +test winfont-4.1 {TkpGetFontFamilies procedure} { + font families + set x {} +} {} + +test winfont-5.1 {Tk_MeasureChars procedure: unbounded right margin} { + .b.l config -wrap 0 -text "000000" + getsize +} "[expr $ax*6] $ay" +test winfont-5.2 {Tk_MeasureChars procedure: static width buffer exceeded} { + .b.l config -wrap 100000 -text "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + getsize +} "[expr $ax*256] $ay" +test winfont-5.3 {Tk_MeasureChars procedure: all chars did fit} { + .b.l config -wrap [expr $ax*10] -text "00000000" + getsize +} "[expr $ax*8] $ay" +test winfont-5.4 {Tk_MeasureChars procedure: not all chars fit} { + .b.l config -wrap [expr $ax*6] -text "00000000" + getsize +} "[expr $ax*6] [expr $ay*2]" +test winfont-5.5 {Tk_MeasureChars procedure: include last partial char} { + .b.c dchars $t 0 end + .b.c insert $t 0 "0000" + .b.c index $t @[expr int($cx*2.5)],1 +} {2} +test winfont-5.6 {Tk_MeasureChars procedure: at least one char on line} { + .b.l config -text "000000" -wrap 1 + getsize +} "$ax [expr $ay*6]" +test winfont-5.7 {Tk_MeasureChars procedure: whole words} { + .b.l config -wrap [expr $ax*8] -text "000000 0000" + getsize +} "[expr $ax*6] [expr $ay*2]" +test winfont-5.8 {Tk_MeasureChars procedure: already saw space in line} { + .b.l config -wrap [expr $ax*12] -text "000000 0000000" + getsize +} "[expr $ax*7] [expr $ay*2]" +test winfont-5.9 {Tk_MeasureChars procedure: internal spaces significant} { + .b.l config -wrap [expr $ax*12] -text "000 00 00000" + getsize +} "[expr $ax*7] [expr $ay*2]" +test winfont-5.10 {Tk_MeasureChars procedure: make first part of word fit} { + .b.l config -wrap [expr $ax*12] -text "0000000000000000" + getsize +} "[expr $ax*12] [expr $ay*2]" + +test winfont-6.1 {Tk_DrawChars procedure: loop test} { + .b.l config -text "a" + update +} {} + +test winfont-7.1 {AllocFont procedure: use old font} { + font create xyz + catch {destroy .c} + button .c -font xyz + font configure xyz -family times + update + destroy .c + font delete xyz +} {} +test winfont-7.2 {AllocFont procedure: extract info from logfont} { + font actual {arial 10 bold italic underline overstrike} +} {-family Arial -size 10 -weight bold -slant italic -underline 1 -overstrike 1} +test winfont-7.3 {AllocFont procedure: extract info from textmetric} { + font metric {arial 10 bold italic underline overstrike} -fixed +} {0} +test winfont-7.4 {AllocFont procedure: extract info from textmetric} { + font metric systemfixed -fixed +} {1} + +destroy .b diff --git a/tests/winMenu.test b/tests/winMenu.test new file mode 100644 index 0000000..ceeced6 --- /dev/null +++ b/tests/winMenu.test @@ -0,0 +1,1030 @@ +# This file is a Tcl script to test menus in Tk. It is +# organized in the standard fashion for Tcl tests. This +# file tests the Macintosh-specific features of the menu +# system. +# +# Copyright (c) 1995-1996 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) winMenu.test 1.19 97/07/02 11:29:57 + +if {$tcl_platform(platform) != "windows"} { + return +} + +if {![info exists INTERACTIVE]} { + puts " Some tests were skipped because they could not be performed" + puts " automatically on this platform. If you wish to execute them" + puts " interactively, set the TCL variable INTERACTIVE and re-run" + puts " the test." + set testConfig(menuInteractive) 0 +} else { + set testConfig(menuInteractive) 1 +} + +if {[lsearch [image types] test] < 0} { + puts "This application hasn't been compiled with the \"test\" image" + puts "type, so I can't run this test. Are you sure you're using" + puts "tktest instead of wish?" + return +} + +if {[info procs test] != "test"} { + source defs +} + +proc deleteWindows {} { + foreach i [winfo children .] { + catch [destroy $i] + } +} + +deleteWindows +wm geometry . {} +raise . + +test winMenu-1.1 {GetNewID} { + catch {destroy .m1} + list [catch {menu .m1} msg] $msg [destroy .m1] +} {0 .m1 {}} +# Basically impossible to test menu IDs wrapping. + +test winMenu-2.1 {FreeID} { + catch {destroy .m1} + menu .m1 + list [catch {destroy .m1} msg] $msg +} {0 {}} + +test winMenu-3.1 {TkpNewMenu} { + catch {destroy .m1} + list [catch {menu .m1} msg] $msg [catch {destroy .m1} msg2] $msg2 +} {0 .m1 0 {}} +test winMenu-3.2 {TkpNewMenu} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + .m1 add command -label "foo" + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [catch {destroy .m1} msg2] $msg2 +} {0 {} {} 0 {}} + +test winMenu-4.1 {TkpDestroyMenu} { + catch {destroy .m1} + menu .m1 + list [catch {destroy .m1} msg] $msg +} {0 {}} +test winMenu-4.2 {TkpDestroyMenu - help menu} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.system + . configure -menu .m1 + list [catch {destroy .m1.system} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} + +test winMenu-5.1 {TkpDestroyMenuEntry} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + .m1 add command -label "test" + update idletasks + list [catch {.m1 delete 1} msg] $msg [destroy .m1] +} {0 {} {}} + +test winMenu-6.1 {GetEntryText} { + catch {destroy .m1} + list [catch {menu .m1} msg] $msg [destroy .m1] +} {0 .m1 {}} +test winMenu-6.2 {GetEntryText} { + catch {destroy .m1} + catch {image delete image1} + menu .m1 + image create test image1 + list [catch {.m1 add command -image image1} msg] $msg [destroy .m1] [image delete image1] +} {0 {} {} {}} +test winMenu-6.3 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -bitmap questhead} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.4 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.5 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "foo"} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.6 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "This string has one & in it"} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.7 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "The & should be underlined." -underline 4} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.8 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "The * should be underlined." -underline 4} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.9 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "foo" -accel "bar"} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.10 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "This string has one & in it" -accel "bar"} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.11 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "The & should be underlined." -underline 4 -accel "bar"} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.12 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "The * should be underlined." -underline 4 -accel "bar"} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.13 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "foo" -accel "&bar"} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.14 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "This string has one & in it" -accel "&bar"} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.15 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "The & should be underlined." -underline 4 -accel "&bar"} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-6.16 {GetEntryText} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command -label "The * should be underlined." -underline 4 -accel "&bar"} msg] $msg [destroy .m1] +} {0 {} {}} + +test winMenu-7.1 {ReconfigureWindowsMenu - system menu item removal} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -menu .m1.system + menu .m1.system + .m1.system add command -label foo + update idletasks + .m1.system add command -label bar + list [catch {update idletasks} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test winMenu-7.2 {ReconfigureWindowsMenu - menu item removal} { + catch {destroy .m1} + menu .m1 + .m1 add command -label Hello + update idletasks + .m1 add command -label foo + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.3 {ReconfigureWindowsMenu - zero items} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label Hello + .m1 delete Hello + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.4 {ReconfigureWindowsMenu - one item} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label Hello + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.5 {ReconfigureWindowsMenu - two items} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label One + .m1 add command -label Two + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.6 {ReconfigureWindowsMenu - separator item} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add separator + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.7 {ReconfigureWindowsMenu - non-text item} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label Hello + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.8 {ReconfigureWindowsMenu - disabled item} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label Hello -state disabled + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.9 {ReconfigureWindowsMenu - non-selected checkbutton} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add checkbutton -label Hello + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.10 {ReconfigureWindowsMenu - non-selected radiobutton} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add radiobutton -label Hello + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.11 {ReconfigureWindowsMenu - selected checkbutton} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add checkbutton -label Hello + .m1 invoke Hello + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.12 {ReconfigureWindowsMenu - selected radiobutton} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add radiobutton -label Hello + .m1 invoke Hello + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.13 {ReconfigureWindowsMenu - cascade missing} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -label Hello + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-7.14 {ReconfigureWindowsMenu - cascade} { + catch {destroy .m1} + catch {destroy .m2} + menu .m1 -tearoff 0 + menu .m2 + .m1 add cascade -menu .m2 -label Hello + list [catch {update idletasks} msg] $msg [destroy .m1] [destroy .m2] +} {0 {} {} {}} +test winMenu-7.15 {ReconfigureWindowsMenu - menubar without system menu} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -menu .m1.file + menu .m1.file -tearoff 0 + . configure -menu .m1 + list [catch {update idletasks} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test winMenu-7.16 {ReconfigureWindowsMenu - system menu already created} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -menu .m1.system + menu .m1.system -tearoff 0 + . configure -menu .m1 + update idletasks + .m1.system add command -label Hello + list [catch {update idletasks} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test winMenu-7.17 {ReconfigureWindowsMenu - system menu update pending} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -menu .m1.system + menu .m1.system -tearoff 0 + . configure -menu .m1 + list [catch {update idletasks} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test winMenu-7.18 {ReconfigureWindowsMenu - system menu update not pending} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add cascade -menu .m1.system + menu .m1.system -tearoff 0 + .m1.system add command -label Hello + update idletasks + . configure -menu .m1 + list [catch {update idletasks} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} +test winMenu-7.19 {ReconfigureWindowsMenu - column break} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label one + .m1 add command -label two -columnbreak 1 + list [catch {update idletasks} msg] $msg [destroy .m1] +} {0 {} {}} + +#Don't know how to generate nested post menus +test winMenu-8.1 {TkpPostMenu} { + catch {destroy .m1} + menu .m1 -postcommand "blork" + list [catch {.m1 post 40 40} msg] $msg [destroy .m1] +} {1 {invalid command name "blork"} {}} +test winMenu-8.2 {TkpPostMenu} { + catch {destroy .m1} + menu .m1 -postcommand "destroy .m1" + list [.m1 post 40 40] [winfo exists .m1] +} {{} 0} +test winMenu-8.3 {TkpPostMenu - popup menu} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "winMenu-8.3: Hit ESCAPE." + list [.m1 post 40 40] [destroy .m1] +} {{} {}} +test winMenu-8.4 {TkpPostMenu - menu button} {menuInteractive} { + catch {destroy .mb} + menubutton .mb -text test -menu .mb.menu + menu .mb.menu + .mb.menu add command -label "winMenu-8.4 - Hit ESCAPE." + pack .mb + list [tkMbPost .mb] [destroy .m1] +} {{} {}} +test winMenu-8.5 {TkpPostMenu - update not pending} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "winMenu-8.5 - Hit ESCAPE." + update idletasks + list [catch {.m1 post 40 40} msg] $msg [destroy .m1] +} {0 {} {}} + +test winMenu-9.1 {TkpMenuNewEntry} { + catch {destroy .m1} + menu .m1 + list [catch {.m1 add command} msg] $msg [destroy .m1] +} {0 {} {}} + +test winMenu-10.1 {TkwinMenuProc} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "winMenu-10.1: Hit ESCAPE." + list [.m1 post 40 40] [destroy .m1] +} {{} {}} + +# Can't generate a WM_INITMENU without a Tk menu yet. +test winMenu-11.1 {TkWinHandleMenuEvent - WM_INITMENU} {menuInteractive} { + catch {destroy .m1} + catch {unset foo} + menu .m1 -postcommand "set foo test" + .m1 add command -label "winMenu-11.1: Hit ESCAPE." + list [.m1 post 40 40] [set foo] [unset foo] [destroy .m1] +} {test test {} {}} +test winMenu-11.2 {TkWinHandleMenuEvent - WM_COMMAND} {menuInteractive} { + catch {destroy .m1} + catch {unset foo} + menu .m1 + .m1 add checkbutton -variable foo -label "winMenu-11.2: Please select this menu item." + list [.m1 post 40 40] [update] [set foo] [unset foo] [destroy .m1] +} {{} {} 1 {} {}} +# Can't test WM_MENUCHAR +test winMenu-11.3 {TkWinHandleMenuEvent - WM_MEASUREITEM} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "winMenu-11.3: Hit ESCAPE." + list [.m1 post 40 40] [destroy .m1] +} {{} {}} +test winMenu-11.4 {TkWinHandleMenuEvent - WM_MEASUREITEM} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label "winMenu-11.4: Hit ESCAPE" -hidemargin 1 + list [.m1 post 40 40] [destroy .m1] +} {{} {}} +test winMenu-11.5 {TkWinHandleMenuEvent - WM_DRAWITEM} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "winMenu-11.5: Hit ESCAPE." + list [.m1 post 40 40] [destroy .m1] +} {{} {}} +test winMenu-11.6 {TkWinHandleMenuEvent - WM_DRAWITEM - item disabled} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "winMenu-11.6: Hit ESCAPE." -state disabled + list [.m1 post 40 40] [destroy .m1] +} {{} {}} +test winMenu-11.7 {TkWinHandleMenuEvent - WM_INITMENU - not pending} {menuInteractive} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label "winMenu-11.7: Hit ESCAPE" + update idletasks + list [catch {.m1 post 40 40} msg] $msg [destroy .m1] +} {0 {} {}} + +test winMenu-12.1 {TkpSetWindowMenuBar} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + .m1 add command -label foo + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [catch {destroy .m1} msg2] $msg2 +} {0 {} {} 0 {}} +test winMenu-12.2 {TkpSetWindowMenuBar} { + catch {destroy .m1} + . configure -menu "" + menu .m1 + .m1 add command -label foo + . configure -menu .m1 + list [catch {. configure -menu ""} msg] $msg [catch {destroy .m1} msg2] $msg2 +} {0 {} 0 {}} +test winMenu-12.3 {TkpSetWindowMenuBar - no update pending} { + catch {destroy .m1} + . configure -menu "" + menu .m1 -tearoff 0 + .m1 add command -label foo + update idletasks + list [catch {. configure -menu .m1} msg] $msg [. configure -menu ""] [destroy .m1] +} {0 {} {} {}} + +test winMenu-13.1 {TkpSetMainMenubar - nothing to do} {} {} + +test winMenu-14.1 {GetMenuIndicatorGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test winMenu-14.2 {GetMenuIndicatorGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo -hidemargin 1 + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} + +test winMenu-15.1 {GetMenuAccelGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo -accel Ctrl+U + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test winMenu-15.2 {GetMenuAccelGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} +test winMenu-15.3 {GetMenuAccelGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Ctrl+U" + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} + +test winMenu-16.1 {GetTearoffEntryGeometry} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "winMenu-19.1: Hit ESCAPE." + list [.m1 post 40 40] [destroy .m1] +} {{} {}} + +test winMenu-17.1 {GetMenuSeparatorGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add separator + list [catch {tkTearOffMenu .m1 40 40}] [destroy .m1] +} {0 {}} + +# Currently, the only callers to DrawWindowsSystemBitmap want things +# centered vertically, and either centered or right aligned horizontally. +test winMenu-18.1 {DrawWindowsSystemBitmap - center aligned} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + .m1 invoke foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-18.2 {DrawWindowsSystemBitmap - right aligned} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} + +test winMenu-19.1 {DrawMenuEntryIndicator - not checkbutton or radiobutton} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-19.2 {DrawMenuEntryIndicator - not selected} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-19.3 {DrawMenuEntryIndicator - checkbutton} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + .m1 invoke foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-19.4 {DrawMenuEntryIndicator - radiobutton} { + catch {destroy .m1} + menu .m1 + .m1 add radiobutton -label foo + .m1 invoke foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-19.5 {DrawMenuEntryIndicator - disabled} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + .m1 invoke foo + .m1 entryconfigure foo -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-19.6 {DrawMenuEntryIndicator - indicator not on} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo -indicatoron 0 + .m1 invoke foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} + +test winMenu-20.1 {DrawMenuEntryAccelerator - disabled} { + catch {destroy .m1} + menu .m1 -disabledforeground red + .m1 add command -label foo -accel "Ctrl+U" -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-20.2 {DrawMenuEntryAccelerator - normal text} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -accel "Ctrl+U" + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-20.3 {DrawMenuEntryAccelerator - disabled, no disabledforeground} { + catch {destroy .m1} + menu .m1 -disabledforeground "" + .m1 add command -label foo -accel "Ctrl+U" -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-20.4 {DrawMenuEntryAccelerator - cascade, drawArrow true} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-20.5 {DrawMenuEntryAccelerator - cascade, drawArrow false} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label "winMenu-23.5: Hit ESCAPE." + list [.m1 post 40 40] [destroy .m1] +} {{} {}} + +test winMenu-21.1 {DrawMenuSeparator} { + catch {destroy .m1} + menu .m1 + .m1 add separator + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} + +test winMenu-22.1 {DrawMenuUnderline} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -underline 0 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} + +test winMenu-23.1 {Don't know how to test MenuKeyBindProc} {} {} +test winMenu-24.1 {TkpInitializeMenuBindings called at boot time} {} {} + +test winMenu-25.1 {DrawMenuEntryLabel - normal} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-25.2 {DrawMenuEntryLabel - disabled with fg} { + catch {destroy .m1} + menu .m1 -disabledforeground red + .m1 add command -label foo -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-25.3 {DrawMenuEntryLabel - disabled with no fg} { + catch {destroy .m1} + menu .m1 -disabledforeground "" + .m1 add command -label foo -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} + +test winMenu-26.1 {TkpComputeMenubarGeometry} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label File + list [. configure -menu .m1] [. configure -menu ""] [destroy .m1] +} {{} {} {}} + +test winMenu-27.1 {DrawTearoffEntry} {menuInteractive} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "winMenu-24.4: Hit ESCAPE." + list [.m1 post 40 40] [destroy .m1] +} {{} {}} + +test winMenu-28.1 {TkpConfigureMenuEntry - update pending} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label Hello + list [catch {.m1 add command -label Two} msg] $msg [destroy .m1] +} {0 {} {}} +test winMenu-28.2 {TkpConfigureMenuEntry - update not pending} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label One + update idletasks + list [catch {.m1 add command -label Two} msg] $msg [destroy .m1] +} {0 {} {}} + +test winMenu-29.1 {TkpDrawMenuEntry - gc for active and not strict motif} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.2 {TkpDrawMenuEntry - gc for active menu item with its own gc} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -activeforeground red + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.3 {TkpDrawMenuEntry - gc for active and strict motif} { + catch {destroy .m1} + menu .m1 + set tk_strictMotif 1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] [set tk_strictMotif 0] +} {{} {} 0} +test winMenu-29.4 {TkpDrawMenuEntry - gc for disabled with disabledfg and custom entry} { + catch {destroy .m1} + menu .m1 -disabledforeground blue + .m1 add command -label foo -state disabled -background red + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.5 {TkpDrawMenuEntry - gc for disabled with disabledFg} { + catch {destroy .m1} + menu .m1 -disabledforeground blue + .m1 add command -label foo -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.6 {TkpDrawMenuEntry - gc for disabled - no disabledFg} { + catch {destroy .m1} + menu .m1 -disabledforeground "" + .m1 add command -label foo -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.7 {TkpDrawMenuEntry - gc for normal - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -foreground red + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.8 {TkpDrawMenuEntry - gc for normal} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.9 {TkpDrawMenuEntry - gc for indicator - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo -selectcolor orange + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.10 {TkpDrawMenuEntry - gc for indicator} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label foo + .m1 invoke 1 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.11 {TkpDrawMenuEntry - border - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -activebackground green + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.12 {TkpDrawMenuEntry - border} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.13 {TkpDrawMenuEntry - active border - strict motif} { + catch {destroy .m1} + set tk_strictMotif 1 + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] [set tk_strictMotif 0] +} {{} {} 0} +test winMenu-29.14 {TkpDrawMenuEntry - active border - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -activeforeground yellow + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.15 {TkpDrawMenuEntry - active border} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + .m1 entryconfigure 1 -state active + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.16 {TkpDrawMenuEntry - font - custom entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo -font "Helvectica 72" + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.17 {TkpDrawMenuEntry - font} { + catch {destroy .m1} + menu .m1 -font "Courier 72" + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.18 {TkpDrawMenuEntry - separator} { + catch {destroy .m1} + menu .m1 + .m1 add separator + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.19 {TkpDrawMenuEntry - standard} { + catch {destroy .mb} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.20 {TkpDrawMenuEntry - disabled cascade item} { + catch {destroy .m1} + menu .m1 + .m1 add cascade -label File -menu .m1.file + menu .m1.file + .m1.file add command -label foo + .m1 entryconfigure File -state disabled + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.21 {TkpDrawMenuEntry - indicator} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label winMenu-31.20 + .m1 invoke winMenu-31.20 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-29.22 {TkpDrawMenuEntry - indicator} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label winMenu-31.21 -hidemargin 1 + .m1 invoke winMenu-31.21 + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} + +test winMenu-30.1 {GetMenuLabelGeometry - image} { + catch {destroy .m1} + catch {image delete image1} + menu .m1 + image create test image1 + .m1 add command -image image1 + list [update idletasks] [destroy .m1] [image delete image1] +} {{} {} {}} +test winMenu-30.2 {GetMenuLabelGeometry - bitmap} { + catch {destroy .m1} + menu .m1 + .m1 add command -bitmap questhead + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-30.3 {GetMenuLabelGeometry - no text} { + catch {destroy .m1} + menu .m1 + .m1 add command + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-30.4 {GetMenuLabelGeometry - text} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "This is a test." + list [update idletasks] [destroy .m1] +} {{} {}} + +test winMenu-31.1 {DrawMenuEntryBackground} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + list [update] [destroy .m1] +} {{} {}} +test winMenu-31.2 {DrawMenuEntryBackground} { + catch {destroy .m1} + menu .m1 + .m1 add command -label foo + set tearoff [tkTearOffMenu .m1 40 40] + $tearoff activate 0 + list [update] [destroy .m1] +} {{} {}} + +test winMenu-32.1 {TkpComputeStandardMenuGeometry - no entries} { + catch {destroy .m1} + menu .m1 + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.2 {TkpComputeStandardMenuGeometry - one entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.3 {TkpComputeStandardMenuGeometry - more than one entry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "one" + .m1 add command -label "two" + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.4 {TkpComputeStandardMenuGeometry - separator} { + catch {destroy .m1} + menu .m1 + .m1 add separator + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.5 {TkpComputeStandardMenuGeometry - tearoff entry} {unixOnly} { + catch {destroy .m1} + menubutton .mb -text "test" -menu .mb.m + menu .mb.m + .mb.m add command -label test + pack .mb + catch {tkMbPost .mb} + list [update] [destroy .mb] +} {{} {}} +test winMenu-32.6 {TkpComputeStandardMenuGeometry - standard label geometry} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.7 {TkpComputeStandardMenuGeometry - different font for entry} { + catch {destroy .m1} + menu .m1 -font "Helvetica 12" + .m1 add command -label "test" -font "Courier 12" + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.8 {TkpComputeStandardMenuGeometry - second entry larger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" + .m1 add command -label "test test" + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.9 {TkpComputeStandardMenuGeometry - first entry larger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test test" + .m1 add command -label "test" + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.10 {TkpComputeStandardMenuGeometry - accelerator} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" -accel "Ctrl+S" + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.11 {TkpComputeStandardMenuGeometry - second accel larger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" -accel "1" + .m1 add command -label "test" -accel "1 1" + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.12 {TkpComputeStandardMenuGeometry - second accel smaller} { + catch {destroy .m1} + menu .m1 + .m1 add command -label "test" -accel "1 1" + .m1 add command -label "test" -accel "1" + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.13 {TkpComputeStandardMenuGeometry - indicator} { + catch {destroy .m1} + menu .m1 + .m1 add checkbutton -label test + .m1 invoke 1 + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.14 {TkpComputeStandardMenuGeometry - second indicator less or equal } { + catch {destroy .m1} + catch {image delete image1} + image create test image1 + menu .m1 + .m1 add checkbutton -image image1 + .m1 invoke 1 + .m1 add checkbutton -label test + .m1 invoke 2 + list [update idletasks] [destroy .m1] [image delete image1] +} {{} {} {}} +test winMenu-32.15 {TkpComputeStandardMenuGeometry - second indicator larger } {unixOnly} { + catch {destroy .m1} + catch {image delete image1} + image create test image1 + menu .m1 + .m1 add checkbutton -image image1 + .m1 invoke 1 + .m1 add checkbutton -label test + .m1 invoke 2 + list [update idletasks] [destroy .m1] [image delete image1] +} {{} {} {}} +test winMenu-32.16 {TkpComputeStandardMenuGeometry - zero sized menus} { + catch {destroy .m1} + menu .m1 -tearoff 0 + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.17 {TkpComputeStandardMenuGeometry - first column bigger} { + catch {destroy .m1} + menu .m1 + .m1 add command -label one + .m1 add command -label two + .m1 add command -label three -columnbreak 1 + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.18 {TkpComputeStandardMenuGeometry - second column bigger} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label one + .m1 add command -label two -columnbreak 1 + .m1 add command -label three + list [update idletasks] [destroy .m1] +} {{} {}} +test winMenu-32.19 {TkpComputeStandardMenuGeometry - three columns} { + catch {destroy .m1} + menu .m1 -tearoff 0 + .m1 add command -label one + .m1 add command -label two -columnbreak 1 + .m1 add command -label three + .m1 add command -label four + .m1 add command -label five -columnbreak 1 + .m1 add command -label six + list [update idletasks] [destroy .m1] +} {{} {}} + +test winMenu-33.1 {TkpNotifyTopLevelCreate - no menu yet} { + catch {destroy .t2} + catch {destroy .m1} + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + list [update idletasks] [destroy .t2] +} {{} {}} +test winMenu-33.2 {TkpNotifyTopLevelCreate - menu} { + catch {destroy .t2} + catch {destroy .m1} + menu .m1 + menu .m1.system + .m1 add cascade -menu .m1.system + .m1.system add separator + .m1.system add command -label foo + toplevel .t2 -menu .m1 + wm geometry .t2 +0+0 + list [update idletasks] [destroy .m1] [destroy .t2] +} {{} {} {}} + +test winMenu-34.1 {TkpMenuInit called at boot time} {} {} + +deleteWindows diff --git a/tests/winWm.test b/tests/winWm.test new file mode 100644 index 0000000..c83e380 --- /dev/null +++ b/tests/winWm.test @@ -0,0 +1,219 @@ +# This file tests is a Tcl script to test the procedures in the file +# tkWinWm.c. It is organized in the standard fashion for Tcl tests. +# +# This file contains a collection of tests for one or more of the Tcl +# built-in commands. Sourcing this file into Tcl runs the tests and +# generates output for errors. No output means no errors were found. +# +# Copyright (c) 1996 by Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) winWm.test 1.5 97/08/13 15:42:46 + +if {$tcl_platform(platform) != "windows"} { + return +} + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + catch {destroy $i} +} + +# Measure the height of a single menu line + +toplevel .t +frame .t.f -width 100 -height 50 +pack .t.f +menu .t.m +.t.m add command -label "thisisreallylong" +.t conf -menu .t.m +wm geom .t -0-0 +update +set menuheight [winfo y .t] +.t.m add command -label "thisisreallylong" +wm geom .t -0-0 +update +set menuheight [expr $menuheight - [winfo y .t]] +destroy .t + +test winWm-1.1 {TkWmMapWindow} { + toplevel .t + wm override .t 1 + wm geometry .t +0+0 + update + set result [list [winfo rootx .t] [winfo rooty .t]] + destroy .t + set result +} {0 0} +test winWm-1.2 {TkWmMapWindow} { + toplevel .t + wm transient .t . + update + wm iconify . + update + wm deiconify . + update + catch {wm iconify .t} msg + destroy .t + set msg +} {can't iconify ".t": it is a transient} +test winWm-1.3 {TkWmMapWindow} { + toplevel .t + update + toplevel .t2 + update + set result [expr [winfo x .t] != [winfo x .t2]] + destroy .t .t2 + set result +} 1 +test winWm-1.4 {TkWmMapWindow} { + toplevel .t + wm geometry .t +10+10 + update + toplevel .t2 + wm geometry .t2 +40+10 + update + set result [list [winfo x .t] [winfo x .t2]] + destroy .t .t2 + set result +} {10 40} +test winWm-1.5 {TkWmMapWindow} { + toplevel .t + wm iconify .t + update + set result [wm state .t] + destroy .t + set result +} iconic + +test winWm-2.1 {TkpWmSetState} { + toplevel .t + wm geometry .t 150x50+10+10 + update + set result [wm state .t] + wm iconify .t + update + lappend result [wm state .t] + wm deiconify .t + update + lappend result [wm state .t] + destroy .t + set result +} {normal iconic normal} +test winWm-2.2 {TkpWmSetState} { + toplevel .t + wm geometry .t 150x50+10+10 + update + set result [wm state .t] + wm withdraw .t + update + lappend result [wm state .t] + wm iconify .t + update + lappend result [wm state .t] + wm deiconify .t + update + lappend result [wm state .t] + destroy .t + set result +} {normal withdrawn iconic normal} +test winWm-2.3 {TkpWmSetState} { + set result {} + toplevel .t + wm geometry .t 150x50+10+10 + update + lappend result [list [wm state .t] [wm geometry .t]] + wm iconify .t + update + lappend result [list [wm state .t] [wm geometry .t]] + wm geometry .t 200x50+10+10 + update + lappend result [list [wm state .t] [wm geometry .t]] + wm deiconify .t + update + lappend result [list [wm state .t] [wm geometry .t]] + destroy .t + set result +} {{normal 150x50+10+10} {iconic 150x50+10+10} {iconic 150x50+10+10} {normal 200x50+10+10}} + + +test winWm-3.1 {ConfigureTopLevel: window geometry propagation} { + toplevel .t + wm geometry .t +0+0 + button .t.b + pack .t.b + update + set x [winfo x .t.b] + destroy .t + toplevel .t + wm geometry .t +0+0 + button .t.b + update + pack .t.b + update + set x [expr $x == [winfo x .t.b]] + destroy .t + set x +} 1 + +test winWm-4.1 {ConfigureTopLevel: menu resizing} { + set result {} + toplevel .t + frame .t.f -width 150 -height 50 -bg red + pack .t.f + wm geometry .t -0-0 + update + set y [winfo y .t] + menu .t.m + .t.m add command -label foo + .t conf -menu .t.m + update + set result [expr $y - [winfo y .t]] + destroy .t + set result +} [expr $menuheight + 1] + +test winWm-5.1 {UpdateGeometryInfo: menu resizing} { + set result {} + toplevel .t + frame .t.f -width 150 -height 50 -bg red + pack .t.f + update + set result [winfo height .t] + menu .t.m + .t.m add command -label foo + .t conf -menu .t.m + update + lappend result [winfo height .t] + .t.m add command -label "thisisreallylong" + .t.m add command -label "thisisreallylong" + update + lappend result [winfo height .t] + destroy .t + set result +} {50 50 50} +test winWm-5.2 {UpdateGeometryInfo: menu resizing} { + set result {} + toplevel .t + frame .t.f -width 150 -height 50 -bg red + pack .t.f + wm geom .t -0-0 + update + set y [winfo rooty .t] + lappend result [winfo height .t] + menu .t.m + .t conf -menu .t.m + .t.m add command -label foo + .t.m add command -label "thisisreallylong" + .t.m add command -label "thisisreallylong" + update + lappend result [winfo height .t] + lappend result [expr $y - [winfo rooty .t]] + destroy .t + set result +} {50 50 0} diff --git a/tests/window.test b/tests/window.test new file mode 100644 index 0000000..aaa29c0 --- /dev/null +++ b/tests/window.test @@ -0,0 +1,131 @@ +# This file is a Tcl script to test the procedures in the file +# tkWindow.c. It is organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1995 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) window.test 1.8 97/01/22 14:17:54 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + destroy $i +} +wm geometry . {} +raise . +update + +# XXX This file is woefully incomplete. Right now it only tests +# a few parts of a few procedures in tkWindow.c + +test window-1.1 {Tk_CreateWindowFromPath procedure, parent dead} { + proc bgerror msg { + global x errorInfo + set x [list $msg $errorInfo] + } + set x unchanged + catch {destroy .t} + frame .t -width 100 -height 50 + place .t -x 10 -y 10 + bind .t <Destroy> {button .t.b -text hello; pack .t.b} + update + destroy .t + update + rename bgerror {} + set x +} {{can't create window: parent has been destroyed} {can't create window: parent has been destroyed + while executing +"button .t.b -text hello" + (command bound to event)}} + +# Most of the tests below don't produce meaningful results; they +# will simply dump core if there are bugs. + +test window-2.1 {Tk_DestroyWindow procedure, destroy handler deletes parent} { + toplevel .t -width 300 -height 200 + wm geometry .t +0+0 + frame .t.f -width 200 -height 200 -relief raised -bd 2 + place .t.f -x 0 -y 0 + frame .t.f.f -width 100 -height 100 -relief raised -bd 2 + place .t.f.f -relx 1 -rely 1 -anchor se + bind .t.f <Destroy> {destroy .t} + update + destroy .t.f +} {} +test window-2.2 {Tk_DestroyWindow procedure, destroy handler deletes parent} { + toplevel .t -width 300 -height 200 + wm geometry .t +0+0 + frame .t.f -width 200 -height 200 -relief raised -bd 2 + place .t.f -x 0 -y 0 + frame .t.f.f -width 100 -height 100 -relief raised -bd 2 + place .t.f.f -relx 1 -rely 1 -anchor se + bind .t.f.f <Destroy> {destroy .t} + update + destroy .t.f +} {} +test window-2.3 {Tk_DestroyWindow procedure, destroy handler deletes parent} { + frame .f -width 80 -height 120 -relief raised -bd 2 + place .f -relx 0.5 -rely 0.5 -anchor center + toplevel .f.t -width 300 -height 200 + wm geometry .f.t +0+0 + frame .f.t.f -width 200 -height 200 -relief raised -bd 2 + place .f.t.f -x 0 -y 0 + frame .f.t.f.f -width 100 -height 100 -relief raised -bd 2 + place .f.t.f.f -relx 1 -rely 1 -anchor se + update + destroy .f +} {} + +test window-3.1 {Tk_MakeWindowExist procedure, stacking order and menubars} unixOnly { + catch {destroy .t} + toplevel .t -width 300 -height 200 + wm geometry .t +0+0 + pack [entry .t.e] + frame .t.f -bd 2 -relief raised + testmenubar window .t .t.f + update + # If stacking order isn't handle properly, generates an X error. +} {} +test window-3.2 {Tk_MakeWindowExist procedure, stacking order and menubars} unixOnly { + catch {destroy .t} + toplevel .t -width 300 -height 200 + wm geometry .t +0+0 + pack [entry .t.e] + pack [entry .t.e2] + update + frame .t.f -bd 2 -relief raised + raise .t.f .t.e + testmenubar window .t .t.f + update + # If stacking order isn't handled properly, generates an X error. +} {} + +test window-4.1 {Tk_NameToWindow procedure} { + catch {destroy .t} + list [catch {winfo geometry .t} msg] $msg +} {1 {bad window path name ".t"}} +test window-4.2 {Tk_NameToWindow procedure} { + catch {destroy .t} + frame .t -width 100 -height 50 + place .t -x 10 -y 10 + update + list [catch {winfo geometry .t} msg] $msg +} {0 100x50+10+10} + +test window-5.1 {Tk_MakeWindowExist procedure, stacking order and menubars} unixOnly { + catch {destroy .t} + toplevel .t -width 300 -height 200 + wm geometry .t +0+0 + pack [entry .t.e] + pack [entry .t.e2] + frame .t.f -bd 2 -relief raised + testmenubar window .t .t.f + update + lower .t.e2 .t.f + update + # If stacking order isn't handled properly, generates an X error. +} {} diff --git a/tests/winfo.test b/tests/winfo.test new file mode 100644 index 0000000..5d7292f --- /dev/null +++ b/tests/winfo.test @@ -0,0 +1,361 @@ +# This file is a Tcl script to test out the "winfo" command. It is +# organized in the standard fashion for Tcl tests. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) winfo.test 1.19 97/05/16 08:49:01 + +if {[info procs test] != "test"} { + source defs +} + +foreach i [winfo children .] { + catch {destroy $i} +} +wm geometry . {} +raise . + +# eatColors -- +# Creates a toplevel window and allocates enough colors in it to +# use up all the slots in the colormap. +# +# Arguments: +# w - Name of toplevel window to create. +# options - Options for w, such as "-colormap new". + +proc eatColors {w {options ""}} { + catch {destroy $w} + eval toplevel $w $options + wm geom $w +0+0 + canvas $w.c -width 400 -height 200 -bd 0 + pack $w.c + for {set y 0} {$y < 8} {incr y} { + for {set x 0} {$x < 40} {incr x} { + set color [format #%02x%02x%02x [expr $x*6] [expr $y*30] 0] + $w.c create rectangle [expr 10*$x] [expr 20*$y] \ + [expr 10*$x + 10] [expr 20*$y + 20] -outline {} \ + -fill $color + } + } + update +} + +# XXX - This test file is woefully incomplete. At present, only a +# few of the winfo options are tested. + +test winfo-1.1 {"winfo atom" command} { + list [catch {winfo atom} msg] $msg +} {1 {wrong # args: should be "winfo atom ?-displayof window? name"}} +test winfo-1.2 {"winfo atom" command} { + list [catch {winfo atom a b} msg] $msg +} {1 {wrong # args: should be "winfo atom ?-displayof window? name"}} +test winfo-1.3 {"winfo atom" command} { + list [catch {winfo atom a b c d} msg] $msg +} {1 {wrong # args: should be "winfo atom ?-displayof window? name"}} +test winfo-1.4 {"winfo atom" command} { + list [catch {winfo atom -displayof geek foo} msg] $msg +} {1 {bad window path name "geek"}} +test winfo-1.5 {"winfo atom" command} { + winfo atom PRIMARY +} 1 +test winfo-1.6 {"winfo atom" command} { + winfo atom -displayof . PRIMARY +} 1 + +test winfo-2.1 {"winfo atomname" command} { + list [catch {winfo atomname} msg] $msg +} {1 {wrong # args: should be "winfo atomname ?-displayof window? id"}} +test winfo-2.2 {"winfo atomname" command} { + list [catch {winfo atomname a b} msg] $msg +} {1 {wrong # args: should be "winfo atomname ?-displayof window? id"}} +test winfo-2.3 {"winfo atomname" command} { + list [catch {winfo atomname a b c d} msg] $msg +} {1 {wrong # args: should be "winfo atomname ?-displayof window? id"}} +test winfo-2.4 {"winfo atomname" command} { + list [catch {winfo atomname -displayof geek foo} msg] $msg +} {1 {bad window path name "geek"}} +test winfo-2.5 {"winfo atomname" command} { + list [catch {winfo atomname 44215} msg] $msg +} {1 {no atom exists with id "44215"}} +test winfo-2.6 {"winfo atomname" command} { + winfo atomname 2 +} SECONDARY +test winfo-2.7 {"winfo atom" command} { + winfo atomname -displayof . 2 +} SECONDARY + +if {([winfo depth .] == 8) && ([winfo visual .] == "pseudocolor")} { + test winfo-3.1 {"winfo colormapfull" command} { + list [catch {winfo colormapfull} msg] $msg + } {1 {wrong # args: should be "winfo colormapfull window"}} + test winfo-3.2 {"winfo colormapfull" command} { + list [catch {winfo colormapfull a b} msg] $msg + } {1 {wrong # args: should be "winfo colormapfull window"}} + test winfo-3.3 {"winfo colormapfull" command} { + list [catch {winfo colormapfull foo} msg] $msg + } {1 {bad window path name "foo"}} + test winfo-3.4 {"winfo colormapfull" command} {macOrUnix} { + eatColors .t {-colormap new} + set result [list [winfo colormapfull .] [winfo colormapfull .t]] + .t.c delete 34 + lappend result [winfo colormapfull .t] + .t.c create rectangle 30 30 80 80 -fill #441739 + lappend result [winfo colormapfull .t] + .t.c create rectangle 40 40 90 90 -fill #ffeedd + lappend result [winfo colormapfull .t] + destroy .t.c + lappend result [winfo colormapfull .t] + } {0 1 0 0 1 0} + catch {destroy .t} +} + +catch {destroy .t} +toplevel .t -width 550 -height 400 +frame .t.f -width 80 -height 60 -bd 2 -relief raised +place .t.f -x 50 -y 50 +wm geom .t +0+0 +update +test winfo-4.1 {"winfo containing" command} { + list [catch {winfo containing 22} msg] $msg +} {1 {wrong # args: should be "winfo containing ?-displayof window? rootX rootY"}} +test winfo-4.2 {"winfo containing" command} { + list [catch {winfo containing a b c} msg] $msg +} {1 {wrong # args: should be "winfo containing ?-displayof window? rootX rootY"}} +test winfo-4.3 {"winfo containing" command} { + list [catch {winfo containing a b c d e} msg] $msg +} {1 {wrong # args: should be "winfo containing ?-displayof window? rootX rootY"}} +test winfo-4.4 {"winfo containing" command} { + list [catch {winfo containing -displayof geek 25 30} msg] $msg +} {1 {bad window path name "geek"}} +test winfo-4.5 {"winfo containing" command} { + winfo containing [winfo rootx .t.f] [winfo rooty .t.f] +} .t.f +test winfo-4.6 {"winfo containing" command} {nonPortable} { + winfo containing [expr [winfo rootx .t.f]-1] [expr [winfo rooty .t.f]-1] +} .t +test winfo-4.7 {"winfo containing" command} { + set x [winfo containing -display .t.f [expr [winfo rootx .t]+600] \ + [expr [winfo rooty .t.f]+450]] + expr {($x == ".") || ($x == "")} +} {1} +destroy .t + +test winfo-5.1 {"winfo interps" command} { + list [catch {winfo interps a} msg] $msg +} {1 {wrong # args: should be "winfo interps ?-displayof window?"}} +test winfo-5.2 {"winfo interps" command} { + list [catch {winfo interps a b c} msg] $msg +} {1 {wrong # args: should be "winfo interps ?-displayof window?"}} +test winfo-5.3 {"winfo interps" command} { + list [catch {winfo interps -displayof geek} msg] $msg +} {1 {bad window path name "geek"}} +test winfo-5.4 {"winfo interps" command} {unixOnly} { + expr [lsearch -exact [winfo interps] [tk appname]] >= 0 +} {1} +test winfo-5.5 {"winfo interps" command} {unixOnly} { + expr [lsearch -exact [winfo interps -displayof .] [tk appname]] >= 0 +} {1} + +test winfo-6.1 {"winfo exists" command} { + list [catch {winfo exists} msg] $msg +} {1 {wrong # args: should be "winfo exists window"}} +test winfo-6.2 {"winfo exists" command} { + list [catch {winfo exists a b} msg] $msg +} {1 {wrong # args: should be "winfo exists window"}} +test winfo-6.3 {"winfo exists" command} { + winfo exists gorp +} {0} +test winfo-6.4 {"winfo exists" command} { + winfo exists . +} {1} +test winfo-6.5 {"winfo exists" command} { + button .b -text "Test button" + set x [winfo exists .b] + pack .b + update + bind .b <Destroy> {lappend x [winfo exists .x]} + destroy .b + lappend x [winfo exists .x] +} {1 0 0} + +catch {destroy .b} +button .b -text "Help" +update +test winfo-7.1 {"winfo pathname" command} { + list [catch {winfo pathname} msg] $msg +} {1 {wrong # args: should be "winfo pathname ?-displayof window? id"}} +test winfo-7.2 {"winfo pathname" command} { + list [catch {winfo pathname a b} msg] $msg +} {1 {wrong # args: should be "winfo pathname ?-displayof window? id"}} +test winfo-7.3 {"winfo pathname" command} { + list [catch {winfo pathname a b c d} msg] $msg +} {1 {wrong # args: should be "winfo pathname ?-displayof window? id"}} +test winfo-7.4 {"winfo pathname" command} { + list [catch {winfo pathname -displayof geek 25} msg] $msg +} {1 {bad window path name "geek"}} +test winfo-7.5 {"winfo pathname" command} { + list [catch {winfo pathname xyz} msg] $msg +} {1 {expected integer but got "xyz"}} +test winfo-7.6 {"winfo pathname" command} { + list [catch {winfo pathname 224} msg] $msg +} {1 {window id "224" doesn't exist in this application}} +test winfo-7.7 {"winfo pathname" command} { + winfo pathname -displayof .b [winfo id .] +} {.} +test winfo-7.8 {"winfo pathname" command} {unixOnly} { + winfo pathname [testwrapper .] +} {} + +test winfo-8.1 {"winfo pointerx" command} { + catch [winfo pointerx .b] +} 1 +test winfo-8.2 {"winfo pointery" command} { + catch [winfo pointery .b] +} 1 +test winfo-8.3 {"winfo pointerxy" command} { + catch [winfo pointerxy .b] +} 1 + +test winfo-9.1 {"winfo viewable" command} { + list [catch {winfo viewable} msg] $msg +} {1 {wrong # args: should be "winfo viewable window"}} +test winfo-9.2 {"winfo viewable" command} { + list [catch {winfo viewable foo} msg] $msg +} {1 {bad window path name "foo"}} +test winfo-9.3 {"winfo viewable" command} { + winfo viewable . +} {1} +test winfo-9.4 {"winfo viewable" command} { + wm iconify . + winfo viewable . +} {0} +wm deiconify . +test winfo-9.5 {"winfo viewable" command} { + frame .f1 -width 100 -height 100 -relief raised -bd 2 + place .f1 -x 0 -y 0 + frame .f1.f2 -width 50 -height 50 -relief raised -bd 2 + place .f1.f2 -x 0 -y 0 + update + list [winfo viewable .f1] [winfo viewable .f1.f2] +} {1 1} +test winfo-9.6 {"winfo viewable" command} { + eval destroy [winfo child .] + frame .f1 -width 100 -height 100 -relief raised -bd 2 + frame .f1.f2 -width 50 -height 50 -relief raised -bd 2 + place .f1.f2 -x 0 -y 0 + update + list [winfo viewable .f1] [winfo viewable .f1.f2] +} {0 0} +test winfo-9.7 {"winfo viewable" command} { + eval destroy [winfo child .] + frame .f1 -width 100 -height 100 -relief raised -bd 2 + place .f1 -x 0 -y 0 + frame .f1.f2 -width 50 -height 50 -relief raised -bd 2 + place .f1.f2 -x 0 -y 0 + update + wm iconify . + list [winfo viewable .f1] [winfo viewable .f1.f2] +} {0 0} +wm deiconify . +eval destroy [winfo child .] + +test winfo-10.1 {"winfo visualid" command} { + list [catch {winfo visualid} msg] $msg +} {1 {wrong # args: should be "winfo visualid window"}} +test winfo-10.2 {"winfo visualid" command} { + list [catch {winfo visualid gorp} msg] $msg +} {1 {bad window path name "gorp"}} +test winfo-10.3 {"winfo visualid" command} { + expr 2+[winfo visualid .]-[winfo visualid .] +} {2} + +test winfo-11.1 {"winfo visualid" command} { + list [catch {winfo visualsavailable} msg] $msg +} {1 {wrong # args: should be "winfo visualsavailable window ?includeids?"}} +test winfo-11.2 {"winfo visualid" command} { + list [catch {winfo visualsavailable gorp} msg] $msg +} {1 {bad window path name "gorp"}} +test winfo-11.3 {"winfo visualid" command} { + list [catch {winfo visualsavailable . includeids foo} msg] $msg +} {1 {wrong # args: should be "winfo visualsavailable window ?includeids?"}} +test winfo-11.4 {"winfo visualid" command} { + llength [lindex [winfo visualsa .] 0] +} {2} +test winfo-11.5 {"winfo visualid" command} { + llength [lindex [winfo visualsa . includeids] 0] +} {3} +test winfo-11.6 {"winfo visualid" command} { + set x [lindex [lindex [winfo visualsa . includeids] 0] 2] + expr $x + 2 - $x +} {2} + +test winfo-12.1 {GetDisplayOf procedure} { + list [catch {winfo atom - foo x} msg] $msg +} {1 {wrong # args: should be "winfo atom ?-displayof window? name"}} +test winfo-12.2 {GetDisplayOf procedure} { + list [catch {winfo atom -d bad_window x} msg] $msg +} {1 {bad window path name "bad_window"}} + +# Some embedding tests +# + +proc MakeEmbed {} { + frame .con -container 1 + pack .con -expand yes -fill both + toplevel .emb -use [winfo id .con] -bd 0 -highlightthickness 0 + button .emb.b + pack .emb.b -expand yes -fill both + update +} +test winfo-13.1 {root coordinates of embedded toplevel} {macOrUnix} { + MakeEmbed + set z [expr [winfo rootx .emb] == [winfo rootx .con] && \ + [winfo rooty .emb] == [winfo rooty .con]] + destroy .emb + destroy .con + set z +} {1} +test winfo-13.2 {destroying embedded toplevel} {macOrUnix} { + catch {destroy .emb} + update + expr [winfo exists .emb.b] || [winfo exists .con] +} 0 + +foreach i [winfo children .] { + destroy $i +} + +test winfo-13.3 {destroying container window} {macOrUnix} { + MakeEmbed + destroy .con + update + set z [expr [winfo exists .emb.b] || [winfo exists .emb]] + catch {destroy .emb} + catch {destroy .con} + set z +} 0 + +foreach i [winfo children .] { + destroy $i +} + +test winfo-13.4 {[winfo containing] with embedded windows} {macOrUnix} { + MakeEmbed + button .b + pack .b -expand yes -fill both + update + + set z [string compare \ + [winfo containing [winfo rootx .emb.b] [winfo rooty .emb.b]] .emb.b] + catch {destroy .con} + catch {destroy .emb} + set z +} 0 + +foreach i [winfo children .] { + catch {destroy $i} +} diff --git a/unix/Makefile.in b/unix/Makefile.in new file mode 100644 index 0000000..51b9723 --- /dev/null +++ b/unix/Makefile.in @@ -0,0 +1,1003 @@ +# +# This file is a Makefile for Tk. If it has the name "Makefile.in" +# then it is a template for a Makefile; to generate the actual Makefile, +# run "./configure", which is a configuration script generated by the +# "autoconf" program (constructs like "@foo@" will get replaced in the +# actual Makefile. +# +# SCCS: @(#) Makefile.in 1.146 97/11/05 11:10:45 + +# Current Tk version; used in various names. + +TCLVERSION = @TCL_VERSION@ +VERSION = @TK_VERSION@ + +#---------------------------------------------------------------- +# Things you can change to personalize the Makefile for your own +# site (you can make these changes in either Makefile.in or +# Makefile, but changes to Makefile will get lost if you re-run +# the configuration script). +#---------------------------------------------------------------- + +# Default top-level directories in which to install architecture- +# specific files (exec_prefix) and machine-independent files such +# as scripts (prefix). The values specified here may be overridden +# at configure-time with the --exec-prefix and --prefix options +# to the "configure" script. + +prefix = @prefix@ +exec_prefix = @exec_prefix@ + +# The following definition can be set to non-null for special systems +# like AFS with replication. It allows the pathnames used for installation +# to be different than those used for actually reference files at +# run-time. INSTALL_ROOT is prepended to $prefix and $exec_prefix +# when installing files. +INSTALL_ROOT = + +# Directory from which applications will reference the library of Tcl +# scripts (note: you can set the TK_LIBRARY environment variable at +# run-time to override the compiled-in location): +TK_LIBRARY = $(prefix)/lib/tk$(VERSION) + +# Path name to use when installing library scripts: +SCRIPT_INSTALL_DIR = $(INSTALL_ROOT)$(TK_LIBRARY) + +# Directory in which to install the .a or .so binary for the Tk library: +LIB_INSTALL_DIR = $(INSTALL_ROOT)$(exec_prefix)/lib + +# Path to use at runtime to refer to LIB_INSTALL_DIR: +LIB_RUNTIME_DIR = $(exec_prefix)/lib + +# Directory in which to install the program wish: +BIN_INSTALL_DIR = $(INSTALL_ROOT)$(exec_prefix)/bin + +# Directory from which the program wish should be referenced by scripts: +BIN_DIR = $(exec_prefix)/bin + +# Directory in which to install the include file tk.h: +INCLUDE_INSTALL_DIR = $(INSTALL_ROOT)$(prefix)/include + +# Top-level directory for manual entries: +MAN_INSTALL_DIR = $(INSTALL_ROOT)$(prefix)/man + +# Directory in which to install manual entry for wish: +MAN1_INSTALL_DIR = $(MAN_INSTALL_DIR)/man1 + +# Directory in which to install manual entries for Tk's C library +# procedures: +MAN3_INSTALL_DIR = $(MAN_INSTALL_DIR)/man3 + +# Directory in which to install manual entries for the built-in +# Tcl commands implemented by Tk: +MANN_INSTALL_DIR = $(MAN_INSTALL_DIR)/mann + +# The directory containing the Tcl sources and headers appropriate +# for this version of Tk ("srcdir" will be replaced or has already +# been replaced by the configure script): +TCL_GENERIC_DIR = @TCL_SRC_DIR@/generic + +# The directory containing the Tcl library archive file appropriate +# for this version of Tk: +TCL_BIN_DIR = @TCL_BIN_DIR@ + +# A "-I" switch that can be used when compiling to make all of the +# X11 include files accessible (the configure script will try to +# set this value, and will cause it to be an empty string if the +# include files are accessible via /usr/include). +X11_INCLUDES = @XINCLUDES@ + +# Linker switch(es) to use to link with the X11 library archive (the +# configure script will try to set this value automatically, but you +# can override it). +X11_LIB_SWITCHES = @XLIBSW@ + +# Libraries to use when linking. This definition is determined by the +# configure script. +LIBS = @TCL_BUILD_LIB_SPEC@ @LIBS@ $(X11_LIB_SWITCHES) @DL_LIBS@ @MATH_LIBS@ -lc + +# To change the compiler switches, for example to change from -O +# to -g, change the following line: +CFLAGS = -O + +# To turn off the security checks that disallow incoming sends when +# the X server appears to be insecure, reverse the comments on the +# following lines: +SECURITY_FLAGS = +#SECURITY_FLAGS = -DTK_NO_SECURITY + +# To disable ANSI-C procedure prototypes reverse the comment characters +# on the following lines: +PROTO_FLAGS = +#PROTO_FLAGS = -DNO_PROTOTYPE + +# To enable memory debugging reverse the comment characters on the following +# lines. Warning: if you enable memory debugging, you must do it +# *everywhere*, including all the code that calls Tcl, and you must use +# ckalloc and ckfree everywhere instead of malloc and free. +MEM_DEBUG_FLAGS = +#MEM_DEBUG_FLAGS = -DTCL_MEM_DEBUG + +# If your X server is X11R4 or earlier, then you may wish to reverse +# the comment characters on the following two lines. This will enable +# extra code to speed up XStringToKeysym. In X11R5 and later releases +# XStringToKeysym is plenty fast, so you needn't define REDO_KEYSYM_LOOKUP. +KEYSYM_FLAGS = +#KEYSYM_FLAGS = -DREDO_KEYSYM_LOOKUP + +# Some versions of make, like SGI's, use the following variable to +# determine which shell to use for executing commands: +SHELL = /bin/sh + +# Tk used to let the configure script choose which program to use +# for installing, but there are just too many different versions of +# "install" around; better to use the install-sh script that comes +# with the distribution, which is slower but guaranteed to work. + +INSTALL = @srcdir@/install-sh -c +INSTALL_PROGRAM = ${INSTALL} +INSTALL_DATA = ${INSTALL} -m 644 + + +# The symbols below provide support for dynamic loading and shared +# libraries. The values of the symbols are normally set by the +# configure script. You shouldn't normally need to modify any of +# these definitions by hand. + +TK_SHLIB_CFLAGS = @TK_SHLIB_CFLAGS@ + +TK_LIB_FILE = @TK_LIB_FILE@ +#TK_LIB_FILE = libtk.a + +# The symbol below provides support for dynamic loading and shared +# libraries. See configure.in for a description of what it means. +# The values of the symbolis normally set by the configure script. + +SHLIB_LD = @SHLIB_LD@ + +# Additional search flags needed to find the various shared libraries +# at run-time. The first symbol is for use when creating a binary +# with cc, and the second is for use when running ld directly. +TK_CC_SEARCH_FLAGS = @TK_CC_SEARCH_FLAGS@ +TK_LD_SEARCH_FLAGS = @TK_LD_SEARCH_FLAGS@ + +#---------------------------------------------------------------- +# The information below is modified by the configure script when +# Makefile is generated from Makefile.in. You shouldn't normally +# modify any of this stuff by hand. +#---------------------------------------------------------------- + +AC_FLAGS = @DEFS@ +RANLIB = @RANLIB@ +SRC_DIR = @srcdir@/.. +TOP_DIR = @srcdir@/.. +GENERIC_DIR = $(TOP_DIR)/generic +UNIX_DIR = @srcdir@ +BMAP_DIR = $(TOP_DIR)/bitmaps +TOOL_DIR = @TCL_SRC_DIR@/tools + +#---------------------------------------------------------------- +# The information below should be usable as is. The configure +# script won't modify it and you shouldn't need to modify it +# either. +#---------------------------------------------------------------- + + +CC = @CC@ +CC_SWITCHES = ${CFLAGS} ${TK_SHLIB_CFLAGS} -I${UNIX_DIR} -I${GENERIC_DIR} \ +-I${BMAP_DIR} -I${TCL_GENERIC_DIR} ${X11_INCLUDES} ${AC_FLAGS} ${PROTO_FLAGS} \ +${SECURITY_FLAGS} ${MEM_DEBUG_FLAGS} ${KEYSYM_FLAGS} + +DEPEND_SWITCHES = ${CFLAGS} -I${UNIX_DIR} -I${GENERIC_DIR} \ +-I${BMAP_DIR} \ +-I${TCL_GENERIC_DIR} ${X11_INCLUDES} \ +${AC_FLAGS} ${PROTO_FLAGS} ${SECURITY_FLAGS} ${MEM_DEBUG_FLAGS} \ +${KEYSYM_FLAGS} + +WISH_OBJS = tkAppInit.o + +TKTEST_OBJS = tkTestInit.o tkTest.o tkSquare.o + +WIDGOBJS = tkButton.o tkEntry.o tkFrame.o tkListbox.o \ + tkMenu.o tkMenubutton.o tkMenuDraw.o tkMessage.o tkScale.o \ + tkScrollbar.o + +CANVOBJS = tkCanvas.o tkCanvArc.o tkCanvBmap.o tkCanvImg.o \ + tkCanvLine.o tkCanvPoly.o tkCanvPs.o tkCanvText.o \ + tkCanvUtil.o tkCanvWind.o tkRectOval.o tkTrig.o + +IMAGEOBJS = tkImage.o tkImgBmap.o tkImgGIF.o tkImgPPM.o tkImgPhoto.o + +TEXTOBJS = tkText.o tkTextBTree.o tkTextDisp.o tkTextImage.o tkTextIndex.o \ + tkTextMark.o tkTextTag.o tkTextWind.o + +UNIXOBJS = tkUnix.o tkUnix3d.o tkUnixButton.o tkUnixColor.o tkUnixCursor.o \ + tkUnixDialog.o tkUnixDraw.o \ + tkUnixEmbed.o tkUnixEvent.o tkUnixFocus.o tkUnixFont.o tkUnixInit.o \ + tkUnixMenu.o tkUnixMenubu.o tkUnixScale.o tkUnixScrlbr.o \ + tkUnixSelect.o tkUnixSend.o tkUnixWm.o tkUnixXId.o + +OBJS = tk3d.o tkArgv.o tkAtom.o tkBind.o tkBitmap.o tkClipboard.o tkCmds.o \ + tkColor.o tkConfig.o tkCursor.o tkError.o tkEvent.o \ + tkFocus.o tkFont.o tkGet.o tkGC.o tkGeometry.o tkGrab.o tkGrid.o \ + tkMain.o tkOption.o tkPack.o tkPlace.o \ + tkSelect.o tkUtil.o tkVisual.o tkWindow.o \ + $(UNIXOBJS) $(WIDGOBJS) $(CANVOBJS) $(IMAGEOBJS) $(TEXTOBJS) + +SRCS = \ + $(GENERIC_DIR)/tk3d.c $(GENERIC_DIR)/tkArgv.c \ + $(GENERIC_DIR)/tkAtom.c $(GENERIC_DIR)/tkBind.c \ + $(GENERIC_DIR)/tkBitmap.c $(GENERIC_DIR)/tkClipboard.c \ + $(GENERIC_DIR)/tkCmds.c $(GENERIC_DIR)/tkColor.c \ + $(GENERIC_DIR)/tkConfig.c $(GENERIC_DIR)/tkCursor.c \ + $(GENERIC_DIR)/tkError.c $(GENERIC_DIR)/tkEvent.c \ + $(GENERIC_DIR)/tkFocus.c $(GENERIC_DIR)/tkFont.c \ + $(GENERIC_DIR)/tkGet.c $(GENERIC_DIR)/tkGC.c \ + $(GENERIC_DIR)/tkGeometry.c $(GENERIC_DIR)/tkGrab.c \ + $(GENERIC_DIR)/tkGrid.c \ + $(GENERIC_DIR)/tkMain.c $(GENERIC_DIR)/tkOption.c \ + $(GENERIC_DIR)/tkPack.c $(GENERIC_DIR)/tkPlace.c \ + $(GENERIC_DIR)/tkSelect.c $(GENERIC_DIR)/tkUtil.c \ + $(GENERIC_DIR)/tkVisual.c $(GENERIC_DIR)/tkWindow.c \ + $(GENERIC_DIR)/tkButton.c \ + $(GENERIC_DIR)/tkEntry.c $(GENERIC_DIR)/tkFrame.c \ + $(GENERIC_DIR)/tkListbox.c $(GENERIC_DIR)/tkMenu.c \ + $(GENERIC_DIR)/tkMenubutton.c $(GENERIC_DIR)/tkMenuDraw.c \ + $(GENERIC_DIR)/tkMessage.c \ + $(GENERIC_DIR)/tkScale.c $(GENERIC_DIR)/tkScrollbar.c \ + $(GENERIC_DIR)/tkCanvas.c $(GENERIC_DIR)/tkCanvArc.c \ + $(GENERIC_DIR)/tkCanvBmap.c $(GENERIC_DIR)/tkCanvImg.c \ + $(GENERIC_DIR)/tkCanvLine.c $(GENERIC_DIR)/tkCanvPoly.c \ + $(GENERIC_DIR)/tkCanvPs.c $(GENERIC_DIR)/tkCanvText.c \ + $(GENERIC_DIR)/tkCanvUtil.c \ + $(GENERIC_DIR)/tkCanvWind.c $(GENERIC_DIR)/tkRectOval.c \ + $(GENERIC_DIR)/tkTrig.c $(GENERIC_DIR)/tkImage.c \ + $(GENERIC_DIR)/tkImgBmap.c $(GENERIC_DIR)/tkImgGIF.c \ + $(GENERIC_DIR)/tkImgPPM.c \ + $(GENERIC_DIR)/tkImgPhoto.c $(GENERIC_DIR)/tkText.c \ + $(GENERIC_DIR)/tkTextBTree.c $(GENERIC_DIR)/tkTextDisp.c \ + $(GENERIC_DIR)/tkTextImage.c \ + $(GENERIC_DIR)/tkTextIndex.c $(GENERIC_DIR)/tkTextMark.c \ + $(GENERIC_DIR)/tkTextTag.c $(GENERIC_DIR)/tkTextWind.c \ + $(GENERIC_DIR)/tkSquare.c $(GENERIC_DIR)/tkTest.c \ + $(UNIX_DIR)/tkAppInit.c $(UNIX_DIR)/tkUnix.c \ + $(UNIX_DIR)/tkUnix3d.c \ + $(UNIX_DIR)/tkUnixButton.c $(UNIX_DIR)/tkUnixColor.c \ + $(UNIX_DIR)/tkUnixCursor.c \ + $(UNIX_DIR)/tkUnixDialog.c $(UNIX_DIR)/tkUnixDraw.c \ + $(UNIX_DIR)/tkUnixEmbed.c $(UNIX_DIR)/tkUnixEvent.c \ + $(UNIX_DIR)/tkUnixFocus.c \ + $(UNIX_DIR)/tkUnixFont.c $(UNIX_DIR)/tkUnixInit.c \ + $(UNIX_DIR)/tkUnixMenu.c $(UNIX_DIR)/tkUnixMenubu.c \ + $(UNIX_DIR)/tkUnixScale.c $(UNIX_DIR)/tkUnixScrlbr.c \ + $(UNIX_DIR)/tkUnixSelect.c \ + $(UNIX_DIR)/tkUnixSend.c $(UNIX_DIR)/tkUnixWm.c \ + $(UNIX_DIR)/tkUnixXId.c + + +HDRS = bltList.h \ + default.h ks_names.h tkPatch.h tk.h tkButton.h tkCanvas.h tkInt.h \ + tkPort.h tkScrollbar.h tkText.h + +DEMOPROGS = browse hello ixset rmt rolodex square tcolor timer widget + +all: wish + +# The following target is configured by autoconf to generate either +# a shared library or non-shared library for Tk. +@TK_LIB_FILE@: ${OBJS} + rm -f @TK_LIB_FILE@ + @MAKE_LIB@ + $(RANLIB) @TK_LIB_FILE@ + +# Make target which outputs the list of the .o contained in the Tk lib +# usefull to build a single big shared library containing Tcl/Tk and other +# extensions. used for the Tcl Plugin. -- dl +tkLibObjs: + @echo ${OBJS} +# This targets actually build the objects needed for the lib in the above +# case +objs: ${OBJS} + + +wish: $(WISH_OBJS) $(TK_LIB_FILE) + $(CC) @LD_FLAGS@ $(WISH_OBJS) @TK_BUILD_LIB_SPEC@ $(LIBS) \ + $(TK_CC_SEARCH_FLAGS) -o wish + +tktest: $(TKTEST_OBJS) $(TK_LIB_FILE) + ${CC} @LD_FLAGS@ $(TKTEST_OBJS) @TK_BUILD_LIB_SPEC@ $(LIBS) \ + $(TK_CC_SEARCH_FLAGS) -o tktest + +xttest: test.o tkTest.o tkSquare.o $(TK_LIB_FILE) + ${CC} @LD_FLAGS@ test.o tkTest.o tkSquare.o \ + @TK_BUILD_LIB_SPEC@ $(LIBS) \ + @TK_LD_SEARCH_FLAGS@ -lXt -o xttest + +# Note, in the target below TCL_LIBRARY needs to be set or else +# "make test" won't work in the case where the compilation directory +# isn't the same as the source directory. + +test: tktest + LD_LIBRARY_PATH=`pwd`:${TCL_BIN_DIR}:${LD_LIBRARY_PATH}; \ + export LD_LIBRARY_PATH; \ + TCL_LIBRARY=@TCL_SRC_DIR@/library; export TCL_LIBRARY; \ + TK_LIBRARY=$(TOP_DIR)/library; export TK_LIBRARY; \ + ( echo cd $(TOP_DIR)/tests\; source all\; exit ) \ + | ./tktest -geometry +0+0 + + +# Useful target to launch a built tktest with the proper path,... +runtest: + LD_LIBRARY_PATH=`pwd`:${TCL_BIN_DIR}:${LD_LIBRARY_PATH}; \ + export LD_LIBRARY_PATH; \ + TCL_LIBRARY=@TCL_SRC_DIR@/library; export TCL_LIBRARY; \ + TK_LIBRARY=$(TOP_DIR)/library; export TK_LIBRARY; \ + ./tktest + +install: install-binaries install-libraries install-demos install-man + +# Note: before running ranlib below, must cd to target directory because +# some ranlibs write to current directory, and this might not always be +# possible (e.g. if installing as root). + +install-binaries: $(TK_LIB_FILE) wish + @for i in $(LIB_INSTALL_DIR) $(BIN_INSTALL_DIR) ; \ + do \ + if [ ! -d $$i ] ; then \ + echo "Making directory $$i"; \ + mkdir $$i; \ + chmod 755 $$i; \ + else true; \ + fi; \ + done; + @echo "Installing $(TK_LIB_FILE)" + @$(INSTALL_DATA) $(TK_LIB_FILE) $(LIB_INSTALL_DIR)/$(TK_LIB_FILE) + @(cd $(LIB_INSTALL_DIR); $(RANLIB) $(TK_LIB_FILE)) + @chmod 555 $(LIB_INSTALL_DIR)/$(TK_LIB_FILE) + @echo "Installing wish" + @$(INSTALL_PROGRAM) wish $(BIN_INSTALL_DIR)/wish$(VERSION) + @echo "Installing tkConfig.sh" + @$(INSTALL_DATA) tkConfig.sh $(LIB_INSTALL_DIR)/tkConfig.sh + +install-libraries: + @for i in $(INSTALL_ROOT)$(prefix)/lib $(INCLUDE_INSTALL_DIR) \ + $(SCRIPT_INSTALL_DIR) $(SCRIPT_INSTALL_DIR)/images; \ + do \ + if [ ! -d $$i ] ; then \ + echo "Making directory $$i"; \ + mkdir $$i; \ + chmod 755 $$i; \ + else true; \ + fi; \ + done; + @echo "Installing tk.h" + @$(INSTALL_DATA) $(GENERIC_DIR)/tk.h $(INCLUDE_INSTALL_DIR)/tk.h + for i in $(SRC_DIR)/library/*.tcl $(SRC_DIR)/library/tclIndex $(SRC_DIR)/library/prolog.ps $(UNIX_DIR)/tkAppInit.c; \ + do \ + echo "Installing $$i"; \ + $(INSTALL_DATA) $$i $(SCRIPT_INSTALL_DIR); \ + done; + for i in $(SRC_DIR)/library/images/*; \ + do \ + if [ -f $$i ] ; then \ + echo "Installing $$i"; \ + $(INSTALL_DATA) $$i $(SCRIPT_INSTALL_DIR)/images; \ + fi; \ + done; + +install-demos: + @for i in $(INSTALL_ROOT)$(prefix)/lib $(SCRIPT_INSTALL_DIR) \ + $(SCRIPT_INSTALL_DIR)/demos \ + $(SCRIPT_INSTALL_DIR)/demos/images ; \ + do \ + if [ ! -d $$i ] ; then \ + echo "Making directory $$i"; \ + mkdir $$i; \ + chmod 755 $$i; \ + else true; \ + fi; \ + done; + @for i in $(SRC_DIR)/library/demos/*; \ + do \ + if [ -f $$i ] ; then \ + echo "Installing $$i"; \ + sed -e '3 s|exec wish|exec wish$(VERSION)|' \ + $$i > $(SCRIPT_INSTALL_DIR)/demos/`basename $$i`; \ + fi; \ + done; + @for i in $(DEMOPROGS); \ + do \ + chmod 755 $(SCRIPT_INSTALL_DIR)/demos/$$i; \ + done; + @for i in $(SRC_DIR)/library/demos/images/*; \ + do \ + if [ -f $$i ] ; then \ + echo "Installing $$i"; \ + $(INSTALL_DATA) $$i $(SCRIPT_INSTALL_DIR)/demos/images; \ + fi; \ + done; + +install-man: + @for i in $(MAN_INSTALL_DIR) $(MAN1_INSTALL_DIR) $(MAN3_INSTALL_DIR) $(MANN_INSTALL_DIR) ; \ + do \ + if [ ! -d $$i ] ; then \ + echo "Making directory $$i"; \ + mkdir $$i; \ + chmod 755 $$i; \ + else true; \ + fi; \ + done; + @cd $(SRC_DIR)/doc; for i in *.1; \ + do \ + echo "Installing doc/$$i"; \ + rm -f $(MAN1_INSTALL_DIR)/$$i; \ + sed -e '/man\.macros/r man.macros' -e '/man\.macros/d' \ + $$i > $(MAN1_INSTALL_DIR)/$$i; \ + chmod 444 $(MAN1_INSTALL_DIR)/$$i; \ + done; + $(UNIX_DIR)/mkLinks $(MAN1_INSTALL_DIR) + @cd $(SRC_DIR)/doc; for i in *.3; \ + do \ + echo "Installing doc/$$i"; \ + rm -f $(MAN3_INSTALL_DIR)/$$i; \ + sed -e '/man\.macros/r man.macros' -e '/man\.macros/d' \ + $$i > $(MAN3_INSTALL_DIR)/$$i; \ + chmod 444 $(MAN3_INSTALL_DIR)/$$i; \ + done; + $(UNIX_DIR)/mkLinks $(MAN3_INSTALL_DIR) + @cd $(SRC_DIR)/doc; for i in *.n; \ + do \ + echo "Installing doc/$$i"; \ + rm -f $(MANN_INSTALL_DIR)/$$i; \ + sed -e '/man\.macros/r man.macros' -e '/man\.macros/d' \ + $$i > $(MANN_INSTALL_DIR)/$$i; \ + chmod 444 $(MANN_INSTALL_DIR)/$$i; \ + done; + $(UNIX_DIR)/mkLinks $(MANN_INSTALL_DIR) + +Makefile: $(UNIX_DIR)/Makefile.in + $(SHELL) config.status + +clean: + rm -f *.a *.o libtk* core errs *~ \#* TAGS *.E a.out errors \ + tktest wish config.info lib.exp + +distclean: clean + rm -f Makefile config.status config.cache config.log tkConfig.sh \ + SUNWtk.* prototype + +depend: + makedepend -- $(DEPEND_SWITCHES) -- $(SRCS) + +# Test binaries. The rule for tkTestInit.o is complicated because +# it is is compiled from tkAppInit.c. Can't use the "-o" option +# because this doesn't work on some strange compilers (e.g. UnixWare). + +tkTestInit.o: $(UNIX_DIR)/tkAppInit.c + @if test -f tkAppInit.o ; then \ + rm -f tkAppInit.sav; \ + mv tkAppInit.o tkAppInit.sav; \ + fi; + $(CC) -c $(CC_SWITCHES) -DTK_TEST $(UNIX_DIR)/tkAppInit.c + rm -f tkTestInit.o + mv tkAppInit.o tkTestInit.o + @if test -f tkAppInit.sav ; then \ + mv tkAppInit.sav tkAppInit.o; \ + fi; + +tk3d.o: $(GENERIC_DIR)/tk3d.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tk3d.c + +tkAppInit.o: $(UNIX_DIR)/tkAppInit.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkAppInit.c + +tkArgv.o: $(GENERIC_DIR)/tkArgv.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkArgv.c + +tkAtom.o: $(GENERIC_DIR)/tkAtom.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkAtom.c + +tkBind.o: $(GENERIC_DIR)/tkBind.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkBind.c + +tkBitmap.o: $(GENERIC_DIR)/tkBitmap.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkBitmap.c + +tkClipboard.o: $(GENERIC_DIR)/tkClipboard.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkClipboard.c + +tkCmds.o: $(GENERIC_DIR)/tkCmds.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCmds.c + +tkColor.o: $(GENERIC_DIR)/tkColor.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkColor.c + +tkConfig.o: $(GENERIC_DIR)/tkConfig.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkConfig.c + +tkCursor.o: $(GENERIC_DIR)/tkCursor.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCursor.c + +tkError.o: $(GENERIC_DIR)/tkError.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkError.c + +tkEvent.o: $(GENERIC_DIR)/tkEvent.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkEvent.c + +tkFocus.o: $(GENERIC_DIR)/tkFocus.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkFocus.c + +tkFont.o: $(GENERIC_DIR)/tkFont.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkFont.c + +tkGet.o: $(GENERIC_DIR)/tkGet.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkGet.c + +tkGC.o: $(GENERIC_DIR)/tkGC.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkGC.c + +tkGeometry.o: $(GENERIC_DIR)/tkGeometry.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkGeometry.c + +tkGrab.o: $(GENERIC_DIR)/tkGrab.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkGrab.c + +tkGrid.o: $(GENERIC_DIR)/tkGrid.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkGrid.c + +tkMain.o: $(GENERIC_DIR)/tkMain.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkMain.c + +tkOption.o: $(GENERIC_DIR)/tkOption.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkOption.c + +tkPack.o: $(GENERIC_DIR)/tkPack.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkPack.c + +tkPlace.o: $(GENERIC_DIR)/tkPlace.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkPlace.c + +tkSelect.o: $(GENERIC_DIR)/tkSelect.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkSelect.c + +tkUtil.o: $(GENERIC_DIR)/tkUtil.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkUtil.c + +tkVisual.o: $(GENERIC_DIR)/tkVisual.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkVisual.c + +tkWindow.o: $(GENERIC_DIR)/tkWindow.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkWindow.c + +tkButton.o: $(GENERIC_DIR)/tkButton.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkButton.c + +tkEntry.o: $(GENERIC_DIR)/tkEntry.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkEntry.c + +tkFrame.o: $(GENERIC_DIR)/tkFrame.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkFrame.c + +tkListbox.o: $(GENERIC_DIR)/tkListbox.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkListbox.c + +tkMenu.o: $(GENERIC_DIR)/tkMenu.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkMenu.c + +tkMenubutton.o: $(GENERIC_DIR)/tkMenubutton.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkMenubutton.c + +tkMenuDraw.o: $(GENERIC_DIR)/tkMenuDraw.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkMenuDraw.c + +tkMessage.o: $(GENERIC_DIR)/tkMessage.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkMessage.c + +tkScale.o: $(GENERIC_DIR)/tkScale.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkScale.c + +tkScrollbar.o: $(GENERIC_DIR)/tkScrollbar.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkScrollbar.c + +tkSquare.o: $(GENERIC_DIR)/tkSquare.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkSquare.c + +tkCanvas.o: $(GENERIC_DIR)/tkCanvas.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCanvas.c + +tkCanvArc.o: $(GENERIC_DIR)/tkCanvArc.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCanvArc.c + +tkCanvBmap.o: $(GENERIC_DIR)/tkCanvBmap.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCanvBmap.c + +tkCanvImg.o: $(GENERIC_DIR)/tkCanvImg.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCanvImg.c + +tkCanvLine.o: $(GENERIC_DIR)/tkCanvLine.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCanvLine.c + +tkCanvPoly.o: $(GENERIC_DIR)/tkCanvPoly.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCanvPoly.c + +tkCanvPs.o: $(GENERIC_DIR)/tkCanvPs.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCanvPs.c + +tkCanvText.o: $(GENERIC_DIR)/tkCanvText.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCanvText.c + +tkCanvUtil.o: $(GENERIC_DIR)/tkCanvUtil.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCanvUtil.c + +tkCanvWind.o: $(GENERIC_DIR)/tkCanvWind.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkCanvWind.c + +tkRectOval.o: $(GENERIC_DIR)/tkRectOval.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkRectOval.c + +tkTrig.o: $(GENERIC_DIR)/tkTrig.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkTrig.c + +tkImage.o: $(GENERIC_DIR)/tkImage.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkImage.c + +tkImgBmap.o: $(GENERIC_DIR)/tkImgBmap.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkImgBmap.c + +tkImgGIF.o: $(GENERIC_DIR)/tkImgGIF.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkImgGIF.c + +tkImgPPM.o: $(GENERIC_DIR)/tkImgPPM.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkImgPPM.c + +tkImgPhoto.o: $(GENERIC_DIR)/tkImgPhoto.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkImgPhoto.c + +tkTest.o: $(GENERIC_DIR)/tkTest.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkTest.c + +tkText.o: $(GENERIC_DIR)/tkText.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkText.c + +tkTextBTree.o: $(GENERIC_DIR)/tkTextBTree.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkTextBTree.c + +tkTextDisp.o: $(GENERIC_DIR)/tkTextDisp.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkTextDisp.c + +tkTextImage.o: $(GENERIC_DIR)/tkTextImage.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkTextImage.c + +tkTextIndex.o: $(GENERIC_DIR)/tkTextIndex.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkTextIndex.c + +tkTextMark.o: $(GENERIC_DIR)/tkTextMark.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkTextMark.c + +tkTextTag.o: $(GENERIC_DIR)/tkTextTag.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkTextTag.c + +tkTextWind.o: $(GENERIC_DIR)/tkTextWind.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkTextWind.c + +tkUnix.o: $(UNIX_DIR)/tkUnix.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnix.c + +tkUnix3d.o: $(UNIX_DIR)/tkUnix3d.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnix3d.c + +tkUnixButton.o: $(UNIX_DIR)/tkUnixButton.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixButton.c + +tkUnixColor.o: $(UNIX_DIR)/tkUnixColor.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixColor.c + +tkUnixCursor.o: $(UNIX_DIR)/tkUnixCursor.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixCursor.c + +tkUnixDialog.o: $(UNIX_DIR)/tkUnixDialog.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixDialog.c + +tkUnixDraw.o: $(UNIX_DIR)/tkUnixDraw.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixDraw.c + +tkUnixEmbed.o: $(UNIX_DIR)/tkUnixEmbed.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixEmbed.c + +tkUnixEvent.o: $(UNIX_DIR)/tkUnixEvent.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixEvent.c + +tkUnixFocus.o: $(UNIX_DIR)/tkUnixFocus.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixFocus.c + +tkUnixFont.o: $(UNIX_DIR)/tkUnixFont.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixFont.c + +tkUnixInit.o: $(UNIX_DIR)/tkUnixInit.c $(GENERIC_DIR)/tkInitScript.h tkConfig.sh + $(CC) -c $(CC_SWITCHES) -DTK_LIBRARY=\"${TK_LIBRARY}\" \ + $(UNIX_DIR)/tkUnixInit.c + +tkUnixMenu.o: $(UNIX_DIR)/tkUnixMenu.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixMenu.c + +tkUnixMenubu.o: $(UNIX_DIR)/tkUnixMenubu.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixMenubu.c + +tkUnixScale.o: $(UNIX_DIR)/tkUnixScale.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixScale.c + +tkUnixScrlbr.o: $(UNIX_DIR)/tkUnixScrlbr.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixScrlbr.c + +tkUnixSelect.o: $(UNIX_DIR)/tkUnixSelect.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixSelect.c + +tkUnixSend.o: $(UNIX_DIR)/tkUnixSend.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixSend.c + +tkUnixWm.o: $(UNIX_DIR)/tkUnixWm.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixWm.c + +tkUnixXId.o: $(UNIX_DIR)/tkUnixXId.c + $(CC) -c $(CC_SWITCHES) $(UNIX_DIR)/tkUnixXId.c + +.c.o: + $(CC) -c $(CC_SWITCHES) $< + +# +# Target to check for proper usage of UCHAR macro. +# + +checkuchar: + -egrep isalnum\|isalpha\|iscntrl\|isdigit\|islower\|isprint\|ispunct\|isspace\|isupper\|isxdigit\|toupper\|tolower $(SRCS) | grep -v UCHAR + +# +# Target to make sure that only symbols with "Tk" prefixes are +# exported. +# + +checkexports: $(TK_LIB_FILE) + -nm -p $(TK_LIB_FILE) | awk '$$2 ~ /[TDB]/ { print $$3 }' | sort -n | grep -v '^[Tt]k' + +# +# Target to create a proper Tk distribution from information in the +# master source directory. DISTDIR must be defined to indicate where +# to put the distribution. DISTDIR must be an absolute path name. +# + +DISTNAME = tk@TK_VERSION@@TK_PATCH_LEVEL@ +ZIPNAME = tk@TK_MAJOR_VERSION@@TK_MINOR_VERSION@@TK_PATCH_LEVEL@.zip +DISTDIR = /proj/tcl/dist/$(DISTNAME) +TCLDIR = @TCL_SRC_DIR@ +$(UNIX_DIR)/configure: $(UNIX_DIR)/configure.in + autoconf $(UNIX_DIR)/configure.in > $(UNIX_DIR)/configure + +dist: $(UNIX_DIR)/configure + rm -rf $(DISTDIR) + mkdir $(DISTDIR) + mkdir $(DISTDIR)/unix + cp -p $(UNIX_DIR)/*.c $(UNIX_DIR)/*.h $(DISTDIR)/unix + cp $(TOP_DIR)/license.terms $(UNIX_DIR)/Makefile.in $(DISTDIR)/unix + chmod 664 $(DISTDIR)/unix/Makefile.in + cp $(UNIX_DIR)/configure $(UNIX_DIR)/configure.in \ + $(UNIX_DIR)/tkConfig.sh.in $(TCLDIR)/unix/install-sh \ + $(UNIX_DIR)/porting.notes $(UNIX_DIR)/porting.old \ + $(UNIX_DIR)/README $(DISTDIR)/unix + chmod 775 $(DISTDIR)/unix/configure $(DISTDIR)/unix/configure.in + chmod +x $(DISTDIR)/unix/install-sh + tclsh $(TCLDIR)/unix/mkLinks.tcl $(TOP_DIR)/doc/*.[13n] \ + > $(DISTDIR)/unix/mkLinks + chmod +x $(DISTDIR)/unix/mkLinks + mkdir $(DISTDIR)/bitmaps + @(cd $(TOP_DIR); for i in bitmaps/* ; do \ + if [ -f $$i ] ; then \ + sed -e 's/static char/static unsigned char/' \ + $$i > $(DISTDIR)/$$i; \ + fi; \ + done;) + mkdir $(DISTDIR)/generic + cp -p $(GENERIC_DIR)/*.c $(GENERIC_DIR)/*.h $(DISTDIR)/generic + cp -p $(GENERIC_DIR)/README $(DISTDIR)/generic + cp -p $(TOP_DIR)/changes $(TOP_DIR)/README $(TOP_DIR)/license.terms \ + $(DISTDIR) + rm -f $(DISTDIR)/generic/blt*.[ch] + mkdir $(DISTDIR)/win + cp -p $(TOP_DIR)/win/*.c $(TOP_DIR)/win/*.h $(DISTDIR)/win + cp -p $(TOP_DIR)/win/makefile.* $(DISTDIR)/win + cp -p $(TOP_DIR)/win/README $(DISTDIR)/win + cp -p $(TOP_DIR)/license.terms $(DISTDIR)/win + mkdir $(DISTDIR)/win/rc + cp -p $(TOP_DIR)/win/rc/*.rc $(TOP_DIR)/win/rc/*.cur \ + $(TOP_DIR)/win/rc/*.ico $(TOP_DIR)/win/rc/*.bmp \ + $(DISTDIR)/win/rc + mkdir $(DISTDIR)/mac + sccs edit -s $(TOP_DIR)/mac/tkMacProjects.sit.hqx + cp -p tkMacProjects.sit.hqx $(DISTDIR)/mac + sccs unedit $(TOP_DIR)/mac/tkMacProjects.sit.hqx + rm -f tkMacProjects.sit.hqx + cp -p $(TOP_DIR)/mac/*.c $(TOP_DIR)/mac/*.h $(TOP_DIR)/mac/*.r \ + $(DISTDIR)/mac + cp -p $(TOP_DIR)/mac/README $(DISTDIR)/mac + cp -p $(TOP_DIR)/license.terms $(DISTDIR)/mac + cp -p $(TOP_DIR)/mac/*.pch $(DISTDIR)/mac + cp -p $(TOP_DIR)/mac/*.doc $(DISTDIR)/mac + cp -p $(TOP_DIR)/mac/*.exp $(DISTDIR)/mac + cp -p $(TOP_DIR)/mac/*.tcl $(DISTDIR)/mac + mkdir $(DISTDIR)/compat + cp -p $(TOP_DIR)/license.terms $(TCLDIR)/compat/unistd.h \ + $(TCLDIR)/compat/stdlib.h $(TCLDIR)/compat/limits.h \ + $(DISTDIR)/compat + mkdir $(DISTDIR)/xlib + cp -p $(TOP_DIR)/xlib/*.h $(TOP_DIR)/xlib/*.c $(DISTDIR)/xlib + cp -p $(TOP_DIR)/license.terms $(DISTDIR)/xlib + mkdir $(DISTDIR)/xlib/X11 + cp -p $(TOP_DIR)/xlib/X11/*.h $(DISTDIR)/xlib/X11 + cp -p $(TOP_DIR)/license.terms $(DISTDIR)/xlib/X11 + mkdir $(DISTDIR)/library + cp -p $(TOP_DIR)/license.terms $(TOP_DIR)/library/*.tcl \ + $(TOP_DIR)/library/tclIndex $(TOP_DIR)/library/prolog.ps \ + $(DISTDIR)/library + mkdir $(DISTDIR)/library/images + @(cd $(TOP_DIR); for i in library/images/* ; do \ + if [ -f $$i ] ; then \ + cp $$i $(DISTDIR)/$$i; \ + fi; \ + done;) + mkdir $(DISTDIR)/library/demos + cp -pr $(TOP_DIR)/library/demos/*.tcl \ + $(TOP_DIR)/library/demos/tclIndex \ + $(TOP_DIR)/library/demos/browse \ + $(TOP_DIR)/library/demos/hello $(TOP_DIR)/library/demos/ixset \ + $(TOP_DIR)/library/demos/rmt $(TOP_DIR)/library/demos/rolodex \ + $(TOP_DIR)/library/demos/square \ + $(TOP_DIR)/library/demos/tcolor \ + $(TOP_DIR)/library/demos/timer \ + $(TOP_DIR)/library/demos/widget \ + $(TOP_DIR)/library/demos/README \ + $(TOP_DIR)/license.terms $(DISTDIR)/library/demos + mkdir $(DISTDIR)/library/demos/images + @(cd $(TOP_DIR); for i in library/demos/images/* ; do \ + if [ -f $$i ] ; then \ + cp $$i $(DISTDIR)/$$i; \ + fi; \ + done;) + mkdir $(DISTDIR)/doc + cp -p $(TOP_DIR)/license.terms $(TOP_DIR)/doc/*.[13n] \ + $(TCLDIR)/doc/man.macros $(DISTDIR)/doc + cp /home/ouster/papers/tk4.0/tk4.0.ps $(DISTDIR)/doc + mkdir $(DISTDIR)/tests + cp -p $(TOP_DIR)/license.terms $(TOP_DIR)/tests/*.test \ + $(TOP_DIR)/tests/visual $(TOP_DIR)/tests/*.tcl \ + $(TOP_DIR)/tests/README $(TOP_DIR)/tests/all \ + $(TOP_DIR)/tests/defs $(TOP_DIR)/tests/option.file* \ + $(DISTDIR)/tests + +# +# The following target can only be used for non-patch releases. Use +# the "allpatch" target below for patch releases. +# + +alldist: dist + rm -f /proj/tcl/dist/$(DISTNAME).tar.Z \ + /proj/tcl/dist/$(DISTNAME).tar.gz \ + /proj/tcl/dist/$(ZIPNAME) + cd /proj/tcl/dist; tar cf $(DISTNAME).tar $(DISTNAME); \ + gzip -9 -c $(DISTNAME).tar > $(DISTNAME).tar.gz; \ + compress $(DISTNAME).tar; zip -r8 $(ZIPNAME) $(DISTNAME) + +# +# The target below is similar to "alldist" except it works for patch +# releases. It is needed because patch releases are peculiar: the +# patch designation appears in the name of the compressed file +# (e.g. tcl8.0p1.tar.gz) but the extracted source directory doesn't +# include the patch designation (e.g. tcl8.0). +# + +allpatch: dist + rm -f /proj/tcl/dist/$(DISTNAME).tar.Z \ + /proj/tcl/dist/$(DISTNAME).tar.gz \ + /proj/tcl/dist/$(ZIPNAME) + mv /proj/tcl/dist/tk${VERSION} /proj/tcl/dist/old + mv /proj/tcl/dist/$(DISTNAME) /proj/tcl/dist/tk${VERSION} + cd /proj/tcl/dist; tar cf $(DISTNAME).tar tk${VERSION}; \ + gzip -9 -c $(DISTNAME).tar > $(DISTNAME).tar.gz; \ + compress $(DISTNAME).tar; zip -r8 $(ZIPNAME) tk${VERSION} + mv /proj/tcl/dist/tk${VERSION} /proj/tcl/dist/$(DISTNAME) + mv /proj/tcl/dist/old /proj/tcl/dist/tk${VERSION} + +# +# Target to create a Macintosh version of the distribution. This will +# do a normal distribution and then massage the output to prepare it +# for moving to the Mac platform. This requires a few scripts and +# programs found only in the Tcl greoup's tool workspace. +# + +macdist: dist + rm -f $(DISTDIR)/mac/tkMacProjects.sit.hqx + tclsh $(TOOL_DIR)/man2html.tcl $(DISTDIR)/tmp ../.. tk$(VERSION) + mv $(DISTDIR)/tmp/tk$(VERSION) $(DISTDIR)/html + rm -rf $(DISTDIR)/doc + rm -rf $(DISTDIR)/tmp + tclsh $(TOOL_DIR)/cvtEOL.tcl $(DISTDIR) + +# +# Targets to build Solaris package of the distribution for the current +# architecture. To build stream packages for both sun4 and i86pc +# architectures: +# +# On the sun4 machine, execute the following: +# make distclean; ./configure +# make DISTDIR=<distdir> package +# +# Once the build is complete, execute the following on the i86pc +# machine: +# make DISTDIR=<distdir> package-quick +# +# <distdir> is the absolute path to a directory where the build should +# take place. These steps will generate the SUNWtk.sun4 and +# SUNWtk.i86pc stream packages. It is important that the packages be +# built in this fashion in order to ensure that the architecture +# independent files are exactly the same, including timestamps, in +# both packages. +# + +package: dist package-config package-common package-binaries package-generate +package-quick: package-config package-binaries package-generate + +# +# Configure for the current architecture in the dist directory. +# +package-config: + mkdir -p $(DISTDIR)/unix/`arch` + cd $(DISTDIR)/unix/`arch`; \ + ../configure --prefix=/opt/SUNWtcl/$(TCLVERSION) \ + --exec_prefix=/opt/SUNWtcl/$(TCLVERSION)/`arch` \ + --with-tcl=$(DISTDIR)/../tcl$(TCLVERSION)/unix/`arch` \ + --enable-shared + mkdir -p $(DISTDIR)/SUNWtcl/$(TCLVERSION) + mkdir -p $(DISTDIR)/SUNWtcl/$(TCLVERSION)/`arch` + +# +# Build and install the architecture independent files in the dist directory. +# + +package-common: + cd $(DISTDIR)/unix/`arch`;\ + $(MAKE); \ + $(MAKE) install-libraries install-man \ + prefix=$(DISTDIR)/SUNWtcl/$(TCLVERSION) \ + exec_prefix=$(DISTDIR)/SUNWtcl/$(TCLVERSION)/`arch` + mkdir -p $(DISTDIR)/SUNWtcl/$(TCLVERSION)/bin + sed -e "s/TCLVERSION/$(TCLVERSION)/g" \ + -e "s/TKVERSION/$(VERSION)/g" < $(UNIX_DIR)/wish.sh \ + > $(DISTDIR)/SUNWtcl/$(TCLVERSION)/bin/wish$(VERSION) + chmod 755 $(DISTDIR)/SUNWtcl/$(TCLVERSION)/bin/wish$(VERSION) + +# +# Build and install the architecture specific files in the dist directory. +# + +package-binaries: + cd $(DISTDIR)/unix/`arch`; \ + $(MAKE); \ + $(MAKE) install-binaries prefix=$(DISTDIR)/SUNWtcl/$(TCLVERSION) \ + exec_prefix=$(DISTDIR)/SUNWtcl/$(TCLVERSION)/`arch` + +# +# Generate a package from the installed files in the dist directory for the +# current architecture. +# + +package-generate: + pkgproto $(DISTDIR)/SUNWtcl/$(TCLVERSION)/bin=bin \ + $(DISTDIR)/SUNWtcl/$(TCLVERSION)/include=include \ + $(DISTDIR)/SUNWtcl/$(TCLVERSION)/lib=lib \ + $(DISTDIR)/SUNWtcl/$(TCLVERSION)/man=man \ + $(DISTDIR)/SUNWtcl/$(TCLVERSION)/`arch`=`arch` \ + | tclsh $(TCLDIR)/unix/mkProto.tcl $(TCLVERSION) \ + $(UNIX_DIR) > prototype + pkgmk -o -d . -f prototype -a `arch` + pkgtrans -s . SUNWtk.`arch` SUNWtk + rm -rf SUNWtk + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/unix/README b/unix/README new file mode 100644 index 0000000..bb06d21 --- /dev/null +++ b/unix/README @@ -0,0 +1,125 @@ +This is the directory where you configure, compile, test, and install +UNIX versions of Tk. This directory also contains source files for Tk +that are specific to UNIX. + +The rest of this file contains instructions on how to do this. The +release should compile and run either "out of the box" or with trivial +changes on any UNIX-like system that approximates POSIX, BSD, or System +V. We know that it runs on workstations from Sun, H-P, DEC, IBM, and +SGI, as well as PCs running Linux, BSDI, and SCO UNIX. To compile for +a PC running Windows, see the README file in the directory ../win. To +compile for a Macintosh, see the README file in the directory ../mac. + +SCCS: @(#) README 1.24 97/08/13 17:31:19 + +How To Compile And Install Tk: +------------------------------ + +(a) Make sure that the Tcl 8.0 release is present in the directory + ../../tcl8.0 (or else use the "--with-tcl" switch described below). + This release of Tk will only work with Tcl 8.0. Also, be sure that + you have configured Tcl before you configure Tk. + +(b) Check for patches as described in ../README. + +(c) If you have already compiled Tk once in this directory and are now + preparing to compile again in the same directory but for a different + platform, or if you have applied patches, type "make distclean" to + discard all the configuration information computed previously. + +(d) Type "./configure". This runs a configuration script created by GNU + autoconf, which configures Tcl for your system and creates a + Makefile. The configure script allows you to customize the Tcl + configuration for your site; for details on how you can do this, + type "./configure -help" or refer to the autoconf documentation (not + included here). Tk's "configure" script supports the following + special switches in addition to the standard ones: + --enable-gcc If this switch is set, Tk will configure + itself to use gcc if it is available on your + system. Note: it is not safe to modify the + Makefile to use gcc after configure is run. + --with-tcl=DIR Specifies the directory containing the Tcl + binaries and Tcl's platform-dependent + configuration information. By default + the Tcl directory is assumed to be in the + location given by (a) above. + --enable-shared If this switch is specified, Tk will compile + itself as a shared library if it can figure + out how to do that on this platform. + Note: be sure to use only absolute path names (those starting with "/") + in the --prefix and --exec_prefix options. + +(e) Type "make". This will create a library archive called "libtk.a" + or "libtk.so" and an interpreter application called "wish" that + allows you to type Tcl commands interactively or execute script files. + +(f) If the make fails then you'll have to personalize the Makefile + for your site or possibly modify the distribution in other ways. + First check the file "porting.notes" to see if there are hints + for compiling on your system. Then look at the porting Web page + described later in this file. If you need to modify Makefile, + there are comments at the beginning of it that describe the things + you might want to change and how to change them. + +(g) Type "make install" to install Tk's binaries and script files in + standard places. You'll need write permission on the installation + directoryies to do this. The installation directories are + determined by the "configure" script and may be specified with + the --prefix and --exec_prefix options to "configure". See the + Makefile for information on what directories were chosen; you + can override these choices by modifying the "prefix" and + "exec_prefix" variables in the Makefile. + +(h) At this point you can play with Tk by invoking the "wish" + program and typing Tcl commands. However, if you haven't installed + Tk then you'll first need to set your TK_LIBRARY environment + variable to hold the full path name of the "library" subdirectory. + If you haven't installed Tcl either then you'll need to set your + TCL_LIBRARY environment variable as well (see the Tcl README file + for information on this). Note that installed versions of wish, + libtk.a, libtk.so, and the Tk library have a version number in their + names, such as "wish8.0" or "libtk8.0.so"; to use the installed + versions, either specify the version number or create a symbolic + link (e.g. from "wish" to "wish8.0"). + +If you have trouble compiling Tk, read through the file "porting.notes". +It contains information that people have provided about changes they had +to make to compile Tcl in various environments. Or, check out the +following Web URL: + http://www.sunlabs.com/cgi-bin/tcl/info.8.0 +This is an on-line database of porting information. We make no guarantees +that this information is accurate, complete, or up-to-date, but you may +find it useful. If you get Tk running on a new configuration and had to +make non-trivial changes to do it, we'd be happy to receive new information +to add to "porting.notes". You can also make a new entry into the +on-line Web database. We're also interested in hearing how to change the +configuration setup so that Tcl compiles on additional platforms "out of +the box". + +Test suite +---------- + +Tk has a substantial self-test suite, consisting of a set of scripts in +the subdirectory "tests". To run the test suite just type "make test" +in this directory. You should then see a printout of the test files +processed. If any errors occur, you'll see a much more substantial +printout for each error. In order to avoid false error reports, be sure +to run the tests with an empty resource database (e.g., remove your +.Xdefaults file or delete any entries starting with *). Also, don't +try to do anything else with your display or keyboard whlie the tests +are running, or you may get false violations. See the README file in +the "tests" directory for more information on the test suite. + +If the test suite generates errors, most likely they are due to non- +portable tests that are interacting badly with your system configuration. +We are gradually eliminating the non-portable tests, but this release +includes many new tests so there will probably be some portability +problems. As long as the test suite doesn't core dump, it's probably +safe to conclude that any errors represent portability problems in the +test suite and not fundamental flaws with Tk. + +There are also a number of visual tests for things such as screen layout, +Postscript generation, etc. These tests all have to be run manually and +the results have to be verified visually. To run the tests, cd to the +"tests" directory and run the script "visual". It will present a main +window with a bunch of menus, which you can use to select various tests. diff --git a/unix/configure.in b/unix/configure.in new file mode 100644 index 0000000..7f3c15f --- /dev/null +++ b/unix/configure.in @@ -0,0 +1,407 @@ +dnl This file is an input file used by the GNU "autoconf" program to +dnl generate the file "configure", which is run during Tk installation +dnl to configure the system for the local environment. +AC_INIT(../generic/tk.h) +# SCCS: @(#) configure.in 1.90 97/11/20 12:45:45 + +TK_VERSION=8.0 +TK_MAJOR_VERSION=8 +TK_MINOR_VERSION=0 +TK_PATCH_LEVEL="p2" +VERSION=${TK_VERSION} + +if test "${prefix}" = "NONE"; then + prefix=/usr/local +fi +if test "${exec_prefix}" = "NONE"; then + exec_prefix=$prefix +fi +TK_SRC_DIR=`cd $srcdir/..; pwd` + +AC_PROG_RANLIB +AC_ARG_ENABLE(gcc, [ --enable-gcc allow use of gcc if available], + [tk_ok=$enableval], [tkl_ok=no]) +if test "$tk_ok" = "yes"; then + AC_PROG_CC +else + CC=${CC-cc} +AC_SUBST(CC) +fi +AC_C_CROSS +AC_HAVE_HEADERS(unistd.h limits.h) + +#-------------------------------------------------------------------- +# See if there was a command-line option for where Tcl is; if +# not, assume that its top-level directory is a sibling of ours. +#-------------------------------------------------------------------- + +AC_ARG_WITH(tcl, [ --with-tcl=DIR use Tcl 8.0 binaries from DIR], + TCL_BIN_DIR=$withval, TCL_BIN_DIR=`cd ../../tcl8.0/unix; pwd`) +if test ! -d $TCL_BIN_DIR; then + AC_MSG_ERROR(Tcl directory $TCL_BIN_DIR doesn't exist) +fi +if test ! -f $TCL_BIN_DIR/Makefile; then + AC_MSG_ERROR(There's no Makefile in $TCL_BIN_DIR; perhaps you didn't specify the Tcl *build* directory (not the toplevel Tcl directory) or you forgot to configure Tcl?) +fi + +#-------------------------------------------------------------------- +# Read in configuration information generated by Tcl for shared +# libraries, and arrange for it to be substituted into our +# Makefile. +#-------------------------------------------------------------------- + +file=$TCL_BIN_DIR/tclConfig.sh +. $file +SHLIB_CFLAGS=$TCL_SHLIB_CFLAGS +SHLIB_LD=$TCL_SHLIB_LD +SHLIB_LD_LIBS=$TCL_SHLIB_LD_LIBS +SHLIB_SUFFIX=$TCL_SHLIB_SUFFIX +SHLIB_VERSION=$TCL_SHLIB_VERSION +DL_LIBS=$TCL_DL_LIBS +LD_FLAGS=$TCL_LD_FLAGS + +LIB_RUNTIME_DIR='${LIB_RUNTIME_DIR}' + +# If Tcl and Tk are installed in different places, adjust the library +# search path to reflect this. + +if test "$TCL_EXEC_PREFIX" != "$exec_prefix"; then + LIB_RUNTIME_DIR="${LIB_RUNTIME_DIR}:${TCL_EXEC_PREFIX}" +fi + +#-------------------------------------------------------------------- +# Supply a substitute for stdlib.h if it doesn't define strtol, +# strtoul, or strtod (which it doesn't in some versions of SunOS). +#-------------------------------------------------------------------- + +AC_MSG_CHECKING(stdlib.h) +AC_HEADER_EGREP(strtol, stdlib.h, tk_ok=yes, tk_ok=no) +AC_HEADER_EGREP(strtoul, stdlib.h, , tk_ok=no) +AC_HEADER_EGREP(strtod, stdlib.h, , tk_ok=no) +if test $tk_ok = no; then + AC_DEFINE(NO_STDLIB_H) +fi +AC_MSG_RESULT($tk_ok) + +#-------------------------------------------------------------------- +# Include sys/select.h if it exists and if it supplies things +# that appear to be useful and aren't already in sys/types.h. +# This appears to be true only on the RS/6000 under AIX. Some +# systems like OSF/1 have a sys/select.h that's of no use, and +# other systems like SCO UNIX have a sys/select.h that's +# pernicious. If "fd_set" isn't defined anywhere then set a +# special flag. +#-------------------------------------------------------------------- + +AC_MSG_CHECKING([fd_set and sys/select]) +AC_TRY_COMPILE([#include <sys/types.h>], + [fd_set readMask, writeMask;], tk_ok=yes, tk_ok=no) +if test $tk_ok = no; then + AC_HEADER_EGREP(fd_mask, sys/select.h, tk_ok=yes) + if test $tk_ok = yes; then + AC_DEFINE(HAVE_SYS_SELECT_H) + fi +fi +AC_MSG_RESULT($tk_ok) +if test $tk_ok = no; then + AC_DEFINE(NO_FD_SET) +fi + +#-------------------------------------------------------------------- +# Check for various typedefs and provide substitutes if +# they don't exist. +#-------------------------------------------------------------------- + +AC_MODE_T +AC_PID_T +AC_SIZE_T +AC_UID_T + +#------------------------------------------------------------------------------ +# Find out about time handling differences. +#------------------------------------------------------------------------------ + +AC_CHECK_HEADERS(sys/time.h) +AC_HEADER_TIME + +#-------------------------------------------------------------------- +# Locate the X11 header files and the X11 library archive. Try +# the ac_path_x macro first, but if it doesn't find the X stuff +# (e.g. because there's no xmkmf program) then check through +# a list of possible directories. Under some conditions the +# autoconf macro will return an include directory that contains +# no include files, so double-check its result just to be safe. +#-------------------------------------------------------------------- + +AC_PATH_X +not_really_there="" +if test "$no_x" = ""; then + if test "$x_includes" = ""; then + AC_TRY_CPP([#include <X11/XIntrinsic.h>], , not_really_there="yes") + else + if test ! -r $x_includes/X11/Intrinsic.h; then + not_really_there="yes" + fi + fi +fi +if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then + AC_MSG_CHECKING(for X11 header files) + XINCLUDES="# no special path needed" + AC_TRY_CPP([#include <X11/Intrinsic.h>], , XINCLUDES="nope") + if test "$XINCLUDES" = nope; then + dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include" + for i in $dirs ; do + if test -r $i/X11/Intrinsic.h; then + AC_MSG_RESULT($i) + XINCLUDES=" -I$i" + break + fi + done + fi +else + if test "$x_includes" != ""; then + XINCLUDES=-I$x_includes + else + XINCLUDES="# no special path needed" + fi +fi +if test "$XINCLUDES" = nope; then + AC_MSG_RESULT(couldn't find any!) + XINCLUDES="# no include files found" +fi + +if test "$no_x" = yes; then + AC_MSG_CHECKING(for X11 libraries) + XLIBSW=nope + dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib" + for i in $dirs ; do + if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl; then + AC_MSG_RESULT($i) + XLIBSW="-L$i -lX11" + x_libraries="$i" + break + fi + done +else + if test "$x_libraries" = ""; then + XLIBSW=-lX11 + else + XLIBSW="-L$x_libraries -lX11" + fi +fi +if test "$XLIBSW" = nope ; then + AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow) +fi +if test "$XLIBSW" = nope ; then + AC_MSG_RESULT(couldn't find any! Using -lX11.) + XLIBSW=-lX11 +fi + +#-------------------------------------------------------------------- +# Various manipulations on the search path used at runtime to +# find shared libraries: +# 1. If the X library binaries are in a non-standard directory, +# add the X library location into that search path. +# 2. On systems such as AIX and Ultrix that use "-L" as the +# search path option, colons cannot be used to separate +# directories from each other. Change colons to " -L". +# 3. Create two sets of search flags, one for use in cc lines +# and the other for when the linker is invoked directly. In +# the second case, '-Wl,' must be stripped off and commas must +# be replaced by spaces. +#-------------------------------------------------------------------- + +if test "x${x_libraries}" != "x"; then + LIB_RUNTIME_DIR="${LIB_RUNTIME_DIR}:${x_libraries}" +fi +if test "${TCL_LD_SEARCH_FLAGS}" = '-L${LIB_RUNTIME_DIR}'; then + LIB_RUNTIME_DIR=`echo ${LIB_RUNTIME_DIR} |sed -e 's/:/ -L/g'` +fi + +# The statement below is very tricky! It actually *evaluates* the +# string in TCL_LD_SEARCH_FLAGS, which causes a substitution of the +# variable LIB_RUNTIME_DIR. + +eval "TK_CC_SEARCH_FLAGS=\"$TCL_LD_SEARCH_FLAGS\"" +TK_LD_SEARCH_FLAGS=`echo ${TK_CC_SEARCH_FLAGS} |sed -e "s|-Wl,||g" -e "s|,| |g"` + +#-------------------------------------------------------------------- +# Check for the existence of various libraries. The order here +# is important, so that then end up in the right order in the +# command line generated by make. The -lsocket and -lnsl libraries +# require a couple of special tricks: +# 1. Use "connect" and "accept" to check for -lsocket, and +# "gethostbyname" to check for -lnsl. +# 2. Use each function name only once: can't redo a check because +# autoconf caches the results of the last check and won't redo it. +# 3. Use -lnsl and -lsocket only if they supply procedures that +# aren't already present in the normal libraries. This is because +# IRIX 5.2 has libraries, but they aren't needed and they're +# bogus: they goof up name resolution if used. +# 4. On some SVR4 systems, can't use -lsocket without -lnsl too. +# To get around this problem, check for both libraries together +# if -lsocket doesn't work by itself. +#-------------------------------------------------------------------- + +AC_CHECK_LIB(Xbsd, main, [LIBS="$LIBS -lXbsd"]) + +tk_checkBoth=0 +AC_CHECK_FUNC(connect, tk_checkSocket=0, tk_checkSocket=1) +if test "$tk_checkSocket" = 1; then + AC_CHECK_LIB(socket, main, LIBS="$LIBS -lsocket", tk_checkBoth=1) +fi +if test "$tk_checkBoth" = 1; then + tk_oldLibs=$LIBS + LIBS="$LIBS -lsocket -lnsl" + AC_CHECK_FUNC(accept, tk_checkNsl=0, [LIBS=$tk_oldLibs]) +fi +AC_CHECK_FUNC(gethostbyname, , AC_CHECK_LIB(nsl, main, [LIBS="$LIBS -lnsl"])) + +#-------------------------------------------------------------------- +# One more check related to the X libraries. The standard releases +# of Ultrix don't support the "xauth" mechanism, so send won't work +# unless TK_NO_SECURITY is defined. However, there are usually copies +# of the MIT X server available as well, which do support xauth. +# Check for the MIT stuff and use it if it exists. +# +# Note: can't use ac_check_lib macro (at least, not in Autoconf 2.1) +# because it can't deal with the "-" in the library name. +#-------------------------------------------------------------------- + +if test -d /usr/include/mit ; then + AC_MSG_CHECKING([MIT X libraries]) + tk_oldCFlags=$CFLAGS + CFLAGS="$CFLAGS -I/usr/include/mit" + tk_oldLibs=$LIBS + LIBS="$LIBS -lX11-mit" + AC_TRY_LINK([ + #include <X11/Xlib.h> + ], [ + XOpenDisplay(0); + ], [ + AC_MSG_RESULT(yes) + XLIBSW="-lX11-mit" + XINCLUDES="-I/usr/include/mit" + ], AC_MSG_RESULT(no)) + CFLAGS=$tk_oldCFlags + LIBS=$tk_oldLibs +fi + +#-------------------------------------------------------------------- +# On a few very rare systems, all of the libm.a stuff is +# already in libc.a. Set compiler flags accordingly. +# Also, Linux requires the "ieee" library for math to +# work right (and it must appear before "-lm"). +#-------------------------------------------------------------------- + +MATH_LIBS="" +AC_CHECK_FUNC(sin, , MATH_LIBS="-lm") +AC_CHECK_LIB(ieee, main, [MATH_LIBS="-lieee $MATH_LIBS"]) + +#-------------------------------------------------------------------- +# If this system doesn't have a memmove procedure, use memcpy +# instead. +#-------------------------------------------------------------------- + +AC_CHECK_FUNC(memmove, , [AC_DEFINE(memmove, memcpy)]) + +#-------------------------------------------------------------------- +# Figure out whether "char" is unsigned. If so, set a +# #define for __CHAR_UNSIGNED__. +#-------------------------------------------------------------------- + +AC_C_CHAR_UNSIGNED + +#-------------------------------------------------------------------- +# Under Solaris 2.4, strtod returns the wrong value for the +# terminating character under some conditions. Check for this +# and if the problem exists use a substitute procedure +# "fixstrtod" (provided by Tcl) that corrects the error. +#-------------------------------------------------------------------- + +AC_CHECK_FUNC(strtod, tk_strtod=1, tk_strtod=0) +if test "$tk_strtod" = 1; then + AC_MSG_CHECKING([for Solaris 2.4 strtod bug]) + AC_TRY_RUN([ + extern double strtod(); + int main() + { + char *string = "NaN"; + char *term; + strtod(string, &term); + if ((term != string) && (term[-1] == 0)) { + exit(1); + } + exit(0); + }], tk_ok=1, tk_ok=0, tk_ok=0) + if test "$tk_ok" = 1; then + AC_MSG_RESULT(ok) + else + AC_MSG_RESULT(buggy) + AC_DEFINE(strtod, fixstrtod) + fi +fi + +#-------------------------------------------------------------------- +# The statements below define a collection of symbols related to +# building libtk as a shared library instead of a static library. +#-------------------------------------------------------------------- + +AC_ARG_ENABLE(shared, + [ --enable-shared build libtk as a shared library], + [ok=$enableval], [ok=no]) +if test "$ok" = "yes" -a "${SHLIB_SUFFIX}" != ""; then + TK_SHARED_BUILD=1 + TK_SHLIB_CFLAGS="${SHLIB_CFLAGS}" + eval "TK_LIB_FILE=libtk${TCL_SHARED_LIB_SUFFIX}" + MAKE_LIB="\${SHLIB_LD} -o ${TK_LIB_FILE} \${OBJS} \$(TK_LD_SEARCH_FLAGS) ${SHLIB_LD_LIBS}" + RANLIB=":" +else + TK_SHARED_BUILD=0 + TK_SHLIB_CFLAGS="" + eval "TK_LIB_FILE=libtk${TCL_UNSHARED_LIB_SUFFIX}" + MAKE_LIB="ar cr ${TK_LIB_FILE} \${OBJS}" +fi + +# Note: in the following variable, it's important to use the absolute +# path name of the Tcl directory rather than "..": this is because +# AIX remembers this path and will attempt to use it at run-time to look +# up the Tcl library. + +if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then + TK_BUILD_LIB_SPEC="-L`pwd` -ltk${VERSION}" + TK_LIB_SPEC="-L${exec_prefix}/lib -ltk${VERSION}" +else + TK_BUILD_LIB_SPEC="-L`pwd` -ltk`echo ${VERSION} | tr -d .`" + TK_LIB_SPEC="-L${exec_prefix}/lib -ltk`echo ${VERSION} | tr -d .`" +fi + +AC_SUBST(DL_LIBS) +AC_SUBST(LD_FLAGS) +AC_SUBST(MATH_LIBS) +AC_SUBST(MAKE_LIB) +AC_SUBST(SHLIB_CFLAGS) +AC_SUBST(SHLIB_LD) +AC_SUBST(SHLIB_LD_LIBS) +AC_SUBST(SHLIB_SUFFIX) +AC_SUBST(SHLIB_VERSION) +AC_SUBST(TCL_BIN_DIR) +AC_SUBST(TCL_BUILD_LIB_SPEC) +AC_SUBST(TCL_SRC_DIR) +AC_SUBST(TCL_VERSION) +AC_SUBST(TK_BUILD_LIB_SPEC) +AC_SUBST(TK_CC_SEARCH_FLAGS) +AC_SUBST(TK_LD_SEARCH_FLAGS) +AC_SUBST(TK_LIB_FILE) +AC_SUBST(TK_LIB_SPEC) +AC_SUBST(TK_MAJOR_VERSION) +AC_SUBST(TK_MINOR_VERSION) +AC_SUBST(TK_PATCH_LEVEL) +AC_SUBST(TK_SHLIB_CFLAGS) +AC_SUBST(TK_SRC_DIR) +AC_SUBST(TK_VERSION) +AC_SUBST(XINCLUDES) +AC_SUBST(XLIBSW) +AC_SUBST(TK_SHARED_BUILD) + +AC_OUTPUT(Makefile tkConfig.sh) diff --git a/unix/install-sh b/unix/install-sh new file mode 100644 index 0000000..0ff4b6a --- /dev/null +++ b/unix/install-sh @@ -0,0 +1,119 @@ +#!/bin/sh + +# +# install - install a program, script, or datafile +# This comes from X11R5; it is not part of GNU. +# +# $XConsortium: install.sh,v 1.2 89/12/18 14:47:22 jim Exp $ +# +# This script is compatible with the BSD install script, but was written +# from scratch. +# + + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit="${DOITPROG-}" + + +# put in absolute paths if you don't have them in your path; or use env. vars. + +mvprog="${MVPROG-mv}" +cpprog="${CPPROG-cp}" +chmodprog="${CHMODPROG-chmod}" +chownprog="${CHOWNPROG-chown}" +chgrpprog="${CHGRPPROG-chgrp}" +stripprog="${STRIPPROG-strip}" +rmprog="${RMPROG-rm}" + +instcmd="$mvprog" +chmodcmd="" +chowncmd="" +chgrpcmd="" +stripcmd="" +rmcmd="$rmprog -f" +mvcmd="$mvprog" +src="" +dst="" + +while [ x"$1" != x ]; do + case $1 in + -c) instcmd="$cpprog" + shift + continue;; + + -m) chmodcmd="$chmodprog $2" + shift + shift + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + -s) stripcmd="$stripprog" + shift + continue;; + + *) if [ x"$src" = x ] + then + src=$1 + else + dst=$1 + fi + shift + continue;; + esac +done + +if [ x"$src" = x ] +then + echo "install: no input file specified" + exit 1 +fi + +if [ x"$dst" = x ] +then + echo "install: no destination specified" + exit 1 +fi + + +# If destination is a directory, append the input filename; if your system +# does not like double slashes in filenames, you may need to add some logic + +if [ -d $dst ] +then + dst="$dst"/`basename $src` +fi + +# Make a temp file name in the proper directory. + +dstdir=`dirname $dst` +dsttmp=$dstdir/#inst.$$# + +# Move or copy the file name to the temp name + +$doit $instcmd $src $dsttmp + +# and set any options; do chmod last to preserve setuid bits + +if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; fi +if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; fi +if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; fi +if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; fi + +# Now rename the file to the real destination. + +$doit $rmcmd $dst +$doit $mvcmd $dsttmp $dst + + +exit 0 diff --git a/unix/mkLinks b/unix/mkLinks new file mode 100644 index 0000000..d817703 --- /dev/null +++ b/unix/mkLinks @@ -0,0 +1,878 @@ +#!/bin/sh +# This script is invoked when installing manual entries. It generates +# additional links to manual entries, corresponding to the procedure +# and command names described by the manual entry. For example, the +# Tcl manual entry Hash.3 describes procedures Tcl_InitHashTable, +# Tcl_CreateHashEntry, and many more. This script will make hard +# links so that Tcl_InitHashTable.3, Tcl_CreateHashEntry.3, and so +# on all refer to Hash.3 in the installed directory. +# +# Because of the length of command and procedure names, this mechanism +# only works on machines that support file names longer than 14 characters. +# This script checks to see if long file names are supported, and it +# doesn't make any links if they are not. +# +# The script takes one argument, which is the name of the directory +# where the manual entries have been installed. + +if test $# != 1; then + echo "Usage: mkLinks dir" + exit 1 +fi + +cd $1 +echo foo > xyzzyTestingAVeryLongFileName.foo +x=`echo xyzzyTe*` +rm xyzzyTe* +if test "$x" != "xyzzyTestingAVeryLongFileName.foo"; then + exit +fi +if test -r 3DBorder.3; then + rm -f Tk_3DBorderColor.3 + ln 3DBorder.3 Tk_3DBorderColor.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_3DBorderGC.3 + ln 3DBorder.3 Tk_3DBorderGC.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_3DHorizontalBevel.3 + ln 3DBorder.3 Tk_3DHorizontalBevel.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_3DVerticalBevel.3 + ln 3DBorder.3 Tk_3DVerticalBevel.3 +fi +if test -r WindowId.3; then + rm -f Tk_Attributes.3 + ln WindowId.3 Tk_Attributes.3 +fi +if test -r BindTable.3; then + rm -f Tk_BindEvent.3 + ln BindTable.3 Tk_BindEvent.3 +fi +if test -r CanvTkwin.3; then + rm -f Tk_CanvasDrawableCoords.3 + ln CanvTkwin.3 Tk_CanvasDrawableCoords.3 +fi +if test -r CanvTkwin.3; then + rm -f Tk_CanvasEventuallyRedraw.3 + ln CanvTkwin.3 Tk_CanvasEventuallyRedraw.3 +fi +if test -r CanvTkwin.3; then + rm -f Tk_CanvasGetCoord.3 + ln CanvTkwin.3 Tk_CanvasGetCoord.3 +fi +if test -r CanvPsY.3; then + rm -f Tk_CanvasPsBitmap.3 + ln CanvPsY.3 Tk_CanvasPsBitmap.3 +fi +if test -r CanvPsY.3; then + rm -f Tk_CanvasPsColor.3 + ln CanvPsY.3 Tk_CanvasPsColor.3 +fi +if test -r CanvPsY.3; then + rm -f Tk_CanvasPsFont.3 + ln CanvPsY.3 Tk_CanvasPsFont.3 +fi +if test -r CanvPsY.3; then + rm -f Tk_CanvasPsPath.3 + ln CanvPsY.3 Tk_CanvasPsPath.3 +fi +if test -r CanvPsY.3; then + rm -f Tk_CanvasPsStipple.3 + ln CanvPsY.3 Tk_CanvasPsStipple.3 +fi +if test -r CanvPsY.3; then + rm -f Tk_CanvasPsY.3 + ln CanvPsY.3 Tk_CanvasPsY.3 +fi +if test -r CanvTkwin.3; then + rm -f Tk_CanvasSetStippleOrigin.3 + ln CanvTkwin.3 Tk_CanvasSetStippleOrigin.3 +fi +if test -r CanvTkwin.3; then + rm -f Tk_CanvasTagsOption.3 + ln CanvTkwin.3 Tk_CanvasTagsOption.3 +fi +if test -r CanvTxtInfo.3; then + rm -f Tk_CanvasTextInfo.3 + ln CanvTxtInfo.3 Tk_CanvasTextInfo.3 +fi +if test -r CanvTkwin.3; then + rm -f Tk_CanvasTkwin.3 + ln CanvTkwin.3 Tk_CanvasTkwin.3 +fi +if test -r CanvTkwin.3; then + rm -f Tk_CanvasWindowCoords.3 + ln CanvTkwin.3 Tk_CanvasWindowCoords.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_ChangeWindowAttributes.3 + ln ConfigWind.3 Tk_ChangeWindowAttributes.3 +fi +if test -r WindowId.3; then + rm -f Tk_Changes.3 + ln WindowId.3 Tk_Changes.3 +fi +if test -r TextLayout.3; then + rm -f Tk_CharBbox.3 + ln TextLayout.3 Tk_CharBbox.3 +fi +if test -r SetClass.3; then + rm -f Tk_Class.3 + ln SetClass.3 Tk_Class.3 +fi +if test -r ClrSelect.3; then + rm -f Tk_ClearSelection.3 + ln ClrSelect.3 Tk_ClearSelection.3 +fi +if test -r Clipboard.3; then + rm -f Tk_ClipboardAppend.3 + ln Clipboard.3 Tk_ClipboardAppend.3 +fi +if test -r Clipboard.3; then + rm -f Tk_ClipboardClear.3 + ln Clipboard.3 Tk_ClipboardClear.3 +fi +if test -r WindowId.3; then + rm -f Tk_Colormap.3 + ln WindowId.3 Tk_Colormap.3 +fi +if test -r TextLayout.3; then + rm -f Tk_ComputeTextLayout.3 + ln TextLayout.3 Tk_ComputeTextLayout.3 +fi +if test -r ConfigWidg.3; then + rm -f Tk_ConfigureInfo.3 + ln ConfigWidg.3 Tk_ConfigureInfo.3 +fi +if test -r ConfigWidg.3; then + rm -f Tk_ConfigureValue.3 + ln ConfigWidg.3 Tk_ConfigureValue.3 +fi +if test -r ConfigWidg.3; then + rm -f Tk_ConfigureWidget.3 + ln ConfigWidg.3 Tk_ConfigureWidget.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_ConfigureWindow.3 + ln ConfigWind.3 Tk_ConfigureWindow.3 +fi +if test -r CoordToWin.3; then + rm -f Tk_CoordsToWindow.3 + ln CoordToWin.3 Tk_CoordsToWindow.3 +fi +if test -r BindTable.3; then + rm -f Tk_CreateBinding.3 + ln BindTable.3 Tk_CreateBinding.3 +fi +if test -r BindTable.3; then + rm -f Tk_CreateBindingTable.3 + ln BindTable.3 Tk_CreateBindingTable.3 +fi +if test -r CrtErrHdlr.3; then + rm -f Tk_CreateErrorHandler.3 + ln CrtErrHdlr.3 Tk_CreateErrorHandler.3 +fi +if test -r EventHndlr.3; then + rm -f Tk_CreateEventHandler.3 + ln EventHndlr.3 Tk_CreateEventHandler.3 +fi +if test -r CrtGenHdlr.3; then + rm -f Tk_CreateGenericHandler.3 + ln CrtGenHdlr.3 Tk_CreateGenericHandler.3 +fi +if test -r CrtImgType.3; then + rm -f Tk_CreateImageType.3 + ln CrtImgType.3 Tk_CreateImageType.3 +fi +if test -r CrtItemType.3; then + rm -f Tk_CreateItemType.3 + ln CrtItemType.3 Tk_CreateItemType.3 +fi +if test -r CrtPhImgFmt.3; then + rm -f Tk_CreatePhotoImageFormat.3 + ln CrtPhImgFmt.3 Tk_CreatePhotoImageFormat.3 +fi +if test -r CrtSelHdlr.3; then + rm -f Tk_CreateSelHandler.3 + ln CrtSelHdlr.3 Tk_CreateSelHandler.3 +fi +if test -r CrtWindow.3; then + rm -f Tk_CreateWindow.3 + ln CrtWindow.3 Tk_CreateWindow.3 +fi +if test -r CrtWindow.3; then + rm -f Tk_CreateWindowFromPath.3 + ln CrtWindow.3 Tk_CreateWindowFromPath.3 +fi +if test -r GetBitmap.3; then + rm -f Tk_DefineBitmap.3 + ln GetBitmap.3 Tk_DefineBitmap.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_DefineCursor.3 + ln ConfigWind.3 Tk_DefineCursor.3 +fi +if test -r BindTable.3; then + rm -f Tk_DeleteAllBindings.3 + ln BindTable.3 Tk_DeleteAllBindings.3 +fi +if test -r BindTable.3; then + rm -f Tk_DeleteBinding.3 + ln BindTable.3 Tk_DeleteBinding.3 +fi +if test -r BindTable.3; then + rm -f Tk_DeleteBindingTable.3 + ln BindTable.3 Tk_DeleteBindingTable.3 +fi +if test -r CrtErrHdlr.3; then + rm -f Tk_DeleteErrorHandler.3 + ln CrtErrHdlr.3 Tk_DeleteErrorHandler.3 +fi +if test -r EventHndlr.3; then + rm -f Tk_DeleteEventHandler.3 + ln EventHndlr.3 Tk_DeleteEventHandler.3 +fi +if test -r CrtGenHdlr.3; then + rm -f Tk_DeleteGenericHandler.3 + ln CrtGenHdlr.3 Tk_DeleteGenericHandler.3 +fi +if test -r DeleteImg.3; then + rm -f Tk_DeleteImage.3 + ln DeleteImg.3 Tk_DeleteImage.3 +fi +if test -r CrtSelHdlr.3; then + rm -f Tk_DeleteSelHandler.3 + ln CrtSelHdlr.3 Tk_DeleteSelHandler.3 +fi +if test -r WindowId.3; then + rm -f Tk_Depth.3 + ln WindowId.3 Tk_Depth.3 +fi +if test -r CrtWindow.3; then + rm -f Tk_DestroyWindow.3 + ln CrtWindow.3 Tk_DestroyWindow.3 +fi +if test -r WindowId.3; then + rm -f Tk_Display.3 + ln WindowId.3 Tk_Display.3 +fi +if test -r WindowId.3; then + rm -f Tk_DisplayName.3 + ln WindowId.3 Tk_DisplayName.3 +fi +if test -r TextLayout.3; then + rm -f Tk_DistanceToTextLayout.3 + ln TextLayout.3 Tk_DistanceToTextLayout.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_Draw3DPolygon.3 + ln 3DBorder.3 Tk_Draw3DPolygon.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_Draw3DRectangle.3 + ln 3DBorder.3 Tk_Draw3DRectangle.3 +fi +if test -r MeasureChar.3; then + rm -f Tk_DrawChars.3 + ln MeasureChar.3 Tk_DrawChars.3 +fi +if test -r DrawFocHlt.3; then + rm -f Tk_DrawFocusHighlight.3 + ln DrawFocHlt.3 Tk_DrawFocusHighlight.3 +fi +if test -r TextLayout.3; then + rm -f Tk_DrawTextLayout.3 + ln TextLayout.3 Tk_DrawTextLayout.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_Fill3DPolygon.3 + ln 3DBorder.3 Tk_Fill3DPolygon.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_Fill3DRectangle.3 + ln 3DBorder.3 Tk_Fill3DRectangle.3 +fi +if test -r FindPhoto.3; then + rm -f Tk_FindPhoto.3 + ln FindPhoto.3 Tk_FindPhoto.3 +fi +if test -r FontId.3; then + rm -f Tk_FontId.3 + ln FontId.3 Tk_FontId.3 +fi +if test -r FontId.3; then + rm -f Tk_FontMetrics.3 + ln FontId.3 Tk_FontMetrics.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_Free3DBorder.3 + ln 3DBorder.3 Tk_Free3DBorder.3 +fi +if test -r GetBitmap.3; then + rm -f Tk_FreeBitmap.3 + ln GetBitmap.3 Tk_FreeBitmap.3 +fi +if test -r GetColor.3; then + rm -f Tk_FreeColor.3 + ln GetColor.3 Tk_FreeColor.3 +fi +if test -r GetClrmap.3; then + rm -f Tk_FreeColormap.3 + ln GetClrmap.3 Tk_FreeColormap.3 +fi +if test -r GetCursor.3; then + rm -f Tk_FreeCursor.3 + ln GetCursor.3 Tk_FreeCursor.3 +fi +if test -r GetFont.3; then + rm -f Tk_FreeFont.3 + ln GetFont.3 Tk_FreeFont.3 +fi +if test -r GetGC.3; then + rm -f Tk_FreeGC.3 + ln GetGC.3 Tk_FreeGC.3 +fi +if test -r GetImage.3; then + rm -f Tk_FreeImage.3 + ln GetImage.3 Tk_FreeImage.3 +fi +if test -r ConfigWidg.3; then + rm -f Tk_FreeOptions.3 + ln ConfigWidg.3 Tk_FreeOptions.3 +fi +if test -r GetPixmap.3; then + rm -f Tk_FreePixmap.3 + ln GetPixmap.3 Tk_FreePixmap.3 +fi +if test -r TextLayout.3; then + rm -f Tk_FreeTextLayout.3 + ln TextLayout.3 Tk_FreeTextLayout.3 +fi +if test -r FreeXId.3; then + rm -f Tk_FreeXId.3 + ln FreeXId.3 Tk_FreeXId.3 +fi +if test -r GeomReq.3; then + rm -f Tk_GeometryRequest.3 + ln GeomReq.3 Tk_GeometryRequest.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_Get3DBorder.3 + ln 3DBorder.3 Tk_Get3DBorder.3 +fi +if test -r BindTable.3; then + rm -f Tk_GetAllBindings.3 + ln BindTable.3 Tk_GetAllBindings.3 +fi +if test -r GetAnchor.3; then + rm -f Tk_GetAnchor.3 + ln GetAnchor.3 Tk_GetAnchor.3 +fi +if test -r InternAtom.3; then + rm -f Tk_GetAtomName.3 + ln InternAtom.3 Tk_GetAtomName.3 +fi +if test -r BindTable.3; then + rm -f Tk_GetBinding.3 + ln BindTable.3 Tk_GetBinding.3 +fi +if test -r GetBitmap.3; then + rm -f Tk_GetBitmap.3 + ln GetBitmap.3 Tk_GetBitmap.3 +fi +if test -r GetBitmap.3; then + rm -f Tk_GetBitmapFromData.3 + ln GetBitmap.3 Tk_GetBitmapFromData.3 +fi +if test -r GetCapStyl.3; then + rm -f Tk_GetCapStyle.3 + ln GetCapStyl.3 Tk_GetCapStyle.3 +fi +if test -r GetColor.3; then + rm -f Tk_GetColor.3 + ln GetColor.3 Tk_GetColor.3 +fi +if test -r GetColor.3; then + rm -f Tk_GetColorByValue.3 + ln GetColor.3 Tk_GetColorByValue.3 +fi +if test -r GetClrmap.3; then + rm -f Tk_GetColormap.3 + ln GetClrmap.3 Tk_GetColormap.3 +fi +if test -r GetCursor.3; then + rm -f Tk_GetCursor.3 + ln GetCursor.3 Tk_GetCursor.3 +fi +if test -r GetCursor.3; then + rm -f Tk_GetCursorFromData.3 + ln GetCursor.3 Tk_GetCursorFromData.3 +fi +if test -r GetFont.3; then + rm -f Tk_GetFont.3 + ln GetFont.3 Tk_GetFont.3 +fi +if test -r GetGC.3; then + rm -f Tk_GetGC.3 + ln GetGC.3 Tk_GetGC.3 +fi +if test -r GetImage.3; then + rm -f Tk_GetImage.3 + ln GetImage.3 Tk_GetImage.3 +fi +if test -r CrtImgType.3; then + rm -f Tk_GetImageMasterData.3 + ln CrtImgType.3 Tk_GetImageMasterData.3 +fi +if test -r CrtItemType.3; then + rm -f Tk_GetItemTypes.3 + ln CrtItemType.3 Tk_GetItemTypes.3 +fi +if test -r GetJoinStl.3; then + rm -f Tk_GetJoinStyle.3 + ln GetJoinStl.3 Tk_GetJoinStyle.3 +fi +if test -r GetJustify.3; then + rm -f Tk_GetJustify.3 + ln GetJustify.3 Tk_GetJustify.3 +fi +if test -r GetOption.3; then + rm -f Tk_GetOption.3 + ln GetOption.3 Tk_GetOption.3 +fi +if test -r GetPixels.3; then + rm -f Tk_GetPixels.3 + ln GetPixels.3 Tk_GetPixels.3 +fi +if test -r GetPixmap.3; then + rm -f Tk_GetPixmap.3 + ln GetPixmap.3 Tk_GetPixmap.3 +fi +if test -r GetRelief.3; then + rm -f Tk_GetRelief.3 + ln GetRelief.3 Tk_GetRelief.3 +fi +if test -r GetRootCrd.3; then + rm -f Tk_GetRootCoords.3 + ln GetRootCrd.3 Tk_GetRootCoords.3 +fi +if test -r GetPixels.3; then + rm -f Tk_GetScreenMM.3 + ln GetPixels.3 Tk_GetScreenMM.3 +fi +if test -r GetScroll.3; then + rm -f Tk_GetScrollInfo.3 + ln GetScroll.3 Tk_GetScrollInfo.3 +fi +if test -r GetSelect.3; then + rm -f Tk_GetSelection.3 + ln GetSelect.3 Tk_GetSelection.3 +fi +if test -r GetUid.3; then + rm -f Tk_GetUid.3 + ln GetUid.3 Tk_GetUid.3 +fi +if test -r GetVRoot.3; then + rm -f Tk_GetVRootGeometry.3 + ln GetVRoot.3 Tk_GetVRootGeometry.3 +fi +if test -r GetVisual.3; then + rm -f Tk_GetVisual.3 + ln GetVisual.3 Tk_GetVisual.3 +fi +if test -r HandleEvent.3; then + rm -f Tk_HandleEvent.3 + ln HandleEvent.3 Tk_HandleEvent.3 +fi +if test -r WindowId.3; then + rm -f Tk_Height.3 + ln WindowId.3 Tk_Height.3 +fi +if test -r IdToWindow.3; then + rm -f Tk_IdToWindow.3 + ln IdToWindow.3 Tk_IdToWindow.3 +fi +if test -r ImgChanged.3; then + rm -f Tk_ImageChanged.3 + ln ImgChanged.3 Tk_ImageChanged.3 +fi +if test -r InternAtom.3; then + rm -f Tk_InternAtom.3 + ln InternAtom.3 Tk_InternAtom.3 +fi +if test -r WindowId.3; then + rm -f Tk_InternalBorderWidth.3 + ln WindowId.3 Tk_InternalBorderWidth.3 +fi +if test -r TextLayout.3; then + rm -f Tk_IntersectTextLayout.3 + ln TextLayout.3 Tk_IntersectTextLayout.3 +fi +if test -r WindowId.3; then + rm -f Tk_IsMapped.3 + ln WindowId.3 Tk_IsMapped.3 +fi +if test -r WindowId.3; then + rm -f Tk_IsTopLevel.3 + ln WindowId.3 Tk_IsTopLevel.3 +fi +if test -r MainLoop.3; then + rm -f Tk_MainLoop.3 + ln MainLoop.3 Tk_MainLoop.3 +fi +if test -r MainWin.3; then + rm -f Tk_MainWindow.3 + ln MainWin.3 Tk_MainWindow.3 +fi +if test -r MaintGeom.3; then + rm -f Tk_MaintainGeometry.3 + ln MaintGeom.3 Tk_MaintainGeometry.3 +fi +if test -r CrtWindow.3; then + rm -f Tk_MakeWindowExist.3 + ln CrtWindow.3 Tk_MakeWindowExist.3 +fi +if test -r ManageGeom.3; then + rm -f Tk_ManageGeometry.3 + ln ManageGeom.3 Tk_ManageGeometry.3 +fi +if test -r MapWindow.3; then + rm -f Tk_MapWindow.3 + ln MapWindow.3 Tk_MapWindow.3 +fi +if test -r MeasureChar.3; then + rm -f Tk_MeasureChars.3 + ln MeasureChar.3 Tk_MeasureChars.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_MoveResizeWindow.3 + ln ConfigWind.3 Tk_MoveResizeWindow.3 +fi +if test -r MoveToplev.3; then + rm -f Tk_MoveToplevelWindow.3 + ln MoveToplev.3 Tk_MoveToplevelWindow.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_MoveWindow.3 + ln ConfigWind.3 Tk_MoveWindow.3 +fi +if test -r Name.3; then + rm -f Tk_Name.3 + ln Name.3 Tk_Name.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_NameOf3DBorder.3 + ln 3DBorder.3 Tk_NameOf3DBorder.3 +fi +if test -r GetAnchor.3; then + rm -f Tk_NameOfAnchor.3 + ln GetAnchor.3 Tk_NameOfAnchor.3 +fi +if test -r GetBitmap.3; then + rm -f Tk_NameOfBitmap.3 + ln GetBitmap.3 Tk_NameOfBitmap.3 +fi +if test -r GetCapStyl.3; then + rm -f Tk_NameOfCapStyle.3 + ln GetCapStyl.3 Tk_NameOfCapStyle.3 +fi +if test -r GetColor.3; then + rm -f Tk_NameOfColor.3 + ln GetColor.3 Tk_NameOfColor.3 +fi +if test -r GetCursor.3; then + rm -f Tk_NameOfCursor.3 + ln GetCursor.3 Tk_NameOfCursor.3 +fi +if test -r GetFont.3; then + rm -f Tk_NameOfFont.3 + ln GetFont.3 Tk_NameOfFont.3 +fi +if test -r NameOfImg.3; then + rm -f Tk_NameOfImage.3 + ln NameOfImg.3 Tk_NameOfImage.3 +fi +if test -r GetJoinStl.3; then + rm -f Tk_NameOfJoinStyle.3 + ln GetJoinStl.3 Tk_NameOfJoinStyle.3 +fi +if test -r GetJustify.3; then + rm -f Tk_NameOfJustify.3 + ln GetJustify.3 Tk_NameOfJustify.3 +fi +if test -r GetRelief.3; then + rm -f Tk_NameOfRelief.3 + ln GetRelief.3 Tk_NameOfRelief.3 +fi +if test -r Name.3; then + rm -f Tk_NameToWindow.3 + ln Name.3 Tk_NameToWindow.3 +fi +if test -r ConfigWidg.3; then + rm -f Tk_Offset.3 + ln ConfigWidg.3 Tk_Offset.3 +fi +if test -r OwnSelect.3; then + rm -f Tk_OwnSelection.3 + ln OwnSelect.3 Tk_OwnSelection.3 +fi +if test -r WindowId.3; then + rm -f Tk_Parent.3 + ln WindowId.3 Tk_Parent.3 +fi +if test -r ParseArgv.3; then + rm -f Tk_ParseArgv.3 + ln ParseArgv.3 Tk_ParseArgv.3 +fi +if test -r Name.3; then + rm -f Tk_PathName.3 + ln Name.3 Tk_PathName.3 +fi +if test -r FindPhoto.3; then + rm -f Tk_PhotoBlank.3 + ln FindPhoto.3 Tk_PhotoBlank.3 +fi +if test -r FindPhoto.3; then + rm -f Tk_PhotoExpand.3 + ln FindPhoto.3 Tk_PhotoExpand.3 +fi +if test -r FindPhoto.3; then + rm -f Tk_PhotoGetImage.3 + ln FindPhoto.3 Tk_PhotoGetImage.3 +fi +if test -r FindPhoto.3; then + rm -f Tk_PhotoGetSize.3 + ln FindPhoto.3 Tk_PhotoGetSize.3 +fi +if test -r FindPhoto.3; then + rm -f Tk_PhotoPutBlock.3 + ln FindPhoto.3 Tk_PhotoPutBlock.3 +fi +if test -r FindPhoto.3; then + rm -f Tk_PhotoPutZoomedBlock.3 + ln FindPhoto.3 Tk_PhotoPutZoomedBlock.3 +fi +if test -r FindPhoto.3; then + rm -f Tk_PhotoSetSize.3 + ln FindPhoto.3 Tk_PhotoSetSize.3 +fi +if test -r TextLayout.3; then + rm -f Tk_PointToChar.3 + ln TextLayout.3 Tk_PointToChar.3 +fi +if test -r FontId.3; then + rm -f Tk_PostscriptFontName.3 + ln FontId.3 Tk_PostscriptFontName.3 +fi +if test -r QWinEvent.3; then + rm -f Tk_QueueWindowEvent.3 + ln QWinEvent.3 Tk_QueueWindowEvent.3 +fi +if test -r GetImage.3; then + rm -f Tk_RedrawImage.3 + ln GetImage.3 Tk_RedrawImage.3 +fi +if test -r WindowId.3; then + rm -f Tk_ReqHeight.3 + ln WindowId.3 Tk_ReqHeight.3 +fi +if test -r WindowId.3; then + rm -f Tk_ReqWidth.3 + ln WindowId.3 Tk_ReqWidth.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_ResizeWindow.3 + ln ConfigWind.3 Tk_ResizeWindow.3 +fi +if test -r Restack.3; then + rm -f Tk_RestackWindow.3 + ln Restack.3 Tk_RestackWindow.3 +fi +if test -r RestrictEv.3; then + rm -f Tk_RestrictEvents.3 + ln RestrictEv.3 Tk_RestrictEvents.3 +fi +if test -r WindowId.3; then + rm -f Tk_Screen.3 + ln WindowId.3 Tk_Screen.3 +fi +if test -r WindowId.3; then + rm -f Tk_ScreenNumber.3 + ln WindowId.3 Tk_ScreenNumber.3 +fi +if test -r SetAppName.3; then + rm -f Tk_SetAppName.3 + ln SetAppName.3 Tk_SetAppName.3 +fi +if test -r 3DBorder.3; then + rm -f Tk_SetBackgroundFromBorder.3 + ln 3DBorder.3 Tk_SetBackgroundFromBorder.3 +fi +if test -r SetClass.3; then + rm -f Tk_SetClass.3 + ln SetClass.3 Tk_SetClass.3 +fi +if test -r SetGrid.3; then + rm -f Tk_SetGrid.3 + ln SetGrid.3 Tk_SetGrid.3 +fi +if test -r GeomReq.3; then + rm -f Tk_SetInternalBorder.3 + ln GeomReq.3 Tk_SetInternalBorder.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_SetWindowBackground.3 + ln ConfigWind.3 Tk_SetWindowBackground.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_SetWindowBackgroundPixmap.3 + ln ConfigWind.3 Tk_SetWindowBackgroundPixmap.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_SetWindowBorder.3 + ln ConfigWind.3 Tk_SetWindowBorder.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_SetWindowBorderPixmap.3 + ln ConfigWind.3 Tk_SetWindowBorderPixmap.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_SetWindowBorderWidth.3 + ln ConfigWind.3 Tk_SetWindowBorderWidth.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_SetWindowColormap.3 + ln ConfigWind.3 Tk_SetWindowColormap.3 +fi +if test -r SetVisual.3; then + rm -f Tk_SetWindowVisual.3 + ln SetVisual.3 Tk_SetWindowVisual.3 +fi +if test -r GetBitmap.3; then + rm -f Tk_SizeOfBitmap.3 + ln GetBitmap.3 Tk_SizeOfBitmap.3 +fi +if test -r GetImage.3; then + rm -f Tk_SizeOfImage.3 + ln GetImage.3 Tk_SizeOfImage.3 +fi +if test -r StrictMotif.3; then + rm -f Tk_StrictMotif.3 + ln StrictMotif.3 Tk_StrictMotif.3 +fi +if test -r TextLayout.3; then + rm -f Tk_TextLayoutToPostscript.3 + ln TextLayout.3 Tk_TextLayoutToPostscript.3 +fi +if test -r MeasureChar.3; then + rm -f Tk_TextWidth.3 + ln MeasureChar.3 Tk_TextWidth.3 +fi +if test -r GetUid.3; then + rm -f Tk_Uid.3 + ln GetUid.3 Tk_Uid.3 +fi +if test -r ConfigWind.3; then + rm -f Tk_UndefineCursor.3 + ln ConfigWind.3 Tk_UndefineCursor.3 +fi +if test -r MeasureChar.3; then + rm -f Tk_UnderlineChars.3 + ln MeasureChar.3 Tk_UnderlineChars.3 +fi +if test -r TextLayout.3; then + rm -f Tk_UnderlineTextLayout.3 + ln TextLayout.3 Tk_UnderlineTextLayout.3 +fi +if test -r MaintGeom.3; then + rm -f Tk_UnmaintainGeometry.3 + ln MaintGeom.3 Tk_UnmaintainGeometry.3 +fi +if test -r MapWindow.3; then + rm -f Tk_UnmapWindow.3 + ln MapWindow.3 Tk_UnmapWindow.3 +fi +if test -r SetGrid.3; then + rm -f Tk_UnsetGrid.3 + ln SetGrid.3 Tk_UnsetGrid.3 +fi +if test -r WindowId.3; then + rm -f Tk_Visual.3 + ln WindowId.3 Tk_Visual.3 +fi +if test -r WindowId.3; then + rm -f Tk_Width.3 + ln WindowId.3 Tk_Width.3 +fi +if test -r WindowId.3; then + rm -f Tk_WindowId.3 + ln WindowId.3 Tk_WindowId.3 +fi +if test -r WindowId.3; then + rm -f Tk_X.3 + ln WindowId.3 Tk_X.3 +fi +if test -r WindowId.3; then + rm -f Tk_Y.3 + ln WindowId.3 Tk_Y.3 +fi +if test -r menubar.n; then + rm -f tk_bindForTraversal.n + ln menubar.n tk_bindForTraversal.n +fi +if test -r palette.n; then + rm -f tk_bisque.n + ln palette.n tk_bisque.n +fi +if test -r chooseColor.n; then + rm -f tk_chooseColor.n + ln chooseColor.n tk_chooseColor.n +fi +if test -r dialog.n; then + rm -f tk_dialog.n + ln dialog.n tk_dialog.n +fi +if test -r focusNext.n; then + rm -f tk_focusFollowsMouse.n + ln focusNext.n tk_focusFollowsMouse.n +fi +if test -r focusNext.n; then + rm -f tk_focusNext.n + ln focusNext.n tk_focusNext.n +fi +if test -r focusNext.n; then + rm -f tk_focusPrev.n + ln focusNext.n tk_focusPrev.n +fi +if test -r getOpenFile.n; then + rm -f tk_getOpenFile.n + ln getOpenFile.n tk_getOpenFile.n +fi +if test -r getOpenFile.n; then + rm -f tk_getSaveFile.n + ln getOpenFile.n tk_getSaveFile.n +fi +if test -r menubar.n; then + rm -f tk_menuBar.n + ln menubar.n tk_menuBar.n +fi +if test -r messageBox.n; then + rm -f tk_messageBox.n + ln messageBox.n tk_messageBox.n +fi +if test -r optionMenu.n; then + rm -f tk_optionMenu.n + ln optionMenu.n tk_optionMenu.n +fi +if test -r popup.n; then + rm -f tk_popup.n + ln popup.n tk_popup.n +fi +if test -r palette.n; then + rm -f tk_setPalette.n + ln palette.n tk_setPalette.n +fi +exit 0 diff --git a/unix/porting.notes b/unix/porting.notes new file mode 100644 index 0000000..ecb395d --- /dev/null +++ b/unix/porting.notes @@ -0,0 +1,86 @@ +This file contains a collection of notes that various people have +provided about porting Tk to various machines and operating systems. +I don't have personal access to any of these machines, so I make +no guarantees that the notes are correct, complete, or up-to-date. +If you see the word "I" in any explanations, it refers to the person +who contributed the information, not to me; this means that I +probably can't answer any questions about any of this stuff. In +some cases, a person has volunteered to act as a contact point for +questions about porting Tcl to a particular machine; in these +cases the person's name and e-mail address are listed. I'm very +interested in getting new porting information to add to the file; +please mail updates to "john.ousterhout@eng.sun.com". + +This file reflects information provided for Tk 4.0 and later releases. +If there is no information for your configuration in this file, check +the file "porting.old" too; it contains information that was +submitted for Tk 3.6 and earlier releases, and some of that information +may still be valid. + +A new porting database has recently become available on the Web at +the following URL: + http://www.sunlabs.com/cgi-bin/tcl/info.4.0 +This page provides information about the platforms on which Tcl 7.4 +and Tk 4.0 have been compiled and what changes were needed to get Tcl +and Tk to compile. You can also add new entries to that database +when you install Tcl and Tk on a new platform. The Web database is +likely to be more up-to-date than this file. + +sccsid = SCCS: @(#) porting.notes 1.10 96/04/10 15:38:54 + +-------------------------------------------- +Solaris, various versions +-------------------------------------------- + +1. If typing "make test" results in an error message saying that +there are no "*.test" files, or you get lots of globbing errors, +it's probably because your system doesn't have cc installed and +you used gcc. In order for this to work, you have to set your +CC environment variable to gcc and your CPP environment variable +to "gcc -E" before running the configure script. + +2. Make sure that /usr/ucb is not in your PATH or LD_LIBRARY_PATH +environment variables; this will cause confusion between the new +Solaris libraries and older UCB versions (Tk will expect one version +and get another). + +3. On 486 PCs with Solaris 2.4, when compiling with gcc 2.6.0, +tkMessage.c appears to hang gcc. If the -O switch is removed +then it compiles fine. + +-------------------------------------------- +486 PCs, Solaris 2.4 +-------------------------------------------- + +When compiling with gcc 2.6.0, tkMessage.c appears to hang gcc. +If the -O switch is removed then it compiles fine. + +-------------------------------------------- +SGI machines, IRIX 5.2, 5.3, IRIX64 6.0.1 +-------------------------------------------- + +1. Add "-D_BSD_TIME" to CFLAGS in Makefile. This avoids type conflicts +in the prototype for the gettimeofday procedure. + +2. If you're running under Irix 6.x and wish dumps core, try +removing -O from the CFLAGS in Makefile and recompiling; compiler +optimizations seem to cause problems on some machines. + +-------------------------------------------- +QNX 4.22 +-------------------------------------------- + +All of the source files built as is. All I had to do was edit the +Makefile generated by ./configure to specify where the X11 libraries +were (ie, I added in -L/usr/X11/lib) + +-------------------------------------------- +HP-UX +-------------------------------------------- + +There are problems compiling Tk gcc (version 2.7.2) and the HP assembler. +The problem is that if static functions are called using a pointer reference, +double arguments are not transferred correctly into the function. That can +be fixed by making all those functions global. This happens with the +ScaleXxx() and TranslateXxx() functions for all canvas item types. +The simplest fix is configure gcc to use the GNU assembler. diff --git a/unix/porting.old b/unix/porting.old new file mode 100644 index 0000000..ea8aa5c --- /dev/null +++ b/unix/porting.old @@ -0,0 +1,324 @@ +This is an old version of the file "porting.notes". It contains +porting information that people submitted for Tk releases numbered +3.6 and earlier. You may find information in this file useful if +there is no information available for your machine in the current +version of "porting.notes". + +I don't have personal access to any of these machines, so I make +no guarantees that the notes are correct, complete, or up-to-date. +If you see the word "I" in any explanations, it refers to the person +who contributed the information, not to me; this means that I +probably can't answer any questions about any of this stuff. In +some cases, a person has volunteered to act as a contact point for +questions about porting Tcl to a particular machine; in these +cases the person's name and e-mail address are listed. I'd be +happy to receive corrections or updates. + +sccsid = SCCS: @(#) porting.old 1.2 96/02/16 10:27:30 + +--------------------------------------------- +DEC Alphas: +--------------------------------------------- + +1. There appears to be a compiler/library bug that prevents tkTrig.c +from compiling unless you turn off optimization (remove the -O compiler +switch). The problem appears to have been fixed in the 1.3-4 version +of the compiler. + +--------------------------------------------- +HP-UX systems: +--------------------------------------------- + +1. Configuration: + HP-UX Release 7.05 on a series 300 (68k) machine. + The native cc has been used for production. + X11r4 libraries and include files were taken from + internet archives, where as the server came with HPUX release 7.05. + + Problems: + Symbol table space for cc had to be increased with: -Wc,-Ns3000 + tkBind.c did not compile under -O: + C1 internal error in "GetField": Set Error Detected + *** Error code 1 + tkBind.c did compile without optimization (no -O). + +2. Note: if you have trouble getting xauth-style access control to work +(and you'll need xauth if you want to use "send"), be sure to uncomment +the line + +# Vuelogin*authorize: True + +in the file /usr/vue/config/Xconfig, so that the server starts up with +authorization enabled. Also, you may have to reboot the machine in +order to force the server to restart. + +--------------------------------------------- +SCO Unix: +--------------------------------------------- + +Getting Tk to run under SCO Unix: + +Add a "#undef select" to tkEvent.c, and remove the reference to TK_EXCEPTION +around line 460 of main.c. + +Tk uses its own scheme for allocating the border colors for its 3D widgets, +which causes problems when running TK on a system with "PseudoColor" +display class, and a 16-cell colormap. + +If you can't go to eight bitplanes, you can instead start the server with a +"-static" (Xsco) or "-analog" (Xsight) option, making the display class +become "StaticColor". This makes the entire colormap read-only, and it will +return the color that most closely maps to the desired color as possible. + +--------------------------------------------- +Silicon Graphics systems: +--------------------------------------------- + +1. Change the CC variable in the Makefile to: + +CC = cc -xansi -D__STDC__ -signed + +2. Change the LIBS variable in the Makefile to use the X11 shared library + ("-lX11_s" instead of "-lX11"). + +3. Under some versions of IRIX (e.g. 4.0.1) you have to turn off + optimization (e.g. change "-O" in CFLAGS to "-O0" or remove it + entirely) because of faulty code generation. If the Tcl or Tk test + suites fail, turn off optimization. + +4. Add a "-lsun" switch just before "-lm" in the LIBS definition. + Under some versions of IRIX (5.1.1.3?) you'll need to omit the + "-lsun" switch, plus remove the "-lsocket" and "-lnsl" switches + added by the configure script; otherwise you won't be able to + use symbolic host names for the display, only numerical Internet + addresses. + +5. Rumor has it that you'll also need a "-lmalloc" switch in the + LIBS definition. + +6. In IRIX 5.2 you'll have to modify Makefile to fix the following problems: + - The "-c" option is illegal with this version of install, but + the "-F" switch is needed instead. Change this in the "INSTALL =" + definition line. + - The order of file and directory have to be changed in all the + invocations of INSTALL_DATA or INSTALL_PROGRAM. + +--------------------------------------------- +IBM RS/6000's: +--------------------------------------------- +1. To allow ALT- sequences to work on the RS-6000, the following +line should be changed in tkBind.c: + + OLD LINE: + {"Alt", Mod2Mask, 0}, + NEW LINE: + {"Alt", Mod1Mask, 0}, + +--------------------------------------------- +AT&T SVR4: +--------------------------------------------- + +1. The first major hurdle is that SVR4's select() subtly differs +from BSD select. This impacts Tk in two ways, some of the Xlib calls +make use of select() and are inherently broken and Tk itself makes +extensive use of select(). The first problem can't be fixed without +rebuilding one's Xlib, but can be avoided. I intend to submit part +of my work the XFree86 guys so that the next version of XFree86 for +SVR4 will not be broken. Until then, it is necessary to comment out +this section of code from Tk_DoOneEvent() (which is near line 1227): + +#if !defined(SVR4) + void (*oldHandler)(); + + oldHandler = (void (*)()) signal(SIGPIPE, SIG_IGN); + XNoOp(display); + XFlush(display); + (void) signal(SIGPIPE, oldHandler); +#endif /* SVR4 */ + +if you don't comment it out, some scripts cause wish to go into +an infinite loop of sending no-ops to the X server. + +2. As for fixing Tk's calls to select(), I've taken the simple +approach of writing a wrapper for select and then using #define to +replace all calls to select with the wrapper. I chose tkConfig.h +to load the wrapper. So at the very end of tkConfig.h, it now looks +like: + +#if defined(SVR4) +# include "BSDselect.h" +#endif + +#endif /* _TKCONFIG */ + +The file BSDselect.h looks like this: + +#include <sys/types.h> +#include <sys/time.h> +#include <sys/select.h> + +/* This is a fix for the difference between BSD's select() and + * SVR4's select(). SVR4's select() can never return a value larger + * than the total number of file descriptors being checked. So, if + * you select for read and write on one file descriptor, and both + * are true, SVR4 select() will only return 1. BSD select in the + * same situation will return 2. + * + * Additionally, BSD select() on timing out, will zero the masks, + * while SVR4 does not. This is fixed here as well. + * + * Set your tabstops to 4 characters to have this code nicely formatted. + * + * Jerry Whelan, guru@bradley.edu, June 12th, 1993 + */ + + +int +BSDselect(nfds, readfds, writefds, exceptfds, timeout) +int nfds; +fd_set *readfds, *writefds, *exceptfds; +struct timeval *timeout; +{ + int rval, + i; + + rval = select(nfds, readfds, writefds, exceptfds, timeout); + + switch(rval) { + case -1: return(rval); + break; + + case 0: if(readfds != NULL) + FD_ZERO(readfds); + if(writefds != NULL) + FD_ZERO(writefds); + if(exceptfds != NULL) + FD_ZERO(exceptfds); + + return(rval); + break; + + default: for(i=0, rval=0; i < nfds; i++) { + if((readfds != NULL) && FD_ISSET +(i, readfds)) rval++; + if((writefds != NULL) && FD_ISSE +T(i, writefds)) rval++; + if((writefds != NULL) && FD_ISSE +T(i, exceptfds)) rval++; + } + return(rval); + } +/* Should never get here */ +} + +--------------------------------------------- +CDC 4680MP, EP/IX 1.4.3: +--------------------------------------------- + +The installation was done in the System V environment (-systype sysv) +with the BSD extensions available (-I/usr/include/bsd and -lbsd). It was +built with the 2.20 level C compiler. The 2.11 level can be used, but +it is better to match what TCL is built with, which must be 2.20 or +higher (see the porting notes with TCL for the details). + +To make the configure script find the BSD extensions, I set environment +variable DEFS to "-I/usr/include/bsd" and LIBS to "-lbsd" before +running it. I would have also set CC to "cc2.20", but that compiler +driver has a bug that loader errors (e.g. not finding a library routine, +which the script uses to tell what is available) do not cause an error +status to be returned to the shell (but see the Tcl 2.1.1 porting notes +for comments about using "-non_shared"). + +After running configure, I changed the CC definition line in Makefile +from: + CC=cc +to + CC=cc2.20 +to match the TCL build. Skip this if the default compiler is already 2.20 +(or later). + +--------------------------------------------- +CDC 4680MP, EP/IX 2.1.1: +--------------------------------------------- + +The installation was done in the System V environment (-systype sysv) +with the BSD extensions available (-I/usr/include/bsd and -lbsd). It was +built with the 3.11 level C compiler. Earlier levels can be used, but it +is better to match what TCL is built with, which must be 2.20 or higher +(see the porting notes with TCL for the details). + +To make the configure script find the BSD extensions, I set environment +variable DEFS to "-I/usr/include/bsd -non_shared" and LIBS to "-lbsd" +before running it. + +See the Tcl porting notes for comments on why "-non_shared" is needed +during the configuration step. It was removed from AC_FLAGS before +building. + +------------------------------------------------- +Pyramid, OSx 5.1a (UCB universe, GCC installed): +------------------------------------------------- + +Instead of typing "./configure" to configure, type + + DEFS="-I/usr/include/X11/attinc" ./configure + +to sh to do the configuration. + +------------------------------------------------- +NextSTEP 3.1: +------------------------------------------------- + +1. Run configure with predefined CPP: + CPP='cc -E' ./configure + (If your shell is [t]csh, do a "setenv CPP 'cc -E'") + +2. Edit Makefile: + -add the following to AC_FLAGS: + -Dstrtod=tcl_strtod + +Note: Tk's raise test may fail when running the tvtwm window manager. +Changing to either twm or even better fvwm ensures that this test will +succeed. + +------------------------------------------------- +Encore 91, UMAX V 3.0.9.3: +------------------------------------------------- + +1. Modify the CFLAGS definition in Makefile to include -DENCORE: + + CFLAGS = -O -DENCORE + +2. "mkdir" does not by default create the parent directories. The mkdir +directives should be modified to "midir -p". + +3. An error of a redeclaration of read, can be resolved by conditionally +not compiling if an ENCORE system. + +#ifndef ENCORE +extern int read _ANSI_ARGS_((int fd, char *buf, size_t size)); +#endif + +------------------------------------------------- +Sequent machines running Dynix: +Contact: Andrew Swan (aswan@soda.berkeley.edu) +------------------------------------------------- + +1. Use gcc instead of the cc distributed by Sequent + +2. There are problems with the distributed version of + <stddef.h>. The easiest solution is probably to create a + copy of stddef.h, make sure it comes early in the include + path and then edit it as need be to eliminate conflicts + with the X11 header files. + +3. The same comments about the tanh function from the notes on + porting Tcl apply to Tk. + +------------------------------------------------- +Systems running Interactive 4.0: +------------------------------------------------- + +1. Add "-posix" to CFLAGS in Makefile (or Makefile.in). + +2. Add "-lnsl_s" to LIBS in Makefile (or Makefile.in). diff --git a/unix/tkAppInit.c b/unix/tkAppInit.c new file mode 100644 index 0000000..6b6b2e2 --- /dev/null +++ b/unix/tkAppInit.c @@ -0,0 +1,120 @@ +/* + * tkAppInit.c -- + * + * Provides a default version of the Tcl_AppInit procedure for + * use in wish and similar Tk-based applications. + * + * Copyright (c) 1993 The Regents of the University of California. + * Copyright (c) 1994 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkAppInit.c 1.22 96/05/29 09:47:08 + */ + +#include "tk.h" + +/* + * The following variable is a special hack that is needed in order for + * Sun shared libraries to be used for Tcl. + */ + +extern int matherr(); +int *tclDummyMathPtr = (int *) matherr; + +#ifdef TK_TEST +EXTERN int Tktest_Init _ANSI_ARGS_((Tcl_Interp *interp)); +#endif /* TK_TEST */ + +/* + *---------------------------------------------------------------------- + * + * main -- + * + * This is the main program for the application. + * + * Results: + * None: Tk_Main never returns here, so this procedure never + * returns either. + * + * Side effects: + * Whatever the application does. + * + *---------------------------------------------------------------------- + */ + +int +main(argc, argv) + int argc; /* Number of command-line arguments. */ + char **argv; /* Values of command-line arguments. */ +{ + Tk_Main(argc, argv, Tcl_AppInit); + return 0; /* Needed only to prevent compiler warning. */ +} + +/* + *---------------------------------------------------------------------- + * + * Tcl_AppInit -- + * + * This procedure performs application-specific initialization. + * Most applications, especially those that incorporate additional + * packages, will have their own version of this procedure. + * + * Results: + * Returns a standard Tcl completion code, and leaves an error + * message in interp->result if an error occurs. + * + * Side effects: + * Depends on the startup script. + * + *---------------------------------------------------------------------- + */ + +int +Tcl_AppInit(interp) + Tcl_Interp *interp; /* Interpreter for application. */ +{ + if (Tcl_Init(interp) == TCL_ERROR) { + return TCL_ERROR; + } + if (Tk_Init(interp) == TCL_ERROR) { + return TCL_ERROR; + } + Tcl_StaticPackage(interp, "Tk", Tk_Init, Tk_SafeInit); +#ifdef TK_TEST + if (Tktest_Init(interp) == TCL_ERROR) { + return TCL_ERROR; + } + Tcl_StaticPackage(interp, "Tktest", Tktest_Init, + (Tcl_PackageInitProc *) NULL); +#endif /* TK_TEST */ + + + /* + * Call the init procedures for included packages. Each call should + * look like this: + * + * if (Mod_Init(interp) == TCL_ERROR) { + * return TCL_ERROR; + * } + * + * where "Mod" is the name of the module. + */ + + /* + * Call Tcl_CreateCommand for application-specific commands, if + * they weren't already created by the init procedures called above. + */ + + /* + * Specify a user-specific startup file to invoke if the application + * is run interactively. Typically the startup file is "~/.apprc" + * where "app" is the name of the application. If this line is deleted + * then no user-specific startup file will be run under any conditions. + */ + + Tcl_SetVar(interp, "tcl_rcFileName", "~/.wishrc", TCL_GLOBAL_ONLY); + return TCL_OK; +} diff --git a/unix/tkConfig.sh.in b/unix/tkConfig.sh.in new file mode 100644 index 0000000..544d658 --- /dev/null +++ b/unix/tkConfig.sh.in @@ -0,0 +1,68 @@ +# tkConfig.sh -- +# +# This shell script (for sh) is generated automatically by Tk's +# configure script. It will create shell variables for most of +# the configuration options discovered by the configure script. +# This script is intended to be included by the configure scripts +# for Tk extensions so that they don't have to figure this all +# out for themselves. This file does not duplicate information +# already provided by tclConfig.sh, so you may need to use that +# file in addition to this one. +# +# The information in this file is specific to a single platform. +# +# SCCS: @(#) tkConfig.sh.in 1.11 97/10/30 13:29:13 + +# Tk's version number. +TK_VERSION='@TK_VERSION@' +TK_MAJOR_VERSION='@TK_MAJOR_VERSION@' +TK_MINOR_VERSION='@TK_MINOR_VERSION@' +TK_PATCH_LEVEL='@TK_PATCH_LEVEL@' + +# -D flags for use with the C compiler. +TK_DEFS='@DEFS@' + +# Flag, 1: we built a shared lib, 0 we didn't +TK_SHARED_BUILD=@TK_SHARED_BUILD@ + +# The name of the Tk library (may be either a .a file or a shared library): +TK_LIB_FILE=@TK_LIB_FILE@ + +# Additional libraries to use when linking Tk. +TK_LIBS='@XLIBSW@ @DL_LIBS@ @LIBS@ @MATH_LIBS@' + +# Top-level directory in which Tcl's platform-independent files are +# installed. +TK_PREFIX='@prefix@' + +# Top-level directory in which Tcl's platform-specific files (e.g. +# executables) are installed. +TK_EXEC_PREFIX='@exec_prefix@' + +# -I switch(es) to use to make all of the X11 include files accessible: +TK_XINCLUDES='@XINCLUDES@' + +# Linker switch(es) to use to link with the X11 library archive. +TK_XLIBSW='@XLIBSW@' + +# String to pass to linker to pick up the Tk library from its +# build directory. +TK_BUILD_LIB_SPEC='@TK_BUILD_LIB_SPEC@' + +# String to pass to linker to pick up the Tk library from its +# installed directory. +TK_LIB_SPEC='@TK_LIB_SPEC@' + +# Location of the top-level source directory from which Tk was built. +# This is the directory that contains a README file as well as +# subdirectories such as generic, unix, etc. If Tk was compiled in a +# different place than the directory containing the source files, this +# points to the location of the sources, not the location where Tk was +# compiled. +TK_SRC_DIR='@TK_SRC_DIR@' + +# Needed if you want to make a 'fat' shared library library +# containing tk objects or link a different wish. +TK_CC_SEARCH_FLAGS='@TK_CC_SEARCH_FLAGS@' +TK_LD_SEARCH_FLAGS='@TK_LD_SEARCH_FLAGS@' + diff --git a/unix/tkUnix.c b/unix/tkUnix.c new file mode 100644 index 0000000..ca6fa07 --- /dev/null +++ b/unix/tkUnix.c @@ -0,0 +1,79 @@ +/* + * tkUnix.c -- + * + * This file contains procedures that are UNIX/X-specific, and + * will probably have to be written differently for Windows or + * Macintosh platforms. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnix.c 1.5 97/01/07 11:41:39 + */ + +#include <tkInt.h> + +/* + *---------------------------------------------------------------------- + * + * TkGetServerInfo -- + * + * Given a window, this procedure returns information about + * the window server for that window. This procedure provides + * the guts of the "winfo server" command. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkGetServerInfo(interp, tkwin) + Tcl_Interp *interp; /* The server information is returned in + * this interpreter's result. */ + Tk_Window tkwin; /* Token for window; this selects a + * particular display and server. */ +{ + char buffer[50], buffer2[50]; + + sprintf(buffer, "X%dR%d ", ProtocolVersion(Tk_Display(tkwin)), + ProtocolRevision(Tk_Display(tkwin))); + sprintf(buffer2, " %d", VendorRelease(Tk_Display(tkwin))); + Tcl_AppendResult(interp, buffer, ServerVendor(Tk_Display(tkwin)), + buffer2, (char *) NULL); +} + +/* + *---------------------------------------------------------------------- + * + * TkGetDefaultScreenName -- + * + * Returns the name of the screen that Tk should use during + * initialization. + * + * Results: + * Returns the argument or a string that should not be freed by + * the caller. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +char * +TkGetDefaultScreenName(interp, screenName) + Tcl_Interp *interp; /* Interp used to find environment variables. */ + char *screenName; /* Screen name from command line, or NULL. */ +{ + if ((screenName == NULL) || (screenName[0] == '\0')) { + screenName = Tcl_GetVar2(interp, "env", "DISPLAY", TCL_GLOBAL_ONLY); + } + return screenName; +} diff --git a/unix/tkUnix3d.c b/unix/tkUnix3d.c new file mode 100644 index 0000000..e7584ce --- /dev/null +++ b/unix/tkUnix3d.c @@ -0,0 +1,448 @@ +/* + * tkUnix3d.c -- + * + * This file contains the platform specific routines for + * drawing 3d borders in the Motif style. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnix3d.c 1.3 96/11/20 14:24:38 + */ + +#include <tk3d.h> + +/* + * This structure is used to keep track of the extra colors used + * by Unix 3d borders. + */ + +typedef struct { + TkBorder info; + GC solidGC; /* Used to draw solid relief. */ +} UnixBorder; + +/* + *---------------------------------------------------------------------- + * + * TkpGetBorder -- + * + * This function allocates a new TkBorder structure. + * + * Results: + * Returns a newly allocated TkBorder. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkBorder * +TkpGetBorder() +{ + UnixBorder *borderPtr = (UnixBorder *) ckalloc(sizeof(UnixBorder)); + borderPtr->solidGC = None; + return (TkBorder *) borderPtr; +} + + +/* + *---------------------------------------------------------------------- + * + * TkpFreeBorder -- + * + * This function frees any colors allocated by the platform + * specific part of this module. + * + * Results: + * None. + * + * Side effects: + * May deallocate some colors. + * + *---------------------------------------------------------------------- + */ + +void +TkpFreeBorder(borderPtr) + TkBorder *borderPtr; +{ + UnixBorder *unixBorderPtr = (UnixBorder *) borderPtr; + Display *display = DisplayOfScreen(borderPtr->screen); + + if (unixBorderPtr->solidGC != None) { + Tk_FreeGC(display, unixBorderPtr->solidGC); + } +} +/* + *-------------------------------------------------------------- + * + * Tk_3DVerticalBevel -- + * + * This procedure draws a vertical bevel along one side of + * an object. The bevel is always rectangular in shape: + * ||| + * ||| + * ||| + * ||| + * ||| + * ||| + * An appropriate shadow color is chosen for the bevel based + * on the leftBevel and relief arguments. Normally this + * procedure is called first, then Tk_3DHorizontalBevel is + * called next to draw neat corners. + * + * Results: + * None. + * + * Side effects: + * Graphics are drawn in drawable. + * + *-------------------------------------------------------------- + */ + +void +Tk_3DVerticalBevel(tkwin, drawable, border, x, y, width, height, + leftBevel, relief) + Tk_Window tkwin; /* Window for which border was allocated. */ + Drawable drawable; /* X window or pixmap in which to draw. */ + Tk_3DBorder border; /* Token for border to draw. */ + int x, y, width, height; /* Area of vertical bevel. */ + int leftBevel; /* Non-zero means this bevel forms the + * left side of the object; 0 means it + * forms the right side. */ + int relief; /* Kind of bevel to draw. For example, + * TK_RELIEF_RAISED means interior of + * object should appear higher than + * exterior. */ +{ + TkBorder *borderPtr = (TkBorder *) border; + GC left, right; + Display *display = Tk_Display(tkwin); + + if ((borderPtr->lightGC == None) && (relief != TK_RELIEF_FLAT)) { + TkpGetShadows(borderPtr, tkwin); + } + + if (relief == TK_RELIEF_RAISED) { + XFillRectangle(display, drawable, + (leftBevel) ? borderPtr->lightGC : borderPtr->darkGC, + x, y, (unsigned) width, (unsigned) height); + } else if (relief == TK_RELIEF_SUNKEN) { + XFillRectangle(display, drawable, + (leftBevel) ? borderPtr->darkGC : borderPtr->lightGC, + x, y, (unsigned) width, (unsigned) height); + } else if (relief == TK_RELIEF_RIDGE) { + int half; + + left = borderPtr->lightGC; + right = borderPtr->darkGC; + ridgeGroove: + half = width/2; + if (!leftBevel && (width & 1)) { + half++; + } + XFillRectangle(display, drawable, left, x, y, (unsigned) half, + (unsigned) height); + XFillRectangle(display, drawable, right, x+half, y, + (unsigned) (width-half), (unsigned) height); + } else if (relief == TK_RELIEF_GROOVE) { + left = borderPtr->darkGC; + right = borderPtr->lightGC; + goto ridgeGroove; + } else if (relief == TK_RELIEF_FLAT) { + XFillRectangle(display, drawable, borderPtr->bgGC, x, y, + (unsigned) width, (unsigned) height); + } else if (relief == TK_RELIEF_SOLID) { + UnixBorder *unixBorderPtr = (UnixBorder *) borderPtr; + if (unixBorderPtr->solidGC == None) { + XGCValues gcValues; + + gcValues.foreground = BlackPixelOfScreen(borderPtr->screen); + unixBorderPtr->solidGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + } + XFillRectangle(display, drawable, unixBorderPtr->solidGC, x, y, + (unsigned) width, (unsigned) height); + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_3DHorizontalBevel -- + * + * This procedure draws a horizontal bevel along one side of + * an object. The bevel has mitered corners (depending on + * leftIn and rightIn arguments). + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +Tk_3DHorizontalBevel(tkwin, drawable, border, x, y, width, height, + leftIn, rightIn, topBevel, relief) + Tk_Window tkwin; /* Window for which border was allocated. */ + Drawable drawable; /* X window or pixmap in which to draw. */ + Tk_3DBorder border; /* Token for border to draw. */ + int x, y, width, height; /* Bounding box of area of bevel. Height + * gives width of border. */ + int leftIn, rightIn; /* Describes whether the left and right + * edges of the bevel angle in or out as + * they go down. For example, if "leftIn" + * is true, the left side of the bevel + * looks like this: + * ___________ + * __________ + * _________ + * ________ + */ + int topBevel; /* Non-zero means this bevel forms the + * top side of the object; 0 means it + * forms the bottom side. */ + int relief; /* Kind of bevel to draw. For example, + * TK_RELIEF_RAISED means interior of + * object should appear higher than + * exterior. */ +{ + TkBorder *borderPtr = (TkBorder *) border; + Display *display = Tk_Display(tkwin); + int bottom, halfway, x1, x2, x1Delta, x2Delta; + UnixBorder *unixBorderPtr = (UnixBorder *) borderPtr; + GC topGC = None, bottomGC = None; + /* Initializations needed only to prevent + * compiler warnings. */ + + if ((borderPtr->lightGC == None) && (relief != TK_RELIEF_FLAT) && + (relief != TK_RELIEF_SOLID)) { + TkpGetShadows(borderPtr, tkwin); + } + + /* + * Compute a GC for the top half of the bevel and a GC for the + * bottom half (they're the same in many cases). + */ + + switch (relief) { + case TK_RELIEF_FLAT: + topGC = bottomGC = borderPtr->bgGC; + break; + case TK_RELIEF_GROOVE: + topGC = borderPtr->darkGC; + bottomGC = borderPtr->lightGC; + break; + case TK_RELIEF_RAISED: + topGC = bottomGC = + (topBevel) ? borderPtr->lightGC : borderPtr->darkGC; + break; + case TK_RELIEF_RIDGE: + topGC = borderPtr->lightGC; + bottomGC = borderPtr->darkGC; + break; + case TK_RELIEF_SOLID: + if (unixBorderPtr->solidGC == None) { + XGCValues gcValues; + + gcValues.foreground = BlackPixelOfScreen(borderPtr->screen); + unixBorderPtr->solidGC = Tk_GetGC(tkwin, GCForeground, + &gcValues); + } + XFillRectangle(display, drawable, unixBorderPtr->solidGC, x, y, + (unsigned) width, (unsigned) height); + return; + case TK_RELIEF_SUNKEN: + topGC = bottomGC = + (topBevel) ? borderPtr->darkGC : borderPtr->lightGC; + break; + } + + /* + * Compute various other geometry-related stuff. + */ + + x1 = x; + if (!leftIn) { + x1 += height; + } + x2 = x+width; + if (!rightIn) { + x2 -= height; + } + x1Delta = (leftIn) ? 1 : -1; + x2Delta = (rightIn) ? -1 : 1; + halfway = y + height/2; + if (!topBevel && (height & 1)) { + halfway++; + } + bottom = y + height; + + /* + * Draw one line for each y-coordinate covered by the bevel. + */ + + for ( ; y < bottom; y++) { + /* + * In some weird cases (such as large border widths for skinny + * rectangles) x1 can be >= x2. Don't draw the lines + * in these cases. + */ + + if (x1 < x2) { + XFillRectangle(display, drawable, + (y < halfway) ? topGC : bottomGC, x1, y, + (unsigned) (x2-x1), (unsigned) 1); + } + x1 += x1Delta; + x2 += x2Delta; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetShadows -- + * + * This procedure computes the shadow colors for a 3-D border + * and fills in the corresponding fields of the Border structure. + * It's called lazily, so that the colors aren't allocated until + * something is actually drawn with them. That way, if a border + * is only used for flat backgrounds the shadow colors will + * never be allocated. + * + * Results: + * None. + * + * Side effects: + * The lightGC and darkGC fields in borderPtr get filled in, + * if they weren't already. + * + *---------------------------------------------------------------------- + */ + +void +TkpGetShadows(borderPtr, tkwin) + TkBorder *borderPtr; /* Information about border. */ + Tk_Window tkwin; /* Window where border will be used for + * drawing. */ +{ + XColor lightColor, darkColor; + int stressed, tmp1, tmp2; + XGCValues gcValues; + + if (borderPtr->lightGC != None) { + return; + } + stressed = TkpCmapStressed(tkwin, borderPtr->colormap); + + /* + * First, handle the case of a color display with lots of colors. + * The shadow colors get computed using whichever formula results + * in the greatest change in color: + * 1. Lighter shadow is half-way to white, darker shadow is half + * way to dark. + * 2. Lighter shadow is 40% brighter than background, darker shadow + * is 40% darker than background. + */ + + if (!stressed && (Tk_Depth(tkwin) >= 6)) { + /* + * This is a color display with lots of colors. For the dark + * shadow, cut 40% from each of the background color components. + * For the light shadow, boost each component by 40% or half-way + * to white, whichever is greater (the first approach works + * better for unsaturated colors, the second for saturated ones). + */ + + darkColor.red = (60 * (int) borderPtr->bgColorPtr->red)/100; + darkColor.green = (60 * (int) borderPtr->bgColorPtr->green)/100; + darkColor.blue = (60 * (int) borderPtr->bgColorPtr->blue)/100; + borderPtr->darkColorPtr = Tk_GetColorByValue(tkwin, &darkColor); + gcValues.foreground = borderPtr->darkColorPtr->pixel; + borderPtr->darkGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + + /* + * Compute the colors using integers, not using lightColor.red + * etc.: these are shorts and may have problems with integer + * overflow. + */ + + tmp1 = (14 * (int) borderPtr->bgColorPtr->red)/10; + if (tmp1 > MAX_INTENSITY) { + tmp1 = MAX_INTENSITY; + } + tmp2 = (MAX_INTENSITY + (int) borderPtr->bgColorPtr->red)/2; + lightColor.red = (tmp1 > tmp2) ? tmp1 : tmp2; + tmp1 = (14 * (int) borderPtr->bgColorPtr->green)/10; + if (tmp1 > MAX_INTENSITY) { + tmp1 = MAX_INTENSITY; + } + tmp2 = (MAX_INTENSITY + (int) borderPtr->bgColorPtr->green)/2; + lightColor.green = (tmp1 > tmp2) ? tmp1 : tmp2; + tmp1 = (14 * (int) borderPtr->bgColorPtr->blue)/10; + if (tmp1 > MAX_INTENSITY) { + tmp1 = MAX_INTENSITY; + } + tmp2 = (MAX_INTENSITY + (int) borderPtr->bgColorPtr->blue)/2; + lightColor.blue = (tmp1 > tmp2) ? tmp1 : tmp2; + borderPtr->lightColorPtr = Tk_GetColorByValue(tkwin, &lightColor); + gcValues.foreground = borderPtr->lightColorPtr->pixel; + borderPtr->lightGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + return; + } + + if (borderPtr->shadow == None) { + borderPtr->shadow = Tk_GetBitmap((Tcl_Interp *) NULL, tkwin, + Tk_GetUid("gray50")); + if (borderPtr->shadow == None) { + panic("TkpGetShadows couldn't allocate bitmap for border"); + } + } + if (borderPtr->visual->map_entries > 2) { + /* + * This isn't a monochrome display, but the colormap either + * ran out of entries or didn't have very many to begin with. + * Generate the light shadows with a white stipple and the + * dark shadows with a black stipple. + */ + + gcValues.foreground = borderPtr->bgColorPtr->pixel; + gcValues.background = BlackPixelOfScreen(borderPtr->screen); + gcValues.stipple = borderPtr->shadow; + gcValues.fill_style = FillOpaqueStippled; + borderPtr->darkGC = Tk_GetGC(tkwin, + GCForeground|GCBackground|GCStipple|GCFillStyle, &gcValues); + gcValues.background = WhitePixelOfScreen(borderPtr->screen); + borderPtr->lightGC = Tk_GetGC(tkwin, + GCForeground|GCBackground|GCStipple|GCFillStyle, &gcValues); + return; + } + + /* + * This is just a measly monochrome display, hardly even worth its + * existence on this earth. Make one shadow a 50% stipple and the + * other the opposite of the background. + */ + + gcValues.foreground = WhitePixelOfScreen(borderPtr->screen); + gcValues.background = BlackPixelOfScreen(borderPtr->screen); + gcValues.stipple = borderPtr->shadow; + gcValues.fill_style = FillOpaqueStippled; + borderPtr->lightGC = Tk_GetGC(tkwin, + GCForeground|GCBackground|GCStipple|GCFillStyle, &gcValues); + if (borderPtr->bgColorPtr->pixel + == WhitePixelOfScreen(borderPtr->screen)) { + gcValues.foreground = BlackPixelOfScreen(borderPtr->screen); + borderPtr->darkGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + } else { + borderPtr->darkGC = borderPtr->lightGC; + borderPtr->lightGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + } +} diff --git a/unix/tkUnixButton.c b/unix/tkUnixButton.c new file mode 100644 index 0000000..8c74dcb --- /dev/null +++ b/unix/tkUnixButton.c @@ -0,0 +1,478 @@ +/* + * tkUnixButton.c -- + * + * This file implements the Unix specific portion of the button + * widgets. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixButton.c 1.4 97/06/06 11:21:40 + */ + +#include "tkButton.h" + +/* + * Declaration of Unix specific button structure. + */ + +typedef struct UnixButton { + TkButton info; /* Generic button info. */ +} UnixButton; + +/* + * The class procedure table for the button widgets. + */ + +TkClassProcs tkpButtonProcs = { + NULL, /* createProc. */ + TkButtonWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + +/* + *---------------------------------------------------------------------- + * + * TkpCreateButton -- + * + * Allocate a new TkButton structure. + * + * Results: + * Returns a newly allocated TkButton structure. + * + * Side effects: + * Registers an event handler for the widget. + * + *---------------------------------------------------------------------- + */ + +TkButton * +TkpCreateButton(tkwin) + Tk_Window tkwin; +{ + UnixButton *butPtr = (UnixButton *)ckalloc(sizeof(UnixButton)); + return (TkButton *) butPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpDisplayButton -- + * + * This procedure is invoked to display a button widget. It is + * normally invoked as an idle handler. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the button in its + * current mode. The REDRAW_PENDING flag is cleared. + * + *---------------------------------------------------------------------- + */ + +void +TkpDisplayButton(clientData) + ClientData clientData; /* Information about widget. */ +{ + register TkButton *butPtr = (TkButton *) clientData; + GC gc; + Tk_3DBorder border; + Pixmap pixmap; + int x = 0; /* Initialization only needed to stop + * compiler warning. */ + int y, relief; + register Tk_Window tkwin = butPtr->tkwin; + int width, height; + int offset; /* 0 means this is a label widget. 1 means + * it is a flavor of button, so we offset + * the text to make the button appear to + * move up and down as the relief changes. */ + + butPtr->flags &= ~REDRAW_PENDING; + if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + return; + } + + border = butPtr->normalBorder; + if ((butPtr->state == tkDisabledUid) && (butPtr->disabledFg != NULL)) { + gc = butPtr->disabledGC; + } else if ((butPtr->state == tkActiveUid) + && !Tk_StrictMotif(butPtr->tkwin)) { + gc = butPtr->activeTextGC; + border = butPtr->activeBorder; + } else { + gc = butPtr->normalTextGC; + } + if ((butPtr->flags & SELECTED) && (butPtr->state != tkActiveUid) + && (butPtr->selectBorder != NULL) && !butPtr->indicatorOn) { + border = butPtr->selectBorder; + } + + /* + * Override the relief specified for the button if this is a + * checkbutton or radiobutton and there's no indicator. + */ + + relief = butPtr->relief; + if ((butPtr->type >= TYPE_CHECK_BUTTON) && !butPtr->indicatorOn) { + relief = (butPtr->flags & SELECTED) ? TK_RELIEF_SUNKEN + : TK_RELIEF_RAISED; + } + + offset = (butPtr->type == TYPE_BUTTON) && !Tk_StrictMotif(butPtr->tkwin); + + /* + * In order to avoid screen flashes, this procedure redraws + * the button in a pixmap, then copies the pixmap to the + * screen in a single operation. This means that there's no + * point in time where the on-sreen image has been cleared. + */ + + pixmap = Tk_GetPixmap(butPtr->display, Tk_WindowId(tkwin), + Tk_Width(tkwin), Tk_Height(tkwin), Tk_Depth(tkwin)); + Tk_Fill3DRectangle(tkwin, pixmap, border, 0, 0, Tk_Width(tkwin), + Tk_Height(tkwin), 0, TK_RELIEF_FLAT); + + /* + * Display image or bitmap or text for button. + */ + + if (butPtr->image != None) { + Tk_SizeOfImage(butPtr->image, &width, &height); + + imageOrBitmap: + TkComputeAnchor(butPtr->anchor, tkwin, 0, 0, + butPtr->indicatorSpace + width, height, &x, &y); + x += butPtr->indicatorSpace; + + x += offset; + y += offset; + if (relief == TK_RELIEF_RAISED) { + x -= offset; + y -= offset; + } else if (relief == TK_RELIEF_SUNKEN) { + x += offset; + y += offset; + } + if (butPtr->image != NULL) { + if ((butPtr->selectImage != NULL) && (butPtr->flags & SELECTED)) { + Tk_RedrawImage(butPtr->selectImage, 0, 0, width, height, pixmap, + x, y); + } else { + Tk_RedrawImage(butPtr->image, 0, 0, width, height, pixmap, + x, y); + } + } else { + XSetClipOrigin(butPtr->display, gc, x, y); + XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, gc, 0, 0, + (unsigned int) width, (unsigned int) height, x, y, 1); + XSetClipOrigin(butPtr->display, gc, 0, 0); + } + y += height/2; + } else if (butPtr->bitmap != None) { + Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height); + goto imageOrBitmap; + } else { + TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY, + butPtr->indicatorSpace + butPtr->textWidth, butPtr->textHeight, + &x, &y); + + x += butPtr->indicatorSpace; + + x += offset; + y += offset; + if (relief == TK_RELIEF_RAISED) { + x -= offset; + y -= offset; + } else if (relief == TK_RELIEF_SUNKEN) { + x += offset; + y += offset; + } + Tk_DrawTextLayout(butPtr->display, pixmap, gc, butPtr->textLayout, + x, y, 0, -1); + Tk_UnderlineTextLayout(butPtr->display, pixmap, gc, + butPtr->textLayout, x, y, butPtr->underline); + y += butPtr->textHeight/2; + } + + /* + * Draw the indicator for check buttons and radio buttons. At this + * point x and y refer to the top-left corner of the text or image + * or bitmap. + */ + + if ((butPtr->type == TYPE_CHECK_BUTTON) && butPtr->indicatorOn) { + int dim; + + dim = butPtr->indicatorDiameter; + x -= butPtr->indicatorSpace; + y -= dim/2; + if (dim > 2*butPtr->borderWidth) { + Tk_Draw3DRectangle(tkwin, pixmap, border, x, y, dim, dim, + butPtr->borderWidth, + (butPtr->flags & SELECTED) ? TK_RELIEF_SUNKEN : + TK_RELIEF_RAISED); + x += butPtr->borderWidth; + y += butPtr->borderWidth; + dim -= 2*butPtr->borderWidth; + if (butPtr->flags & SELECTED) { + GC gc; + + gc = Tk_3DBorderGC(tkwin,(butPtr->selectBorder != NULL) + ? butPtr->selectBorder : butPtr->normalBorder, + TK_3D_FLAT_GC); + XFillRectangle(butPtr->display, pixmap, gc, x, y, + (unsigned int) dim, (unsigned int) dim); + } else { + Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, x, y, + dim, dim, butPtr->borderWidth, TK_RELIEF_FLAT); + } + } + } else if ((butPtr->type == TYPE_RADIO_BUTTON) && butPtr->indicatorOn) { + XPoint points[4]; + int radius; + + radius = butPtr->indicatorDiameter/2; + points[0].x = x - butPtr->indicatorSpace; + points[0].y = y; + points[1].x = points[0].x + radius; + points[1].y = points[0].y + radius; + points[2].x = points[1].x + radius; + points[2].y = points[0].y; + points[3].x = points[1].x; + points[3].y = points[0].y - radius; + if (butPtr->flags & SELECTED) { + GC gc; + + gc = Tk_3DBorderGC(tkwin, (butPtr->selectBorder != NULL) + ? butPtr->selectBorder : butPtr->normalBorder, + TK_3D_FLAT_GC); + XFillPolygon(butPtr->display, pixmap, gc, points, 4, Convex, + CoordModeOrigin); + } else { + Tk_Fill3DPolygon(tkwin, pixmap, butPtr->normalBorder, points, + 4, butPtr->borderWidth, TK_RELIEF_FLAT); + } + Tk_Draw3DPolygon(tkwin, pixmap, border, points, 4, butPtr->borderWidth, + (butPtr->flags & SELECTED) ? TK_RELIEF_SUNKEN : + TK_RELIEF_RAISED); + } + + /* + * If the button is disabled with a stipple rather than a special + * foreground color, generate the stippled effect. If the widget + * is selected and we use a different background color when selected, + * must temporarily modify the GC. + */ + + if ((butPtr->state == tkDisabledUid) + && ((butPtr->disabledFg == NULL) || (butPtr->image != NULL))) { + if ((butPtr->flags & SELECTED) && !butPtr->indicatorOn + && (butPtr->selectBorder != NULL)) { + XSetForeground(butPtr->display, butPtr->disabledGC, + Tk_3DBorderColor(butPtr->selectBorder)->pixel); + } + XFillRectangle(butPtr->display, pixmap, butPtr->disabledGC, + butPtr->inset, butPtr->inset, + (unsigned) (Tk_Width(tkwin) - 2*butPtr->inset), + (unsigned) (Tk_Height(tkwin) - 2*butPtr->inset)); + if ((butPtr->flags & SELECTED) && !butPtr->indicatorOn + && (butPtr->selectBorder != NULL)) { + XSetForeground(butPtr->display, butPtr->disabledGC, + Tk_3DBorderColor(butPtr->normalBorder)->pixel); + } + } + + /* + * Draw the border and traversal highlight last. This way, if the + * button's contents overflow they'll be covered up by the border. + * This code is complicated by the possible combinations of focus + * highlight and default rings. We draw the focus and highlight rings + * using the highlight border and highlight foreground color. + */ + + if (relief != TK_RELIEF_FLAT) { + int inset = butPtr->highlightWidth; + if (butPtr->defaultState == tkActiveUid) { + /* + * Draw the default ring with 2 pixels of space between the + * default ring and the button and the default ring and the + * focus ring. Note that we need to explicitly draw the space + * in the highlightBorder color to ensure that we overwrite any + * overflow text and/or a different button background color. + */ + + Tk_Draw3DRectangle(tkwin, pixmap, butPtr->highlightBorder, inset, + inset, Tk_Width(tkwin) - 2*inset, + Tk_Height(tkwin) - 2*inset, 2, TK_RELIEF_FLAT); + inset += 2; + Tk_Draw3DRectangle(tkwin, pixmap, butPtr->highlightBorder, inset, + inset, Tk_Width(tkwin) - 2*inset, + Tk_Height(tkwin) - 2*inset, 1, TK_RELIEF_SUNKEN); + inset++; + Tk_Draw3DRectangle(tkwin, pixmap, butPtr->highlightBorder, inset, + inset, Tk_Width(tkwin) - 2*inset, + Tk_Height(tkwin) - 2*inset, 2, TK_RELIEF_FLAT); + + inset += 2; + } else if (butPtr->defaultState == tkNormalUid) { + /* + * Leave room for the default ring and write over any text or + * background color. + */ + + Tk_Draw3DRectangle(tkwin, pixmap, butPtr->highlightBorder, 0, + 0, Tk_Width(tkwin), + Tk_Height(tkwin), 5, TK_RELIEF_FLAT); + inset += 5; + } + + /* + * Draw the button border. + */ + + Tk_Draw3DRectangle(tkwin, pixmap, border, inset, inset, + Tk_Width(tkwin) - 2*inset, Tk_Height(tkwin) - 2*inset, + butPtr->borderWidth, relief); + } + if (butPtr->highlightWidth != 0) { + GC gc; + + if (butPtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(butPtr->highlightColorPtr, pixmap); + } else { + gc = Tk_GCForColor(Tk_3DBorderColor(butPtr->highlightBorder), + pixmap); + } + + /* + * Make sure the focus ring shrink-wraps the actual button, not the + * padding space left for a default ring. + */ + + if (butPtr->defaultState == tkNormalUid) { + TkDrawInsetFocusHighlight(tkwin, gc, butPtr->highlightWidth, + pixmap, 5); + } else { + Tk_DrawFocusHighlight(tkwin, gc, butPtr->highlightWidth, pixmap); + } + } + + /* + * Copy the information from the off-screen pixmap onto the screen, + * then delete the pixmap. + */ + + XCopyArea(butPtr->display, pixmap, Tk_WindowId(tkwin), + butPtr->copyGC, 0, 0, (unsigned) Tk_Width(tkwin), + (unsigned) Tk_Height(tkwin), 0, 0); + Tk_FreePixmap(butPtr->display, pixmap); +} + +/* + *---------------------------------------------------------------------- + * + * TkpComputeButtonGeometry -- + * + * After changes in a button's text or bitmap, this procedure + * recomputes the button's geometry and passes this information + * along to the geometry manager for the window. + * + * Results: + * None. + * + * Side effects: + * The button's window may change size. + * + *---------------------------------------------------------------------- + */ + +void +TkpComputeButtonGeometry(butPtr) + register TkButton *butPtr; /* Button whose geometry may have changed. */ +{ + int width, height, avgWidth; + Tk_FontMetrics fm; + + if (butPtr->highlightWidth < 0) { + butPtr->highlightWidth = 0; + } + butPtr->inset = butPtr->highlightWidth + butPtr->borderWidth; + + /* + * Leave room for the default ring if needed. + */ + + if (butPtr->defaultState != tkDisabledUid) { + butPtr->inset += 5; + } + butPtr->indicatorSpace = 0; + if (butPtr->image != NULL) { + Tk_SizeOfImage(butPtr->image, &width, &height); + imageOrBitmap: + if (butPtr->width > 0) { + width = butPtr->width; + } + if (butPtr->height > 0) { + height = butPtr->height; + } + if ((butPtr->type >= TYPE_CHECK_BUTTON) && butPtr->indicatorOn) { + butPtr->indicatorSpace = height; + if (butPtr->type == TYPE_CHECK_BUTTON) { + butPtr->indicatorDiameter = (65*height)/100; + } else { + butPtr->indicatorDiameter = (75*height)/100; + } + } + } else if (butPtr->bitmap != None) { + Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height); + goto imageOrBitmap; + } else { + Tk_FreeTextLayout(butPtr->textLayout); + butPtr->textLayout = Tk_ComputeTextLayout(butPtr->tkfont, + butPtr->text, -1, butPtr->wrapLength, butPtr->justify, 0, + &butPtr->textWidth, &butPtr->textHeight); + + width = butPtr->textWidth; + height = butPtr->textHeight; + avgWidth = Tk_TextWidth(butPtr->tkfont, "0", 1); + Tk_GetFontMetrics(butPtr->tkfont, &fm); + + if (butPtr->width > 0) { + width = butPtr->width * avgWidth; + } + if (butPtr->height > 0) { + height = butPtr->height * fm.linespace; + } + if ((butPtr->type >= TYPE_CHECK_BUTTON) && butPtr->indicatorOn) { + butPtr->indicatorDiameter = fm.linespace; + if (butPtr->type == TYPE_CHECK_BUTTON) { + butPtr->indicatorDiameter = (80*butPtr->indicatorDiameter)/100; + } + butPtr->indicatorSpace = butPtr->indicatorDiameter + avgWidth; + } + } + + /* + * When issuing the geometry request, add extra space for the indicator, + * if any, and for the border and padding, plus two extra pixels so the + * display can be offset by 1 pixel in either direction for the raised + * or lowered effect. + */ + + if ((butPtr->image == NULL) && (butPtr->bitmap == None)) { + width += 2*butPtr->padX; + height += 2*butPtr->padY; + } + if ((butPtr->type == TYPE_BUTTON) && !Tk_StrictMotif(butPtr->tkwin)) { + width += 2; + height += 2; + } + Tk_GeometryRequest(butPtr->tkwin, (int) (width + butPtr->indicatorSpace + + 2*butPtr->inset), (int) (height + 2*butPtr->inset)); + Tk_SetInternalBorder(butPtr->tkwin, butPtr->inset); +} diff --git a/unix/tkUnixColor.c b/unix/tkUnixColor.c new file mode 100644 index 0000000..d3a5a27 --- /dev/null +++ b/unix/tkUnixColor.c @@ -0,0 +1,424 @@ +/* + * tkUnixColor.c -- + * + * This file contains the platform specific color routines + * needed for X support. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixColor.c 1.1 96/10/22 16:52:31 + */ + +#include <tkColor.h> + +/* + * If a colormap fills up, attempts to allocate new colors from that + * colormap will fail. When that happens, we'll just choose the + * closest color from those that are available in the colormap. + * One of the following structures will be created for each "stressed" + * colormap to keep track of the colors that are available in the + * colormap (otherwise we would have to re-query from the server on + * each allocation, which would be very slow). These entries are + * flushed after a few seconds, since other clients may release or + * reallocate colors over time. + */ + +struct TkStressedCmap { + Colormap colormap; /* X's token for the colormap. */ + int numColors; /* Number of entries currently active + * at *colorPtr. */ + XColor *colorPtr; /* Pointer to malloc'ed array of all + * colors that seem to be available in + * the colormap. Some may not actually + * be available, e.g. because they are + * read-write for another client; when + * we find this out, we remove them + * from the array. */ + struct TkStressedCmap *nextPtr; /* Next in list of all stressed + * colormaps for the display. */ +}; + +/* + * Forward declarations for procedures defined in this file: + */ + +static void DeleteStressedCmap _ANSI_ARGS_((Display *display, + Colormap colormap)); +static void FindClosestColor _ANSI_ARGS_((Tk_Window tkwin, + XColor *desiredColorPtr, XColor *actualColorPtr)); + +/* + *---------------------------------------------------------------------- + * + * TkpFreeColor -- + * + * Release the specified color back to the system. + * + * Results: + * None + * + * Side effects: + * Invalidates the colormap cache for the colormap associated with + * the given color. + * + *---------------------------------------------------------------------- + */ + +void +TkpFreeColor(tkColPtr) + TkColor *tkColPtr; /* Color to be released. Must have been + * allocated by TkpGetColor or + * TkpGetColorByValue. */ +{ + Visual *visual; + Screen *screen = tkColPtr->screen; + + /* + * Careful! Don't free black or white, since this will + * make some servers very unhappy. Also, there is a bug in + * some servers (such Sun's X11/NeWS server) where reference + * counting is performed incorrectly, so that if a color is + * allocated twice in different places and then freed twice, + * the second free generates an error (this bug existed as of + * 10/1/92). To get around this problem, ignore errors that + * occur during the free operation. + */ + + visual = tkColPtr->visual; + if ((visual->class != StaticGray) && (visual->class != StaticColor) + && (tkColPtr->color.pixel != BlackPixelOfScreen(screen)) + && (tkColPtr->color.pixel != WhitePixelOfScreen(screen))) { + Tk_ErrorHandler handler; + + handler = Tk_CreateErrorHandler(DisplayOfScreen(screen), + -1, -1, -1, (Tk_ErrorProc *) NULL, (ClientData) NULL); + XFreeColors(DisplayOfScreen(screen), tkColPtr->colormap, + &tkColPtr->color.pixel, 1, 0L); + Tk_DeleteErrorHandler(handler); + } + DeleteStressedCmap(DisplayOfScreen(screen), tkColPtr->colormap); +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetColor -- + * + * Allocate a new TkColor for the color with the given name. + * + * Results: + * Returns a newly allocated TkColor, or NULL on failure. + * + * Side effects: + * May invalidate the colormap cache associated with tkwin upon + * allocating a new colormap entry. Allocates a new TkColor + * structure. + * + *---------------------------------------------------------------------- + */ + +TkColor * +TkpGetColor(tkwin, name) + Tk_Window tkwin; /* Window in which color will be used. */ + Tk_Uid name; /* Name of color to allocated (in form + * suitable for passing to XParseColor). */ +{ + Display *display = Tk_Display(tkwin); + Colormap colormap = Tk_Colormap(tkwin); + XColor color; + TkColor *tkColPtr; + + /* + * Map from the name to a pixel value. Call XAllocNamedColor rather than + * XParseColor for non-# names: this saves a server round-trip for those + * names. + */ + + if (*name != '#') { + XColor screen; + + if (XAllocNamedColor(display, colormap, name, &screen, + &color) != 0) { + DeleteStressedCmap(display, colormap); + } else { + /* + * Couldn't allocate the color. Try translating the name to + * a color value, to see whether the problem is a bad color + * name or a full colormap. If the colormap is full, then + * pick an approximation to the desired color. + */ + + if (XLookupColor(display, colormap, name, &color, + &screen) == 0) { + return (TkColor *) NULL; + } + FindClosestColor(tkwin, &screen, &color); + } + } else { + if (XParseColor(display, colormap, name, &color) == 0) { + return (TkColor *) NULL; + } + if (XAllocColor(display, colormap, &color) != 0) { + DeleteStressedCmap(display, colormap); + } else { + FindClosestColor(tkwin, &color, &color); + } + } + + tkColPtr = (TkColor *) ckalloc(sizeof(TkColor)); + tkColPtr->color = color; + + return tkColPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetColorByValue -- + * + * Given a desired set of red-green-blue intensities for a color, + * locate a pixel value to use to draw that color in a given + * window. + * + * Results: + * The return value is a pointer to an TkColor structure that + * indicates the closest red, blue, and green intensities available + * to those specified in colorPtr, and also specifies a pixel + * value to use to draw in that color. + * + * Side effects: + * May invalidate the colormap cache for the specified window. + * Allocates a new TkColor structure. + * + *---------------------------------------------------------------------- + */ + +TkColor * +TkpGetColorByValue(tkwin, colorPtr) + Tk_Window tkwin; /* Window in which color will be used. */ + XColor *colorPtr; /* Red, green, and blue fields indicate + * desired color. */ +{ + Display *display = Tk_Display(tkwin); + Colormap colormap = Tk_Colormap(tkwin); + TkColor *tkColPtr = (TkColor *) ckalloc(sizeof(TkColor)); + + tkColPtr->color.red = colorPtr->red; + tkColPtr->color.green = colorPtr->green; + tkColPtr->color.blue = colorPtr->blue; + if (XAllocColor(display, colormap, &tkColPtr->color) != 0) { + DeleteStressedCmap(display, colormap); + } else { + FindClosestColor(tkwin, &tkColPtr->color, &tkColPtr->color); + } + + return tkColPtr; +} + +/* + *---------------------------------------------------------------------- + * + * FindClosestColor -- + * + * When Tk can't allocate a color because a colormap has filled + * up, this procedure is called to find and allocate the closest + * available color in the colormap. + * + * Results: + * There is no return value, but *actualColorPtr is filled in + * with information about the closest available color in tkwin's + * colormap. This color has been allocated via X, so it must + * be released by the caller when the caller is done with it. + * + * Side effects: + * A color is allocated. + * + *---------------------------------------------------------------------- + */ + +static void +FindClosestColor(tkwin, desiredColorPtr, actualColorPtr) + Tk_Window tkwin; /* Window where color will be used. */ + XColor *desiredColorPtr; /* RGB values of color that was + * wanted (but unavailable). */ + XColor *actualColorPtr; /* Structure to fill in with RGB and + * pixel for closest available + * color. */ +{ + TkStressedCmap *stressPtr; + double tmp, distance, closestDistance; + int i, closest, numFound; + XColor *colorPtr; + TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr; + Colormap colormap = Tk_Colormap(tkwin); + XVisualInfo template, *visInfoPtr; + + /* + * Find the TkStressedCmap structure for this colormap, or create + * a new one if needed. + */ + + for (stressPtr = dispPtr->stressPtr; ; stressPtr = stressPtr->nextPtr) { + if (stressPtr == NULL) { + stressPtr = (TkStressedCmap *) ckalloc(sizeof(TkStressedCmap)); + stressPtr->colormap = colormap; + template.visualid = XVisualIDFromVisual(Tk_Visual(tkwin)); + visInfoPtr = XGetVisualInfo(Tk_Display(tkwin), + VisualIDMask, &template, &numFound); + if (numFound < 1) { + panic("FindClosestColor couldn't lookup visual"); + } + stressPtr->numColors = visInfoPtr->colormap_size; + XFree((char *) visInfoPtr); + stressPtr->colorPtr = (XColor *) ckalloc((unsigned) + (stressPtr->numColors * sizeof(XColor))); + for (i = 0; i < stressPtr->numColors; i++) { + stressPtr->colorPtr[i].pixel = (unsigned long) i; + } + XQueryColors(dispPtr->display, colormap, stressPtr->colorPtr, + stressPtr->numColors); + stressPtr->nextPtr = dispPtr->stressPtr; + dispPtr->stressPtr = stressPtr; + break; + } + if (stressPtr->colormap == colormap) { + break; + } + } + + /* + * Find the color that best approximates the desired one, then + * try to allocate that color. If that fails, it must mean that + * the color was read-write (so we can't use it, since it's owner + * might change it) or else it was already freed. Try again, + * over and over again, until something succeeds. + */ + + while (1) { + if (stressPtr->numColors == 0) { + panic("FindClosestColor ran out of colors"); + } + closestDistance = 1e30; + closest = 0; + for (colorPtr = stressPtr->colorPtr, i = 0; i < stressPtr->numColors; + colorPtr++, i++) { + /* + * Use Euclidean distance in RGB space, weighted by Y (of YIQ) + * as the objective function; this accounts for differences + * in the color sensitivity of the eye. + */ + + tmp = .30*(((int) desiredColorPtr->red) - (int) colorPtr->red); + distance = tmp*tmp; + tmp = .61*(((int) desiredColorPtr->green) - (int) colorPtr->green); + distance += tmp*tmp; + tmp = .11*(((int) desiredColorPtr->blue) - (int) colorPtr->blue); + distance += tmp*tmp; + if (distance < closestDistance) { + closest = i; + closestDistance = distance; + } + } + if (XAllocColor(dispPtr->display, colormap, + &stressPtr->colorPtr[closest]) != 0) { + *actualColorPtr = stressPtr->colorPtr[closest]; + return; + } + + /* + * Couldn't allocate the color. Remove it from the table and + * go back to look for the next best color. + */ + + stressPtr->colorPtr[closest] = + stressPtr->colorPtr[stressPtr->numColors-1]; + stressPtr->numColors -= 1; + } +} + +/* + *---------------------------------------------------------------------- + * + * DeleteStressedCmap -- + * + * This procedure releases the information cached for "colormap" + * so that it will be refetched from the X server the next time + * it is needed. + * + * Results: + * None. + * + * Side effects: + * The TkStressedCmap structure for colormap is deleted; the + * colormap is no longer considered to be "stressed". + * + * Note: + * This procedure is invoked whenever a color in a colormap is + * freed, and whenever a color allocation in a colormap succeeds. + * This guarantees that TkStressedCmap structures are always + * deleted before the corresponding Colormap is freed. + * + *---------------------------------------------------------------------- + */ + +static void +DeleteStressedCmap(display, colormap) + Display *display; /* Xlib's handle for the display + * containing the colormap. */ + Colormap colormap; /* Colormap to flush. */ +{ + TkStressedCmap *prevPtr, *stressPtr; + TkDisplay *dispPtr = TkGetDisplay(display); + + for (prevPtr = NULL, stressPtr = dispPtr->stressPtr; stressPtr != NULL; + prevPtr = stressPtr, stressPtr = stressPtr->nextPtr) { + if (stressPtr->colormap == colormap) { + if (prevPtr == NULL) { + dispPtr->stressPtr = stressPtr->nextPtr; + } else { + prevPtr->nextPtr = stressPtr->nextPtr; + } + ckfree((char *) stressPtr->colorPtr); + ckfree((char *) stressPtr); + return; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpCmapStressed -- + * + * Check to see whether a given colormap is known to be out + * of entries. + * + * Results: + * 1 is returned if "colormap" is stressed (i.e. it has run out + * of entries recently), 0 otherwise. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpCmapStressed(tkwin, colormap) + Tk_Window tkwin; /* Window that identifies the display + * containing the colormap. */ + Colormap colormap; /* Colormap to check for stress. */ +{ + TkStressedCmap *stressPtr; + + for (stressPtr = ((TkWindow *) tkwin)->dispPtr->stressPtr; + stressPtr != NULL; stressPtr = stressPtr->nextPtr) { + if (stressPtr->colormap == colormap) { + return 1; + } + } + return 0; +} diff --git a/unix/tkUnixCursor.c b/unix/tkUnixCursor.c new file mode 100644 index 0000000..da75ac6 --- /dev/null +++ b/unix/tkUnixCursor.c @@ -0,0 +1,407 @@ +/* + * tkUnixCursor.c -- + * + * This file contains X specific cursor manipulation routines. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixCursor.c 1.4 96/10/08 09:33:08 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * The following data structure is a superset of the TkCursor structure + * defined in tkCursor.c. Each system specific cursor module will define + * a different cursor structure. All of these structures must have the + * same header consisting of the fields in TkCursor. + */ + + + +typedef struct { + TkCursor info; /* Generic cursor info used by tkCursor.c */ + Display *display; /* Display for which cursor is valid. */ +} TkUnixCursor; + +/* + * The table below is used to map from the name of a cursor to its + * index in the official cursor font: + */ + +static struct CursorName { + char *name; + unsigned int shape; +} cursorNames[] = { + {"X_cursor", XC_X_cursor}, + {"arrow", XC_arrow}, + {"based_arrow_down", XC_based_arrow_down}, + {"based_arrow_up", XC_based_arrow_up}, + {"boat", XC_boat}, + {"bogosity", XC_bogosity}, + {"bottom_left_corner", XC_bottom_left_corner}, + {"bottom_right_corner", XC_bottom_right_corner}, + {"bottom_side", XC_bottom_side}, + {"bottom_tee", XC_bottom_tee}, + {"box_spiral", XC_box_spiral}, + {"center_ptr", XC_center_ptr}, + {"circle", XC_circle}, + {"clock", XC_clock}, + {"coffee_mug", XC_coffee_mug}, + {"cross", XC_cross}, + {"cross_reverse", XC_cross_reverse}, + {"crosshair", XC_crosshair}, + {"diamond_cross", XC_diamond_cross}, + {"dot", XC_dot}, + {"dotbox", XC_dotbox}, + {"double_arrow", XC_double_arrow}, + {"draft_large", XC_draft_large}, + {"draft_small", XC_draft_small}, + {"draped_box", XC_draped_box}, + {"exchange", XC_exchange}, + {"fleur", XC_fleur}, + {"gobbler", XC_gobbler}, + {"gumby", XC_gumby}, + {"hand1", XC_hand1}, + {"hand2", XC_hand2}, + {"heart", XC_heart}, + {"icon", XC_icon}, + {"iron_cross", XC_iron_cross}, + {"left_ptr", XC_left_ptr}, + {"left_side", XC_left_side}, + {"left_tee", XC_left_tee}, + {"leftbutton", XC_leftbutton}, + {"ll_angle", XC_ll_angle}, + {"lr_angle", XC_lr_angle}, + {"man", XC_man}, + {"middlebutton", XC_middlebutton}, + {"mouse", XC_mouse}, + {"pencil", XC_pencil}, + {"pirate", XC_pirate}, + {"plus", XC_plus}, + {"question_arrow", XC_question_arrow}, + {"right_ptr", XC_right_ptr}, + {"right_side", XC_right_side}, + {"right_tee", XC_right_tee}, + {"rightbutton", XC_rightbutton}, + {"rtl_logo", XC_rtl_logo}, + {"sailboat", XC_sailboat}, + {"sb_down_arrow", XC_sb_down_arrow}, + {"sb_h_double_arrow", XC_sb_h_double_arrow}, + {"sb_left_arrow", XC_sb_left_arrow}, + {"sb_right_arrow", XC_sb_right_arrow}, + {"sb_up_arrow", XC_sb_up_arrow}, + {"sb_v_double_arrow", XC_sb_v_double_arrow}, + {"shuttle", XC_shuttle}, + {"sizing", XC_sizing}, + {"spider", XC_spider}, + {"spraycan", XC_spraycan}, + {"star", XC_star}, + {"target", XC_target}, + {"tcross", XC_tcross}, + {"top_left_arrow", XC_top_left_arrow}, + {"top_left_corner", XC_top_left_corner}, + {"top_right_corner", XC_top_right_corner}, + {"top_side", XC_top_side}, + {"top_tee", XC_top_tee}, + {"trek", XC_trek}, + {"ul_angle", XC_ul_angle}, + {"umbrella", XC_umbrella}, + {"ur_angle", XC_ur_angle}, + {"watch", XC_watch}, + {"xterm", XC_xterm}, + {NULL, 0} +}; + +/* + * Font to use for cursors: + */ + +#ifndef CURSORFONT +#define CURSORFONT "cursor" +#endif + + +/* + *---------------------------------------------------------------------- + * + * TkGetCursorByName -- + * + * Retrieve a cursor by name. Parse the cursor name into fields + * and create a cursor, either from the standard cursor font or + * from bitmap files. + * + * Results: + * Returns a new cursor, or NULL on errors. + * + * Side effects: + * Allocates a new cursor. + * + *---------------------------------------------------------------------- + */ + +TkCursor * +TkGetCursorByName(interp, tkwin, string) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + Tk_Window tkwin; /* Window in which cursor will be used. */ + Tk_Uid string; /* Description of cursor. See manual entry + * for details on legal syntax. */ +{ + TkUnixCursor *cursorPtr = NULL; + Cursor cursor = None; + int argc; + char **argv = NULL; + Pixmap source = None; + Pixmap mask = None; + Display *display = Tk_Display(tkwin); + + if (Tcl_SplitList(interp, string, &argc, &argv) != TCL_OK) { + return NULL; + } + if (argc == 0) { + goto badString; + } + if (argv[0][0] != '@') { + XColor fg, bg; + unsigned int maskIndex; + register struct CursorName *namePtr; + TkDisplay *dispPtr; + + /* + * The cursor is to come from the standard cursor font. If one + * arg, it is cursor name (use black and white for fg and bg). + * If two args, they are name and fg color (ignore mask). If + * three args, they are name, fg, bg. Some of the code below + * is stolen from the XCreateFontCursor Xlib procedure. + */ + + if (argc > 3) { + goto badString; + } + for (namePtr = cursorNames; ; namePtr++) { + if (namePtr->name == NULL) { + goto badString; + } + if ((namePtr->name[0] == argv[0][0]) + && (strcmp(namePtr->name, argv[0]) == 0)) { + break; + } + } + maskIndex = namePtr->shape + 1; + if (argc == 1) { + fg.red = fg.green = fg.blue = 0; + bg.red = bg.green = bg.blue = 65535; + } else { + if (XParseColor(display, Tk_Colormap(tkwin), argv[1], + &fg) == 0) { + Tcl_AppendResult(interp, "invalid color name \"", argv[1], + "\"", (char *) NULL); + goto cleanup; + } + if (argc == 2) { + bg.red = bg.green = bg.blue = 0; + maskIndex = namePtr->shape; + } else { + if (XParseColor(display, Tk_Colormap(tkwin), argv[2], + &bg) == 0) { + Tcl_AppendResult(interp, "invalid color name \"", argv[2], + "\"", (char *) NULL); + goto cleanup; + } + } + } + dispPtr = ((TkWindow *) tkwin)->dispPtr; + if (dispPtr->cursorFont == None) { + dispPtr->cursorFont = XLoadFont(display, CURSORFONT); + if (dispPtr->cursorFont == None) { + interp->result = "couldn't load cursor font"; + goto cleanup; + } + } + cursor = XCreateGlyphCursor(display, dispPtr->cursorFont, + dispPtr->cursorFont, namePtr->shape, maskIndex, + &fg, &bg); + } else { + int width, height, maskWidth, maskHeight; + int xHot, yHot, dummy1, dummy2; + XColor fg, bg; + + /* + * Prevent file system access in safe interpreters. + */ + + if (Tcl_IsSafe(interp)) { + Tcl_AppendResult(interp, "can't get cursor from a file in", + " a safe interpreter", (char *) NULL); + cursorPtr = NULL; + goto cleanup; + } + + /* + * The cursor is to be created by reading bitmap files. There + * should be either two elements in the list (source, color) or + * four (source mask fg bg). + */ + + if ((argc != 2) && (argc != 4)) { + goto badString; + } + if (XReadBitmapFile(display, + RootWindowOfScreen(Tk_Screen(tkwin)), &argv[0][1], + (unsigned int *) &width, (unsigned int *) &height, + &source, &xHot, &yHot) != BitmapSuccess) { + Tcl_AppendResult(interp, "cleanup reading bitmap file \"", + &argv[0][1], "\"", (char *) NULL); + goto cleanup; + } + if ((xHot < 0) || (yHot < 0) || (xHot >= width) || (yHot >= height)) { + Tcl_AppendResult(interp, "bad hot spot in bitmap file \"", + &argv[0][1], "\"", (char *) NULL); + goto cleanup; + } + if (argc == 2) { + if (XParseColor(display, Tk_Colormap(tkwin), argv[1], + &fg) == 0) { + Tcl_AppendResult(interp, "invalid color name \"", + argv[1], "\"", (char *) NULL); + goto cleanup; + } + cursor = XCreatePixmapCursor(display, source, source, + &fg, &fg, (unsigned) xHot, (unsigned) yHot); + } else { + if (XReadBitmapFile(display, + RootWindowOfScreen(Tk_Screen(tkwin)), argv[1], + (unsigned int *) &maskWidth, (unsigned int *) &maskHeight, + &mask, &dummy1, &dummy2) != BitmapSuccess) { + Tcl_AppendResult(interp, "cleanup reading bitmap file \"", + argv[1], "\"", (char *) NULL); + goto cleanup; + } + if ((maskWidth != width) && (maskHeight != height)) { + interp->result = + "source and mask bitmaps have different sizes"; + goto cleanup; + } + if (XParseColor(display, Tk_Colormap(tkwin), argv[2], + &fg) == 0) { + Tcl_AppendResult(interp, "invalid color name \"", argv[2], + "\"", (char *) NULL); + goto cleanup; + } + if (XParseColor(display, Tk_Colormap(tkwin), argv[3], + &bg) == 0) { + Tcl_AppendResult(interp, "invalid color name \"", argv[3], + "\"", (char *) NULL); + goto cleanup; + } + cursor = XCreatePixmapCursor(display, source, mask, + &fg, &bg, (unsigned) xHot, (unsigned) yHot); + } + } + + if (cursor != None) { + cursorPtr = (TkUnixCursor *) ckalloc(sizeof(TkUnixCursor)); + cursorPtr->info.cursor = (Tk_Cursor) cursor; + cursorPtr->display = display; + } + + cleanup: + if (argv != NULL) { + ckfree((char *) argv); + } + if (source != None) { + Tk_FreePixmap(display, source); + } + if (mask != None) { + Tk_FreePixmap(display, mask); + } + return (TkCursor *) cursorPtr; + + + badString: + Tcl_AppendResult(interp, "bad cursor spec \"", string, "\"", + (char *) NULL); + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TkCreateCursorFromData -- + * + * Creates a cursor from the source and mask bits. + * + * Results: + * Returns a new cursor, or NULL on errors. + * + * Side effects: + * Allocates a new cursor. + * + *---------------------------------------------------------------------- + */ + +TkCursor * +TkCreateCursorFromData(tkwin, source, mask, width, height, xHot, yHot, + fgColor, bgColor) + Tk_Window tkwin; /* Window in which cursor will be used. */ + char *source; /* Bitmap data for cursor shape. */ + char *mask; /* Bitmap data for cursor mask. */ + int width, height; /* Dimensions of cursor. */ + int xHot, yHot; /* Location of hot-spot in cursor. */ + XColor fgColor; /* Foreground color for cursor. */ + XColor bgColor; /* Background color for cursor. */ +{ + Cursor cursor; + Pixmap sourcePixmap, maskPixmap; + TkUnixCursor *cursorPtr = NULL; + Display *display = Tk_Display(tkwin); + + sourcePixmap = XCreateBitmapFromData(display, + RootWindowOfScreen(Tk_Screen(tkwin)), source, (unsigned) width, + (unsigned) height); + maskPixmap = XCreateBitmapFromData(display, + RootWindowOfScreen(Tk_Screen(tkwin)), mask, (unsigned) width, + (unsigned) height); + cursor = XCreatePixmapCursor(display, sourcePixmap, + maskPixmap, &fgColor, &bgColor, (unsigned) xHot, (unsigned) yHot); + Tk_FreePixmap(display, sourcePixmap); + Tk_FreePixmap(display, maskPixmap); + + if (cursor != None) { + cursorPtr = (TkUnixCursor *) ckalloc(sizeof(TkUnixCursor)); + cursorPtr->info.cursor = (Tk_Cursor) cursor; + cursorPtr->display = display; + } + return (TkCursor *) cursorPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkFreeCursor -- + * + * This procedure is called to release a cursor allocated by + * TkGetCursorByName. + * + * Results: + * None. + * + * Side effects: + * The cursor data structure is deallocated. + * + *---------------------------------------------------------------------- + */ + +void +TkFreeCursor(cursorPtr) + TkCursor *cursorPtr; +{ + TkUnixCursor *unixCursorPtr = (TkUnixCursor *) cursorPtr; + XFreeCursor(unixCursorPtr->display, (Cursor) unixCursorPtr->info.cursor); + Tk_FreeXId(unixCursorPtr->display, (XID) unixCursorPtr->info.cursor); + ckfree((char *) unixCursorPtr); +} diff --git a/unix/tkUnixDefault.h b/unix/tkUnixDefault.h new file mode 100644 index 0000000..f895d63 --- /dev/null +++ b/unix/tkUnixDefault.h @@ -0,0 +1,450 @@ +/* + * tkUnixDefault.h -- + * + * This file defines the defaults for all options for all of + * the Tk widgets. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixDefault.h 1.105 97/10/09 17:45:10 + */ + +#ifndef _TKUNIXDEFAULT +#define _TKUNIXDEFAULT + +/* + * The definitions below provide symbolic names for the default colors. + * NORMAL_BG - Normal background color. + * ACTIVE_BG - Background color when widget is active. + * SELECT_BG - Background color for selected text. + * TROUGH - Background color for troughs in scales and scrollbars. + * INDICATOR - Color for indicator when button is selected. + * DISABLED - Foreground color when widget is disabled. + */ + +#define BLACK "Black" +#define WHITE "White" + +#define NORMAL_BG "#d9d9d9" +#define ACTIVE_BG "#ececec" +#define SELECT_BG "#c3c3c3" +#define TROUGH "#c3c3c3" +#define INDICATOR "#b03060" +#define DISABLED "#a3a3a3" + +/* + * Defaults for labels, buttons, checkbuttons, and radiobuttons: + */ + +#define DEF_BUTTON_ANCHOR "center" +#define DEF_BUTTON_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_BUTTON_ACTIVE_BG_MONO BLACK +#define DEF_BUTTON_ACTIVE_FG_COLOR BLACK +#define DEF_CHKRAD_ACTIVE_FG_COLOR DEF_BUTTON_ACTIVE_FG_COLOR +#define DEF_BUTTON_ACTIVE_FG_MONO WHITE +#define DEF_BUTTON_BG_COLOR NORMAL_BG +#define DEF_BUTTON_BG_MONO WHITE +#define DEF_BUTTON_BITMAP "" +#define DEF_BUTTON_BORDER_WIDTH "2" +#define DEF_BUTTON_CURSOR "" +#define DEF_BUTTON_COMMAND "" +#define DEF_BUTTON_DEFAULT "disabled" +#define DEF_BUTTON_DISABLED_FG_COLOR DISABLED +#define DEF_BUTTON_DISABLED_FG_MONO "" +#define DEF_BUTTON_FG BLACK +#define DEF_CHKRAD_FG DEF_BUTTON_FG +#define DEF_BUTTON_FONT "Helvetica -12 bold" +#define DEF_BUTTON_HEIGHT "0" +#define DEF_BUTTON_HIGHLIGHT_BG NORMAL_BG +#define DEF_BUTTON_HIGHLIGHT BLACK +#define DEF_LABEL_HIGHLIGHT_WIDTH "0" +#define DEF_BUTTON_HIGHLIGHT_WIDTH "1" +#define DEF_BUTTON_IMAGE (char *) NULL +#define DEF_BUTTON_INDICATOR "1" +#define DEF_BUTTON_JUSTIFY "center" +#define DEF_BUTTON_OFF_VALUE "0" +#define DEF_BUTTON_ON_VALUE "1" +#define DEF_BUTTON_PADX "3m" +#define DEF_LABCHKRAD_PADX "1" +#define DEF_BUTTON_PADY "1m" +#define DEF_LABCHKRAD_PADY "1" +#define DEF_BUTTON_RELIEF "raised" +#define DEF_LABCHKRAD_RELIEF "flat" +#define DEF_BUTTON_SELECT_COLOR INDICATOR +#define DEF_BUTTON_SELECT_MONO BLACK +#define DEF_BUTTON_SELECT_IMAGE (char *) NULL +#define DEF_BUTTON_STATE "normal" +#define DEF_LABEL_TAKE_FOCUS "0" +#define DEF_BUTTON_TAKE_FOCUS (char *) NULL +#define DEF_BUTTON_TEXT "" +#define DEF_BUTTON_TEXT_VARIABLE "" +#define DEF_BUTTON_UNDERLINE "-1" +#define DEF_BUTTON_VALUE "" +#define DEF_BUTTON_WIDTH "0" +#define DEF_BUTTON_WRAP_LENGTH "0" +#define DEF_RADIOBUTTON_VARIABLE "selectedButton" +#define DEF_CHECKBUTTON_VARIABLE "" + +/* + * Defaults for canvases: + */ + +#define DEF_CANVAS_BG_COLOR NORMAL_BG +#define DEF_CANVAS_BG_MONO WHITE +#define DEF_CANVAS_BORDER_WIDTH "0" +#define DEF_CANVAS_CLOSE_ENOUGH "1" +#define DEF_CANVAS_CONFINE "1" +#define DEF_CANVAS_CURSOR "" +#define DEF_CANVAS_HEIGHT "7c" +#define DEF_CANVAS_HIGHLIGHT_BG NORMAL_BG +#define DEF_CANVAS_HIGHLIGHT BLACK +#define DEF_CANVAS_HIGHLIGHT_WIDTH "1" +#define DEF_CANVAS_INSERT_BG BLACK +#define DEF_CANVAS_INSERT_BD_COLOR "0" +#define DEF_CANVAS_INSERT_BD_MONO "0" +#define DEF_CANVAS_INSERT_OFF_TIME "300" +#define DEF_CANVAS_INSERT_ON_TIME "600" +#define DEF_CANVAS_INSERT_WIDTH "2" +#define DEF_CANVAS_RELIEF "flat" +#define DEF_CANVAS_SCROLL_REGION "" +#define DEF_CANVAS_SELECT_COLOR SELECT_BG +#define DEF_CANVAS_SELECT_MONO BLACK +#define DEF_CANVAS_SELECT_BD_COLOR "1" +#define DEF_CANVAS_SELECT_BD_MONO "0" +#define DEF_CANVAS_SELECT_FG_COLOR BLACK +#define DEF_CANVAS_SELECT_FG_MONO WHITE +#define DEF_CANVAS_TAKE_FOCUS (char *) NULL +#define DEF_CANVAS_WIDTH "10c" +#define DEF_CANVAS_X_SCROLL_CMD "" +#define DEF_CANVAS_X_SCROLL_INCREMENT "0" +#define DEF_CANVAS_Y_SCROLL_CMD "" +#define DEF_CANVAS_Y_SCROLL_INCREMENT "0" + +/* + * Defaults for entries: + */ + +#define DEF_ENTRY_BG_COLOR NORMAL_BG +#define DEF_ENTRY_BG_MONO WHITE +#define DEF_ENTRY_BORDER_WIDTH "2" +#define DEF_ENTRY_CURSOR "xterm" +#define DEF_ENTRY_EXPORT_SELECTION "1" +#define DEF_ENTRY_FONT "Helvetica -12" +#define DEF_ENTRY_FG BLACK +#define DEF_ENTRY_HIGHLIGHT_BG NORMAL_BG +#define DEF_ENTRY_HIGHLIGHT BLACK +#define DEF_ENTRY_HIGHLIGHT_WIDTH "1" +#define DEF_ENTRY_INSERT_BG BLACK +#define DEF_ENTRY_INSERT_BD_COLOR "0" +#define DEF_ENTRY_INSERT_BD_MONO "0" +#define DEF_ENTRY_INSERT_OFF_TIME "300" +#define DEF_ENTRY_INSERT_ON_TIME "600" +#define DEF_ENTRY_INSERT_WIDTH "2" +#define DEF_ENTRY_JUSTIFY "left" +#define DEF_ENTRY_RELIEF "sunken" +#define DEF_ENTRY_SCROLL_COMMAND "" +#define DEF_ENTRY_SELECT_COLOR SELECT_BG +#define DEF_ENTRY_SELECT_MONO BLACK +#define DEF_ENTRY_SELECT_BD_COLOR "1" +#define DEF_ENTRY_SELECT_BD_MONO "0" +#define DEF_ENTRY_SELECT_FG_COLOR BLACK +#define DEF_ENTRY_SELECT_FG_MONO WHITE +#define DEF_ENTRY_SHOW (char *) NULL +#define DEF_ENTRY_STATE "normal" +#define DEF_ENTRY_TAKE_FOCUS (char *) NULL +#define DEF_ENTRY_TEXT_VARIABLE "" +#define DEF_ENTRY_WIDTH "20" + +/* + * Defaults for frames: + */ + +#define DEF_FRAME_BG_COLOR NORMAL_BG +#define DEF_FRAME_BG_MONO WHITE +#define DEF_FRAME_BORDER_WIDTH "0" +#define DEF_FRAME_CLASS "Frame" +#define DEF_FRAME_COLORMAP "" +#define DEF_FRAME_CONTAINER "0" +#define DEF_FRAME_CURSOR "" +#define DEF_FRAME_HEIGHT "0" +#define DEF_FRAME_HIGHLIGHT_BG NORMAL_BG +#define DEF_FRAME_HIGHLIGHT BLACK +#define DEF_FRAME_HIGHLIGHT_WIDTH "0" +#define DEF_FRAME_RELIEF "flat" +#define DEF_FRAME_TAKE_FOCUS "0" +#define DEF_FRAME_USE "" +#define DEF_FRAME_VISUAL "" +#define DEF_FRAME_WIDTH "0" + +/* + * Defaults for listboxes: + */ + +#define DEF_LISTBOX_BG_COLOR NORMAL_BG +#define DEF_LISTBOX_BG_MONO WHITE +#define DEF_LISTBOX_BORDER_WIDTH "2" +#define DEF_LISTBOX_CURSOR "" +#define DEF_LISTBOX_EXPORT_SELECTION "1" +#define DEF_LISTBOX_FONT "Helvetica -12 bold" +#define DEF_LISTBOX_FG BLACK +#define DEF_LISTBOX_HEIGHT "10" +#define DEF_LISTBOX_HIGHLIGHT_BG NORMAL_BG +#define DEF_LISTBOX_HIGHLIGHT BLACK +#define DEF_LISTBOX_HIGHLIGHT_WIDTH "1" +#define DEF_LISTBOX_RELIEF "sunken" +#define DEF_LISTBOX_SCROLL_COMMAND "" +#define DEF_LISTBOX_SELECT_COLOR SELECT_BG +#define DEF_LISTBOX_SELECT_MONO BLACK +#define DEF_LISTBOX_SELECT_BD "1" +#define DEF_LISTBOX_SELECT_FG_COLOR BLACK +#define DEF_LISTBOX_SELECT_FG_MONO WHITE +#define DEF_LISTBOX_SELECT_MODE "browse" +#define DEF_LISTBOX_SET_GRID "0" +#define DEF_LISTBOX_TAKE_FOCUS (char *) NULL +#define DEF_LISTBOX_WIDTH "20" + +/* + * Defaults for individual entries of menus: + */ + +#define DEF_MENU_ENTRY_ACTIVE_BG (char *) NULL +#define DEF_MENU_ENTRY_ACTIVE_FG (char *) NULL +#define DEF_MENU_ENTRY_ACCELERATOR (char *) NULL +#define DEF_MENU_ENTRY_BG (char *) NULL +#define DEF_MENU_ENTRY_BITMAP None +#define DEF_MENU_ENTRY_COLUMN_BREAK "0" +#define DEF_MENU_ENTRY_COMMAND (char *) NULL +#define DEF_MENU_ENTRY_FG (char *) NULL +#define DEF_MENU_ENTRY_FONT (char *) NULL +#define DEF_MENU_ENTRY_HIDE_MARGIN "0" +#define DEF_MENU_ENTRY_IMAGE (char *) NULL +#define DEF_MENU_ENTRY_INDICATOR "1" +#define DEF_MENU_ENTRY_LABEL (char *) NULL +#define DEF_MENU_ENTRY_MENU (char *) NULL +#define DEF_MENU_ENTRY_OFF_VALUE "0" +#define DEF_MENU_ENTRY_ON_VALUE "1" +#define DEF_MENU_ENTRY_SELECT_IMAGE (char *) NULL +#define DEF_MENU_ENTRY_STATE "normal" +#define DEF_MENU_ENTRY_VALUE (char *) NULL +#define DEF_MENU_ENTRY_CHECK_VARIABLE (char *) NULL +#define DEF_MENU_ENTRY_RADIO_VARIABLE "selectedButton" +#define DEF_MENU_ENTRY_SELECT (char *) NULL +#define DEF_MENU_ENTRY_UNDERLINE "-1" + +/* + * Defaults for menus overall: + */ + +#define DEF_MENU_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_MENU_ACTIVE_BG_MONO BLACK +#define DEF_MENU_ACTIVE_BORDER_WIDTH "2" +#define DEF_MENU_ACTIVE_FG_COLOR BLACK +#define DEF_MENU_ACTIVE_FG_MONO WHITE +#define DEF_MENU_BG_COLOR NORMAL_BG +#define DEF_MENU_BG_MONO WHITE +#define DEF_MENU_BORDER_WIDTH "2" +#define DEF_MENU_CURSOR "arrow" +#define DEF_MENU_DISABLED_FG_COLOR DISABLED +#define DEF_MENU_DISABLED_FG_MONO "" +#define DEF_MENU_FONT "Helvetica -12 bold" +#define DEF_MENU_FG BLACK +#define DEF_MENU_POST_COMMAND "" +#define DEF_MENU_RELIEF "raised" +#define DEF_MENU_SELECT_COLOR INDICATOR +#define DEF_MENU_SELECT_MONO BLACK +#define DEF_MENU_TAKE_FOCUS "0" +#define DEF_MENU_TEAROFF "1" +#define DEF_MENU_TEAROFF_CMD (char *) NULL +#define DEF_MENU_TITLE "" +#define DEF_MENU_TYPE "normal" + +/* + * Defaults for menubuttons: + */ + +#define DEF_MENUBUTTON_ANCHOR "center" +#define DEF_MENUBUTTON_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_MENUBUTTON_ACTIVE_BG_MONO BLACK +#define DEF_MENUBUTTON_ACTIVE_FG_COLOR BLACK +#define DEF_MENUBUTTON_ACTIVE_FG_MONO WHITE +#define DEF_MENUBUTTON_BG_COLOR NORMAL_BG +#define DEF_MENUBUTTON_BG_MONO WHITE +#define DEF_MENUBUTTON_BITMAP "" +#define DEF_MENUBUTTON_BORDER_WIDTH "2" +#define DEF_MENUBUTTON_CURSOR "" +#define DEF_MENUBUTTON_DIRECTION "below" +#define DEF_MENUBUTTON_DISABLED_FG_COLOR DISABLED +#define DEF_MENUBUTTON_DISABLED_FG_MONO "" +#define DEF_MENUBUTTON_FONT "Helvetica -12 bold" +#define DEF_MENUBUTTON_FG BLACK +#define DEF_MENUBUTTON_HEIGHT "0" +#define DEF_MENUBUTTON_HIGHLIGHT_BG NORMAL_BG +#define DEF_MENUBUTTON_HIGHLIGHT BLACK +#define DEF_MENUBUTTON_HIGHLIGHT_WIDTH "0" +#define DEF_MENUBUTTON_IMAGE (char *) NULL +#define DEF_MENUBUTTON_INDICATOR "0" +#define DEF_MENUBUTTON_JUSTIFY "center" +#define DEF_MENUBUTTON_MENU "" +#define DEF_MENUBUTTON_PADX "4p" +#define DEF_MENUBUTTON_PADY "3p" +#define DEF_MENUBUTTON_RELIEF "flat" +#define DEF_MENUBUTTON_STATE "normal" +#define DEF_MENUBUTTON_TAKE_FOCUS "0" +#define DEF_MENUBUTTON_TEXT "" +#define DEF_MENUBUTTON_TEXT_VARIABLE "" +#define DEF_MENUBUTTON_UNDERLINE "-1" +#define DEF_MENUBUTTON_WIDTH "0" +#define DEF_MENUBUTTON_WRAP_LENGTH "0" + +/* + * Defaults for messages: + */ + +#define DEF_MESSAGE_ANCHOR "center" +#define DEF_MESSAGE_ASPECT "150" +#define DEF_MESSAGE_BG_COLOR NORMAL_BG +#define DEF_MESSAGE_BG_MONO WHITE +#define DEF_MESSAGE_BORDER_WIDTH "2" +#define DEF_MESSAGE_CURSOR "" +#define DEF_MESSAGE_FG BLACK +#define DEF_MESSAGE_FONT "Helvetica -12 bold" +#define DEF_MESSAGE_HIGHLIGHT_BG NORMAL_BG +#define DEF_MESSAGE_HIGHLIGHT BLACK +#define DEF_MESSAGE_HIGHLIGHT_WIDTH "0" +#define DEF_MESSAGE_JUSTIFY "left" +#define DEF_MESSAGE_PADX "-1" +#define DEF_MESSAGE_PADY "-1" +#define DEF_MESSAGE_RELIEF "flat" +#define DEF_MESSAGE_TAKE_FOCUS "0" +#define DEF_MESSAGE_TEXT "" +#define DEF_MESSAGE_TEXT_VARIABLE "" +#define DEF_MESSAGE_WIDTH "0" + +/* + * Defaults for scales: + */ + +#define DEF_SCALE_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_SCALE_ACTIVE_BG_MONO BLACK +#define DEF_SCALE_BG_COLOR NORMAL_BG +#define DEF_SCALE_BG_MONO WHITE +#define DEF_SCALE_BIG_INCREMENT "0" +#define DEF_SCALE_BORDER_WIDTH "2" +#define DEF_SCALE_COMMAND "" +#define DEF_SCALE_CURSOR "" +#define DEF_SCALE_DIGITS "0" +#define DEF_SCALE_FONT "Helvetica -12 bold" +#define DEF_SCALE_FG_COLOR BLACK +#define DEF_SCALE_FG_MONO BLACK +#define DEF_SCALE_FROM "0" +#define DEF_SCALE_HIGHLIGHT_BG NORMAL_BG +#define DEF_SCALE_HIGHLIGHT BLACK +#define DEF_SCALE_HIGHLIGHT_WIDTH "1" +#define DEF_SCALE_LABEL "" +#define DEF_SCALE_LENGTH "100" +#define DEF_SCALE_ORIENT "vertical" +#define DEF_SCALE_RELIEF "flat" +#define DEF_SCALE_REPEAT_DELAY "300" +#define DEF_SCALE_REPEAT_INTERVAL "100" +#define DEF_SCALE_RESOLUTION "1" +#define DEF_SCALE_TROUGH_COLOR TROUGH +#define DEF_SCALE_TROUGH_MONO WHITE +#define DEF_SCALE_SHOW_VALUE "1" +#define DEF_SCALE_SLIDER_LENGTH "30" +#define DEF_SCALE_SLIDER_RELIEF "raised" +#define DEF_SCALE_STATE "normal" +#define DEF_SCALE_TAKE_FOCUS (char *) NULL +#define DEF_SCALE_TICK_INTERVAL "0" +#define DEF_SCALE_TO "100" +#define DEF_SCALE_VARIABLE "" +#define DEF_SCALE_WIDTH "15" + +/* + * Defaults for scrollbars: + */ + +#define DEF_SCROLLBAR_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_SCROLLBAR_ACTIVE_BG_MONO BLACK +#define DEF_SCROLLBAR_ACTIVE_RELIEF "raised" +#define DEF_SCROLLBAR_BG_COLOR NORMAL_BG +#define DEF_SCROLLBAR_BG_MONO WHITE +#define DEF_SCROLLBAR_BORDER_WIDTH "2" +#define DEF_SCROLLBAR_COMMAND "" +#define DEF_SCROLLBAR_CURSOR "" +#define DEF_SCROLLBAR_EL_BORDER_WIDTH "-1" +#define DEF_SCROLLBAR_HIGHLIGHT_BG NORMAL_BG +#define DEF_SCROLLBAR_HIGHLIGHT BLACK +#define DEF_SCROLLBAR_HIGHLIGHT_WIDTH "1" +#define DEF_SCROLLBAR_JUMP "0" +#define DEF_SCROLLBAR_ORIENT "vertical" +#define DEF_SCROLLBAR_RELIEF "sunken" +#define DEF_SCROLLBAR_REPEAT_DELAY "300" +#define DEF_SCROLLBAR_REPEAT_INTERVAL "100" +#define DEF_SCROLLBAR_TAKE_FOCUS (char *) NULL +#define DEF_SCROLLBAR_TROUGH_COLOR TROUGH +#define DEF_SCROLLBAR_TROUGH_MONO WHITE +#define DEF_SCROLLBAR_WIDTH "15" + +/* + * Defaults for texts: + */ + +#define DEF_TEXT_BG_COLOR NORMAL_BG +#define DEF_TEXT_BG_MONO WHITE +#define DEF_TEXT_BORDER_WIDTH "2" +#define DEF_TEXT_CURSOR "xterm" +#define DEF_TEXT_FG BLACK +#define DEF_TEXT_EXPORT_SELECTION "1" +#define DEF_TEXT_FONT "Courier -12" +#define DEF_TEXT_HEIGHT "24" +#define DEF_TEXT_HIGHLIGHT_BG NORMAL_BG +#define DEF_TEXT_HIGHLIGHT BLACK +#define DEF_TEXT_HIGHLIGHT_WIDTH "1" +#define DEF_TEXT_INSERT_BG BLACK +#define DEF_TEXT_INSERT_BD_COLOR "0" +#define DEF_TEXT_INSERT_BD_MONO "0" +#define DEF_TEXT_INSERT_OFF_TIME "300" +#define DEF_TEXT_INSERT_ON_TIME "600" +#define DEF_TEXT_INSERT_WIDTH "2" +#define DEF_TEXT_PADX "1" +#define DEF_TEXT_PADY "1" +#define DEF_TEXT_RELIEF "sunken" +#define DEF_TEXT_SELECT_COLOR SELECT_BG +#define DEF_TEXT_SELECT_MONO BLACK +#define DEF_TEXT_SELECT_BD_COLOR "1" +#define DEF_TEXT_SELECT_BD_MONO "0" +#define DEF_TEXT_SELECT_FG_COLOR BLACK +#define DEF_TEXT_SELECT_FG_MONO WHITE +#define DEF_TEXT_SELECT_RELIEF "raised" +#define DEF_TEXT_SET_GRID "0" +#define DEF_TEXT_SPACING1 "0" +#define DEF_TEXT_SPACING2 "0" +#define DEF_TEXT_SPACING3 "0" +#define DEF_TEXT_STATE "normal" +#define DEF_TEXT_TABS "" +#define DEF_TEXT_TAKE_FOCUS (char *) NULL +#define DEF_TEXT_WIDTH "80" +#define DEF_TEXT_WRAP "char" +#define DEF_TEXT_XSCROLL_COMMAND "" +#define DEF_TEXT_YSCROLL_COMMAND "" + +/* + * Defaults for canvas text: + */ + +#define DEF_CANVTEXT_FONT "Helvetica -12" + +/* + * Defaults for toplevels (most of the defaults for frames also apply + * to toplevels): + */ + +#define DEF_TOPLEVEL_CLASS "Toplevel" +#define DEF_TOPLEVEL_MENU "" +#define DEF_TOPLEVEL_SCREEN "" + +#endif /* _TKUNIXDEFAULT */ diff --git a/unix/tkUnixDialog.c b/unix/tkUnixDialog.c new file mode 100644 index 0000000..b8a1ab0 --- /dev/null +++ b/unix/tkUnixDialog.c @@ -0,0 +1,207 @@ +/* + * tkUnixDialog.c -- + * + * Contains the Unix implementation of the common dialog boxes: + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixDialog.c 1.5 96/08/28 21:21:01 + * + */ + +#include "tkPort.h" +#include "tkInt.h" +#include "tkUnixInt.h" + +/* + *---------------------------------------------------------------------- + * + * EvalArgv -- + * + * Invokes the Tcl procedure with the arguments. argv[0] is set by + * the caller of this function. It may be different than cmdName. + * The TCL command will see argv[0], not cmdName, as its name if it + * invokes [lindex [info level 0] 0] + * + * Results: + * TCL_ERROR if the command does not exist and cannot be autoloaded. + * Otherwise, return the result of the evaluation of the command. + * + * Side effects: + * The command may be autoloaded. + * + *---------------------------------------------------------------------- + */ + +static int EvalArgv(interp, cmdName, argc, argv) + Tcl_Interp *interp; /* Current interpreter. */ + char * cmdName; /* Name of the TCL command to call */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tcl_CmdInfo cmdInfo; + + if (!Tcl_GetCommandInfo(interp, cmdName, &cmdInfo)) { + char * cmdArgv[2]; + + /* + * This comand is not in the interpreter yet -- looks like we + * have to auto-load it + */ + if (!Tcl_GetCommandInfo(interp, "auto_load", &cmdInfo)) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "cannot execute command \"auto_load\"", + NULL); + return TCL_ERROR; + } + + cmdArgv[0] = "auto_load"; + cmdArgv[1] = cmdName; + + if ((*cmdInfo.proc)(cmdInfo.clientData, interp, 2, cmdArgv)!= TCL_OK){ + return TCL_ERROR; + } + + if (!Tcl_GetCommandInfo(interp, cmdName, &cmdInfo)) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "cannot auto-load command \"", + cmdName, "\"",NULL); + return TCL_ERROR; + } + } + + return (*cmdInfo.proc)(cmdInfo.clientData, interp, argc, argv); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_ChooseColorCmd -- + * + * This procedure implements the color dialog box for the Unix + * platform. See the user documentation for details on what it + * does. + * + * Results: + * See user documentation. + * + * Side effects: + * A dialog window is created the first time this procedure is called. + * This window is not destroyed and will be reused the next time the + * application invokes the "tk_chooseColor" command. + * + *---------------------------------------------------------------------- + */ + +int +Tk_ChooseColorCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + return EvalArgv(interp, "tkColorDialog", argc, argv); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetOpenFileCmd -- + * + * This procedure implements the "open file" dialog box for the + * Unix platform. See the user documentation for details on what + * it does. + * + * Results: + * See user documentation. + * + * Side effects: + * A dialog window is created the first this procedure is called. + * This window is not destroyed and will be reused the next time + * the application invokes the "tk_getOpenFile" or + * "tk_getSaveFile" command. + * + *---------------------------------------------------------------------- + */ + +int +Tk_GetOpenFileCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window)clientData; + + if (Tk_StrictMotif(tkwin)) { + return EvalArgv(interp, "tkMotifFDialog", argc, argv); + } else { + return EvalArgv(interp, "tkFDialog", argc, argv); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetSaveFileCmd -- + * + * Same as Tk_GetOpenFileCmd but opens a "save file" dialog box + * instead + * + * Results: + * Same as Tk_GetOpenFileCmd. + * + * Side effects: + * Same as Tk_GetOpenFileCmd. + * + *---------------------------------------------------------------------- + */ + +int +Tk_GetSaveFileCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window)clientData; + + if (Tk_StrictMotif(tkwin)) { + return EvalArgv(interp, "tkMotifFDialog", argc, argv); + } else { + return EvalArgv(interp, "tkFDialog", argc, argv); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_MessageBoxCmd -- + * + * This procedure implements the MessageBox window for the + * Unix platform. See the user documentation for details on what + * it does. + * + * Results: + * See user documentation. + * + * Side effects: + * None. The MessageBox window will be destroy before this procedure + * returns. + * + *---------------------------------------------------------------------- + */ + +int +Tk_MessageBoxCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + return EvalArgv(interp, "tkMessageBox", argc, argv); +} + diff --git a/unix/tkUnixDraw.c b/unix/tkUnixDraw.c new file mode 100644 index 0000000..65bf2e4 --- /dev/null +++ b/unix/tkUnixDraw.c @@ -0,0 +1,171 @@ +/* + * tkUnixDraw.c -- + * + * This file contains X specific drawing routines. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixDraw.c 1.9 97/03/21 11:16:18 + */ + +#include "tkPort.h" +#include "tkInt.h" + +/* + * The following structure is used to pass information to + * ScrollRestrictProc from TkScrollWindow. + */ + +typedef struct ScrollInfo { + int done; /* Flag is 0 until filtering is done. */ + Display *display; /* Display to filter. */ + Window window; /* Window to filter. */ + TkRegion region; /* Region into which damage is accumulated. */ + int dx, dy; /* Amount by which window was shifted. */ +} ScrollInfo; + +/* + * Forward declarations for procedures declared later in this file: + */ + +static Tk_RestrictAction ScrollRestrictProc _ANSI_ARGS_(( + ClientData arg, XEvent *eventPtr)); + +/* + *---------------------------------------------------------------------- + * + * TkScrollWindow -- + * + * Scroll a rectangle of the specified window and accumulate + * damage information in the specified Region. + * + * Results: + * Returns 0 if no damage additional damage was generated. Sets + * damageRgn to contain the damaged areas and returns 1 if + * GraphicsExpose events were detected. + * + * Side effects: + * Scrolls the bits in the window and enters the event loop + * looking for damage events. + * + *---------------------------------------------------------------------- + */ + +int +TkScrollWindow(tkwin, gc, x, y, width, height, dx, dy, damageRgn) + Tk_Window tkwin; /* The window to be scrolled. */ + GC gc; /* GC for window to be scrolled. */ + int x, y, width, height; /* Position rectangle to be scrolled. */ + int dx, dy; /* Distance rectangle should be moved. */ + TkRegion damageRgn; /* Region to accumulate damage in. */ +{ + Tk_RestrictProc *oldProc; + ClientData oldArg, dummy; + ScrollInfo info; + + XCopyArea(Tk_Display(tkwin), Tk_WindowId(tkwin), Tk_WindowId(tkwin), gc, + x, y, (unsigned int) width, (unsigned int) height, x + dx, y + dy); + + info.done = 0; + info.window = Tk_WindowId(tkwin); + info.display = Tk_Display(tkwin); + info.region = damageRgn; + info.dx = dx; + info.dy = dy; + + /* + * Sync the event stream so all of the expose events will be on the + * Tk event queue before we start filtering. This avoids busy waiting + * while we filter events. + */ + + TkpSync(info.display); + oldProc = Tk_RestrictEvents(ScrollRestrictProc, (ClientData) &info, + &oldArg); + while (!info.done) { + Tcl_ServiceEvent(TCL_WINDOW_EVENTS); + } + Tk_RestrictEvents(oldProc, oldArg, &dummy); + + return XEmptyRegion((Region) damageRgn) ? 0 : 1; +} + +/* + *---------------------------------------------------------------------- + * + * ScrollRestrictProc -- + * + * A Tk_RestrictProc used by TkScrollWindow to gather up Expose + * information into a single damage region. It accumulates damage + * events on the specified window until a NoExpose or the last + * GraphicsExpose event is detected. + * + * Results: + * None. + * + * Side effects: + * Discards Expose events after accumulating damage information + * for a particular window. + * + *---------------------------------------------------------------------- + */ + +static Tk_RestrictAction +ScrollRestrictProc(arg, eventPtr) + ClientData arg; + XEvent *eventPtr; +{ + ScrollInfo *info = (ScrollInfo *) arg; + XRectangle rect; + + /* + * Defer events which aren't for the specified window. + */ + + if (info->done || (eventPtr->xany.display != info->display) + || (eventPtr->xany.window != info->window)) { + return TK_DEFER_EVENT; + } + + if (eventPtr->type == NoExpose) { + info->done = 1; + } else if (eventPtr->type == GraphicsExpose) { + rect.x = eventPtr->xgraphicsexpose.x; + rect.y = eventPtr->xgraphicsexpose.y; + rect.width = eventPtr->xgraphicsexpose.width; + rect.height = eventPtr->xgraphicsexpose.height; + XUnionRectWithRegion(&rect, (Region) info->region, + (Region) info->region); + + if (eventPtr->xgraphicsexpose.count == 0) { + info->done = 1; + } + } else if (eventPtr->type == Expose) { + + /* + * This case is tricky. This event was already queued before + * the XCopyArea was issued. If this area overlaps the area + * being copied, then some of the copied area may be invalid. + * The easiest way to handle this case is to mark both the + * original area and the shifted area as damaged. + */ + + rect.x = eventPtr->xexpose.x; + rect.y = eventPtr->xexpose.y; + rect.width = eventPtr->xexpose.width; + rect.height = eventPtr->xexpose.height; + XUnionRectWithRegion(&rect, (Region) info->region, + (Region) info->region); + rect.x += info->dx; + rect.y += info->dy; + XUnionRectWithRegion(&rect, (Region) info->region, + (Region) info->region); + } else { + return TK_DEFER_EVENT; + } + return TK_DISCARD_EVENT; +} + diff --git a/unix/tkUnixEmbed.c b/unix/tkUnixEmbed.c new file mode 100644 index 0000000..fd20a34 --- /dev/null +++ b/unix/tkUnixEmbed.c @@ -0,0 +1,1001 @@ +/* + * tkUnixEmbed.c -- + * + * This file contains platform-specific procedures for UNIX to provide + * basic operations needed for application embedding (where one + * application can use as its main window an internal window from + * some other application). + * + * Copyright (c) 1996-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixEmbed.c 1.22 97/08/13 11:15:51 + */ + +#include "tkInt.h" +#include "tkUnixInt.h" + +/* + * One of the following structures exists for each container in this + * application. It keeps track of the container window and its + * associated embedded window. + */ + +typedef struct Container { + Window parent; /* X's window id for the parent of + * the pair (the container). */ + Window parentRoot; /* Id for the root window of parent's + * screen. */ + TkWindow *parentPtr; /* Tk's information about the container, + * or NULL if the container isn't + * in this process. */ + Window wrapper; /* X's window id for the wrapper + * window for the embedded window. + * Starts off as None, but gets + * filled in when the window is + * eventually created. */ + TkWindow *embeddedPtr; /* Tk's information about the embedded + * window, or NULL if the embedded + * application isn't in this process. + * Note that this is *not* the + * same window as wrapper: wrapper is + * the parent of embeddedPtr. */ + struct Container *nextPtr; /* Next in list of all containers in + * this process. */ +} Container; + +static Container *firstContainerPtr = NULL; + /* First in list of all containers + * managed by this process. */ + +/* + * Prototypes for static procedures defined in this file: + */ + +static void ContainerEventProc _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +static void EmbeddedEventProc _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +static int EmbedErrorProc _ANSI_ARGS_((ClientData clientData, + XErrorEvent *errEventPtr)); +static void EmbedFocusProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void EmbedGeometryRequest _ANSI_ARGS_(( + Container * containerPtr, int width, int height)); +static void EmbedSendConfigure _ANSI_ARGS_(( + Container *containerPtr)); +static void EmbedStructureProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void EmbedWindowDeleted _ANSI_ARGS_((TkWindow *winPtr)); + +/* + *---------------------------------------------------------------------- + * + * TkpUseWindow -- + * + * This procedure causes a Tk window to use a given X window as + * its parent window, rather than the root window for the screen. + * It is invoked by an embedded application to specify the window + * in which it is embedded. + * + * Results: + * The return value is normally TCL_OK. If an error occurs (such + * as string not being a valid window spec), then the return value + * is TCL_ERROR and an error message is left in interp->result if + * interp is non-NULL. + * + * Side effects: + * Changes the colormap and other visual information to match that + * of the parent window given by "string". + * + *---------------------------------------------------------------------- + */ + +int +TkpUseWindow(interp, tkwin, string) + Tcl_Interp *interp; /* If not NULL, used for error reporting + * if string is bogus. */ + Tk_Window tkwin; /* Tk window that does not yet have an + * associated X window. */ + char *string; /* String identifying an X window to use + * for tkwin; must be an integer value. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + int id, anyError; + Window parent; + Tk_ErrorHandler handler; + Container *containerPtr; + XWindowAttributes parentAtts; + + if (winPtr->window != None) { + panic("TkUseWindow: X window already assigned"); + } + if (Tcl_GetInt(interp, string, &id) != TCL_OK) { + return TCL_ERROR; + } + parent = (Window) id; + + /* + * Tk sets the window colormap to the screen default colormap in + * tkWindow.c:AllocWindow. This doesn't work well for embedded + * windows. So we override the colormap and visual settings to be + * the same as the parent window (which is in the container app). + */ + + anyError = 0; + handler = Tk_CreateErrorHandler(winPtr->display, -1, -1, -1, + EmbedErrorProc, (ClientData) &anyError); + if (!XGetWindowAttributes(winPtr->display, parent, &parentAtts)) { + anyError = 1; + } + XSync(winPtr->display, False); + Tk_DeleteErrorHandler(handler); + if (anyError) { + if (interp != NULL) { + Tcl_AppendResult(interp, "couldn't create child of window \"", + string, "\"", (char *) NULL); + } + return TCL_ERROR; + } + Tk_SetWindowVisual(tkwin, parentAtts.visual, parentAtts.depth, + parentAtts.colormap); + + /* + * Create an event handler to clean up the Container structure when + * tkwin is eventually deleted. + */ + + Tk_CreateEventHandler(tkwin, StructureNotifyMask, EmbeddedEventProc, + (ClientData) winPtr); + + /* + * Save information about the container and the embedded window + * in a Container structure. If there is already an existing + * Container structure, it means that both container and embedded + * app. are in the same process. + */ + + for (containerPtr = firstContainerPtr; containerPtr != NULL; + containerPtr = containerPtr->nextPtr) { + if (containerPtr->parent == parent) { + winPtr->flags |= TK_BOTH_HALVES; + containerPtr->parentPtr->flags |= TK_BOTH_HALVES; + break; + } + } + if (containerPtr == NULL) { + containerPtr = (Container *) ckalloc(sizeof(Container)); + containerPtr->parent = parent; + containerPtr->parentRoot = parentAtts.root; + containerPtr->parentPtr = NULL; + containerPtr->wrapper = None; + containerPtr->nextPtr = firstContainerPtr; + firstContainerPtr = containerPtr; + } + containerPtr->embeddedPtr = winPtr; + winPtr->flags |= TK_EMBEDDED; + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpMakeWindow -- + * + * Create an actual window system window object based on the + * current attributes of the specified TkWindow. + * + * Results: + * Returns the handle to the new window, or None on failure. + * + * Side effects: + * Creates a new X window. + * + *---------------------------------------------------------------------- + */ + +Window +TkpMakeWindow(winPtr, parent) + TkWindow *winPtr; /* Tk's information about the window that + * is to be instantiated. */ + Window parent; /* Window system token for the parent in + * which the window is to be created. */ +{ + Container *containerPtr; + + if (winPtr->flags & TK_EMBEDDED) { + /* + * This window is embedded. Don't create the new window in the + * given parent; instead, create it as a child of the root window + * of the container's screen. The window will get reparented + * into a wrapper window later. + */ + + for (containerPtr = firstContainerPtr; ; + containerPtr = containerPtr->nextPtr) { + if (containerPtr == NULL) { + panic("TkMakeWindow couldn't find container for window"); + } + if (containerPtr->embeddedPtr == winPtr) { + break; + } + } + parent = containerPtr->parentRoot; + } + + return XCreateWindow(winPtr->display, parent, winPtr->changes.x, + winPtr->changes.y, (unsigned) winPtr->changes.width, + (unsigned) winPtr->changes.height, + (unsigned) winPtr->changes.border_width, winPtr->depth, + InputOutput, winPtr->visual, winPtr->dirtyAtts, + &winPtr->atts); +} + +/* + *---------------------------------------------------------------------- + * + * TkpMakeContainer -- + * + * This procedure is called to indicate that a particular window + * will be a container for an embedded application. This changes + * certain aspects of the window's behavior, such as whether it + * will receive events anymore. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpMakeContainer(tkwin) + Tk_Window tkwin; /* Token for a window that is about to + * become a container. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + Container *containerPtr; + + /* + * Register the window as a container so that, for example, we can + * find out later if the embedded app. is in the same process. + */ + + Tk_MakeWindowExist(tkwin); + containerPtr = (Container *) ckalloc(sizeof(Container)); + containerPtr->parent = Tk_WindowId(tkwin); + containerPtr->parentRoot = RootWindowOfScreen(Tk_Screen(tkwin)); + containerPtr->parentPtr = winPtr; + containerPtr->wrapper = None; + containerPtr->embeddedPtr = NULL; + containerPtr->nextPtr = firstContainerPtr; + firstContainerPtr = containerPtr; + winPtr->flags |= TK_CONTAINER; + + /* + * Request SubstructureNotify events so that we can find out when + * the embedded application creates its window or attempts to + * resize it. Also watch Configure events on the container so that + * we can resize the child to match. + */ + + winPtr->atts.event_mask |= SubstructureRedirectMask|SubstructureNotifyMask; + XSelectInput(winPtr->display, winPtr->window, winPtr->atts.event_mask); + Tk_CreateEventHandler(tkwin, + SubstructureNotifyMask|SubstructureRedirectMask, + ContainerEventProc, (ClientData) winPtr); + Tk_CreateEventHandler(tkwin, StructureNotifyMask, EmbedStructureProc, + (ClientData) containerPtr); + Tk_CreateEventHandler(tkwin, FocusChangeMask, EmbedFocusProc, + (ClientData) containerPtr); +} + +/* + *---------------------------------------------------------------------- + * + * EmbedErrorProc -- + * + * This procedure is invoked if an error occurs while creating + * an embedded window. + * + * Results: + * Always returns 0 to indicate that the error has been properly + * handled. + * + * Side effects: + * The integer pointed to by the clientData argument is set to 1. + * + *---------------------------------------------------------------------- + */ + +static int +EmbedErrorProc(clientData, errEventPtr) + ClientData clientData; /* Points to integer to set. */ + XErrorEvent *errEventPtr; /* Points to information about error + * (not used). */ +{ + int *iPtr = (int *) clientData; + + *iPtr = 1; + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * EmbeddedEventProc -- + * + * This procedure is invoked by the Tk event dispatcher when various + * useful events are received for a window that is embedded in + * another application. + * + * Results: + * None. + * + * Side effects: + * Our internal state gets cleaned up when an embedded window is + * destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +EmbeddedEventProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + TkWindow *winPtr = (TkWindow *) clientData; + + if (eventPtr->type == DestroyNotify) { + EmbedWindowDeleted(winPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * ContainerEventProc -- + * + * This procedure is invoked by the Tk event dispatcher when various + * useful events are received for the children of a container + * window. It forwards relevant information, such as geometry + * requests, from the events into the container's application. + * + * Results: + * None. + * + * Side effects: + * Depends on the event. For example, when ConfigureRequest events + * occur, geometry information gets set for the container window. + * + *---------------------------------------------------------------------- + */ + +static void +ContainerEventProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + TkWindow *winPtr = (TkWindow *) clientData; + Container *containerPtr; + Tk_ErrorHandler errHandler; + + /* + * Ignore any X protocol errors that happen in this procedure + * (almost any operation could fail, for example, if the embedded + * application has deleted its window). + */ + + errHandler = Tk_CreateErrorHandler(eventPtr->xfocus.display, -1, + -1, -1, (Tk_ErrorProc *) NULL, (ClientData) NULL); + + /* + * Find the Container structure associated with the parent window. + */ + + for (containerPtr = firstContainerPtr; + containerPtr->parent != eventPtr->xmaprequest.parent; + containerPtr = containerPtr->nextPtr) { + if (containerPtr == NULL) { + panic("ContainerEventProc couldn't find Container record"); + } + } + + if (eventPtr->type == CreateNotify) { + /* + * A new child window has been created in the container. Record + * its id in the Container structure (if more than one child is + * created, just remember the last one and ignore the earlier + * ones). Also set the child's size to match the container. + */ + + containerPtr->wrapper = eventPtr->xcreatewindow.window; + XMoveResizeWindow(eventPtr->xcreatewindow.display, + containerPtr->wrapper, 0, 0, + (unsigned int) Tk_Width( + (Tk_Window) containerPtr->parentPtr), + (unsigned int) Tk_Height( + (Tk_Window) containerPtr->parentPtr)); + } else if (eventPtr->type == ConfigureRequest) { + if ((eventPtr->xconfigurerequest.x != 0) + || (eventPtr->xconfigurerequest.y != 0)) { + /* + * The embedded application is trying to move itself, which + * isn't legal. At this point, the window hasn't actually + * moved, but we need to send it a ConfigureNotify event to + * let it know that its request has been denied. If the + * embedded application was also trying to resize itself, a + * ConfigureNotify will be sent by the geometry management + * code below, so we don't need to do anything. Otherwise, + * generate a synthetic event. + */ + + if ((eventPtr->xconfigurerequest.width == winPtr->changes.width) + && (eventPtr->xconfigurerequest.height + == winPtr->changes.height)) { + EmbedSendConfigure(containerPtr); + } + } + EmbedGeometryRequest(containerPtr, + eventPtr->xconfigurerequest.width, + eventPtr->xconfigurerequest.height); + } else if (eventPtr->type == MapRequest) { + /* + * The embedded application's map request was ignored and simply + * passed on to us, so we have to map the window for it to appear + * on the screen. + */ + + XMapWindow(eventPtr->xmaprequest.display, + eventPtr->xmaprequest.window); + } else if (eventPtr->type == DestroyNotify) { + /* + * The embedded application is gone. Destroy the container window. + */ + + Tk_DestroyWindow((Tk_Window) winPtr); + } + Tk_DeleteErrorHandler(errHandler); +} + +/* + *---------------------------------------------------------------------- + * + * EmbedStructureProc -- + * + * This procedure is invoked by the Tk event dispatcher when + * a container window owned by this application gets resized + * (and also at several other times that we don't care about). + * This procedure reflects the size change in the embedded + * window that corresponds to the container. + * + * Results: + * None. + * + * Side effects: + * The embedded window gets resized to match the container. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedStructureProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + Container *containerPtr = (Container *) clientData; + Tk_ErrorHandler errHandler; + + if (eventPtr->type == ConfigureNotify) { + if (containerPtr->wrapper != None) { + /* + * Ignore errors, since the embedded application could have + * deleted its window. + */ + + errHandler = Tk_CreateErrorHandler(eventPtr->xfocus.display, -1, + -1, -1, (Tk_ErrorProc *) NULL, (ClientData) NULL); + XMoveResizeWindow(eventPtr->xconfigure.display, + containerPtr->wrapper, 0, 0, + (unsigned int) Tk_Width( + (Tk_Window) containerPtr->parentPtr), + (unsigned int) Tk_Height( + (Tk_Window) containerPtr->parentPtr)); + Tk_DeleteErrorHandler(errHandler); + } + } else if (eventPtr->type == DestroyNotify) { + EmbedWindowDeleted(containerPtr->parentPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * EmbedFocusProc -- + * + * This procedure is invoked by the Tk event dispatcher when + * FocusIn and FocusOut events occur for a container window owned + * by this application. It is responsible for moving the focus + * back and forth between a container application and an embedded + * application. + * + * Results: + * None. + * + * Side effects: + * The X focus may change. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedFocusProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + Container *containerPtr = (Container *) clientData; + Tk_ErrorHandler errHandler; + Display *display; + + display = Tk_Display(containerPtr->parentPtr); + if (eventPtr->type == FocusIn) { + /* + * The focus just arrived at the container. Change the X focus + * to move it to the embedded application, if there is one. + * Ignore X errors that occur during this operation (it's + * possible that the new focus window isn't mapped). + */ + + if (containerPtr->wrapper != None) { + errHandler = Tk_CreateErrorHandler(eventPtr->xfocus.display, -1, + -1, -1, (Tk_ErrorProc *) NULL, (ClientData) NULL); + XSetInputFocus(display, containerPtr->wrapper, RevertToParent, + CurrentTime); + Tk_DeleteErrorHandler(errHandler); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * EmbedGeometryRequest -- + * + * This procedure is invoked when an embedded application requests + * a particular size. It processes the request (which may or may + * not actually honor the request) and reflects the results back + * to the embedded application. + * + * Results: + * None. + * + * Side effects: + * If we deny the child's size change request, a Configure event + * is synthesized to let the child know how big it ought to be. + * Events get processed while we're waiting for the geometry + * managers to do their thing. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedGeometryRequest(containerPtr, width, height) + Container *containerPtr; /* Information about the embedding. */ + int width, height; /* Size that the child has requested. */ +{ + TkWindow *winPtr = containerPtr->parentPtr; + + /* + * Forward the requested size into our geometry management hierarchy + * via the container window. We need to send a Configure event back + * to the embedded application if we decide not to honor its + * request; to make this happen, process all idle event handlers + * synchronously here (so that the geometry managers have had a + * chance to do whatever they want to do), and if the window's size + * didn't change then generate a configure event. + */ + + Tk_GeometryRequest((Tk_Window) winPtr, width, height); + while (Tcl_DoOneEvent(TCL_IDLE_EVENTS)) { + /* Empty loop body. */ + } + if ((winPtr->changes.width != width) + || (winPtr->changes.height != height)) { + EmbedSendConfigure(containerPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * EmbedSendConfigure -- + * + * This procedure synthesizes a ConfigureNotify event to notify an + * embedded application of its current size and location. This + * procedure is called when the embedded application made a + * geometry request that we did not grant, so that the embedded + * application knows that its geometry didn't change after all. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedSendConfigure(containerPtr) + Container *containerPtr; /* Information about the embedding. */ +{ + TkWindow *winPtr = containerPtr->parentPtr; + XEvent event; + + event.xconfigure.type = ConfigureNotify; + event.xconfigure.serial = + LastKnownRequestProcessed(winPtr->display); + event.xconfigure.send_event = True; + event.xconfigure.display = winPtr->display; + event.xconfigure.event = containerPtr->wrapper; + event.xconfigure.window = containerPtr->wrapper; + event.xconfigure.x = 0; + event.xconfigure.y = 0; + event.xconfigure.width = winPtr->changes.width; + event.xconfigure.height = winPtr->changes.height; + event.xconfigure.above = None; + event.xconfigure.override_redirect = False; + + /* + * Note: when sending the event below, the ButtonPressMask + * causes the event to be sent only to applications that have + * selected for ButtonPress events, which should be just the + * embedded application. + */ + + XSendEvent(winPtr->display, containerPtr->wrapper, False, + 0, &event); + + /* + * The following needs to be done if the embedded window is + * not in the same application as the container window. + */ + + if (containerPtr->embeddedPtr == NULL) { + XMoveResizeWindow(winPtr->display, containerPtr->wrapper, 0, 0, + (unsigned int) winPtr->changes.width, + (unsigned int) winPtr->changes.height); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetOtherWindow -- + * + * If both the container and embedded window are in the same + * process, this procedure will return either one, given the other. + * + * Results: + * If winPtr is a container, the return value is the token for the + * embedded window, and vice versa. If the "other" window isn't in + * this process, NULL is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkpGetOtherWindow(winPtr) + TkWindow *winPtr; /* Tk's structure for a container or + * embedded window. */ +{ + Container *containerPtr; + + for (containerPtr = firstContainerPtr; containerPtr != NULL; + containerPtr = containerPtr->nextPtr) { + if (containerPtr->embeddedPtr == winPtr) { + return containerPtr->parentPtr; + } else if (containerPtr->parentPtr == winPtr) { + return containerPtr->embeddedPtr; + } + } + panic("TkpGetOtherWindow couldn't find window"); + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TkpRedirectKeyEvent -- + * + * This procedure is invoked when a key press or release event + * arrives for an application that does not believe it owns the + * input focus. This can happen because of embedding; for example, + * X can send an event to an embedded application when the real + * focus window is in the container application and is an ancestor + * of the container. This procedure's job is to forward the event + * back to the application where it really belongs. + * + * Results: + * None. + * + * Side effects: + * The event may get sent to a different application. + * + *---------------------------------------------------------------------- + */ + +void +TkpRedirectKeyEvent(winPtr, eventPtr) + TkWindow *winPtr; /* Window to which the event was originally + * reported. */ + XEvent *eventPtr; /* X event to redirect (should be KeyPress + * or KeyRelease). */ +{ + Container *containerPtr; + Window saved; + + /* + * First, find the top-level window corresponding to winPtr. + */ + + while (1) { + if (winPtr == NULL) { + /* + * This window is being deleted. This is too confusing a + * case to handle so discard the event. + */ + + return; + } + if (winPtr->flags & TK_TOP_LEVEL) { + break; + } + winPtr = winPtr->parentPtr; + } + + if (winPtr->flags & TK_EMBEDDED) { + /* + * This application is embedded. If we got a key event without + * officially having the focus, it means that the focus is + * really in the container, but the mouse was over the embedded + * application. Send the event back to the container. + */ + + for (containerPtr = firstContainerPtr; + containerPtr->embeddedPtr != winPtr; + containerPtr = containerPtr->nextPtr) { + /* Empty loop body. */ + } + saved = eventPtr->xkey.window; + eventPtr->xkey.window = containerPtr->parent; + XSendEvent(eventPtr->xkey.display, eventPtr->xkey.window, False, + KeyPressMask|KeyReleaseMask, eventPtr); + eventPtr->xkey.window = saved; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpClaimFocus -- + * + * This procedure is invoked when someone asks or the input focus + * to be put on a window in an embedded application, but the + * application doesn't currently have the focus. It requests the + * input focus from the container application. + * + * Results: + * None. + * + * Side effects: + * The input focus may change. + * + *---------------------------------------------------------------------- + */ + +void +TkpClaimFocus(topLevelPtr, force) + TkWindow *topLevelPtr; /* Top-level window containing desired + * focus window; should be embedded. */ + int force; /* One means that the container should + * claim the focus if it doesn't + * currently have it. */ +{ + XEvent event; + Container *containerPtr; + + if (!(topLevelPtr->flags & TK_EMBEDDED)) { + return; + } + + for (containerPtr = firstContainerPtr; + containerPtr->embeddedPtr != topLevelPtr; + containerPtr = containerPtr->nextPtr) { + /* Empty loop body. */ + } + + event.xfocus.type = FocusIn; + event.xfocus.serial = LastKnownRequestProcessed(topLevelPtr->display); + event.xfocus.send_event = 1; + event.xfocus.display = topLevelPtr->display; + event.xfocus.window = containerPtr->parent; + event.xfocus.mode = EMBEDDED_APP_WANTS_FOCUS; + event.xfocus.detail = force; + XSendEvent(event.xfocus.display, event.xfocus.window, False, 0, &event); +} + +/* + *---------------------------------------------------------------------- + * + * TkpTestembedCmd -- + * + * This procedure implements the "testembed" command. It returns + * some or all of the information in the list pointed to by + * firstContainerPtr. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpTestembedCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window for application. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + int all; + Container *containerPtr; + Tcl_DString dString; + char buffer[50]; + + if ((argc > 1) && (strcmp(argv[1], "all") == 0)) { + all = 1; + } else { + all = 0; + } + Tcl_DStringInit(&dString); + for (containerPtr = firstContainerPtr; containerPtr != NULL; + containerPtr = containerPtr->nextPtr) { + Tcl_DStringStartSublist(&dString); + if (containerPtr->parent == None) { + Tcl_DStringAppendElement(&dString, ""); + } else { + if (all) { + sprintf(buffer, "0x%x", (int) containerPtr->parent); + Tcl_DStringAppendElement(&dString, buffer); + } else { + Tcl_DStringAppendElement(&dString, "XXX"); + } + } + if (containerPtr->parentPtr == NULL) { + Tcl_DStringAppendElement(&dString, ""); + } else { + Tcl_DStringAppendElement(&dString, + containerPtr->parentPtr->pathName); + } + if (containerPtr->wrapper == None) { + Tcl_DStringAppendElement(&dString, ""); + } else { + if (all) { + sprintf(buffer, "0x%x", (int) containerPtr->wrapper); + Tcl_DStringAppendElement(&dString, buffer); + } else { + Tcl_DStringAppendElement(&dString, "XXX"); + } + } + if (containerPtr->embeddedPtr == NULL) { + Tcl_DStringAppendElement(&dString, ""); + } else { + Tcl_DStringAppendElement(&dString, + containerPtr->embeddedPtr->pathName); + } + Tcl_DStringEndSublist(&dString); + } + Tcl_DStringResult(interp, &dString); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * EmbedWindowDeleted -- + * + * This procedure is invoked when a window involved in embedding + * (as either the container or the embedded application) is + * destroyed. It cleans up the Container structure for the window. + * + * Results: + * None. + * + * Side effects: + * A Container structure may be freed. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedWindowDeleted(winPtr) + TkWindow *winPtr; /* Tk's information about window that + * was deleted. */ +{ + Container *containerPtr, *prevPtr; + + /* + * Find the Container structure for this window work. Delete the + * information about the embedded application and free the container's + * record. + */ + + prevPtr = NULL; + containerPtr = firstContainerPtr; + while (1) { + if (containerPtr->embeddedPtr == winPtr) { + containerPtr->wrapper = None; + containerPtr->embeddedPtr = NULL; + break; + } + if (containerPtr->parentPtr == winPtr) { + containerPtr->parentPtr = NULL; + break; + } + prevPtr = containerPtr; + containerPtr = containerPtr->nextPtr; + } + if ((containerPtr->embeddedPtr == NULL) + && (containerPtr->parentPtr == NULL)) { + if (prevPtr == NULL) { + firstContainerPtr = containerPtr->nextPtr; + } else { + prevPtr->nextPtr = containerPtr->nextPtr; + } + ckfree((char *) containerPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkUnixContainerId -- + * + * Given an embedded window, this procedure returns the X window + * identifier for the associated container window. + * + * Results: + * The return value is the X window identifier for winPtr's + * container window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Window +TkUnixContainerId(winPtr) + TkWindow *winPtr; /* Tk's structure for an embedded window. */ +{ + Container *containerPtr; + + for (containerPtr = firstContainerPtr; containerPtr != NULL; + containerPtr = containerPtr->nextPtr) { + if (containerPtr->embeddedPtr == winPtr) { + return containerPtr->parent; + } + } + panic("TkUnixContainerId couldn't find window"); + return None; +} diff --git a/unix/tkUnixEvent.c b/unix/tkUnixEvent.c new file mode 100644 index 0000000..ace4cc3 --- /dev/null +++ b/unix/tkUnixEvent.c @@ -0,0 +1,498 @@ +/* + * tkUnixEvent.c -- + * + * This file implements an event source for X displays for the + * UNIX version of Tk. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixEvent.c 1.17 97/09/11 12:51:04 + */ + +#include "tkInt.h" +#include "tkUnixInt.h" +#include <signal.h> + +/* + * The following static indicates whether this module has been initialized. + */ + +static int initialized = 0; + +/* + * Prototypes for procedures that are referenced only in this file: + */ + +static void DisplayCheckProc _ANSI_ARGS_((ClientData clientData, + int flags)); +static void DisplayExitHandler _ANSI_ARGS_(( + ClientData clientData)); +static void DisplayFileProc _ANSI_ARGS_((ClientData clientData, + int flags)); +static void DisplaySetupProc _ANSI_ARGS_((ClientData clientData, + int flags)); + +/* + *---------------------------------------------------------------------- + * + * TkCreateXEventSource -- + * + * This procedure is called during Tk initialization to create + * the event source for X Window events. + * + * Results: + * None. + * + * Side effects: + * A new event source is created. + * + *---------------------------------------------------------------------- + */ + +void +TkCreateXEventSource() +{ + if (!initialized) { + initialized = 1; + Tcl_CreateEventSource(DisplaySetupProc, DisplayCheckProc, NULL); + Tcl_CreateExitHandler(DisplayExitHandler, NULL); + } +} + +/* + *---------------------------------------------------------------------- + * + * DisplayExitHandler -- + * + * This function is called during finalization to clean up the + * display module. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +DisplayExitHandler(clientData) + ClientData clientData; /* Not used. */ +{ + Tcl_DeleteEventSource(DisplaySetupProc, DisplayCheckProc, NULL); + initialized = 0; +} + +/* + *---------------------------------------------------------------------- + * + * TkpOpenDisplay -- + * + * Allocates a new TkDisplay, opens the X display, and establishes + * the file handler for the connection. + * + * Results: + * A pointer to a Tk display structure. + * + * Side effects: + * Opens a display. + * + *---------------------------------------------------------------------- + */ + +TkDisplay * +TkpOpenDisplay(display_name) + char *display_name; +{ + TkDisplay *dispPtr; + Display *display = XOpenDisplay(display_name); + + if (display == NULL) { + return NULL; + } + dispPtr = (TkDisplay *) ckalloc(sizeof(TkDisplay)); + dispPtr->display = display; + Tcl_CreateFileHandler(ConnectionNumber(display), TCL_READABLE, + DisplayFileProc, (ClientData) dispPtr); + return dispPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpCloseDisplay -- + * + * Cancels notifier callbacks and closes a display. + * + * Results: + * None. + * + * Side effects: + * Deallocates the displayPtr. + * + *---------------------------------------------------------------------- + */ + +void +TkpCloseDisplay(displayPtr) + TkDisplay *displayPtr; +{ + TkDisplay *dispPtr = (TkDisplay *) displayPtr; + + if (dispPtr->display != 0) { + Tcl_DeleteFileHandler(ConnectionNumber(dispPtr->display)); + + (void) XSync(dispPtr->display, False); + (void) XCloseDisplay(dispPtr->display); + } + + ckfree((char *) dispPtr); +} + +/* + *---------------------------------------------------------------------- + * + * DisplaySetupProc -- + * + * This procedure implements the setup part of the UNIX X display + * event source. It is invoked by Tcl_DoOneEvent before entering + * the notifier to check for events on all displays. + * + * Results: + * None. + * + * Side effects: + * If data is queued on a display inside Xlib, then the maximum + * block time will be set to 0 to ensure that the notifier returns + * control to Tcl even if there is no more data on the X connection. + * + *---------------------------------------------------------------------- + */ + +static void +DisplaySetupProc(clientData, flags) + ClientData clientData; /* Not used. */ + int flags; +{ + TkDisplay *dispPtr; + static Tcl_Time blockTime = { 0, 0 }; + + if (!(flags & TCL_WINDOW_EVENTS)) { + return; + } + + for (dispPtr = tkDisplayList; dispPtr != NULL; + dispPtr = dispPtr->nextPtr) { + + /* + * Flush the display. If data is pending on the X queue, set + * the block time to zero. This ensures that we won't block + * in the notifier if there is data in the X queue, but not on + * the server socket. + */ + + XFlush(dispPtr->display); + if (XQLength(dispPtr->display) > 0) { + Tcl_SetMaxBlockTime(&blockTime); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * DisplayCheckProc -- + * + * This procedure checks for events sitting in the X event + * queue. + * + * Results: + * None. + * + * Side effects: + * Moves queued events onto the Tcl event queue. + * + *---------------------------------------------------------------------- + */ + +static void +DisplayCheckProc(clientData, flags) + ClientData clientData; /* Not used. */ + int flags; +{ + TkDisplay *dispPtr; + XEvent event; + int numFound; + + if (!(flags & TCL_WINDOW_EVENTS)) { + return; + } + + for (dispPtr = tkDisplayList; dispPtr != NULL; + dispPtr = dispPtr->nextPtr) { + XFlush(dispPtr->display); + numFound = XQLength(dispPtr->display); + + /* + * Transfer events from the X event queue to the Tk event queue. + */ + + while (numFound > 0) { + XNextEvent(dispPtr->display, &event); + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + numFound--; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * DisplayFileProc -- + * + * This procedure implements the file handler for the X connection. + * + * Results: + * None. + * + * Side effects: + * Makes entries on the Tcl event queue for all the events available + * from all the displays. + * + *---------------------------------------------------------------------- + */ + +static void +DisplayFileProc(clientData, flags) + ClientData clientData; /* The display pointer. */ + int flags; /* Should be TCL_READABLE. */ +{ + TkDisplay *dispPtr = (TkDisplay *) clientData; + Display *display = dispPtr->display; + XEvent event; + int numFound; + + XFlush(display); + numFound = XEventsQueued(display, QueuedAfterReading); + if (numFound == 0) { + + /* + * Things are very tricky if there aren't any events readable + * at this point (after all, there was supposedly data + * available on the connection). A couple of things could + * have occurred: + * + * One possibility is that there were only error events in the + * input from the server. If this happens, we should return + * (we don't want to go to sleep in XNextEvent below, since + * this would block out other sources of input to the + * process). + * + * Another possibility is that our connection to the server + * has been closed. This will not necessarily be detected in + * XEventsQueued (!!), so if we just return then there will be + * an infinite loop. To detect such an error, generate a NoOp + * protocol request to exercise the connection to the server, + * then return. However, must disable SIGPIPE while sending + * the request, or else the process will die from the signal + * and won't invoke the X error function to print a nice (?!) + * message. + */ + + void (*oldHandler)(); + + oldHandler = (void (*)()) signal(SIGPIPE, SIG_IGN); + XNoOp(display); + XFlush(display); + (void) signal(SIGPIPE, oldHandler); + } + + /* + * Transfer events from the X event queue to the Tk event queue. + */ + + while (numFound > 0) { + XNextEvent(display, &event); + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + numFound--; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkUnixDoOneXEvent -- + * + * This routine waits for an X event to be processed or for + * a timeout to occur. The timeout is specified as an absolute + * time. This routine is called when Tk needs to wait for a + * particular X event without letting arbitrary events be + * processed. The caller will typically call Tk_RestrictEvents + * to set up an event filter before calling this routine. This + * routine will service at most one event per invocation. + * + * Results: + * Returns 0 if the timeout has expired, otherwise returns 1. + * + * Side effects: + * Can invoke arbitrary Tcl scripts. + * + *---------------------------------------------------------------------- + */ + +int +TkUnixDoOneXEvent(timePtr) + Tcl_Time *timePtr; /* Specifies the absolute time when the + * call should time out. */ +{ + TkDisplay *dispPtr; + static fd_mask readMask[MASK_SIZE]; + struct timeval blockTime, *timeoutPtr; + Tcl_Time now; + int fd, index, bit, numFound, numFdBits = 0; + + /* + * Look for queued events first. + */ + + if (Tcl_ServiceEvent(TCL_WINDOW_EVENTS)) { + return 1; + } + + /* + * Compute the next block time and check to see if we have timed out. + * Note that HP-UX defines tv_sec to be unsigned so we have to be + * careful in our arithmetic. + */ + + if (timePtr) { + TclpGetTime(&now); + blockTime.tv_sec = timePtr->sec; + blockTime.tv_usec = timePtr->usec - now.usec; + if (blockTime.tv_usec < 0) { + now.sec += 1; + blockTime.tv_usec += 1000000; + } + if (blockTime.tv_sec < now.sec) { + blockTime.tv_sec = 0; + blockTime.tv_usec = 0; + } else { + blockTime.tv_sec -= now.sec; + } + timeoutPtr = &blockTime; + } else { + timeoutPtr = NULL; + } + + /* + * Set up the select mask for all of the displays. If a display has + * data pending, then we want to poll instead of blocking. + */ + + memset((VOID *) readMask, 0, MASK_SIZE*sizeof(fd_mask)); + for (dispPtr = tkDisplayList; dispPtr != NULL; + dispPtr = dispPtr->nextPtr) { + XFlush(dispPtr->display); + if (XQLength(dispPtr->display) > 0) { + blockTime.tv_sec = 0; + blockTime.tv_usec = 0; + } + fd = ConnectionNumber(dispPtr->display); + index = fd/(NBBY*sizeof(fd_mask)); + bit = 1 << (fd%(NBBY*sizeof(fd_mask))); + readMask[index] |= bit; + if (numFdBits <= fd) { + numFdBits = fd+1; + } + } + + numFound = select(numFdBits, (SELECT_MASK *) &readMask[0], NULL, NULL, + timeoutPtr); + if (numFound <= 0) { + /* + * Some systems don't clear the masks after an error, so + * we have to do it here. + */ + + memset((VOID *) readMask, 0, MASK_SIZE*sizeof(fd_mask)); + } + + /* + * Process any new events on the display connections. + */ + + for (dispPtr = tkDisplayList; dispPtr != NULL; + dispPtr = dispPtr->nextPtr) { + fd = ConnectionNumber(dispPtr->display); + index = fd/(NBBY*sizeof(fd_mask)); + bit = 1 << (fd%(NBBY*sizeof(fd_mask))); + if ((readMask[index] & bit) || (XQLength(dispPtr->display) > 0)) { + DisplayFileProc((ClientData)dispPtr, TCL_READABLE); + } + } + if (Tcl_ServiceEvent(TCL_WINDOW_EVENTS)) { + return 1; + } + + /* + * Check to see if we timed out. + */ + + if (timePtr) { + TclpGetTime(&now); + if ((now.sec > timePtr->sec) || ((now.sec == timePtr->sec) + && (now.usec > timePtr->usec))) { + return 0; + } + } + + /* + * We had an event but we did not generate a Tcl event from it. Behave + * as though we dealt with it. (JYL&SS) + */ + + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * TkpSync -- + * + * This routine ensures that all pending X requests have been + * seen by the server, and that any pending X events have been + * moved onto the Tk event queue. + * + * Results: + * None. + * + * Side effects: + * Places new events on the Tk event queue. + * + *---------------------------------------------------------------------- + */ + +void +TkpSync(display) + Display *display; /* Display to sync. */ +{ + int numFound = 0; + XEvent event; + + XSync(display, False); + + /* + * Transfer events from the X event queue to the Tk event queue. + */ + + numFound = XQLength(display); + while (numFound > 0) { + XNextEvent(display, &event); + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + numFound--; + } +} diff --git a/unix/tkUnixFocus.c b/unix/tkUnixFocus.c new file mode 100644 index 0000000..5c1a4f6 --- /dev/null +++ b/unix/tkUnixFocus.c @@ -0,0 +1,149 @@ +/* + * tkUnixFocus.c -- + * + * This file contains platform specific procedures that manage + * focus for Tk. + * + * Copyright (c) 1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixFocus.c 1.9 97/10/31 09:54:04 + */ + +#include "tkInt.h" +#include "tkPort.h" +#include "tkUnixInt.h" + +extern int tclFocusDebug; + +/* + *---------------------------------------------------------------------- + * + * TkpChangeFocus -- + * + * This procedure is invoked to move the official X focus from + * one window to another. + * + * Results: + * The return value is the serial number of the command that + * changed the focus. It may be needed by the caller to filter + * out focus change events that were queued before the command. + * If the procedure doesn't actually change the focus then + * it returns 0. + * + * Side effects: + * The official X focus window changes; the application's focus + * window isn't changed by this procedure. + * + *---------------------------------------------------------------------- + */ + +int +TkpChangeFocus(winPtr, force) + TkWindow *winPtr; /* Window that is to receive the X focus. */ + int force; /* Non-zero means claim the focus even + * if it didn't originally belong to + * topLevelPtr's application. */ +{ + TkDisplay *dispPtr = winPtr->dispPtr; + Tk_ErrorHandler errHandler; + Window window, root, parent, *children; + unsigned int numChildren, serial; + TkWindow *winPtr2; + int dummy; + + /* + * Don't set the X focus to a window that's marked + * override-redirect. This is a hack to avoid problems with menus + * under olvwm: if we move the focus then the focus can get lost + * during keyboard traversal. Fortunately, we don't really need to + * move the focus for menus: events will still find their way to the + * focus window, and menus aren't decorated anyway so the window + * manager doesn't need to hear about the focus change in order to + * redecorate the menu. + */ + + serial = 0; + if (winPtr->atts.override_redirect) { + return serial; + } + + /* + * Check to make sure that the focus is still in one of the windows + * of this application or one of their descendants. Furthermore, + * grab the server to make sure that the focus doesn't change in the + * middle of this operation. + */ + + XGrabServer(dispPtr->display); + if (!force) { + /* + * Find the focus window, then see if it or one of its ancestors + * is a window in our application (it's possible that the focus + * window is in an embedded application, which may or may not be + * in the same process. + */ + + XGetInputFocus(dispPtr->display, &window, &dummy); + while (1) { + winPtr2 = (TkWindow *) Tk_IdToWindow(dispPtr->display, window); + if ((winPtr2 != NULL) && (winPtr2->mainPtr == winPtr->mainPtr)) { + break; + } + if ((window == PointerRoot) || (window == None)) { + goto done; + } + XQueryTree(dispPtr->display, window, &root, &parent, &children, + &numChildren); + if (children != NULL) { + XFree((void *) children); + } + if (parent == root) { + goto done; + } + window = parent; + } + } + + /* + * Tell X to change the focus. Ignore errors that occur when changing + * the focus: it is still possible that the window we're focussing + * to could have gotten unmapped, which will generate an error. + */ + + errHandler = Tk_CreateErrorHandler(dispPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + if (winPtr->window == None) { + panic("ChangeXFocus got null X window"); + } + XSetInputFocus(dispPtr->display, winPtr->window, RevertToParent, + CurrentTime); + Tk_DeleteErrorHandler(errHandler); + + /* + * Remember the current serial number for the X server and issue + * a dummy server request. This marks the position at which we + * changed the focus, so we can distinguish FocusIn and FocusOut + * events on either side of the mark. + */ + + serial = NextRequest(winPtr->display); + XNoOp(winPtr->display); + + done: + XUngrabServer(dispPtr->display); + + /* + * After ungrabbing the server, it's important to flush the output + * immediately so that the server sees the ungrab command. Otherwise + * we might do something else that needs to communicate with the + * server (such as invoking a subprocess that needs to do I/O to + * the screen); if the ungrab command is still sitting in our + * output buffer, we could deadlock. + */ + + XFlush(dispPtr->display); + return serial; +} diff --git a/unix/tkUnixFont.c b/unix/tkUnixFont.c new file mode 100644 index 0000000..d25f157 --- /dev/null +++ b/unix/tkUnixFont.c @@ -0,0 +1,979 @@ +/* + * tkUnixFont.c -- + * + * Contains the Unix implementation of the platform-independant + * font package interface. + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixFont.c 1.16 97/10/23 12:47:53 + */ + +#include "tkPort.h" +#include "tkInt.h" +#include "tkUnixInt.h" + +#include "tkFont.h" + +#ifndef ABS +#define ABS(n) (((n) < 0) ? -(n) : (n)) +#endif + +/* + * The following structure represents Unix's implementation of a font. + */ + +typedef struct UnixFont { + TkFont font; /* Stuff used by generic font package. Must + * be first in structure. */ + Display *display; /* The display to which font belongs. */ + XFontStruct *fontStructPtr; /* X information about font. */ + char types[256]; /* Array giving types of all characters in + * the font, used when displaying control + * characters. See below for definition. */ + int widths[256]; /* Array giving widths of all possible + * characters in the font. */ + int underlinePos; /* Offset from baseline to origin of + * underline bar (used for simulating a native + * underlined font). */ + int barHeight; /* Height of underline or overstrike bar + * (used for simulating a native underlined or + * strikeout font). */ +} UnixFont; + +/* + * Possible values for entries in the "types" field in a UnixFont structure, + * which classifies the types of all characters in the given font. This + * information is used when measuring and displaying characters. + * + * NORMAL: Standard character. + * REPLACE: This character doesn't print: instead of + * displaying character, display a replacement + * sequence like "\n" (for those characters where + * ANSI C defines such a sequence) or a sequence + * of the form "\xdd" where dd is the hex equivalent + * of the character. + * SKIP: Don't display anything for this character. This + * is only used where the font doesn't contain + * all the characters needed to generate + * replacement sequences. + */ + +#define NORMAL 0 +#define REPLACE 1 +#define SKIP 2 + +/* + * Characters used when displaying control sequences. + */ + +static char hexChars[] = "0123456789abcdefxtnvr\\"; + +/* + * The following table maps some control characters to sequences like '\n' + * rather than '\x10'. A zero entry in the table means no such mapping + * exists, and the table only maps characters less than 0x10. + */ + +static char mapChars[] = { + 0, 0, 0, 0, 0, 0, 0, + 'a', 'b', 't', 'n', 'v', 'f', 'r', + 0 +}; + + +static UnixFont * AllocFont _ANSI_ARGS_((TkFont *tkFontPtr, + Tk_Window tkwin, XFontStruct *fontStructPtr, + CONST char *fontName)); +static void DrawChars _ANSI_ARGS_((Display *display, + Drawable drawable, GC gc, UnixFont *fontPtr, + CONST char *source, int numChars, int x, + int y)); +static int GetControlCharSubst _ANSI_ARGS_((int c, char buf[4])); + + +/* + *--------------------------------------------------------------------------- + * + * TkpGetNativeFont -- + * + * Map a platform-specific native font name to a TkFont. + * + * Results: + * The return value is a pointer to a TkFont that represents the + * native font. If a native font by the given name could not be + * found, the return value is NULL. + * + * Every call to this procedure returns a new TkFont structure, + * even if the name has already been seen before. The caller should + * call TkpDeleteFont() when the font is no longer needed. + * + * The caller is responsible for initializing the memory associated + * with the generic TkFont when this function returns and releasing + * the contents of the generic TkFont before calling TkpDeleteFont(). + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +TkFont * +TkpGetNativeFont(tkwin, name) + Tk_Window tkwin; /* For display where font will be used. */ + CONST char *name; /* Platform-specific font name. */ +{ + XFontStruct *fontStructPtr; + + fontStructPtr = XLoadQueryFont(Tk_Display(tkwin), name); + if (fontStructPtr == NULL) { + return NULL; + } + + return (TkFont *) AllocFont(NULL, tkwin, fontStructPtr, name); +} + +/* + *--------------------------------------------------------------------------- + * + * TkpGetFontFromAttributes -- + * + * Given a desired set of attributes for a font, find a font with + * the closest matching attributes. + * + * Results: + * The return value is a pointer to a TkFont that represents the + * font with the desired attributes. If a font with the desired + * attributes could not be constructed, some other font will be + * substituted automatically. + * + * Every call to this procedure returns a new TkFont structure, + * even if the specified attributes have already been seen before. + * The caller should call TkpDeleteFont() to free the platform- + * specific data when the font is no longer needed. + * + * The caller is responsible for initializing the memory associated + * with the generic TkFont when this function returns and releasing + * the contents of the generic TkFont before calling TkpDeleteFont(). + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ +TkFont * +TkpGetFontFromAttributes(tkFontPtr, tkwin, faPtr) + TkFont *tkFontPtr; /* If non-NULL, store the information in + * this existing TkFont structure, rather than + * allocating a new structure to hold the + * font; the existing contents of the font + * will be released. If NULL, a new TkFont + * structure is allocated. */ + Tk_Window tkwin; /* For display where font will be used. */ + CONST TkFontAttributes *faPtr; /* Set of attributes to match. */ +{ + int numNames, score, i, scaleable, pixelsize, xaPixelsize; + int bestIdx, bestScore, bestScaleableIdx, bestScaleableScore; + TkXLFDAttributes xa; + char buf[256]; + UnixFont *fontPtr; + char **nameList; + XFontStruct *fontStructPtr; + CONST char *fmt, *family; + double d; + + family = faPtr->family; + if (family == NULL) { + family = "*"; + } + + pixelsize = -faPtr->pointsize; + if (pixelsize < 0) { + d = -pixelsize * 25.4 / 72; + d *= WidthOfScreen(Tk_Screen(tkwin)); + d /= WidthMMOfScreen(Tk_Screen(tkwin)); + d += 0.5; + pixelsize = (int) d; + } + + /* + * Replace the standard Windows and Mac family names with the names that + * X likes. + */ + + if ((strcasecmp("Times New Roman", family) == 0) + || (strcasecmp("New York", family) == 0)) { + family = "Times"; + } else if ((strcasecmp("Courier New", family) == 0) + || (strcasecmp("Monaco", family) == 0)) { + family = "Courier"; + } else if ((strcasecmp("Arial", family) == 0) + || (strcasecmp("Geneva", family) == 0)) { + family = "Helvetica"; + } + + /* + * First try for the Q&D exact match. + */ + +#if 0 + sprintf(buf, "-*-%.200s-%s-%c-normal-*-*-%d-*-*-*-*-iso8859-1", family, + ((faPtr->weight > TK_FW_NORMAL) ? "bold" : "medium"), + ((faPtr->slant == TK_FS_ROMAN) ? 'r' : + (faPtr->slant == TK_FS_ITALIC) ? 'i' : 'o'), + faPtr->pointsize * 10); + fontStructPtr = XLoadQueryFont(Tk_Display(tkwin), buf); +#else + fontStructPtr = NULL; +#endif + + if (fontStructPtr != NULL) { + goto end; + } + /* + * Couldn't find exact match. Now fall back to other available + * physical fonts. + */ + + fmt = "-*-%.240s-*-*-*-*-*-*-*-*-*-*-*-*"; + sprintf(buf, fmt, family); + nameList = XListFonts(Tk_Display(tkwin), buf, 10000, &numNames); + if (numNames == 0) { + /* + * Try getting some system font. + */ + + sprintf(buf, fmt, "fixed"); + nameList = XListFonts(Tk_Display(tkwin), buf, 10000, &numNames); + if (numNames == 0) { + getsystem: + fontStructPtr = XLoadQueryFont(Tk_Display(tkwin), "fixed"); + if (fontStructPtr == NULL) { + fontStructPtr = XLoadQueryFont(Tk_Display(tkwin), "*"); + if (fontStructPtr == NULL) { + panic("TkpGetFontFromAttributes: cannot get any font"); + } + } + goto end; + } + } + + /* + * Inspect each of the XLFDs and pick the one that most closely + * matches the desired attributes. + */ + + bestIdx = 0; + bestScore = INT_MAX; + bestScaleableIdx = 0; + bestScaleableScore = INT_MAX; + + for (i = 0; i < numNames; i++) { + score = 0; + scaleable = 0; + if (TkParseXLFD(nameList[i], &xa) != TCL_OK) { + continue; + } + xaPixelsize = -xa.fa.pointsize; + + /* + * Since most people used to use -adobe-* in their XLFDs, + * preserve the preference for "adobe" foundry. Otherwise + * some applications looks may change slightly if another foundry + * is chosen. + */ + + if (strcasecmp(xa.foundry, "adobe") != 0) { + score += 3000; + } + if (xa.fa.pointsize == 0) { + /* + * A scaleable font is almost always acceptable, but the + * corresponding bitmapped font would be better. + */ + + score += 10; + scaleable = 1; + } else { + /* + * A font that is too small is better than one that is too + * big. + */ + + if (xaPixelsize > pixelsize) { + score += (xaPixelsize - pixelsize) * 120; + } else { + score += (pixelsize - xaPixelsize) * 100; + } + } + + score += ABS(xa.fa.weight - faPtr->weight) * 30; + score += ABS(xa.fa.slant - faPtr->slant) * 25; + if (xa.slant == TK_FS_OBLIQUE) { + /* + * Italic fonts are preferred over oblique. */ + + score += 4; + } + + if (xa.setwidth != TK_SW_NORMAL) { + /* + * The normal setwidth is highly preferred. + */ + score += 2000; + } + if (xa.charset == TK_CS_OTHER) { + /* + * The standard character set is highly preferred over + * foreign languages charsets (because we don't support + * other languages yet). + */ + score += 11000; + } + if ((xa.charset == TK_CS_NORMAL) && (xa.encoding != 1)) { + /* + * The '1' encoding for the characters above 0x7f is highly + * preferred over the other encodings. + */ + score += 8000; + } + + if (scaleable) { + if (score < bestScaleableScore) { + bestScaleableIdx = i; + bestScaleableScore = score; + } + } else { + if (score < bestScore) { + bestIdx = i; + bestScore = score; + } + } + if (score == 0) { + break; + } + } + + /* + * Now we know which is the closest matching scaleable font and the + * closest matching bitmapped font. If the scaleable font was a + * better match, try getting the scaleable font; however, if the + * scalable font was not actually available in the desired + * pointsize, fall back to the closest bitmapped font. + */ + + fontStructPtr = NULL; + if (bestScaleableScore < bestScore) { + char *str, *rest; + + /* + * Fill in the desired pointsize info for this font. + */ + + tryscale: + str = nameList[bestScaleableIdx]; + for (i = 0; i < XLFD_PIXEL_SIZE - 1; i++) { + str = strchr(str + 1, '-'); + } + rest = str; + for (i = XLFD_PIXEL_SIZE - 1; i < XLFD_REGISTRY; i++) { + rest = strchr(rest + 1, '-'); + } + *str = '\0'; + sprintf(buf, "%.240s-*-%d-*-*-*-*-*%s", nameList[bestScaleableIdx], + pixelsize, rest); + *str = '-'; + fontStructPtr = XLoadQueryFont(Tk_Display(tkwin), buf); + bestScaleableScore = INT_MAX; + } + if (fontStructPtr == NULL) { + strcpy(buf, nameList[bestIdx]); + fontStructPtr = XLoadQueryFont(Tk_Display(tkwin), buf); + if (fontStructPtr == NULL) { + /* + * This shouldn't happen because the font name is one of the + * names that X gave us to use, but it does anyhow. + */ + + if (bestScaleableScore < INT_MAX) { + goto tryscale; + } else { + XFreeFontNames(nameList); + goto getsystem; + } + } + } + XFreeFontNames(nameList); + + end: + fontPtr = AllocFont(tkFontPtr, tkwin, fontStructPtr, buf); + fontPtr->font.fa.underline = faPtr->underline; + fontPtr->font.fa.overstrike = faPtr->overstrike; + + return (TkFont *) fontPtr; +} + + +/* + *--------------------------------------------------------------------------- + * + * TkpDeleteFont -- + * + * Called to release a font allocated by TkpGetNativeFont() or + * TkpGetFontFromAttributes(). The caller should have already + * released the fields of the TkFont that are used exclusively by + * the generic TkFont code. + * + * Results: + * None. + * + * Side effects: + * TkFont is deallocated. + * + *--------------------------------------------------------------------------- + */ + +void +TkpDeleteFont(tkFontPtr) + TkFont *tkFontPtr; /* Token of font to be deleted. */ +{ + UnixFont *fontPtr; + + fontPtr = (UnixFont *) tkFontPtr; + + XFreeFont(fontPtr->display, fontPtr->fontStructPtr); + ckfree((char *) fontPtr); +} + +/* + *--------------------------------------------------------------------------- + * + * TkpGetFontFamilies -- + * + * Return information about the font families that are available + * on the display of the given window. + * + * Results: + * interp->result is modified to hold a list of all the available + * font families. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +void +TkpGetFontFamilies(interp, tkwin) + Tcl_Interp *interp; + Tk_Window tkwin; +{ + int i, new, numNames; + char *family, *end, *p; + Tcl_HashTable familyTable; + Tcl_HashEntry *hPtr; + Tcl_HashSearch search; + char **nameList; + + Tcl_InitHashTable(&familyTable, TCL_STRING_KEYS); + + nameList = XListFonts(Tk_Display(tkwin), "*", 10000, &numNames); + for (i = 0; i < numNames; i++) { + if (nameList[i][0] != '-') { + continue; + } + family = strchr(nameList[i] + 1, '-'); + if (family == NULL) { + continue; + } + family++; + end = strchr(family, '-'); + if (end == NULL) { + continue; + } + *end = '\0'; + for (p = family; *p != '\0'; p++) { + if (isupper(UCHAR(*p))) { + *p = tolower(UCHAR(*p)); + } + } + Tcl_CreateHashEntry(&familyTable, family, &new); + } + + hPtr = Tcl_FirstHashEntry(&familyTable, &search); + while (hPtr != NULL) { + Tcl_AppendElement(interp, Tcl_GetHashKey(&familyTable, hPtr)); + hPtr = Tcl_NextHashEntry(&search); + } + + Tcl_DeleteHashTable(&familyTable); + XFreeFontNames(nameList); +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_MeasureChars -- + * + * Determine the number of characters from the string that will fit + * in the given horizontal span. The measurement is done under the + * assumption that Tk_DrawChars() will be used to actually display + * the characters. + * + * Results: + * The return value is the number of characters from source that + * fit into the span that extends from 0 to maxLength. *lengthPtr is + * filled with the x-coordinate of the right edge of the last + * character that did fit. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ +int +Tk_MeasureChars(tkfont, source, numChars, maxLength, flags, lengthPtr) + Tk_Font tkfont; /* Font in which characters will be drawn. */ + CONST char *source; /* Characters to be displayed. Need not be + * '\0' terminated. */ + int numChars; /* Maximum number of characters to consider + * from source string. */ + int maxLength; /* If > 0, maxLength specifies the longest + * permissible line length; don't consider any + * character that would cross this + * x-position. If <= 0, then line length is + * unbounded and the flags argument is + * ignored. */ + int flags; /* Various flag bits OR-ed together: + * TK_PARTIAL_OK means include the last char + * which only partially fit on this line. + * TK_WHOLE_WORDS means stop on a word + * boundary, if possible. + * TK_AT_LEAST_ONE means return at least one + * character even if no characters fit. */ + int *lengthPtr; /* Filled with x-location just after the + * terminating character. */ +{ + UnixFont *fontPtr; + CONST char *p; /* Current character. */ + CONST char *term; /* Pointer to most recent character that + * may legally be a terminating character. */ + int termX; /* X-position just after term. */ + int curX; /* X-position corresponding to p. */ + int newX; /* X-position corresponding to p+1. */ + int c, sawNonSpace; + + fontPtr = (UnixFont *) tkfont; + + if (numChars == 0) { + *lengthPtr = 0; + return 0; + } + + if (maxLength <= 0) { + maxLength = INT_MAX; + } + + newX = curX = termX = 0; + p = term = source; + sawNonSpace = !isspace(UCHAR(*p)); + + /* + * Scan the input string one character at a time, calculating width. + */ + + for (c = UCHAR(*p); ; ) { + newX += fontPtr->widths[c]; + if (newX > maxLength) { + break; + } + curX = newX; + numChars--; + p++; + if (numChars == 0) { + term = p; + termX = curX; + break; + } + + c = UCHAR(*p); + if (isspace(c)) { + if (sawNonSpace) { + term = p; + termX = curX; + sawNonSpace = 0; + } + } else { + sawNonSpace = 1; + } + } + + /* + * P points to the first character that doesn't fit in the desired + * span. Use the flags to figure out what to return. + */ + + if ((flags & TK_PARTIAL_OK) && (numChars > 0) && (curX < maxLength)) { + /* + * Include the first character that didn't quite fit in the desired + * span. The width returned will include the width of that extra + * character. + */ + + numChars--; + curX = newX; + p++; + } + if ((flags & TK_AT_LEAST_ONE) && (term == source) && (numChars > 0)) { + term = p; + termX = curX; + if (term == source) { + term++; + termX = newX; + } + } else if ((numChars == 0) || !(flags & TK_WHOLE_WORDS)) { + term = p; + termX = curX; + } + + *lengthPtr = termX; + return term-source; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_DrawChars, DrawChars -- + * + * Draw a string of characters on the screen. Tk_DrawChars() + * expands control characters that occur in the string to \X or + * \xXX sequences. DrawChars() just draws the strings. + * + * Results: + * None. + * + * Side effects: + * Information gets drawn on the screen. + * + *--------------------------------------------------------------------------- + */ + +void +Tk_DrawChars(display, drawable, gc, tkfont, source, numChars, x, y) + Display *display; /* Display on which to draw. */ + Drawable drawable; /* Window or pixmap in which to draw. */ + GC gc; /* Graphics context for drawing characters. */ + Tk_Font tkfont; /* Font in which characters will be drawn; + * must be the same as font used in GC. */ + CONST char *source; /* Characters to be displayed. Need not be + * '\0' terminated. All Tk meta-characters + * (tabs, control characters, and newlines) + * should be stripped out of the string that + * is passed to this function. If they are + * not stripped out, they will be displayed as + * regular printing characters. */ + int numChars; /* Number of characters in string. */ + int x, y; /* Coordinates at which to place origin of + * string when drawing. */ +{ + UnixFont *fontPtr; + CONST char *p; + int i, type; + char buf[4]; + + fontPtr = (UnixFont *) tkfont; + + p = source; + for (i = 0; i < numChars; i++) { + type = fontPtr->types[UCHAR(*p)]; + if (type != NORMAL) { + DrawChars(display, drawable, gc, fontPtr, source, p - source, x, y); + x += XTextWidth(fontPtr->fontStructPtr, source, p - source); + if (type == REPLACE) { + DrawChars(display, drawable, gc, fontPtr, buf, + GetControlCharSubst(UCHAR(*p), buf), x, y); + x += fontPtr->widths[UCHAR(*p)]; + } + source = p + 1; + } + p++; + } + + DrawChars(display, drawable, gc, fontPtr, source, p - source, x, y); +} + +static void +DrawChars(display, drawable, gc, fontPtr, source, numChars, x, y) + Display *display; /* Display on which to draw. */ + Drawable drawable; /* Window or pixmap in which to draw. */ + GC gc; /* Graphics context for drawing characters. */ + UnixFont *fontPtr; /* Font in which characters will be drawn; + * must be the same as font used in GC. */ + CONST char *source; /* Characters to be displayed. Need not be + * '\0' terminated. All Tk meta-characters + * (tabs, control characters, and newlines) + * should be stripped out of the string that + * is passed to this function. If they are + * not stripped out, they will be displayed as + * regular printing characters. */ + int numChars; /* Number of characters in string. */ + int x, y; /* Coordinates at which to place origin of + * string when drawing. */ +{ + XDrawString(display, drawable, gc, x, y, source, numChars); + + if (fontPtr->font.fa.underline != 0) { + XFillRectangle(display, drawable, gc, x, + y + fontPtr->underlinePos, + (unsigned) XTextWidth(fontPtr->fontStructPtr, source, numChars), + (unsigned) fontPtr->barHeight); + } + if (fontPtr->font.fa.overstrike != 0) { + y -= fontPtr->font.fm.descent + (fontPtr->font.fm.ascent) / 10; + XFillRectangle(display, drawable, gc, x, y, + (unsigned) XTextWidth(fontPtr->fontStructPtr, source, numChars), + (unsigned) fontPtr->barHeight); + } +} + +/* + *--------------------------------------------------------------------------- + * + * AllocFont -- + * + * Helper for TkpGetNativeFont() and TkpGetFontFromAttributes(). + * Allocates and intializes the memory for a new TkFont that + * wraps the platform-specific data. + * + * Results: + * Returns pointer to newly constructed TkFont. + * + * The caller is responsible for initializing the fields of the + * TkFont that are used exclusively by the generic TkFont code, and + * for releasing those fields before calling TkpDeleteFont(). + * + * Side effects: + * Memory allocated. + * + *--------------------------------------------------------------------------- + */ + +static UnixFont * +AllocFont(tkFontPtr, tkwin, fontStructPtr, fontName) + TkFont *tkFontPtr; /* If non-NULL, store the information in + * this existing TkFont structure, rather than + * allocating a new structure to hold the + * font; the existing contents of the font + * will be released. If NULL, a new TkFont + * structure is allocated. */ + Tk_Window tkwin; /* For display where font will be used. */ + XFontStruct *fontStructPtr; /* X information about font. */ + CONST char *fontName; /* The string passed to XLoadQueryFont() to + * construct the fontStructPtr. */ +{ + UnixFont *fontPtr; + unsigned long value; + int i, width, firstChar, lastChar, n, replaceOK; + char *name, *p; + char buf[4]; + TkXLFDAttributes xa; + double d; + + if (tkFontPtr != NULL) { + fontPtr = (UnixFont *) tkFontPtr; + XFreeFont(fontPtr->display, fontPtr->fontStructPtr); + } else { + fontPtr = (UnixFont *) ckalloc(sizeof(UnixFont)); + } + + /* + * Encapsulate the generic stuff in the TkFont. + */ + + fontPtr->font.fid = fontStructPtr->fid; + + if (XGetFontProperty(fontStructPtr, XA_FONT, &value) && (value != 0)) { + name = Tk_GetAtomName(tkwin, (Atom) value); + TkInitFontAttributes(&xa.fa); + if (TkParseXLFD(name, &xa) == TCL_OK) { + goto ok; + } + } + TkInitFontAttributes(&xa.fa); + if (TkParseXLFD(fontName, &xa) != TCL_OK) { + TkInitFontAttributes(&fontPtr->font.fa); + fontPtr->font.fa.family = Tk_GetUid(fontName); + } else { + ok: + fontPtr->font.fa = xa.fa; + } + + if (fontPtr->font.fa.pointsize < 0) { + d = -fontPtr->font.fa.pointsize * 72 / 25.4; + d *= WidthMMOfScreen(Tk_Screen(tkwin)); + d /= WidthOfScreen(Tk_Screen(tkwin)); + d += 0.5; + fontPtr->font.fa.pointsize = (int) d; + } + + fontPtr->font.fm.ascent = fontStructPtr->ascent; + fontPtr->font.fm.descent = fontStructPtr->descent; + fontPtr->font.fm.maxWidth = fontStructPtr->max_bounds.width; + fontPtr->font.fm.fixed = 1; + fontPtr->display = Tk_Display(tkwin); + fontPtr->fontStructPtr = fontStructPtr; + + /* + * Classify the characters. + */ + + firstChar = fontStructPtr->min_char_or_byte2; + lastChar = fontStructPtr->max_char_or_byte2; + for (i = 0; i < 256; i++) { + if ((i == 0177) || (i < firstChar) || (i > lastChar)) { + fontPtr->types[i] = REPLACE; + } else { + fontPtr->types[i] = NORMAL; + } + } + + /* + * Compute the widths for all the normal characters. Any other + * characters are given an initial width of 0. Also, this determines + * if this is a fixed or variable width font, by comparing the widths + * of all the normal characters. + */ + + width = 0; + for (i = 0; i < 256; i++) { + if (fontPtr->types[i] != NORMAL) { + n = 0; + } else if (fontStructPtr->per_char == NULL) { + n = fontStructPtr->max_bounds.width; + } else { + n = fontStructPtr->per_char[i - firstChar].width; + } + fontPtr->widths[i] = n; + if (n != 0) { + if (width == 0) { + width = n; + } else if (width != n) { + fontPtr->font.fm.fixed = 0; + } + } + } + + /* + * Compute the widths of the characters that should be replaced with + * control character expansions. If the appropriate chars are not + * available in this font, then control character expansions will not + * be used; control chars will be invisible & zero-width. + */ + + replaceOK = 1; + for (p = hexChars; *p != '\0'; p++) { + if ((UCHAR(*p) < firstChar) || (UCHAR(*p) > lastChar)) { + replaceOK = 0; + break; + } + } + for (i = 0; i < 256; i++) { + if (fontPtr->types[i] == REPLACE) { + if (replaceOK) { + n = GetControlCharSubst(i, buf); + for ( ; --n >= 0; ) { + fontPtr->widths[i] += fontPtr->widths[UCHAR(buf[n])]; + } + } else { + fontPtr->types[i] = SKIP; + } + } + } + + if (XGetFontProperty(fontStructPtr, XA_UNDERLINE_POSITION, &value)) { + fontPtr->underlinePos = value; + } else { + /* + * If the XA_UNDERLINE_POSITION property does not exist, the X + * manual recommends using the following value: + */ + + fontPtr->underlinePos = fontStructPtr->descent / 2; + } + fontPtr->barHeight = 0; + if (XGetFontProperty(fontStructPtr, XA_UNDERLINE_THICKNESS, &value)) { + /* + * Sometimes this is 0 even though it shouldn't be. + */ + fontPtr->barHeight = value; + } + if (fontPtr->barHeight == 0) { + /* + * If the XA_UNDERLINE_THICKNESS property does not exist, the X + * manual recommends using the width of the stem on a capital + * letter. I don't know of a way to get the stem width of a letter, + * so guess and use 1/3 the width of a capital I. + */ + + fontPtr->barHeight = fontPtr->widths['I'] / 3; + if (fontPtr->barHeight == 0) { + fontPtr->barHeight = 1; + } + } + if (fontPtr->underlinePos + fontPtr->barHeight > fontStructPtr->descent) { + /* + * If this set of cobbled together values would cause the bottom of + * the underline bar to stick below the descent of the font, jack + * the underline up a bit higher. + */ + + fontPtr->barHeight = fontStructPtr->descent - fontPtr->underlinePos; + if (fontPtr->barHeight == 0) { + fontPtr->underlinePos--; + fontPtr->barHeight = 1; + } + } + + return fontPtr; +} + +/* + *--------------------------------------------------------------------------- + * + * GetControlCharSubst -- + * + * When displaying text in a widget, a backslashed escape sequence + * is substituted for control characters that occur in the text. + * Given a control character, fill in a buffer with the replacement + * string that should be displayed. + * + * Results: + * The return value is the length of the substitute string. buf is + * filled with the substitute string; it is not '\0' terminated. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +static int +GetControlCharSubst(c, buf) + int c; /* The control character to be replaced. */ + char buf[4]; /* Buffer that gets replacement string. It + * only needs to be 4 characters long. */ +{ + buf[0] = '\\'; + if ((c < sizeof(mapChars)) && (mapChars[c] != 0)) { + buf[1] = mapChars[c]; + return 2; + } else { + buf[1] = 'x'; + buf[2] = hexChars[(c >> 4) & 0xf]; + buf[3] = hexChars[c & 0xf]; + return 4; + } +} diff --git a/unix/tkUnixInit.c b/unix/tkUnixInit.c new file mode 100644 index 0000000..acfd8de --- /dev/null +++ b/unix/tkUnixInit.c @@ -0,0 +1,130 @@ +/* + * tkUnixInit.c -- + * + * This file contains Unix-specific interpreter initialization + * functions. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixInit.c 1.24 97/07/24 14:46:09 + */ + +#include "tkInt.h" +#include "tkUnixInt.h" + +/* + * The Init script (common to Windows and Unix platforms) is + * defined in tkInitScript.h + */ +#include "tkInitScript.h" + + +/* + * Default directory in which to look for libraries: + */ + +static char defaultLibraryDir[200] = TK_LIBRARY; + + +/* + *---------------------------------------------------------------------- + * + * TkpInit -- + * + * Performs Unix-specific interpreter initialization related to the + * tk_library variable. + * + * Results: + * Returns a standard Tcl result. Leaves an error message or result + * in interp->result. + * + * Side effects: + * Sets "tk_library" Tcl variable, runs "tk.tcl" script. + * + *---------------------------------------------------------------------- + */ + +int +TkpInit(interp) + Tcl_Interp *interp; +{ + char *libDir; + + libDir = Tcl_GetVar(interp, "tk_library", TCL_GLOBAL_ONLY); + if (libDir == NULL) { + Tcl_SetVar(interp, "tk_library", defaultLibraryDir, TCL_GLOBAL_ONLY); + } + TkCreateXEventSource(); + return Tcl_Eval(interp, initScript); +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetAppName -- + * + * Retrieves the name of the current application from a platform + * specific location. For Unix, the application name is the tail + * of the path contained in the tcl variable argv0. + * + * Results: + * Returns the application name in the given Tcl_DString. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpGetAppName(interp, namePtr) + Tcl_Interp *interp; + Tcl_DString *namePtr; /* A previously initialized Tcl_DString. */ +{ + char *p, *name; + + name = Tcl_GetVar(interp, "argv0", TCL_GLOBAL_ONLY); + if ((name == NULL) || (*name == 0)) { + name = "tk"; + } else { + p = strrchr(name, '/'); + if (p != NULL) { + name = p+1; + } + } + Tcl_DStringAppend(namePtr, name, -1); +} + +/* + *---------------------------------------------------------------------- + * + * TkpDisplayWarning -- + * + * This routines is called from Tk_Main to display warning + * messages that occur during startup. + * + * Results: + * None. + * + * Side effects: + * Generates messages on stdout. + * + *---------------------------------------------------------------------- + */ + +void +TkpDisplayWarning(msg, title) + char *msg; /* Message to be displayed. */ + char *title; /* Title of warning. */ +{ + Tcl_Channel errChannel = Tcl_GetStdChannel(TCL_STDERR); + if (errChannel) { + Tcl_Write(errChannel, title, -1); + Tcl_Write(errChannel, ": ", 2); + Tcl_Write(errChannel, msg, -1); + Tcl_Write(errChannel, "\n", 1); + } +} diff --git a/unix/tkUnixInt.h b/unix/tkUnixInt.h new file mode 100644 index 0000000..41bbb66 --- /dev/null +++ b/unix/tkUnixInt.h @@ -0,0 +1,32 @@ +/* + * tkUnixInt.h -- + * + * This file contains declarations that are shared among the + * UNIX-specific parts of Tk but aren't used by the rest of + * Tk. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixInt.h 1.9 97/05/08 11:20:12 + */ + +#ifndef _TKUNIXINT +#define _TKUNIXINT + +/* + * Prototypes for procedures that are referenced in files other + * than the ones they're defined in. + */ + +EXTERN void TkCreateXEventSource _ANSI_ARGS_((void)); +EXTERN TkWindow * TkpGetContainer _ANSI_ARGS_((TkWindow *embeddedPtr)); +EXTERN TkWindow * TkpGetWrapperWindow _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN Window TkUnixContainerId _ANSI_ARGS_((TkWindow *winPtr)); +EXTERN int TkUnixDoOneXEvent _ANSI_ARGS_((Tcl_Time *timePtr)); +EXTERN void TkUnixSetMenubar _ANSI_ARGS_((Tk_Window tkwin, + Tk_Window menubar)); + +#endif /* _TKUNIXINT */ diff --git a/unix/tkUnixMenu.c b/unix/tkUnixMenu.c new file mode 100644 index 0000000..3179a31 --- /dev/null +++ b/unix/tkUnixMenu.c @@ -0,0 +1,1603 @@ +/* + * tkUnixMenu.c -- + * + * This module implements the UNIX platform-specific features of menus. + * + * Copyright (c) 1996-1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixMenu.c 1.76 97/11/05 09:08:22 + */ + +#include "tkPort.h" +#include "default.h" +#include "tkInt.h" +#include "tkUnixInt.h" +#include "tkMenu.h" + +/* + * Constants used for menu drawing. + */ + +#define MENU_MARGIN_WIDTH 2 +#define MENU_DIVIDER_HEIGHT 2 + +/* + * Platform specific flags for Unix. + */ + +#define ENTRY_HELP_MENU ENTRY_PLATFORM_FLAG1 + +/* + * Procedures used internally. + */ + +static void SetHelpMenu _ANSI_ARGS_((TkMenu *menuPtr)); +static void DrawMenuEntryAccelerator _ANSI_ARGS_(( + 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 _ANSI_ARGS_(( + TkMenu *menuPtr, TkMenuEntry *mePtr, + Drawable d, Tk_3DBorder activeBorder, + Tk_3DBorder bgBorder, int x, int y, + int width, int heigth)); +static void DrawMenuEntryIndicator _ANSI_ARGS_(( + 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 _ANSI_ARGS_(( + 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 _ANSI_ARGS_((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 _ANSI_ARGS_((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 DrawMenuUnderline _ANSI_ARGS_((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 GetMenuAccelGeometry _ANSI_ARGS_((TkMenu *menuPtr, + TkMenuEntry *mePtr, Tk_Font tkfont, + CONST Tk_FontMetrics *fmPtr, int *widthPtr, + int *heightPtr)); +static void GetMenuLabelGeometry _ANSI_ARGS_((TkMenuEntry *mePtr, + Tk_Font tkfont, CONST Tk_FontMetrics *fmPtr, + int *widthPtr, int *heightPtr)); +static void GetMenuIndicatorGeometry _ANSI_ARGS_(( + TkMenu *menuPtr, TkMenuEntry *mePtr, + Tk_Font tkfont, CONST Tk_FontMetrics *fmPtr, + int *widthPtr, int *heightPtr)); +static void GetMenuSeparatorGeometry _ANSI_ARGS_(( + TkMenu *menuPtr, TkMenuEntry *mePtr, + Tk_Font tkfont, CONST Tk_FontMetrics *fmPtr, + int *widthPtr, int *heightPtr)); +static void GetTearoffEntryGeometry _ANSI_ARGS_((TkMenu *menuPtr, + TkMenuEntry *mePtr, Tk_Font tkfont, + CONST Tk_FontMetrics *fmPtr, int *widthPtr, + int *heightPtr)); + + +/* + *---------------------------------------------------------------------- + * + * TkpNewMenu -- + * + * Gets the platform-specific piece of the menu. Invoked during idle + * after the generic part of the menu has been created. + * + * Results: + * Standard TCL error. + * + * Side effects: + * Allocates any platform specific allocations and places them + * in the platformData field of the menuPtr. + * + *---------------------------------------------------------------------- + */ + +int +TkpNewMenu(menuPtr) + TkMenu *menuPtr; +{ + SetHelpMenu(menuPtr); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyMenu -- + * + * Destroys platform-specific menu structures. Called when the + * generic menu structure is destroyed for the menu. + * + * Results: + * None. + * + * Side effects: + * All platform-specific allocations are freed up. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyMenu(menuPtr) + TkMenu *menuPtr; +{ + /* + * Nothing to do. + */ +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyMenuEntry -- + * + * Cleans up platform-specific menu entry items. Called when entry + * is destroyed in the generic code. + * + * Results: + * None. + * + * Side effects: + * All platform specific allocations are freed up. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyMenuEntry(mEntryPtr) + TkMenuEntry *mEntryPtr; +{ + /* + * Nothing to do. + */ +} + +/* + *---------------------------------------------------------------------- + * + * TkpConfigureMenuEntry -- + * + * Processes configuration options for menu entries. Called when + * the generic options are processed for the menu. + * + * Results: + * Returns standard TCL result. If TCL_ERROR is returned, then + * interp->result contains an error message. + * + * Side effects: + * Configuration information get set for mePtr; old resources + * get freed, if any need it. + * + *---------------------------------------------------------------------- + */ + +int +TkpConfigureMenuEntry(mePtr) + register TkMenuEntry *mePtr; /* Information about menu entry; may + * or may not already have values for + * some fields. */ +{ + /* + * If this is a cascade menu, and the child menu exists, check to + * see if the child menu is a help menu. + */ + + if ((mePtr->type == CASCADE_ENTRY) && (mePtr->name != NULL)) { + TkMenuReferences *menuRefPtr; + + menuRefPtr = TkFindMenuReferences(mePtr->menuPtr->interp, + mePtr->name); + if ((menuRefPtr != NULL) && (menuRefPtr->menuPtr != NULL)) { + SetHelpMenu(menuRefPtr->menuPtr); + } + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpMenuNewEntry -- + * + * Called when a new entry is created in a menu. Fills in platform + * specific data for the entry. The platformEntryData field + * is used to store the indicator diameter for radio button + * and check box entries. + * + * Results: + * Standard TCL error. + * + * Side effects: + * None on Unix. + * + *---------------------------------------------------------------------- + */ + +int +TkpMenuNewEntry(mePtr) + TkMenuEntry *mePtr; +{ + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpSetWindowMenuBar -- + * + * Sets up the menu as a menubar in the given window. + * + * Results: + * None. + * + * Side effects: + * Recomputes geometry of given window. + * + *---------------------------------------------------------------------- + */ + +void +TkpSetWindowMenuBar(tkwin, menuPtr) + Tk_Window tkwin; /* The window we are setting */ + TkMenu *menuPtr; /* The menu we are setting */ +{ + if (menuPtr == NULL) { + TkUnixSetMenubar(tkwin, NULL); + } else { + TkUnixSetMenubar(tkwin, menuPtr->tkwin); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpSetMainMenuBar -- + * + * Called when a toplevel widget is brought to front. On the + * Macintosh, sets up the menubar that goes accross the top + * of the main monitor. On other platforms, nothing is necessary. + * + * Results: + * None. + * + * Side effects: + * Recompute geometry of given window. + * + *---------------------------------------------------------------------- + */ + +void +TkpSetMainMenubar(interp, tkwin, menuName) + Tcl_Interp *interp; + Tk_Window tkwin; + char *menuName; +{ + /* + * Nothing to do. + */ +} + +/* + *---------------------------------------------------------------------- + * + * GetMenuIndicatorGeometry -- + * + * Fills out the geometry of the indicator in a menu item. Note + * that the mePtr->height field must have already been filled in + * by GetMenuLabelGeometry since this height depends on the label + * height. + * + * Results: + * widthPtr and heightPtr point to the new geometry values. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +GetMenuIndicatorGeometry(menuPtr, mePtr, tkfont, fmPtr, widthPtr, heightPtr) + TkMenu *menuPtr; /* The menu we are drawing. */ + TkMenuEntry *mePtr; /* The entry we are interested in. */ + Tk_Font tkfont; /* The precalculated font */ + CONST Tk_FontMetrics *fmPtr; /* The precalculated metrics */ + int *widthPtr; /* The resulting width */ + int *heightPtr; /* The resulting height */ +{ + if (!mePtr->hideMargin && mePtr->indicatorOn && + ((mePtr->type == CHECK_BUTTON_ENTRY) + || (mePtr->type == RADIO_BUTTON_ENTRY))) { + if ((mePtr->image != NULL) || (mePtr->bitmap != None)) { + *widthPtr = (14 * mePtr->height) / 10; + *heightPtr = mePtr->height; + if (mePtr->type == CHECK_BUTTON_ENTRY) { + mePtr->platformEntryData = + (TkMenuPlatformEntryData) ((65 * mePtr->height) / 100); + } else { + mePtr->platformEntryData = + (TkMenuPlatformEntryData) ((75 * mePtr->height) / 100); + } + } else { + *widthPtr = *heightPtr = mePtr->height; + if (mePtr->type == CHECK_BUTTON_ENTRY) { + mePtr->platformEntryData = (TkMenuPlatformEntryData) + ((80 * mePtr->height) / 100); + } else { + mePtr->platformEntryData = (TkMenuPlatformEntryData) + mePtr->height; + } + } + } else { + *heightPtr = 0; + *widthPtr = menuPtr->borderWidth; + } +} + + +/* + *---------------------------------------------------------------------- + * + * GetMenuAccelGeometry -- + * + * Get the geometry of the accelerator area of a menu item. + * + * Results: + * heightPtr and widthPtr are set. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +GetMenuAccelGeometry(menuPtr, mePtr, tkfont, fmPtr, widthPtr, heightPtr) + TkMenu *menuPtr; /* The menu was are drawing */ + TkMenuEntry *mePtr; /* The entry we are getting the geometry for */ + Tk_Font tkfont; /* The precalculated font */ + CONST Tk_FontMetrics *fmPtr;/* The precalculated font metrics */ + int *widthPtr; /* The width of the acclerator area */ + int *heightPtr; /* The height of the accelerator area */ +{ + *heightPtr = fmPtr->linespace; + if (mePtr->type == CASCADE_ENTRY) { + *widthPtr = 2 * CASCADE_ARROW_WIDTH; + } else if ((menuPtr->menuType != MENUBAR) && (mePtr->accel != NULL)) { + *widthPtr = Tk_TextWidth(tkfont, mePtr->accel, mePtr->accelLength); + } else { + *widthPtr = 0; + } +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuEntryBackground -- + * + * This procedure draws the background part of a menu. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static void +DrawMenuEntryBackground(menuPtr, mePtr, d, activeBorder, bgBorder, x, y, + width, height) + TkMenu *menuPtr; /* The menu we are drawing */ + TkMenuEntry *mePtr; /* The entry we are drawing. */ + Drawable d; /* The drawable we are drawing into */ + Tk_3DBorder activeBorder; /* The border for an active item */ + Tk_3DBorder bgBorder; /* The background border */ + int x; /* Left coordinate of entry rect */ + int y; /* Right coordinate of entry rect */ + int width; /* Width of entry rect */ + int height; /* Height of entry rect */ +{ + if (mePtr->state == tkActiveUid) { + int relief; + bgBorder = activeBorder; + + if ((menuPtr->menuType == MENUBAR) + && ((menuPtr->postedCascade == NULL) + || (menuPtr->postedCascade != mePtr))) { + relief = TK_RELIEF_FLAT; + } else { + relief = TK_RELIEF_RAISED; + } + + Tk_Fill3DRectangle(menuPtr->tkwin, d, bgBorder, x, y, width, height, + menuPtr->activeBorderWidth, relief); + } else { + Tk_Fill3DRectangle(menuPtr->tkwin, d, bgBorder, x, y, width, height, + 0, TK_RELIEF_FLAT); + } +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuEntryAccelerator -- + * + * This procedure draws the background part of a menu. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static void +DrawMenuEntryAccelerator(menuPtr, mePtr, d, gc, tkfont, fmPtr, activeBorder, + x, y, width, height, drawArrow) + 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 precalculated gc to draw with */ + Tk_Font tkfont; /* The precalculated font */ + CONST Tk_FontMetrics *fmPtr; /* The precalculated metrics */ + Tk_3DBorder activeBorder; /* The border for an active item */ + int x; /* Left coordinate of entry rect */ + int y; /* Top coordinate of entry rect */ + int width; /* Width of entry */ + int height; /* Height of entry */ + int drawArrow; /* Whether or not to draw arrow. */ +{ + XPoint points[3]; + + /* + * Draw accelerator or cascade arrow. + */ + + if (menuPtr->menuType == MENUBAR) { + return; + } + + if ((mePtr->type == CASCADE_ENTRY) && drawArrow) { + points[0].x = x + width - menuPtr->borderWidth + - menuPtr->activeBorderWidth - CASCADE_ARROW_WIDTH; + points[0].y = y + (height - CASCADE_ARROW_HEIGHT)/2; + points[1].x = points[0].x; + points[1].y = points[0].y + CASCADE_ARROW_HEIGHT; + points[2].x = points[0].x + CASCADE_ARROW_WIDTH; + points[2].y = points[0].y + CASCADE_ARROW_HEIGHT/2; + Tk_Fill3DPolygon(menuPtr->tkwin, d, activeBorder, points, 3, + DECORATION_BORDER_WIDTH, + (menuPtr->postedCascade == mePtr) + ? TK_RELIEF_SUNKEN : TK_RELIEF_RAISED); + } else if (mePtr->accel != NULL) { + int left = x + mePtr->labelWidth + menuPtr->activeBorderWidth + + mePtr->indicatorSpace; + if (menuPtr->menuType == MENUBAR) { + left += 5; + } + Tk_DrawChars(menuPtr->display, d, gc, tkfont, mePtr->accel, + mePtr->accelLength, left, + (y + (height + fmPtr->ascent - fmPtr->descent) / 2)); + } +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuEntryIndicator -- + * + * This procedure draws the background part of a menu. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static void +DrawMenuEntryIndicator(menuPtr, mePtr, d, gc, indicatorGC, tkfont, fmPtr, + x, y, width, height) + TkMenu *menuPtr; /* The menu we are drawing */ + TkMenuEntry *mePtr; /* The entry we are drawing */ + Drawable d; /* The drawable to draw into */ + GC gc; /* The gc to draw with */ + GC indicatorGC; /* The gc that indicators draw with */ + Tk_Font tkfont; /* The font to draw with */ + CONST Tk_FontMetrics *fmPtr; /* The font metrics of the font */ + int x; /* The left of the entry rect */ + int y; /* The top of the entry rect */ + int width; /* Width of menu entry */ + int height; /* Height of menu entry */ +{ + + /* + * Draw check-button indicator. + */ + + if ((mePtr->type == CHECK_BUTTON_ENTRY) + && mePtr->indicatorOn) { + int dim, top, left; + + dim = (int) mePtr->platformEntryData; + left = x + menuPtr->activeBorderWidth + + (mePtr->indicatorSpace - dim)/2; + if (menuPtr->menuType == MENUBAR) { + left += 5; + } + top = y + (height - dim)/2; + Tk_Fill3DRectangle(menuPtr->tkwin, d, menuPtr->border, left, top, dim, + dim, DECORATION_BORDER_WIDTH, TK_RELIEF_SUNKEN); + left += DECORATION_BORDER_WIDTH; + top += DECORATION_BORDER_WIDTH; + dim -= 2*DECORATION_BORDER_WIDTH; + if ((dim > 0) && (mePtr->entryFlags + & ENTRY_SELECTED)) { + XFillRectangle(menuPtr->display, d, indicatorGC, left, top, + (unsigned int) dim, (unsigned int) dim); + } + } + + /* + * Draw radio-button indicator. + */ + + if ((mePtr->type == RADIO_BUTTON_ENTRY) + && mePtr->indicatorOn) { + XPoint points[4]; + int radius; + + radius = ((int) mePtr->platformEntryData)/2; + points[0].x = x + (mePtr->indicatorSpace + - (int) mePtr->platformEntryData)/2; + points[0].y = y + (height)/2; + points[1].x = points[0].x + radius; + points[1].y = points[0].y + radius; + points[2].x = points[1].x + radius; + points[2].y = points[0].y; + points[3].x = points[1].x; + points[3].y = points[0].y - radius; + if (mePtr->entryFlags & ENTRY_SELECTED) { + XFillPolygon(menuPtr->display, d, indicatorGC, points, 4, Convex, + CoordModeOrigin); + } else { + Tk_Fill3DPolygon(menuPtr->tkwin, d, menuPtr->border, points, 4, + DECORATION_BORDER_WIDTH, TK_RELIEF_FLAT); + } + Tk_Draw3DPolygon(menuPtr->tkwin, d, menuPtr->border, points, 4, + DECORATION_BORDER_WIDTH, TK_RELIEF_SUNKEN); + } +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuSeparator -- + * + * This procedure draws a separator menu item. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static void +DrawMenuSeparator(menuPtr, mePtr, d, gc, tkfont, fmPtr, x, y, width, height) + TkMenu *menuPtr; /* The menu we are drawing */ + TkMenuEntry *mePtr; /* The entry we are drawing */ + Drawable d; /* The drawable we are using */ + GC gc; /* The gc to draw into */ + Tk_Font tkfont; /* The font to draw with */ + CONST Tk_FontMetrics *fmPtr; /* The font metrics from the font */ + int x; + int y; + int width; + int height; +{ + XPoint points[2]; + int margin; + + if (menuPtr->menuType == MENUBAR) { + return; + } + + margin = (fmPtr->ascent + fmPtr->descent)/2; + points[0].x = x; + points[0].y = y + height/2; + points[1].x = width - 1; + points[1].y = points[0].y; + Tk_Draw3DPolygon(menuPtr->tkwin, d, menuPtr->border, points, 2, 1, + TK_RELIEF_RAISED); +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static void +DrawMenuEntryLabel( + menuPtr, /* The menu we are drawing */ + mePtr, /* The entry we are drawing */ + d, /* What we are drawing into */ + gc, /* The gc we are drawing into */ + tkfont, /* The precalculated font */ + fmPtr, /* The precalculated font metrics */ + x, /* left edge */ + y, /* right edge */ + width, /* width of entry */ + height) /* height of entry */ + TkMenu *menuPtr; + TkMenuEntry *mePtr; + Drawable d; + GC gc; + Tk_Font tkfont; + CONST Tk_FontMetrics *fmPtr; + int x, y, width, height; +{ + int baseline; + int indicatorSpace = mePtr->indicatorSpace; + int leftEdge = x + indicatorSpace + menuPtr->activeBorderWidth; + int imageHeight, imageWidth; + + if (menuPtr->menuType == MENUBAR) { + leftEdge += 5; + } + + /* + * Draw label or bitmap or image for entry. + */ + + baseline = y + (height + fmPtr->ascent - fmPtr->descent) / 2; + if (mePtr->image != NULL) { + Tk_SizeOfImage(mePtr->image, &imageWidth, &imageHeight); + if ((mePtr->selectImage != NULL) + && (mePtr->entryFlags & ENTRY_SELECTED)) { + Tk_RedrawImage(mePtr->selectImage, 0, 0, + imageWidth, imageHeight, d, leftEdge, + (int) (y + (mePtr->height - imageHeight)/2)); + } else { + Tk_RedrawImage(mePtr->image, 0, 0, imageWidth, + imageHeight, d, leftEdge, + (int) (y + (mePtr->height - imageHeight)/2)); + } + } else if (mePtr->bitmap != None) { + int width, height; + + Tk_SizeOfBitmap(menuPtr->display, + mePtr->bitmap, &width, &height); + XCopyPlane(menuPtr->display, + mePtr->bitmap, d, + gc, 0, 0, (unsigned) width, (unsigned) height, leftEdge, + (int) (y + (mePtr->height - height)/2), 1); + } else { + if (mePtr->labelLength > 0) { + Tk_DrawChars(menuPtr->display, d, gc, + tkfont, mePtr->label, mePtr->labelLength, + leftEdge, baseline); + DrawMenuUnderline(menuPtr, mePtr, d, gc, tkfont, fmPtr, x, y, + width, height); + } + } + + if (mePtr->state == tkDisabledUid) { + if (menuPtr->disabledFg == NULL) { + XFillRectangle(menuPtr->display, d, menuPtr->disabledGC, x, y, + (unsigned) width, (unsigned) height); + } else if ((mePtr->image != NULL) + && (menuPtr->disabledImageGC != None)) { + XFillRectangle(menuPtr->display, d, menuPtr->disabledImageGC, + leftEdge, + (int) (y + (mePtr->height - imageHeight)/2), + (unsigned) imageWidth, (unsigned) imageHeight); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuUnderline -- + * + * On appropriate platforms, draw the underline character for the + * menu. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static void +DrawMenuUnderline(menuPtr, mePtr, d, gc, tkfont, fmPtr, x, y, width, height) + TkMenu *menuPtr; /* The menu to draw into */ + TkMenuEntry *mePtr; /* The entry we are drawing */ + Drawable d; /* What we are drawing into */ + GC gc; /* The gc to draw into */ + Tk_Font tkfont; /* The precalculated font */ + CONST Tk_FontMetrics *fmPtr; /* The precalculated font metrics */ + int x; + int y; + int width; + int height; +{ + int indicatorSpace = mePtr->indicatorSpace; + if (mePtr->underline >= 0) { + int leftEdge = x + indicatorSpace + menuPtr->activeBorderWidth; + if (menuPtr->menuType == MENUBAR) { + leftEdge += 5; + } + + Tk_UnderlineChars(menuPtr->display, d, gc, tkfont, mePtr->label, + leftEdge, y + (height + fmPtr->ascent - fmPtr->descent) / 2, + mePtr->underline, mePtr->underline + 1); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpPostMenu -- + * + * Posts a menu on the screen + * + * Results: + * None. + * + * Side effects: + * The menu is posted and handled. + * + *---------------------------------------------------------------------- + */ + +int +TkpPostMenu(interp, menuPtr, x, y) + Tcl_Interp *interp; + TkMenu *menuPtr; + int x; + int y; +{ + return TkPostTearoffMenu(interp, menuPtr, x, y); +} + +/* + *---------------------------------------------------------------------- + * + * GetMenuSeparatorGeometry -- + * + * Gets the width and height of the indicator area of a menu. + * + * Results: + * widthPtr and heightPtr are set. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +GetMenuSeparatorGeometry(menuPtr, mePtr, tkfont, fmPtr, widthPtr, + heightPtr) + 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 precalcualted font metrics */ + int *widthPtr; /* The resulting width */ + int *heightPtr; /* The resulting height */ +{ + *widthPtr = 0; + *heightPtr = fmPtr->linespace; +} + +/* + *---------------------------------------------------------------------- + * + * GetTearoffEntryGeometry -- + * + * Gets the width and height of the indicator area of a menu. + * + * Results: + * widthPtr and heightPtr are set. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +GetTearoffEntryGeometry(menuPtr, mePtr, tkfont, fmPtr, widthPtr, heightPtr) + 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 */ +{ + if (menuPtr->menuType != MASTER_MENU) { + *heightPtr = 0; + *widthPtr = 0; + } else { + *heightPtr = fmPtr->linespace; + *widthPtr = Tk_TextWidth(tkfont, "W", -1); + } +} + +/* + *-------------------------------------------------------------- + * + * 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(menuPtr) + TkMenu *menuPtr; /* Structure describing menu. */ +{ + Tk_Font tkfont; + Tk_FontMetrics menuMetrics, entryMetrics, *fmPtr; + int width, height; + int i, j; + int x, y, currentRowHeight, currentRowWidth, maxWidth; + int maxWindowWidth; + int lastRowBreak; + int helpMenuIndex = -1; + TkMenuEntry *mePtr; + int lastEntry; + + if (menuPtr->tkwin == NULL) { + return; + } + + maxWidth = 0; + if (menuPtr->numEntries == 0) { + height = 0; + } else { + maxWindowWidth = Tk_Width(menuPtr->tkwin); + if (maxWindowWidth == 1) { + maxWindowWidth = 0x7ffffff; + } + currentRowHeight = 0; + x = y = menuPtr->borderWidth; + lastRowBreak = 0; + currentRowWidth = 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 measureing and drawing + * routines. We will measure the font metrics of the menu once, + * and if an entry has a font set, we will measure it as we come + * to it, and then we decide which set to give the geometry routines. + */ + + Tk_GetFontMetrics(menuPtr->tkfont, &menuMetrics); + + for (i = 0; i < menuPtr->numEntries; i++) { + mePtr = menuPtr->entries[i]; + mePtr->entryFlags &= ~ENTRY_LAST_COLUMN; + tkfont = mePtr->tkfont; + if (tkfont == NULL) { + tkfont = menuPtr->tkfont; + fmPtr = &menuMetrics; + } else { + Tk_GetFontMetrics(tkfont, &entryMetrics); + fmPtr = &entryMetrics; + } + + /* + * For every entry, we need to check to see whether or not we + * wrap. If we do wrap, then we have to adjust all of the previous + * entries' height and y position, because when we see them + * the first time, we don't know how big its neighbor might + * be. + */ + + if ((mePtr->type == SEPARATOR_ENTRY) + || (mePtr->type == TEAROFF_ENTRY)) { + mePtr->height = mePtr->width = 0; + } else { + + GetMenuLabelGeometry(mePtr, tkfont, fmPtr, + &width, &height); + mePtr->height = height + 2 * menuPtr->activeBorderWidth + 10; + mePtr->width = width; + + GetMenuIndicatorGeometry(menuPtr, mePtr, + tkfont, fmPtr, &width, &height); + mePtr->indicatorSpace = width; + if (width > 0) { + mePtr->width += width; + } + mePtr->width += 2 * menuPtr->activeBorderWidth + 10; + } + if (mePtr->entryFlags & ENTRY_HELP_MENU) { + helpMenuIndex = i; + } else if (x + mePtr->width + menuPtr->borderWidth + > maxWindowWidth) { + + if (i == lastRowBreak) { + mePtr->y = y; + mePtr->x = x; + lastRowBreak++; + y += mePtr->height; + currentRowHeight = 0; + } else { + x = menuPtr->borderWidth; + for (j = lastRowBreak; j < i; j++) { + menuPtr->entries[j]->y = y + currentRowHeight + - menuPtr->entries[j]->height; + menuPtr->entries[j]->x = x; + x += menuPtr->entries[j]->width; + } + lastRowBreak = i; + y += currentRowHeight; + currentRowHeight = mePtr->height; + } + if (x > maxWidth) { + maxWidth = x; + } + x = menuPtr->borderWidth; + } else { + x += mePtr->width; + if (mePtr->height > currentRowHeight) { + currentRowHeight = mePtr->height; + } + } + } + + lastEntry = menuPtr->numEntries - 1; + if (helpMenuIndex == lastEntry) { + lastEntry--; + } + if ((lastEntry >= 0) && (x + menuPtr->entries[lastEntry]->width + + menuPtr->borderWidth > maxWidth)) { + maxWidth = x + menuPtr->entries[lastEntry]->width + + menuPtr->borderWidth; + } + x = menuPtr->borderWidth; + for (j = lastRowBreak; j < menuPtr->numEntries; j++) { + if (j == helpMenuIndex) { + continue; + } + menuPtr->entries[j]->y = y + currentRowHeight + - menuPtr->entries[j]->height; + menuPtr->entries[j]->x = x; + x += menuPtr->entries[j]->width; + } + + + if (helpMenuIndex != -1) { + mePtr = menuPtr->entries[helpMenuIndex]; + if (x + mePtr->width + menuPtr->borderWidth > maxWindowWidth) { + y += currentRowHeight; + currentRowHeight = mePtr->height; + x = menuPtr->borderWidth; + } else if (mePtr->height > currentRowHeight) { + currentRowHeight = mePtr->height; + } + mePtr->x = maxWindowWidth - menuPtr->borderWidth - mePtr->width; + mePtr->y = y + currentRowHeight - mePtr->height; + } + height = y + currentRowHeight + menuPtr->borderWidth; + } + width = Tk_Width(menuPtr->tkwin); + + /* + * 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 (width <= 0) { + width = 1; + } + if (height <= 0) { + height = 1; + } + menuPtr->totalWidth = maxWidth; + menuPtr->totalHeight = height; +} + +/* + *---------------------------------------------------------------------- + * + * DrawTearoffEntry -- + * + * This procedure draws the background part of a menu. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static void +DrawTearoffEntry(menuPtr, mePtr, d, gc, tkfont, fmPtr, x, y, width, height) + 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; + int y; + int width; + int height; +{ + XPoint points[2]; + int margin, segmentWidth, maxX; + + if (menuPtr->menuType != MASTER_MENU) { + return; + } + + margin = (fmPtr->ascent + fmPtr->descent)/2; + points[0].x = x; + points[0].y = y + height/2; + points[1].y = points[0].y; + segmentWidth = 6; + maxX = width - 1; + + 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, menuPtr->border, points, 2, 1, + TK_RELIEF_RAISED); + points[0].x += 2*segmentWidth; + } +} + +/* + *-------------------------------------------------------------- + * + * 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(interp, bindingTable) + Tcl_Interp *interp; /* The interpreter to set. */ + Tk_BindingTable bindingTable; /* The table to add to. */ +{ + /* + * Nothing to do. + */ +} + +/* + *---------------------------------------------------------------------- + * + * SetHelpMenu -- + * + * Given a menu, check to see whether or not it is a help menu + * cascade in a menubar. If it is, the entry that points to + * this menu will be marked. + * + * RESULTS: + * None. + * + * Side effects: + * Will set the ENTRY_HELP_MENU flag appropriately. + * + *---------------------------------------------------------------------- + */ + +static void +SetHelpMenu(menuPtr) + TkMenu *menuPtr; /* The menu we are checking */ +{ + TkMenuEntry *cascadeEntryPtr; + + for (cascadeEntryPtr = menuPtr->menuRefPtr->parentEntryPtr; + cascadeEntryPtr != NULL; + cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr) { + if ((cascadeEntryPtr->menuPtr->menuType == MENUBAR) + && (cascadeEntryPtr->menuPtr->masterMenuPtr->tkwin != NULL) + && (menuPtr->masterMenuPtr->tkwin != NULL)) { + TkMenu *masterMenuPtr = cascadeEntryPtr->menuPtr->masterMenuPtr; + char *helpMenuName = ckalloc(strlen(Tk_PathName( + masterMenuPtr->tkwin)) + strlen(".help") + 1); + + strcpy(helpMenuName, Tk_PathName(masterMenuPtr->tkwin)); + strcat(helpMenuName, ".help"); + if (strcmp(helpMenuName, + Tk_PathName(menuPtr->masterMenuPtr->tkwin)) == 0) { + cascadeEntryPtr->entryFlags |= ENTRY_HELP_MENU; + } else { + cascadeEntryPtr->entryFlags &= ~ENTRY_HELP_MENU; + } + ckfree(helpMenuName); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * 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(mePtr, d, tkfont, menuMetricsPtr, x, y, width, height, + strictMotif, drawArrow) + 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, indicatorGC; + TkMenu *menuPtr = mePtr->menuPtr; + Tk_3DBorder bgBorder, activeBorder; + CONST Tk_FontMetrics *fmPtr; + Tk_FontMetrics entryMetrics; + int padY = (menuPtr->menuType == MENUBAR) ? 3 : 0; + int adjustedY = y + padY; + int adjustedHeight = height - 2 * padY; + + /* + * Choose the gc for drawing the foreground part of the entry. + */ + + if ((mePtr->state == tkActiveUid) + && !strictMotif) { + gc = mePtr->activeGC; + if (gc == NULL) { + gc = menuPtr->activeGC; + } + } else { + TkMenuEntry *cascadeEntryPtr; + int parentDisabled = 0; + + for (cascadeEntryPtr = menuPtr->menuRefPtr->parentEntryPtr; + cascadeEntryPtr != NULL; + cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr) { + if (strcmp(cascadeEntryPtr->name, + Tk_PathName(menuPtr->tkwin)) == 0) { + if (cascadeEntryPtr->state == tkDisabledUid) { + parentDisabled = 1; + } + break; + } + } + + if (((parentDisabled || (mePtr->state == tkDisabledUid))) + && (menuPtr->disabledFg != 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 = mePtr->border; + if (bgBorder == NULL) { + bgBorder = menuPtr->border; + } + if (strictMotif) { + activeBorder = bgBorder; + } else { + activeBorder = mePtr->activeBorder; + if (activeBorder == NULL) { + activeBorder = menuPtr->activeBorder; + } + } + + if (mePtr->tkfont == NULL) { + fmPtr = menuMetricsPtr; + } else { + tkfont = mePtr->tkfont; + 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); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static void +GetMenuLabelGeometry(mePtr, tkfont, fmPtr, widthPtr, heightPtr) + 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; + + if (mePtr->image != NULL) { + Tk_SizeOfImage(mePtr->image, widthPtr, heightPtr); + } else if (mePtr->bitmap != (Pixmap) NULL) { + Tk_SizeOfBitmap(menuPtr->display, mePtr->bitmap, widthPtr, heightPtr); + } else { + *heightPtr = fmPtr->linespace; + + if (mePtr->label != NULL) { + *widthPtr = Tk_TextWidth(tkfont, mePtr->label, mePtr->labelLength); + } else { + *widthPtr = 0; + } + } + *heightPtr += 1; +} + +/* + *-------------------------------------------------------------- + * + * 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( + menuPtr) /* Structure describing menu. */ + TkMenu *menuPtr; +{ + Tk_Font tkfont; + Tk_FontMetrics menuMetrics, entryMetrics, *fmPtr; + int x, y, height, width, indicatorSpace, labelWidth, accelWidth; + int windowWidth, windowHeight, accelSpace; + int i, j, lastColumnBreak = 0; + TkMenuEntry *mePtr; + + if (menuPtr->tkwin == NULL) { + return; + } + + x = y = menuPtr->borderWidth; + indicatorSpace = labelWidth = accelWidth = 0; + windowHeight = windowWidth = 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. + */ + + Tk_GetFontMetrics(menuPtr->tkfont, &menuMetrics); + accelSpace = Tk_TextWidth(menuPtr->tkfont, "M", 1); + + for (i = 0; i < menuPtr->numEntries; i++) { + mePtr = menuPtr->entries[i]; + tkfont = mePtr->tkfont; + if (tkfont == NULL) { + tkfont = menuPtr->tkfont; + fmPtr = &menuMetrics; + } else { + Tk_GetFontMetrics(tkfont, &entryMetrics); + fmPtr = &entryMetrics; + } + + if ((i > 0) && mePtr->columnBreak) { + if (accelWidth != 0) { + labelWidth += accelSpace; + } + for (j = lastColumnBreak; j < i; j++) { + menuPtr->entries[j]->indicatorSpace = indicatorSpace; + menuPtr->entries[j]->labelWidth = labelWidth; + menuPtr->entries[j]->width = indicatorSpace + labelWidth + + accelWidth + 2 * menuPtr->activeBorderWidth; + menuPtr->entries[j]->x = x; + menuPtr->entries[j]->entryFlags &= ~ENTRY_LAST_COLUMN; + } + x += indicatorSpace + labelWidth + accelWidth + + 2 * menuPtr->activeBorderWidth; + windowWidth = x; + indicatorSpace = labelWidth = accelWidth = 0; + lastColumnBreak = i; + y = menuPtr->borderWidth; + } + + if (mePtr->type == SEPARATOR_ENTRY) { + GetMenuSeparatorGeometry(menuPtr, mePtr, tkfont, + fmPtr, &width, &height); + mePtr->height = height; + } else if (mePtr->type == TEAROFF_ENTRY) { + GetTearoffEntryGeometry(menuPtr, mePtr, tkfont, + fmPtr, &width, &height); + mePtr->height = height; + labelWidth = width; + } 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, &width, + &height); + mePtr->height = height; + if (!mePtr->hideMargin) { + width += MENU_MARGIN_WIDTH; + } + if (width > labelWidth) { + labelWidth = width; + } + + GetMenuAccelGeometry(menuPtr, mePtr, tkfont, + fmPtr, &width, &height); + if (height > mePtr->height) { + mePtr->height = height; + } + if (!mePtr->hideMargin) { + width += MENU_MARGIN_WIDTH; + } + if (width > accelWidth) { + accelWidth = width; + } + + GetMenuIndicatorGeometry(menuPtr, mePtr, tkfont, + fmPtr, &width, &height); + if (height > mePtr->height) { + mePtr->height = height; + } + if (!mePtr->hideMargin) { + width += MENU_MARGIN_WIDTH; + } + if (width > indicatorSpace) { + indicatorSpace = width; + } + + mePtr->height += 2 * menuPtr->activeBorderWidth + + MENU_DIVIDER_HEIGHT; + } + mePtr->y = y; + y += mePtr->height; + if (y > windowHeight) { + windowHeight = y; + } + } + + if (accelWidth != 0) { + labelWidth += accelSpace; + } + for (j = lastColumnBreak; j < menuPtr->numEntries; j++) { + menuPtr->entries[j]->indicatorSpace = indicatorSpace; + menuPtr->entries[j]->labelWidth = labelWidth; + menuPtr->entries[j]->width = indicatorSpace + labelWidth + + accelWidth + 2 * menuPtr->activeBorderWidth; + menuPtr->entries[j]->x = x; + menuPtr->entries[j]->entryFlags |= ENTRY_LAST_COLUMN; + } + windowWidth = x + indicatorSpace + labelWidth + accelWidth + + 2 * menuPtr->activeBorderWidth + 2 * menuPtr->borderWidth; + + + windowHeight += menuPtr->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; +} + +/* + *---------------------------------------------------------------------- + * + * 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. Not applicable to UNIX. + * + * Results: + * None. + * + * Side effects: + * An idle handler is set up to do the reconfiguration. + * + *---------------------------------------------------------------------- + */ + +void +TkpMenuNotifyToplevelCreate(interp, menuName) + Tcl_Interp *interp; /* The interp the menu lives in. */ + char *menuName; /* The name of the menu to + * reconfigure. */ +{ + /* + * Nothing to do. + */ +} + +/* + *---------------------------------------------------------------------- + * + * TkpMenuInit -- + * + * Does platform-specific initialization of menus. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpMenuInit() +{ + /* + * Nothing to do. + */ +} diff --git a/unix/tkUnixMenubu.c b/unix/tkUnixMenubu.c new file mode 100644 index 0000000..b5f4fd5 --- /dev/null +++ b/unix/tkUnixMenubu.c @@ -0,0 +1,307 @@ +/* + * tkUnixMenubu.c -- + * + * This file implements the Unix specific portion of the + * menubutton widget. + * + * Copyright (c) 1996-1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixMenubu.c 1.9 97/05/23 16:25:01 + */ + +#include "tkMenubutton.h" + +/* + * The structure below defines menubutton class behavior by means of + * procedures that can be invoked from generic window code. + */ + +TkClassProcs tkpMenubuttonClass = { + NULL, /* createProc. */ + TkMenuButtonWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + +/* + *---------------------------------------------------------------------- + * + * TkpCreateMenuButton -- + * + * Allocate a new TkMenuButton structure. + * + * Results: + * Returns a newly allocated TkMenuButton structure. + * + * Side effects: + * Registers an event handler for the widget. + * + *---------------------------------------------------------------------- + */ + +TkMenuButton * +TkpCreateMenuButton(tkwin) + Tk_Window tkwin; +{ + return (TkMenuButton *)ckalloc(sizeof(TkMenuButton)); +} + +/* + *---------------------------------------------------------------------- + * + * TkpDisplayMenuButton -- + * + * This procedure is invoked to display a menubutton widget. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menubutton in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +void +TkpDisplayMenuButton(clientData) + ClientData clientData; /* Information about widget. */ +{ + register TkMenuButton *mbPtr = (TkMenuButton *) clientData; + GC gc; + Tk_3DBorder border; + Pixmap pixmap; + int x = 0; /* Initialization needed only to stop + * compiler warning. */ + int y; + register Tk_Window tkwin = mbPtr->tkwin; + int width, height; + + mbPtr->flags &= ~REDRAW_PENDING; + if ((mbPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + return; + } + + if ((mbPtr->state == tkDisabledUid) && (mbPtr->disabledFg != NULL)) { + gc = mbPtr->disabledGC; + border = mbPtr->normalBorder; + } else if ((mbPtr->state == tkActiveUid) && !Tk_StrictMotif(mbPtr->tkwin)) { + gc = mbPtr->activeTextGC; + border = mbPtr->activeBorder; + } else { + gc = mbPtr->normalTextGC; + border = mbPtr->normalBorder; + } + + /* + * In order to avoid screen flashes, this procedure redraws + * the menu button in a pixmap, then copies the pixmap to the + * screen in a single operation. This means that there's no + * point in time where the on-sreen image has been cleared. + */ + + pixmap = Tk_GetPixmap(mbPtr->display, Tk_WindowId(tkwin), + Tk_Width(tkwin), Tk_Height(tkwin), Tk_Depth(tkwin)); + Tk_Fill3DRectangle(tkwin, pixmap, border, 0, 0, Tk_Width(tkwin), + Tk_Height(tkwin), 0, TK_RELIEF_FLAT); + + /* + * Display image or bitmap or text for button. + */ + + if (mbPtr->image != None) { + Tk_SizeOfImage(mbPtr->image, &width, &height); + + imageOrBitmap: + TkComputeAnchor(mbPtr->anchor, tkwin, 0, 0, + width + mbPtr->indicatorWidth, height, &x, &y); + if (mbPtr->image != NULL) { + Tk_RedrawImage(mbPtr->image, 0, 0, width, height, pixmap, + x, y); + } else { + XCopyPlane(mbPtr->display, mbPtr->bitmap, pixmap, + gc, 0, 0, (unsigned) width, (unsigned) height, x, y, 1); + } + } else if (mbPtr->bitmap != None) { + Tk_SizeOfBitmap(mbPtr->display, mbPtr->bitmap, &width, &height); + goto imageOrBitmap; + } else { + TkComputeAnchor(mbPtr->anchor, tkwin, mbPtr->padX, mbPtr->padY, + mbPtr->textWidth + mbPtr->indicatorWidth, + mbPtr->textHeight, &x, &y); + Tk_DrawTextLayout(mbPtr->display, pixmap, gc, mbPtr->textLayout, x, y, + 0, -1); + Tk_UnderlineTextLayout(mbPtr->display, pixmap, gc, mbPtr->textLayout, + x, y, mbPtr->underline); + } + + /* + * If the menu button is disabled with a stipple rather than a special + * foreground color, generate the stippled effect. + */ + + if ((mbPtr->state == tkDisabledUid) + && ((mbPtr->disabledFg == NULL) || (mbPtr->image != NULL))) { + XFillRectangle(mbPtr->display, pixmap, mbPtr->disabledGC, + mbPtr->inset, mbPtr->inset, + (unsigned) (Tk_Width(tkwin) - 2*mbPtr->inset), + (unsigned) (Tk_Height(tkwin) - 2*mbPtr->inset)); + } + + /* + * Draw the cascade indicator for the menu button on the + * right side of the window, if desired. + */ + + if (mbPtr->indicatorOn) { + int borderWidth; + + borderWidth = (mbPtr->indicatorHeight+1)/3; + if (borderWidth < 1) { + borderWidth = 1; + } + /*y += mbPtr->textHeight / 2;*/ + Tk_Fill3DRectangle(tkwin, pixmap, border, + Tk_Width(tkwin) - mbPtr->inset - mbPtr->indicatorWidth + + mbPtr->indicatorHeight, + ((int) (Tk_Height(tkwin) - mbPtr->indicatorHeight))/2, + mbPtr->indicatorWidth - 2*mbPtr->indicatorHeight, + mbPtr->indicatorHeight, borderWidth, TK_RELIEF_RAISED); + } + + /* + * Draw the border and traversal highlight last. This way, if the + * menu button's contents overflow onto the border they'll be covered + * up by the border. + */ + + if (mbPtr->relief != TK_RELIEF_FLAT) { + Tk_Draw3DRectangle(tkwin, pixmap, border, + mbPtr->highlightWidth, mbPtr->highlightWidth, + Tk_Width(tkwin) - 2*mbPtr->highlightWidth, + Tk_Height(tkwin) - 2*mbPtr->highlightWidth, + mbPtr->borderWidth, mbPtr->relief); + } + if (mbPtr->highlightWidth != 0) { + GC gc; + + if (mbPtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(mbPtr->highlightColorPtr, pixmap); + } else { + gc = Tk_GCForColor(mbPtr->highlightBgColorPtr, pixmap); + } + Tk_DrawFocusHighlight(tkwin, gc, mbPtr->highlightWidth, pixmap); + } + + /* + * Copy the information from the off-screen pixmap onto the screen, + * then delete the pixmap. + */ + + XCopyArea(mbPtr->display, pixmap, Tk_WindowId(tkwin), + mbPtr->normalTextGC, 0, 0, (unsigned) Tk_Width(tkwin), + (unsigned) Tk_Height(tkwin), 0, 0); + Tk_FreePixmap(mbPtr->display, pixmap); +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyMenuButton -- + * + * Free data structures associated with the menubutton control. + * + * Results: + * None. + * + * Side effects: + * Restores the default control state. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyMenuButton(mbPtr) + TkMenuButton *mbPtr; +{ +} + +/* + *---------------------------------------------------------------------- + * + * TkpComputeMenuButtonGeometry -- + * + * After changes in a menu button's text or bitmap, this procedure + * recomputes the menu button's geometry and passes this information + * along to the geometry manager for the window. + * + * Results: + * None. + * + * Side effects: + * The menu button's window may change size. + * + *---------------------------------------------------------------------- + */ + +void +TkpComputeMenuButtonGeometry(mbPtr) + register TkMenuButton *mbPtr; /* Widget record for menu button. */ +{ + int width, height, mm, pixels; + + mbPtr->inset = mbPtr->highlightWidth + mbPtr->borderWidth; + if (mbPtr->image != None) { + Tk_SizeOfImage(mbPtr->image, &width, &height); + if (mbPtr->width > 0) { + width = mbPtr->width; + } + if (mbPtr->height > 0) { + height = mbPtr->height; + } + } else if (mbPtr->bitmap != None) { + Tk_SizeOfBitmap(mbPtr->display, mbPtr->bitmap, &width, &height); + if (mbPtr->width > 0) { + width = mbPtr->width; + } + if (mbPtr->height > 0) { + height = mbPtr->height; + } + } else { + Tk_FreeTextLayout(mbPtr->textLayout); + mbPtr->textLayout = Tk_ComputeTextLayout(mbPtr->tkfont, mbPtr->text, + -1, mbPtr->wrapLength, mbPtr->justify, 0, &mbPtr->textWidth, + &mbPtr->textHeight); + width = mbPtr->textWidth; + height = mbPtr->textHeight; + if (mbPtr->width > 0) { + width = mbPtr->width * Tk_TextWidth(mbPtr->tkfont, "0", 1); + } + if (mbPtr->height > 0) { + Tk_FontMetrics fm; + + Tk_GetFontMetrics(mbPtr->tkfont, &fm); + height = mbPtr->height * fm.linespace; + } + width += 2*mbPtr->padX; + height += 2*mbPtr->padY; + } + + if (mbPtr->indicatorOn) { + mm = WidthMMOfScreen(Tk_Screen(mbPtr->tkwin)); + pixels = WidthOfScreen(Tk_Screen(mbPtr->tkwin)); + mbPtr->indicatorHeight= (INDICATOR_HEIGHT * pixels)/(10*mm); + mbPtr->indicatorWidth = (INDICATOR_WIDTH * pixels)/(10*mm) + + 2*mbPtr->indicatorHeight; + width += mbPtr->indicatorWidth; + } else { + mbPtr->indicatorHeight = 0; + mbPtr->indicatorWidth = 0; + } + + Tk_GeometryRequest(mbPtr->tkwin, (int) (width + 2*mbPtr->inset), + (int) (height + 2*mbPtr->inset)); + Tk_SetInternalBorder(mbPtr->tkwin, mbPtr->inset); +} diff --git a/unix/tkUnixPort.h b/unix/tkUnixPort.h new file mode 100644 index 0000000..146e60d --- /dev/null +++ b/unix/tkUnixPort.h @@ -0,0 +1,235 @@ +/* + * tkUnixPort.h -- + * + * This file is included by all of the Tk C files. It contains + * information that may be configuration-dependent, such as + * #includes for system include files and a few other things. + * + * Copyright (c) 1991-1993 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixPort.h 1.38 97/05/17 16:48:19 + */ + +#ifndef _UNIXPORT +#define _UNIXPORT + +#define __UNIX__ 1 + +/* + * Macro to use instead of "void" for arguments that must have + * type "void *" in ANSI C; maps them to type "char *" in + * non-ANSI systems. This macro may be used in some of the include + * files below, which is why it is defined here. + */ + +#ifndef VOID +# ifdef __STDC__ +# define VOID void +# else +# define VOID char +# endif +#endif + +#include <stdio.h> +#include <ctype.h> +#include <fcntl.h> +#ifdef HAVE_LIMITS_H +# include <limits.h> +#else +# include "../compat/limits.h" +#endif +#include <math.h> +#include <pwd.h> +#ifdef NO_STDLIB_H +# include "../compat/stdlib.h" +#else +# include <stdlib.h> +#endif +#include <string.h> +#include <sys/types.h> +#include <sys/file.h> +#ifdef HAVE_SYS_SELECT_H +# include <sys/select.h> +#endif +#include <sys/stat.h> +#ifndef _TCL +# include <tcl.h> +#endif +#if TIME_WITH_SYS_TIME +# include <sys/time.h> +# include <time.h> +#else +# if HAVE_SYS_TIME_H +# include <sys/time.h> +# else +# include <time.h> +# endif +#endif +#ifdef HAVE_UNISTD_H +# include <unistd.h> +#else +# include "../compat/unistd.h" +#endif +#include <X11/Xlib.h> +#include <X11/cursorfont.h> +#include <X11/keysym.h> +#include <X11/Xatom.h> +#include <X11/Xproto.h> +#include <X11/Xresource.h> +#include <X11/Xutil.h> + +/* + * The following macro defines the type of the mask arguments to + * select: + */ + +#ifndef NO_FD_SET +# define SELECT_MASK fd_set +#else +# ifndef _AIX + typedef long fd_mask; +# endif +# if defined(_IBMR2) +# define SELECT_MASK void +# else +# define SELECT_MASK int +# endif +#endif + +/* + * The following macro defines the number of fd_masks in an fd_set: + */ + +#ifndef FD_SETSIZE +# ifdef OPEN_MAX +# define FD_SETSIZE OPEN_MAX +# else +# define FD_SETSIZE 256 +# endif +#endif +#if !defined(howmany) +# define howmany(x, y) (((x)+((y)-1))/(y)) +#endif +#ifndef NFDBITS +# define NFDBITS NBBY*sizeof(fd_mask) +#endif +#define MASK_SIZE howmany(FD_SETSIZE, NFDBITS) + +/* + * Not all systems declare the errno variable in errno.h. so this + * file does it explicitly. + */ + +extern int errno; + +/* + * Define "NBBY" (number of bits per byte) if it's not already defined. + */ + +#ifndef NBBY +# define NBBY 8 +#endif + +/* + * These macros are just wrappers for the equivalent X Region calls. + */ + +#define TkClipBox(rgn, rect) XClipBox((Region) rgn, rect) +#define TkCreateRegion() (TkRegion) XCreateRegion() +#define TkDestroyRegion(rgn) XDestroyRegion((Region) rgn) +#define TkIntersectRegion(a, b, r) XIntersectRegion((Region) a, \ + (Region) b, (Region) r) +#define TkRectInRegion(r, x, y, w, h) XRectInRegion((Region) r, x, y, w, h) +#define TkSetRegion(d, gc, rgn) XSetRegion(d, gc, (Region) rgn) +#define TkUnionRectWithRegion(rect, src, ret) XUnionRectWithRegion(rect, \ + (Region) src, (Region) ret) + +/* + * The TkPutImage macro strips off the color table information, which isn't + * needed for X. + */ + +#define TkPutImage(colors, ncolors, display, pixels, gc, image, destx, desty, srcx, srcy, width, height) \ + XPutImage(display, pixels, gc, image, destx, desty, srcx, \ + srcy, width, height); + +/* + * The following Tk functions are implemented as macros under Windows. + */ + +#define TkGetNativeProlog(interp) TkGetProlog(interp) + +/* + * Supply macros for seek offsets, if they're not already provided by + * an include file. + */ + +#ifndef SEEK_SET +# define SEEK_SET 0 +#endif + +#ifndef SEEK_CUR +# define SEEK_CUR 1 +#endif + +#ifndef SEEK_END +# define SEEK_END 2 +#endif + +/* + * Declarations for various library procedures that may not be declared + * in any other header file. + */ + +extern void panic _ANSI_ARGS_(TCL_VARARGS(char *, string)); + +/* + * These functions do nothing under Unix, so we just eliminate calls to them. + */ + +#define TkpDestroyButton(butPtr) {} +#define TkSelUpdateClipboard(a,b) {} +#define TkSetPixmapColormap(p,c) {} + +/* + * These calls implement native bitmaps which are not supported under + * UNIX. The macros eliminate the calls. + */ + +#define TkpDefineNativeBitmaps() +#define TkpCreateNativeBitmap(display, source) None +#define TkpGetNativeAppBitmap(display, name, w, h) None + +/* + * This macro stores a representation of the window handle in a string. + */ + +#define TkpPrintWindowId(buf,w) \ + sprintf((buf), "0x%x", (unsigned int) (w)) + +/* + * TkpScanWindowId is just an alias for Tcl_GetInt on Unix. + */ + +#define TkpScanWindowId(i,s,wp) \ + Tcl_GetInt((i),(s),(wp)) + +/* + * This macro indicates that entry and text widgets should display + * the selection highlight regardless of which window has the focus. + */ + +#define ALWAYS_SHOW_SELECTION + +/* + * The following declaration is used to get access to a private Tcl interface + * that is needed for portability reasons. + */ + +EXTERN void TclpGetTime _ANSI_ARGS_((Tcl_Time *time)); + +#endif /* _UNIXPORT */ diff --git a/unix/tkUnixScale.c b/unix/tkUnixScale.c new file mode 100644 index 0000000..05b2a19 --- /dev/null +++ b/unix/tkUnixScale.c @@ -0,0 +1,828 @@ +/* + * tkUnixScale.c -- + * + * This file implements the X specific portion of the scrollbar + * widget. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixScale.c 1.5 96/07/31 14:22:29 + */ + +#include "tkScale.h" +#include "tkInt.h" + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void DisplayHorizontalScale _ANSI_ARGS_((TkScale *scalePtr, + Drawable drawable, XRectangle *drawnAreaPtr)); +static void DisplayHorizontalValue _ANSI_ARGS_((TkScale *scalePtr, + Drawable drawable, double value, int top)); +static void DisplayVerticalScale _ANSI_ARGS_((TkScale *scalePtr, + Drawable drawable, XRectangle *drawnAreaPtr)); +static void DisplayVerticalValue _ANSI_ARGS_((TkScale *scalePtr, + Drawable drawable, double value, int rightEdge)); + +/* + *---------------------------------------------------------------------- + * + * TkpCreateScale -- + * + * Allocate a new TkScale structure. + * + * Results: + * Returns a newly allocated TkScale structure. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkScale * +TkpCreateScale(tkwin) + Tk_Window tkwin; +{ + return (TkScale *) ckalloc(sizeof(TkScale)); +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyScale -- + * + * Destroy a TkScale structure. + * + * Results: + * None + * + * Side effects: + * Memory is freed. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyScale(scalePtr) + TkScale *scalePtr; +{ + ckfree((char *) scalePtr); +} + +/* + *-------------------------------------------------------------- + * + * DisplayVerticalScale -- + * + * This procedure redraws the contents of a vertical scale + * window. It is invoked as a do-when-idle handler, so it only + * runs when there's nothing else for the application to do. + * + * Results: + * There is no return value. If only a part of the scale needs + * to be redrawn, then drawnAreaPtr is modified to reflect the + * area that was actually modified. + * + * Side effects: + * Information appears on the screen. + * + *-------------------------------------------------------------- + */ + +static void +DisplayVerticalScale(scalePtr, drawable, drawnAreaPtr) + TkScale *scalePtr; /* Widget record for scale. */ + Drawable drawable; /* Where to display scale (window + * or pixmap). */ + XRectangle *drawnAreaPtr; /* Initally contains area of window; + * if only a part of the scale is + * redrawn, gets modified to reflect + * the part of the window that was + * redrawn. */ +{ + Tk_Window tkwin = scalePtr->tkwin; + int x, y, width, height, shadowWidth; + double tickValue; + Tk_3DBorder sliderBorder; + + /* + * Display the information from left to right across the window. + */ + + if (!(scalePtr->flags & REDRAW_OTHER)) { + drawnAreaPtr->x = scalePtr->vertTickRightX; + drawnAreaPtr->y = scalePtr->inset; + drawnAreaPtr->width = scalePtr->vertTroughX + scalePtr->width + + 2*scalePtr->borderWidth - scalePtr->vertTickRightX; + drawnAreaPtr->height -= 2*scalePtr->inset; + } + Tk_Fill3DRectangle(tkwin, drawable, scalePtr->bgBorder, + drawnAreaPtr->x, drawnAreaPtr->y, drawnAreaPtr->width, + drawnAreaPtr->height, 0, TK_RELIEF_FLAT); + if (scalePtr->flags & REDRAW_OTHER) { + /* + * Display the tick marks. + */ + + if (scalePtr->tickInterval != 0) { + for (tickValue = scalePtr->fromValue; ; + tickValue += scalePtr->tickInterval) { + /* + * The TkRoundToResolution call gets rid of accumulated + * round-off errors, if any. + */ + + tickValue = TkRoundToResolution(scalePtr, tickValue); + if (scalePtr->toValue >= scalePtr->fromValue) { + if (tickValue > scalePtr->toValue) { + break; + } + } else { + if (tickValue < scalePtr->toValue) { + break; + } + } + DisplayVerticalValue(scalePtr, drawable, tickValue, + scalePtr->vertTickRightX); + } + } + } + + /* + * Display the value, if it is desired. + */ + + if (scalePtr->showValue) { + DisplayVerticalValue(scalePtr, drawable, scalePtr->value, + scalePtr->vertValueRightX); + } + + /* + * Display the trough and the slider. + */ + + Tk_Draw3DRectangle(tkwin, drawable, + scalePtr->bgBorder, scalePtr->vertTroughX, scalePtr->inset, + scalePtr->width + 2*scalePtr->borderWidth, + Tk_Height(tkwin) - 2*scalePtr->inset, scalePtr->borderWidth, + TK_RELIEF_SUNKEN); + XFillRectangle(scalePtr->display, drawable, scalePtr->troughGC, + scalePtr->vertTroughX + scalePtr->borderWidth, + scalePtr->inset + scalePtr->borderWidth, + (unsigned) scalePtr->width, + (unsigned) (Tk_Height(tkwin) - 2*scalePtr->inset + - 2*scalePtr->borderWidth)); + if (scalePtr->state == tkActiveUid) { + sliderBorder = scalePtr->activeBorder; + } else { + sliderBorder = scalePtr->bgBorder; + } + width = scalePtr->width; + height = scalePtr->sliderLength/2; + x = scalePtr->vertTroughX + scalePtr->borderWidth; + y = TkpValueToPixel(scalePtr, scalePtr->value) - height; + shadowWidth = scalePtr->borderWidth/2; + if (shadowWidth == 0) { + shadowWidth = 1; + } + Tk_Draw3DRectangle(tkwin, drawable, sliderBorder, x, y, width, + 2*height, shadowWidth, scalePtr->sliderRelief); + x += shadowWidth; + y += shadowWidth; + width -= 2*shadowWidth; + height -= shadowWidth; + Tk_Fill3DRectangle(tkwin, drawable, sliderBorder, x, y, width, + height, shadowWidth, scalePtr->sliderRelief); + Tk_Fill3DRectangle(tkwin, drawable, sliderBorder, x, y+height, + width, height, shadowWidth, scalePtr->sliderRelief); + + /* + * Draw the label to the right of the scale. + */ + + if ((scalePtr->flags & REDRAW_OTHER) && (scalePtr->labelLength != 0)) { + Tk_FontMetrics fm; + + Tk_GetFontMetrics(scalePtr->tkfont, &fm); + Tk_DrawChars(scalePtr->display, drawable, scalePtr->textGC, + scalePtr->tkfont, scalePtr->label, scalePtr->labelLength, + scalePtr->vertLabelX, scalePtr->inset + (3*fm.ascent)/2); + } +} + +/* + *---------------------------------------------------------------------- + * + * DisplayVerticalValue -- + * + * This procedure is called to display values (scale readings) + * for vertically-oriented scales. + * + * Results: + * None. + * + * Side effects: + * The numerical value corresponding to value is displayed with + * its right edge at "rightEdge", and at a vertical position in + * the scale that corresponds to "value". + * + *---------------------------------------------------------------------- + */ + +static void +DisplayVerticalValue(scalePtr, drawable, value, rightEdge) + register TkScale *scalePtr; /* Information about widget in which to + * display value. */ + Drawable drawable; /* Pixmap or window in which to draw + * the value. */ + double value; /* Y-coordinate of number to display, + * specified in application coords, not + * in pixels (we'll compute pixels). */ + int rightEdge; /* X-coordinate of right edge of text, + * specified in pixels. */ +{ + register Tk_Window tkwin = scalePtr->tkwin; + int y, width, length; + char valueString[PRINT_CHARS]; + Tk_FontMetrics fm; + + Tk_GetFontMetrics(scalePtr->tkfont, &fm); + y = TkpValueToPixel(scalePtr, value) + fm.ascent/2; + sprintf(valueString, scalePtr->format, value); + length = strlen(valueString); + width = Tk_TextWidth(scalePtr->tkfont, valueString, length); + + /* + * Adjust the y-coordinate if necessary to keep the text entirely + * inside the window. + */ + + if ((y - fm.ascent) < (scalePtr->inset + SPACING)) { + y = scalePtr->inset + SPACING + fm.ascent; + } + if ((y + fm.descent) > (Tk_Height(tkwin) - scalePtr->inset - SPACING)) { + y = Tk_Height(tkwin) - scalePtr->inset - SPACING - fm.descent; + } + Tk_DrawChars(scalePtr->display, drawable, scalePtr->textGC, + scalePtr->tkfont, valueString, length, rightEdge - width, y); +} + +/* + *-------------------------------------------------------------- + * + * DisplayHorizontalScale -- + * + * This procedure redraws the contents of a horizontal scale + * window. It is invoked as a do-when-idle handler, so it only + * runs when there's nothing else for the application to do. + * + * Results: + * There is no return value. If only a part of the scale needs + * to be redrawn, then drawnAreaPtr is modified to reflect the + * area that was actually modified. + * + * Side effects: + * Information appears on the screen. + * + *-------------------------------------------------------------- + */ + +static void +DisplayHorizontalScale(scalePtr, drawable, drawnAreaPtr) + TkScale *scalePtr; /* Widget record for scale. */ + Drawable drawable; /* Where to display scale (window + * or pixmap). */ + XRectangle *drawnAreaPtr; /* Initally contains area of window; + * if only a part of the scale is + * redrawn, gets modified to reflect + * the part of the window that was + * redrawn. */ +{ + register Tk_Window tkwin = scalePtr->tkwin; + int x, y, width, height, shadowWidth; + double tickValue; + Tk_3DBorder sliderBorder; + + /* + * Display the information from bottom to top across the window. + */ + + if (!(scalePtr->flags & REDRAW_OTHER)) { + drawnAreaPtr->x = scalePtr->inset; + drawnAreaPtr->y = scalePtr->horizValueY; + drawnAreaPtr->width -= 2*scalePtr->inset; + drawnAreaPtr->height = scalePtr->horizTroughY + scalePtr->width + + 2*scalePtr->borderWidth - scalePtr->horizValueY; + } + Tk_Fill3DRectangle(tkwin, drawable, scalePtr->bgBorder, + drawnAreaPtr->x, drawnAreaPtr->y, drawnAreaPtr->width, + drawnAreaPtr->height, 0, TK_RELIEF_FLAT); + if (scalePtr->flags & REDRAW_OTHER) { + /* + * Display the tick marks. + */ + + if (scalePtr->tickInterval != 0) { + for (tickValue = scalePtr->fromValue; ; + tickValue += scalePtr->tickInterval) { + /* + * The TkRoundToResolution call gets rid of accumulated + * round-off errors, if any. + */ + + tickValue = TkRoundToResolution(scalePtr, tickValue); + if (scalePtr->toValue >= scalePtr->fromValue) { + if (tickValue > scalePtr->toValue) { + break; + } + } else { + if (tickValue < scalePtr->toValue) { + break; + } + } + DisplayHorizontalValue(scalePtr, drawable, tickValue, + scalePtr->horizTickY); + } + } + } + + /* + * Display the value, if it is desired. + */ + + if (scalePtr->showValue) { + DisplayHorizontalValue(scalePtr, drawable, scalePtr->value, + scalePtr->horizValueY); + } + + /* + * Display the trough and the slider. + */ + + y = scalePtr->horizTroughY; + Tk_Draw3DRectangle(tkwin, drawable, + scalePtr->bgBorder, scalePtr->inset, y, + Tk_Width(tkwin) - 2*scalePtr->inset, + scalePtr->width + 2*scalePtr->borderWidth, + scalePtr->borderWidth, TK_RELIEF_SUNKEN); + XFillRectangle(scalePtr->display, drawable, scalePtr->troughGC, + scalePtr->inset + scalePtr->borderWidth, + y + scalePtr->borderWidth, + (unsigned) (Tk_Width(tkwin) - 2*scalePtr->inset + - 2*scalePtr->borderWidth), + (unsigned) scalePtr->width); + if (scalePtr->state == tkActiveUid) { + sliderBorder = scalePtr->activeBorder; + } else { + sliderBorder = scalePtr->bgBorder; + } + width = scalePtr->sliderLength/2; + height = scalePtr->width; + x = TkpValueToPixel(scalePtr, scalePtr->value) - width; + y += scalePtr->borderWidth; + shadowWidth = scalePtr->borderWidth/2; + if (shadowWidth == 0) { + shadowWidth = 1; + } + Tk_Draw3DRectangle(tkwin, drawable, sliderBorder, + x, y, 2*width, height, shadowWidth, scalePtr->sliderRelief); + x += shadowWidth; + y += shadowWidth; + width -= shadowWidth; + height -= 2*shadowWidth; + Tk_Fill3DRectangle(tkwin, drawable, sliderBorder, x, y, width, height, + shadowWidth, scalePtr->sliderRelief); + Tk_Fill3DRectangle(tkwin, drawable, sliderBorder, x+width, y, + width, height, shadowWidth, scalePtr->sliderRelief); + + /* + * Draw the label at the top of the scale. + */ + + if ((scalePtr->flags & REDRAW_OTHER) && (scalePtr->labelLength != 0)) { + Tk_FontMetrics fm; + + Tk_GetFontMetrics(scalePtr->tkfont, &fm); + Tk_DrawChars(scalePtr->display, drawable, scalePtr->textGC, + scalePtr->tkfont, scalePtr->label, scalePtr->labelLength, + scalePtr->inset + fm.ascent/2, scalePtr->horizLabelY + fm.ascent); + } +} + +/* + *---------------------------------------------------------------------- + * + * DisplayHorizontalValue -- + * + * This procedure is called to display values (scale readings) + * for horizontally-oriented scales. + * + * Results: + * None. + * + * Side effects: + * The numerical value corresponding to value is displayed with + * its bottom edge at "bottom", and at a horizontal position in + * the scale that corresponds to "value". + * + *---------------------------------------------------------------------- + */ + +static void +DisplayHorizontalValue(scalePtr, drawable, value, top) + register TkScale *scalePtr; /* Information about widget in which to + * display value. */ + Drawable drawable; /* Pixmap or window in which to draw + * the value. */ + double value; /* X-coordinate of number to display, + * specified in application coords, not + * in pixels (we'll compute pixels). */ + int top; /* Y-coordinate of top edge of text, + * specified in pixels. */ +{ + register Tk_Window tkwin = scalePtr->tkwin; + int x, y, length, width; + char valueString[PRINT_CHARS]; + Tk_FontMetrics fm; + + x = TkpValueToPixel(scalePtr, value); + Tk_GetFontMetrics(scalePtr->tkfont, &fm); + y = top + fm.ascent; + sprintf(valueString, scalePtr->format, value); + length = strlen(valueString); + width = Tk_TextWidth(scalePtr->tkfont, valueString, length); + + /* + * Adjust the x-coordinate if necessary to keep the text entirely + * inside the window. + */ + + x -= (width)/2; + if (x < (scalePtr->inset + SPACING)) { + x = scalePtr->inset + SPACING; + } + if (x > (Tk_Width(tkwin) - scalePtr->inset)) { + x = Tk_Width(tkwin) - scalePtr->inset - SPACING - width; + } + Tk_DrawChars(scalePtr->display, drawable, scalePtr->textGC, + scalePtr->tkfont, valueString, length, x, y); +} + +/* + *---------------------------------------------------------------------- + * + * TkpDisplayScale -- + * + * This procedure is invoked as an idle handler to redisplay + * the contents of a scale widget. + * + * Results: + * None. + * + * Side effects: + * The scale gets redisplayed. + * + *---------------------------------------------------------------------- + */ + +void +TkpDisplayScale(clientData) + ClientData clientData; /* Widget record for scale. */ +{ + TkScale *scalePtr = (TkScale *) clientData; + Tk_Window tkwin = scalePtr->tkwin; + Tcl_Interp *interp = scalePtr->interp; + Pixmap pixmap; + int result; + char string[PRINT_CHARS]; + XRectangle drawnArea; + + if ((scalePtr->tkwin == NULL) || !Tk_IsMapped(scalePtr->tkwin)) { + goto done; + } + + /* + * Invoke the scale's command if needed. + */ + + Tcl_Preserve((ClientData) scalePtr); + Tcl_Preserve((ClientData) interp); + if ((scalePtr->flags & INVOKE_COMMAND) && (scalePtr->command != NULL)) { + sprintf(string, scalePtr->format, scalePtr->value); + result = Tcl_VarEval(interp, scalePtr->command, " ", string, + (char *) NULL); + if (result != TCL_OK) { + Tcl_AddErrorInfo(interp, "\n (command executed by scale)"); + Tcl_BackgroundError(interp); + } + } + Tcl_Release((ClientData) interp); + scalePtr->flags &= ~INVOKE_COMMAND; + if (scalePtr->tkwin == NULL) { + Tcl_Release((ClientData) scalePtr); + return; + } + Tcl_Release((ClientData) scalePtr); + + /* + * In order to avoid screen flashes, this procedure redraws + * the scale in a pixmap, then copies the pixmap to the + * screen in a single operation. This means that there's no + * point in time where the on-sreen image has been cleared. + */ + + pixmap = Tk_GetPixmap(scalePtr->display, Tk_WindowId(tkwin), + Tk_Width(tkwin), Tk_Height(tkwin), Tk_Depth(tkwin)); + drawnArea.x = 0; + drawnArea.y = 0; + drawnArea.width = Tk_Width(tkwin); + drawnArea.height = Tk_Height(tkwin); + + /* + * Much of the redisplay is done totally differently for + * horizontal and vertical scales. Handle the part that's + * different. + */ + + if (scalePtr->vertical) { + DisplayVerticalScale(scalePtr, pixmap, &drawnArea); + } else { + DisplayHorizontalScale(scalePtr, pixmap, &drawnArea); + } + + /* + * Now handle the part of redisplay that is the same for + * horizontal and vertical scales: border and traversal + * highlight. + */ + + if (scalePtr->flags & REDRAW_OTHER) { + if (scalePtr->relief != TK_RELIEF_FLAT) { + Tk_Draw3DRectangle(tkwin, pixmap, scalePtr->bgBorder, + scalePtr->highlightWidth, scalePtr->highlightWidth, + Tk_Width(tkwin) - 2*scalePtr->highlightWidth, + Tk_Height(tkwin) - 2*scalePtr->highlightWidth, + scalePtr->borderWidth, scalePtr->relief); + } + if (scalePtr->highlightWidth != 0) { + GC gc; + + if (scalePtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(scalePtr->highlightColorPtr, pixmap); + } else { + gc = Tk_GCForColor(scalePtr->highlightBgColorPtr, pixmap); + } + Tk_DrawFocusHighlight(tkwin, gc, scalePtr->highlightWidth, pixmap); + } + } + + /* + * Copy the information from the off-screen pixmap onto the screen, + * then delete the pixmap. + */ + + XCopyArea(scalePtr->display, pixmap, Tk_WindowId(tkwin), + scalePtr->copyGC, drawnArea.x, drawnArea.y, drawnArea.width, + drawnArea.height, drawnArea.x, drawnArea.y); + Tk_FreePixmap(scalePtr->display, pixmap); + + done: + scalePtr->flags &= ~REDRAW_ALL; +} + +/* + *---------------------------------------------------------------------- + * + * TkpScaleElement -- + * + * Determine which part of a scale widget lies under a given + * point. + * + * Results: + * The return value is either TROUGH1, SLIDER, TROUGH2, or + * OTHER, depending on which of the scale's active elements + * (if any) is under the point at (x,y). + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpScaleElement(scalePtr, x, y) + TkScale *scalePtr; /* Widget record for scale. */ + int x, y; /* Coordinates within scalePtr's window. */ +{ + int sliderFirst; + + if (scalePtr->vertical) { + if ((x < scalePtr->vertTroughX) + || (x >= (scalePtr->vertTroughX + 2*scalePtr->borderWidth + + scalePtr->width))) { + return OTHER; + } + if ((y < scalePtr->inset) + || (y >= (Tk_Height(scalePtr->tkwin) - scalePtr->inset))) { + return OTHER; + } + sliderFirst = TkpValueToPixel(scalePtr, scalePtr->value) + - scalePtr->sliderLength/2; + if (y < sliderFirst) { + return TROUGH1; + } + if (y < (sliderFirst+scalePtr->sliderLength)) { + return SLIDER; + } + return TROUGH2; + } + + if ((y < scalePtr->horizTroughY) + || (y >= (scalePtr->horizTroughY + 2*scalePtr->borderWidth + + scalePtr->width))) { + return OTHER; + } + if ((x < scalePtr->inset) + || (x >= (Tk_Width(scalePtr->tkwin) - scalePtr->inset))) { + return OTHER; + } + sliderFirst = TkpValueToPixel(scalePtr, scalePtr->value) + - scalePtr->sliderLength/2; + if (x < sliderFirst) { + return TROUGH1; + } + if (x < (sliderFirst+scalePtr->sliderLength)) { + return SLIDER; + } + return TROUGH2; +} + +/* + *-------------------------------------------------------------- + * + * TkpSetScaleValue -- + * + * This procedure changes the value of a scale and invokes + * a Tcl command to reflect the current position of a scale + * + * Results: + * None. + * + * Side effects: + * A Tcl command is invoked, and an additional error-processing + * command may also be invoked. The scale's slider is redrawn. + * + *-------------------------------------------------------------- + */ + +void +TkpSetScaleValue(scalePtr, value, setVar, invokeCommand) + register TkScale *scalePtr; /* Info about widget. */ + double value; /* New value for scale. Gets adjusted + * if it's off the scale. */ + int setVar; /* Non-zero means reflect new value through + * to associated variable, if any. */ + int invokeCommand; /* Non-zero means invoked -command option + * to notify of new value, 0 means don't. */ +{ + char string[PRINT_CHARS]; + + value = TkRoundToResolution(scalePtr, value); + if ((value < scalePtr->fromValue) + ^ (scalePtr->toValue < scalePtr->fromValue)) { + value = scalePtr->fromValue; + } + if ((value > scalePtr->toValue) + ^ (scalePtr->toValue < scalePtr->fromValue)) { + value = scalePtr->toValue; + } + if (scalePtr->flags & NEVER_SET) { + scalePtr->flags &= ~NEVER_SET; + } else if (scalePtr->value == value) { + return; + } + scalePtr->value = value; + if (invokeCommand) { + scalePtr->flags |= INVOKE_COMMAND; + } + TkEventuallyRedrawScale(scalePtr, REDRAW_SLIDER); + + if (setVar && (scalePtr->varName != NULL)) { + sprintf(string, scalePtr->format, scalePtr->value); + scalePtr->flags |= SETTING_VAR; + Tcl_SetVar(scalePtr->interp, scalePtr->varName, string, + TCL_GLOBAL_ONLY); + scalePtr->flags &= ~SETTING_VAR; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpPixelToValue -- + * + * Given a pixel within a scale window, return the scale + * reading corresponding to that pixel. + * + * Results: + * A double-precision scale reading. If the value is outside + * the legal range for the scale then it's rounded to the nearest + * end of the scale. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +double +TkpPixelToValue(scalePtr, x, y) + register TkScale *scalePtr; /* Information about widget. */ + int x, y; /* Coordinates of point within + * window. */ +{ + double value, pixelRange; + + if (scalePtr->vertical) { + pixelRange = Tk_Height(scalePtr->tkwin) - scalePtr->sliderLength + - 2*scalePtr->inset - 2*scalePtr->borderWidth; + value = y; + } else { + pixelRange = Tk_Width(scalePtr->tkwin) - scalePtr->sliderLength + - 2*scalePtr->inset - 2*scalePtr->borderWidth; + value = x; + } + + if (pixelRange <= 0) { + /* + * Not enough room for the slider to actually slide: just return + * the scale's current value. + */ + + return scalePtr->value; + } + value -= scalePtr->sliderLength/2 + scalePtr->inset + + scalePtr->borderWidth; + value /= pixelRange; + if (value < 0) { + value = 0; + } + if (value > 1) { + value = 1; + } + value = scalePtr->fromValue + + value * (scalePtr->toValue - scalePtr->fromValue); + return TkRoundToResolution(scalePtr, value); +} + +/* + *---------------------------------------------------------------------- + * + * TkpValueToPixel -- + * + * Given a reading of the scale, return the x-coordinate or + * y-coordinate corresponding to that reading, depending on + * whether the scale is vertical or horizontal, respectively. + * + * Results: + * An integer value giving the pixel location corresponding + * to reading. The value is restricted to lie within the + * defined range for the scale. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpValueToPixel(scalePtr, value) + register TkScale *scalePtr; /* Information about widget. */ + double value; /* Reading of the widget. */ +{ + int y, pixelRange; + double valueRange; + + valueRange = scalePtr->toValue - scalePtr->fromValue; + pixelRange = (scalePtr->vertical ? Tk_Height(scalePtr->tkwin) + : Tk_Width(scalePtr->tkwin)) - scalePtr->sliderLength + - 2*scalePtr->inset - 2*scalePtr->borderWidth; + if (valueRange == 0) { + y = 0; + } else { + y = (int) ((value - scalePtr->fromValue) * pixelRange + / valueRange + 0.5); + if (y < 0) { + y = 0; + } else if (y > pixelRange) { + y = pixelRange; + } + } + y += scalePtr->sliderLength/2 + scalePtr->inset + scalePtr->borderWidth; + return y; +} diff --git a/unix/tkUnixScrlbr.c b/unix/tkUnixScrlbr.c new file mode 100644 index 0000000..74b46e8 --- /dev/null +++ b/unix/tkUnixScrlbr.c @@ -0,0 +1,476 @@ +/* + * tkUnixScrollbar.c -- + * + * This file implements the Unix specific portion of the scrollbar + * widget. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixScrlbr.c 1.8 96/12/10 20:05:07 + */ + +#include "tkScrollbar.h" + +/* + * Minimum slider length, in pixels (designed to make sure that the slider + * is always easy to grab with the mouse). + */ + +#define MIN_SLIDER_LENGTH 5 + +/* + * Declaration of Unix specific scrollbar structure. + */ + +typedef struct UnixScrollbar { + TkScrollbar info; /* Generic scrollbar info. */ + GC troughGC; /* For drawing trough. */ + GC copyGC; /* Used for copying from pixmap onto screen. */ +} UnixScrollbar; + +/* + * The class procedure table for the scrollbar widget. + */ + +TkClassProcs tkpScrollbarProcs = { + NULL, /* createProc. */ + NULL, /* geometryProc. */ + NULL /* modalProc. */ +}; + + +/* + *---------------------------------------------------------------------- + * + * TkpCreateScrollbar -- + * + * Allocate a new TkScrollbar structure. + * + * Results: + * Returns a newly allocated TkScrollbar structure. + * + * Side effects: + * Registers an event handler for the widget. + * + *---------------------------------------------------------------------- + */ + +TkScrollbar * +TkpCreateScrollbar(tkwin) + Tk_Window tkwin; +{ + UnixScrollbar *scrollPtr = (UnixScrollbar *)ckalloc(sizeof(UnixScrollbar)); + scrollPtr->troughGC = None; + scrollPtr->copyGC = None; + + Tk_CreateEventHandler(tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + TkScrollbarEventProc, (ClientData) scrollPtr); + + return (TkScrollbar *) scrollPtr; +} + +/* + *-------------------------------------------------------------- + * + * TkpDisplayScrollbar -- + * + * This procedure redraws the contents of a scrollbar window. + * It is invoked as a do-when-idle handler, so it only runs + * when there's nothing else for the application to do. + * + * Results: + * None. + * + * Side effects: + * Information appears on the screen. + * + *-------------------------------------------------------------- + */ + +void +TkpDisplayScrollbar(clientData) + ClientData clientData; /* Information about window. */ +{ + register TkScrollbar *scrollPtr = (TkScrollbar *) clientData; + register Tk_Window tkwin = scrollPtr->tkwin; + XPoint points[7]; + Tk_3DBorder border; + int relief, width, elementBorderWidth; + Pixmap pixmap; + + if ((scrollPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + goto done; + } + + if (scrollPtr->vertical) { + width = Tk_Width(tkwin) - 2*scrollPtr->inset; + } else { + width = Tk_Height(tkwin) - 2*scrollPtr->inset; + } + elementBorderWidth = scrollPtr->elementBorderWidth; + if (elementBorderWidth < 0) { + elementBorderWidth = scrollPtr->borderWidth; + } + + /* + * In order to avoid screen flashes, this procedure redraws + * the scrollbar in a pixmap, then copies the pixmap to the + * screen in a single operation. This means that there's no + * point in time where the on-sreen image has been cleared. + */ + + pixmap = Tk_GetPixmap(scrollPtr->display, Tk_WindowId(tkwin), + Tk_Width(tkwin), Tk_Height(tkwin), Tk_Depth(tkwin)); + + if (scrollPtr->highlightWidth != 0) { + GC gc; + + if (scrollPtr->flags & GOT_FOCUS) { + gc = Tk_GCForColor(scrollPtr->highlightColorPtr, pixmap); + } else { + gc = Tk_GCForColor(scrollPtr->highlightBgColorPtr, pixmap); + } + Tk_DrawFocusHighlight(tkwin, gc, scrollPtr->highlightWidth, pixmap); + } + Tk_Draw3DRectangle(tkwin, pixmap, scrollPtr->bgBorder, + scrollPtr->highlightWidth, scrollPtr->highlightWidth, + Tk_Width(tkwin) - 2*scrollPtr->highlightWidth, + Tk_Height(tkwin) - 2*scrollPtr->highlightWidth, + scrollPtr->borderWidth, scrollPtr->relief); + XFillRectangle(scrollPtr->display, pixmap, + ((UnixScrollbar*)scrollPtr)->troughGC, + scrollPtr->inset, scrollPtr->inset, + (unsigned) (Tk_Width(tkwin) - 2*scrollPtr->inset), + (unsigned) (Tk_Height(tkwin) - 2*scrollPtr->inset)); + + /* + * Draw the top or left arrow. The coordinates of the polygon + * points probably seem odd, but they were carefully chosen with + * respect to X's rules for filling polygons. These point choices + * cause the arrows to just fill the narrow dimension of the + * scrollbar and be properly centered. + */ + + if (scrollPtr->activeField == TOP_ARROW) { + border = scrollPtr->activeBorder; + relief = scrollPtr->activeField == TOP_ARROW ? scrollPtr->activeRelief + : TK_RELIEF_RAISED; + } else { + border = scrollPtr->bgBorder; + relief = TK_RELIEF_RAISED; + } + if (scrollPtr->vertical) { + points[0].x = scrollPtr->inset - 1; + points[0].y = scrollPtr->arrowLength + scrollPtr->inset - 1; + points[1].x = width + scrollPtr->inset; + points[1].y = points[0].y; + points[2].x = width/2 + scrollPtr->inset; + points[2].y = scrollPtr->inset - 1; + Tk_Fill3DPolygon(tkwin, pixmap, border, points, 3, + elementBorderWidth, relief); + } else { + points[0].x = scrollPtr->arrowLength + scrollPtr->inset - 1; + points[0].y = scrollPtr->inset - 1; + points[1].x = scrollPtr->inset; + points[1].y = width/2 + scrollPtr->inset; + points[2].x = points[0].x; + points[2].y = width + scrollPtr->inset; + Tk_Fill3DPolygon(tkwin, pixmap, border, points, 3, + elementBorderWidth, relief); + } + + /* + * Display the bottom or right arrow. + */ + + if (scrollPtr->activeField == BOTTOM_ARROW) { + border = scrollPtr->activeBorder; + relief = scrollPtr->activeField == BOTTOM_ARROW + ? scrollPtr->activeRelief : TK_RELIEF_RAISED; + } else { + border = scrollPtr->bgBorder; + relief = TK_RELIEF_RAISED; + } + if (scrollPtr->vertical) { + points[0].x = scrollPtr->inset; + points[0].y = Tk_Height(tkwin) - scrollPtr->arrowLength + - scrollPtr->inset + 1; + points[1].x = width/2 + scrollPtr->inset; + points[1].y = Tk_Height(tkwin) - scrollPtr->inset; + points[2].x = width + scrollPtr->inset; + points[2].y = points[0].y; + Tk_Fill3DPolygon(tkwin, pixmap, border, + points, 3, elementBorderWidth, relief); + } else { + points[0].x = Tk_Width(tkwin) - scrollPtr->arrowLength + - scrollPtr->inset + 1; + points[0].y = scrollPtr->inset - 1; + points[1].x = points[0].x; + points[1].y = width + scrollPtr->inset; + points[2].x = Tk_Width(tkwin) - scrollPtr->inset; + points[2].y = width/2 + scrollPtr->inset; + Tk_Fill3DPolygon(tkwin, pixmap, border, + points, 3, elementBorderWidth, relief); + } + + /* + * Display the slider. + */ + + if (scrollPtr->activeField == SLIDER) { + border = scrollPtr->activeBorder; + relief = scrollPtr->activeField == SLIDER ? scrollPtr->activeRelief + : TK_RELIEF_RAISED; + } else { + border = scrollPtr->bgBorder; + relief = TK_RELIEF_RAISED; + } + if (scrollPtr->vertical) { + Tk_Fill3DRectangle(tkwin, pixmap, border, + scrollPtr->inset, scrollPtr->sliderFirst, + width, scrollPtr->sliderLast - scrollPtr->sliderFirst, + elementBorderWidth, relief); + } else { + Tk_Fill3DRectangle(tkwin, pixmap, border, + scrollPtr->sliderFirst, scrollPtr->inset, + scrollPtr->sliderLast - scrollPtr->sliderFirst, width, + elementBorderWidth, relief); + } + + /* + * Copy the information from the off-screen pixmap onto the screen, + * then delete the pixmap. + */ + + XCopyArea(scrollPtr->display, pixmap, Tk_WindowId(tkwin), + ((UnixScrollbar*)scrollPtr)->copyGC, 0, 0, + (unsigned) Tk_Width(tkwin), (unsigned) Tk_Height(tkwin), 0, 0); + Tk_FreePixmap(scrollPtr->display, pixmap); + + done: + scrollPtr->flags &= ~REDRAW_PENDING; +} + +/* + *---------------------------------------------------------------------- + * + * TkpComputeScrollbarGeometry -- + * + * After changes in a scrollbar's size or configuration, this + * procedure recomputes various geometry information used in + * displaying the scrollbar. + * + * Results: + * None. + * + * Side effects: + * The scrollbar will be displayed differently. + * + *---------------------------------------------------------------------- + */ + +extern void +TkpComputeScrollbarGeometry(scrollPtr) + register TkScrollbar *scrollPtr; /* Scrollbar whose geometry may + * have changed. */ +{ + int width, fieldLength; + + if (scrollPtr->highlightWidth < 0) { + scrollPtr->highlightWidth = 0; + } + scrollPtr->inset = scrollPtr->highlightWidth + scrollPtr->borderWidth; + width = (scrollPtr->vertical) ? Tk_Width(scrollPtr->tkwin) + : Tk_Height(scrollPtr->tkwin); + scrollPtr->arrowLength = width - 2*scrollPtr->inset + 1; + fieldLength = (scrollPtr->vertical ? Tk_Height(scrollPtr->tkwin) + : Tk_Width(scrollPtr->tkwin)) + - 2*(scrollPtr->arrowLength + scrollPtr->inset); + if (fieldLength < 0) { + fieldLength = 0; + } + scrollPtr->sliderFirst = fieldLength*scrollPtr->firstFraction; + scrollPtr->sliderLast = fieldLength*scrollPtr->lastFraction; + + /* + * Adjust the slider so that some piece of it is always + * displayed in the scrollbar and so that it has at least + * a minimal width (so it can be grabbed with the mouse). + */ + + if (scrollPtr->sliderFirst > (fieldLength - 2*scrollPtr->borderWidth)) { + scrollPtr->sliderFirst = fieldLength - 2*scrollPtr->borderWidth; + } + if (scrollPtr->sliderFirst < 0) { + scrollPtr->sliderFirst = 0; + } + if (scrollPtr->sliderLast < (scrollPtr->sliderFirst + + MIN_SLIDER_LENGTH)) { + scrollPtr->sliderLast = scrollPtr->sliderFirst + MIN_SLIDER_LENGTH; + } + if (scrollPtr->sliderLast > fieldLength) { + scrollPtr->sliderLast = fieldLength; + } + scrollPtr->sliderFirst += scrollPtr->arrowLength + scrollPtr->inset; + scrollPtr->sliderLast += scrollPtr->arrowLength + scrollPtr->inset; + + /* + * Register the desired geometry for the window (leave enough space + * for the two arrows plus a minimum-size slider, plus border around + * the whole window, if any). Then arrange for the window to be + * redisplayed. + */ + + if (scrollPtr->vertical) { + Tk_GeometryRequest(scrollPtr->tkwin, + scrollPtr->width + 2*scrollPtr->inset, + 2*(scrollPtr->arrowLength + scrollPtr->borderWidth + + scrollPtr->inset)); + } else { + Tk_GeometryRequest(scrollPtr->tkwin, + 2*(scrollPtr->arrowLength + scrollPtr->borderWidth + + scrollPtr->inset), scrollPtr->width + 2*scrollPtr->inset); + } + Tk_SetInternalBorder(scrollPtr->tkwin, scrollPtr->inset); +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyScrollbar -- + * + * Free data structures associated with the scrollbar control. + * + * Results: + * None. + * + * Side effects: + * Frees the GCs associated with the scrollbar. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyScrollbar(scrollPtr) + TkScrollbar *scrollPtr; +{ + UnixScrollbar *unixScrollPtr = (UnixScrollbar *)scrollPtr; + + if (unixScrollPtr->troughGC != None) { + Tk_FreeGC(scrollPtr->display, unixScrollPtr->troughGC); + } + if (unixScrollPtr->copyGC != None) { + Tk_FreeGC(scrollPtr->display, unixScrollPtr->copyGC); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpConfigureScrollbar -- + * + * This procedure is called after the generic code has finished + * processing configuration options, in order to configure + * platform specific options. + * + * Results: + * None. + * + * Side effects: + * Configuration info may get changed. + * + *---------------------------------------------------------------------- + */ + +void +TkpConfigureScrollbar(scrollPtr) + register TkScrollbar *scrollPtr; /* Information about widget; may or + * may not already have values for + * some fields. */ +{ + XGCValues gcValues; + GC new; + UnixScrollbar *unixScrollPtr = (UnixScrollbar *) scrollPtr; + + Tk_SetBackgroundFromBorder(scrollPtr->tkwin, scrollPtr->bgBorder); + + gcValues.foreground = scrollPtr->troughColorPtr->pixel; + new = Tk_GetGC(scrollPtr->tkwin, GCForeground, &gcValues); + if (unixScrollPtr->troughGC != None) { + Tk_FreeGC(scrollPtr->display, unixScrollPtr->troughGC); + } + unixScrollPtr->troughGC = new; + if (unixScrollPtr->copyGC == None) { + gcValues.graphics_exposures = False; + unixScrollPtr->copyGC = Tk_GetGC(scrollPtr->tkwin, GCGraphicsExposures, + &gcValues); + } +} + +/* + *-------------------------------------------------------------- + * + * TkpScrollbarPosition -- + * + * Determine the scrollbar element corresponding to a + * given position. + * + * Results: + * One of TOP_ARROW, TOP_GAP, etc., indicating which element + * of the scrollbar covers the position given by (x, y). If + * (x,y) is outside the scrollbar entirely, then OUTSIDE is + * returned. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkpScrollbarPosition(scrollPtr, x, y) + register TkScrollbar *scrollPtr; /* Scrollbar widget record. */ + int x, y; /* Coordinates within scrollPtr's + * window. */ +{ + int length, width, tmp; + + if (scrollPtr->vertical) { + length = Tk_Height(scrollPtr->tkwin); + width = Tk_Width(scrollPtr->tkwin); + } else { + tmp = x; + x = y; + y = tmp; + length = Tk_Width(scrollPtr->tkwin); + width = Tk_Height(scrollPtr->tkwin); + } + + if ((x < scrollPtr->inset) || (x >= (width - scrollPtr->inset)) + || (y < scrollPtr->inset) || (y >= (length - scrollPtr->inset))) { + return OUTSIDE; + } + + /* + * All of the calculations in this procedure mirror those in + * TkpDisplayScrollbar. Be sure to keep the two consistent. + */ + + if (y < (scrollPtr->inset + scrollPtr->arrowLength)) { + return TOP_ARROW; + } + if (y < scrollPtr->sliderFirst) { + return TOP_GAP; + } + if (y < scrollPtr->sliderLast) { + return SLIDER; + } + if (y >= (length - (scrollPtr->arrowLength + scrollPtr->inset))) { + return BOTTOM_ARROW; + } + return BOTTOM_GAP; +} diff --git a/unix/tkUnixSelect.c b/unix/tkUnixSelect.c new file mode 100644 index 0000000..404631e --- /dev/null +++ b/unix/tkUnixSelect.c @@ -0,0 +1,1189 @@ +/* + * tkUnixSelect.c -- + * + * This file contains X specific routines for manipulating + * selections. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixSelect.c 1.5 96/03/29 14:14:31 + */ + +#include "tkInt.h" +#include "tkSelect.h" + +/* + * When handling INCR-style selection retrievals, the selection owner + * uses the following data structure to communicate between the + * ConvertSelection procedure and TkSelPropProc. + */ + +typedef struct IncrInfo { + TkWindow *winPtr; /* Window that owns selection. */ + Atom selection; /* Selection that is being retrieved. */ + Atom *multAtoms; /* Information about conversions to + * perform: one or more pairs of + * (target, property). This either + * points to a retrieved property (for + * MULTIPLE retrievals) or to a static + * array. */ + unsigned long numConversions; + /* Number of entries in offsets (same as + * # of pairs in multAtoms). */ + int *offsets; /* One entry for each pair in + * multAtoms; -1 means all data has + * been transferred for this + * conversion. -2 means only the + * final zero-length transfer still + * has to be done. Otherwise it is the + * offset of the next chunk of data + * to transfer. This array is malloc-ed. */ + int numIncrs; /* Number of entries in offsets that + * aren't -1 (i.e. # of INCR-mode transfers + * not yet completed). */ + Tcl_TimerToken timeout; /* Token for timer procedure. */ + int idleTime; /* Number of seconds since we heard + * anything from the selection + * requestor. */ + Window reqWindow; /* Requestor's window id. */ + Time time; /* Timestamp corresponding to + * selection at beginning of request; + * used to abort transfer if selection + * changes. */ + struct IncrInfo *nextPtr; /* Next in list of all INCR-style + * retrievals currently pending. */ +} IncrInfo; + +static IncrInfo *pendingIncrs = NULL; + /* List of all incr structures + * currently active. */ + +/* + * Largest property that we'll accept when sending or receiving the + * selection: + */ + +#define MAX_PROP_WORDS 100000 + +static TkSelRetrievalInfo *pendingRetrievals = NULL; + /* List of all retrievals currently + * being waited for. */ + +/* + * Forward declarations for procedures defined in this file: + */ + +static void ConvertSelection _ANSI_ARGS_((TkWindow *winPtr, + XSelectionRequestEvent *eventPtr)); +static void IncrTimeoutProc _ANSI_ARGS_((ClientData clientData)); +static char * SelCvtFromX _ANSI_ARGS_((long *propPtr, int numValues, + Atom type, Tk_Window tkwin)); +static long * SelCvtToX _ANSI_ARGS_((char *string, Atom type, + Tk_Window tkwin, int *numLongsPtr)); +static int SelectionSize _ANSI_ARGS_((TkSelHandler *selPtr)); +static void SelRcvIncrProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void SelTimeoutProc _ANSI_ARGS_((ClientData clientData)); + +/* + *---------------------------------------------------------------------- + * + * TkSelGetSelection -- + * + * Retrieve the specified selection from another process. + * + * Results: + * The return value is a standard Tcl return value. + * If an error occurs (such as no selection exists) + * then an error message is left in interp->result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkSelGetSelection(interp, tkwin, selection, target, proc, clientData) + Tcl_Interp *interp; /* Interpreter to use for reporting + * errors. */ + Tk_Window tkwin; /* Window on whose behalf to retrieve + * the selection (determines display + * from which to retrieve). */ + Atom selection; /* Selection to retrieve. */ + Atom target; /* Desired form in which selection + * is to be returned. */ + Tk_GetSelProc *proc; /* Procedure to call to process the + * selection, once it has been retrieved. */ + ClientData clientData; /* Arbitrary value to pass to proc. */ +{ + TkSelRetrievalInfo retr; + TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr = winPtr->dispPtr; + + /* + * The selection is owned by some other process. To + * retrieve it, first record information about the retrieval + * in progress. Use an internal window as the requestor. + */ + + retr.interp = interp; + if (dispPtr->clipWindow == NULL) { + int result; + + result = TkClipInit(interp, dispPtr); + if (result != TCL_OK) { + return result; + } + } + retr.winPtr = (TkWindow *) dispPtr->clipWindow; + retr.selection = selection; + retr.property = selection; + retr.target = target; + retr.proc = proc; + retr.clientData = clientData; + retr.result = -1; + retr.idleTime = 0; + retr.nextPtr = pendingRetrievals; + pendingRetrievals = &retr; + + /* + * Initiate the request for the selection. Note: can't use + * TkCurrentTime for the time. If we do, and this application hasn't + * received any X events in a long time, the current time will be way + * in the past and could even predate the time when the selection was + * made; if this happens, the request will be rejected. + */ + + XConvertSelection(winPtr->display, retr.selection, retr.target, + retr.property, retr.winPtr->window, CurrentTime); + + /* + * Enter a loop processing X events until the selection + * has been retrieved and processed. If no response is + * received within a few seconds, then timeout. + */ + + retr.timeout = Tcl_CreateTimerHandler(1000, SelTimeoutProc, + (ClientData) &retr); + while (retr.result == -1) { + Tcl_DoOneEvent(0); + } + Tcl_DeleteTimerHandler(retr.timeout); + + /* + * Unregister the information about the selection retrieval + * in progress. + */ + + if (pendingRetrievals == &retr) { + pendingRetrievals = retr.nextPtr; + } else { + TkSelRetrievalInfo *retrPtr; + + for (retrPtr = pendingRetrievals; retrPtr != NULL; + retrPtr = retrPtr->nextPtr) { + if (retrPtr->nextPtr == &retr) { + retrPtr->nextPtr = retr.nextPtr; + break; + } + } + } + return retr.result; +} + +/* + *---------------------------------------------------------------------- + * + * TkSelPropProc -- + * + * This procedure is invoked when property-change events + * occur on windows not known to the toolkit. Its function + * is to implement the sending side of the INCR selection + * retrieval protocol when the selection requestor deletes + * the property containing a part of the selection. + * + * Results: + * None. + * + * Side effects: + * If the property that is receiving the selection was just + * deleted, then a new piece of the selection is fetched and + * placed in the property, until eventually there's no more + * selection to fetch. + * + *---------------------------------------------------------------------- + */ + +void +TkSelPropProc(eventPtr) + register XEvent *eventPtr; /* X PropertyChange event. */ +{ + register IncrInfo *incrPtr; + int i, format; + Atom target, formatType; + register TkSelHandler *selPtr; + long buffer[TK_SEL_WORDS_AT_ONCE]; + int numItems; + char *propPtr; + Tk_ErrorHandler errorHandler; + + /* + * See if this event announces the deletion of a property being + * used for an INCR transfer. If so, then add the next chunk of + * data to the property. + */ + + if (eventPtr->xproperty.state != PropertyDelete) { + return; + } + for (incrPtr = pendingIncrs; incrPtr != NULL; + incrPtr = incrPtr->nextPtr) { + if (incrPtr->reqWindow != eventPtr->xproperty.window) { + continue; + } + for (i = 0; i < incrPtr->numConversions; i++) { + if ((eventPtr->xproperty.atom != incrPtr->multAtoms[2*i + 1]) + || (incrPtr->offsets[i] == -1)){ + continue; + } + target = incrPtr->multAtoms[2*i]; + incrPtr->idleTime = 0; + for (selPtr = incrPtr->winPtr->selHandlerList; ; + selPtr = selPtr->nextPtr) { + if (selPtr == NULL) { + incrPtr->multAtoms[2*i + 1] = None; + incrPtr->offsets[i] = -1; + incrPtr->numIncrs --; + return; + } + if ((selPtr->target == target) + && (selPtr->selection == incrPtr->selection)) { + formatType = selPtr->format; + if (incrPtr->offsets[i] == -2) { + numItems = 0; + ((char *) buffer)[0] = 0; + } else { + TkSelInProgress ip; + ip.selPtr = selPtr; + ip.nextPtr = pendingPtr; + pendingPtr = &ip; + numItems = (*selPtr->proc)(selPtr->clientData, + incrPtr->offsets[i], (char *) buffer, + TK_SEL_BYTES_AT_ONCE); + pendingPtr = ip.nextPtr; + if (ip.selPtr == NULL) { + /* + * The selection handler deleted itself. + */ + + return; + } + if (numItems > TK_SEL_BYTES_AT_ONCE) { + panic("selection handler returned too many bytes"); + } else { + if (numItems < 0) { + numItems = 0; + } + } + ((char *) buffer)[numItems] = '\0'; + } + if (numItems < TK_SEL_BYTES_AT_ONCE) { + if (numItems <= 0) { + incrPtr->offsets[i] = -1; + incrPtr->numIncrs--; + } else { + incrPtr->offsets[i] = -2; + } + } else { + incrPtr->offsets[i] += numItems; + } + if (formatType == XA_STRING) { + propPtr = (char *) buffer; + format = 8; + } else { + propPtr = (char *) SelCvtToX((char *) buffer, + formatType, (Tk_Window) incrPtr->winPtr, + &numItems); + format = 32; + } + errorHandler = Tk_CreateErrorHandler( + eventPtr->xproperty.display, -1, -1, -1, + (int (*)()) NULL, (ClientData) NULL); + XChangeProperty(eventPtr->xproperty.display, + eventPtr->xproperty.window, + eventPtr->xproperty.atom, formatType, + format, PropModeReplace, + (unsigned char *) propPtr, numItems); + Tk_DeleteErrorHandler(errorHandler); + if (propPtr != (char *) buffer) { + ckfree(propPtr); + } + return; + } + } + } + } +} + +/* + *-------------------------------------------------------------- + * + * TkSelEventProc -- + * + * This procedure is invoked whenever a selection-related + * event occurs. It does the lion's share of the work + * in implementing the selection protocol. + * + * Results: + * None. + * + * Side effects: + * Lots: depends on the type of event. + * + *-------------------------------------------------------------- + */ + +void +TkSelEventProc(tkwin, eventPtr) + Tk_Window tkwin; /* Window for which event was + * targeted. */ + register XEvent *eventPtr; /* X event: either SelectionClear, + * SelectionRequest, or + * SelectionNotify. */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr = winPtr->dispPtr; + Tcl_Interp *interp; + + /* + * Case #1: SelectionClear events. + */ + + if (eventPtr->type == SelectionClear) { + TkSelClearSelection(tkwin, eventPtr); + } + + /* + * Case #2: SelectionNotify events. Call the relevant procedure + * to handle the incoming selection. + */ + + if (eventPtr->type == SelectionNotify) { + register TkSelRetrievalInfo *retrPtr; + char *propInfo; + Atom type; + int format, result; + unsigned long numItems, bytesAfter; + + for (retrPtr = pendingRetrievals; ; retrPtr = retrPtr->nextPtr) { + if (retrPtr == NULL) { + return; + } + if ((retrPtr->winPtr == winPtr) + && (retrPtr->selection == eventPtr->xselection.selection) + && (retrPtr->target == eventPtr->xselection.target) + && (retrPtr->result == -1)) { + if (retrPtr->property == eventPtr->xselection.property) { + break; + } + if (eventPtr->xselection.property == None) { + Tcl_SetResult(retrPtr->interp, (char *) NULL, TCL_STATIC); + Tcl_AppendResult(retrPtr->interp, + Tk_GetAtomName(tkwin, retrPtr->selection), + " selection doesn't exist or form \"", + Tk_GetAtomName(tkwin, retrPtr->target), + "\" not defined", (char *) NULL); + retrPtr->result = TCL_ERROR; + return; + } + } + } + + propInfo = NULL; + result = XGetWindowProperty(eventPtr->xselection.display, + eventPtr->xselection.requestor, retrPtr->property, + 0, MAX_PROP_WORDS, False, (Atom) AnyPropertyType, + &type, &format, &numItems, &bytesAfter, + (unsigned char **) &propInfo); + if ((result != Success) || (type == None)) { + return; + } + if (bytesAfter != 0) { + Tcl_SetResult(retrPtr->interp, "selection property too large", + TCL_STATIC); + retrPtr->result = TCL_ERROR; + XFree(propInfo); + return; + } + if ((type == XA_STRING) || (type == dispPtr->textAtom) + || (type == dispPtr->compoundTextAtom)) { + if (format != 8) { + sprintf(retrPtr->interp->result, + "bad format for string selection: wanted \"8\", got \"%d\"", + format); + retrPtr->result = TCL_ERROR; + return; + } + interp = retrPtr->interp; + Tcl_Preserve((ClientData) interp); + retrPtr->result = (*retrPtr->proc)(retrPtr->clientData, + interp, propInfo); + Tcl_Release((ClientData) interp); + } else if (type == dispPtr->incrAtom) { + + /* + * It's a !?#@!?!! INCR-style reception. Arrange to receive + * the selection in pieces, using the ICCCM protocol, then + * hang around until either the selection is all here or a + * timeout occurs. + */ + + retrPtr->idleTime = 0; + Tk_CreateEventHandler(tkwin, PropertyChangeMask, SelRcvIncrProc, + (ClientData) retrPtr); + XDeleteProperty(Tk_Display(tkwin), Tk_WindowId(tkwin), + retrPtr->property); + while (retrPtr->result == -1) { + Tcl_DoOneEvent(0); + } + Tk_DeleteEventHandler(tkwin, PropertyChangeMask, SelRcvIncrProc, + (ClientData) retrPtr); + } else { + char *string; + + if (format != 32) { + sprintf(retrPtr->interp->result, + "bad format for selection: wanted \"32\", got \"%d\"", + format); + retrPtr->result = TCL_ERROR; + return; + } + string = SelCvtFromX((long *) propInfo, (int) numItems, type, + (Tk_Window) winPtr); + interp = retrPtr->interp; + Tcl_Preserve((ClientData) interp); + retrPtr->result = (*retrPtr->proc)(retrPtr->clientData, + interp, string); + Tcl_Release((ClientData) interp); + ckfree(string); + } + XFree(propInfo); + return; + } + + /* + * Case #3: SelectionRequest events. Call ConvertSelection to + * do the dirty work. + */ + + if (eventPtr->type == SelectionRequest) { + ConvertSelection(winPtr, &eventPtr->xselectionrequest); + return; + } +} + +/* + *---------------------------------------------------------------------- + * + * SelTimeoutProc -- + * + * This procedure is invoked once every second while waiting for + * the selection to be returned. After a while it gives up and + * aborts the selection retrieval. + * + * Results: + * None. + * + * Side effects: + * A new timer callback is created to call us again in another + * second, unless time has expired, in which case an error is + * recorded for the retrieval. + * + *---------------------------------------------------------------------- + */ + +static void +SelTimeoutProc(clientData) + ClientData clientData; /* Information about retrieval + * in progress. */ +{ + register TkSelRetrievalInfo *retrPtr = (TkSelRetrievalInfo *) clientData; + + /* + * Make sure that the retrieval is still in progress. Then + * see how long it's been since any sort of response was received + * from the other side. + */ + + if (retrPtr->result != -1) { + return; + } + retrPtr->idleTime++; + if (retrPtr->idleTime >= 5) { + + /* + * Use a careful procedure to store the error message, because + * the result could already be partially filled in with a partial + * selection return. + */ + + Tcl_SetResult(retrPtr->interp, "selection owner didn't respond", + TCL_STATIC); + retrPtr->result = TCL_ERROR; + } else { + retrPtr->timeout = Tcl_CreateTimerHandler(1000, SelTimeoutProc, + (ClientData) retrPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * ConvertSelection -- + * + * This procedure is invoked to handle SelectionRequest events. + * It responds to the requests, obeying the ICCCM protocols. + * + * Results: + * None. + * + * Side effects: + * Properties are created for the selection requestor, and a + * SelectionNotify event is generated for the selection + * requestor. In the event of long selections, this procedure + * implements INCR-mode transfers, using the ICCCM protocol. + * + *---------------------------------------------------------------------- + */ + +static void +ConvertSelection(winPtr, eventPtr) + TkWindow *winPtr; /* Window that received the + * conversion request; may not be + * selection's current owner, be we + * set it to the current owner. */ + register XSelectionRequestEvent *eventPtr; + /* Event describing request. */ +{ + XSelectionEvent reply; /* Used to notify requestor that + * selection info is ready. */ + int multiple; /* Non-zero means a MULTIPLE request + * is being handled. */ + IncrInfo incr; /* State of selection conversion. */ + Atom singleInfo[2]; /* incr.multAtoms points here except + * for multiple conversions. */ + int i; + Tk_ErrorHandler errorHandler; + TkSelectionInfo *infoPtr; + TkSelInProgress ip; + + errorHandler = Tk_CreateErrorHandler(eventPtr->display, -1, -1,-1, + (int (*)()) NULL, (ClientData) NULL); + + /* + * Initialize the reply event. + */ + + reply.type = SelectionNotify; + reply.serial = 0; + reply.send_event = True; + reply.display = eventPtr->display; + reply.requestor = eventPtr->requestor; + reply.selection = eventPtr->selection; + reply.target = eventPtr->target; + reply.property = eventPtr->property; + if (reply.property == None) { + reply.property = reply.target; + } + reply.time = eventPtr->time; + + for (infoPtr = winPtr->dispPtr->selectionInfoPtr; infoPtr != NULL; + infoPtr = infoPtr->nextPtr) { + if (infoPtr->selection == eventPtr->selection) + break; + } + if (infoPtr == NULL) { + goto refuse; + } + winPtr = (TkWindow *) infoPtr->owner; + + /* + * Figure out which kind(s) of conversion to perform. If handling + * a MULTIPLE conversion, then read the property describing which + * conversions to perform. + */ + + incr.winPtr = winPtr; + incr.selection = eventPtr->selection; + if (eventPtr->target != winPtr->dispPtr->multipleAtom) { + multiple = 0; + singleInfo[0] = reply.target; + singleInfo[1] = reply.property; + incr.multAtoms = singleInfo; + incr.numConversions = 1; + } else { + Atom type; + int format, result; + unsigned long bytesAfter; + + multiple = 1; + incr.multAtoms = NULL; + if (eventPtr->property == None) { + goto refuse; + } + result = XGetWindowProperty(eventPtr->display, + eventPtr->requestor, eventPtr->property, + 0, MAX_PROP_WORDS, False, XA_ATOM, + &type, &format, &incr.numConversions, &bytesAfter, + (unsigned char **) &incr.multAtoms); + if ((result != Success) || (bytesAfter != 0) || (format != 32) + || (type == None)) { + if (incr.multAtoms != NULL) { + XFree((char *) incr.multAtoms); + } + goto refuse; + } + incr.numConversions /= 2; /* Two atoms per conversion. */ + } + + /* + * Loop through all of the requested conversions, and either return + * the entire converted selection, if it can be returned in a single + * bunch, or return INCR information only (the actual selection will + * be returned below). + */ + + incr.offsets = (int *) ckalloc((unsigned) + (incr.numConversions*sizeof(int))); + incr.numIncrs = 0; + for (i = 0; i < incr.numConversions; i++) { + Atom target, property, type; + long buffer[TK_SEL_WORDS_AT_ONCE]; + register TkSelHandler *selPtr; + int numItems, format; + char *propPtr; + + target = incr.multAtoms[2*i]; + property = incr.multAtoms[2*i + 1]; + incr.offsets[i] = -1; + + for (selPtr = winPtr->selHandlerList; selPtr != NULL; + selPtr = selPtr->nextPtr) { + if ((selPtr->target == target) + && (selPtr->selection == eventPtr->selection)) { + break; + } + } + + if (selPtr == NULL) { + /* + * Nobody seems to know about this kind of request. If + * it's of a sort that we can handle without any help, do + * it. Otherwise mark the request as an errror. + */ + + numItems = TkSelDefaultSelection(infoPtr, target, (char *) buffer, + TK_SEL_BYTES_AT_ONCE, &type); + if (numItems < 0) { + incr.multAtoms[2*i + 1] = None; + continue; + } + } else { + ip.selPtr = selPtr; + ip.nextPtr = pendingPtr; + pendingPtr = &ip; + type = selPtr->format; + numItems = (*selPtr->proc)(selPtr->clientData, 0, + (char *) buffer, TK_SEL_BYTES_AT_ONCE); + pendingPtr = ip.nextPtr; + if ((ip.selPtr == NULL) || (numItems < 0)) { + incr.multAtoms[2*i + 1] = None; + continue; + } + if (numItems > TK_SEL_BYTES_AT_ONCE) { + panic("selection handler returned too many bytes"); + } + ((char *) buffer)[numItems] = '\0'; + } + + /* + * Got the selection; store it back on the requestor's property. + */ + + if (numItems == TK_SEL_BYTES_AT_ONCE) { + /* + * Selection is too big to send at once; start an + * INCR-mode transfer. + */ + + incr.numIncrs++; + type = winPtr->dispPtr->incrAtom; + buffer[0] = SelectionSize(selPtr); + if (buffer[0] == 0) { + incr.multAtoms[2*i + 1] = None; + continue; + } + numItems = 1; + propPtr = (char *) buffer; + format = 32; + incr.offsets[i] = 0; + } else if (type == XA_STRING) { + propPtr = (char *) buffer; + format = 8; + } else { + propPtr = (char *) SelCvtToX((char *) buffer, + type, (Tk_Window) winPtr, &numItems); + format = 32; + } + XChangeProperty(reply.display, reply.requestor, + property, type, format, PropModeReplace, + (unsigned char *) propPtr, numItems); + if (propPtr != (char *) buffer) { + ckfree(propPtr); + } + } + + /* + * Send an event back to the requestor to indicate that the + * first stage of conversion is complete (everything is done + * except for long conversions that have to be done in INCR + * mode). + */ + + if (incr.numIncrs > 0) { + XSelectInput(reply.display, reply.requestor, PropertyChangeMask); + incr.timeout = Tcl_CreateTimerHandler(1000, IncrTimeoutProc, + (ClientData) &incr); + incr.idleTime = 0; + incr.reqWindow = reply.requestor; + incr.time = infoPtr->time; + incr.nextPtr = pendingIncrs; + pendingIncrs = &incr; + } + if (multiple) { + XChangeProperty(reply.display, reply.requestor, reply.property, + XA_ATOM, 32, PropModeReplace, + (unsigned char *) incr.multAtoms, + (int) incr.numConversions*2); + } else { + + /* + * Not a MULTIPLE request. The first property in "multAtoms" + * got set to None if there was an error in conversion. + */ + + reply.property = incr.multAtoms[1]; + } + XSendEvent(reply.display, reply.requestor, False, 0, (XEvent *) &reply); + Tk_DeleteErrorHandler(errorHandler); + + /* + * Handle any remaining INCR-mode transfers. This all happens + * in callbacks to TkSelPropProc, so just wait until the number + * of uncompleted INCR transfers drops to zero. + */ + + if (incr.numIncrs > 0) { + IncrInfo *incrPtr2; + + while (incr.numIncrs > 0) { + Tcl_DoOneEvent(0); + } + Tcl_DeleteTimerHandler(incr.timeout); + errorHandler = Tk_CreateErrorHandler(winPtr->display, + -1, -1,-1, (int (*)()) NULL, (ClientData) NULL); + XSelectInput(reply.display, reply.requestor, 0L); + Tk_DeleteErrorHandler(errorHandler); + if (pendingIncrs == &incr) { + pendingIncrs = incr.nextPtr; + } else { + for (incrPtr2 = pendingIncrs; incrPtr2 != NULL; + incrPtr2 = incrPtr2->nextPtr) { + if (incrPtr2->nextPtr == &incr) { + incrPtr2->nextPtr = incr.nextPtr; + break; + } + } + } + } + + /* + * All done. Cleanup and return. + */ + + ckfree((char *) incr.offsets); + if (multiple) { + XFree((char *) incr.multAtoms); + } + return; + + /* + * An error occurred. Send back a refusal message. + */ + + refuse: + reply.property = None; + XSendEvent(reply.display, reply.requestor, False, 0, (XEvent *) &reply); + Tk_DeleteErrorHandler(errorHandler); + return; +} + +/* + *---------------------------------------------------------------------- + * + * SelRcvIncrProc -- + * + * This procedure handles the INCR protocol on the receiving + * side. It is invoked in response to property changes on + * the requestor's window (which hopefully are because a new + * chunk of the selection arrived). + * + * Results: + * None. + * + * Side effects: + * If a new piece of selection has arrived, a procedure is + * invoked to deal with that piece. When the whole selection + * is here, a flag is left for the higher-level procedure that + * initiated the selection retrieval. + * + *---------------------------------------------------------------------- + */ + +static void +SelRcvIncrProc(clientData, eventPtr) + ClientData clientData; /* Information about retrieval. */ + register XEvent *eventPtr; /* X PropertyChange event. */ +{ + register TkSelRetrievalInfo *retrPtr = (TkSelRetrievalInfo *) clientData; + char *propInfo; + Atom type; + int format, result; + unsigned long numItems, bytesAfter; + Tcl_Interp *interp; + + if ((eventPtr->xproperty.atom != retrPtr->property) + || (eventPtr->xproperty.state != PropertyNewValue) + || (retrPtr->result != -1)) { + return; + } + propInfo = NULL; + result = XGetWindowProperty(eventPtr->xproperty.display, + eventPtr->xproperty.window, retrPtr->property, 0, MAX_PROP_WORDS, + True, (Atom) AnyPropertyType, &type, &format, &numItems, + &bytesAfter, (unsigned char **) &propInfo); + if ((result != Success) || (type == None)) { + return; + } + if (bytesAfter != 0) { + Tcl_SetResult(retrPtr->interp, "selection property too large", + TCL_STATIC); + retrPtr->result = TCL_ERROR; + goto done; + } + if (numItems == 0) { + retrPtr->result = TCL_OK; + } else if ((type == XA_STRING) + || (type == retrPtr->winPtr->dispPtr->textAtom) + || (type == retrPtr->winPtr->dispPtr->compoundTextAtom)) { + if (format != 8) { + Tcl_SetResult(retrPtr->interp, (char *) NULL, TCL_STATIC); + sprintf(retrPtr->interp->result, + "bad format for string selection: wanted \"8\", got \"%d\"", + format); + retrPtr->result = TCL_ERROR; + goto done; + } + interp = retrPtr->interp; + Tcl_Preserve((ClientData) interp); + result = (*retrPtr->proc)(retrPtr->clientData, interp, propInfo); + Tcl_Release((ClientData) interp); + if (result != TCL_OK) { + retrPtr->result = result; + } + } else { + char *string; + + if (format != 32) { + Tcl_SetResult(retrPtr->interp, (char *) NULL, TCL_STATIC); + sprintf(retrPtr->interp->result, + "bad format for selection: wanted \"32\", got \"%d\"", + format); + retrPtr->result = TCL_ERROR; + goto done; + } + string = SelCvtFromX((long *) propInfo, (int) numItems, type, + (Tk_Window) retrPtr->winPtr); + interp = retrPtr->interp; + Tcl_Preserve((ClientData) interp); + result = (*retrPtr->proc)(retrPtr->clientData, interp, string); + Tcl_Release((ClientData) interp); + if (result != TCL_OK) { + retrPtr->result = result; + } + ckfree(string); + } + + done: + XFree(propInfo); + retrPtr->idleTime = 0; +} + +/* + *---------------------------------------------------------------------- + * + * SelectionSize -- + * + * This procedure is called when the selection is too large to + * send in a single buffer; it computes the total length of + * the selection in bytes. + * + * Results: + * The return value is the number of bytes in the selection + * given by selPtr. + * + * Side effects: + * The selection is retrieved from its current owner (this is + * the only way to compute its size). + * + *---------------------------------------------------------------------- + */ + +static int +SelectionSize(selPtr) + TkSelHandler *selPtr; /* Information about how to retrieve + * the selection whose size is wanted. */ +{ + char buffer[TK_SEL_BYTES_AT_ONCE+1]; + int size, chunkSize; + TkSelInProgress ip; + + size = TK_SEL_BYTES_AT_ONCE; + ip.selPtr = selPtr; + ip.nextPtr = pendingPtr; + pendingPtr = &ip; + do { + chunkSize = (*selPtr->proc)(selPtr->clientData, size, + (char *) buffer, TK_SEL_BYTES_AT_ONCE); + if (ip.selPtr == NULL) { + size = 0; + break; + } + size += chunkSize; + } while (chunkSize == TK_SEL_BYTES_AT_ONCE); + pendingPtr = ip.nextPtr; + return size; +} + +/* + *---------------------------------------------------------------------- + * + * IncrTimeoutProc -- + * + * This procedure is invoked once a second while sending the + * selection to a requestor in INCR mode. After a while it + * gives up and aborts the selection operation. + * + * Results: + * None. + * + * Side effects: + * A new timeout gets registered so that this procedure gets + * called again in another second, unless too many seconds + * have elapsed, in which case incrPtr is marked as "all done". + * + *---------------------------------------------------------------------- + */ + +static void +IncrTimeoutProc(clientData) + ClientData clientData; /* Information about INCR-mode + * selection retrieval for which + * we are selection owner. */ +{ + register IncrInfo *incrPtr = (IncrInfo *) clientData; + + incrPtr->idleTime++; + if (incrPtr->idleTime >= 5) { + incrPtr->numIncrs = 0; + } else { + incrPtr->timeout = Tcl_CreateTimerHandler(1000, IncrTimeoutProc, + (ClientData) incrPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * SelCvtToX -- + * + * Given a selection represented as a string (the normal Tcl form), + * convert it to the ICCCM-mandated format for X, depending on + * the type argument. This procedure and SelCvtFromX are inverses. + * + * Results: + * The return value is a malloc'ed buffer holding a value + * equivalent to "string", but formatted as for "type". It is + * the caller's responsibility to free the string when done with + * it. The word at *numLongsPtr is filled in with the number of + * 32-bit words returned in the result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static long * +SelCvtToX(string, type, tkwin, numLongsPtr) + char *string; /* String representation of selection. */ + Atom type; /* Atom specifying the X format that is + * desired for the selection. Should not + * be XA_STRING (if so, don't bother calling + * this procedure at all). */ + Tk_Window tkwin; /* Window that governs atom conversion. */ + int *numLongsPtr; /* Number of 32-bit words contained in the + * result. */ +{ + register char *p; + char *field; + int numFields; + long *propPtr, *longPtr; +#define MAX_ATOM_NAME_LENGTH 100 + char atomName[MAX_ATOM_NAME_LENGTH+1]; + + /* + * The string is assumed to consist of fields separated by spaces. + * The property gets generated by converting each field to an + * integer number, in one of two ways: + * 1. If type is XA_ATOM, convert each field to its corresponding + * atom. + * 2. If type is anything else, convert each field from an ASCII number + * to a 32-bit binary number. + */ + + numFields = 1; + for (p = string; *p != 0; p++) { + if (isspace(UCHAR(*p))) { + numFields++; + } + } + propPtr = (long *) ckalloc((unsigned) numFields*sizeof(long)); + + /* + * Convert the fields one-by-one. + */ + + for (longPtr = propPtr, *numLongsPtr = 0, p = string; + ; longPtr++, (*numLongsPtr)++) { + while (isspace(UCHAR(*p))) { + p++; + } + if (*p == 0) { + break; + } + field = p; + while ((*p != 0) && !isspace(UCHAR(*p))) { + p++; + } + if (type == XA_ATOM) { + int length; + + length = p - field; + if (length > MAX_ATOM_NAME_LENGTH) { + length = MAX_ATOM_NAME_LENGTH; + } + strncpy(atomName, field, (unsigned) length); + atomName[length] = 0; + *longPtr = (long) Tk_InternAtom(tkwin, atomName); + } else { + char *dummy; + + *longPtr = strtol(field, &dummy, 0); + } + } + return propPtr; +} + +/* + *---------------------------------------------------------------------- + * + * SelCvtFromX -- + * + * Given an X property value, formatted as a collection of 32-bit + * values according to "type" and the ICCCM conventions, convert + * the value to a string suitable for manipulation by Tcl. This + * procedure is the inverse of SelCvtToX. + * + * Results: + * The return value is the string equivalent of "property". It is + * malloc-ed and should be freed by the caller when no longer + * needed. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static char * +SelCvtFromX(propPtr, numValues, type, tkwin) + register long *propPtr; /* Property value from X. */ + int numValues; /* Number of 32-bit values in property. */ + Atom type; /* Type of property Should not be + * XA_STRING (if so, don't bother calling + * this procedure at all). */ + Tk_Window tkwin; /* Window to use for atom conversion. */ +{ + char *result; + int resultSpace, curSize, fieldSize; + char *atomName; + + /* + * Convert each long in the property to a string value, which is + * either the name of an atom (if type is XA_ATOM) or a hexadecimal + * string. Make an initial guess about the size of the result, but + * be prepared to enlarge the result if necessary. + */ + + resultSpace = 12*numValues+1; + curSize = 0; + atomName = ""; /* Not needed, but eliminates compiler warning. */ + result = (char *) ckalloc((unsigned) resultSpace); + *result = '\0'; + for ( ; numValues > 0; propPtr++, numValues--) { + if (type == XA_ATOM) { + atomName = Tk_GetAtomName(tkwin, (Atom) *propPtr); + fieldSize = strlen(atomName) + 1; + } else { + fieldSize = 12; + } + if (curSize+fieldSize >= resultSpace) { + char *newResult; + + resultSpace *= 2; + if (curSize+fieldSize >= resultSpace) { + resultSpace = curSize + fieldSize + 1; + } + newResult = (char *) ckalloc((unsigned) resultSpace); + strncpy(newResult, result, (unsigned) curSize); + ckfree(result); + result = newResult; + } + if (curSize != 0) { + result[curSize] = ' '; + curSize++; + } + if (type == XA_ATOM) { + strcpy(result+curSize, atomName); + } else { + sprintf(result+curSize, "0x%x", (unsigned int) *propPtr); + } + curSize += strlen(result+curSize); + } + return result; +} diff --git a/unix/tkUnixSend.c b/unix/tkUnixSend.c new file mode 100644 index 0000000..f07c59b --- /dev/null +++ b/unix/tkUnixSend.c @@ -0,0 +1,1851 @@ +/* + * tkUnixSend.c -- + * + * This file provides procedures that implement the "send" + * command, allowing commands to be passed from interpreter + * to interpreter. + * + * Copyright (c) 1989-1994 The Regents of the University of California. + * Copyright (c) 1994-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixSend.c 1.74 97/11/04 17:12:18 + */ + +#include "tkPort.h" +#include "tkInt.h" +#include "tkUnixInt.h" + +/* + * The following structure is used to keep track of the interpreters + * registered by this process. + */ + +typedef struct RegisteredInterp { + char *name; /* Interpreter's name (malloc-ed). */ + Tcl_Interp *interp; /* Interpreter associated with name. NULL + * means that the application was unregistered + * or deleted while a send was in progress + * to it. */ + TkDisplay *dispPtr; /* Display for the application. Needed + * because we may need to unregister the + * interpreter after its main window has + * been deleted. */ + struct RegisteredInterp *nextPtr; + /* Next in list of names associated + * with interps in this process. + * NULL means end of list. */ +} RegisteredInterp; + +static RegisteredInterp *registry = NULL; + /* List of all interpreters + * registered by this process. */ + +/* + * A registry of all interpreters for a display is kept in a + * property "InterpRegistry" on the root window of the display. + * It is organized as a series of zero or more concatenated strings + * (in no particular order), each of the form + * window space name '\0' + * where "window" is the hex id of the comm. window to use to talk + * to an interpreter named "name". + * + * When the registry is being manipulated by an application (e.g. to + * add or remove an entry), it is loaded into memory using a structure + * of the following type: + */ + +typedef struct NameRegistry { + TkDisplay *dispPtr; /* Display from which the registry was + * read. */ + int locked; /* Non-zero means that the display was + * locked when the property was read in. */ + int modified; /* Non-zero means that the property has + * been modified, so it needs to be written + * out when the NameRegistry is closed. */ + unsigned long propLength; /* Length of the property, in bytes. */ + char *property; /* The contents of the property, or NULL + * if none. See format description above; + * this is *not* terminated by the first + * null character. Dynamically allocated. */ + int allocedByX; /* Non-zero means must free property with + * XFree; zero means use ckfree. */ +} NameRegistry; + +/* + * When a result is being awaited from a sent command, one of + * the following structures is present on a list of all outstanding + * sent commands. The information in the structure is used to + * process the result when it arrives. You're probably wondering + * how there could ever be multiple outstanding sent commands. + * This could happen if interpreters invoke each other recursively. + * It's unlikely, but possible. + */ + +typedef struct PendingCommand { + int serial; /* Serial number expected in + * result. */ + TkDisplay *dispPtr; /* Display being used for communication. */ + char *target; /* Name of interpreter command is + * being sent to. */ + Window commWindow; /* Target's communication window. */ + Tcl_Interp *interp; /* Interpreter from which the send + * was invoked. */ + int code; /* Tcl return code for command + * will be stored here. */ + char *result; /* String result for command (malloc'ed), + * or NULL. */ + char *errorInfo; /* Information for "errorInfo" variable, + * or NULL (malloc'ed). */ + char *errorCode; /* Information for "errorCode" variable, + * or NULL (malloc'ed). */ + int gotResponse; /* 1 means a response has been received, + * 0 means the command is still outstanding. */ + struct PendingCommand *nextPtr; + /* Next in list of all outstanding + * commands. NULL means end of + * list. */ +} PendingCommand; + +static PendingCommand *pendingCommands = NULL; + /* List of all commands currently + * being waited for. */ + +/* + * The information below is used for communication between processes + * during "send" commands. Each process keeps a private window, never + * even mapped, with one property, "Comm". When a command is sent to + * an interpreter, the command is appended to the comm property of the + * communication window associated with the interp's process. Similarly, + * when a result is returned from a sent command, it is also appended + * to the comm property. + * + * Each command and each result takes the form of ASCII text. For a + * command, the text consists of a zero character followed by several + * null-terminated ASCII strings. The first string consists of the + * single letter "c". Subsequent strings have the form "option value" + * where the following options are supported: + * + * -r commWindow serial + * + * This option means that a response should be sent to the window + * whose X identifier is "commWindow" (in hex), and the response should + * be identified with the serial number given by "serial" (in decimal). + * If this option isn't specified then the send is asynchronous and + * no response is sent. + * + * -n name + * "Name" gives the name of the application for which the command is + * intended. This option must be present. + * + * -s script + * + * "Script" is the script to be executed. This option must be present. + * + * The options may appear in any order. The -n and -s options must be + * present, but -r may be omitted for asynchronous RPCs. For compatibility + * with future releases that may add new features, there may be additional + * options present; as long as they start with a "-" character, they will + * be ignored. + * + * A result also consists of a zero character followed by several null- + * terminated ASCII strings. The first string consists of the single + * letter "r". Subsequent strings have the form "option value" where + * the following options are supported: + * + * -s serial + * + * Identifies the command for which this is the result. It is the + * same as the "serial" field from the -s option in the command. This + * option must be present. + * + * -c code + * + * "Code" is the completion code for the script, in decimal. If the + * code is omitted it defaults to TCL_OK. + * + * -r result + * + * "Result" is the result string for the script, which may be either + * a result or an error message. If this field is omitted then it + * defaults to an empty string. + * + * -i errorInfo + * + * "ErrorInfo" gives a string with which to initialize the errorInfo + * variable. This option may be omitted; it is ignored unless the + * completion code is TCL_ERROR. + * + * -e errorCode + * + * "ErrorCode" gives a string with with to initialize the errorCode + * variable. This option may be omitted; it is ignored unless the + * completion code is TCL_ERROR. + * + * Options may appear in any order, and only the -s option must be + * present. As with commands, there may be additional options besides + * these; unknown options are ignored. + */ + +/* + * The following variable is the serial number that was used in the + * last "send" command. It is exported only for testing purposes. + */ + +int tkSendSerial = 0; + +/* + * Maximum size property that can be read at one time by + * this module: + */ + +#define MAX_PROP_WORDS 100000 + +/* + * The following variable can be set while debugging to do things like + * skip locking the server. + */ + +static int sendDebug = 0; + +/* + * Forward declarations for procedures defined later in this file: + */ + +static int AppendErrorProc _ANSI_ARGS_((ClientData clientData, + XErrorEvent *errorPtr)); +static void AppendPropCarefully _ANSI_ARGS_((Display *display, + Window window, Atom property, char *value, + int length, PendingCommand *pendingPtr)); +static void DeleteProc _ANSI_ARGS_((ClientData clientData)); +static void RegAddName _ANSI_ARGS_((NameRegistry *regPtr, + char *name, Window commWindow)); +static void RegClose _ANSI_ARGS_((NameRegistry *regPtr)); +static void RegDeleteName _ANSI_ARGS_((NameRegistry *regPtr, + char *name)); +static Window RegFindName _ANSI_ARGS_((NameRegistry *regPtr, + char *name)); +static NameRegistry * RegOpen _ANSI_ARGS_((Tcl_Interp *interp, + TkDisplay *dispPtr, int lock)); +static void SendEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int SendInit _ANSI_ARGS_((Tcl_Interp *interp, + TkDisplay *dispPtr)); +static Tk_RestrictAction SendRestrictProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int ServerSecure _ANSI_ARGS_((TkDisplay *dispPtr)); +static void UpdateCommWindow _ANSI_ARGS_((TkDisplay *dispPtr)); +static int ValidateName _ANSI_ARGS_((TkDisplay *dispPtr, + char *name, Window commWindow, int oldOK)); + +/* + *---------------------------------------------------------------------- + * + * RegOpen -- + * + * This procedure loads the name registry for a display into + * memory so that it can be manipulated. + * + * Results: + * The return value is a pointer to the loaded registry. + * + * Side effects: + * If "lock" is set then the server will be locked. It is the + * caller's responsibility to call RegClose when finished with + * the registry, so that we can write back the registry if + * neeeded, unlock the server if needed, and free memory. + * + *---------------------------------------------------------------------- + */ + +static NameRegistry * +RegOpen(interp, dispPtr, lock) + Tcl_Interp *interp; /* Interpreter to use for error reporting + * (errors cause a panic so in fact no + * error is ever returned, but the interpreter + * is needed anyway). */ + TkDisplay *dispPtr; /* Display whose name registry is to be + * opened. */ + int lock; /* Non-zero means lock the window server + * when opening the registry, so no-one + * else can use the registry until we + * close it. */ +{ + NameRegistry *regPtr; + int result, actualFormat; + unsigned long bytesAfter; + Atom actualType; + + if (dispPtr->commTkwin == NULL) { + SendInit(interp, dispPtr); + } + + regPtr = (NameRegistry *) ckalloc(sizeof(NameRegistry)); + regPtr->dispPtr = dispPtr; + regPtr->locked = 0; + regPtr->modified = 0; + regPtr->allocedByX = 1; + + if (lock && !sendDebug) { + XGrabServer(dispPtr->display); + regPtr->locked = 1; + } + + /* + * Read the registry property. + */ + + result = XGetWindowProperty(dispPtr->display, + RootWindow(dispPtr->display, 0), + dispPtr->registryProperty, 0, MAX_PROP_WORDS, + False, XA_STRING, &actualType, &actualFormat, + ®Ptr->propLength, &bytesAfter, + (unsigned char **) ®Ptr->property); + + if (actualType == None) { + regPtr->propLength = 0; + regPtr->property = NULL; + } else if ((result != Success) || (actualFormat != 8) + || (actualType != XA_STRING)) { + /* + * The property is improperly formed; delete it. + */ + + if (regPtr->property != NULL) { + XFree(regPtr->property); + regPtr->propLength = 0; + regPtr->property = NULL; + } + XDeleteProperty(dispPtr->display, + RootWindow(dispPtr->display, 0), + dispPtr->registryProperty); + } + + /* + * Xlib placed an extra null byte after the end of the property, just + * to make sure that it is always NULL-terminated. Be sure to include + * this byte in our count if it's needed to ensure null termination + * (note: as of 8/95 I'm no longer sure why this code is needed; seems + * like it shouldn't be). + */ + + if ((regPtr->propLength > 0) + && (regPtr->property[regPtr->propLength-1] != 0)) { + regPtr->propLength++; + } + return regPtr; +} + +/* + *---------------------------------------------------------------------- + * + * RegFindName -- + * + * Given an open name registry, this procedure finds an entry + * with a given name, if there is one, and returns information + * about that entry. + * + * Results: + * The return value is the X identifier for the comm window for + * the application named "name", or None if there is no such + * entry in the registry. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static Window +RegFindName(regPtr, name) + NameRegistry *regPtr; /* Pointer to a registry opened with a + * previous call to RegOpen. */ + char *name; /* Name of an application. */ +{ + char *p, *entry; + unsigned int id; + + for (p = regPtr->property; (p-regPtr->property) < (int) regPtr->propLength; ) { + entry = p; + while ((*p != 0) && (!isspace(UCHAR(*p)))) { + p++; + } + if ((*p != 0) && (strcmp(name, p+1) == 0)) { + if (sscanf(entry, "%x", &id) == 1) { + /* + * Must cast from an unsigned int to a Window in case we + * are on a 64-bit architecture. + */ + + return (Window) id; + } + } + while (*p != 0) { + p++; + } + p++; + } + return None; +} + +/* + *---------------------------------------------------------------------- + * + * RegDeleteName -- + * + * This procedure deletes the entry for a given name from + * an open registry. + * + * Results: + * None. + * + * Side effects: + * If there used to be an entry named "name" in the registry, + * then it is deleted and the registry is marked as modified + * so it will be written back when closed. + * + *---------------------------------------------------------------------- + */ + +static void +RegDeleteName(regPtr, name) + NameRegistry *regPtr; /* Pointer to a registry opened with a + * previous call to RegOpen. */ + char *name; /* Name of an application. */ +{ + char *p, *entry, *entryName; + int count; + + for (p = regPtr->property; (p-regPtr->property) < (int) regPtr->propLength; ) { + entry = p; + while ((*p != 0) && (!isspace(UCHAR(*p)))) { + p++; + } + if (*p != 0) { + p++; + } + entryName = p; + while (*p != 0) { + p++; + } + p++; + if ((strcmp(name, entryName) == 0)) { + /* + * Found the matching entry. Copy everything after it + * down on top of it. + */ + + count = regPtr->propLength - (p - regPtr->property); + if (count > 0) { + char *src, *dst; + + for (src = p, dst = entry; count > 0; src++, dst++, count--) { + *dst = *src; + } + } + regPtr->propLength -= p - entry; + regPtr->modified = 1; + return; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * RegAddName -- + * + * Add a new entry to an open registry. + * + * Results: + * None. + * + * Side effects: + * The open registry is expanded; it is marked as modified so that + * it will be written back when closed. + * + *---------------------------------------------------------------------- + */ + +static void +RegAddName(regPtr, name, commWindow) + NameRegistry *regPtr; /* Pointer to a registry opened with a + * previous call to RegOpen. */ + char *name; /* Name of an application. The caller + * must ensure that this name isn't + * already registered. */ + Window commWindow; /* X identifier for comm. window of + * application. */ +{ + char id[30]; + char *newProp; + int idLength, newBytes; + + sprintf(id, "%x ", (unsigned int) commWindow); + idLength = strlen(id); + newBytes = idLength + strlen(name) + 1; + newProp = (char *) ckalloc((unsigned) (regPtr->propLength + newBytes)); + strcpy(newProp, id); + strcpy(newProp+idLength, name); + if (regPtr->property != NULL) { + memcpy((VOID *) (newProp + newBytes), (VOID *) regPtr->property, + regPtr->propLength); + if (regPtr->allocedByX) { + XFree(regPtr->property); + } else { + ckfree(regPtr->property); + } + } + regPtr->modified = 1; + regPtr->propLength += newBytes; + regPtr->property = newProp; + regPtr->allocedByX = 0; +} + +/* + *---------------------------------------------------------------------- + * + * RegClose -- + * + * This procedure is called to end a series of operations on + * a name registry. + * + * Results: + * None. + * + * Side effects: + * The registry is written back if it has been modified, and the + * X server is unlocked if it was locked. Memory for the + * registry is freed, so the caller should never use regPtr + * again. + * + *---------------------------------------------------------------------- + */ + +static void +RegClose(regPtr) + NameRegistry *regPtr; /* Pointer to a registry opened with a + * previous call to RegOpen. */ +{ + if (regPtr->modified) { + if (!regPtr->locked && !sendDebug) { + panic("The name registry was modified without being locked!"); + } + XChangeProperty(regPtr->dispPtr->display, + RootWindow(regPtr->dispPtr->display, 0), + regPtr->dispPtr->registryProperty, XA_STRING, 8, + PropModeReplace, (unsigned char *) regPtr->property, + (int) regPtr->propLength); + } + + if (regPtr->locked) { + XUngrabServer(regPtr->dispPtr->display); + } + + /* + * After ungrabbing the server, it's important to flush the output + * immediately so that the server sees the ungrab command. Otherwise + * we might do something else that needs to communicate with the + * server (such as invoking a subprocess that needs to do I/O to + * the screen); if the ungrab command is still sitting in our + * output buffer, we could deadlock. + */ + + XFlush(regPtr->dispPtr->display); + + if (regPtr->property != NULL) { + if (regPtr->allocedByX) { + XFree(regPtr->property); + } else { + ckfree(regPtr->property); + } + } + ckfree((char *) regPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ValidateName -- + * + * This procedure checks to see if an entry in the registry + * is still valid. + * + * Results: + * The return value is 1 if the given commWindow exists and its + * name is "name". Otherwise 0 is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +ValidateName(dispPtr, name, commWindow, oldOK) + TkDisplay *dispPtr; /* Display for which to perform the + * validation. */ + char *name; /* The name of an application. */ + Window commWindow; /* X identifier for the application's + * comm. window. */ + int oldOK; /* Non-zero means that we should consider + * an application to be valid even if it + * looks like an old-style (pre-4.0) one; + * 0 means consider these invalid. */ +{ + int result, actualFormat, argc, i; + unsigned long length, bytesAfter; + Atom actualType; + char *property; + Tk_ErrorHandler handler; + char **argv; + + property = NULL; + + /* + * Ignore X errors when reading the property (e.g., the window + * might not exist). If an error occurs, result will be some + * value other than Success. + */ + + handler = Tk_CreateErrorHandler(dispPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + result = XGetWindowProperty(dispPtr->display, commWindow, + dispPtr->appNameProperty, 0, MAX_PROP_WORDS, + False, XA_STRING, &actualType, &actualFormat, + &length, &bytesAfter, (unsigned char **) &property); + + if ((result == Success) && (actualType == None)) { + XWindowAttributes atts; + + /* + * The comm. window exists but the property we're looking for + * doesn't exist. This probably means that the application + * comes from an older version of Tk (< 4.0) that didn't set the + * property; if this is the case, then assume for compatibility's + * sake that everything's OK. However, it's also possible that + * some random application has re-used the window id for something + * totally unrelated. Check a few characteristics of the window, + * such as its dimensions and mapped state, to be sure that it + * still "smells" like a commWindow. + */ + + if (!oldOK + || !XGetWindowAttributes(dispPtr->display, commWindow, &atts) + || (atts.width != 1) || (atts.height != 1) + || (atts.map_state != IsUnmapped)) { + result = 0; + } else { + result = 1; + } + } else if ((result == Success) && (actualFormat == 8) + && (actualType == XA_STRING)) { + result = 0; + if (Tcl_SplitList((Tcl_Interp *) NULL, property, &argc, &argv) + == TCL_OK) { + for (i = 0; i < argc; i++) { + if (strcmp(argv[i], name) == 0) { + result = 1; + break; + } + } + ckfree((char *) argv); + } + } else { + result = 0; + } + Tk_DeleteErrorHandler(handler); + if (property != NULL) { + XFree(property); + } + return result; +} + +/* + *---------------------------------------------------------------------- + * + * ServerSecure -- + * + * Check whether a server is secure enough for us to trust + * Tcl scripts arriving via that server. + * + * Results: + * The return value is 1 if the server is secure, which means + * that host-style authentication is turned on but there are + * no hosts in the enabled list. This means that some other + * form of authorization (presumably more secure, such as xauth) + * is in use. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +ServerSecure(dispPtr) + TkDisplay *dispPtr; /* Display to check. */ +{ +#ifdef TK_NO_SECURITY + return 1; +#else + XHostAddress *addrPtr; + int numHosts, secure; + Bool enabled; + + secure = 0; + addrPtr = XListHosts(dispPtr->display, &numHosts, &enabled); + if (enabled && (numHosts == 0)) { + secure = 1; + } + if (addrPtr != NULL) { + XFree((char *) addrPtr); + } + return secure; +#endif /* TK_NO_SECURITY */ +} + +/* + *-------------------------------------------------------------- + * + * Tk_SetAppName -- + * + * This procedure is called to associate an ASCII name with a Tk + * application. If the application has already been named, the + * name replaces the old one. + * + * Results: + * The return value is the name actually given to the application. + * This will normally be the same as name, but if name was already + * in use for an application then a name of the form "name #2" will + * be chosen, with a high enough number to make the name unique. + * + * Side effects: + * Registration info is saved, thereby allowing the "send" command + * to be used later to invoke commands in the application. In + * addition, the "send" command is created in the application's + * interpreter. The registration will be removed automatically + * if the interpreter is deleted or the "send" command is removed. + * + *-------------------------------------------------------------- + */ + +char * +Tk_SetAppName(tkwin, name) + Tk_Window tkwin; /* Token for any window in the application + * to be named: it is just used to identify + * the application and the display. */ + char *name; /* The name that will be used to + * refer to the interpreter in later + * "send" commands. Must be globally + * unique. */ +{ + RegisteredInterp *riPtr, *riPtr2; + Window w; + TkWindow *winPtr = (TkWindow *) tkwin; + TkDisplay *dispPtr; + NameRegistry *regPtr; + Tcl_Interp *interp; + char *actualName; + Tcl_DString dString; + int offset, i; + +#ifdef __WIN32__ + return name; +#endif /* __WIN32__ */ + + dispPtr = winPtr->dispPtr; + interp = winPtr->mainPtr->interp; + if (dispPtr->commTkwin == NULL) { + SendInit(interp, winPtr->dispPtr); + } + + /* + * See if the application is already registered; if so, remove its + * current name from the registry. + */ + + regPtr = RegOpen(interp, winPtr->dispPtr, 1); + for (riPtr = registry; ; riPtr = riPtr->nextPtr) { + if (riPtr == NULL) { + + /* + * This interpreter isn't currently registered; create + * the data structure that will be used to register it locally, + * plus add the "send" command to the interpreter. + */ + + riPtr = (RegisteredInterp *) ckalloc(sizeof(RegisteredInterp)); + riPtr->interp = interp; + riPtr->dispPtr = winPtr->dispPtr; + riPtr->nextPtr = registry; + registry = riPtr; + Tcl_CreateCommand(interp, "send", Tk_SendCmd, (ClientData) riPtr, + DeleteProc); + if (Tcl_IsSafe(interp)) { + Tcl_HideCommand(interp, "send", "send"); + } + break; + } + if (riPtr->interp == interp) { + /* + * The interpreter is currently registered; remove it from + * the name registry. + */ + + RegDeleteName(regPtr, riPtr->name); + ckfree(riPtr->name); + break; + } + } + + /* + * Pick a name to use for the application. Use "name" if it's not + * already in use. Otherwise add a suffix such as " #2", trying + * larger and larger numbers until we eventually find one that is + * unique. + */ + + actualName = name; + offset = 0; /* Needed only to avoid "used before + * set" compiler warnings. */ + for (i = 1; ; i++) { + if (i > 1) { + if (i == 2) { + Tcl_DStringInit(&dString); + Tcl_DStringAppend(&dString, name, -1); + Tcl_DStringAppend(&dString, " #", 2); + offset = Tcl_DStringLength(&dString); + Tcl_DStringSetLength(&dString, offset+10); + actualName = Tcl_DStringValue(&dString); + } + sprintf(actualName + offset, "%d", i); + } + w = RegFindName(regPtr, actualName); + if (w == None) { + break; + } + + /* + * The name appears to be in use already, but double-check to + * be sure (perhaps the application died without removing its + * name from the registry?). + */ + + if (w == Tk_WindowId(dispPtr->commTkwin)) { + for (riPtr2 = registry; riPtr2 != NULL; riPtr2 = riPtr2->nextPtr) { + if ((riPtr2->interp != interp) && + (strcmp(riPtr2->name, actualName) == 0)) { + goto nextSuffix; + } + } + RegDeleteName(regPtr, actualName); + break; + } else if (!ValidateName(winPtr->dispPtr, actualName, w, 1)) { + RegDeleteName(regPtr, actualName); + break; + } + nextSuffix: + continue; + } + + /* + * We've now got a name to use. Store it in the name registry and + * in the local entry for this application, plus put it in a property + * on the commWindow. + */ + + RegAddName(regPtr, actualName, Tk_WindowId(dispPtr->commTkwin)); + RegClose(regPtr); + riPtr->name = (char *) ckalloc((unsigned) (strlen(actualName) + 1)); + strcpy(riPtr->name, actualName); + if (actualName != name) { + Tcl_DStringFree(&dString); + } + UpdateCommWindow(dispPtr); + + return riPtr->name; +} + +/* + *-------------------------------------------------------------- + * + * Tk_SendCmd -- + * + * This procedure is invoked to process the "send" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *-------------------------------------------------------------- + */ + +int +Tk_SendCmd(clientData, interp, argc, argv) + ClientData clientData; /* Information about sender (only + * dispPtr field is used). */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + TkWindow *winPtr; + Window commWindow; + PendingCommand pending; + register RegisteredInterp *riPtr; + char *destName, buffer[30]; + int result, c, async, i, firstArg; + size_t length; + Tk_RestrictProc *prevRestrictProc; + ClientData prevArg; + TkDisplay *dispPtr; + Tcl_Time timeout; + NameRegistry *regPtr; + Tcl_DString request; + Tcl_Interp *localInterp; /* Used when the interpreter to + * send the command to is within + * the same process. */ + + /* + * Process options, if any. + */ + + async = 0; + winPtr = (TkWindow *) Tk_MainWindow(interp); + if (winPtr == NULL) { + return TCL_ERROR; + } + for (i = 1; i < (argc-1); ) { + if (argv[i][0] != '-') { + break; + } + c = argv[i][1]; + length = strlen(argv[i]); + if ((c == 'a') && (strncmp(argv[i], "-async", length) == 0)) { + async = 1; + i++; + } else if ((c == 'd') && (strncmp(argv[i], "-displayof", + length) == 0)) { + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[i+1], + (Tk_Window) winPtr); + if (winPtr == NULL) { + return TCL_ERROR; + } + i += 2; + } else if (strcmp(argv[i], "--") == 0) { + i++; + break; + } else { + Tcl_AppendResult(interp, "bad option \"", argv[i], + "\": must be -async, -displayof, or --", (char *) NULL); + return TCL_ERROR; + } + } + + if (argc < (i+2)) { + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ?options? interpName arg ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + destName = argv[i]; + firstArg = i+1; + + dispPtr = winPtr->dispPtr; + if (dispPtr->commTkwin == NULL) { + SendInit(interp, winPtr->dispPtr); + } + + /* + * See if the target interpreter is local. If so, execute + * the command directly without going through the X server. + * The only tricky thing is passing the result from the target + * interpreter to the invoking interpreter. Watch out: they + * could be the same! + */ + + for (riPtr = registry; riPtr != NULL; riPtr = riPtr->nextPtr) { + if ((riPtr->dispPtr != dispPtr) + || (strcmp(riPtr->name, destName) != 0)) { + continue; + } + Tcl_Preserve((ClientData) riPtr); + localInterp = riPtr->interp; + Tcl_Preserve((ClientData) localInterp); + if (firstArg == (argc-1)) { + result = Tcl_GlobalEval(localInterp, argv[firstArg]); + } else { + Tcl_DStringInit(&request); + Tcl_DStringAppend(&request, argv[firstArg], -1); + for (i = firstArg+1; i < argc; i++) { + Tcl_DStringAppend(&request, " ", 1); + Tcl_DStringAppend(&request, argv[i], -1); + } + result = Tcl_GlobalEval(localInterp, Tcl_DStringValue(&request)); + Tcl_DStringFree(&request); + } + if (interp != localInterp) { + if (result == TCL_ERROR) { + + /* + * An error occurred, so transfer error information from the + * destination interpreter back to our interpreter. Must clear + * interp's result before calling Tcl_AddErrorInfo, since + * Tcl_AddErrorInfo will store the interp's result in errorInfo + * before appending riPtr's $errorInfo; we've already got + * everything we need in riPtr's $errorInfo. + */ + + Tcl_ResetResult(interp); + Tcl_AddErrorInfo(interp, Tcl_GetVar2(localInterp, + "errorInfo", (char *) NULL, TCL_GLOBAL_ONLY)); + Tcl_SetVar2(interp, "errorCode", (char *) NULL, + Tcl_GetVar2(localInterp, "errorCode", (char *) NULL, + TCL_GLOBAL_ONLY), TCL_GLOBAL_ONLY); + } + if (localInterp->freeProc != TCL_STATIC) { + interp->result = localInterp->result; + interp->freeProc = localInterp->freeProc; + localInterp->freeProc = TCL_STATIC; + } else { + Tcl_SetResult(interp, localInterp->result, TCL_VOLATILE); + } + Tcl_ResetResult(localInterp); + } + Tcl_Release((ClientData) riPtr); + Tcl_Release((ClientData) localInterp); + return result; + } + + /* + * Bind the interpreter name to a communication window. + */ + + regPtr = RegOpen(interp, winPtr->dispPtr, 0); + commWindow = RegFindName(regPtr, destName); + RegClose(regPtr); + if (commWindow == None) { + Tcl_AppendResult(interp, "no application named \"", + destName, "\"", (char *) NULL); + return TCL_ERROR; + } + + /* + * Send the command to the target interpreter by appending it to the + * comm window in the communication window. + */ + + tkSendSerial++; + Tcl_DStringInit(&request); + Tcl_DStringAppend(&request, "\0c\0-n ", 6); + Tcl_DStringAppend(&request, destName, -1); + if (!async) { + sprintf(buffer, "%x %d", + (unsigned int) Tk_WindowId(dispPtr->commTkwin), + tkSendSerial); + Tcl_DStringAppend(&request, "\0-r ", 4); + Tcl_DStringAppend(&request, buffer, -1); + } + Tcl_DStringAppend(&request, "\0-s ", 4); + Tcl_DStringAppend(&request, argv[firstArg], -1); + for (i = firstArg+1; i < argc; i++) { + Tcl_DStringAppend(&request, " ", 1); + Tcl_DStringAppend(&request, argv[i], -1); + } + (void) AppendPropCarefully(dispPtr->display, commWindow, + dispPtr->commProperty, Tcl_DStringValue(&request), + Tcl_DStringLength(&request) + 1, + (async) ? (PendingCommand *) NULL : &pending); + Tcl_DStringFree(&request); + if (async) { + /* + * This is an asynchronous send: return immediately without + * waiting for a response. + */ + + return TCL_OK; + } + + /* + * Register the fact that we're waiting for a command to complete + * (this is needed by SendEventProc and by AppendErrorProc to pass + * back the command's results). Set up a timeout handler so that + * we can check during long sends to make sure that the destination + * application is still alive. + */ + + pending.serial = tkSendSerial; + pending.dispPtr = dispPtr; + pending.target = destName; + pending.commWindow = commWindow; + pending.interp = interp; + pending.result = NULL; + pending.errorInfo = NULL; + pending.errorCode = NULL; + pending.gotResponse = 0; + pending.nextPtr = pendingCommands; + pendingCommands = &pending; + + /* + * Enter a loop processing X events until the result comes + * in or the target is declared to be dead. While waiting + * for a result, look only at send-related events so that + * the send is synchronous with respect to other events in + * the application. + */ + + prevRestrictProc = Tk_RestrictEvents(SendRestrictProc, + (ClientData) NULL, &prevArg); + TclpGetTime(&timeout); + timeout.sec += 2; + while (!pending.gotResponse) { + if (!TkUnixDoOneXEvent(&timeout)) { + /* + * An unusually long amount of time has elapsed during the + * processing of a sent command. Check to make sure that the + * target application still exists. If it does, reset the timeout. + */ + + if (!ValidateName(pending.dispPtr, pending.target, + pending.commWindow, 0)) { + char *msg; + if (ValidateName(pending.dispPtr, pending.target, + pending.commWindow, 1)) { + msg = "target application died or uses a Tk version before 4.0"; + } else { + msg = "target application died"; + } + pending.code = TCL_ERROR; + pending.result = (char *) ckalloc((unsigned) (strlen(msg) + 1)); + strcpy(pending.result, msg); + pending.gotResponse = 1; + } else { + TclpGetTime(&timeout); + timeout.sec += 2; + } + } + } + (void) Tk_RestrictEvents(prevRestrictProc, prevArg, &prevArg); + + /* + * Unregister the information about the pending command + * and return the result. + */ + + if (pendingCommands != &pending) { + panic("Tk_SendCmd: corrupted send stack"); + } + pendingCommands = pending.nextPtr; + if (pending.errorInfo != NULL) { + /* + * Special trick: must clear the interp's result before calling + * Tcl_AddErrorInfo, since Tcl_AddErrorInfo will store the interp's + * result in errorInfo before appending pending.errorInfo; we've + * already got everything we need in pending.errorInfo. + */ + + Tcl_ResetResult(interp); + Tcl_AddErrorInfo(interp, pending.errorInfo); + ckfree(pending.errorInfo); + } + if (pending.errorCode != NULL) { + Tcl_SetVar2(interp, "errorCode", (char *) NULL, pending.errorCode, + TCL_GLOBAL_ONLY); + ckfree(pending.errorCode); + } + Tcl_SetResult(interp, pending.result, TCL_DYNAMIC); + return pending.code; +} + +/* + *---------------------------------------------------------------------- + * + * TkGetInterpNames -- + * + * This procedure is invoked to fetch a list of all the + * interpreter names currently registered for the display + * of a particular window. + * + * Results: + * A standard Tcl return value. Interp->result will be set + * to hold a list of all the interpreter names defined for + * tkwin's display. If an error occurs, then TCL_ERROR + * is returned and interp->result will hold an error message. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkGetInterpNames(interp, tkwin) + Tcl_Interp *interp; /* Interpreter for returning a result. */ + Tk_Window tkwin; /* Window whose display is to be used + * for the lookup. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + char *p, *entry, *entryName; + NameRegistry *regPtr; + Window commWindow; + int count; + unsigned int id; + + /* + * Read the registry property, then scan through all of its entries. + * Validate each entry to be sure that its application still exists. + */ + + regPtr = RegOpen(interp, winPtr->dispPtr, 1); + for (p = regPtr->property; (p-regPtr->property) < (int) regPtr->propLength; ) { + entry = p; + if (sscanf(p, "%x",(unsigned int *) &id) != 1) { + commWindow = None; + } else { + commWindow = id; + } + while ((*p != 0) && (!isspace(UCHAR(*p)))) { + p++; + } + if (*p != 0) { + p++; + } + entryName = p; + while (*p != 0) { + p++; + } + p++; + if (ValidateName(winPtr->dispPtr, entryName, commWindow, 1)) { + /* + * The application still exists; add its name to the result. + */ + + Tcl_AppendElement(interp, entryName); + } else { + /* + * This name is bogus (perhaps the application died without + * cleaning up its entry in the registry?). Delete the name. + */ + + count = regPtr->propLength - (p - regPtr->property); + if (count > 0) { + char *src, *dst; + + for (src = p, dst = entry; count > 0; src++, dst++, count--) { + *dst = *src; + } + } + regPtr->propLength -= p - entry; + regPtr->modified = 1; + p = entry; + } + } + RegClose(regPtr); + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * SendInit -- + * + * This procedure is called to initialize the + * communication channels for sending commands and + * receiving results. + * + * Results: + * None. + * + * Side effects: + * Sets up various data structures and windows. + * + *-------------------------------------------------------------- + */ + +static int +SendInit(interp, dispPtr) + Tcl_Interp *interp; /* Interpreter to use for error reporting + * (no errors are ever returned, but the + * interpreter is needed anyway). */ + TkDisplay *dispPtr; /* Display to initialize. */ +{ + XSetWindowAttributes atts; + + /* + * Create the window used for communication, and set up an + * event handler for it. + */ + + dispPtr->commTkwin = Tk_CreateWindow(interp, (Tk_Window) NULL, + "_comm", DisplayString(dispPtr->display)); + if (dispPtr->commTkwin == NULL) { + panic("Tk_CreateWindow failed in SendInit!"); + } + atts.override_redirect = True; + Tk_ChangeWindowAttributes(dispPtr->commTkwin, + CWOverrideRedirect, &atts); + Tk_CreateEventHandler(dispPtr->commTkwin, PropertyChangeMask, + SendEventProc, (ClientData) dispPtr); + Tk_MakeWindowExist(dispPtr->commTkwin); + + /* + * Get atoms used as property names. + */ + + dispPtr->commProperty = Tk_InternAtom(dispPtr->commTkwin, "Comm"); + dispPtr->registryProperty = Tk_InternAtom(dispPtr->commTkwin, + "InterpRegistry"); + dispPtr->appNameProperty = Tk_InternAtom(dispPtr->commTkwin, + "TK_APPLICATION"); + + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * SendEventProc -- + * + * This procedure is invoked automatically by the toolkit + * event manager when a property changes on the communication + * window. This procedure reads the property and handles + * command requests and responses. + * + * Results: + * None. + * + * Side effects: + * If there are command requests in the property, they + * are executed. If there are responses in the property, + * their information is saved for the (ostensibly waiting) + * "send" commands. The property is deleted. + * + *-------------------------------------------------------------- + */ + +static void +SendEventProc(clientData, eventPtr) + ClientData clientData; /* Display information. */ + XEvent *eventPtr; /* Information about event. */ +{ + TkDisplay *dispPtr = (TkDisplay *) clientData; + char *propInfo; + register char *p; + int result, actualFormat; + unsigned long numItems, bytesAfter; + Atom actualType; + Tcl_Interp *remoteInterp; /* Interp in which to execute the command. */ + + if ((eventPtr->xproperty.atom != dispPtr->commProperty) + || (eventPtr->xproperty.state != PropertyNewValue)) { + return; + } + + /* + * Read the comm property and delete it. + */ + + propInfo = NULL; + result = XGetWindowProperty(dispPtr->display, + Tk_WindowId(dispPtr->commTkwin), + dispPtr->commProperty, 0, MAX_PROP_WORDS, True, + XA_STRING, &actualType, &actualFormat, + &numItems, &bytesAfter, (unsigned char **) &propInfo); + + /* + * If the property doesn't exist or is improperly formed + * then ignore it. + */ + + if ((result != Success) || (actualType != XA_STRING) + || (actualFormat != 8)) { + if (propInfo != NULL) { + XFree(propInfo); + } + return; + } + + /* + * Several commands and results could arrive in the property at + * one time; each iteration through the outer loop handles a + * single command or result. + */ + + for (p = propInfo; (p-propInfo) < (int) numItems; ) { + /* + * Ignore leading NULLs; each command or result starts with a + * NULL so that no matter how badly formed a preceding command + * is, we'll be able to tell that a new command/result is + * starting. + */ + + if (*p == 0) { + p++; + continue; + } + + if ((*p == 'c') && (p[1] == 0)) { + Window commWindow; + char *interpName, *script, *serial, *end; + Tcl_DString reply; + RegisteredInterp *riPtr; + + /* + *---------------------------------------------------------- + * This is an incoming command from some other application. + * Iterate over all of its options. Stop when we reach + * the end of the property or something that doesn't look + * like an option. + *---------------------------------------------------------- + */ + + p += 2; + interpName = NULL; + commWindow = None; + serial = ""; + script = NULL; + while (((p-propInfo) < (int) numItems) && (*p == '-')) { + switch (p[1]) { + case 'r': + commWindow = (Window) strtoul(p+2, &end, 16); + if ((end == p+2) || (*end != ' ')) { + commWindow = None; + } else { + p = serial = end+1; + } + break; + case 'n': + if (p[2] == ' ') { + interpName = p+3; + } + break; + case 's': + if (p[2] == ' ') { + script = p+3; + } + break; + } + while (*p != 0) { + p++; + } + p++; + } + + if ((script == NULL) || (interpName == NULL)) { + continue; + } + + /* + * Initialize the result property, so that we're ready at any + * time if we need to return an error. + */ + + if (commWindow != None) { + Tcl_DStringInit(&reply); + Tcl_DStringAppend(&reply, "\0r\0-s ", 6); + Tcl_DStringAppend(&reply, serial, -1); + Tcl_DStringAppend(&reply, "\0-r ", 4); + } + + if (!ServerSecure(dispPtr)) { + if (commWindow != None) { + Tcl_DStringAppend(&reply, "X server insecure (must use xauth-style authorization); command ignored", -1); + } + result = TCL_ERROR; + goto returnResult; + } + + /* + * Locate the application, then execute the script. + */ + + for (riPtr = registry; ; riPtr = riPtr->nextPtr) { + if (riPtr == NULL) { + if (commWindow != None) { + Tcl_DStringAppend(&reply, + "receiver never heard of interpreter \"", -1); + Tcl_DStringAppend(&reply, interpName, -1); + Tcl_DStringAppend(&reply, "\"", 1); + } + result = TCL_ERROR; + goto returnResult; + } + if (strcmp(riPtr->name, interpName) == 0) { + break; + } + } + Tcl_Preserve((ClientData) riPtr); + + /* + * We must protect the interpreter because the script may + * enter another event loop, which might call Tcl_DeleteInterp. + */ + + remoteInterp = riPtr->interp; + Tcl_Preserve((ClientData) remoteInterp); + + result = Tcl_GlobalEval(remoteInterp, script); + + /* + * The call to Tcl_Release may have released the interpreter + * which will cause the "send" command for that interpreter + * to be deleted. The command deletion callback will set the + * riPtr->interp field to NULL, hence the check below for NULL. + */ + + if (commWindow != None) { + Tcl_DStringAppend(&reply, remoteInterp->result, -1); + if (result == TCL_ERROR) { + char *varValue; + + varValue = Tcl_GetVar2(remoteInterp, "errorInfo", + (char *) NULL, TCL_GLOBAL_ONLY); + if (varValue != NULL) { + Tcl_DStringAppend(&reply, "\0-i ", 4); + Tcl_DStringAppend(&reply, varValue, -1); + } + varValue = Tcl_GetVar2(remoteInterp, "errorCode", + (char *) NULL, TCL_GLOBAL_ONLY); + if (varValue != NULL) { + Tcl_DStringAppend(&reply, "\0-e ", 4); + Tcl_DStringAppend(&reply, varValue, -1); + } + } + } + Tcl_Release((ClientData) remoteInterp); + Tcl_Release((ClientData) riPtr); + + /* + * Return the result to the sender if a commWindow was + * specified (if none was specified then this is an asynchronous + * call). Right now reply has everything but the completion + * code, but it needs the NULL to terminate the current option. + */ + + returnResult: + if (commWindow != None) { + if (result != TCL_OK) { + char buffer[20]; + + sprintf(buffer, "%d", result); + Tcl_DStringAppend(&reply, "\0-c ", 4); + Tcl_DStringAppend(&reply, buffer, -1); + } + (void) AppendPropCarefully(dispPtr->display, commWindow, + dispPtr->commProperty, Tcl_DStringValue(&reply), + Tcl_DStringLength(&reply) + 1, + (PendingCommand *) NULL); + XFlush(dispPtr->display); + Tcl_DStringFree(&reply); + } + } else if ((*p == 'r') && (p[1] == 0)) { + int serial, code, gotSerial; + char *errorInfo, *errorCode, *resultString; + PendingCommand *pcPtr; + + /* + *---------------------------------------------------------- + * This is a reply to some command that we sent out. Iterate + * over all of its options. Stop when we reach the end of the + * property or something that doesn't look like an option. + *---------------------------------------------------------- + */ + + p += 2; + code = TCL_OK; + gotSerial = 0; + errorInfo = NULL; + errorCode = NULL; + resultString = ""; + while (((p-propInfo) < (int) numItems) && (*p == '-')) { + switch (p[1]) { + case 'c': + if (sscanf(p+2, " %d", &code) != 1) { + code = TCL_OK; + } + break; + case 'e': + if (p[2] == ' ') { + errorCode = p+3; + } + break; + case 'i': + if (p[2] == ' ') { + errorInfo = p+3; + } + break; + case 'r': + if (p[2] == ' ') { + resultString = p+3; + } + break; + case 's': + if (sscanf(p+2, " %d", &serial) == 1) { + gotSerial = 1; + } + break; + } + while (*p != 0) { + p++; + } + p++; + } + + if (!gotSerial) { + continue; + } + + /* + * Give the result information to anyone who's + * waiting for it. + */ + + for (pcPtr = pendingCommands; pcPtr != NULL; + pcPtr = pcPtr->nextPtr) { + if ((serial != pcPtr->serial) || (pcPtr->result != NULL)) { + continue; + } + pcPtr->code = code; + if (resultString != NULL) { + pcPtr->result = (char *) ckalloc((unsigned) + (strlen(resultString) + 1)); + strcpy(pcPtr->result, resultString); + } + if (code == TCL_ERROR) { + if (errorInfo != NULL) { + pcPtr->errorInfo = (char *) ckalloc((unsigned) + (strlen(errorInfo) + 1)); + strcpy(pcPtr->errorInfo, errorInfo); + } + if (errorCode != NULL) { + pcPtr->errorCode = (char *) ckalloc((unsigned) + (strlen(errorCode) + 1)); + strcpy(pcPtr->errorCode, errorCode); + } + } + pcPtr->gotResponse = 1; + break; + } + } else { + /* + * Didn't recognize this thing. Just skip through the next + * null character and try again. + */ + + while (*p != 0) { + p++; + } + p++; + } + } + XFree(propInfo); +} + +/* + *-------------------------------------------------------------- + * + * AppendPropCarefully -- + * + * Append a given property to a given window, but set up + * an X error handler so that if the append fails this + * procedure can return an error code rather than having + * Xlib panic. + * + * Results: + * None. + * + * Side effects: + * The given property on the given window is appended to. + * If this operation fails and if pendingPtr is non-NULL, + * then the pending operation is marked as complete with + * an error. + * + *-------------------------------------------------------------- + */ + +static void +AppendPropCarefully(display, window, property, value, length, pendingPtr) + Display *display; /* Display on which to operate. */ + Window window; /* Window whose property is to + * be modified. */ + Atom property; /* Name of property. */ + char *value; /* Characters to append to property. */ + int length; /* Number of bytes to append. */ + PendingCommand *pendingPtr; /* Pending command to mark complete + * if an error occurs during the + * property op. NULL means just + * ignore the error. */ +{ + Tk_ErrorHandler handler; + + handler = Tk_CreateErrorHandler(display, -1, -1, -1, AppendErrorProc, + (ClientData) pendingPtr); + XChangeProperty(display, window, property, XA_STRING, 8, + PropModeAppend, (unsigned char *) value, length); + Tk_DeleteErrorHandler(handler); +} + +/* + * The procedure below is invoked if an error occurs during + * the XChangeProperty operation above. + */ + + /* ARGSUSED */ +static int +AppendErrorProc(clientData, errorPtr) + ClientData clientData; /* Command to mark complete, or NULL. */ + XErrorEvent *errorPtr; /* Information about error. */ +{ + PendingCommand *pendingPtr = (PendingCommand *) clientData; + register PendingCommand *pcPtr; + + if (pendingPtr == NULL) { + return 0; + } + + /* + * Make sure this command is still pending. + */ + + for (pcPtr = pendingCommands; pcPtr != NULL; + pcPtr = pcPtr->nextPtr) { + if ((pcPtr == pendingPtr) && (pcPtr->result == NULL)) { + pcPtr->result = (char *) ckalloc((unsigned) + (strlen(pcPtr->target) + 50)); + sprintf(pcPtr->result, "no application named \"%s\"", + pcPtr->target); + pcPtr->code = TCL_ERROR; + pcPtr->gotResponse = 1; + break; + } + } + return 0; +} + +/* + *-------------------------------------------------------------- + * + * DeleteProc -- + * + * This procedure is invoked by Tcl when the "send" command + * is deleted in an interpreter. It unregisters the interpreter. + * + * Results: + * None. + * + * Side effects: + * The interpreter given by riPtr is unregistered. + * + *-------------------------------------------------------------- + */ + +static void +DeleteProc(clientData) + ClientData clientData; /* Info about registration, passed + * as ClientData. */ +{ + RegisteredInterp *riPtr = (RegisteredInterp *) clientData; + register RegisteredInterp *riPtr2; + NameRegistry *regPtr; + + regPtr = RegOpen(riPtr->interp, riPtr->dispPtr, 1); + RegDeleteName(regPtr, riPtr->name); + RegClose(regPtr); + + if (registry == riPtr) { + registry = riPtr->nextPtr; + } else { + for (riPtr2 = registry; riPtr2 != NULL; + riPtr2 = riPtr2->nextPtr) { + if (riPtr2->nextPtr == riPtr) { + riPtr2->nextPtr = riPtr->nextPtr; + break; + } + } + } + ckfree((char *) riPtr->name); + riPtr->interp = NULL; + UpdateCommWindow(riPtr->dispPtr); + Tcl_EventuallyFree((ClientData) riPtr, TCL_DYNAMIC); +} + +/* + *---------------------------------------------------------------------- + * + * SendRestrictProc -- + * + * This procedure filters incoming events when a "send" command + * is outstanding. It defers all events except those containing + * send commands and results. + * + * Results: + * False is returned except for property-change events on a + * commWindow. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static Tk_RestrictAction +SendRestrictProc(clientData, eventPtr) + ClientData clientData; /* Not used. */ + register XEvent *eventPtr; /* Event that just arrived. */ +{ + TkDisplay *dispPtr; + + if (eventPtr->type != PropertyNotify) { + return TK_DEFER_EVENT; + } + for (dispPtr = tkDisplayList; dispPtr != NULL; dispPtr = dispPtr->nextPtr) { + if ((eventPtr->xany.display == dispPtr->display) + && (eventPtr->xproperty.window + == Tk_WindowId(dispPtr->commTkwin))) { + return TK_PROCESS_EVENT; + } + } + return TK_DEFER_EVENT; +} + +/* + *---------------------------------------------------------------------- + * + * UpdateCommWindow -- + * + * This procedure updates the list of application names stored + * on our commWindow. It is typically called when interpreters + * are registered and unregistered. + * + * Results: + * None. + * + * Side effects: + * The TK_APPLICATION property on the comm window is updated. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateCommWindow(dispPtr) + TkDisplay *dispPtr; /* Display whose commWindow is to be + * updated. */ +{ + Tcl_DString names; + RegisteredInterp *riPtr; + + Tcl_DStringInit(&names); + for (riPtr = registry; riPtr != NULL; riPtr = riPtr->nextPtr) { + Tcl_DStringAppendElement(&names, riPtr->name); + } + XChangeProperty(dispPtr->display, Tk_WindowId(dispPtr->commTkwin), + dispPtr->appNameProperty, XA_STRING, 8, PropModeReplace, + (unsigned char *) Tcl_DStringValue(&names), + Tcl_DStringLength(&names)); + Tcl_DStringFree(&names); +} diff --git a/unix/tkUnixWm.c b/unix/tkUnixWm.c new file mode 100644 index 0000000..0c26c9b --- /dev/null +++ b/unix/tkUnixWm.c @@ -0,0 +1,4813 @@ +/* + * tkUnixWm.c -- + * + * This module takes care of the interactions between a Tk-based + * application and the window manager. Among other things, it + * implements the "wm" command and passes geometry information + * to the window manager. + * + * Copyright (c) 1991-1994 The Regents of the University of California. + * Copyright (c) 1994-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixWm.c 1.155 97/10/28 08:35:19 + */ + +#include "tkPort.h" +#include "tkInt.h" +#include "tkUnixInt.h" +#include <errno.h> + +/* + * A data structure of the following type holds information for + * each window manager protocol (such as WM_DELETE_WINDOW) for + * which a handler (i.e. a Tcl command) has been defined for a + * particular top-level window. + */ + +typedef struct ProtocolHandler { + Atom protocol; /* Identifies the protocol. */ + struct ProtocolHandler *nextPtr; + /* Next in list of protocol handlers for + * the same top-level window, or NULL for + * end of list. */ + Tcl_Interp *interp; /* Interpreter in which to invoke command. */ + char command[4]; /* Tcl command to invoke when a client + * message for this protocol arrives. + * The actual size of the structure varies + * to accommodate the needs of the actual + * command. THIS MUST BE THE LAST FIELD OF + * THE STRUCTURE. */ +} ProtocolHandler; + +#define HANDLER_SIZE(cmdLength) \ + ((unsigned) (sizeof(ProtocolHandler) - 3 + cmdLength)) + +/* + * A data structure of the following type holds window-manager-related + * information for each top-level window in an application. + */ + +typedef struct TkWmInfo { + TkWindow *winPtr; /* Pointer to main Tk information for + * this window. */ + Window reparent; /* If the window has been reparented, this + * gives the ID of the ancestor of the window + * that is a child of the root window (may + * not be window's immediate parent). If + * the window isn't reparented, this has the + * value None. */ + char *title; /* Title to display in window caption. If + * NULL, use name of widget. Malloced. */ + char *iconName; /* Name to display in icon. Malloced. */ + Window master; /* Master window for TRANSIENT_FOR property, + * or None. */ + XWMHints hints; /* Various pieces of information for + * window manager. */ + char *leaderName; /* Path name of leader of window group + * (corresponds to hints.window_group). + * Malloc-ed. Note: this field doesn't + * get updated if leader is destroyed. */ + char *masterWindowName; /* Path name of window specified as master + * in "wm transient" command, or NULL. + * Malloc-ed. Note: this field doesn't + * get updated if masterWindowName is + * destroyed. */ + Tk_Window icon; /* Window to use as icon for this window, + * or NULL. */ + Tk_Window iconFor; /* Window for which this window is icon, or + * NULL if this isn't an icon for anyone. */ + int withdrawn; /* Non-zero means window has been withdrawn. */ + + /* + * In order to support menubars transparently under X, each toplevel + * window is encased in an additional window, called the wrapper, + * that holds the toplevel and the menubar, if any. The information + * below is used to keep track of the wrapper and the menubar. + */ + + TkWindow *wrapperPtr; /* Pointer to information about the wrapper. + * This is the "real" toplevel window as + * seen by the window manager. Although + * this is an official Tk window, it + * doesn't appear in the application's + * window hierarchy. NULL means that + * the wrapper hasn't been created yet. */ + Tk_Window menubar; /* Pointer to information about the + * menubar, or NULL if there is no + * menubar for this toplevel. */ + int menuHeight; /* Amount of vertical space needed for + * menubar, measured in pixels. If + * menubar is non-NULL, this is >= 1 (X + * servers don't like dimensions of 0). */ + + /* + * Information used to construct an XSizeHints structure for + * the window manager: + */ + + int sizeHintsFlags; /* Flags word for XSizeHints structure. + * If the PBaseSize flag is set then the + * window is gridded; otherwise it isn't + * gridded. */ + int minWidth, minHeight; /* Minimum dimensions of window, in + * grid units, not pixels. */ + int maxWidth, maxHeight; /* Maximum dimensions of window, in + * grid units, not pixels. */ + Tk_Window gridWin; /* Identifies the window that controls + * gridding for this top-level, or NULL if + * the top-level isn't currently gridded. */ + int widthInc, heightInc; /* Increments for size changes (# pixels + * per step). */ + struct { + int x; /* numerator */ + int y; /* denominator */ + } minAspect, maxAspect; /* Min/max aspect ratios for window. */ + int reqGridWidth, reqGridHeight; + /* The dimensions of the window (in + * grid units) requested through + * the geometry manager. */ + int gravity; /* Desired window gravity. */ + + /* + * Information used to manage the size and location of a window. + */ + + int width, height; /* Desired dimensions of window, specified + * in grid units. These values are + * set by the "wm geometry" command and by + * ConfigureNotify events (for when wm + * resizes window). -1 means user hasn't + * requested dimensions. */ + int x, y; /* Desired X and Y coordinates for window. + * These values are set by "wm geometry", + * plus by ConfigureNotify events (when wm + * moves window). These numbers are + * different than the numbers stored in + * winPtr->changes because (a) they could be + * measured from the right or bottom edge + * of the screen (see WM_NEGATIVE_X and + * WM_NEGATIVE_Y flags) and (b) if the window + * has been reparented then they refer to the + * parent rather than the window itself. */ + int parentWidth, parentHeight; + /* Width and height of reparent, in pixels + * *including border*. If window hasn't been + * reparented then these will be the outer + * dimensions of the window, including + * border. */ + int xInParent, yInParent; /* Offset of wrapperPtr within reparent, + * measured in pixels from upper-left outer + * corner of reparent's border to upper-left + * outer corner of wrapperPtr's border. If + * not reparented then these are zero. */ + int configWidth, configHeight; + /* Dimensions passed to last request that we + * issued to change geometry of the wrapper. + * Used to eliminate redundant resize + * operations. */ + + /* + * Information about the virtual root window for this top-level, + * if there is one. + */ + + Window vRoot; /* Virtual root window for this top-level, + * or None if there is no virtual root + * window (i.e. just use the screen's root). */ + int vRootX, vRootY; /* Position of the virtual root inside the + * root window. If the WM_VROOT_OFFSET_STALE + * flag is set then this information may be + * incorrect and needs to be refreshed from + * the X server. If vRoot is None then these + * values are both 0. */ + int vRootWidth, vRootHeight;/* Dimensions of the virtual root window. + * If vRoot is None, gives the dimensions + * of the containing screen. This information + * is never stale, even though vRootX and + * vRootY can be. */ + + /* + * Miscellaneous information. + */ + + ProtocolHandler *protPtr; /* First in list of protocol handlers for + * this window (NULL means none). */ + int cmdArgc; /* Number of elements in cmdArgv below. */ + char **cmdArgv; /* Array of strings to store in the + * WM_COMMAND property. NULL means nothing + * available. */ + char *clientMachine; /* String to store in WM_CLIENT_MACHINE + * property, or NULL. */ + int flags; /* Miscellaneous flags, defined below. */ + struct TkWmInfo *nextPtr; /* Next in list of all top-level windows. */ +} WmInfo; + +/* + * Flag values for WmInfo structures: + * + * WM_NEVER_MAPPED - non-zero means window has never been + * mapped; need to update all info when + * window is first mapped. + * WM_UPDATE_PENDING - non-zero means a call to UpdateGeometryInfo + * has already been scheduled for this + * window; no need to schedule another one. + * WM_NEGATIVE_X - non-zero means x-coordinate is measured in + * pixels from right edge of screen, rather + * than from left edge. + * WM_NEGATIVE_Y - non-zero means y-coordinate is measured in + * pixels up from bottom of screen, rather than + * down from top. + * WM_UPDATE_SIZE_HINTS - non-zero means that new size hints need to be + * propagated to window manager. + * WM_SYNC_PENDING - set to non-zero while waiting for the window + * manager to respond to some state change. + * WM_VROOT_OFFSET_STALE - non-zero means that (x,y) offset information + * about the virtual root window is stale and + * needs to be fetched fresh from the X server. + * WM_ABOUT_TO_MAP - non-zero means that the window is about to + * be mapped by TkWmMapWindow. This is used + * by UpdateGeometryInfo to modify its behavior. + * WM_MOVE_PENDING - non-zero means the application has requested + * a new position for the window, but it hasn't + * been reflected through the window manager + * yet. + * WM_COLORMAPS_EXPLICIT - non-zero means the colormap windows were + * set explicitly via "wm colormapwindows". + * WM_ADDED_TOPLEVEL_COLORMAP - non-zero means that when "wm colormapwindows" + * was called the top-level itself wasn't + * specified, so we added it implicitly at + * the end of the list. + * WM_WIDTH_NOT_RESIZABLE - non-zero means that we're not supposed to + * allow the user to change the width of the + * window (controlled by "wm resizable" + * command). + * WM_HEIGHT_NOT_RESIZABLE - non-zero means that we're not supposed to + * allow the user to change the height of the + * window (controlled by "wm resizable" + * command). + */ + +#define WM_NEVER_MAPPED 1 +#define WM_UPDATE_PENDING 2 +#define WM_NEGATIVE_X 4 +#define WM_NEGATIVE_Y 8 +#define WM_UPDATE_SIZE_HINTS 0x10 +#define WM_SYNC_PENDING 0x20 +#define WM_VROOT_OFFSET_STALE 0x40 +#define WM_ABOUT_TO_MAP 0x100 +#define WM_MOVE_PENDING 0x200 +#define WM_COLORMAPS_EXPLICIT 0x400 +#define WM_ADDED_TOPLEVEL_COLORMAP 0x800 +#define WM_WIDTH_NOT_RESIZABLE 0x1000 +#define WM_HEIGHT_NOT_RESIZABLE 0x2000 + +/* + * This module keeps a list of all top-level windows, primarily to + * simplify the job of Tk_CoordsToWindow. + */ + +static WmInfo *firstWmPtr = NULL; /* Points to first top-level window. */ + + +/* + * The variable below is used to enable or disable tracing in this + * module. If tracing is enabled, then information is printed on + * standard output about interesting interactions with the window + * manager. + */ + +static int wmTracing = 0; + +/* + * The following structures are the official type records for geometry + * management of top-level and menubar windows. + */ + +static void TopLevelReqProc _ANSI_ARGS_((ClientData dummy, + Tk_Window tkwin)); + +static Tk_GeomMgr wmMgrType = { + "wm", /* name */ + TopLevelReqProc, /* requestProc */ + (Tk_GeomLostSlaveProc *) NULL, /* lostSlaveProc */ +}; + +static void MenubarReqProc _ANSI_ARGS_((ClientData clientData, + Tk_Window tkwin)); + +static Tk_GeomMgr menubarMgrType = { + "menubar", /* name */ + MenubarReqProc, /* requestProc */ + (Tk_GeomLostSlaveProc *) NULL, /* lostSlaveProc */ +}; + +/* + * Structures of the following type are used for communication between + * WaitForEvent, WaitRestrictProc, and WaitTimeoutProc. + */ + +typedef struct WaitRestrictInfo { + Display *display; /* Window belongs to this display. */ + Window window; /* We're waiting for events on this window. */ + int type; /* We only care about this type of event. */ + XEvent *eventPtr; /* Where to store the event when it's found. */ + int foundEvent; /* Non-zero means that an event of the + * desired type has been found. */ +} WaitRestrictInfo; + +/* + * Forward declarations for procedures defined in this file: + */ + +static int ComputeReparentGeometry _ANSI_ARGS_((WmInfo *wmPtr)); +static void ConfigureEvent _ANSI_ARGS_((WmInfo *wmPtr, + XConfigureEvent *eventPtr)); +static void CreateWrapper _ANSI_ARGS_((WmInfo *wmPtr)); +static void GetMaxSize _ANSI_ARGS_((WmInfo *wmPtr, + int *maxWidthPtr, int *maxHeightPtr)); +static void MenubarDestroyProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static int ParseGeometry _ANSI_ARGS_((Tcl_Interp *interp, + char *string, TkWindow *winPtr)); +static void ReparentEvent _ANSI_ARGS_((WmInfo *wmPtr, + XReparentEvent *eventPtr)); +static void TopLevelReqProc _ANSI_ARGS_((ClientData dummy, + Tk_Window tkwin)); +static void UpdateGeometryInfo _ANSI_ARGS_(( + ClientData clientData)); +static void UpdateHints _ANSI_ARGS_((TkWindow *winPtr)); +static void UpdateSizeHints _ANSI_ARGS_((TkWindow *winPtr)); +static void UpdateVRootGeometry _ANSI_ARGS_((WmInfo *wmPtr)); +static void UpdateWmProtocols _ANSI_ARGS_((WmInfo *wmPtr)); +static void WaitForConfigureNotify _ANSI_ARGS_((TkWindow *winPtr, + unsigned long serial)); +static int WaitForEvent _ANSI_ARGS_((Display *display, + Window window, int type, XEvent *eventPtr)); +static void WaitForMapNotify _ANSI_ARGS_((TkWindow *winPtr, + int mapped)); +static Tk_RestrictAction + WaitRestrictProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void WrapperEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); + +/* + *-------------------------------------------------------------- + * + * TkWmNewWindow -- + * + * This procedure is invoked whenever a new top-level + * window is created. Its job is to initialize the WmInfo + * structure for the window. + * + * Results: + * None. + * + * Side effects: + * A WmInfo structure gets allocated and initialized. + * + *-------------------------------------------------------------- + */ + +void +TkWmNewWindow(winPtr) + TkWindow *winPtr; /* Newly-created top-level window. */ +{ + register WmInfo *wmPtr; + + wmPtr = (WmInfo *) ckalloc(sizeof(WmInfo)); + wmPtr->winPtr = winPtr; + wmPtr->reparent = None; + wmPtr->title = NULL; + wmPtr->iconName = NULL; + wmPtr->master = None; + wmPtr->hints.flags = InputHint | StateHint; + wmPtr->hints.input = True; + wmPtr->hints.initial_state = NormalState; + wmPtr->hints.icon_pixmap = None; + wmPtr->hints.icon_window = None; + wmPtr->hints.icon_x = wmPtr->hints.icon_y = 0; + wmPtr->hints.icon_mask = None; + wmPtr->hints.window_group = None; + wmPtr->leaderName = NULL; + wmPtr->masterWindowName = NULL; + wmPtr->icon = NULL; + wmPtr->iconFor = NULL; + wmPtr->withdrawn = 0; + wmPtr->wrapperPtr = NULL; + wmPtr->menubar = NULL; + wmPtr->menuHeight = 0; + wmPtr->sizeHintsFlags = 0; + wmPtr->minWidth = wmPtr->minHeight = 1; + + /* + * Default the maximum dimensions to the size of the display, minus + * a guess about how space is needed for window manager decorations. + */ + + wmPtr->maxWidth = 0; + wmPtr->maxHeight = 0; + wmPtr->gridWin = NULL; + wmPtr->widthInc = wmPtr->heightInc = 1; + wmPtr->minAspect.x = wmPtr->minAspect.y = 1; + wmPtr->maxAspect.x = wmPtr->maxAspect.y = 1; + wmPtr->reqGridWidth = wmPtr->reqGridHeight = -1; + wmPtr->gravity = NorthWestGravity; + wmPtr->width = -1; + wmPtr->height = -1; + wmPtr->x = winPtr->changes.x; + wmPtr->y = winPtr->changes.y; + wmPtr->parentWidth = winPtr->changes.width + + 2*winPtr->changes.border_width; + wmPtr->parentHeight = winPtr->changes.height + + 2*winPtr->changes.border_width; + wmPtr->xInParent = wmPtr->yInParent = 0; + wmPtr->configWidth = -1; + wmPtr->configHeight = -1; + wmPtr->vRoot = None; + wmPtr->protPtr = NULL; + wmPtr->cmdArgv = NULL; + wmPtr->clientMachine = NULL; + wmPtr->flags = WM_NEVER_MAPPED; + wmPtr->nextPtr = firstWmPtr; + firstWmPtr = wmPtr; + winPtr->wmInfoPtr = wmPtr; + + UpdateVRootGeometry(wmPtr); + + /* + * Arrange for geometry requests to be reflected from the window + * to the window manager. + */ + + Tk_ManageGeometry((Tk_Window) winPtr, &wmMgrType, (ClientData) 0); +} + +/* + *-------------------------------------------------------------- + * + * TkWmMapWindow -- + * + * This procedure is invoked to map a top-level window. This + * module gets a chance to update all window-manager-related + * information in properties before the window manager sees + * the map event and checks the properties. It also gets to + * decide whether or not to even map the window after all. + * + * Results: + * None. + * + * Side effects: + * Properties of winPtr may get updated to provide up-to-date + * information to the window manager. The window may also get + * mapped, but it may not be if this procedure decides that + * isn't appropriate (e.g. because the window is withdrawn). + * + *-------------------------------------------------------------- + */ + +void +TkWmMapWindow(winPtr) + TkWindow *winPtr; /* Top-level window that's about to + * be mapped. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + XTextProperty textProp; + char *string; + + if (wmPtr->flags & WM_NEVER_MAPPED) { + wmPtr->flags &= ~WM_NEVER_MAPPED; + + /* + * This is the first time this window has ever been mapped. + * First create the wrapper window that provides space for a + * menubar. + */ + + if (wmPtr->wrapperPtr == NULL) { + CreateWrapper(wmPtr); + } + + /* + * Store all the window-manager-related information for the + * window. + */ + + string = (wmPtr->title != NULL) ? wmPtr->title : winPtr->nameUid; + if (XStringListToTextProperty(&string, 1, &textProp) != 0) { + XSetWMName(winPtr->display, wmPtr->wrapperPtr->window, &textProp); + XFree((char *) textProp.value); + } + + TkWmSetClass(winPtr); + + if (wmPtr->iconName != NULL) { + XSetIconName(winPtr->display, wmPtr->wrapperPtr->window, + wmPtr->iconName); + } + + if (wmPtr->master != None) { + XSetTransientForHint(winPtr->display, wmPtr->wrapperPtr->window, + wmPtr->master); + } + + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + UpdateHints(winPtr); + UpdateWmProtocols(wmPtr); + if (wmPtr->cmdArgv != NULL) { + XSetCommand(winPtr->display, wmPtr->wrapperPtr->window, + wmPtr->cmdArgv, wmPtr->cmdArgc); + } + if (wmPtr->clientMachine != NULL) { + if (XStringListToTextProperty(&wmPtr->clientMachine, 1, &textProp) + != 0) { + XSetWMClientMachine(winPtr->display, wmPtr->wrapperPtr->window, + &textProp); + XFree((char *) textProp.value); + } + } + } + if (wmPtr->hints.initial_state == WithdrawnState) { + return; + } + if (wmPtr->iconFor != NULL) { + /* + * This window is an icon for somebody else. Make sure that + * the geometry is up-to-date, then return without mapping + * the window. + */ + + if (wmPtr->flags & WM_UPDATE_PENDING) { + Tcl_CancelIdleCall(UpdateGeometryInfo, (ClientData) winPtr); + } + UpdateGeometryInfo((ClientData) winPtr); + return; + } + wmPtr->flags |= WM_ABOUT_TO_MAP; + if (wmPtr->flags & WM_UPDATE_PENDING) { + Tcl_CancelIdleCall(UpdateGeometryInfo, (ClientData) winPtr); + } + UpdateGeometryInfo((ClientData) winPtr); + wmPtr->flags &= ~WM_ABOUT_TO_MAP; + + /* + * Map the window, then wait to be sure that the window manager has + * processed the map operation. + */ + + XMapWindow(winPtr->display, wmPtr->wrapperPtr->window); + if (wmPtr->hints.initial_state == NormalState) { + WaitForMapNotify(winPtr, 1); + } +} + +/* + *-------------------------------------------------------------- + * + * TkWmUnmapWindow -- + * + * This procedure is invoked to unmap a top-level window. The + * only thing it does special is to wait for the window actually + * to be unmapped. + * + * Results: + * None. + * + * Side effects: + * Unmaps the window. + * + *-------------------------------------------------------------- + */ + +void +TkWmUnmapWindow(winPtr) + TkWindow *winPtr; /* Top-level window that's about to + * be mapped. */ +{ + /* + * It seems to be important to wait after unmapping a top-level + * window until the window really gets unmapped. I don't completely + * understand all the interactions with the window manager, but if + * we go on without waiting, and if the window is then mapped again + * quickly, events seem to get lost so that we think the window isn't + * mapped when in fact it is mapped. I suspect that this has something + * to do with the window manager filtering Map events (and possily not + * filtering Unmap events?). + */ + XUnmapWindow(winPtr->display, winPtr->wmInfoPtr->wrapperPtr->window); + WaitForMapNotify(winPtr, 0); +} + +/* + *-------------------------------------------------------------- + * + * TkWmDeadWindow -- + * + * This procedure is invoked when a top-level window is + * about to be deleted. It cleans up the wm-related data + * structures for the window. + * + * Results: + * None. + * + * Side effects: + * The WmInfo structure for winPtr gets freed up. + * + *-------------------------------------------------------------- + */ + +void +TkWmDeadWindow(winPtr) + TkWindow *winPtr; /* Top-level window that's being deleted. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + WmInfo *wmPtr2; + + if (wmPtr == NULL) { + return; + } + if (firstWmPtr == wmPtr) { + firstWmPtr = wmPtr->nextPtr; + } else { + register WmInfo *prevPtr; + + for (prevPtr = firstWmPtr; ; prevPtr = prevPtr->nextPtr) { + if (prevPtr == NULL) { + panic("couldn't unlink window in TkWmDeadWindow"); + } + if (prevPtr->nextPtr == wmPtr) { + prevPtr->nextPtr = wmPtr->nextPtr; + break; + } + } + } + if (wmPtr->title != NULL) { + ckfree(wmPtr->title); + } + if (wmPtr->iconName != NULL) { + ckfree(wmPtr->iconName); + } + if (wmPtr->hints.flags & IconPixmapHint) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_pixmap); + } + if (wmPtr->hints.flags & IconMaskHint) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_mask); + } + if (wmPtr->leaderName != NULL) { + ckfree(wmPtr->leaderName); + } + if (wmPtr->masterWindowName != NULL) { + ckfree(wmPtr->masterWindowName); + } + if (wmPtr->icon != NULL) { + wmPtr2 = ((TkWindow *) wmPtr->icon)->wmInfoPtr; + wmPtr2->iconFor = NULL; + wmPtr2->withdrawn = 1; + } + if (wmPtr->iconFor != NULL) { + wmPtr2 = ((TkWindow *) wmPtr->iconFor)->wmInfoPtr; + wmPtr2->icon = NULL; + wmPtr2->hints.flags &= ~IconWindowHint; + UpdateHints((TkWindow *) wmPtr->iconFor); + } + if (wmPtr->menubar != NULL) { + Tk_DestroyWindow(wmPtr->menubar); + } + if (wmPtr->wrapperPtr != NULL) { + /* + * The rest of Tk doesn't know that we reparent the toplevel + * inside the wrapper, so reparent it back out again before + * deleting the wrapper; otherwise the toplevel will get deleted + * twice (once implicitly by the deletion of the wrapper). + */ + + XUnmapWindow(winPtr->display, winPtr->window); + XReparentWindow(winPtr->display, winPtr->window, + XRootWindow(winPtr->display, winPtr->screenNum), 0, 0); + Tk_DestroyWindow((Tk_Window) wmPtr->wrapperPtr); + } + while (wmPtr->protPtr != NULL) { + ProtocolHandler *protPtr; + + protPtr = wmPtr->protPtr; + wmPtr->protPtr = protPtr->nextPtr; + Tcl_EventuallyFree((ClientData) protPtr, TCL_DYNAMIC); + } + if (wmPtr->cmdArgv != NULL) { + ckfree((char *) wmPtr->cmdArgv); + } + if (wmPtr->clientMachine != NULL) { + ckfree((char *) wmPtr->clientMachine); + } + if (wmPtr->flags & WM_UPDATE_PENDING) { + Tcl_CancelIdleCall(UpdateGeometryInfo, (ClientData) winPtr); + } + ckfree((char *) wmPtr); + winPtr->wmInfoPtr = NULL; +} + +/* + *-------------------------------------------------------------- + * + * TkWmSetClass -- + * + * This procedure is invoked whenever a top-level window's + * class is changed. If the window has been mapped then this + * procedure updates the window manager property for the + * class. If the window hasn't been mapped, the update is + * deferred until just before the first mapping. + * + * Results: + * None. + * + * Side effects: + * A window property may get updated. + * + *-------------------------------------------------------------- + */ + +void +TkWmSetClass(winPtr) + TkWindow *winPtr; /* Newly-created top-level window. */ +{ + if (winPtr->wmInfoPtr->flags & WM_NEVER_MAPPED) { + return; + } + + if (winPtr->classUid != NULL) { + XClassHint *classPtr; + + classPtr = XAllocClassHint(); + classPtr->res_name = winPtr->nameUid; + classPtr->res_class = winPtr->classUid; + XSetClassHint(winPtr->display, winPtr->wmInfoPtr->wrapperPtr->window, + classPtr); + XFree((char *) classPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_WmCmd -- + * + * This procedure is invoked to process the "wm" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +Tk_WmCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + TkWindow *winPtr; + register WmInfo *wmPtr; + int c; + size_t length; + + if (argc < 2) { + wrongNumArgs: + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option window ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 't') && (strncmp(argv[1], "tracing", length) == 0) + && (length >= 3)) { + if ((argc != 2) && (argc != 3)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " tracing ?boolean?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 2) { + interp->result = (wmTracing) ? "on" : "off"; + return TCL_OK; + } + return Tcl_GetBoolean(interp, argv[2], &wmTracing); + } + + if (argc < 3) { + goto wrongNumArgs; + } + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[2], tkwin); + if (winPtr == NULL) { + return TCL_ERROR; + } + if (!(winPtr->flags & TK_TOP_LEVEL)) { + Tcl_AppendResult(interp, "window \"", winPtr->pathName, + "\" isn't a top-level window", (char *) NULL); + return TCL_ERROR; + } + wmPtr = winPtr->wmInfoPtr; + if ((c == 'a') && (strncmp(argv[1], "aspect", length) == 0)) { + int numer1, denom1, numer2, denom2; + + if ((argc != 3) && (argc != 7)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " aspect window ?minNumer minDenom ", + "maxNumer maxDenom?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & PAspect) { + sprintf(interp->result, "%d %d %d %d", wmPtr->minAspect.x, + wmPtr->minAspect.y, wmPtr->maxAspect.x, + wmPtr->maxAspect.y); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->sizeHintsFlags &= ~PAspect; + } else { + if ((Tcl_GetInt(interp, argv[3], &numer1) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &denom1) != TCL_OK) + || (Tcl_GetInt(interp, argv[5], &numer2) != TCL_OK) + || (Tcl_GetInt(interp, argv[6], &denom2) != TCL_OK)) { + return TCL_ERROR; + } + if ((numer1 <= 0) || (denom1 <= 0) || (numer2 <= 0) || + (denom2 <= 0)) { + interp->result = "aspect number can't be <= 0"; + return TCL_ERROR; + } + wmPtr->minAspect.x = numer1; + wmPtr->minAspect.y = denom1; + wmPtr->maxAspect.x = numer2; + wmPtr->maxAspect.y = denom2; + wmPtr->sizeHintsFlags |= PAspect; + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 'c') && (strncmp(argv[1], "client", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " client window ?name?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->clientMachine != NULL) { + interp->result = wmPtr->clientMachine; + } + return TCL_OK; + } + if (argv[3][0] == 0) { + if (wmPtr->clientMachine != NULL) { + ckfree((char *) wmPtr->clientMachine); + wmPtr->clientMachine = NULL; + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XDeleteProperty(winPtr->display, wmPtr->wrapperPtr->window, + Tk_InternAtom((Tk_Window) winPtr, + "WM_CLIENT_MACHINE")); + } + } + return TCL_OK; + } + if (wmPtr->clientMachine != NULL) { + ckfree((char *) wmPtr->clientMachine); + } + wmPtr->clientMachine = (char *) + ckalloc((unsigned) (strlen(argv[3]) + 1)); + strcpy(wmPtr->clientMachine, argv[3]); + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XTextProperty textProp; + if (XStringListToTextProperty(&wmPtr->clientMachine, 1, &textProp) + != 0) { + XSetWMClientMachine(winPtr->display, wmPtr->wrapperPtr->window, + &textProp); + XFree((char *) textProp.value); + } + } + } else if ((c == 'c') && (strncmp(argv[1], "colormapwindows", length) == 0) + && (length >= 3)) { + Window *cmapList; + TkWindow *winPtr2; + int count, i, windowArgc, gotToplevel; + char buffer[20], **windowArgv; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " colormapwindows window ?windowList?\"", + (char *) NULL); + return TCL_ERROR; + } + Tk_MakeWindowExist((Tk_Window) winPtr); + if (wmPtr->wrapperPtr == NULL) { + CreateWrapper(wmPtr); + } + if (argc == 3) { + if (XGetWMColormapWindows(winPtr->display, + wmPtr->wrapperPtr->window, &cmapList, &count) == 0) { + return TCL_OK; + } + for (i = 0; i < count; i++) { + if ((i == (count-1)) + && (wmPtr->flags & WM_ADDED_TOPLEVEL_COLORMAP)) { + break; + } + winPtr2 = (TkWindow *) Tk_IdToWindow(winPtr->display, + cmapList[i]); + if (winPtr2 == NULL) { + sprintf(buffer, "0x%lx", cmapList[i]); + Tcl_AppendElement(interp, buffer); + } else { + Tcl_AppendElement(interp, winPtr2->pathName); + } + } + XFree((char *) cmapList); + return TCL_OK; + } + if (Tcl_SplitList(interp, argv[3], &windowArgc, &windowArgv) + != TCL_OK) { + return TCL_ERROR; + } + cmapList = (Window *) ckalloc((unsigned) + ((windowArgc+1)*sizeof(Window))); + gotToplevel = 0; + for (i = 0; i < windowArgc; i++) { + winPtr2 = (TkWindow *) Tk_NameToWindow(interp, windowArgv[i], + tkwin); + if (winPtr2 == NULL) { + ckfree((char *) cmapList); + ckfree((char *) windowArgv); + return TCL_ERROR; + } + if (winPtr2 == winPtr) { + gotToplevel = 1; + } + if (winPtr2->window == None) { + Tk_MakeWindowExist((Tk_Window) winPtr2); + } + cmapList[i] = winPtr2->window; + } + if (!gotToplevel) { + wmPtr->flags |= WM_ADDED_TOPLEVEL_COLORMAP; + cmapList[windowArgc] = wmPtr->wrapperPtr->window; + windowArgc++; + } else { + wmPtr->flags &= ~WM_ADDED_TOPLEVEL_COLORMAP; + } + wmPtr->flags |= WM_COLORMAPS_EXPLICIT; + XSetWMColormapWindows(winPtr->display, wmPtr->wrapperPtr->window, + cmapList, windowArgc); + ckfree((char *) cmapList); + ckfree((char *) windowArgv); + return TCL_OK; + } else if ((c == 'c') && (strncmp(argv[1], "command", length) == 0) + && (length >= 3)) { + int cmdArgc; + char **cmdArgv; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " command window ?value?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->cmdArgv != NULL) { + interp->result = Tcl_Merge(wmPtr->cmdArgc, wmPtr->cmdArgv); + interp->freeProc = TCL_DYNAMIC; + } + return TCL_OK; + } + if (argv[3][0] == 0) { + if (wmPtr->cmdArgv != NULL) { + ckfree((char *) wmPtr->cmdArgv); + wmPtr->cmdArgv = NULL; + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XDeleteProperty(winPtr->display, wmPtr->wrapperPtr->window, + Tk_InternAtom((Tk_Window) winPtr, "WM_COMMAND")); + } + } + return TCL_OK; + } + if (Tcl_SplitList(interp, argv[3], &cmdArgc, &cmdArgv) != TCL_OK) { + return TCL_ERROR; + } + if (wmPtr->cmdArgv != NULL) { + ckfree((char *) wmPtr->cmdArgv); + } + wmPtr->cmdArgc = cmdArgc; + wmPtr->cmdArgv = cmdArgv; + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XSetCommand(winPtr->display, wmPtr->wrapperPtr->window, + cmdArgv, cmdArgc); + } + } else if ((c == 'd') && (strncmp(argv[1], "deiconify", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " deiconify window\"", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + Tcl_AppendResult(interp, "can't deiconify ", argv[2], + ": it is an icon for ", Tk_PathName(wmPtr->iconFor), + (char *) NULL); + return TCL_ERROR; + } + wmPtr->hints.initial_state = NormalState; + wmPtr->withdrawn = 0; + if (wmPtr->flags & WM_NEVER_MAPPED) { + return TCL_OK; + } + UpdateHints(winPtr); + Tk_MapWindow((Tk_Window) winPtr); + } else if ((c == 'f') && (strncmp(argv[1], "focusmodel", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " focusmodel window ?active|passive?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + interp->result = wmPtr->hints.input ? "passive" : "active"; + return TCL_OK; + } + c = argv[3][0]; + length = strlen(argv[3]); + if ((c == 'a') && (strncmp(argv[3], "active", length) == 0)) { + wmPtr->hints.input = False; + } else if ((c == 'p') && (strncmp(argv[3], "passive", length) == 0)) { + wmPtr->hints.input = True; + } else { + Tcl_AppendResult(interp, "bad argument \"", argv[3], + "\": must be active or passive", (char *) NULL); + return TCL_ERROR; + } + UpdateHints(winPtr); + } else if ((c == 'f') && (strncmp(argv[1], "frame", length) == 0) + && (length >= 2)) { + Window window; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " frame window\"", (char *) NULL); + return TCL_ERROR; + } + window = wmPtr->reparent; + if (window == None) { + window = Tk_WindowId((Tk_Window) winPtr); + } + sprintf(interp->result, "0x%x", (unsigned int) window); + } else if ((c == 'g') && (strncmp(argv[1], "geometry", length) == 0) + && (length >= 2)) { + char xSign, ySign; + int width, height; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " geometry window ?newGeometry?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + xSign = (wmPtr->flags & WM_NEGATIVE_X) ? '-' : '+'; + ySign = (wmPtr->flags & WM_NEGATIVE_Y) ? '-' : '+'; + if (wmPtr->gridWin != NULL) { + width = wmPtr->reqGridWidth + (winPtr->changes.width + - winPtr->reqWidth)/wmPtr->widthInc; + height = wmPtr->reqGridHeight + (winPtr->changes.height + - winPtr->reqHeight)/wmPtr->heightInc; + } else { + width = winPtr->changes.width; + height = winPtr->changes.height; + } + sprintf(interp->result, "%dx%d%c%d%c%d", width, height, + xSign, wmPtr->x, ySign, wmPtr->y); + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->width = -1; + wmPtr->height = -1; + goto updateGeom; + } + return ParseGeometry(interp, argv[3], winPtr); + } else if ((c == 'g') && (strncmp(argv[1], "grid", length) == 0) + && (length >= 3)) { + int reqWidth, reqHeight, widthInc, heightInc; + + if ((argc != 3) && (argc != 7)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " grid window ?baseWidth baseHeight ", + "widthInc heightInc?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & PBaseSize) { + sprintf(interp->result, "%d %d %d %d", wmPtr->reqGridWidth, + wmPtr->reqGridHeight, wmPtr->widthInc, + wmPtr->heightInc); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + /* + * Turn off gridding and reset the width and height + * to make sense as ungridded numbers. + */ + + wmPtr->sizeHintsFlags &= ~(PBaseSize|PResizeInc); + if (wmPtr->width != -1) { + wmPtr->width = winPtr->reqWidth + (wmPtr->width + - wmPtr->reqGridWidth)*wmPtr->widthInc; + wmPtr->height = winPtr->reqHeight + (wmPtr->height + - wmPtr->reqGridHeight)*wmPtr->heightInc; + } + wmPtr->widthInc = 1; + wmPtr->heightInc = 1; + } else { + if ((Tcl_GetInt(interp, argv[3], &reqWidth) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &reqHeight) != TCL_OK) + || (Tcl_GetInt(interp, argv[5], &widthInc) != TCL_OK) + || (Tcl_GetInt(interp, argv[6], &heightInc) != TCL_OK)) { + return TCL_ERROR; + } + if (reqWidth < 0) { + interp->result = "baseWidth can't be < 0"; + return TCL_ERROR; + } + if (reqHeight < 0) { + interp->result = "baseHeight can't be < 0"; + return TCL_ERROR; + } + if (widthInc < 0) { + interp->result = "widthInc can't be < 0"; + return TCL_ERROR; + } + if (heightInc < 0) { + interp->result = "heightInc can't be < 0"; + return TCL_ERROR; + } + Tk_SetGrid((Tk_Window) winPtr, reqWidth, reqHeight, widthInc, + heightInc); + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 'g') && (strncmp(argv[1], "group", length) == 0) + && (length >= 3)) { + Tk_Window tkwin2; + WmInfo *wmPtr2; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " group window ?pathName?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & WindowGroupHint) { + interp->result = wmPtr->leaderName; + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->hints.flags &= ~WindowGroupHint; + if (wmPtr->leaderName != NULL) { + ckfree(wmPtr->leaderName); + } + wmPtr->leaderName = NULL; + } else { + tkwin2 = Tk_NameToWindow(interp, argv[3], tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + while (!Tk_IsTopLevel(tkwin2)) { + /* + * Ensure that the group leader is actually a Tk toplevel. + */ + + tkwin2 = Tk_Parent(tkwin2); + } + Tk_MakeWindowExist(tkwin2); + wmPtr2 = ((TkWindow *) tkwin2)->wmInfoPtr; + if (wmPtr2->wrapperPtr == NULL) { + CreateWrapper(wmPtr2); + } + wmPtr->hints.window_group = Tk_WindowId(wmPtr2->wrapperPtr); + wmPtr->hints.flags |= WindowGroupHint; + wmPtr->leaderName = ckalloc((unsigned) (strlen(argv[3])+1)); + strcpy(wmPtr->leaderName, argv[3]); + } + UpdateHints(winPtr); + } else if ((c == 'i') && (strncmp(argv[1], "iconbitmap", length) == 0) + && (length >= 5)) { + Pixmap pixmap; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconbitmap window ?bitmap?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & IconPixmapHint) { + interp->result = Tk_NameOfBitmap(winPtr->display, + wmPtr->hints.icon_pixmap); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + if (wmPtr->hints.icon_pixmap != None) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_pixmap); + wmPtr->hints.icon_pixmap = None; + } + wmPtr->hints.flags &= ~IconPixmapHint; + } else { + pixmap = Tk_GetBitmap(interp, (Tk_Window) winPtr, + Tk_GetUid(argv[3])); + if (pixmap == None) { + return TCL_ERROR; + } + wmPtr->hints.icon_pixmap = pixmap; + wmPtr->hints.flags |= IconPixmapHint; + } + UpdateHints(winPtr); + } else if ((c == 'i') && (strncmp(argv[1], "iconify", length) == 0) + && (length >= 5)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconify window\"", (char *) NULL); + return TCL_ERROR; + } + if (Tk_Attributes((Tk_Window) winPtr)->override_redirect) { + Tcl_AppendResult(interp, "can't iconify \"", winPtr->pathName, + "\": override-redirect flag is set", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->master != None) { + Tcl_AppendResult(interp, "can't iconify \"", winPtr->pathName, + "\": it is a transient", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + Tcl_AppendResult(interp, "can't iconify ", argv[2], + ": it is an icon for ", Tk_PathName(wmPtr->iconFor), + (char *) NULL); + return TCL_ERROR; + } + wmPtr->hints.initial_state = IconicState; + if (wmPtr->flags & WM_NEVER_MAPPED) { + return TCL_OK; + } + if (wmPtr->withdrawn) { + UpdateHints(winPtr); + Tk_MapWindow((Tk_Window) winPtr); + wmPtr->withdrawn = 0; + } else { + if (XIconifyWindow(winPtr->display, wmPtr->wrapperPtr->window, + winPtr->screenNum) == 0) { + interp->result = + "couldn't send iconify message to window manager"; + return TCL_ERROR; + } + WaitForMapNotify(winPtr, 0); + } + } else if ((c == 'i') && (strncmp(argv[1], "iconmask", length) == 0) + && (length >= 5)) { + Pixmap pixmap; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconmask window ?bitmap?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & IconMaskHint) { + interp->result = Tk_NameOfBitmap(winPtr->display, + wmPtr->hints.icon_mask); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + if (wmPtr->hints.icon_mask != None) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_mask); + } + wmPtr->hints.flags &= ~IconMaskHint; + } else { + pixmap = Tk_GetBitmap(interp, tkwin, Tk_GetUid(argv[3])); + if (pixmap == None) { + return TCL_ERROR; + } + wmPtr->hints.icon_mask = pixmap; + wmPtr->hints.flags |= IconMaskHint; + } + UpdateHints(winPtr); + } else if ((c == 'i') && (strncmp(argv[1], "iconname", length) == 0) + && (length >= 5)) { + if (argc > 4) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconname window ?newName?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + interp->result = (wmPtr->iconName != NULL) ? wmPtr->iconName : ""; + return TCL_OK; + } else { + wmPtr->iconName = ckalloc((unsigned) (strlen(argv[3]) + 1)); + strcpy(wmPtr->iconName, argv[3]); + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XSetIconName(winPtr->display, wmPtr->wrapperPtr->window, + wmPtr->iconName); + } + } + } else if ((c == 'i') && (strncmp(argv[1], "iconposition", length) == 0) + && (length >= 5)) { + int x, y; + + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconposition window ?x y?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & IconPositionHint) { + sprintf(interp->result, "%d %d", wmPtr->hints.icon_x, + wmPtr->hints.icon_y); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->hints.flags &= ~IconPositionHint; + } else { + if ((Tcl_GetInt(interp, argv[3], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &y) != TCL_OK)){ + return TCL_ERROR; + } + wmPtr->hints.icon_x = x; + wmPtr->hints.icon_y = y; + wmPtr->hints.flags |= IconPositionHint; + } + UpdateHints(winPtr); + } else if ((c == 'i') && (strncmp(argv[1], "iconwindow", length) == 0) + && (length >= 5)) { + Tk_Window tkwin2; + WmInfo *wmPtr2; + XSetWindowAttributes atts; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconwindow window ?pathName?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->icon != NULL) { + interp->result = Tk_PathName(wmPtr->icon); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->hints.flags &= ~IconWindowHint; + if (wmPtr->icon != NULL) { + /* + * Remove the icon window relationship. In principle we + * should also re-enable button events for the window, but + * this doesn't work in general because the window manager + * is probably selecting on them (we'll get an error if + * we try to re-enable the events). So, just leave the + * icon window event-challenged; the user will have to + * recreate it if they want button events. + */ + + wmPtr2 = ((TkWindow *) wmPtr->icon)->wmInfoPtr; + wmPtr2->iconFor = NULL; + wmPtr2->withdrawn = 1; + wmPtr2->hints.initial_state = WithdrawnState; + } + wmPtr->icon = NULL; + } else { + tkwin2 = Tk_NameToWindow(interp, argv[3], tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + if (!Tk_IsTopLevel(tkwin2)) { + Tcl_AppendResult(interp, "can't use ", argv[3], + " as icon window: not at top level", (char *) NULL); + return TCL_ERROR; + } + wmPtr2 = ((TkWindow *) tkwin2)->wmInfoPtr; + if (wmPtr2->iconFor != NULL) { + Tcl_AppendResult(interp, argv[3], " is already an icon for ", + Tk_PathName(wmPtr2->iconFor), (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->icon != NULL) { + WmInfo *wmPtr3 = ((TkWindow *) wmPtr->icon)->wmInfoPtr; + wmPtr3->iconFor = NULL; + wmPtr3->withdrawn = 1; + wmPtr3->hints.initial_state = WithdrawnState; + } + + /* + * Disable button events in the icon window: some window + * managers (like olvwm) want to get the events themselves, + * but X only allows one application at a time to receive + * button events for a window. + */ + + atts.event_mask = Tk_Attributes(tkwin2)->event_mask + & ~ButtonPressMask; + Tk_ChangeWindowAttributes(tkwin2, CWEventMask, &atts); + Tk_MakeWindowExist(tkwin2); + if (wmPtr2->wrapperPtr == NULL) { + CreateWrapper(wmPtr2); + } + wmPtr->hints.icon_window = Tk_WindowId(wmPtr2->wrapperPtr); + wmPtr->hints.flags |= IconWindowHint; + wmPtr->icon = tkwin2; + wmPtr2->iconFor = (Tk_Window) winPtr; + if (!wmPtr2->withdrawn && !(wmPtr2->flags & WM_NEVER_MAPPED)) { + wmPtr2->withdrawn = 0; + if (XWithdrawWindow(Tk_Display(tkwin2), + Tk_WindowId(wmPtr2->wrapperPtr), + Tk_ScreenNumber(tkwin2)) == 0) { + interp->result = + "couldn't send withdraw message to window manager"; + return TCL_ERROR; + } + WaitForMapNotify((TkWindow *) tkwin2, 0); + } + } + UpdateHints(winPtr); + } else if ((c == 'm') && (strncmp(argv[1], "maxsize", length) == 0) + && (length >= 2)) { + int width, height; + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " maxsize window ?width height?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + GetMaxSize(wmPtr, &width, &height); + sprintf(interp->result, "%d %d", width, height); + return TCL_OK; + } + if ((Tcl_GetInt(interp, argv[3], &width) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &height) != TCL_OK)) { + return TCL_ERROR; + } + wmPtr->maxWidth = width; + wmPtr->maxHeight = height; + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 'm') && (strncmp(argv[1], "minsize", length) == 0) + && (length >= 2)) { + int width, height; + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " minsize window ?width height?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + sprintf(interp->result, "%d %d", wmPtr->minWidth, + wmPtr->minHeight); + return TCL_OK; + } + if ((Tcl_GetInt(interp, argv[3], &width) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &height) != TCL_OK)) { + return TCL_ERROR; + } + wmPtr->minWidth = width; + wmPtr->minHeight = height; + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 'o') + && (strncmp(argv[1], "overrideredirect", length) == 0)) { + int boolean; + XSetWindowAttributes atts; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " overrideredirect window ?boolean?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (Tk_Attributes((Tk_Window) winPtr)->override_redirect) { + interp->result = "1"; + } else { + interp->result = "0"; + } + return TCL_OK; + } + if (Tcl_GetBoolean(interp, argv[3], &boolean) != TCL_OK) { + return TCL_ERROR; + } + atts.override_redirect = (boolean) ? True : False; + Tk_ChangeWindowAttributes((Tk_Window) winPtr, CWOverrideRedirect, + &atts); + if (winPtr->wmInfoPtr->wrapperPtr != NULL) { + Tk_ChangeWindowAttributes( + (Tk_Window) winPtr->wmInfoPtr->wrapperPtr, + CWOverrideRedirect, &atts); + } + } else if ((c == 'p') && (strncmp(argv[1], "positionfrom", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " positionfrom window ?user/program?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & USPosition) { + interp->result = "user"; + } else if (wmPtr->sizeHintsFlags & PPosition) { + interp->result = "program"; + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->sizeHintsFlags &= ~(USPosition|PPosition); + } else { + c = argv[3][0]; + length = strlen(argv[3]); + if ((c == 'u') && (strncmp(argv[3], "user", length) == 0)) { + wmPtr->sizeHintsFlags &= ~PPosition; + wmPtr->sizeHintsFlags |= USPosition; + } else if ((c == 'p') && (strncmp(argv[3], "program", length) == 0)) { + wmPtr->sizeHintsFlags &= ~USPosition; + wmPtr->sizeHintsFlags |= PPosition; + } else { + Tcl_AppendResult(interp, "bad argument \"", argv[3], + "\": must be program or user", (char *) NULL); + return TCL_ERROR; + } + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 'p') && (strncmp(argv[1], "protocol", length) == 0) + && (length >= 2)) { + register ProtocolHandler *protPtr, *prevPtr; + Atom protocol; + int cmdLength; + + if ((argc < 3) || (argc > 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " protocol window ?name? ?command?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + /* + * Return a list of all defined protocols for the window. + */ + for (protPtr = wmPtr->protPtr; protPtr != NULL; + protPtr = protPtr->nextPtr) { + Tcl_AppendElement(interp, + Tk_GetAtomName((Tk_Window) winPtr, protPtr->protocol)); + } + return TCL_OK; + } + protocol = Tk_InternAtom((Tk_Window) winPtr, argv[3]); + if (argc == 4) { + /* + * Return the command to handle a given protocol. + */ + for (protPtr = wmPtr->protPtr; protPtr != NULL; + protPtr = protPtr->nextPtr) { + if (protPtr->protocol == protocol) { + interp->result = protPtr->command; + return TCL_OK; + } + } + return TCL_OK; + } + + /* + * Delete any current protocol handler, then create a new + * one with the specified command, unless the command is + * empty. + */ + + for (protPtr = wmPtr->protPtr, prevPtr = NULL; protPtr != NULL; + prevPtr = protPtr, protPtr = protPtr->nextPtr) { + if (protPtr->protocol == protocol) { + if (prevPtr == NULL) { + wmPtr->protPtr = protPtr->nextPtr; + } else { + prevPtr->nextPtr = protPtr->nextPtr; + } + Tcl_EventuallyFree((ClientData) protPtr, TCL_DYNAMIC); + break; + } + } + cmdLength = strlen(argv[4]); + if (cmdLength > 0) { + protPtr = (ProtocolHandler *) ckalloc(HANDLER_SIZE(cmdLength)); + protPtr->protocol = protocol; + protPtr->nextPtr = wmPtr->protPtr; + wmPtr->protPtr = protPtr; + protPtr->interp = interp; + strcpy(protPtr->command, argv[4]); + } + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + UpdateWmProtocols(wmPtr); + } + } else if ((c == 'r') && (strncmp(argv[1], "resizable", length) == 0)) { + int width, height; + + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " resizable window ?width height?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + sprintf(interp->result, "%d %d", + (wmPtr->flags & WM_WIDTH_NOT_RESIZABLE) ? 0 : 1, + (wmPtr->flags & WM_HEIGHT_NOT_RESIZABLE) ? 0 : 1); + return TCL_OK; + } + if ((Tcl_GetBoolean(interp, argv[3], &width) != TCL_OK) + || (Tcl_GetBoolean(interp, argv[4], &height) != TCL_OK)) { + return TCL_ERROR; + } + if (width) { + wmPtr->flags &= ~WM_WIDTH_NOT_RESIZABLE; + } else { + wmPtr->flags |= WM_WIDTH_NOT_RESIZABLE; + } + if (height) { + wmPtr->flags &= ~WM_HEIGHT_NOT_RESIZABLE; + } else { + wmPtr->flags |= WM_HEIGHT_NOT_RESIZABLE; + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 's') && (strncmp(argv[1], "sizefrom", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " sizefrom window ?user|program?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & USSize) { + interp->result = "user"; + } else if (wmPtr->sizeHintsFlags & PSize) { + interp->result = "program"; + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->sizeHintsFlags &= ~(USSize|PSize); + } else { + c = argv[3][0]; + length = strlen(argv[3]); + if ((c == 'u') && (strncmp(argv[3], "user", length) == 0)) { + wmPtr->sizeHintsFlags &= ~PSize; + wmPtr->sizeHintsFlags |= USSize; + } else if ((c == 'p') + && (strncmp(argv[3], "program", length) == 0)) { + wmPtr->sizeHintsFlags &= ~USSize; + wmPtr->sizeHintsFlags |= PSize; + } else { + Tcl_AppendResult(interp, "bad argument \"", argv[3], + "\": must be program or user", (char *) NULL); + return TCL_ERROR; + } + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 's') && (strncmp(argv[1], "state", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " state window\"", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + interp->result = "icon"; + } else if (wmPtr->withdrawn) { + interp->result = "withdrawn"; + } else if (Tk_IsMapped((Tk_Window) winPtr) + || ((wmPtr->flags & WM_NEVER_MAPPED) + && (wmPtr->hints.initial_state == NormalState))) { + interp->result = "normal"; + } else { + interp->result = "iconic"; + } + } else if ((c == 't') && (strncmp(argv[1], "title", length) == 0) + && (length >= 2)) { + if (argc > 4) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " title window ?newTitle?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + interp->result = (wmPtr->title != NULL) ? wmPtr->title + : winPtr->nameUid; + return TCL_OK; + } else { + wmPtr->title = ckalloc((unsigned) (strlen(argv[3]) + 1)); + strcpy(wmPtr->title, argv[3]); + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XTextProperty textProp; + + if (XStringListToTextProperty(&wmPtr->title, 1, + &textProp) != 0) { + XSetWMName(winPtr->display, wmPtr->wrapperPtr->window, + &textProp); + XFree((char *) textProp.value); + } + } + } + } else if ((c == 't') && (strncmp(argv[1], "transient", length) == 0) + && (length >= 3)) { + Tk_Window master; + WmInfo *wmPtr2; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " transient window ?master?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->master != None) { + interp->result = wmPtr->masterWindowName; + } + return TCL_OK; + } + if (argv[3][0] == '\0') { + wmPtr->master = None; + if (wmPtr->masterWindowName != NULL) { + ckfree(wmPtr->masterWindowName); + } + wmPtr->masterWindowName = NULL; + } else { + master = Tk_NameToWindow(interp, argv[3], tkwin); + if (master == NULL) { + return TCL_ERROR; + } + while (!Tk_IsTopLevel(master)) { + /* + * Ensure that the master window is actually a Tk toplevel. + */ + + master = Tk_Parent(master); + } + Tk_MakeWindowExist(master); + wmPtr2 = ((TkWindow *) master)->wmInfoPtr; + if (wmPtr2->wrapperPtr == NULL) { + CreateWrapper(wmPtr2); + } + wmPtr->master = Tk_WindowId(wmPtr2->wrapperPtr); + wmPtr->masterWindowName = ckalloc((unsigned) (strlen(argv[3])+1)); + strcpy(wmPtr->masterWindowName, argv[3]); + } + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XSetTransientForHint(winPtr->display, wmPtr->wrapperPtr->window, + wmPtr->master); + } + } else if ((c == 'w') && (strncmp(argv[1], "withdraw", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " withdraw window\"", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + Tcl_AppendResult(interp, "can't withdraw ", argv[2], + ": it is an icon for ", Tk_PathName(wmPtr->iconFor), + (char *) NULL); + return TCL_ERROR; + } + wmPtr->hints.initial_state = WithdrawnState; + wmPtr->withdrawn = 1; + if (wmPtr->flags & WM_NEVER_MAPPED) { + return TCL_OK; + } + if (XWithdrawWindow(winPtr->display, wmPtr->wrapperPtr->window, + winPtr->screenNum) == 0) { + interp->result = + "couldn't send withdraw message to window manager"; + return TCL_ERROR; + } + WaitForMapNotify(winPtr, 0); + } else { + Tcl_AppendResult(interp, "unknown or ambiguous option \"", argv[1], + "\": must be aspect, client, command, deiconify, ", + "focusmodel, frame, geometry, grid, group, iconbitmap, ", + "iconify, iconmask, iconname, iconposition, ", + "iconwindow, maxsize, minsize, overrideredirect, ", + "positionfrom, protocol, resizable, sizefrom, state, title, ", + "transient, or withdraw", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; + + updateGeom: + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_SetGrid -- + * + * This procedure is invoked by a widget when it wishes to set a grid + * coordinate system that controls the size of a top-level window. + * It provides a C interface equivalent to the "wm grid" command and + * is usually asscoiated with the -setgrid option. + * + * Results: + * None. + * + * Side effects: + * Grid-related information will be passed to the window manager, so + * that the top-level window associated with tkwin will resize on + * even grid units. If some other window already controls gridding + * for the top-level window then this procedure call has no effect. + * + *---------------------------------------------------------------------- + */ + +void +Tk_SetGrid(tkwin, reqWidth, reqHeight, widthInc, heightInc) + Tk_Window tkwin; /* Token for window. New window mgr info + * will be posted for the top-level window + * associated with this window. */ + int reqWidth; /* Width (in grid units) corresponding to + * the requested geometry for tkwin. */ + int reqHeight; /* Height (in grid units) corresponding to + * the requested geometry for tkwin. */ + int widthInc, heightInc; /* Pixel increments corresponding to a + * change of one grid unit. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + register WmInfo *wmPtr; + + /* + * Find the top-level window for tkwin, plus the window manager + * information. + */ + + while (!(winPtr->flags & TK_TOP_LEVEL)) { + winPtr = winPtr->parentPtr; + if (winPtr == NULL) { + /* + * The window is being deleted... just skip this operation. + */ + + return; + } + } + wmPtr = winPtr->wmInfoPtr; + + if ((wmPtr->gridWin != NULL) && (wmPtr->gridWin != tkwin)) { + return; + } + + if ((wmPtr->reqGridWidth == reqWidth) + && (wmPtr->reqGridHeight == reqHeight) + && (wmPtr->widthInc == widthInc) + && (wmPtr->heightInc == heightInc) + && ((wmPtr->sizeHintsFlags & (PBaseSize|PResizeInc)) + == (PBaseSize|PResizeInc) )) { + return; + } + + /* + * If gridding was previously off, then forget about any window + * size requests made by the user or via "wm geometry": these are + * in pixel units and there's no easy way to translate them to + * grid units since the new requested size of the top-level window in + * pixels may not yet have been registered yet (it may filter up + * the hierarchy in DoWhenIdle handlers). However, if the window + * has never been mapped yet then just leave the window size alone: + * assume that it is intended to be in grid units but just happened + * to have been specified before this procedure was called. + */ + + if ((wmPtr->gridWin == NULL) && !(wmPtr->flags & WM_NEVER_MAPPED)) { + wmPtr->width = -1; + wmPtr->height = -1; + } + + /* + * Set the new gridding information, and start the process of passing + * all of this information to the window manager. + */ + + wmPtr->gridWin = tkwin; + wmPtr->reqGridWidth = reqWidth; + wmPtr->reqGridHeight = reqHeight; + wmPtr->widthInc = widthInc; + wmPtr->heightInc = heightInc; + wmPtr->sizeHintsFlags |= PBaseSize|PResizeInc; + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_UnsetGrid -- + * + * This procedure cancels the effect of a previous call + * to Tk_SetGrid. + * + * Results: + * None. + * + * Side effects: + * If tkwin currently controls gridding for its top-level window, + * gridding is cancelled for that top-level window; if some other + * window controls gridding then this procedure has no effect. + * + *---------------------------------------------------------------------- + */ + +void +Tk_UnsetGrid(tkwin) + Tk_Window tkwin; /* Token for window that is currently + * controlling gridding. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + register WmInfo *wmPtr; + + /* + * Find the top-level window for tkwin, plus the window manager + * information. + */ + + while (!(winPtr->flags & TK_TOP_LEVEL)) { + winPtr = winPtr->parentPtr; + if (winPtr == NULL) { + /* + * The window is being deleted... just skip this operation. + */ + + return; + } + } + wmPtr = winPtr->wmInfoPtr; + if (tkwin != wmPtr->gridWin) { + return; + } + + wmPtr->gridWin = NULL; + wmPtr->sizeHintsFlags &= ~(PBaseSize|PResizeInc); + if (wmPtr->width != -1) { + wmPtr->width = winPtr->reqWidth + (wmPtr->width + - wmPtr->reqGridWidth)*wmPtr->widthInc; + wmPtr->height = winPtr->reqHeight + (wmPtr->height + - wmPtr->reqGridHeight)*wmPtr->heightInc; + } + wmPtr->widthInc = 1; + wmPtr->heightInc = 1; + + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureEvent -- + * + * This procedure is called to handle ConfigureNotify events on + * wrapper windows. + * + * Results: + * None. + * + * Side effects: + * Information gets updated in the WmInfo structure for the window + * and the toplevel itself gets repositioned within the wrapper. + * + *---------------------------------------------------------------------- + */ + +static void +ConfigureEvent(wmPtr, configEventPtr) + WmInfo *wmPtr; /* Information about toplevel window. */ + XConfigureEvent *configEventPtr; /* Event that just occurred for + * wmPtr->wrapperPtr. */ +{ + TkWindow *wrapperPtr = wmPtr->wrapperPtr; + TkWindow *winPtr = wmPtr->winPtr; + + /* + * Update size information from the event. There are a couple of + * tricky points here: + * + * 1. If the user changed the size externally then set wmPtr->width + * and wmPtr->height just as if a "wm geometry" command had been + * invoked with the same information. + * 2. However, if the size is changing in response to a request + * coming from us (WM_SYNC_PENDING is set), then don't set wmPtr->width + * or wmPtr->height if they were previously -1 (otherwise the + * window will stop tracking geometry manager requests). + */ + + if (((wrapperPtr->changes.width != configEventPtr->width) + || (wrapperPtr->changes.height != configEventPtr->height)) + && !(wmPtr->flags & WM_SYNC_PENDING)){ + if (wmTracing) { + printf("TopLevelEventProc: user changed %s size to %dx%d\n", + winPtr->pathName, configEventPtr->width, + configEventPtr->height); + } + if ((wmPtr->width == -1) + && (configEventPtr->width == winPtr->reqWidth)) { + /* + * Don't set external width, since the user didn't change it + * from what the widgets asked for. + */ + } else { + /* + * Note: if this window is embedded then don't set the external + * size, since it came from the containing application, not the + * user. In this case we want to keep sending our size requests + * to the containing application; if the user fixes the size + * of that application then it will still percolate down to us + * in the right way. + */ + + if (!(winPtr->flags & TK_EMBEDDED)) { + if (wmPtr->gridWin != NULL) { + wmPtr->width = wmPtr->reqGridWidth + + (configEventPtr->width + - winPtr->reqWidth)/wmPtr->widthInc; + if (wmPtr->width < 0) { + wmPtr->width = 0; + } + } else { + wmPtr->width = configEventPtr->width; + } + } + } + if ((wmPtr->height == -1) + && (configEventPtr->height == + (winPtr->reqHeight + wmPtr->menuHeight))) { + /* + * Don't set external height, since the user didn't change it + * from what the widgets asked for. + */ + } else { + /* + * See note for wmPtr->width about not setting external size + * for embedded windows. + */ + + if (!(winPtr->flags & TK_EMBEDDED)) { + if (wmPtr->gridWin != NULL) { + wmPtr->height = wmPtr->reqGridHeight + + (configEventPtr->height - wmPtr->menuHeight + - winPtr->reqHeight)/wmPtr->heightInc; + if (wmPtr->height < 0) { + wmPtr->height = 0; + } + } else { + wmPtr->height = configEventPtr->height - wmPtr->menuHeight; + } + } + } + wmPtr->configWidth = configEventPtr->width; + wmPtr->configHeight = configEventPtr->height; + } + + if (wmTracing) { + printf("ConfigureEvent: %s x = %d y = %d, width = %d, height = %d", + winPtr->pathName, configEventPtr->x, configEventPtr->y, + configEventPtr->width, configEventPtr->height); + printf(" send_event = %d, serial = %ld\n", configEventPtr->send_event, + configEventPtr->serial); + } + wrapperPtr->changes.width = configEventPtr->width; + wrapperPtr->changes.height = configEventPtr->height; + wrapperPtr->changes.border_width = configEventPtr->border_width; + wrapperPtr->changes.sibling = configEventPtr->above; + wrapperPtr->changes.stack_mode = Above; + + /* + * Reparenting window managers make life difficult. If the + * window manager reparents a top-level window then the x and y + * information that comes in events for the window is wrong: + * it gives the location of the window inside its decorative + * parent, rather than the location of the window in root + * coordinates, which is what we want. Window managers + * are supposed to send synthetic events with the correct + * information, but ICCCM doesn't require them to do this + * under all conditions, and the information provided doesn't + * include everything we need here. So, the code below + * maintains a bunch of information about the parent window. + * If the window hasn't been reparented, we pretend that + * there is a parent shrink-wrapped around the window. + */ + + if ((wmPtr->reparent == None) || !ComputeReparentGeometry(wmPtr)) { + wmPtr->parentWidth = configEventPtr->width + + 2*configEventPtr->border_width; + wmPtr->parentHeight = configEventPtr->height + + 2*configEventPtr->border_width; + wrapperPtr->changes.x = wmPtr->x = configEventPtr->x; + wrapperPtr->changes.y = wmPtr->y = configEventPtr->y; + if (wmPtr->flags & WM_NEGATIVE_X) { + wmPtr->x = wmPtr->vRootWidth - (wmPtr->x + wmPtr->parentWidth); + } + if (wmPtr->flags & WM_NEGATIVE_Y) { + wmPtr->y = wmPtr->vRootHeight - (wmPtr->y + wmPtr->parentHeight); + } + } + + /* + * Make sure that the toplevel and menubar are properly positioned within + * the wrapper. + */ + + XMoveResizeWindow(winPtr->display, winPtr->window, 0, + wmPtr->menuHeight, (unsigned) wrapperPtr->changes.width, + (unsigned) (wrapperPtr->changes.height - wmPtr->menuHeight)); + if ((wmPtr->menubar != NULL) + && ((Tk_Width(wmPtr->menubar) != wrapperPtr->changes.width) + || (Tk_Height(wmPtr->menubar) != wmPtr->menuHeight))) { + Tk_MoveResizeWindow(wmPtr->menubar, 0, 0, wrapperPtr->changes.width, + wmPtr->menuHeight); + } + + /* + * Update the coordinates in the toplevel (they should refer to the + * position in root window coordinates, not the coordinates of the + * wrapper window). Then synthesize a ConfigureNotify event to tell + * the application about the change. + */ + + winPtr->changes.x = wrapperPtr->changes.x; + winPtr->changes.y = wrapperPtr->changes.y + wmPtr->menuHeight; + winPtr->changes.width = wrapperPtr->changes.width; + winPtr->changes.height = wrapperPtr->changes.height - wmPtr->menuHeight; + TkDoConfigureNotify(winPtr); +} + +/* + *---------------------------------------------------------------------- + * + * ReparentEvent -- + * + * This procedure is called to handle ReparentNotify events on + * wrapper windows. + * + * Results: + * None. + * + * Side effects: + * Information gets updated in the WmInfo structure for the window. + * + *---------------------------------------------------------------------- + */ + +static void +ReparentEvent(wmPtr, reparentEventPtr) + WmInfo *wmPtr; /* Information about toplevel window. */ + XReparentEvent *reparentEventPtr; /* Event that just occurred for + * wmPtr->wrapperPtr. */ +{ + TkWindow *wrapperPtr = wmPtr->wrapperPtr; + Window vRoot, ancestor, *children, dummy2, *virtualRootPtr; + Atom actualType; + int actualFormat; + unsigned long numItems, bytesAfter; + unsigned int dummy; + Tk_ErrorHandler handler; + + /* + * Identify the root window for wrapperPtr. This is tricky because of + * virtual root window managers like tvtwm. If the window has a + * property named __SWM_ROOT or __WM_ROOT then this property gives + * the id for a virtual root window that should be used instead of + * the root window of the screen. + */ + + vRoot = RootWindow(wrapperPtr->display, wrapperPtr->screenNum); + wmPtr->vRoot = None; + handler = Tk_CreateErrorHandler(wrapperPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + if (((XGetWindowProperty(wrapperPtr->display, wrapperPtr->window, + Tk_InternAtom((Tk_Window) wrapperPtr, "__WM_ROOT"), 0, (long) 1, + False, XA_WINDOW, &actualType, &actualFormat, &numItems, + &bytesAfter, (unsigned char **) &virtualRootPtr) == Success) + && (actualType == XA_WINDOW)) + || ((XGetWindowProperty(wrapperPtr->display, wrapperPtr->window, + Tk_InternAtom((Tk_Window) wrapperPtr, "__SWM_ROOT"), 0, (long) 1, + False, XA_WINDOW, &actualType, &actualFormat, &numItems, + &bytesAfter, (unsigned char **) &virtualRootPtr) == Success) + && (actualType == XA_WINDOW))) { + if ((actualFormat == 32) && (numItems == 1)) { + vRoot = wmPtr->vRoot = *virtualRootPtr; + } else if (wmTracing) { + printf("%s format %d numItems %ld\n", + "ReparentEvent got bogus VROOT property:", actualFormat, + numItems); + } + XFree((char *) virtualRootPtr); + } + Tk_DeleteErrorHandler(handler); + + if (wmTracing) { + printf("ReparentEvent: %s reparented to 0x%x, vRoot = 0x%x\n", + wmPtr->winPtr->pathName, + (unsigned int) reparentEventPtr->parent, (unsigned int) vRoot); + } + + /* + * Fetch correct geometry information for the new virtual root. + */ + + UpdateVRootGeometry(wmPtr); + + /* + * If the window's new parent is the root window, then mark it as + * no longer reparented. + */ + + if (reparentEventPtr->parent == vRoot) { + noReparent: + wmPtr->reparent = None; + wmPtr->parentWidth = wrapperPtr->changes.width; + wmPtr->parentHeight = wrapperPtr->changes.height; + wmPtr->xInParent = wmPtr->yInParent = 0; + wrapperPtr->changes.x = reparentEventPtr->x; + wrapperPtr->changes.y = reparentEventPtr->y; + return; + } + + /* + * Search up the window hierarchy to find the ancestor of this + * window that is just below the (virtual) root. This is tricky + * because it's possible that things have changed since the event + * was generated so that the ancestry indicated by the event no + * longer exists. If this happens then an error will occur and + * we just discard the event (there will be a more up-to-date + * ReparentNotify event coming later). + */ + + handler = Tk_CreateErrorHandler(wrapperPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + wmPtr->reparent = reparentEventPtr->parent; + while (1) { + if (XQueryTree(wrapperPtr->display, wmPtr->reparent, &dummy2, &ancestor, + &children, &dummy) == 0) { + Tk_DeleteErrorHandler(handler); + goto noReparent; + } + XFree((char *) children); + if ((ancestor == vRoot) || + (ancestor == RootWindow(wrapperPtr->display, + wrapperPtr->screenNum))) { + break; + } + wmPtr->reparent = ancestor; + } + Tk_DeleteErrorHandler(handler); + + if (!ComputeReparentGeometry(wmPtr)) { + goto noReparent; + } +} + +/* + *---------------------------------------------------------------------- + * + * ComputeReparentGeometry -- + * + * This procedure is invoked to recompute geometry information + * related to a reparented top-level window, such as the position + * and total size of the parent and the position within it of + * the top-level window. + * + * Results: + * The return value is 1 if everything completed successfully + * and 0 if an error occurred while querying information about + * winPtr's parents. In this case winPtr is marked as no longer + * being reparented. + * + * Side effects: + * Geometry information in wmPtr, wmPtr->winPtr, and + * wmPtr->wrapperPtr gets updated. + * + *---------------------------------------------------------------------- + */ + +static int +ComputeReparentGeometry(wmPtr) + WmInfo *wmPtr; /* Information about toplevel window + * whose reparent info is to be recomputed. */ +{ + TkWindow *wrapperPtr = wmPtr->wrapperPtr; + int width, height, bd; + unsigned int dummy; + int xOffset, yOffset, x, y; + Window dummy2; + Status status; + Tk_ErrorHandler handler; + + handler = Tk_CreateErrorHandler(wrapperPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + (void) XTranslateCoordinates(wrapperPtr->display, wrapperPtr->window, + wmPtr->reparent, 0, 0, &xOffset, &yOffset, &dummy2); + status = XGetGeometry(wrapperPtr->display, wmPtr->reparent, + &dummy2, &x, &y, (unsigned int *) &width, + (unsigned int *) &height, (unsigned int *) &bd, &dummy); + Tk_DeleteErrorHandler(handler); + if (status == 0) { + /* + * It appears that the reparented parent went away and + * no-one told us. Reset the window to indicate that + * it's not reparented. + */ + wmPtr->reparent = None; + wmPtr->xInParent = wmPtr->yInParent = 0; + return 0; + } + wmPtr->xInParent = xOffset + bd; + wmPtr->yInParent = yOffset + bd; + wmPtr->parentWidth = width + 2*bd; + wmPtr->parentHeight = height + 2*bd; + + /* + * Some tricky issues in updating wmPtr->x and wmPtr->y: + * + * 1. Don't update them if the event occurred because of something + * we did (i.e. WM_SYNC_PENDING and WM_MOVE_PENDING are both set). + * This is because window managers treat coords differently than Tk, + * and no two window managers are alike. If the window manager moved + * the window because we told it to, remember the coordinates we told + * it, not the ones it actually moved it to. This allows us to move + * the window back to the same coordinates later and get the same + * result. Without this check, windows can "walk" across the screen + * under some conditions. + * + * 2. Don't update wmPtr->x and wmPtr->y unless wrapperPtr->changes.x + * or wrapperPtr->changes.y has changed (otherwise a size change can + * spoof us into thinking that the position changed too and defeat + * the intent of (1) above. + * + * (As of 9/96 the above 2 comments appear to be stale. They're + * being left in place as a reminder of what was once true (and + * perhaps should still be true?)). + * + * 3. Ignore size changes coming from the window system if we're + * about to change the size ourselves but haven't seen the event for + * it yet: our size change is supposed to take priority. + */ + + if (!(wmPtr->flags & WM_MOVE_PENDING) + && ((wmPtr->wrapperPtr->changes.x != (x + wmPtr->xInParent)) + || (wmPtr->wrapperPtr->changes.y != (y + wmPtr->yInParent)))) { + wmPtr->x = x; + if (wmPtr->flags & WM_NEGATIVE_X) { + wmPtr->x = wmPtr->vRootWidth - (wmPtr->x + wmPtr->parentWidth); + } + wmPtr->y = y; + if (wmPtr->flags & WM_NEGATIVE_Y) { + wmPtr->y = wmPtr->vRootHeight - (wmPtr->y + wmPtr->parentHeight); + } + } + + wmPtr->wrapperPtr->changes.x = x + wmPtr->xInParent; + wmPtr->wrapperPtr->changes.y = y + wmPtr->yInParent; + if (wmTracing) { + printf("wrapperPtr coords %d,%d, wmPtr coords %d,%d, offsets %d %d\n", + wrapperPtr->changes.x, wrapperPtr->changes.y, + wmPtr->x, wmPtr->y, wmPtr->xInParent, wmPtr->yInParent); + } + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * WrapperEventProc -- + * + * This procedure is invoked by the event loop when a wrapper window + * is restructured. + * + * Results: + * None. + * + * Side effects: + * Tk's internal data structures for the window get modified to + * reflect the structural change. + * + *---------------------------------------------------------------------- + */ + +static void +WrapperEventProc(clientData, eventPtr) + ClientData clientData; /* Information about toplevel window. */ + XEvent *eventPtr; /* Event that just happened. */ +{ + WmInfo *wmPtr = (WmInfo *) clientData; + XEvent mapEvent; + + wmPtr->flags |= WM_VROOT_OFFSET_STALE; + if (eventPtr->type == DestroyNotify) { + Tk_ErrorHandler handler; + + if (!(wmPtr->wrapperPtr->flags & TK_ALREADY_DEAD)) { + /* + * A top-level window was deleted externally (e.g., by the window + * manager). This is probably not a good thing, but cleanup as + * best we can. The error handler is needed because + * Tk_DestroyWindow will try to destroy the window, but of course + * it's already gone. + */ + + handler = Tk_CreateErrorHandler(wmPtr->winPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + Tk_DestroyWindow((Tk_Window) wmPtr->winPtr); + Tk_DeleteErrorHandler(handler); + } + if (wmTracing) { + printf("TopLevelEventProc: %s deleted\n", wmPtr->winPtr->pathName); + } + } else if (eventPtr->type == ConfigureNotify) { + /* + * Ignore the event if the window has never been mapped yet. + * Such an event occurs only in weird cases like changing the + * internal border width of a top-level window, which results + * in a synthetic Configure event. These events are not relevant + * to us, and if we process them confusion may result (e.g. we + * may conclude erroneously that the user repositioned or resized + * the window). + */ + + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + ConfigureEvent(wmPtr, &eventPtr->xconfigure); + } + } else if (eventPtr->type == MapNotify) { + wmPtr->wrapperPtr->flags |= TK_MAPPED; + wmPtr->winPtr->flags |= TK_MAPPED; + XMapWindow(wmPtr->winPtr->display, wmPtr->winPtr->window); + goto doMapEvent; + } else if (eventPtr->type == UnmapNotify) { + wmPtr->wrapperPtr->flags &= ~TK_MAPPED; + wmPtr->winPtr->flags &= ~TK_MAPPED; + XUnmapWindow(wmPtr->winPtr->display, wmPtr->winPtr->window); + goto doMapEvent; + } else if (eventPtr->type == ReparentNotify) { + ReparentEvent(wmPtr, &eventPtr->xreparent); + } + return; + + doMapEvent: + mapEvent = *eventPtr; + mapEvent.xmap.event = wmPtr->winPtr->window; + mapEvent.xmap.window = wmPtr->winPtr->window; + Tk_HandleEvent(&mapEvent); +} + +/* + *---------------------------------------------------------------------- + * + * TopLevelReqProc -- + * + * This procedure is invoked by the geometry manager whenever + * the requested size for a top-level window is changed. + * + * Results: + * None. + * + * Side effects: + * Arrange for the window to be resized to satisfy the request + * (this happens as a when-idle action). + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +TopLevelReqProc(dummy, tkwin) + ClientData dummy; /* Not used. */ + Tk_Window tkwin; /* Information about window. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + WmInfo *wmPtr; + + wmPtr = winPtr->wmInfoPtr; + + if ((wmPtr->width >= 0) && (wmPtr->height >= 0)) { + /* + * Explicit dimensions have been set for this window, so we + * should ignore the geometry request. It's actually important + * to ignore the geometry request because, due to quirks in + * window managers, invoking UpdateGeometryInfo may cause the + * window to move. For example, if "wm geometry -10-20" was + * invoked, the window may be positioned incorrectly the first + * time it appears (because we didn't know the proper width of + * the window manager borders); if we invoke UpdateGeometryInfo + * again, the window will be positioned correctly, which may + * cause it to jump on the screen. + */ + + return; + } + + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } + + /* + * If the window isn't being positioned by its upper left corner + * then we have to move it as well. + */ + + if (wmPtr->flags & (WM_NEGATIVE_X | WM_NEGATIVE_Y)) { + wmPtr->flags |= WM_MOVE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * UpdateGeometryInfo -- + * + * This procedure is invoked when a top-level window is first + * mapped, and also as a when-idle procedure, to bring the + * geometry and/or position of a top-level window back into + * line with what has been requested by the user and/or widgets. + * This procedure doesn't return until the window manager has + * responded to the geometry change. + * + * Results: + * None. + * + * Side effects: + * The size and location of both the toplevel window and its wrapper + * may change, unless the WM prevents that from happening. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateGeometryInfo(clientData) + ClientData clientData; /* Pointer to the window's record. */ +{ + register TkWindow *winPtr = (TkWindow *) clientData; + register WmInfo *wmPtr = winPtr->wmInfoPtr; + int x, y, width, height; + unsigned long serial; + + wmPtr->flags &= ~WM_UPDATE_PENDING; + + /* + * Compute the new size for the top-level window. See the + * user documentation for details on this, but the size + * requested depends on (a) the size requested internally + * by the window's widgets, (b) the size requested by the + * user in a "wm geometry" command or via wm-based interactive + * resizing (if any), and (c) whether or not the window is + * gridded. Don't permit sizes <= 0 because this upsets + * the X server. + */ + + if (wmPtr->width == -1) { + width = winPtr->reqWidth; + } else if (wmPtr->gridWin != NULL) { + width = winPtr->reqWidth + + (wmPtr->width - wmPtr->reqGridWidth)*wmPtr->widthInc; + } else { + width = wmPtr->width; + } + if (width <= 0) { + width = 1; + } + if (wmPtr->height == -1) { + height = winPtr->reqHeight; + } else if (wmPtr->gridWin != NULL) { + height = winPtr->reqHeight + + (wmPtr->height - wmPtr->reqGridHeight)*wmPtr->heightInc; + } else { + height = wmPtr->height; + } + if (height <= 0) { + height = 1; + } + + /* + * Compute the new position for the upper-left pixel of the window's + * decorative frame. This is tricky, because we need to include the + * border widths supplied by a reparented parent in this calculation, + * but can't use the parent's current overall size since that may + * change as a result of this code. + */ + + if (wmPtr->flags & WM_NEGATIVE_X) { + x = wmPtr->vRootWidth - wmPtr->x + - (width + (wmPtr->parentWidth - winPtr->changes.width)); + } else { + x = wmPtr->x; + } + if (wmPtr->flags & WM_NEGATIVE_Y) { + y = wmPtr->vRootHeight - wmPtr->y + - (height + (wmPtr->parentHeight - winPtr->changes.height)); + } else { + y = wmPtr->y; + } + + /* + * If the window's size is going to change and the window is + * supposed to not be resizable by the user, then we have to + * update the size hints. There may also be a size-hint-update + * request pending from somewhere else, too. + */ + + if (((width != winPtr->changes.width) + || (height != winPtr->changes.height)) + && (wmPtr->gridWin == NULL) + && ((wmPtr->sizeHintsFlags & (PMinSize|PMaxSize)) == 0)) { + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + } + if (wmPtr->flags & WM_UPDATE_SIZE_HINTS) { + UpdateSizeHints(winPtr); + } + + /* + * Reconfigure the wrapper if it isn't already configured correctly. + * A few tricky points: + * + * 1. If the window is embeddedand the container is also in this + * process, don't actually reconfigure the window; just pass the + * desired size on to the container. Also, zero out any position + * information, since embedded windows are not allowed to move. + * 2. Sometimes the window manager will give us a different size + * than we asked for (e.g. mwm has a minimum size for windows), so + * base the size check on what we *asked for* last time, not what we + * got. + * 3. Can't just reconfigure always, because we may not get a + * ConfigureNotify event back if nothing changed, so + * WaitForConfigureNotify will hang a long time. + * 4. Don't move window unless a new position has been requested for + * it. This is because of "features" in some window managers (e.g. + * twm, as of 4/24/91) where they don't interpret coordinates + * according to ICCCM. Moving a window to its current location may + * cause it to shift position on the screen. + */ + + if ((winPtr->flags & (TK_EMBEDDED|TK_BOTH_HALVES)) + == (TK_EMBEDDED|TK_BOTH_HALVES)) { + /* + * This window is embedded and the container is also in this + * process, so we don't need to do anything special about the + * geometry, except to make sure that the desired size is known + * by the container. Also, zero out any position information, + * since embedded windows are not allowed to move. + */ + + wmPtr->x = wmPtr->y = 0; + wmPtr->flags &= ~(WM_NEGATIVE_X|WM_NEGATIVE_Y); + height += wmPtr->menuHeight; + Tk_GeometryRequest((Tk_Window) TkpGetOtherWindow(winPtr), + width, height); + return; + } + serial = NextRequest(winPtr->display); + height += wmPtr->menuHeight; + if (wmPtr->flags & WM_MOVE_PENDING) { + if ((x == winPtr->changes.x) && (y == winPtr->changes.y) + && (width == wmPtr->wrapperPtr->changes.width) + && (height == wmPtr->wrapperPtr->changes.height)) { + /* + * The window already has the correct geometry, so don't bother + * to configure it; the X server appears to ignore these + * requests, so we won't get back a ConfigureNotify and the + * WaitForConfigureNotify call below will hang for a while. + */ + + wmPtr->flags &= ~WM_MOVE_PENDING; + return; + } + wmPtr->configWidth = width; + wmPtr->configHeight = height; + if (wmTracing) { + printf("UpdateGeometryInfo moving to %d %d, resizing to %d x %d,\n", + x, y, width, height); + } + XMoveResizeWindow(winPtr->display, wmPtr->wrapperPtr->window, x, y, + (unsigned) width, (unsigned) height); + } else if ((width != wmPtr->configWidth) + || (height != wmPtr->configHeight)) { + if ((width == wmPtr->wrapperPtr->changes.width) + && (height == wmPtr->wrapperPtr->changes.height)) { + /* + * The window is already just the size we want, so don't bother + * to configure it; the X server appears to ignore these + * requests, so we won't get back a ConfigureNotify and the + * WaitForConfigureNotify call below will hang for a while. + */ + + return; + } + wmPtr->configWidth = width; + wmPtr->configHeight = height; + if (wmTracing) { + printf("UpdateGeometryInfo resizing to %d x %d\n", width, height); + } + XResizeWindow(winPtr->display, wmPtr->wrapperPtr->window, + (unsigned) width, (unsigned) height); + } else if ((wmPtr->menubar != NULL) + && ((Tk_Width(wmPtr->menubar) != wmPtr->wrapperPtr->changes.width) + || (Tk_Height(wmPtr->menubar) != wmPtr->menuHeight))) { + /* + * It is possible that the window's overall size has not changed + * but the menu size has. + */ + + Tk_MoveResizeWindow(wmPtr->menubar, 0, 0, + wmPtr->wrapperPtr->changes.width, wmPtr->menuHeight); + XResizeWindow(winPtr->display, wmPtr->wrapperPtr->window, + (unsigned) width, (unsigned) height); + } else { + return; + } + + /* + * Wait for the configure operation to complete. Don't need to do + * this, however, if the window is about to be mapped: it will be + * taken care of elsewhere. + */ + + if (!(wmPtr->flags & WM_ABOUT_TO_MAP)) { + WaitForConfigureNotify(winPtr, serial); + } +} + +/* + *-------------------------------------------------------------- + * + * UpdateSizeHints -- + * + * This procedure is called to update the window manager's + * size hints information from the information in a WmInfo + * structure. + * + * Results: + * None. + * + * Side effects: + * Properties get changed for winPtr. + * + *-------------------------------------------------------------- + */ + +static void +UpdateSizeHints(winPtr) + TkWindow *winPtr; +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + XSizeHints *hintsPtr; + int maxWidth, maxHeight; + + wmPtr->flags &= ~WM_UPDATE_SIZE_HINTS; + + hintsPtr = XAllocSizeHints(); + if (hintsPtr == NULL) { + return; + } + + /* + * Compute the pixel-based sizes for the various fields in the + * size hints structure, based on the grid-based sizes in + * our structure. + */ + + GetMaxSize(wmPtr, &maxWidth, &maxHeight); + if (wmPtr->gridWin != NULL) { + hintsPtr->base_width = winPtr->reqWidth + - (wmPtr->reqGridWidth * wmPtr->widthInc); + if (hintsPtr->base_width < 0) { + hintsPtr->base_width = 0; + } + hintsPtr->base_height = winPtr->reqHeight + wmPtr->menuHeight + - (wmPtr->reqGridHeight * wmPtr->heightInc); + if (hintsPtr->base_height < 0) { + hintsPtr->base_height = 0; + } + hintsPtr->min_width = hintsPtr->base_width + + (wmPtr->minWidth * wmPtr->widthInc); + hintsPtr->min_height = hintsPtr->base_height + + (wmPtr->minHeight * wmPtr->heightInc); + hintsPtr->max_width = hintsPtr->base_width + + (maxWidth * wmPtr->widthInc); + hintsPtr->max_height = hintsPtr->base_height + + (maxHeight * wmPtr->heightInc); + } else { + hintsPtr->min_width = wmPtr->minWidth; + hintsPtr->min_height = wmPtr->minHeight; + hintsPtr->max_width = maxWidth; + hintsPtr->max_height = maxHeight; + hintsPtr->base_width = 0; + hintsPtr->base_height = 0; + } + hintsPtr->width_inc = wmPtr->widthInc; + hintsPtr->height_inc = wmPtr->heightInc; + hintsPtr->min_aspect.x = wmPtr->minAspect.x; + hintsPtr->min_aspect.y = wmPtr->minAspect.y; + hintsPtr->max_aspect.x = wmPtr->maxAspect.x; + hintsPtr->max_aspect.y = wmPtr->maxAspect.y; + hintsPtr->win_gravity = wmPtr->gravity; + hintsPtr->flags = wmPtr->sizeHintsFlags | PMinSize | PMaxSize; + + /* + * If the window isn't supposed to be resizable, then set the + * minimum and maximum dimensions to be the same. + */ + + if (wmPtr->flags & WM_WIDTH_NOT_RESIZABLE) { + if (wmPtr->width >= 0) { + hintsPtr->min_width = wmPtr->width; + } else { + hintsPtr->min_width = winPtr->reqWidth; + } + hintsPtr->max_width = hintsPtr->min_width; + } + if (wmPtr->flags & WM_HEIGHT_NOT_RESIZABLE) { + if (wmPtr->height >= 0) { + hintsPtr->min_height = wmPtr->height; + } else { + hintsPtr->min_height = winPtr->reqHeight + wmPtr->menuHeight; + } + hintsPtr->max_height = hintsPtr->min_height; + } + + XSetWMNormalHints(winPtr->display, wmPtr->wrapperPtr->window, hintsPtr); + + XFree((char *) hintsPtr); +} + +/* + *---------------------------------------------------------------------- + * + * WaitForConfigureNotify -- + * + * This procedure is invoked in order to synchronize with the + * window manager. It waits for a ConfigureNotify event to + * arrive, signalling that the window manager has seen an attempt + * on our part to move or resize a top-level window. + * + * Results: + * None. + * + * Side effects: + * Delays the execution of the process until a ConfigureNotify event + * arrives with serial number at least as great as serial. This + * is useful for two reasons: + * + * 1. It's important to distinguish ConfigureNotify events that are + * coming in response to a request we've made from those generated + * spontaneously by the user. The reason for this is that if the + * user resizes the window we take that as an order to ignore + * geometry requests coming from inside the window hierarchy. If + * we accidentally interpret a response to our request as a + * user-initiated action, the window will stop responding to + * new geometry requests. To make this distinction, (a) this + * procedure sets a flag for TopLevelEventProc to indicate that + * we're waiting to sync with the wm, and (b) all changes to + * the size of a top-level window are followed by calls to this + * procedure. + * 2. Races and confusion can come about if there are multiple + * operations outstanding at a time (e.g. two different resizes + * of the top-level window: it's hard to tell which of the + * ConfigureNotify events coming back is for which request). + * While waiting, all events covered by StructureNotifyMask are + * processed and all others are deferred. + * + *---------------------------------------------------------------------- + */ + +static void +WaitForConfigureNotify(winPtr, serial) + TkWindow *winPtr; /* Top-level window for which we want + * to see a ConfigureNotify. */ + unsigned long serial; /* Serial number of resize request. Want to + * be sure wm has seen this. */ +{ + WmInfo *wmPtr = winPtr->wmInfoPtr; + XEvent event; + int diff, code; + int gotConfig = 0; + + /* + * One more tricky detail about this procedure. In some cases the + * window manager will decide to ignore a configure request (e.g. + * because it thinks the window is already in the right place). + * To avoid hanging in this situation, only wait for a few seconds, + * then give up. + */ + + while (!gotConfig) { + wmPtr->flags |= WM_SYNC_PENDING; + code = WaitForEvent(winPtr->display, wmPtr->wrapperPtr->window, + ConfigureNotify, &event); + wmPtr->flags &= ~WM_SYNC_PENDING; + if (code != TCL_OK) { + if (wmTracing) { + printf("WaitForConfigureNotify giving up on %s\n", + winPtr->pathName); + } + break; + } + diff = event.xconfigure.serial - serial; + if (diff >= 0) { + gotConfig = 1; + } + } + wmPtr->flags &= ~WM_MOVE_PENDING; + if (wmTracing) { + printf("WaitForConfigureNotify finished with %s, serial %ld\n", + winPtr->pathName, serial); + } +} + +/* + *---------------------------------------------------------------------- + * + * WaitForEvent -- + * + * This procedure is used by WaitForConfigureNotify and + * WaitForMapNotify to wait for an event of a certain type + * to arrive. + * + * Results: + * Under normal conditions, TCL_OK is returned and an event for + * display and window that matches "mask" is stored in *eventPtr. + * This event has already been processed by Tk before this procedure + * returns. If a long time goes by with no event of the right type + * arriving, or if an error occurs while waiting for the event to + * arrive, then TCL_ERROR is returned. + * + * Side effects: + * While waiting for the desired event to occur, Configurenotify + * events for window are processed, as are all ReparentNotify events, + * + *---------------------------------------------------------------------- + */ + +static int +WaitForEvent(display, window, type, eventPtr) + Display *display; /* Display event is coming from. */ + Window window; /* Window for which event is desired. */ + int type; /* Type of event that is wanted. */ + XEvent *eventPtr; /* Place to store event. */ +{ + WaitRestrictInfo info; + Tk_RestrictProc *oldRestrictProc; + ClientData oldRestrictData; + Tcl_Time timeout; + + /* + * Set up an event filter to select just the events we want, and + * a timer handler, then wait for events until we get the event + * we want or a timeout happens. + */ + + info.display = display; + info.window = window; + info.type = type; + info.eventPtr = eventPtr; + info.foundEvent = 0; + oldRestrictProc = Tk_RestrictEvents(WaitRestrictProc, (ClientData) &info, + &oldRestrictData); + + TclpGetTime(&timeout); + timeout.sec += 2; + + while (!info.foundEvent) { + if (!TkUnixDoOneXEvent(&timeout)) { + break; + } + } + (void) Tk_RestrictEvents(oldRestrictProc, oldRestrictData, + &oldRestrictData); + if (info.foundEvent) { + return TCL_OK; + } + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * WaitRestrictProc -- + * + * This procedure is a Tk_RestrictProc that is used to filter + * events while WaitForEvent is active. + * + * Results: + * Returns TK_PROCESS_EVENT if the right event is found. Also + * returns TK_PROCESS_EVENT if any ReparentNotify event is found + * for window or if the event is a ConfigureNotify for window. + * Otherwise returns TK_DEFER_EVENT. + * + * Side effects: + * An event may get stored in the area indicated by the caller + * of WaitForEvent. + * + *---------------------------------------------------------------------- + */ + +static Tk_RestrictAction +WaitRestrictProc(clientData, eventPtr) + ClientData clientData; /* Pointer to WaitRestrictInfo structure. */ + XEvent *eventPtr; /* Event that is about to be handled. */ +{ + WaitRestrictInfo *infoPtr = (WaitRestrictInfo *) clientData; + + if (eventPtr->type == ReparentNotify) { + return TK_PROCESS_EVENT; + } + if ((eventPtr->xany.window != infoPtr->window) + || (eventPtr->xany.display != infoPtr->display)) { + return TK_DEFER_EVENT; + } + if (eventPtr->type == infoPtr->type) { + *infoPtr->eventPtr = *eventPtr; + infoPtr->foundEvent = 1; + return TK_PROCESS_EVENT; + } + if (eventPtr->type == ConfigureNotify) { + return TK_PROCESS_EVENT; + } + return TK_DEFER_EVENT; +} + +/* + *---------------------------------------------------------------------- + * + * WaitForMapNotify -- + * + * This procedure is invoked in order to synchronize with the + * window manager. It waits for the window's mapped state to + * reach the value given by mapped. + * + * Results: + * None. + * + * Side effects: + * Delays the execution of the process until winPtr becomes mapped + * or unmapped, depending on the "mapped" argument. This allows us + * to synchronize with the window manager, and allows us to + * identify changes in window size that come about when the window + * manager first starts managing the window (as opposed to those + * requested interactively by the user later). See the comments + * for WaitForConfigureNotify and WM_SYNC_PENDING. While waiting, + * all events covered by StructureNotifyMask are processed and all + * others are deferred. + * + *---------------------------------------------------------------------- + */ + +static void +WaitForMapNotify(winPtr, mapped) + TkWindow *winPtr; /* Top-level window for which we want + * to see a particular mapping state. */ + int mapped; /* If non-zero, wait for window to become + * mapped, otherwise wait for it to become + * unmapped. */ +{ + WmInfo *wmPtr = winPtr->wmInfoPtr; + XEvent event; + int code; + + while (1) { + if (mapped) { + if (winPtr->flags & TK_MAPPED) { + break; + } + } else if (!(winPtr->flags & TK_MAPPED)) { + break; + } + wmPtr->flags |= WM_SYNC_PENDING; + code = WaitForEvent(winPtr->display, wmPtr->wrapperPtr->window, + mapped ? MapNotify : UnmapNotify, &event); + wmPtr->flags &= ~WM_SYNC_PENDING; + if (code != TCL_OK) { + /* + * There are some bizarre situations in which the window + * manager can't respond or chooses not to (e.g. if we've + * got a grab set it can't respond). If this happens then + * just quit. + */ + + if (wmTracing) { + printf("WaitForMapNotify giving up on %s\n", winPtr->pathName); + } + break; + } + } + wmPtr->flags &= ~WM_MOVE_PENDING; + if (wmTracing) { + printf("WaitForMapNotify finished with %s\n", winPtr->pathName); + } +} + +/* + *-------------------------------------------------------------- + * + * UpdateHints -- + * + * This procedure is called to update the window manager's + * hints information from the information in a WmInfo + * structure. + * + * Results: + * None. + * + * Side effects: + * Properties get changed for winPtr. + * + *-------------------------------------------------------------- + */ + +static void +UpdateHints(winPtr) + TkWindow *winPtr; +{ + WmInfo *wmPtr = winPtr->wmInfoPtr; + + if (wmPtr->flags & WM_NEVER_MAPPED) { + return; + } + XSetWMHints(winPtr->display, wmPtr->wrapperPtr->window, &wmPtr->hints); +} + +/* + *-------------------------------------------------------------- + * + * ParseGeometry -- + * + * This procedure parses a geometry string and updates + * information used to control the geometry of a top-level + * window. + * + * Results: + * A standard Tcl return value, plus an error message in + * interp->result if an error occurs. + * + * Side effects: + * The size and/or location of winPtr may change. + * + *-------------------------------------------------------------- + */ + +static int +ParseGeometry(interp, string, winPtr) + Tcl_Interp *interp; /* Used for error reporting. */ + char *string; /* String containing new geometry. Has the + * standard form "=wxh+x+y". */ + TkWindow *winPtr; /* Pointer to top-level window whose + * geometry is to be changed. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + int x, y, width, height, flags; + char *end; + register char *p = string; + + /* + * The leading "=" is optional. + */ + + if (*p == '=') { + p++; + } + + /* + * Parse the width and height, if they are present. Don't + * actually update any of the fields of wmPtr until we've + * successfully parsed the entire geometry string. + */ + + width = wmPtr->width; + height = wmPtr->height; + x = wmPtr->x; + y = wmPtr->y; + flags = wmPtr->flags; + if (isdigit(UCHAR(*p))) { + width = strtoul(p, &end, 10); + p = end; + if (*p != 'x') { + goto error; + } + p++; + if (!isdigit(UCHAR(*p))) { + goto error; + } + height = strtoul(p, &end, 10); + p = end; + } + + /* + * Parse the X and Y coordinates, if they are present. + */ + + if (*p != '\0') { + flags &= ~(WM_NEGATIVE_X | WM_NEGATIVE_Y); + if (*p == '-') { + flags |= WM_NEGATIVE_X; + } else if (*p != '+') { + goto error; + } + p++; + if (!isdigit(UCHAR(*p)) && (*p != '-')) { + goto error; + } + x = strtol(p, &end, 10); + p = end; + if (*p == '-') { + flags |= WM_NEGATIVE_Y; + } else if (*p != '+') { + goto error; + } + p++; + if (!isdigit(UCHAR(*p)) && (*p != '-')) { + goto error; + } + y = strtol(p, &end, 10); + if (*end != '\0') { + goto error; + } + + /* + * Assume that the geometry information came from the user, + * unless an explicit source has been specified. Otherwise + * most window managers assume that the size hints were + * program-specified and they ignore them. + */ + + if ((wmPtr->sizeHintsFlags & (USPosition|PPosition)) == 0) { + wmPtr->sizeHintsFlags |= USPosition; + flags |= WM_UPDATE_SIZE_HINTS; + } + } + + /* + * Everything was parsed OK. Update the fields of *wmPtr and + * arrange for the appropriate information to be percolated out + * to the window manager at the next idle moment. + */ + + wmPtr->width = width; + wmPtr->height = height; + wmPtr->x = x; + wmPtr->y = y; + flags |= WM_MOVE_PENDING; + wmPtr->flags = flags; + + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } + return TCL_OK; + + error: + Tcl_AppendResult(interp, "bad geometry specifier \"", + string, "\"", (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetRootCoords -- + * + * Given a token for a window, this procedure traces through the + * window's lineage to find the (virtual) root-window coordinates + * corresponding to point (0,0) in the window. + * + * Results: + * The locations pointed to by xPtr and yPtr are filled in with + * the root coordinates of the (0,0) point in tkwin. If a virtual + * root window is in effect for the window, then the coordinates + * in the virtual root are returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +Tk_GetRootCoords(tkwin, xPtr, yPtr) + Tk_Window tkwin; /* Token for window. */ + int *xPtr; /* Where to store x-displacement of (0,0). */ + int *yPtr; /* Where to store y-displacement of (0,0). */ +{ + int x, y; + register TkWindow *winPtr = (TkWindow *) tkwin; + + /* + * Search back through this window's parents all the way to a + * top-level window, combining the offsets of each window within + * its parent. + */ + + x = y = 0; + while (1) { + x += winPtr->changes.x + winPtr->changes.border_width; + y += winPtr->changes.y + winPtr->changes.border_width; + if ((winPtr->wmInfoPtr != NULL) + && (winPtr->wmInfoPtr->menubar == (Tk_Window) winPtr)) { + /* + * This window is a special menubar; switch over to its + * associated toplevel, compensate for their differences in + * y coordinates, then continue with the toplevel (in case + * it's embedded). + */ + + y -= winPtr->wmInfoPtr->menuHeight; + winPtr = winPtr->wmInfoPtr->winPtr; + continue; + } + if (winPtr->flags & TK_TOP_LEVEL) { + TkWindow *otherPtr; + + if (!(winPtr->flags & TK_EMBEDDED)) { + break; + } + otherPtr = TkpGetOtherWindow(winPtr); + if (otherPtr == NULL) { + /* + * The container window is not in the same application. + * Query the X server. + */ + + Window root, dummyChild; + int rootX, rootY; + + root = winPtr->wmInfoPtr->vRoot; + if (root == None) { + root = RootWindowOfScreen(Tk_Screen((Tk_Window)winPtr)); + } + XTranslateCoordinates(winPtr->display, winPtr->window, + root, 0, 0, &rootX, &rootY, &dummyChild); + x += rootX; + y += rootY; + break; + } else { + /* + * The container window is in the same application. + * Let's query its coordinates. + */ + + winPtr = otherPtr; + continue; + } + } + winPtr = winPtr->parentPtr; + if (winPtr == NULL) { + break; + } + } + *xPtr = x; + *yPtr = y; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_CoordsToWindow -- + * + * Given the (virtual) root coordinates of a point, this procedure + * returns the token for the top-most window covering that point, + * if there exists such a window in this application. + * + * Results: + * The return result is either a token for the window corresponding + * to rootX and rootY, or else NULL to indicate that there is no such + * window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +Tk_CoordsToWindow(rootX, rootY, tkwin) + int rootX, rootY; /* Coordinates of point in root window. If + * a virtual-root window manager is in use, + * these coordinates refer to the virtual + * root, not the real root. */ + Tk_Window tkwin; /* Token for any window in application; + * used to identify the display. */ +{ + Window window, parent, child; + int x, y, childX, childY, tmpx, tmpy, bd; + WmInfo *wmPtr; + TkWindow *winPtr, *childPtr, *nextPtr; + + /* + * Step 1: scan the list of toplevel windows to see if there is a + * virtual root for the screen we're interested in. If so, we have + * to translate the coordinates from virtual root to root + * coordinates. + */ + + parent = window = RootWindowOfScreen(Tk_Screen(tkwin)); + x = rootX; + y = rootY; + for (wmPtr = firstWmPtr; wmPtr != NULL; wmPtr = wmPtr->nextPtr) { + if (Tk_Screen(wmPtr->winPtr) != Tk_Screen(tkwin)) { + continue; + } + if (wmPtr->vRoot == None) { + continue; + } + UpdateVRootGeometry(wmPtr); + parent = wmPtr->vRoot; + break; + } + + /* + * Step 2: work down through the window hierarchy starting at the + * root. For each window, find the child that contains the given + * point and then see if this child is either a wrapper for one of + * our toplevel windows or a window manager decoration window for + * one of our toplevels. This approach handles several tricky + * cases: + * + * 1. There may be a virtual root window between the root and one of + * our toplevels. + * 2. If a toplevel is embedded, we may have to search through the + * windows of the container application(s) before getting to + * the toplevel. + */ + + while (1) { + if (XTranslateCoordinates(Tk_Display(tkwin), parent, window, + x, y, &childX, &childY, &child) == False) { + panic("Tk_CoordsToWindow got False return from XTranslateCoordinates"); + } + if (child == None) { + return NULL; + } + for (wmPtr = firstWmPtr; wmPtr != NULL; wmPtr = wmPtr->nextPtr) { + if (wmPtr->reparent == child) { + goto gotToplevel; + } + if (wmPtr->wrapperPtr != NULL) { + if (child == wmPtr->wrapperPtr->window) { + goto gotToplevel; + } + } else if (child == wmPtr->winPtr->window) { + goto gotToplevel; + } + } + x = childX; + y = childY; + parent = window; + window = child; + } + + gotToplevel: + winPtr = wmPtr->winPtr; + if (winPtr->mainPtr != ((TkWindow *) tkwin)->mainPtr) { + return NULL; + } + + /* + * Step 3: at this point winPtr and wmPtr refer to the toplevel that + * contains the given coordinates, and childX and childY give the + * translated coordinates in the *parent* of the toplevel. Now + * decide whether the coordinates are in the menubar or the actual + * toplevel, and translate the coordinates into the coordinate + * system of that window. + */ + + x = childX - winPtr->changes.x; + y = childY - winPtr->changes.y; + if ((x < 0) || (x >= winPtr->changes.width) + || (y >= winPtr->changes.height)) { + return NULL; + } + if (y < 0) { + winPtr = (TkWindow *) wmPtr->menubar; + if (winPtr == NULL) { + return NULL; + } + y += wmPtr->menuHeight; + if (y < 0) { + return NULL; + } + } + + /* + * Step 4: work down through the hierarchy underneath the current + * window. At each level, scan through all the children to find the + * highest one in the stacking order that contains the point. Then + * repeat the whole process on that child. + */ + + while (1) { + nextPtr = NULL; + for (childPtr = winPtr->childList; childPtr != NULL; + childPtr = childPtr->nextPtr) { + if (!Tk_IsMapped(childPtr) || (childPtr->flags & TK_TOP_LEVEL)) { + continue; + } + if (childPtr->flags & TK_REPARENTED) { + continue; + } + tmpx = x - childPtr->changes.x; + tmpy = y - childPtr->changes.y; + bd = childPtr->changes.border_width; + if ((tmpx >= -bd) && (tmpy >= -bd) + && (tmpx < (childPtr->changes.width + bd)) + && (tmpy < (childPtr->changes.height + bd))) { + nextPtr = childPtr; + } + } + if (nextPtr == NULL) { + break; + } + winPtr = nextPtr; + x -= winPtr->changes.x; + y -= winPtr->changes.y; + if ((winPtr->flags & TK_CONTAINER) + && (winPtr->flags & TK_BOTH_HALVES)) { + /* + * The window containing the point is a container, and the + * embedded application is in this same process. Switch + * over to the toplevel for the embedded application and + * start processing that toplevel from scratch. + */ + + winPtr = TkpGetOtherWindow(winPtr); + wmPtr = winPtr->wmInfoPtr; + childX = x; + childY = y; + goto gotToplevel; + } + } + return (Tk_Window) winPtr; +} + +/* + *---------------------------------------------------------------------- + * + * UpdateVRootGeometry -- + * + * This procedure is called to update all the virtual root + * geometry information in wmPtr. + * + * Results: + * None. + * + * Side effects: + * The vRootX, vRootY, vRootWidth, and vRootHeight fields in + * wmPtr are filled with the most up-to-date information. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateVRootGeometry(wmPtr) + WmInfo *wmPtr; /* Window manager information to be + * updated. The wmPtr->vRoot field must + * be valid. */ +{ + TkWindow *winPtr = wmPtr->winPtr; + int bd; + unsigned int dummy; + Window dummy2; + Status status; + Tk_ErrorHandler handler; + + /* + * If this isn't a virtual-root window manager, just return information + * about the screen. + */ + + wmPtr->flags &= ~WM_VROOT_OFFSET_STALE; + if (wmPtr->vRoot == None) { + noVRoot: + wmPtr->vRootX = wmPtr->vRootY = 0; + wmPtr->vRootWidth = DisplayWidth(winPtr->display, winPtr->screenNum); + wmPtr->vRootHeight = DisplayHeight(winPtr->display, winPtr->screenNum); + return; + } + + /* + * Refresh the virtual root information if it's out of date. + */ + + handler = Tk_CreateErrorHandler(winPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + status = XGetGeometry(winPtr->display, wmPtr->vRoot, + &dummy2, &wmPtr->vRootX, &wmPtr->vRootY, + (unsigned int *) &wmPtr->vRootWidth, + (unsigned int *) &wmPtr->vRootHeight, (unsigned int *) &bd, + &dummy); + if (wmTracing) { + printf("UpdateVRootGeometry: x = %d, y = %d, width = %d, ", + wmPtr->vRootX, wmPtr->vRootY, wmPtr->vRootWidth); + printf("height = %d, status = %d\n", wmPtr->vRootHeight, status); + } + Tk_DeleteErrorHandler(handler); + if (status == 0) { + /* + * The virtual root is gone! Pretend that it never existed. + */ + + wmPtr->vRoot = None; + goto noVRoot; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetVRootGeometry -- + * + * This procedure returns information about the virtual root + * window corresponding to a particular Tk window. + * + * Results: + * The values at xPtr, yPtr, widthPtr, and heightPtr are set + * with the offset and dimensions of the root window corresponding + * to tkwin. If tkwin is being managed by a virtual root window + * manager these values correspond to the virtual root window being + * used for tkwin; otherwise the offsets will be 0 and the + * dimensions will be those of the screen. + * + * Side effects: + * Vroot window information is refreshed if it is out of date. + * + *---------------------------------------------------------------------- + */ + +void +Tk_GetVRootGeometry(tkwin, xPtr, yPtr, widthPtr, heightPtr) + Tk_Window tkwin; /* Window whose virtual root is to be + * queried. */ + int *xPtr, *yPtr; /* Store x and y offsets of virtual root + * here. */ + int *widthPtr, *heightPtr; /* Store dimensions of virtual root here. */ +{ + WmInfo *wmPtr; + TkWindow *winPtr = (TkWindow *) tkwin; + + /* + * Find the top-level window for tkwin, and locate the window manager + * information for that window. + */ + + while (!(winPtr->flags & TK_TOP_LEVEL) && (winPtr->parentPtr != NULL)) { + winPtr = winPtr->parentPtr; + } + wmPtr = winPtr->wmInfoPtr; + + /* + * Make sure that the geometry information is up-to-date, then copy + * it out to the caller. + */ + + if (wmPtr->flags & WM_VROOT_OFFSET_STALE) { + UpdateVRootGeometry(wmPtr); + } + *xPtr = wmPtr->vRootX; + *yPtr = wmPtr->vRootY; + *widthPtr = wmPtr->vRootWidth; + *heightPtr = wmPtr->vRootHeight; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_MoveToplevelWindow -- + * + * This procedure is called instead of Tk_MoveWindow to adjust + * the x-y location of a top-level window. It delays the actual + * move to a later time and keeps window-manager information + * up-to-date with the move + * + * Results: + * None. + * + * Side effects: + * The window is eventually moved so that its upper-left corner + * (actually, the upper-left corner of the window's decorative + * frame, if there is one) is at (x,y). + * + *---------------------------------------------------------------------- + */ + +void +Tk_MoveToplevelWindow(tkwin, x, y) + Tk_Window tkwin; /* Window to move. */ + int x, y; /* New location for window (within + * parent). */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + register WmInfo *wmPtr = winPtr->wmInfoPtr; + + if (!(winPtr->flags & TK_TOP_LEVEL)) { + panic("Tk_MoveToplevelWindow called with non-toplevel window"); + } + wmPtr->x = x; + wmPtr->y = y; + wmPtr->flags |= WM_MOVE_PENDING; + wmPtr->flags &= ~(WM_NEGATIVE_X|WM_NEGATIVE_Y); + if ((wmPtr->sizeHintsFlags & (USPosition|PPosition)) == 0) { + wmPtr->sizeHintsFlags |= USPosition; + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + } + + /* + * If the window has already been mapped, must bring its geometry + * up-to-date immediately, otherwise an event might arrive from the + * server that would overwrite wmPtr->x and wmPtr->y and lose the + * new position. + */ + + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + if (wmPtr->flags & WM_UPDATE_PENDING) { + Tcl_CancelIdleCall(UpdateGeometryInfo, (ClientData) winPtr); + } + UpdateGeometryInfo((ClientData) winPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * UpdateWmProtocols -- + * + * This procedure transfers the most up-to-date information about + * window manager protocols from the WmInfo structure to the actual + * property on the top-level window. + * + * Results: + * None. + * + * Side effects: + * The WM_PROTOCOLS property gets changed for wmPtr's window. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateWmProtocols(wmPtr) + register WmInfo *wmPtr; /* Information about top-level window. */ +{ + register ProtocolHandler *protPtr; + Atom deleteWindowAtom; + int count; + Atom *arrayPtr, *atomPtr; + + /* + * There are only two tricky parts here. First, there could be any + * number of atoms for the window, so count them and malloc an array + * to hold all of their atoms. Second, we *always* want to respond + * to the WM_DELETE_WINDOW protocol, even if no-one's officially asked. + */ + + for (protPtr = wmPtr->protPtr, count = 1; protPtr != NULL; + protPtr = protPtr->nextPtr, count++) { + /* Empty loop body; we're just counting the handlers. */ + } + arrayPtr = (Atom *) ckalloc((unsigned) (count * sizeof(Atom))); + deleteWindowAtom = Tk_InternAtom((Tk_Window) wmPtr->winPtr, + "WM_DELETE_WINDOW"); + arrayPtr[0] = deleteWindowAtom; + for (protPtr = wmPtr->protPtr, atomPtr = &arrayPtr[1]; + protPtr != NULL; protPtr = protPtr->nextPtr) { + if (protPtr->protocol != deleteWindowAtom) { + *atomPtr = protPtr->protocol; + atomPtr++; + } + } + XChangeProperty(wmPtr->winPtr->display, wmPtr->wrapperPtr->window, + Tk_InternAtom((Tk_Window) wmPtr->winPtr, "WM_PROTOCOLS"), + XA_ATOM, 32, PropModeReplace, (unsigned char *) arrayPtr, + atomPtr-arrayPtr); + ckfree((char *) arrayPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TkWmProtocolEventProc -- + * + * This procedure is called by the Tk_HandleEvent whenever a + * ClientMessage event arrives whose type is "WM_PROTOCOLS". + * This procedure handles the message from the window manager + * in an appropriate fashion. + * + * Results: + * None. + * + * Side effects: + * Depends on what sort of handler, if any, was set up for the + * protocol. + * + *---------------------------------------------------------------------- + */ + +void +TkWmProtocolEventProc(winPtr, eventPtr) + TkWindow *winPtr; /* Window to which the event was sent. */ + XEvent *eventPtr; /* X event. */ +{ + WmInfo *wmPtr; + register ProtocolHandler *protPtr; + Atom protocol; + int result; + char *protocolName; + Tcl_Interp *interp; + + wmPtr = winPtr->wmInfoPtr; + if (wmPtr == NULL) { + return; + } + protocol = (Atom) eventPtr->xclient.data.l[0]; + + /* + * Note: it's very important to retrieve the protocol name now, + * before invoking the command, even though the name won't be used + * until after the command returns. This is because the command + * could delete winPtr, making it impossible for us to use it + * later in the call to Tk_GetAtomName. + */ + + protocolName = Tk_GetAtomName((Tk_Window) winPtr, protocol); + for (protPtr = wmPtr->protPtr; protPtr != NULL; + protPtr = protPtr->nextPtr) { + if (protocol == protPtr->protocol) { + Tcl_Preserve((ClientData) protPtr); + interp = protPtr->interp; + Tcl_Preserve((ClientData) interp); + result = Tcl_GlobalEval(interp, protPtr->command); + if (result != TCL_OK) { + Tcl_AddErrorInfo(interp, "\n (command for \""); + Tcl_AddErrorInfo(interp, protocolName); + Tcl_AddErrorInfo(interp, + "\" window manager protocol)"); + Tcl_BackgroundError(interp); + } + Tcl_Release((ClientData) interp); + Tcl_Release((ClientData) protPtr); + return; + } + } + + /* + * No handler was present for this protocol. If this is a + * WM_DELETE_WINDOW message then just destroy the window. + */ + + if (protocol == Tk_InternAtom((Tk_Window) winPtr, "WM_DELETE_WINDOW")) { + Tk_DestroyWindow((Tk_Window) wmPtr->winPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWmRestackToplevel -- + * + * This procedure restacks a top-level window. + * + * Results: + * None. + * + * Side effects: + * WinPtr gets restacked as specified by aboveBelow and otherPtr. + * This procedure doesn't return until the restack has taken + * effect and the ConfigureNotify event for it has been received. + * + *---------------------------------------------------------------------- + */ + +void +TkWmRestackToplevel(winPtr, aboveBelow, otherPtr) + TkWindow *winPtr; /* Window to restack. */ + int aboveBelow; /* Gives relative position for restacking; + * must be Above or Below. */ + TkWindow *otherPtr; /* Window relative to which to restack; + * if NULL, then winPtr gets restacked + * above or below *all* siblings. */ +{ + XWindowChanges changes; + XWindowAttributes atts; + unsigned int mask; + Window window, dummy1, dummy2, vRoot; + Window *children; + unsigned int numChildren; + int i; + int desiredIndex = 0; /* Initialized to stop gcc warnings. */ + int ourIndex = 0; /* Initialized to stop gcc warnings. */ + unsigned long serial; + XEvent event; + int diff; + Tk_ErrorHandler handler; + TkWindow *wrapperPtr; + + changes.stack_mode = aboveBelow; + changes.sibling = None; + mask = CWStackMode; + if (winPtr->window == None) { + Tk_MakeWindowExist((Tk_Window) winPtr); + } + if (winPtr->wmInfoPtr->flags & WM_NEVER_MAPPED) { + /* + * Can't set stacking order properly until the window is on the + * screen (mapping it may give it a reparent window), so make sure + * it's on the screen. + */ + + TkWmMapWindow(winPtr); + } + wrapperPtr = winPtr->wmInfoPtr->wrapperPtr; + window = (winPtr->wmInfoPtr->reparent != None) + ? winPtr->wmInfoPtr->reparent : wrapperPtr->window; + if (otherPtr != NULL) { + if (otherPtr->window == None) { + Tk_MakeWindowExist((Tk_Window) otherPtr); + } + if (otherPtr->wmInfoPtr->flags & WM_NEVER_MAPPED) { + TkWmMapWindow(otherPtr); + } + changes.sibling = (otherPtr->wmInfoPtr->reparent != None) + ? otherPtr->wmInfoPtr->reparent + : otherPtr->wmInfoPtr->wrapperPtr->window; + mask = CWStackMode|CWSibling; + } + + /* + * Before actually reconfiguring the window, see if it's already + * in the right place. If so then don't reconfigure it. The + * reason for this extra work is that some window managers will + * ignore the reconfigure request if the window is already in + * the right place, causing a long delay in WaitForConfigureNotify + * while it times out. Special note: if the window is almost in + * the right place, and the only windows between it and the right + * place aren't mapped, then we don't reconfigure it either, for + * the same reason. + */ + + vRoot = winPtr->wmInfoPtr->vRoot; + if (vRoot == None) { + vRoot = RootWindowOfScreen(Tk_Screen((Tk_Window) winPtr)); + } + if (XQueryTree(winPtr->display, vRoot, &dummy1, &dummy2, + &children, &numChildren) != 0) { + /* + * Find where our window is in the stacking order, and + * compute the desired location in the stacking order. + */ + + for (i = 0; i < numChildren; i++) { + if (children[i] == window) { + ourIndex = i; + } + if (children[i] == changes.sibling) { + desiredIndex = i; + } + } + if (mask & CWSibling) { + if (aboveBelow == Above) { + if (desiredIndex < ourIndex) { + desiredIndex += 1; + } + } else { + if (desiredIndex > ourIndex) { + desiredIndex -= 1; + } + } + } else { + if (aboveBelow == Above) { + desiredIndex = numChildren-1; + } else { + desiredIndex = 0; + } + } + + /* + * See if there are any mapped windows between where we are + * and where we want to be. + */ + + handler = Tk_CreateErrorHandler(winPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + while (desiredIndex != ourIndex) { + if ((XGetWindowAttributes(winPtr->display, children[desiredIndex], + &atts) != 0) && (atts.map_state != IsUnmapped)) { + break; + } + if (desiredIndex < ourIndex) { + desiredIndex++; + } else { + desiredIndex--; + } + } + Tk_DeleteErrorHandler(handler); + XFree((char *) children); + if (ourIndex == desiredIndex) { + return; + } + } + + /* + * Reconfigure the window. This tricky because of two things: + * (a) Some window managers, like olvwm, insist that we raise + * or lower the toplevel window itself, as opposed to its + * decorative frame. Attempts to raise or lower the frame + * are ignored. + * (b) If the raise or lower is relative to a sibling, X will + * generate an error unless we work with the frames (the + * toplevels themselves aren't siblings). + * Fortunately, the procedure XReconfigureWMWindow is supposed + * to handle all of this stuff, so be careful to use it instead + * of XConfigureWindow. + */ + + serial = NextRequest(winPtr->display); + if (window != wrapperPtr->window) { + /* + * We're going to have to wait for events on a window that + * Tk doesn't own, so we have to tell X specially that we + * want to get events on that window. To make matters worse, + * it's possible that the window doesn't exist anymore (e.g. + * the toplevel could have been withdrawn) so ignore events + * occurring during the request. + */ + + handler = Tk_CreateErrorHandler(winPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + XSelectInput(winPtr->display, window, StructureNotifyMask); + Tk_DeleteErrorHandler(handler); + } + XReconfigureWMWindow(winPtr->display, wrapperPtr->window, + Tk_ScreenNumber((Tk_Window) winPtr), mask, &changes); + + /* + * Wait for the reconfiguration to complete. If we don't wait, then + * the window may not restack for a while and the application might + * observe it before it has restacked. Waiting for the reconfiguration + * is tricky if winPtr has been reparented, since the window getting + * the event isn't one that Tk owns. + */ + + if (window == wrapperPtr->window) { + WaitForConfigureNotify(winPtr, serial); + } else { + while (1) { + if (WaitForEvent(winPtr->display, window, ConfigureNotify, + &event) != TCL_OK) { + break; + } + diff = event.xconfigure.serial - serial; + if (diff >= 0) { + break; + } + } + + /* + * Ignore errors that occur when we are de-selecting events on + * window, since it's possible that the window doesn't exist + * anymore (see comment above previous call to XSelectInput). + */ + + handler = Tk_CreateErrorHandler(winPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + XSelectInput(winPtr->display, window, (long) 0); + Tk_DeleteErrorHandler(handler); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWmAddToColormapWindows -- + * + * This procedure is called to add a given window to the + * WM_COLORMAP_WINDOWS property for its top-level, if it + * isn't already there. It is invoked by the Tk code that + * creates a new colormap, in order to make sure that colormap + * information is propagated to the window manager by default. + * + * Results: + * None. + * + * Side effects: + * WinPtr's window gets added to the WM_COLORMAP_WINDOWS + * property of its nearest top-level ancestor, unless the + * colormaps have been set explicitly with the + * "wm colormapwindows" command. + * + *---------------------------------------------------------------------- + */ + +void +TkWmAddToColormapWindows(winPtr) + TkWindow *winPtr; /* Window with a non-default colormap. + * Should not be a top-level window. */ +{ + TkWindow *wrapperPtr; + TkWindow *topPtr; + Window *oldPtr, *newPtr; + int count, i; + + if (winPtr->window == None) { + return; + } + + for (topPtr = winPtr->parentPtr; ; topPtr = topPtr->parentPtr) { + if (topPtr == NULL) { + /* + * Window is being deleted. Skip the whole operation. + */ + + return; + } + if (topPtr->flags & TK_TOP_LEVEL) { + break; + } + } + if (topPtr->wmInfoPtr->flags & WM_COLORMAPS_EXPLICIT) { + return; + } + if (topPtr->wmInfoPtr->wrapperPtr == NULL) { + CreateWrapper(topPtr->wmInfoPtr); + } + wrapperPtr = topPtr->wmInfoPtr->wrapperPtr; + + /* + * Fetch the old value of the property. + */ + + if (XGetWMColormapWindows(topPtr->display, wrapperPtr->window, + &oldPtr, &count) == 0) { + oldPtr = NULL; + count = 0; + } + + /* + * Make sure that the window isn't already in the list. + */ + + for (i = 0; i < count; i++) { + if (oldPtr[i] == winPtr->window) { + return; + } + } + + /* + * Make a new bigger array and use it to reset the property. + * Automatically add the toplevel itself as the last element + * of the list. + */ + + newPtr = (Window *) ckalloc((unsigned) ((count+2)*sizeof(Window))); + for (i = 0; i < count; i++) { + newPtr[i] = oldPtr[i]; + } + if (count == 0) { + count++; + } + newPtr[count-1] = winPtr->window; + newPtr[count] = topPtr->window; + XSetWMColormapWindows(topPtr->display, wrapperPtr->window, newPtr, + count+1); + ckfree((char *) newPtr); + if (oldPtr != NULL) { + XFree((char *) oldPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWmRemoveFromColormapWindows -- + * + * This procedure is called to remove a given window from the + * WM_COLORMAP_WINDOWS property for its top-level. It is invoked + * when windows are deleted. + * + * Results: + * None. + * + * Side effects: + * WinPtr's window gets removed from the WM_COLORMAP_WINDOWS + * property of its nearest top-level ancestor, unless the + * top-level itself is being deleted too. + * + *---------------------------------------------------------------------- + */ + +void +TkWmRemoveFromColormapWindows(winPtr) + TkWindow *winPtr; /* Window that may be present in + * WM_COLORMAP_WINDOWS property for its + * top-level. Should not be a top-level + * window. */ +{ + TkWindow *wrapperPtr; + TkWindow *topPtr; + Window *oldPtr; + int count, i, j; + + if (winPtr->window == None) { + return; + } + + for (topPtr = winPtr->parentPtr; ; topPtr = topPtr->parentPtr) { + if (topPtr == NULL) { + /* + * Ancestors have been deleted, so skip the whole operation. + * Seems like this can't ever happen? + */ + + return; + } + if (topPtr->flags & TK_TOP_LEVEL) { + break; + } + } + if (topPtr->flags & TK_ALREADY_DEAD) { + /* + * Top-level is being deleted, so there's no need to cleanup + * the WM_COLORMAP_WINDOWS property. + */ + + return; + } + if (topPtr->wmInfoPtr->wrapperPtr == NULL) { + CreateWrapper(topPtr->wmInfoPtr); + } + wrapperPtr = topPtr->wmInfoPtr->wrapperPtr; + if (wrapperPtr == NULL) { + return; + } + + /* + * Fetch the old value of the property. + */ + + if (XGetWMColormapWindows(topPtr->display, wrapperPtr->window, + &oldPtr, &count) == 0) { + return; + } + + /* + * Find the window and slide the following ones down to cover + * it up. + */ + + for (i = 0; i < count; i++) { + if (oldPtr[i] == winPtr->window) { + for (j = i ; j < count-1; j++) { + oldPtr[j] = oldPtr[j+1]; + } + XSetWMColormapWindows(topPtr->display, wrapperPtr->window, + oldPtr, count-1); + break; + } + } + XFree((char *) oldPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TkGetPointerCoords -- + * + * Fetch the position of the mouse pointer. + * + * Results: + * *xPtr and *yPtr are filled in with the (virtual) root coordinates + * of the mouse pointer for tkwin's display. If the pointer isn't + * on tkwin's screen, then -1 values are returned for both + * coordinates. The argument tkwin must be a toplevel window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkGetPointerCoords(tkwin, xPtr, yPtr) + Tk_Window tkwin; /* Toplevel window that identifies screen + * on which lookup is to be done. */ + int *xPtr, *yPtr; /* Store pointer coordinates here. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + WmInfo *wmPtr; + Window w, root, child; + int rootX, rootY; + unsigned int mask; + + wmPtr = winPtr->wmInfoPtr; + + w = wmPtr->vRoot; + if (w == None) { + w = RootWindow(winPtr->display, winPtr->screenNum); + } + if (XQueryPointer(winPtr->display, w, &root, &child, &rootX, &rootY, + xPtr, yPtr, &mask) != True) { + *xPtr = -1; + *yPtr = -1; + } +} + +/* + *---------------------------------------------------------------------- + * + * GetMaxSize -- + * + * This procedure computes the current maxWidth and maxHeight + * values for a window, taking into account the possibility + * that they may be defaulted. + * + * Results: + * The values at *maxWidthPtr and *maxHeightPtr are filled + * in with the maximum allowable dimensions of wmPtr's window, + * in grid units. If no maximum has been specified for the + * window, then this procedure computes the largest sizes that + * will fit on the screen. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +GetMaxSize(wmPtr, maxWidthPtr, maxHeightPtr) + WmInfo *wmPtr; /* Window manager information for the + * window. */ + int *maxWidthPtr; /* Where to store the current maximum + * width of the window. */ + int *maxHeightPtr; /* Where to store the current maximum + * height of the window. */ +{ + int tmp; + + if (wmPtr->maxWidth > 0) { + *maxWidthPtr = wmPtr->maxWidth; + } else { + /* + * Must compute a default width. Fill up the display, leaving a + * bit of extra space for the window manager's borders. + */ + + tmp = DisplayWidth(wmPtr->winPtr->display, wmPtr->winPtr->screenNum) + - 15; + if (wmPtr->gridWin != NULL) { + /* + * Gridding is turned on; convert from pixels to grid units. + */ + + tmp = wmPtr->reqGridWidth + + (tmp - wmPtr->winPtr->reqWidth)/wmPtr->widthInc; + } + *maxWidthPtr = tmp; + } + if (wmPtr->maxHeight > 0) { + *maxHeightPtr = wmPtr->maxHeight; + } else { + tmp = DisplayHeight(wmPtr->winPtr->display, wmPtr->winPtr->screenNum) + - 30; + if (wmPtr->gridWin != NULL) { + tmp = wmPtr->reqGridHeight + + (tmp - wmPtr->winPtr->reqHeight)/wmPtr->heightInc; + } + *maxHeightPtr = tmp; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpMakeMenuWindow -- + * + * Configure the window to be either a pull-down (or pop-up) + * menu, or as a toplevel (torn-off) menu or palette. + * + * Results: + * None. + * + * Side effects: + * Changes the style bit used to create a new Mac toplevel. + * + *---------------------------------------------------------------------- + */ + +void +TkpMakeMenuWindow(tkwin, transient) + Tk_Window tkwin; /* New window. */ + int transient; /* 1 means menu is only posted briefly as + * a popup or pulldown or cascade. 0 means + * menu is always visible, e.g. as a torn-off + * menu. Determines whether save_under and + * override_redirect should be set. */ +{ + WmInfo *wmPtr; + XSetWindowAttributes atts; + TkWindow *wrapperPtr; + + if (!Tk_IsTopLevel(tkwin)) { + return; + } + wmPtr = ((TkWindow *) tkwin)->wmInfoPtr; + if (wmPtr->wrapperPtr == NULL) { + CreateWrapper(wmPtr); + } + wrapperPtr = wmPtr->wrapperPtr; + if (transient) { + atts.override_redirect = True; + atts.save_under = True; + } else { + atts.override_redirect = False; + atts.save_under = False; + } + + /* + * The override-redirect and save-under bits must be set on the + * wrapper window in order to have the desired effect. However, + * also set the override-redirect bit on the window itself, so + * that the "wm overrideredirect" command will see it. + */ + + if ((atts.override_redirect != Tk_Attributes(wrapperPtr)->override_redirect) + || (atts.save_under != Tk_Attributes(wrapperPtr)->save_under)) { + Tk_ChangeWindowAttributes((Tk_Window) wrapperPtr, + CWOverrideRedirect|CWSaveUnder, &atts); + } + if (atts.override_redirect != Tk_Attributes(tkwin)->override_redirect) { + Tk_ChangeWindowAttributes(tkwin, CWOverrideRedirect, &atts); + } +} + +/* + *---------------------------------------------------------------------- + * + * CreateWrapper -- + * + * This procedure is invoked to create the wrapper window for a + * toplevel window. It is called just before a toplevel is mapped + * for the first time. + * + * Results: + * None. + * + * Side effects: + * The wrapper is created and the toplevel is reparented inside it. + * + *---------------------------------------------------------------------- + */ + +static void +CreateWrapper(wmPtr) + WmInfo *wmPtr; /* Window manager information for the + * window. */ +{ + TkWindow *winPtr, *wrapperPtr; + Window parent; + Tcl_HashEntry *hPtr; + int new; + + winPtr = wmPtr->winPtr; + if (winPtr->window == None) { + Tk_MakeWindowExist((Tk_Window) winPtr); + } + + /* + * The code below is copied from CreateTopLevelWindow, + * Tk_MakeWindowExist, and TkpMakeWindow; The idea is to create an + * "official" Tk window (so that we can get events on it), but to + * hide the window outside the official Tk hierarchy so that it + * isn't visible to the application. See the comments for the other + * procedures if you have questions about this code. + */ + + wmPtr->wrapperPtr = wrapperPtr = TkAllocWindow(winPtr->dispPtr, + Tk_ScreenNumber((Tk_Window) winPtr), winPtr); + wrapperPtr->dirtyAtts |= CWBorderPixel; + + /* + * Tk doesn't normally select for StructureNotifyMask events because + * the events are synthesized internally. However, for wrapper + * windows we need to know when the window manager modifies the + * window configuration. We also need to select on focus change + * events; these are the only windows for which we care about focus + * changes. + */ + + wrapperPtr->flags |= TK_WRAPPER; + wrapperPtr->atts.event_mask |= StructureNotifyMask|FocusChangeMask; + wrapperPtr->atts.override_redirect = winPtr->atts.override_redirect; + if (winPtr->flags & TK_EMBEDDED) { + parent = TkUnixContainerId(winPtr); + } else { + parent = XRootWindow(wrapperPtr->display, wrapperPtr->screenNum); + } + wrapperPtr->window = XCreateWindow(wrapperPtr->display, + parent, wrapperPtr->changes.x, wrapperPtr->changes.y, + (unsigned) wrapperPtr->changes.width, + (unsigned) wrapperPtr->changes.height, + (unsigned) wrapperPtr->changes.border_width, wrapperPtr->depth, + InputOutput, wrapperPtr->visual, + wrapperPtr->dirtyAtts|CWOverrideRedirect, &wrapperPtr->atts); + hPtr = Tcl_CreateHashEntry(&wrapperPtr->dispPtr->winTable, + (char *) wrapperPtr->window, &new); + Tcl_SetHashValue(hPtr, wrapperPtr); + wrapperPtr->mainPtr = winPtr->mainPtr; + wrapperPtr->mainPtr->refCount++; + wrapperPtr->dirtyAtts = 0; + wrapperPtr->dirtyChanges = 0; +#ifdef TK_USE_INPUT_METHODS + wrapperPtr->inputContext = NULL; +#endif /* TK_USE_INPUT_METHODS */ + wrapperPtr->wmInfoPtr = wmPtr; + + /* + * Reparent the toplevel window inside the wrapper. + */ + + XReparentWindow(wrapperPtr->display, winPtr->window, wrapperPtr->window, + 0, 0); + + /* + * Tk must monitor structure events for wrapper windows in order + * to detect changes made by window managers such as resizing, + * mapping, unmapping, etc.. + */ + + Tk_CreateEventHandler((Tk_Window) wmPtr->wrapperPtr, StructureNotifyMask, + WrapperEventProc, (ClientData) wmPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TkWmFocusToplevel -- + * + * This is a utility procedure invoked by focus-management code. + * The focus code responds to externally generated focus-related + * events on wrapper windows but ignores those events for any other + * windows. This procedure determines whether a given window is a + * wrapper window and, if so, returns the toplevel window + * corresponding to the wrapper. + * + * Results: + * If winPtr is a wrapper window, returns a pointer to the + * corresponding toplevel window; otherwise returns NULL. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkWmFocusToplevel(winPtr) + TkWindow *winPtr; /* Window that received a focus-related + * event. */ +{ + if (!(winPtr->flags & TK_WRAPPER)) { + return NULL; + } + return winPtr->wmInfoPtr->winPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkUnixSetMenubar -- + * + * This procedure is invoked by menu management code to specify the + * window to use as a menubar for a given toplevel window. + * + * Results: + * None. + * + * Side effects: + * The window given by menubar will be mapped and positioned inside + * the wrapper for tkwin and above tkwin. Menubar will + * automatically be resized to maintain the height specified by + * TkUnixSetMenuHeight the same width as tkwin. Any previous + * menubar specified for tkwin will be unmapped and ignored from + * now on. + * + *---------------------------------------------------------------------- + */ + +void +TkUnixSetMenubar(tkwin, menubar) + Tk_Window tkwin; /* Token for toplevel window. */ + Tk_Window menubar; /* Token for window that is to serve as + * menubar for tkwin. Must not be a + * toplevel window. If NULL, any + * existing menubar is canceled and the + * menu height is reset to 0. */ +{ + WmInfo *wmPtr = ((TkWindow *) tkwin)->wmInfoPtr; + Tk_Window parent; + TkWindow *menubarPtr = (TkWindow *) menubar; + + if (wmPtr->menubar != NULL) { + /* + * There's already a menubar for this toplevel. If it isn't the + * same as the new menubar, unmap it so that it is out of the + * way, and reparent it back to its original parent. + */ + + if (wmPtr->menubar == menubar) { + return; + } + ((TkWindow *) wmPtr->menubar)->wmInfoPtr = NULL; + ((TkWindow *) wmPtr->menubar)->flags &= ~TK_REPARENTED; + Tk_UnmapWindow(wmPtr->menubar); + parent = Tk_Parent(wmPtr->menubar); + if (parent != NULL) { + Tk_MakeWindowExist(parent); + XReparentWindow(Tk_Display(wmPtr->menubar), + Tk_WindowId(wmPtr->menubar), Tk_WindowId(parent), 0, 0); + } + Tk_DeleteEventHandler(wmPtr->menubar, StructureNotifyMask, + MenubarDestroyProc, (ClientData) wmPtr->menubar); + Tk_ManageGeometry(wmPtr->menubar, NULL, (ClientData) NULL); + } + + wmPtr->menubar = menubar; + if (menubar == NULL) { + wmPtr->menuHeight = 0; + } else { + if ((menubarPtr->flags & TK_TOP_LEVEL) + || (Tk_Screen(menubar) != Tk_Screen(tkwin))) { + panic("TkUnixSetMenubar got bad menubar"); + } + wmPtr->menuHeight = Tk_ReqHeight(menubar); + if (wmPtr->menuHeight == 0) { + wmPtr->menuHeight = 1; + } + Tk_MakeWindowExist(tkwin); + Tk_MakeWindowExist(menubar); + if (wmPtr->wrapperPtr == NULL) { + CreateWrapper(wmPtr); + } + XReparentWindow(Tk_Display(menubar), Tk_WindowId(menubar), + wmPtr->wrapperPtr->window, 0, 0); + menubarPtr->wmInfoPtr = wmPtr; + Tk_MoveResizeWindow(menubar, 0, 0, Tk_Width(tkwin), wmPtr->menuHeight); + Tk_MapWindow(menubar); + Tk_CreateEventHandler(menubar, StructureNotifyMask, MenubarDestroyProc, + (ClientData) menubar); + Tk_ManageGeometry(menubar, &menubarMgrType, (ClientData) wmPtr); + menubarPtr->flags |= TK_REPARENTED; + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) tkwin); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * MenubarDestroyProc -- + * + * This procedure is invoked by the event dispatcher whenever a + * menubar window is destroyed (it's also invoked for a few other + * kinds of events, but we ignore those). + * + * Results: + * None. + * + * Side effects: + * The association between the window and its toplevel is broken, + * so that the window is no longer considered to be a menubar. + * + *---------------------------------------------------------------------- + */ + +static void +MenubarDestroyProc(clientData, eventPtr) + ClientData clientData; /* TkWindow pointer for menubar. */ + XEvent *eventPtr; /* Describes what just happened. */ +{ + WmInfo *wmPtr; + + if (eventPtr->type != DestroyNotify) { + return; + } + wmPtr = ((TkWindow *) clientData)->wmInfoPtr; + wmPtr->menubar = NULL; + wmPtr->menuHeight = 0; + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) wmPtr->winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * MenubarReqProc -- + * + * This procedure is invoked by the Tk geometry management code + * whenever a menubar calls Tk_GeometryRequest to request a new + * size. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +MenubarReqProc(clientData, tkwin) + ClientData clientData; /* Pointer to the window manager + * information for tkwin's toplevel. */ + Tk_Window tkwin; /* Handle for menubar window. */ +{ + WmInfo *wmPtr = (WmInfo *) clientData; + + wmPtr->menuHeight = Tk_ReqHeight(tkwin); + if (wmPtr->menuHeight <= 0) { + wmPtr->menuHeight = 1; + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) wmPtr->winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetWrapperWindow -- + * + * Given a toplevel window return the hidden wrapper window for + * the toplevel window if available. + * + * Results: + * The wrapper window. NULL is we were not passed a toplevel + * window or the wrapper has yet to be created. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkpGetWrapperWindow(winPtr) + TkWindow *winPtr; /* A toplevel window pointer. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + + if ((winPtr == NULL) || (wmPtr == NULL)) { + return NULL; + } + + return wmPtr->wrapperPtr; +} diff --git a/unix/tkUnixXId.c b/unix/tkUnixXId.c new file mode 100644 index 0000000..f67c35c --- /dev/null +++ b/unix/tkUnixXId.c @@ -0,0 +1,537 @@ +/* + * tkUnixXId.c -- + * + * This file provides a replacement function for the default X + * resource allocator (_XAllocID). The problem with the default + * allocator is that it never re-uses ids, which causes long-lived + * applications to crash when X resource identifiers wrap around. + * The replacement functions in this file re-use old identifiers + * to prevent this problem. + * + * The code in this file is based on similar implementations by + * George C. Kaplan and Michael Hoegeman. + * + * Copyright (c) 1993 The Regents of the University of California. + * Copyright (c) 1994-1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkUnixXId.c 1.22 97/06/25 13:16:47 + */ + +/* + * The definition below is needed on some systems so that we can access + * the resource_alloc field of Display structures in order to replace + * the resource allocator. + */ + +#define XLIB_ILLEGAL_ACCESS 1 + +#include "tkInt.h" +#include "tkPort.h" +#include "tkUnixInt.h" + +/* + * A structure of the following type is used to hold one or more + * available resource identifiers. There is a list of these structures + * for each display. + */ + +#define IDS_PER_STACK 10 +typedef struct TkIdStack { + XID ids[IDS_PER_STACK]; /* Array of free identifiers. */ + int numUsed; /* Indicates how many of the entries + * in ids are currently in use. */ + TkDisplay *dispPtr; /* Display to which ids belong. */ + struct TkIdStack *nextPtr; /* Next bunch of free identifiers + * for the same display. */ +} TkIdStack; + +/* + * Forward declarations for procedures defined in this file: + */ + +static XID AllocXId _ANSI_ARGS_((Display *display)); +static Tk_RestrictAction CheckRestrictProc _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +static void WindowIdCleanup _ANSI_ARGS_((ClientData clientData)); +static void WindowIdCleanup2 _ANSI_ARGS_((ClientData clientData)); + +/* + *---------------------------------------------------------------------- + * + * TkInitXId -- + * + * This procedure is called to initialize the id allocator for + * a given display. + * + * Results: + * None. + * + * Side effects: + * The official allocator for the display is set up to be Tk_AllocXID. + * + *---------------------------------------------------------------------- + */ + +void +TkInitXId(dispPtr) + TkDisplay *dispPtr; /* Tk's information about the + * display. */ +{ + dispPtr->idStackPtr = NULL; + dispPtr->defaultAllocProc = (XID (*) _ANSI_ARGS_((Display *display))) + dispPtr->display->resource_alloc; + dispPtr->display->resource_alloc = AllocXId; + dispPtr->windowStackPtr = NULL; + dispPtr->idCleanupScheduled = 0; +} + +/* + *---------------------------------------------------------------------- + * + * AllocXId -- + * + * This procedure is invoked by Xlib as the resource allocator + * for a display. + * + * Results: + * The return value is an X resource identifier that isn't currently + * in use. + * + * Side effects: + * The identifier is removed from the stack of free identifiers, + * if it was previously on the stack. + * + *---------------------------------------------------------------------- + */ + +static XID +AllocXId(display) + Display *display; /* Display for which to allocate. */ +{ + TkDisplay *dispPtr; + TkIdStack *stackPtr; + + /* + * Find Tk's information about the display. + */ + + dispPtr = TkGetDisplay(display); + + /* + * If the topmost chunk on the stack is empty then free it. Then + * check for a free id on the stack and return it if it exists. + */ + + stackPtr = dispPtr->idStackPtr; + if (stackPtr != NULL) { + while (stackPtr->numUsed == 0) { + dispPtr->idStackPtr = stackPtr->nextPtr; + ckfree((char *) stackPtr); + stackPtr = dispPtr->idStackPtr; + if (stackPtr == NULL) { + goto defAlloc; + } + } + stackPtr->numUsed--; + return stackPtr->ids[stackPtr->numUsed]; + } + + /* + * No free ids in the stack: just get one from the default + * allocator. + */ + + defAlloc: + return (*dispPtr->defaultAllocProc)(display); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreeXId -- + * + * This procedure is called to indicate that an X resource identifier + * is now free. + * + * Results: + * None. + * + * Side effects: + * The identifier is added to the stack of free identifiers for its + * display, so that it can be re-used. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreeXId(display, xid) + Display *display; /* Display for which xid was + * allocated. */ + XID xid; /* Identifier that is no longer + * in use. */ +{ + TkDisplay *dispPtr; + TkIdStack *stackPtr; + + /* + * Find Tk's information about the display. + */ + + dispPtr = TkGetDisplay(display); + + /* + * Add a new chunk to the stack if the current chunk is full. + */ + + stackPtr = dispPtr->idStackPtr; + if ((stackPtr == NULL) || (stackPtr->numUsed >= IDS_PER_STACK)) { + stackPtr = (TkIdStack *) ckalloc(sizeof(TkIdStack)); + stackPtr->numUsed = 0; + stackPtr->dispPtr = dispPtr; + stackPtr->nextPtr = dispPtr->idStackPtr; + dispPtr->idStackPtr = stackPtr; + } + + /* + * Add the id to the current chunk. + */ + + stackPtr->ids[stackPtr->numUsed] = xid; + stackPtr->numUsed++; +} + +/* + *---------------------------------------------------------------------- + * + * TkFreeWindowId -- + * + * This procedure is invoked instead of TkFreeXId for window ids. + * See below for the reason why. + * + * Results: + * None. + * + * Side effects: + * The id given by w will eventually be freed, so that it can be + * reused for other resources. + * + * Design: + * Freeing window ids is very tricky because there could still be + * events pending for a window in the event queue (or even in the + * server) at the time the window is destroyed. If the window + * id were to get reused immediately for another window, old + * events could "drop in" on the new window, causing unexpected + * behavior. + * + * Thus we have to wait to re-use a window id until we know that + * there are no events left for it. Right now this is done in + * two steps. First, we wait until we know that the server + * has seen the XDestroyWindow request, so we can be sure that + * it won't generate more events for the window and that any + * existing events are in our queue. Second, we make sure that + * there are no events whatsoever in our queue (this is conservative + * but safe). + * + * The first step is done by remembering the request id of the + * XDestroyWindow request and using LastKnownRequestProcessed to + * see what events the server has processed. If multiple windows + * get destroyed at about the same time, we just remember the + * most recent request number for any of them (again, conservative + * but safe). + * + * There are a few other complications as well. When Tk destroys a + * sub-tree of windows, it only issues a single XDestroyWindow call, + * at the very end for the root of the subtree. We can't free any of + * the window ids until the final XDestroyWindow call. To make sure + * that this happens, we have to keep track of deletions in progress, + * hence the need for the "destroyCount" field of the display. + * + * One final problem. Some servers, like Sun X11/News servers still + * seem to have problems with ids getting reused too quickly. I'm + * not completely sure why this is a problem, but delaying the + * recycling of ids appears to eliminate it. Therefore, we wait + * an additional few seconds, even after "the coast is clear" + * before reusing the ids. + * + *---------------------------------------------------------------------- + */ + +void +TkFreeWindowId(dispPtr, w) + TkDisplay *dispPtr; /* Display that w belongs to. */ + Window w; /* X identifier for window on dispPtr. */ +{ + TkIdStack *stackPtr; + + /* + * Put the window id on a separate stack of window ids, rather + * than the main stack, so it won't get reused right away. Add + * a new chunk to the stack if the current chunk is full. + */ + + stackPtr = dispPtr->windowStackPtr; + if ((stackPtr == NULL) || (stackPtr->numUsed >= IDS_PER_STACK)) { + stackPtr = (TkIdStack *) ckalloc(sizeof(TkIdStack)); + stackPtr->numUsed = 0; + stackPtr->dispPtr = dispPtr; + stackPtr->nextPtr = dispPtr->windowStackPtr; + dispPtr->windowStackPtr = stackPtr; + } + + /* + * Add the id to the current chunk. + */ + + stackPtr->ids[stackPtr->numUsed] = w; + stackPtr->numUsed++; + + /* + * Schedule a call to WindowIdCleanup if one isn't already + * scheduled. + */ + + if (!dispPtr->idCleanupScheduled) { + dispPtr->idCleanupScheduled = 1; + Tcl_CreateTimerHandler(100, WindowIdCleanup, (ClientData) dispPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * WindowIdCleanup -- + * + * See if we can now free up all the accumulated ids of + * deleted windows. + * + * Results: + * None. + * + * Side effects: + * If it's safe to move the window ids back to the main free + * list, we schedule this to happen after a few mores seconds + * of delay. If it's not safe to move them yet, a timer handler + * gets invoked to try again later. + * + *---------------------------------------------------------------------- + */ + +static void +WindowIdCleanup(clientData) + ClientData clientData; /* Pointer to TkDisplay for display */ +{ + TkDisplay *dispPtr = (TkDisplay *) clientData; + int anyEvents, delta; + Tk_RestrictProc *oldProc; + ClientData oldData; + static Tcl_Time timeout = {0, 0}; + + dispPtr->idCleanupScheduled = 0; + + /* + * See if it's safe to recycle the window ids. It's safe if: + * (a) no deletions are in progress. + * (b) the server has seen all of the requests up to the last + * XDestroyWindow request. + * (c) there are no events in the event queue; the only way to + * test for this right now is to create a restrict proc that + * will filter the events, then call Tcl_DoOneEvent to see if + * the procedure gets invoked. + */ + + if (dispPtr->destroyCount > 0) { + goto tryAgain; + } + delta = LastKnownRequestProcessed(dispPtr->display) + - dispPtr->lastDestroyRequest; + if (delta < 0) { + XSync(dispPtr->display, False); + } + anyEvents = 0; + oldProc = Tk_RestrictEvents(CheckRestrictProc, (ClientData) &anyEvents, + &oldData); + TkUnixDoOneXEvent(&timeout); + Tk_RestrictEvents(oldProc, oldData, &oldData); + if (anyEvents) { + goto tryAgain; + } + + /* + * These ids look safe to recycle, but we still need to delay a bit + * more (see comments for TkFreeWindowId). Schedule the final freeing. + */ + + if (dispPtr->windowStackPtr != NULL) { + Tcl_CreateTimerHandler(5000, WindowIdCleanup2, + (ClientData) dispPtr->windowStackPtr); + dispPtr->windowStackPtr = NULL; + } + return; + + /* + * It's still not safe to free up the ids. Try again a bit later. + */ + + tryAgain: + dispPtr->idCleanupScheduled = 1; + Tcl_CreateTimerHandler(500, WindowIdCleanup, (ClientData) dispPtr); +} + +/* + *---------------------------------------------------------------------- + * + * WindowIdCleanup2 -- + * + * This procedure is the last one in the chain that recycles + * window ids. It takes all of the ids indicated by its + * argument and adds them back to the main id free list. + * + * Results: + * None. + * + * Side effects: + * Window ids get added to the main free list for their display. + * + *---------------------------------------------------------------------- + */ + +static void +WindowIdCleanup2(clientData) + ClientData clientData; /* Pointer to TkIdStack list. */ +{ + TkIdStack *stackPtr = (TkIdStack *) clientData; + TkIdStack *lastPtr; + + lastPtr = stackPtr; + while (lastPtr->nextPtr != NULL) { + lastPtr = lastPtr->nextPtr; + } + lastPtr->nextPtr = stackPtr->dispPtr->idStackPtr; + stackPtr->dispPtr->idStackPtr = stackPtr; +} + +/* + *---------------------------------------------------------------------- + * + * CheckRestrictProc -- + * + * This procedure is a restrict procedure, called by Tcl_DoOneEvent + * to filter X events. All it does is to set a flag to indicate + * that there are X events present. + * + * Results: + * Sets the integer pointed to by the argument, then returns + * TK_DEFER_EVENT. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static Tk_RestrictAction +CheckRestrictProc(clientData, eventPtr) + ClientData clientData; /* Pointer to flag to set. */ + XEvent *eventPtr; /* Event to filter; not used. */ +{ + int *flag = (int *) clientData; + *flag = 1; + return TK_DEFER_EVENT; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetPixmap -- + * + * Same as the XCreatePixmap procedure except that it manages + * resource identifiers better. + * + * Results: + * Returns a new pixmap. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Pixmap +Tk_GetPixmap(display, d, width, height, depth) + Display *display; /* Display for new pixmap. */ + Drawable d; /* Drawable where pixmap will be used. */ + int width, height; /* Dimensions of pixmap. */ + int depth; /* Bits per pixel for pixmap. */ +{ + return XCreatePixmap(display, d, (unsigned) width, (unsigned) height, + (unsigned) depth); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreePixmap -- + * + * Same as the XFreePixmap procedure except that it also marks + * the resource identifier as free. + * + * Results: + * None. + * + * Side effects: + * The pixmap is freed in the X server and its resource identifier + * is saved for re-use. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreePixmap(display, pixmap) + Display *display; /* Display for which pixmap was allocated. */ + Pixmap pixmap; /* Identifier for pixmap. */ +{ + XFreePixmap(display, pixmap); + Tk_FreeXId(display, (XID) pixmap); +} + +/* + *---------------------------------------------------------------------- + * + * TkpWindowWasRecentlyDeleted -- + * + * Checks whether the window was recently deleted. This is called + * by the generic error handler to detect asynchronous notification + * of errors due to operations by Tk on a window that was already + * deleted by the server. + * + * Results: + * 1 if the window was deleted recently, 0 otherwise. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpWindowWasRecentlyDeleted(win, dispPtr) + Window win; /* The window to check for. */ + TkDisplay *dispPtr; /* The window belongs to this display. */ +{ + TkIdStack *stackPtr; + int i; + + for (stackPtr = dispPtr->windowStackPtr; + stackPtr != NULL; + stackPtr = stackPtr->nextPtr) { + for (i = 0; i < stackPtr->numUsed; i++) { + if ((Window) stackPtr->ids[i] == win) { + return 1; + } + } + } + return 0; +} diff --git a/win/README b/win/README new file mode 100644 index 0000000..17a488c --- /dev/null +++ b/win/README @@ -0,0 +1,124 @@ +Tk 8.0p2 for Windows + +by Scott Stanton +Sun Microsystems Laboratories +scott.stanton@eng.sun.com + +SCCS: @(#) README 1.20 97/11/21 15:17:54 + +1. Introduction +--------------- + +This is the directory where you configure and compile the Windows +version of Tk. This directory also contains source files for Tk +that are specific to Microsoft Windows. The rest of this file +contains information specific to the Windows version of Tk. + +2. Distribution notes +--------------------- + +Tk 8.0 for Windows is distributed in binary form in addition to the +common source release. The binary distribution is a self-extracting +archive with a built-in installation script. + +Look for the binary release in the same location as the source release +(ftp.smli.com:/pub/tcl or any of the mirror sites). For most users, +the binary release will be much easier to install and use. You only +need the source release if you plan to modify the core of Tcl, or if +you need to compile with a different compiler. With the addition of +the dynamic loading interface, it is no longer necessary to have the +source distribution in order to build and use extensions. + +3. Compiling Tk +---------------- + +In order to compile Tk for Windows, you need the following items: + + Tcl 8.0 Source Distribution (plus any patches) + Tk 8.0 Source Distribution (plus any patches) + + The latest Win32 SDK header files + + Borland C++ 4.5 or later (32-bit compiler) + or + Visual C++ 2.x or later + + +In the "win" subdirectory of the source release, you will find two +files called "makefile.bc" and "makefile.vc". These are the makefiles +for the Borland and Visual C++ compilers respectively. You should +copy the appropriate one to "makefile" and update the paths at the top +of the file to reflect your system configuration. Now you can use +"make" (or "nmake" for VC++) to build the tk libraries and the wish +executable. + +In order to use the binaries generated by these makefiles, you will +need to place the Tk script library files someplace where Tk can +find them. Tk looks in one of two places for the library files: + + 1) The environment variable "TK_LIBRARY". + + 2) In the lib\tk8.0 directory under the Tcl installation directory + as specified in the registry: + + For Windows NT & 95: + HKEY_LOCAL_MACHINE\SOFTWARE\Sun\Tcl\8.0 + Value Name is "Root" + + For Win32s: + HKEY_CLASSES_ROOT\SOFTWARE\Sun\Tcl\8.0\ + + 2) Relative to the directory containing the current .exe. + Tk will look for a directory "..\lib\tk8.0" relative to the + directory containing the currently running .exe. + +Note that in order to run wish80.exe, you must ensure that tcl80.dll, +tclpip80.dll (plus tcl1680.dll under Win32s), and tk80.dll are on your +path, in the system directory, or in the directory containing +wish80.exe. + +4. Test suite +------------- + +The Windows version of Tk does not pass many of the tests in the test +suite. This is primarily due to dependencies in the test suite on the +size of particular X fonts, and other X related features as well as +problems with "exec". We will be working to develop a more general +test suite for Tk under Windows, but for now, you will not be able to +pass many of the tests. + +5. Known Bugs +------------- + +Here is the current list of known bugs/missing features for the +Windows beta version of Tk: + +- There is no support for custom cursors/application icons. The core + set of X cursors is supported, although you cannot change their color. +- Stippling of arcs isn't implemented yet. +- Some "wm" functions don't map to Windows and aren't implemented; + others should map, but just aren't implemented. The worst offenders + are the icon manipulation routines. +- Under Win32s, you can only start one instance of Wish at a time. +- Color management on some displays doesn't work properly resulting in + Tk switching to monochrome mode. +- Tk seems to fail to draw anything on some Matrox Millenium cards. +- Send and winfo interps are not currently supported +- Printing does not work for images (e.g. GIF) on a canvas. +- Tk_dialog appears in the upper left corner. This is a symptom of a + larger problem with "wm geometry" when applied to unmapped or + iconified windows. +- Some keys don't work on international keyboards. +- Grabs do not affect native menus or the title bar. +- PPM images are using the wrong translation mode for writing to + files, resulting in CR/LF terminated PPM files. +- Tk crashes if the display depth changes while it is running. Tk + also doesn't consistently track changes in the system colors. + +If you have comments or bug reports for the Windows version of Tk, +please direct them to: + +Scott Stanton +scott.stanton@eng.sun.com + +or post them to the newsgroup comp.lang.tcl. diff --git a/win/makefile.bc b/win/makefile.bc new file mode 100644 index 0000000..a77c0ed --- /dev/null +++ b/win/makefile.bc @@ -0,0 +1,341 @@ +# Borland C++ 4.5 makefile for Tk +# +# Copyright (c) 1995-1996 by Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# SCCS: @(#) makefile.bc 1.73 97/11/05 16:12:27 + + +# +# Project directories +# +# ROOT = top of source tree +# TMPDIR = location where .obj files should be stored during build +# TCLDIR = location of top of Tcl source heirarchy +# + +ROOT = .. +TMPDIR = . +TOOLS = c:\bc45 +TCLDIR = ..\..\tcl8.0 + +# uncomment the following line to compile with symbols +#DEBUG=1 + +# uncomment the following line to compile with TCL_MEM_DEBUG +#DEBUGDEFINES =TCL_MEM_DEBUG + +# +# Borland C++ tools +# + +BORLAND = $(TOOLS) +IMPLIB = $(BORLAND)\bin\Implib +BCC32 = $(BORLAND)\bin\Bcc32 +TLINK32 = $(BORLAND)\bin\tlink32 +RC = $(BORLAND)\bin\brcc32 +CP = copy +RM = del + +INCLUDES = $(BORLAND)\include;$(ROOT)\generic;$(ROOT)\bitmaps;$(ROOT)\xlib;$(ROOT)\win;$(TCLDIR)\generic +LIBDIRS = $(BORLAND)\lib;$(ROOT)\win +TCLLIBDIR = $(TCLDIR)\win + + +!ifndef DEBUG + +# these macros cause maximum optimization and no symbols +DEBUGLDFLAGS = +DEBUGCCFLAGS = -v- -vi- -O2 + +!else + +# these macros enable debugging +DEBUGLDFLAGS = -v +DEBUGCCFLAGS = -k -Od -v + +!endif + +DEFINES = MT;_RTLDLL;STRICT;$(DEBUGDEFINES) +PROJECTCCFLAGS= $(DEBUGCCFLAGS) -w-par -w-stu + +LNFLAGS_exe = -Tpe -aa -c $(DEBUGLDFLAGS) $(BORLAND)\lib\c0w32 +LNFLAGS_dll = -Tpd -aa -c $(DEBUGLDFLAGS) $(BORLAND)\lib\c0d32 + +LNLIBS_exe = $(TKLIB) $(TCLLIBDIR)\$(TCLLIB) import32 cw32mti +LNLIBS_dll = $(TCLLIBDIR)\$(TCLLIB) import32 cw32mti + +# +# Global makefile settings +# + +.AUTODEPEND +.CACHEAUTODEPEND + +.suffixes: .c .dll .lib .obj .exe + +.path.c=$(ROOT)\win;$(ROOT)\generic;$(ROOT)\xlib;$(ROOT)\unix +.path.obj=$(TMPDIR) + +WISHOBJS = \ + $(TMPDIR)\tkConsole.obj \ + $(TMPDIR)\winMain.obj + +TKTESTOBJS = \ + $(TMPDIR)\tkConsole.obj \ + $(TMPDIR)\tkTest.obj \ + $(TMPDIR)\tkSquare.obj \ + $(TMPDIR)\testMain.obj + +XLIBOBJS = \ + $(TMPDIR)\xcolors.obj \ + $(TMPDIR)\xdraw.obj \ + $(TMPDIR)\xgc.obj \ + $(TMPDIR)\ximage.obj \ + $(TMPDIR)\xutil.obj + +TKOBJS = \ + $(TMPDIR)\tkUnixMenubu.obj \ + $(TMPDIR)\tkUnixScale.obj \ + $(XLIBOBJS) \ + $(TMPDIR)\tkWin3d.obj \ + $(TMPDIR)\tkWin32Dll.obj \ + $(TMPDIR)\tkWinButton.obj \ + $(TMPDIR)\tkWinClipboard.obj \ + $(TMPDIR)\tkWinColor.obj \ + $(TMPDIR)\tkWinCursor.obj \ + $(TMPDIR)\tkWinDialog.obj \ + $(TMPDIR)\tkWinDraw.obj \ + $(TMPDIR)\tkWinEmbed.obj \ + $(TMPDIR)\tkWinFont.obj \ + $(TMPDIR)\tkWinImage.obj \ + $(TMPDIR)\tkWinInit.obj \ + $(TMPDIR)\tkWinKey.obj \ + $(TMPDIR)\tkWinMenu.obj \ + $(TMPDIR)\tkWinPixmap.obj \ + $(TMPDIR)\tkWinPointer.obj \ + $(TMPDIR)\tkWinRegion.obj \ + $(TMPDIR)\tkWinScrlbr.obj \ + $(TMPDIR)\tkWinSend.obj \ + $(TMPDIR)\tkWinWindow.obj \ + $(TMPDIR)\tkWinWm.obj \ + $(TMPDIR)\tkWinX.obj \ + $(TMPDIR)\stubs.obj \ + $(TMPDIR)\tk3d.obj \ + $(TMPDIR)\tkArgv.obj \ + $(TMPDIR)\tkAtom.obj \ + $(TMPDIR)\tkBind.obj \ + $(TMPDIR)\tkBitmap.obj \ + $(TMPDIR)\tkButton.obj \ + $(TMPDIR)\tkCanvArc.obj \ + $(TMPDIR)\tkCanvBmap.obj \ + $(TMPDIR)\tkCanvImg.obj \ + $(TMPDIR)\tkCanvLine.obj \ + $(TMPDIR)\tkCanvPoly.obj \ + $(TMPDIR)\tkCanvPs.obj \ + $(TMPDIR)\tkCanvText.obj \ + $(TMPDIR)\tkCanvUtil.obj \ + $(TMPDIR)\tkCanvWind.obj \ + $(TMPDIR)\tkCanvas.obj \ + $(TMPDIR)\tkClipboard.obj \ + $(TMPDIR)\tkCmds.obj \ + $(TMPDIR)\tkColor.obj \ + $(TMPDIR)\tkConfig.obj \ + $(TMPDIR)\tkCursor.obj \ + $(TMPDIR)\tkEntry.obj \ + $(TMPDIR)\tkError.obj \ + $(TMPDIR)\tkEvent.obj \ + $(TMPDIR)\tkFileFilter.obj \ + $(TMPDIR)\tkFocus.obj \ + $(TMPDIR)\tkFont.obj \ + $(TMPDIR)\tkFrame.obj \ + $(TMPDIR)\tkGC.obj \ + $(TMPDIR)\tkGeometry.obj \ + $(TMPDIR)\tkGet.obj \ + $(TMPDIR)\tkGrab.obj \ + $(TMPDIR)\tkGrid.obj \ + $(TMPDIR)\tkImage.obj \ + $(TMPDIR)\tkImgBmap.obj \ + $(TMPDIR)\tkImgGIF.obj \ + $(TMPDIR)\tkImgPPM.obj \ + $(TMPDIR)\tkImgPhoto.obj \ + $(TMPDIR)\tkImgUtil.obj \ + $(TMPDIR)\tkListbox.obj \ + $(TMPDIR)\tkMacWinMenu.obj \ + $(TMPDIR)\tkMain.obj \ + $(TMPDIR)\tkMenu.obj \ + $(TMPDIR)\tkMenubutton.obj \ + $(TMPDIR)\tkMenuDraw.obj \ + $(TMPDIR)\tkMessage.obj \ + $(TMPDIR)\tkOption.obj \ + $(TMPDIR)\tkPack.obj \ + $(TMPDIR)\tkPlace.obj \ + $(TMPDIR)\tkPointer.obj \ + $(TMPDIR)\tkRectOval.obj \ + $(TMPDIR)\tkScale.obj \ + $(TMPDIR)\tkScrollbar.obj \ + $(TMPDIR)\tkSelect.obj \ + $(TMPDIR)\tkText.obj \ + $(TMPDIR)\tkTextBTree.obj \ + $(TMPDIR)\tkTextDisp.obj \ + $(TMPDIR)\tkTextImage.obj \ + $(TMPDIR)\tkTextIndex.obj \ + $(TMPDIR)\tkTextMark.obj \ + $(TMPDIR)\tkTextTag.obj \ + $(TMPDIR)\tkTextWind.obj \ + $(TMPDIR)\tkTrig.obj \ + $(TMPDIR)\tkUtil.obj \ + $(TMPDIR)\tkVisual.obj \ + $(TMPDIR)\tkWindow.obj + +TCLDLL = tcl80.dll +TCLLIB = tcl80.lib +TKDLL = tk80.dll +TKLIB = tk80.lib +WISH = wish80.exe +TKTEST = tktest.exe + +# +# Targets +# + +all: cfgdll $(TKDLL) cfgexe $(WISH) cfgcln +tktest: cfgdll $(TKDLL) cfgtest $(TKTEST) cfgcln + +test: tktest + $(TKTEST) &&| + cd ../tests + console show + update + source all +| + +# Implicit Targets + +.c.obj: + @$(BCC32) {$< } + +.dll.lib: + $(IMPLIB) -c $@ $< + +.rc.res: + $(RC) -i$(INCLUDES) $< + +# +# Special case object file targets +# + +$(TMPDIR)\testMain.obj : $(ROOT)\win\winMain.c + $(BCC32) -c -o$@ $(ROOT)\win\winMain.c + +# +# Configuration file targets - these files are implicitly used by the compiler +# + +cfgdll: + @$(CP) &&| + -n$(TMPDIR) -I$(INCLUDES) -c -WM + -D$(DEFINES) -3 -d $(PROJECTCCFLAGS) +| bcc32.cfg >NUL + +cfgexe: + @$(CP) &&| + -n$(TMPDIR) -I$(INCLUDES) -c -W + -D$(DEFINES) -3 -d $(PROJECTCCFLAGS) +| bcc32.cfg >NUL + +cfgtest: + @$(CP) &&| + -n$(TMPDIR) -I$(INCLUDES) -c -W + -D$(DEFINES);TK_TEST -3 -d $(PROJECTCCFLAGS) +| bcc32.cfg >NUL + +cfgcln: + @$(RM) bcc32.cfg + +# +# Executable targets +# + +$(TKDLL): $(TKOBJS) tk.def rc\tk.res + $(TLINK32) @&&| +$(LNFLAGS_dll) $(TKOBJS) +$@ +-x +$(LNLIBS_dll) +tk.def +rc\tk.res +| + +$(WISH): $(WISHOBJS) $(TKLIB) rc\wish.res + $(TLINK32) @&&| +$(LNFLAGS_exe) $(WISHOBJS) +$@ +-x +$(LNLIBS_exe) +|, &&| +EXETYPE WINDOWS +CODE PRELOAD MOVEABLE DISCARDABLE +DATA PRELOAD MOVEABLE MULTIPLE +|, rc\wish.res + +$(TKTEST): $(TKTESTOBJS) $(TKLIB) + $(TLINK32) $(LNFLAGS_exe) @&&| +$(TKTESTOBJS) +$@ +-x +$(LNLIBS_exe) +|, &&| +EXETYPE WINDOWS +CODE PRELOAD MOVEABLE DISCARDABLE +DATA PRELOAD MOVEABLE MULTIPLE +|, + +# +# Other dependencies +# + +rc\wish.res: rc\wish.ico +rc\tk.res: rc\tk.ico rc\*.cur + +# The following rule automatically generates a tk.def file containing +# an export entry for every public symbol in the $(TKDLL) library. + +tk.def: $(TKOBJS) + $(TCLLIBDIR)\dumpexts.exe -o $@ $(TKDLL) @&&| + $(TKOBJS) +| + +# rule to build library object files + +# debugging rules, the .dll and .exe files must be in the same +# directory as the object files for debugging purposes + +$(TMPDIR)\$(TKDLL): $(TKDLL) + $(CP) $(TKDLL) $(TMPDIR) + +$(TMPDIR)\$(TCLDLL): $(TCLLIBDIR)\$(TCLDLL) + $(CP) $(TCLLIBDIR)\$(TCLDLL) $(TMPDIR) + +$(TMPDIR)\$(WISH): $(WISH) + $(CP) $(WISH) $(TMPDIR) + +$(TMPDIR)\$(TKTEST): $(TKTEST) + $(CP) $(TKTEST) $(TMPDIR) + +debug: $(TMPDIR)\$(TKDLL) $(TMPDIR)\$(TCLDLL) $(TMPDIR)\$(TKTEST) + + +# remove all generated files + +clean: + $(RM) $(WISH) + $(RM) $(TKTEST) + $(RM) $(TKLIB) + $(RM) $(TKDLL) + $(RM) rc\*.res + $(RM) tk.def + $(RM) $(TMPDIR)\*.obj + $(RM) *.cfg diff --git a/win/makefile.vc b/win/makefile.vc new file mode 100644 index 0000000..7312db0 --- /dev/null +++ b/win/makefile.vc @@ -0,0 +1,397 @@ +# Visual C++ 2.x and 4.0 makefile +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# Copyright (c) 1995-1996 Sun Microsystems, Inc. +# SCCS: @(#) makefile.vc 1.64 97/10/27 17:27:20 + +# Does not depend on the presence of any environment variables in +# order to compile tcl; all needed information is derived from +# location of the compiler directories. + +# +# Project directories +# +# ROOT = top of source tree +# +# TMPDIR = location where .obj files should be stored during build +# +# TOOLS32 = location of VC++ 32-bit development tools. Note that the +# VC++ 2.0 header files are broken, so you need to use the +# ones that come with the developer network CD's, or later +# versions of VC++. +# +# TCLDIR = location of top of Tcl source heirarchy +# + +ROOT = .. +TMPDIR = . +TOOLS32 = c:\msdev +TCLDIR = ..\..\tcl8.0 + +# Set this to the appropriate value of /MACHINE: for your platform +MACHINE = IX86 + +# Comment the following line to compile with symbols +NODEBUG=1 + +# uncomment the following two lines to compile with TCL_MEM_DEBUG +#DEBUGDEFINES =-DTCL_MEM_DEBUG + +###################################################################### +# Do not modify below this line +###################################################################### + +VERSION = 80 + +TCLDLL = tcl$(VERSION).dll +TCLLIB = tcl$(VERSION).lib +TCLPLUGINDLL = tcl$(VERSION)p.dll +TCLPLUGINLIB = tcl$(VERSION)p.lib +TKDLL = tk$(VERSION).dll +TKLIB = tk$(VERSION).lib +TKPLUGINDLL = tk$(VERSION)p.dll +TKPLUGINLIB = tk$(VERSION)p.lib + +WISH = wish$(VERSION).exe +WISHP = wishp$(VERSION).exe +TKTEST = tktest.exe +DUMPEXTS = $(TMPDIR)\dumpexts.exe + +WISHOBJS = \ + $(TMPDIR)\tkConsole.obj \ + $(TMPDIR)\winMain.obj + +TKTESTOBJS = \ + $(TMPDIR)\tkConsole.obj \ + $(TMPDIR)\tkTest.obj \ + $(TMPDIR)\tkSquare.obj \ + $(TMPDIR)\testMain.obj + +XLIBOBJS = \ + $(TMPDIR)\xcolors.obj \ + $(TMPDIR)\xdraw.obj \ + $(TMPDIR)\xgc.obj \ + $(TMPDIR)\ximage.obj \ + $(TMPDIR)\xutil.obj + +TKOBJS = \ + $(TMPDIR)\tkUnixMenubu.obj \ + $(TMPDIR)\tkUnixScale.obj \ + $(XLIBOBJS) \ + $(TMPDIR)\tkWin3d.obj \ + $(TMPDIR)\tkWin32Dll.obj \ + $(TMPDIR)\tkWinButton.obj \ + $(TMPDIR)\tkWinClipboard.obj \ + $(TMPDIR)\tkWinColor.obj \ + $(TMPDIR)\tkWinCursor.obj \ + $(TMPDIR)\tkWinDialog.obj \ + $(TMPDIR)\tkWinDraw.obj \ + $(TMPDIR)\tkWinEmbed.obj \ + $(TMPDIR)\tkWinFont.obj \ + $(TMPDIR)\tkWinImage.obj \ + $(TMPDIR)\tkWinInit.obj \ + $(TMPDIR)\tkWinKey.obj \ + $(TMPDIR)\tkWinMenu.obj \ + $(TMPDIR)\tkWinPixmap.obj \ + $(TMPDIR)\tkWinPointer.obj \ + $(TMPDIR)\tkWinRegion.obj \ + $(TMPDIR)\tkWinScrlbr.obj \ + $(TMPDIR)\tkWinSend.obj \ + $(TMPDIR)\tkWinWindow.obj \ + $(TMPDIR)\tkWinWm.obj \ + $(TMPDIR)\tkWinX.obj \ + $(TMPDIR)\stubs.obj \ + $(TMPDIR)\tk3d.obj \ + $(TMPDIR)\tkArgv.obj \ + $(TMPDIR)\tkAtom.obj \ + $(TMPDIR)\tkBind.obj \ + $(TMPDIR)\tkBitmap.obj \ + $(TMPDIR)\tkButton.obj \ + $(TMPDIR)\tkCanvArc.obj \ + $(TMPDIR)\tkCanvBmap.obj \ + $(TMPDIR)\tkCanvImg.obj \ + $(TMPDIR)\tkCanvLine.obj \ + $(TMPDIR)\tkCanvPoly.obj \ + $(TMPDIR)\tkCanvPs.obj \ + $(TMPDIR)\tkCanvText.obj \ + $(TMPDIR)\tkCanvUtil.obj \ + $(TMPDIR)\tkCanvWind.obj \ + $(TMPDIR)\tkCanvas.obj \ + $(TMPDIR)\tkClipboard.obj \ + $(TMPDIR)\tkCmds.obj \ + $(TMPDIR)\tkColor.obj \ + $(TMPDIR)\tkConfig.obj \ + $(TMPDIR)\tkCursor.obj \ + $(TMPDIR)\tkEntry.obj \ + $(TMPDIR)\tkError.obj \ + $(TMPDIR)\tkEvent.obj \ + $(TMPDIR)\tkFileFilter.obj \ + $(TMPDIR)\tkFocus.obj \ + $(TMPDIR)\tkFont.obj \ + $(TMPDIR)\tkFrame.obj \ + $(TMPDIR)\tkGC.obj \ + $(TMPDIR)\tkGeometry.obj \ + $(TMPDIR)\tkGet.obj \ + $(TMPDIR)\tkGrab.obj \ + $(TMPDIR)\tkGrid.obj \ + $(TMPDIR)\tkImage.obj \ + $(TMPDIR)\tkImgBmap.obj \ + $(TMPDIR)\tkImgGIF.obj \ + $(TMPDIR)\tkImgPPM.obj \ + $(TMPDIR)\tkImgPhoto.obj \ + $(TMPDIR)\tkImgUtil.obj \ + $(TMPDIR)\tkListbox.obj \ + $(TMPDIR)\tkMacWinMenu.obj \ + $(TMPDIR)\tkMain.obj \ + $(TMPDIR)\tkMenu.obj \ + $(TMPDIR)\tkMenubutton.obj \ + $(TMPDIR)\tkMenuDraw.obj \ + $(TMPDIR)\tkMessage.obj \ + $(TMPDIR)\tkOption.obj \ + $(TMPDIR)\tkPack.obj \ + $(TMPDIR)\tkPlace.obj \ + $(TMPDIR)\tkPointer.obj \ + $(TMPDIR)\tkRectOval.obj \ + $(TMPDIR)\tkScale.obj \ + $(TMPDIR)\tkScrollbar.obj \ + $(TMPDIR)\tkSelect.obj \ + $(TMPDIR)\tkText.obj \ + $(TMPDIR)\tkTextBTree.obj \ + $(TMPDIR)\tkTextDisp.obj \ + $(TMPDIR)\tkTextImage.obj \ + $(TMPDIR)\tkTextIndex.obj \ + $(TMPDIR)\tkTextMark.obj \ + $(TMPDIR)\tkTextTag.obj \ + $(TMPDIR)\tkTextWind.obj \ + $(TMPDIR)\tkTrig.obj \ + $(TMPDIR)\tkUtil.obj \ + $(TMPDIR)\tkVisual.obj \ + $(TMPDIR)\tkWindow.obj + +cc32 = $(TOOLS32)\bin\cl.exe +link32 = $(TOOLS32)\bin\link.exe +rc32 = $(TOOLS32)\bin\rc.exe +include32 = -I$(TOOLS32)\include + +WINDIR = $(ROOT)\win +GENERICDIR = $(ROOT)\generic +XLIBDIR = $(ROOT)\xlib +BITMAPDIR = $(ROOT)\bitmaps +TCLLIBDIR = $(TCLDIR)\win +RCDIR = $(WINDIR)\rc + +TK_INCLUDES = -I$(WINDIR) -I$(GENERICDIR) -I$(BITMAPDIR) -I$(XLIBDIR) \ + -I$(TCLDIR)\generic +TK_DEFINES = $(DEBUGDEFINES) + +TK_CFLAGS = $(cdebug) $(cflags) $(cvarsdll) $(include32) \ + $(TK_INCLUDES) $(TK_DEFINES) + +###################################################################### +# Link flags +###################################################################### + +!IFDEF NODEBUG +ldebug = /RELEASE +!ELSE +ldebug = -debug:full -debugtype:cv +!ENDIF + +# declarations common to all linker options +lcommon = /NODEFAULTLIB /RELEASE /NOLOGO + +# declarations for use on Intel i386, i486, and Pentium systems +!IF "$(MACHINE)" == "IX86" +DLLENTRY = @12 +lflags = $(lcommon) -align:0x1000 /MACHINE:$(MACHINE) +!ELSE +lflags = $(lcommon) /MACHINE:$(MACHINE) +!ENDIF + +conlflags = $(lflags) -subsystem:console -entry:mainCRTStartup +guilflags = $(lflags) -subsystem:windows -entry:WinMainCRTStartup +dlllflags = $(lflags) -entry:_DllMainCRTStartup$(DLLENTRY) -dll + +!IF "$(MACHINE)" == "PPC" +libc = libc.lib +libcdll = crtdll.lib +!ELSE +libc = libc.lib oldnames.lib +libcdll = msvcrt.lib oldnames.lib +!ENDIF + +baselibs = kernel32.lib $(optlibs) advapi32.lib +winlibs = $(baselibs) user32.lib gdi32.lib comdlg32.lib winspool.lib +guilibs = $(libc) $(winlibs) + +guilibsdll = $(libcdll) $(winlibs) + +###################################################################### +# Compile flags +###################################################################### + +!IFDEF NODEBUG +cdebug = -Oti -Gs -GD +!ELSE +cdebug = -Z7 -Od -WX +!ENDIF + +# declarations common to all compiler options +ccommon = -c -W3 -nologo -YX + +!IF "$(MACHINE)" == "IX86" +cflags = $(ccommon) -D_X86_=1 +!ELSE +!IF "$(MACHINE)" == "MIPS" +cflags = $(ccommon) -D_MIPS_=1 +!ELSE +!IF "$(MACHINE)" == "PPC" +cflags = $(ccommon) -D_PPC_=1 +!ELSE +!IF "$(MACHINE)" == "ALPHA" +cflags = $(ccommon) -D_ALPHA_=1 +!ENDIF +!ENDIF +!ENDIF +!ENDIF + +cvars = -DWIN32 -D_WIN32 +cvarsmt = $(cvars) -D_MT +cvarsdll = $(cvarsmt) -D_DLL + +CON_CFLAGS = $(cdebug) $(cflags) $(cvars) $(include32) -DCONSOLE + +###################################################################### +# Project specific targets +###################################################################### + +all: $(WISH) +test: $(TKTEST) +plugin: $(TKPLUGINDLL) $(WISHP) + +$(TKLIB): $(TKDLL) + +$(TKDLL): $(TKOBJS) $(TMPDIR)\tk.res $(TMPDIR)\tk.def + set LIB=$(TOOLS32)\lib + $(link32) $(ldebug) $(dlllflags) -def:$(TMPDIR)\tk.def \ + -out:$@ $(TMPDIR)\tk.res $(TCLLIBDIR)\$(TCLLIB) \ + $(guilibsdll) @<< + $(TKOBJS) +<< + +$(TKPLUGINLIB): $(TKPLUGINDLL) + +$(TKPLUGINDLL): $(TKOBJS) $(TMPDIR)\tk.res $(TMPDIR)\plugin.def + set LIB=$(TOOLS32)\lib + $(link32) $(ldebug) $(dlllflags) -def:$(TMPDIR)\plugin.def \ + -out:$@ $(TMPDIR)\tk.res $(TCLLIBDIR)\$(TCLPLUGINLIB) \ + $(guilibsdll) @<< + $(TKOBJS) +<< + +$(WISH): $(WISHOBJS) $(TKLIB) $(TMPDIR)\wish.res + set LIB=$(TOOLS32)\lib + $(link32) $(ldebug) $(guilflags) $(TMPDIR)\wish.res -out:$@ \ + $(guilibsdll) $(TCLLIBDIR)\$(TCLLIB) $(TKLIB) $(WISHOBJS) + +$(WISHP): $(WISHOBJS) $(TKPLUGINLIB) $(TMPDIR)\wish.res + set LIB=$(TOOLS32)\lib + $(link32) $(ldebug) $(guilflags) $(TMPDIR)\wish.res -out:$@ \ + $(guilibsdll) $(TCLLIBDIR)\$(TCLPLUGINLIB) \ + $(TKPLUGINLIB) $(WISHOBJS) + +$(TKTEST): $(TKTESTOBJS) $(TKLIB) $(TMPDIR)\wish.res + set LIB=$(TOOLS32)\lib + $(link32) $(ldebug) $(guilflags) $(TMPDIR)\wish.res -out:$@ \ + $(guilibsdll) $(TCLLIBDIR)\$(TCLLIB) $(TKLIB) $(TKTESTOBJS) + +$(TMPDIR)\tk.def: $(DUMPEXTS) $(TKOBJS) + $(DUMPEXTS) -o $@ $(TKDLL) @<< + $(TKOBJS) +<< + +$(TMPDIR)\plugin.def: $(DUMPEXTS) $(TKOBJS) + $(DUMPEXTS) -o $@ $(TKPLUGINDLL) @<< + $(TKOBJS) +<< + +$(DUMPEXTS): $(TCLDIR)\win\winDumpExts.c + $(cc32) $(CON_CFLAGS) -Fo$(TMPDIR)\ $? + set LIB=$(TOOLS32)\lib + $(link32) $(ldebug) $(conlflags) $(guilibs) -out:$@ \ + $(TMPDIR)\winDumpExts.obj + +# +# Special case object file targets +# + +$(TMPDIR)\testMain.obj: $(ROOT)\win\winMain.c + $(cc32) $(TK_CFLAGS) -DTK_TEST -Fo$@ $? + +# +# Implicit rules +# + +{$(XLIBDIR)}.c{$(TMPDIR)}.obj: + $(cc32) $(TK_CFLAGS) -Fo$(TMPDIR)\ $< + +{$(GENERICDIR)}.c{$(TMPDIR)}.obj: + $(cc32) $(TK_CFLAGS) -Fo$(TMPDIR)\ $< + +{$(WINDIR)}.c{$(TMPDIR)}.obj: + $(cc32) $(TK_CFLAGS) -Fo$(TMPDIR)\ $< + +{$(ROOT)\unix}.c{$(TMPDIR)}.obj: + $(cc32) $(TK_CFLAGS) -Fo$(TMPDIR)\ $< + +{$(RCDIR)}.rc{$(TMPDIR)}.res: + $(rc32) -fo $@ -r -i $(GENERICDIR) $< + +clean: + -@del *.exp + -@del *.lib + -@del *.dll + -@del *.exe + -@del $(TMPDIR)\*.obj + -@del $(TMPDIR)\*.res + -@del $(TMPDIR)\*.def + +# dependencies + +$(TMPDIR)\tk.res: \ + $(RCDIR)\buttons.bmp \ + $(RCDIR)\cursor*.cur \ + $(RCDIR)\tk.ico + +$(GENERICDIR)/default.h: $(WINDIR)/tkWinDefault.h +$(GENERICDIR)/tkButton.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkCanvas.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkEntry.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkFrame.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkListbox.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkMenu.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkMenubutton.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkMessage.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkScale.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkScrollbar.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkText.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkTextIndex.c: $(GENERICDIR)/default.h +$(GENERICDIR)/tkTextTag.c: $(GENERICDIR)/default.h + +$(GENERICDIR)/tkText.c: $(GENERICDIR)/tkText.h +$(GENERICDIR)/tkTextBTree.c: $(GENERICDIR)/tkText.h +$(GENERICDIR)/tkTextDisp.c: $(GENERICDIR)/tkText.h +$(GENERICDIR)/tkTextDisp.c: $(GENERICDIR)/tkText.h +$(GENERICDIR)/tkTextImage.c: $(GENERICDIR)/tkText.h +$(GENERICDIR)/tkTextIndex.c: $(GENERICDIR)/tkText.h +$(GENERICDIR)/tkTextMark.c: $(GENERICDIR)/tkText.h +$(GENERICDIR)/tkTextTag.c: $(GENERICDIR)/tkText.h +$(GENERICDIR)/tkTextWind.c: $(GENERICDIR)/tkText.h + +$(GENERICDIR)/tkMacWinMenu.c: $(GENERICDIR)/tkMenu.h +$(GENERICDIR)/tkMenu.c: $(GENERICDIR)/tkMenu.h +$(GENERICDIR)/tkMenuDraw.c: $(GENERICDIR)/tkMenu.h +$(WINDIR)/tkWinMenu.c: $(GENERICDIR)/tkMenu.h + diff --git a/win/rc/buttons.bmp b/win/rc/buttons.bmp new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/buttons.bmp diff --git a/win/rc/cursor00.cur b/win/rc/cursor00.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor00.cur diff --git a/win/rc/cursor02.cur b/win/rc/cursor02.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor02.cur diff --git a/win/rc/cursor04.cur b/win/rc/cursor04.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor04.cur diff --git a/win/rc/cursor06.cur b/win/rc/cursor06.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor06.cur diff --git a/win/rc/cursor08.cur b/win/rc/cursor08.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor08.cur diff --git a/win/rc/cursor0a.cur b/win/rc/cursor0a.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor0a.cur diff --git a/win/rc/cursor0c.cur b/win/rc/cursor0c.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor0c.cur diff --git a/win/rc/cursor0e.cur b/win/rc/cursor0e.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor0e.cur diff --git a/win/rc/cursor10.cur b/win/rc/cursor10.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor10.cur diff --git a/win/rc/cursor12.cur b/win/rc/cursor12.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor12.cur diff --git a/win/rc/cursor14.cur b/win/rc/cursor14.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor14.cur diff --git a/win/rc/cursor16.cur b/win/rc/cursor16.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor16.cur diff --git a/win/rc/cursor18.cur b/win/rc/cursor18.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor18.cur diff --git a/win/rc/cursor1a.cur b/win/rc/cursor1a.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor1a.cur diff --git a/win/rc/cursor1c.cur b/win/rc/cursor1c.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor1c.cur diff --git a/win/rc/cursor1e.cur b/win/rc/cursor1e.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor1e.cur diff --git a/win/rc/cursor20.cur b/win/rc/cursor20.cur new file mode 100644 index 0000000..95c4dc1 --- /dev/null +++ b/win/rc/cursor20.cur @@ -0,0 +1,2 @@ + 0( @ÿÿÿB„¢ŠR”*¨Ð + ü~ü~ diff --git a/win/rc/cursor22.cur b/win/rc/cursor22.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor22.cur diff --git a/win/rc/cursor24.cur b/win/rc/cursor24.cur new file mode 100644 index 0000000..c971b66 --- /dev/null +++ b/win/rc/cursor24.cur @@ -0,0 +1,2 @@ + 0( @ÿÿÿ€À + "ˆB„þþþþB„"ˆ diff --git a/win/rc/cursor26.cur b/win/rc/cursor26.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor26.cur diff --git a/win/rc/cursor28.cur b/win/rc/cursor28.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor28.cur diff --git a/win/rc/cursor2a.cur b/win/rc/cursor2a.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor2a.cur diff --git a/win/rc/cursor2c.cur b/win/rc/cursor2c.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor2c.cur diff --git a/win/rc/cursor2e.cur b/win/rc/cursor2e.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor2e.cur diff --git a/win/rc/cursor30.cur b/win/rc/cursor30.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor30.cur diff --git a/win/rc/cursor32.cur b/win/rc/cursor32.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor32.cur diff --git a/win/rc/cursor34.cur b/win/rc/cursor34.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor34.cur diff --git a/win/rc/cursor36.cur b/win/rc/cursor36.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor36.cur diff --git a/win/rc/cursor38.cur b/win/rc/cursor38.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor38.cur diff --git a/win/rc/cursor3a.cur b/win/rc/cursor3a.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor3a.cur diff --git a/win/rc/cursor3c.cur b/win/rc/cursor3c.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor3c.cur diff --git a/win/rc/cursor3e.cur b/win/rc/cursor3e.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor3e.cur diff --git a/win/rc/cursor40.cur b/win/rc/cursor40.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor40.cur diff --git a/win/rc/cursor42.cur b/win/rc/cursor42.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor42.cur diff --git a/win/rc/cursor44.cur b/win/rc/cursor44.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor44.cur diff --git a/win/rc/cursor46.cur b/win/rc/cursor46.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor46.cur diff --git a/win/rc/cursor48.cur b/win/rc/cursor48.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor48.cur diff --git a/win/rc/cursor4a.cur b/win/rc/cursor4a.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor4a.cur diff --git a/win/rc/cursor4c.cur b/win/rc/cursor4c.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor4c.cur diff --git a/win/rc/cursor4e.cur b/win/rc/cursor4e.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor4e.cur diff --git a/win/rc/cursor50.cur b/win/rc/cursor50.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor50.cur diff --git a/win/rc/cursor52.cur b/win/rc/cursor52.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor52.cur diff --git a/win/rc/cursor54.cur b/win/rc/cursor54.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor54.cur diff --git a/win/rc/cursor56.cur b/win/rc/cursor56.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor56.cur diff --git a/win/rc/cursor58.cur b/win/rc/cursor58.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor58.cur diff --git a/win/rc/cursor5a.cur b/win/rc/cursor5a.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor5a.cur diff --git a/win/rc/cursor5c.cur b/win/rc/cursor5c.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor5c.cur diff --git a/win/rc/cursor5e.cur b/win/rc/cursor5e.cur new file mode 100644 index 0000000..9141887 --- /dev/null +++ b/win/rc/cursor5e.cur @@ -0,0 +1 @@ + diff --git a/win/rc/cursor60.cur b/win/rc/cursor60.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor60.cur diff --git a/win/rc/cursor62.cur b/win/rc/cursor62.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor62.cur diff --git a/win/rc/cursor64.cur b/win/rc/cursor64.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor64.cur diff --git a/win/rc/cursor66.cur b/win/rc/cursor66.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor66.cur diff --git a/win/rc/cursor68.cur b/win/rc/cursor68.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor68.cur diff --git a/win/rc/cursor6a.cur b/win/rc/cursor6a.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor6a.cur diff --git a/win/rc/cursor6c.cur b/win/rc/cursor6c.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor6c.cur diff --git a/win/rc/cursor6e.cur b/win/rc/cursor6e.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor6e.cur diff --git a/win/rc/cursor70.cur b/win/rc/cursor70.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor70.cur diff --git a/win/rc/cursor72.cur b/win/rc/cursor72.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor72.cur diff --git a/win/rc/cursor74.cur b/win/rc/cursor74.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor74.cur diff --git a/win/rc/cursor76.cur b/win/rc/cursor76.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor76.cur diff --git a/win/rc/cursor78.cur b/win/rc/cursor78.cur new file mode 100644 index 0000000..53ab3d0 --- /dev/null +++ b/win/rc/cursor78.cur @@ -0,0 +1 @@ + 0( @ÿÿÿþ diff --git a/win/rc/cursor7a.cur b/win/rc/cursor7a.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor7a.cur diff --git a/win/rc/cursor7c.cur b/win/rc/cursor7c.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor7c.cur diff --git a/win/rc/cursor7e.cur b/win/rc/cursor7e.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor7e.cur diff --git a/win/rc/cursor80.cur b/win/rc/cursor80.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor80.cur diff --git a/win/rc/cursor82.cur b/win/rc/cursor82.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor82.cur diff --git a/win/rc/cursor84.cur b/win/rc/cursor84.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor84.cur diff --git a/win/rc/cursor86.cur b/win/rc/cursor86.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor86.cur diff --git a/win/rc/cursor88.cur b/win/rc/cursor88.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor88.cur diff --git a/win/rc/cursor8a.cur b/win/rc/cursor8a.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor8a.cur diff --git a/win/rc/cursor8c.cur b/win/rc/cursor8c.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor8c.cur diff --git a/win/rc/cursor8e.cur b/win/rc/cursor8e.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor8e.cur diff --git a/win/rc/cursor90.cur b/win/rc/cursor90.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor90.cur diff --git a/win/rc/cursor92.cur b/win/rc/cursor92.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor92.cur diff --git a/win/rc/cursor94.cur b/win/rc/cursor94.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor94.cur diff --git a/win/rc/cursor96.cur b/win/rc/cursor96.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor96.cur diff --git a/win/rc/cursor98.cur b/win/rc/cursor98.cur new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/cursor98.cur diff --git a/win/rc/tk.ico b/win/rc/tk.ico new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/tk.ico diff --git a/win/rc/tk.rc b/win/rc/tk.rc new file mode 100644 index 0000000..0d74ec3 --- /dev/null +++ b/win/rc/tk.rc @@ -0,0 +1,132 @@ +// SCCS: @(#) tk.rc 1.22 97/03/21 18:35:14 +// +// Version +// + +#define RESOURCE_INCLUDED +#include <tk.h> + +#define STRINGIFY1(x) #x +#define STRINGIFY(x) STRINGIFY1(x) + +VS_VERSION_INFO VERSIONINFO + FILEVERSION TK_MAJOR_VERSION,TK_MINOR_VERSION,TK_RELEASE_LEVEL,TK_RELEASE_SERIAL + PRODUCTVERSION TK_MAJOR_VERSION,TK_MINOR_VERSION,TK_RELEASE_LEVEL,TK_RELEASE_SERIAL + FILEFLAGSMASK 0x3fL + FILEFLAGS 0x0L + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "Tk DLL\0" + VALUE "OriginalFilename", "tk" STRINGIFY(TK_MAJOR_VERSION) STRINGIFY(TK_MINOR_VERSION) ".dll\0" + VALUE "CompanyName", "Sun Microsystems, Inc.\0" + VALUE "FileVersion", TK_PATCH_LEVEL + VALUE "LegalCopyright", "Copyright \251 1995-1996\0" + VALUE "ProductName", "Tk " TK_VERSION " for Windows\0" + VALUE "ProductVersion", TK_PATCH_LEVEL + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +// +// Icons +// + +tk ICON DISCARDABLE "tk.ico" + +// +// Bitmaps +// + +buttons BITMAP DISCARDABLE "buttons.bmp" + +// +// Cursors +// + +X_cursor CURSOR DISCARDABLE "cursor00.cur" +arrow CURSOR DISCARDABLE "cursor02.cur" +based_arrow_down CURSOR DISCARDABLE "cursor04.cur" +based_arrow_up CURSOR DISCARDABLE "cursor06.cur" +boat CURSOR DISCARDABLE "cursor08.cur" +bogosity CURSOR DISCARDABLE "cursor0a.cur" +bottom_left_corner CURSOR DISCARDABLE "cursor0c.cur" +bottom_right_corner CURSOR DISCARDABLE "cursor0e.cur" +bottom_side CURSOR DISCARDABLE "cursor10.cur" +bottom_tee CURSOR DISCARDABLE "cursor12.cur" +box_spiral CURSOR DISCARDABLE "cursor14.cur" +center_ptr CURSOR DISCARDABLE "cursor16.cur" +circle CURSOR DISCARDABLE "cursor18.cur" +clock CURSOR DISCARDABLE "cursor1a.cur" +coffee_mug CURSOR DISCARDABLE "cursor1c.cur" +cross CURSOR DISCARDABLE "cursor1e.cur" +cross_reverse CURSOR DISCARDABLE "cursor20.cur" +crosshair CURSOR DISCARDABLE "cursor22.cur" +diamond_cross CURSOR DISCARDABLE "cursor24.cur" +dot CURSOR DISCARDABLE "cursor26.cur" +dotbox CURSOR DISCARDABLE "cursor28.cur" +double_arrow CURSOR DISCARDABLE "cursor2a.cur" +draft_large CURSOR DISCARDABLE "cursor2c.cur" +draft_small CURSOR DISCARDABLE "cursor2e.cur" +draped_box CURSOR DISCARDABLE "cursor30.cur" +exchange CURSOR DISCARDABLE "cursor32.cur" +fleur CURSOR DISCARDABLE "cursor34.cur" +gobbler CURSOR DISCARDABLE "cursor36.cur" +gumby CURSOR DISCARDABLE "cursor38.cur" +hand1 CURSOR DISCARDABLE "cursor3a.cur" +hand2 CURSOR DISCARDABLE "cursor3c.cur" +heart CURSOR DISCARDABLE "cursor3e.cur" +icon CURSOR DISCARDABLE "cursor40.cur" +iron_cross CURSOR DISCARDABLE "cursor42.cur" +left_ptr CURSOR DISCARDABLE "cursor44.cur" +left_side CURSOR DISCARDABLE "cursor46.cur" +left_tee CURSOR DISCARDABLE "cursor48.cur" +leftbutton CURSOR DISCARDABLE "cursor4a.cur" +ll_angle CURSOR DISCARDABLE "cursor4c.cur" +lr_angle CURSOR DISCARDABLE "cursor4e.cur" +man CURSOR DISCARDABLE "cursor50.cur" +middlebutton CURSOR DISCARDABLE "cursor52.cur" +mouse CURSOR DISCARDABLE "cursor54.cur" +pencil CURSOR DISCARDABLE "cursor56.cur" +pirate CURSOR DISCARDABLE "cursor58.cur" +plus CURSOR DISCARDABLE "cursor5a.cur" +question_arrow CURSOR DISCARDABLE "cursor5c.cur" +right_ptr CURSOR DISCARDABLE "cursor5e.cur" +right_side CURSOR DISCARDABLE "cursor60.cur" +right_tee CURSOR DISCARDABLE "cursor62.cur" +rightbutton CURSOR DISCARDABLE "cursor64.cur" +rtl_logo CURSOR DISCARDABLE "cursor66.cur" +sailboat CURSOR DISCARDABLE "cursor68.cur" +sb_down_arrow CURSOR DISCARDABLE "cursor6a.cur" +sb_h_double_arrow CURSOR DISCARDABLE "cursor6c.cur" +sb_left_arrow CURSOR DISCARDABLE "cursor6e.cur" +sb_right_arrow CURSOR DISCARDABLE "cursor70.cur" +sb_up_arrow CURSOR DISCARDABLE "cursor72.cur" +sb_v_double_arrow CURSOR DISCARDABLE "cursor74.cur" +shuttle CURSOR DISCARDABLE "cursor76.cur" +sizing CURSOR DISCARDABLE "cursor78.cur" +spider CURSOR DISCARDABLE "cursor7a.cur" +spraycan CURSOR DISCARDABLE "cursor7c.cur" +star CURSOR DISCARDABLE "cursor7e.cur" +target CURSOR DISCARDABLE "cursor80.cur" +tcross CURSOR DISCARDABLE "cursor82.cur" +top_left_arrow CURSOR DISCARDABLE "cursor84.cur" +top_left_corner CURSOR DISCARDABLE "cursor86.cur" +top_right_corner CURSOR DISCARDABLE "cursor88.cur" +top_side CURSOR DISCARDABLE "cursor8a.cur" +top_tee CURSOR DISCARDABLE "cursor8c.cur" +trek CURSOR DISCARDABLE "cursor8e.cur" +ul_angle CURSOR DISCARDABLE "cursor90.cur" +umbrella CURSOR DISCARDABLE "cursor92.cur" +ur_angle CURSOR DISCARDABLE "cursor94.cur" +watch CURSOR DISCARDABLE "cursor96.cur" +xterm CURSOR DISCARDABLE "cursor98.cur" diff --git a/win/rc/wish.ico b/win/rc/wish.ico new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/win/rc/wish.ico diff --git a/win/rc/wish.rc b/win/rc/wish.rc new file mode 100644 index 0000000..76cf124 --- /dev/null +++ b/win/rc/wish.rc @@ -0,0 +1,44 @@ +// SCCS: @(#) wish.rc 1.15 96/09/17 13:24:11 +// +// Version +// + +#define RESOURCE_INCLUDED +#include <tk.h> + +#define STRINGIFY1(x) #x +#define STRINGIFY(x) STRINGIFY1(x) + +VS_VERSION_INFO VERSIONINFO + FILEVERSION TK_MAJOR_VERSION,TK_MINOR_VERSION,TK_RELEASE_LEVEL,TK_RELEASE_SERIAL + PRODUCTVERSION TK_MAJOR_VERSION,TK_MINOR_VERSION,TK_RELEASE_LEVEL,TK_RELEASE_SERIAL + FILEFLAGSMASK 0x3fL + FILEFLAGS 0x0L + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "Wish Application\0" + VALUE "OriginalFilename", "wish" STRINGIFY(TK_MAJOR_VERSION) STRINGIFY(TK_MINOR_VERSION) ".exe\0" + VALUE "CompanyName", "Sun Microsystems, Inc.\0" + VALUE "FileVersion", TK_PATCH_LEVEL + VALUE "LegalCopyright", "Copyright \251 1995-1996\0" + VALUE "ProductName", "Tk " TK_VERSION " for Windows\0" + VALUE "ProductVersion", TK_PATCH_LEVEL + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +// +// Icon +// + +wish ICON DISCARDABLE "wish.ico" diff --git a/win/stubs.c b/win/stubs.c new file mode 100644 index 0000000..c9b97f5 --- /dev/null +++ b/win/stubs.c @@ -0,0 +1,397 @@ +#include <X11/X.h> +#include <X11/Xlib.h> +#include <stdio.h> +#include <tkInt.h> +#include <tkPort.h> + +/* + * Undocumented Xlib internal function + */ + +_XInitImageFuncPtrs(XImage *image) +{ + return 0; +} + +/* + * From Xutil.h + */ + +void +XSetWMClientMachine(display, w, text_prop) + Display* display; + Window w; + XTextProperty* text_prop; +{ +} + +Status +XStringListToTextProperty(list, count, text_prop_return) + char** list; + int count; + XTextProperty* text_prop_return; +{ + return (Status) NULL; +} + +/* + * From Xlib.h + */ + +void +XChangeProperty(display, w, property, type, format, mode, data, nelements) + Display* display; + Window w; + Atom property; + Atom type; + int format; + int mode; + _Xconst unsigned char* data; + int nelements; +{ +} + +Cursor +XCreateGlyphCursor(display, source_font, mask_font, source_char, mask_char, + foreground_color, background_color) + Display* display; + Font source_font; + Font mask_font; + unsigned int source_char; + unsigned int mask_char; + XColor* foreground_color; + XColor* background_color; +{ + return 1; +} + +XIC +XCreateIC() +{ + return NULL; +} + +Cursor +XCreatePixmapCursor(display, source, mask, foreground_color, + background_color, x, y) + Display* display; + Pixmap source; + Pixmap mask; + XColor* foreground_color; + XColor* background_color; + unsigned int x; + unsigned int y; +{ + return (Cursor) NULL; +} + +void +XDeleteProperty(display, w, property) + Display* display; + Window w; + Atom property; +{ +} + +void +XDestroyIC(ic) + XIC ic; +{ +} + +Bool +XFilterEvent(event, window) + XEvent* event; + Window window; +{ + return 0; +} + +extern void XForceScreenSaver(display, mode) + Display* display; + int mode; +{ +} + +void +XFreeCursor(display, cursor) + Display* display; + Cursor cursor; +{ +} + +GContext +XGContextFromGC(gc) + GC gc; +{ + return (GContext) NULL; +} + +char * +XGetAtomName(display, atom) + Display* display; + Atom atom; +{ + return NULL; +} + +int +XGetWindowAttributes(display, w, window_attributes_return) + Display* display; + Window w; + XWindowAttributes* window_attributes_return; +{ + return 0; +} + +Status +XGetWMColormapWindows(display, w, windows_return, count_return) + Display* display; + Window w; + Window** windows_return; + int* count_return; +{ + return (Status) NULL; +} + +int +XIconifyWindow(display, w, screen_number) + Display* display; + Window w; + int screen_number; +{ + return 0; +} + +XHostAddress * +XListHosts(display, nhosts_return, state_return) + Display* display; + int* nhosts_return; + Bool* state_return; +{ + return NULL; +} + +int +XLookupColor(display, colormap, color_name, exact_def_return, + screen_def_return) + Display* display; + Colormap colormap; + _Xconst char* color_name; + XColor* exact_def_return; + XColor* screen_def_return; +{ + return 0; +} + +void +XNextEvent(display, event_return) + Display* display; + XEvent* event_return; +{ +} + +void +XPutBackEvent(display, event) + Display* display; + XEvent* event; +{ +} + +void +XQueryColors(display, colormap, defs_in_out, ncolors) + Display* display; + Colormap colormap; + XColor* defs_in_out; + int ncolors; +{ +} + +int +XQueryTree(display, w, root_return, parent_return, children_return, + nchildren_return) + Display* display; + Window w; + Window* root_return; + Window* parent_return; + Window** children_return; + unsigned int* nchildren_return; +{ + return 0; +} + +void +XRefreshKeyboardMapping(event_map) + XMappingEvent* event_map; +{ +} + +Window +XRootWindow(display, screen_number) + Display* display; + int screen_number; +{ + return (Window) NULL; +} + +void +XSelectInput(display, w, event_mask) + Display* display; + Window w; + long event_mask; +{ +} + +int +XSendEvent(display, w, propagate, event_mask, event_send) + Display* display; + Window w; + Bool propagate; + long event_mask; + XEvent* event_send; +{ + return 0; +} + +void +XSetCommand(display, w, argv, argc) + Display* display; + Window w; + char** argv; + int argc; +{ +} + +XErrorHandler +XSetErrorHandler (handler) + XErrorHandler handler; +{ + return NULL; +} + +void +XSetIconName(display, w, icon_name) + Display* display; + Window w; + _Xconst char* icon_name; +{ +} + +void +XSetWindowBackground(display, w, background_pixel) + Display* display; + Window w; + unsigned long background_pixel; +{ +} + +void +XSetWindowBackgroundPixmap(display, w, background_pixmap) + Display* display; + Window w; + Pixmap background_pixmap; +{ +} + +void +XSetWindowBorder(display, w, border_pixel) + Display* display; + Window w; + unsigned long border_pixel; +{ +} + +void +XSetWindowBorderPixmap(display, w, border_pixmap) + Display* display; + Window w; + Pixmap border_pixmap; +{ +} + +void +XSetWindowBorderWidth(display, w, width) + Display* display; + Window w; + unsigned int width; +{ +} + +void +XSetWindowColormap(display, w, colormap) + Display* display; + Window w; + Colormap colormap; +{ +} + +Bool +XTranslateCoordinates(display, src_w, dest_w, src_x, src_y, dest_x_return, + dest_y_return, child_return) + Display* display; + Window src_w; + Window dest_w; + int src_x; + int src_y; + int* dest_x_return; + int* dest_y_return; + Window* child_return; +{ + return 0; +} + +void +XWindowEvent(display, w, event_mask, event_return) + Display* display; + Window w; + long event_mask; + XEvent* event_return; +{ +} + +int +XWithdrawWindow(display, w, screen_number) + Display* display; + Window w; + int screen_number; +{ + return 0; +} + +int +XmbLookupString(ic, event, buffer_return, bytes_buffer, keysym_return, + status_return) + XIC ic; + XKeyPressedEvent* event; + char* buffer_return; + int bytes_buffer; + KeySym* keysym_return; + Status* status_return; +{ + return 0; +} + +int +XGetWindowProperty(display, w, property, long_offset, long_length, delete, + req_type, actual_type_return, actual_format_return, nitems_return, + bytes_after_return, prop_return) + Display* display; + Window w; + Atom property; + long long_offset; + long long_length; + Bool delete; + Atom req_type; + Atom* actual_type_return; + int* actual_format_return; + unsigned long* nitems_return; + unsigned long* bytes_after_return; + unsigned char** prop_return; +{ + *actual_type_return = None; + *actual_format_return = 0; + *nitems_return = 0; + *bytes_after_return = 0; + *prop_return = NULL; + return BadValue; +} diff --git a/win/tkWin.h b/win/tkWin.h new file mode 100644 index 0000000..c9d9360 --- /dev/null +++ b/win/tkWin.h @@ -0,0 +1,56 @@ +/* + * tkWin.h -- + * + * Declarations of public types and interfaces that are only + * available under Windows. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWin.h 1.6 96/08/15 13:19:41 + */ + +#ifndef _TKWIN +#define _TKWIN + +#ifndef _TK +#include <tk.h> +#endif + +#define WIN32_LEAN_AND_MEAN +#include <windows.h> +#undef WIN32_LEAN_AND_MEAN + +/* + * The following messages are use to communicate between a Tk toplevel + * and its container window. + */ + +#define TK_CLAIMFOCUS (WM_USER) +#define TK_GEOMETRYREQ (WM_USER+1) +#define TK_ATTACHWINDOW (WM_USER+2) +#define TK_DETACHWINDOW (WM_USER+3) + + +/* + *-------------------------------------------------------------- + * + * Exported procedures defined for the Windows platform only. + * + *-------------------------------------------------------------- + */ + +EXTERN Window Tk_AttachHWND _ANSI_ARGS_((Tk_Window tkwin, + HWND hwnd)); +EXTERN HINSTANCE Tk_GetHINSTANCE _ANSI_ARGS_((void)); +EXTERN HWND Tk_GetHWND _ANSI_ARGS_((Window window)); +EXTERN Tk_Window Tk_HWNDToWindow _ANSI_ARGS_((HWND hwnd)); +EXTERN void Tk_PointerEvent _ANSI_ARGS_((HWND hwnd, + int x, int y)); +EXTERN int Tk_TranslateWinEvent _ANSI_ARGS_((HWND hwnd, + UINT message, WPARAM wParam, LPARAM lParam, + LRESULT *result)); + +#endif /* _TKWIN */ diff --git a/win/tkWin32Dll.c b/win/tkWin32Dll.c new file mode 100644 index 0000000..969e687 --- /dev/null +++ b/win/tkWin32Dll.c @@ -0,0 +1,85 @@ +/* + * tkWin32Dll.c -- + * + * This file contains a stub dll entry point. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWin32Dll.c 1.9 96/08/06 15:59:08 + */ + +#include "tkPort.h" +#include "tkWinInt.h" + +/* + * The following declaration is for the VC++ DLL entry point. + */ + +BOOL APIENTRY DllMain _ANSI_ARGS_((HINSTANCE hInst, + DWORD reason, LPVOID reserved)); + +/* + *---------------------------------------------------------------------- + * + * DllEntryPoint -- + * + * This wrapper function is used by Borland to invoke the + * initialization code for Tk. It simply calls the DllMain + * routine. + * + * Results: + * See DllMain. + * + * Side effects: + * See DllMain. + * + *---------------------------------------------------------------------- + */ + +BOOL APIENTRY +DllEntryPoint(hInst, reason, reserved) + HINSTANCE hInst; /* Library instance handle. */ + DWORD reason; /* Reason this function is being called. */ + LPVOID reserved; /* Not used. */ +{ + return DllMain(hInst, reason, reserved); +} + +/* + *---------------------------------------------------------------------- + * + * DllMain -- + * + * DLL entry point. + * + * Results: + * TRUE on sucess, FALSE on failure. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +BOOL APIENTRY +DllMain(hInstance, reason, reserved) + HINSTANCE hInstance; + DWORD reason; + LPVOID reserved; +{ + /* + * If we are attaching to the DLL from a new process, tell Tk about + * the hInstance to use. If we are detaching then clean up any + * data structures related to this DLL. + */ + + if (reason == DLL_PROCESS_ATTACH) { + TkWinXInit(hInstance); + } else if (reason == DLL_PROCESS_DETACH) { + TkWinXCleanup(hInstance); + } + return(TRUE); +} diff --git a/win/tkWin3d.c b/win/tkWin3d.c new file mode 100644 index 0000000..3ee9907 --- /dev/null +++ b/win/tkWin3d.c @@ -0,0 +1,535 @@ +/* + * tkWin3d.c -- + * + * This file contains the platform specific routines for + * drawing 3d borders in the Windows 95 style. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWin3d.c 1.6 97/08/12 14:28:54 + */ + +#include <tk3d.h> +#include <tkWinInt.h> + +/* + * This structure is used to keep track of the extra colors used by + * Windows 3d borders. + */ + +typedef struct { + TkBorder info; + XColor *light2ColorPtr; /* System3dLight */ + XColor *dark2ColorPtr; /* System3dDarkShadow */ +} WinBorder; + + +/* + *---------------------------------------------------------------------- + * + * TkpGetBorder -- + * + * This function allocates a new TkBorder structure. + * + * Results: + * Returns a newly allocated TkBorder. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkBorder * +TkpGetBorder() +{ + WinBorder *borderPtr = (WinBorder *) ckalloc(sizeof(WinBorder)); + borderPtr->light2ColorPtr = NULL; + borderPtr->dark2ColorPtr = NULL; + return (TkBorder *) borderPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpFreeBorder -- + * + * This function frees any colors allocated by the platform + * specific part of this module. + * + * Results: + * None. + * + * Side effects: + * May deallocate some colors. + * + *---------------------------------------------------------------------- + */ + +void +TkpFreeBorder(borderPtr) + TkBorder *borderPtr; +{ + WinBorder *winBorderPtr = (WinBorder *) borderPtr; + if (winBorderPtr->light2ColorPtr) { + Tk_FreeColor(winBorderPtr->light2ColorPtr); + } + if (winBorderPtr->dark2ColorPtr) { + Tk_FreeColor(winBorderPtr->dark2ColorPtr); + } +} + +/* + *-------------------------------------------------------------- + * + * Tk_3DVerticalBevel -- + * + * This procedure draws a vertical bevel along one side of + * an object. The bevel is always rectangular in shape: + * ||| + * ||| + * ||| + * ||| + * ||| + * ||| + * An appropriate shadow color is chosen for the bevel based + * on the leftBevel and relief arguments. Normally this + * procedure is called first, then Tk_3DHorizontalBevel is + * called next to draw neat corners. + * + * Results: + * None. + * + * Side effects: + * Graphics are drawn in drawable. + * + *-------------------------------------------------------------- + */ + +void +Tk_3DVerticalBevel(tkwin, drawable, border, x, y, width, height, + leftBevel, relief) + Tk_Window tkwin; /* Window for which border was allocated. */ + Drawable drawable; /* X window or pixmap in which to draw. */ + Tk_3DBorder border; /* Token for border to draw. */ + int x, y, width, height; /* Area of vertical bevel. */ + int leftBevel; /* Non-zero means this bevel forms the + * left side of the object; 0 means it + * forms the right side. */ + int relief; /* Kind of bevel to draw. For example, + * TK_RELIEF_RAISED means interior of + * object should appear higher than + * exterior. */ +{ + TkBorder *borderPtr = (TkBorder *) border; + int left, right; + Display *display = Tk_Display(tkwin); + TkWinDCState state; + HDC dc = TkWinGetDrawableDC(display, drawable, &state); + int half; + + if ((borderPtr->lightGC == None) && (relief != TK_RELIEF_FLAT)) { + TkpGetShadows(borderPtr, tkwin); + } + + switch (relief) { + case TK_RELIEF_RAISED: + left = (leftBevel) + ? borderPtr->lightGC->foreground + : borderPtr->darkGC->foreground; + right = (leftBevel) + ? ((WinBorder *)borderPtr)->light2ColorPtr->pixel + : ((WinBorder *)borderPtr)->dark2ColorPtr->pixel; + break; + case TK_RELIEF_SUNKEN: + left = (leftBevel) + ? ((WinBorder *)borderPtr)->dark2ColorPtr->pixel + : ((WinBorder *)borderPtr)->light2ColorPtr->pixel; + right = (leftBevel) + ? borderPtr->darkGC->foreground + : borderPtr->lightGC->foreground; + break; + case TK_RELIEF_RIDGE: + left = borderPtr->lightGC->foreground; + right = borderPtr->darkGC->foreground; + break; + case TK_RELIEF_GROOVE: + left = borderPtr->darkGC->foreground; + right = borderPtr->lightGC->foreground; + break; + case TK_RELIEF_FLAT: + left = right = borderPtr->bgGC->foreground; + break; + case TK_RELIEF_SOLID: + left = right = RGB(0,0,0); + break; + } + half = width/2; + if (leftBevel && (width & 1)) { + half++; + } + TkWinFillRect(dc, x, y, half, height, left); + TkWinFillRect(dc, x+half, y, width-half, height, right); + TkWinReleaseDrawableDC(drawable, dc, &state); +} + +/* + *-------------------------------------------------------------- + * + * Tk_3DHorizontalBevel -- + * + * This procedure draws a horizontal bevel along one side of + * an object. The bevel has mitered corners (depending on + * leftIn and rightIn arguments). + * + * Results: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +void +Tk_3DHorizontalBevel(tkwin, drawable, border, x, y, width, height, + leftIn, rightIn, topBevel, relief) + Tk_Window tkwin; /* Window for which border was allocated. */ + Drawable drawable; /* X window or pixmap in which to draw. */ + Tk_3DBorder border; /* Token for border to draw. */ + int x, y, width, height; /* Bounding box of area of bevel. Height + * gives width of border. */ + int leftIn, rightIn; /* Describes whether the left and right + * edges of the bevel angle in or out as + * they go down. For example, if "leftIn" + * is true, the left side of the bevel + * looks like this: + * ___________ + * __________ + * _________ + * ________ + */ + int topBevel; /* Non-zero means this bevel forms the + * top side of the object; 0 means it + * forms the bottom side. */ + int relief; /* Kind of bevel to draw. For example, + * TK_RELIEF_RAISED means interior of + * object should appear higher than + * exterior. */ +{ + TkBorder *borderPtr = (TkBorder *) border; + Display *display = Tk_Display(tkwin); + int bottom, halfway, x1, x2, x1Delta, x2Delta; + TkWinDCState state; + HDC dc = TkWinGetDrawableDC(display, drawable, &state); + int topColor, bottomColor; + + if ((borderPtr->lightGC == None) && (relief != TK_RELIEF_FLAT)) { + TkpGetShadows(borderPtr, tkwin); + } + + /* + * Compute a GC for the top half of the bevel and a GC for the + * bottom half (they're the same in many cases). + */ + + switch (relief) { + case TK_RELIEF_RAISED: + topColor = (topBevel) + ? borderPtr->lightGC->foreground + : borderPtr->darkGC->foreground; + bottomColor = (topBevel) + ? ((WinBorder *)borderPtr)->light2ColorPtr->pixel + : ((WinBorder *)borderPtr)->dark2ColorPtr->pixel; + break; + case TK_RELIEF_SUNKEN: + topColor = (topBevel) + ? ((WinBorder *)borderPtr)->dark2ColorPtr->pixel + : ((WinBorder *)borderPtr)->light2ColorPtr->pixel; + bottomColor = (topBevel) + ? borderPtr->darkGC->foreground + : borderPtr->lightGC->foreground; + break; + case TK_RELIEF_RIDGE: + topColor = borderPtr->lightGC->foreground; + bottomColor = borderPtr->darkGC->foreground; + break; + case TK_RELIEF_GROOVE: + topColor = borderPtr->darkGC->foreground; + bottomColor = borderPtr->lightGC->foreground; + break; + case TK_RELIEF_FLAT: + topColor = bottomColor = borderPtr->bgGC->foreground; + break; + case TK_RELIEF_SOLID: + topColor = bottomColor = RGB(0,0,0); + } + + /* + * Compute various other geometry-related stuff. + */ + + if (leftIn) { + x1 = x+1; + } else { + x1 = x+height-1; + } + x2 = x+width; + if (rightIn) { + x2--; + } else { + x2 -= height; + } + x1Delta = (leftIn) ? 1 : -1; + x2Delta = (rightIn) ? -1 : 1; + halfway = y + height/2; + if (topBevel && (height & 1)) { + halfway++; + } + bottom = y + height; + + /* + * Draw one line for each y-coordinate covered by the bevel. + */ + + for ( ; y < bottom; y++) { + /* + * In some weird cases (such as large border widths for skinny + * rectangles) x1 can be >= x2. Don't draw the lines + * in these cases. + */ + + if (x1 < x2) { + TkWinFillRect(dc, x1, y, x2-x1, 1, + (y < halfway) ? topColor : bottomColor); + } + x1 += x1Delta; + x2 += x2Delta; + } + TkWinReleaseDrawableDC(drawable, dc, &state); +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetShadows -- + * + * This procedure computes the shadow colors for a 3-D border + * and fills in the corresponding fields of the Border structure. + * It's called lazily, so that the colors aren't allocated until + * something is actually drawn with them. That way, if a border + * is only used for flat backgrounds the shadow colors will + * never be allocated. + * + * Results: + * None. + * + * Side effects: + * The lightGC and darkGC fields in borderPtr get filled in, + * if they weren't already. + * + *---------------------------------------------------------------------- + */ + +void +TkpGetShadows(borderPtr, tkwin) + TkBorder *borderPtr; /* Information about border. */ + Tk_Window tkwin; /* Window where border will be used for + * drawing. */ +{ + XColor lightColor, darkColor; + int tmp1, tmp2; + XGCValues gcValues; + + if (borderPtr->lightGC != None) { + return; + } + + /* + * Handle the special case of the default system colors. + */ + + if ((TkWinIndexOfColor(borderPtr->bgColorPtr) == COLOR_3DFACE) + || (TkWinIndexOfColor(borderPtr->bgColorPtr) == COLOR_WINDOW)) { + borderPtr->darkColorPtr = Tk_GetColor(NULL, tkwin, + Tk_GetUid("SystemButtonShadow")); + gcValues.foreground = borderPtr->darkColorPtr->pixel; + borderPtr->darkGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + borderPtr->lightColorPtr = Tk_GetColor(NULL, tkwin, + Tk_GetUid("SystemButtonHighlight")); + gcValues.foreground = borderPtr->lightColorPtr->pixel; + borderPtr->lightGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + ((WinBorder*)borderPtr)->dark2ColorPtr = Tk_GetColor(NULL, tkwin, + Tk_GetUid("System3dDarkShadow")); + ((WinBorder*)borderPtr)->light2ColorPtr = Tk_GetColor(NULL, tkwin, + Tk_GetUid("System3dLight")); + return; + } else { + darkColor.red = 0; + darkColor.green = 0; + darkColor.blue = 0; + ((WinBorder*)borderPtr)->dark2ColorPtr = Tk_GetColorByValue(tkwin, + &darkColor); + lightColor = *(borderPtr->bgColorPtr); + ((WinBorder*)borderPtr)->light2ColorPtr = Tk_GetColorByValue(tkwin, + &lightColor); + } + + /* + * First, handle the case of a color display with lots of colors. + * The shadow colors get computed using whichever formula results + * in the greatest change in color: + * 1. Lighter shadow is half-way to white, darker shadow is half + * way to dark. + * 2. Lighter shadow is 40% brighter than background, darker shadow + * is 40% darker than background. + */ + + if (Tk_Depth(tkwin) >= 6) { + /* + * This is a color display with lots of colors. For the dark + * shadow, cut 40% from each of the background color components. + * For the light shadow, boost each component by 40% or half-way + * to white, whichever is greater (the first approach works + * better for unsaturated colors, the second for saturated ones). + */ + + darkColor.red = (60 * (int) borderPtr->bgColorPtr->red)/100; + darkColor.green = (60 * (int) borderPtr->bgColorPtr->green)/100; + darkColor.blue = (60 * (int) borderPtr->bgColorPtr->blue)/100; + borderPtr->darkColorPtr = Tk_GetColorByValue(tkwin, &darkColor); + gcValues.foreground = borderPtr->darkColorPtr->pixel; + borderPtr->darkGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + + /* + * Compute the colors using integers, not using lightColor.red + * etc.: these are shorts and may have problems with integer + * overflow. + */ + + tmp1 = (14 * (int) borderPtr->bgColorPtr->red)/10; + if (tmp1 > MAX_INTENSITY) { + tmp1 = MAX_INTENSITY; + } + tmp2 = (MAX_INTENSITY + (int) borderPtr->bgColorPtr->red)/2; + lightColor.red = (tmp1 > tmp2) ? tmp1 : tmp2; + tmp1 = (14 * (int) borderPtr->bgColorPtr->green)/10; + if (tmp1 > MAX_INTENSITY) { + tmp1 = MAX_INTENSITY; + } + tmp2 = (MAX_INTENSITY + (int) borderPtr->bgColorPtr->green)/2; + lightColor.green = (tmp1 > tmp2) ? tmp1 : tmp2; + tmp1 = (14 * (int) borderPtr->bgColorPtr->blue)/10; + if (tmp1 > MAX_INTENSITY) { + tmp1 = MAX_INTENSITY; + } + tmp2 = (MAX_INTENSITY + (int) borderPtr->bgColorPtr->blue)/2; + lightColor.blue = (tmp1 > tmp2) ? tmp1 : tmp2; + borderPtr->lightColorPtr = Tk_GetColorByValue(tkwin, &lightColor); + gcValues.foreground = borderPtr->lightColorPtr->pixel; + borderPtr->lightGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + return; + } + + if (borderPtr->shadow == None) { + borderPtr->shadow = Tk_GetBitmap((Tcl_Interp *) NULL, tkwin, + Tk_GetUid("gray50")); + if (borderPtr->shadow == None) { + panic("TkpGetShadows couldn't allocate bitmap for border"); + } + } + if (borderPtr->visual->map_entries > 2) { + /* + * This isn't a monochrome display, but the colormap either + * ran out of entries or didn't have very many to begin with. + * Generate the light shadows with a white stipple and the + * dark shadows with a black stipple. + */ + + gcValues.foreground = borderPtr->bgColorPtr->pixel; + gcValues.background = BlackPixelOfScreen(borderPtr->screen); + gcValues.stipple = borderPtr->shadow; + gcValues.fill_style = FillOpaqueStippled; + borderPtr->darkGC = Tk_GetGC(tkwin, + GCForeground|GCBackground|GCStipple|GCFillStyle, &gcValues); + gcValues.foreground = WhitePixelOfScreen(borderPtr->screen); + gcValues.background = borderPtr->bgColorPtr->pixel; + borderPtr->lightGC = Tk_GetGC(tkwin, + GCForeground|GCBackground|GCStipple|GCFillStyle, &gcValues); + return; + } + + /* + * This is just a measly monochrome display, hardly even worth its + * existence on this earth. Make one shadow a 50% stipple and the + * other the opposite of the background. + */ + + gcValues.foreground = WhitePixelOfScreen(borderPtr->screen); + gcValues.background = BlackPixelOfScreen(borderPtr->screen); + gcValues.stipple = borderPtr->shadow; + gcValues.fill_style = FillOpaqueStippled; + borderPtr->lightGC = Tk_GetGC(tkwin, + GCForeground|GCBackground|GCStipple|GCFillStyle, &gcValues); + if (borderPtr->bgColorPtr->pixel + == WhitePixelOfScreen(borderPtr->screen)) { + gcValues.foreground = BlackPixelOfScreen(borderPtr->screen); + borderPtr->darkGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + } else { + borderPtr->darkGC = borderPtr->lightGC; + borderPtr->lightGC = Tk_GetGC(tkwin, GCForeground, &gcValues); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWinGetBorderPixels -- + * + * This routine returns the 5 COLORREFs used to draw a given + * 3d border. + * + * Results: + * Returns the colors in the specified array. + * + * Side effects: + * May cause the remaining colors to be allocated. + * + *---------------------------------------------------------------------- + */ + +COLORREF +TkWinGetBorderPixels(tkwin, border, which) + Tk_Window tkwin; + Tk_3DBorder border; + int which; /* One of TK_3D_FLAT_GC, TK_3D_LIGHT_GC, + * TK_3D_DARK_GC, TK_3D_LIGHT2, TK_3D_DARK2 */ +{ + WinBorder *borderPtr = (WinBorder *) border; + + if (borderPtr->info.lightGC == None) { + TkpGetShadows(&borderPtr->info, tkwin); + } + switch (which) { + case TK_3D_FLAT_GC: + return borderPtr->info.bgColorPtr->pixel; + case TK_3D_LIGHT_GC: + if (borderPtr->info.lightColorPtr == NULL) { + return WhitePixelOfScreen(borderPtr->info.screen); + } + return borderPtr->info.lightColorPtr->pixel; + case TK_3D_DARK_GC: + if (borderPtr->info.darkColorPtr == NULL) { + return BlackPixelOfScreen(borderPtr->info.screen); + } + return borderPtr->info.darkColorPtr->pixel; + case TK_3D_LIGHT2: + return borderPtr->light2ColorPtr->pixel; + case TK_3D_DARK2: + return borderPtr->dark2ColorPtr->pixel; + } + return 0; +} diff --git a/win/tkWinButton.c b/win/tkWinButton.c new file mode 100644 index 0000000..47a74e6 --- /dev/null +++ b/win/tkWinButton.c @@ -0,0 +1,811 @@ +/* + * tkWinButton.c -- + * + * This file implements the Windows specific portion of the button + * widgets. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinButton.c 1.12 97/09/02 13:18:27 + */ + +#define OEMRESOURCE +#include "tkWinInt.h" +#include "tkButton.h" + +/* + * These macros define the base style flags for the different button types. + */ + +#define LABEL_STYLE (BS_OWNERDRAW | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS) +#define PUSH_STYLE (BS_OWNERDRAW | BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS) +#define CHECK_STYLE (BS_OWNERDRAW | BS_CHECKBOX | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS) +#define RADIO_STYLE (BS_OWNERDRAW | BS_RADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS) + +static DWORD buttonStyles[] = { + LABEL_STYLE, PUSH_STYLE, CHECK_STYLE, RADIO_STYLE +}; + +/* + * Declaration of Windows specific button structure. + */ + +typedef struct WinButton { + TkButton info; /* Generic button info. */ + WNDPROC oldProc; /* Old window procedure. */ + HWND hwnd; /* Current window handle. */ + Pixmap pixmap; /* Bitmap for rendering the button. */ + DWORD style; /* Window style flags. */ +} WinButton; + + +/* + * The following macro reverses the order of RGB bytes to convert + * between RGBQUAD and COLORREF values. + */ + +#define FlipColor(rgb) (RGB(GetBValue(rgb),GetGValue(rgb),GetRValue(rgb))) + +/* + * The following enumeration defines the meaning of the palette entries + * in the "buttons" image used to draw checkbox and radiobutton indicators. + */ + +enum { + PAL_CHECK = 0, + PAL_TOP_OUTER = 1, + PAL_BOTTOM_OUTER = 2, + PAL_BOTTOM_INNER = 3, + PAL_INTERIOR = 4, + PAL_TOP_INNER = 5, + PAL_BACKGROUND = 6 +}; + +/* + * Set to non-zero if this module is initialized. + */ + +static int initialized = 0; + +/* + * Variables for the cached information about the boxes bitmap. + */ + +static BITMAPINFOHEADER *boxesPtr = NULL; /* Information about the bitmap. */ +static DWORD *boxesPalette = NULL; /* Pointer to color palette. */ +static LPSTR boxesBits = NULL; /* Pointer to bitmap data. */ +static DWORD boxHeight = 0, boxWidth = 0; /* Size of each sub-image. */ + +/* + * This variable holds the default border width for a button in string + * form for use in a Tk_ConfigSpec. + */ + +static char defWidth[8]; + +/* + * Declarations for functions defined in this file. + */ + +static int ButtonBindProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, XEvent *eventPtr, + Tk_Window tkwin, KeySym keySym)); +static LRESULT CALLBACK ButtonProc _ANSI_ARGS_((HWND hwnd, UINT message, + WPARAM wParam, LPARAM lParam)); +static DWORD ComputeStyle _ANSI_ARGS_((WinButton* butPtr)); +static Window CreateProc _ANSI_ARGS_((Tk_Window tkwin, + Window parent, ClientData instanceData)); +static void InitBoxes _ANSI_ARGS_((void)); +static void UpdateButtonDefaults _ANSI_ARGS_((void)); + +/* + * The class procedure table for the button widgets. + */ + +TkClassProcs tkpButtonProcs = { + CreateProc, /* createProc. */ + TkButtonWorldChanged, /* geometryProc. */ + NULL /* modalProc. */ +}; + + +/* + *---------------------------------------------------------------------- + * + * InitBoxes -- + * + * This function load the Tk 3d button bitmap. "buttons" is a 16 + * color bitmap that is laid out such that the top row contains + * the 4 checkbox images, and the bottom row contains the radio + * button images. Note that the bitmap is stored in bottom-up + * format. Also, the first seven palette entries are used to + * identify the different parts of the bitmaps so we can do the + * appropriate color mappings based on the current button colors. + * + * Results: + * None. + * + * Side effects: + * Loads the "buttons" resource. + * + *---------------------------------------------------------------------- + */ + +static void +InitBoxes() +{ + /* + * For DLLs like Tk, the HINSTANCE is the same as the HMODULE. + */ + + HMODULE module = (HINSTANCE) Tk_GetHINSTANCE(); + HRSRC hrsrc; + HGLOBAL hblk; + LPBITMAPINFOHEADER newBitmap; + DWORD size; + + hrsrc = FindResource(module, "buttons", RT_BITMAP); + if (hrsrc) { + hblk = LoadResource(module, hrsrc); + boxesPtr = (LPBITMAPINFOHEADER)LockResource(hblk); + } + + /* + * Copy the DIBitmap into writable memory. + */ + + if (boxesPtr != NULL && !(boxesPtr->biWidth % 4) + && !(boxesPtr->biHeight % 2)) { + size = boxesPtr->biSize + (1 << boxesPtr->biBitCount) * sizeof(RGBQUAD) + + boxesPtr->biSizeImage; + newBitmap = (LPBITMAPINFOHEADER) ckalloc(size); + memcpy(newBitmap, boxesPtr, size); + boxesPtr = newBitmap; + boxWidth = boxesPtr->biWidth / 4; + boxHeight = boxesPtr->biHeight / 2; + boxesPalette = (DWORD*) (((LPSTR)boxesPtr) + boxesPtr->biSize); + boxesBits = ((LPSTR)boxesPalette) + + ((1 << boxesPtr->biBitCount) * sizeof(RGBQUAD)); + } else { + boxesPtr = NULL; + } +} + +/* + *---------------------------------------------------------------------- + * + * UpdateButtonDefaults -- + * + * This function retrieves the current system defaults for + * the button widgets. + * + * Results: + * None. + * + * Side effects: + * Updates the configuration defaults for buttons. + * + *---------------------------------------------------------------------- + */ + +void +UpdateButtonDefaults() +{ + Tk_ConfigSpec *specPtr; + int width = GetSystemMetrics(SM_CXEDGE); + + if (width == 0) { + width = 1; + } + sprintf(defWidth, "%d", width); + for (specPtr = tkpButtonConfigSpecs; specPtr->type != TK_CONFIG_END; + specPtr++) { + if (specPtr->offset == Tk_Offset(TkButton, borderWidth)) { + specPtr->defValue = defWidth; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpCreateButton -- + * + * Allocate a new TkButton structure. + * + * Results: + * Returns a newly allocated TkButton structure. + * + * Side effects: + * Registers an event handler for the widget. + * + *---------------------------------------------------------------------- + */ + +TkButton * +TkpCreateButton(tkwin) + Tk_Window tkwin; +{ + WinButton *butPtr; + + if (!initialized) { + UpdateButtonDefaults(); + initialized = 1; + } + + butPtr = (WinButton *)ckalloc(sizeof(WinButton)); + butPtr->hwnd = NULL; + return (TkButton *) butPtr; +} + +/* + *---------------------------------------------------------------------- + * + * CreateProc -- + * + * This function creates a new Button control, subclasses + * the instance, and generates a new Window object. + * + * Results: + * Returns the newly allocated Window object, or None on failure. + * + * Side effects: + * Causes a new Button control to come into existence. + * + *---------------------------------------------------------------------- + */ + +static Window +CreateProc(tkwin, parentWin, instanceData) + Tk_Window tkwin; /* Token for window. */ + Window parentWin; /* Parent of new window. */ + ClientData instanceData; /* Button instance data. */ +{ + Window window; + HWND parent; + char *class; + WinButton *butPtr = (WinButton *)instanceData; + + parent = Tk_GetHWND(parentWin); + if (butPtr->info.type == TYPE_LABEL) { + class = "STATIC"; + butPtr->style = SS_OWNERDRAW | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS; + } else { + class = "BUTTON"; + butPtr->style = BS_OWNERDRAW | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS; + } + butPtr->hwnd = CreateWindow(class, NULL, butPtr->style, + Tk_X(tkwin), Tk_Y(tkwin), Tk_Width(tkwin), Tk_Height(tkwin), + parent, NULL, Tk_GetHINSTANCE(), NULL); + SetWindowPos(butPtr->hwnd, HWND_TOP, 0, 0, 0, 0, + SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); + butPtr->oldProc = (WNDPROC)SetWindowLong(butPtr->hwnd, GWL_WNDPROC, + (DWORD) ButtonProc); + + window = Tk_AttachHWND(tkwin, butPtr->hwnd); + return window; +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyButton -- + * + * Free data structures associated with the button control. + * + * Results: + * None. + * + * Side effects: + * Restores the default control state. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyButton(butPtr) + TkButton *butPtr; +{ + WinButton *winButPtr = (WinButton *)butPtr; + HWND hwnd = winButPtr->hwnd; + if (hwnd) { + SetWindowLong(hwnd, GWL_WNDPROC, (DWORD) winButPtr->oldProc); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpDisplayButton -- + * + * This procedure is invoked to display a button widget. It is + * normally invoked as an idle handler. + * + * Results: + * None. + * + * Side effects: + * Information appears on the screen. The REDRAW_PENDING flag + * is cleared. + * + *---------------------------------------------------------------------- + */ + +void +TkpDisplayButton(clientData) + ClientData clientData; /* Information about widget. */ +{ + TkWinDCState state; + HDC dc; + register TkButton *butPtr = (TkButton *) clientData; + GC gc; + Tk_3DBorder border; + Pixmap pixmap; + int x = 0; /* Initialization only needed to stop + * compiler warning. */ + int y, relief; + register Tk_Window tkwin = butPtr->tkwin; + int width, height; + int defaultWidth; /* Width of default ring. */ + int offset; /* 0 means this is a label widget. 1 means + * it is a flavor of button, so we offset + * the text to make the button appear to + * move up and down as the relief changes. */ + + butPtr->flags &= ~REDRAW_PENDING; + if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { + return; + } + + border = butPtr->normalBorder; + if ((butPtr->state == tkDisabledUid) && (butPtr->disabledFg != NULL)) { + gc = butPtr->disabledGC; + } else if ((butPtr->state == tkActiveUid) + && !Tk_StrictMotif(butPtr->tkwin)) { + gc = butPtr->activeTextGC; + border = butPtr->activeBorder; + } else { + gc = butPtr->normalTextGC; + } + if ((butPtr->flags & SELECTED) && (butPtr->state != tkActiveUid) + && (butPtr->selectBorder != NULL) && !butPtr->indicatorOn) { + border = butPtr->selectBorder; + } + + /* + * Override the relief specified for the button if this is a + * checkbutton or radiobutton and there's no indicator. + */ + + relief = butPtr->relief; + if ((butPtr->type >= TYPE_CHECK_BUTTON) && !butPtr->indicatorOn) { + relief = (butPtr->flags & SELECTED) ? TK_RELIEF_SUNKEN + : TK_RELIEF_RAISED; + } + + /* + * Compute width of default ring and offset for pushed buttons. + */ + + if (butPtr->type == TYPE_BUTTON) { + defaultWidth = ((butPtr->defaultState == tkActiveUid) + ? butPtr->highlightWidth : 0); + offset = 1; + } else { + defaultWidth = 0; + if ((butPtr->type >= TYPE_CHECK_BUTTON) && !butPtr->indicatorOn) { + offset = 1; + } else { + offset = 0; + } + } + + /* + * In order to avoid screen flashes, this procedure redraws + * the button in a pixmap, then copies the pixmap to the + * screen in a single operation. This means that there's no + * point in time where the on-sreen image has been cleared. + */ + + pixmap = Tk_GetPixmap(butPtr->display, Tk_WindowId(tkwin), + Tk_Width(tkwin), Tk_Height(tkwin), Tk_Depth(tkwin)); + Tk_Fill3DRectangle(tkwin, pixmap, border, 0, 0, Tk_Width(tkwin), + Tk_Height(tkwin), 0, TK_RELIEF_FLAT); + + /* + * Display image or bitmap or text for button. + */ + + if (butPtr->image != None) { + Tk_SizeOfImage(butPtr->image, &width, &height); + + imageOrBitmap: + TkComputeAnchor(butPtr->anchor, tkwin, 0, 0, + butPtr->indicatorSpace + width, height, &x, &y); + x += butPtr->indicatorSpace; + + if (relief == TK_RELIEF_SUNKEN) { + x += offset; + y += offset; + } + if (butPtr->image != NULL) { + if ((butPtr->selectImage != NULL) && (butPtr->flags & SELECTED)) { + Tk_RedrawImage(butPtr->selectImage, 0, 0, width, height, + pixmap, x, y); + } else { + Tk_RedrawImage(butPtr->image, 0, 0, width, height, pixmap, + x, y); + } + } else { + XSetClipOrigin(butPtr->display, gc, x, y); + XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, gc, 0, 0, + (unsigned int) width, (unsigned int) height, x, y, 1); + XSetClipOrigin(butPtr->display, gc, 0, 0); + } + y += height/2; + } else if (butPtr->bitmap != None) { + Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height); + goto imageOrBitmap; + } else { + RECT rect; + TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY, + butPtr->indicatorSpace + butPtr->textWidth, butPtr->textHeight, + &x, &y); + + x += butPtr->indicatorSpace; + + if (relief == TK_RELIEF_SUNKEN) { + x += offset; + y += offset; + } + Tk_DrawTextLayout(butPtr->display, pixmap, gc, butPtr->textLayout, + x, y, 0, -1); + Tk_UnderlineTextLayout(butPtr->display, pixmap, gc, + butPtr->textLayout, x, y, butPtr->underline); + + /* + * Draw the focus ring. If this is a push button then we need to put + * it around the inner edge of the border, otherwise we put it around + * the text. + */ + + if (butPtr->flags & GOT_FOCUS && butPtr->type != TYPE_LABEL) { + dc = TkWinGetDrawableDC(butPtr->display, pixmap, &state); + if (butPtr->type == TYPE_BUTTON || !butPtr->indicatorOn) { + rect.top = butPtr->borderWidth + 1 + defaultWidth; + rect.left = rect.top; + rect.right = Tk_Width(tkwin) - rect.left; + rect.bottom = Tk_Height(tkwin) - rect.top; + } else { + rect.top = y-2; + rect.left = x-2; + rect.right = x+butPtr->textWidth + 1; + rect.bottom = y+butPtr->textHeight + 1; + } + SetTextColor(dc, gc->foreground); + SetBkColor(dc, gc->background); + DrawFocusRect(dc, &rect); + TkWinReleaseDrawableDC(pixmap, dc, &state); + } + y += butPtr->textHeight/2; + } + + /* + * Draw the indicator for check buttons and radio buttons. At this + * point x and y refer to the top-left corner of the text or image + * or bitmap. + */ + + if ((butPtr->type >= TYPE_CHECK_BUTTON) && butPtr->indicatorOn + && boxesPtr) { + int xSrc, ySrc; + + x -= butPtr->indicatorSpace; + y -= butPtr->indicatorDiameter / 2; + + xSrc = (butPtr->flags & SELECTED) ? boxWidth : 0; + if (butPtr->state == tkActiveUid) { + xSrc += boxWidth*2; + } + ySrc = (butPtr->type == TYPE_RADIO_BUTTON) ? 0 : boxHeight; + + /* + * Update the palette in the boxes bitmap to reflect the current + * button colors. Note that this code relies on the layout of the + * bitmap's palette. Also, all of the colors used to draw the + * bitmap must be in the palette that is selected into the DC of + * the offscreen pixmap. This requires that the static colors + * be placed into the palette. + */ + + boxesPalette[PAL_CHECK] = FlipColor(gc->foreground); + boxesPalette[PAL_TOP_OUTER] = FlipColor(TkWinGetBorderPixels(tkwin, + border, TK_3D_DARK_GC)); + boxesPalette[PAL_TOP_INNER] = FlipColor(TkWinGetBorderPixels(tkwin, + border, TK_3D_DARK2)); + boxesPalette[PAL_BOTTOM_INNER] = FlipColor(TkWinGetBorderPixels(tkwin, + border, TK_3D_LIGHT2)); + boxesPalette[PAL_BOTTOM_OUTER] = FlipColor(TkWinGetBorderPixels(tkwin, + border, TK_3D_LIGHT_GC)); + if (butPtr->state == tkDisabledUid) { + boxesPalette[PAL_INTERIOR] = FlipColor(TkWinGetBorderPixels(tkwin, + border, TK_3D_LIGHT2)); + } else if (butPtr->selectBorder != NULL) { + boxesPalette[PAL_INTERIOR] = FlipColor(TkWinGetBorderPixels(tkwin, + butPtr->selectBorder, TK_3D_FLAT_GC)); + } else { + boxesPalette[PAL_INTERIOR] = FlipColor(GetSysColor(COLOR_WINDOW)); + } + boxesPalette[PAL_BACKGROUND] = FlipColor(TkWinGetBorderPixels(tkwin, + border, TK_3D_FLAT_GC)); + + dc = TkWinGetDrawableDC(butPtr->display, pixmap, &state); + StretchDIBits(dc, x, y, boxWidth, boxHeight, xSrc, ySrc, + boxWidth, boxHeight, boxesBits, (LPBITMAPINFO)boxesPtr, + DIB_RGB_COLORS, SRCCOPY); + TkWinReleaseDrawableDC(pixmap, dc, &state); + } + + /* + * If the button is disabled with a stipple rather than a special + * foreground color, generate the stippled effect. If the widget + * is selected and we use a different background color when selected, + * must temporarily modify the GC. + */ + + if ((butPtr->state == tkDisabledUid) + && ((butPtr->disabledFg == NULL) || (butPtr->image != NULL))) { + if ((butPtr->flags & SELECTED) && !butPtr->indicatorOn + && (butPtr->selectBorder != NULL)) { + XSetForeground(butPtr->display, butPtr->disabledGC, + Tk_3DBorderColor(butPtr->selectBorder)->pixel); + } + XFillRectangle(butPtr->display, pixmap, butPtr->disabledGC, + butPtr->inset, butPtr->inset, + (unsigned) (Tk_Width(tkwin) - 2*butPtr->inset), + (unsigned) (Tk_Height(tkwin) - 2*butPtr->inset)); + if ((butPtr->flags & SELECTED) && !butPtr->indicatorOn + && (butPtr->selectBorder != NULL)) { + XSetForeground(butPtr->display, butPtr->disabledGC, + Tk_3DBorderColor(butPtr->normalBorder)->pixel); + } + } + + /* + * Draw the border and traversal highlight last. This way, if the + * button's contents overflow they'll be covered up by the border. + */ + + if (relief != TK_RELIEF_FLAT) { + Tk_Draw3DRectangle(tkwin, pixmap, border, + defaultWidth, defaultWidth, + Tk_Width(tkwin) - 2*defaultWidth, + Tk_Height(tkwin) - 2*defaultWidth, + butPtr->borderWidth, relief); + } + if (defaultWidth != 0) { + dc = TkWinGetDrawableDC(butPtr->display, pixmap, &state); + TkWinFillRect(dc, 0, 0, Tk_Width(tkwin), defaultWidth, + butPtr->highlightColorPtr->pixel); + TkWinFillRect(dc, 0, 0, defaultWidth, Tk_Height(tkwin), + butPtr->highlightColorPtr->pixel); + TkWinFillRect(dc, 0, Tk_Height(tkwin) - defaultWidth, + Tk_Width(tkwin), defaultWidth, + butPtr->highlightColorPtr->pixel); + TkWinFillRect(dc, Tk_Width(tkwin) - defaultWidth, 0, + defaultWidth, Tk_Height(tkwin), + butPtr->highlightColorPtr->pixel); + TkWinReleaseDrawableDC(pixmap, dc, &state); + } + + /* + * Copy the information from the off-screen pixmap onto the screen, + * then delete the pixmap. + */ + + XCopyArea(butPtr->display, pixmap, Tk_WindowId(tkwin), + butPtr->copyGC, 0, 0, (unsigned) Tk_Width(tkwin), + (unsigned) Tk_Height(tkwin), 0, 0); + Tk_FreePixmap(butPtr->display, pixmap); +} + +/* + *---------------------------------------------------------------------- + * + * TkpComputeButtonGeometry -- + * + * After changes in a button's text or bitmap, this procedure + * recomputes the button's geometry and passes this information + * along to the geometry manager for the window. + * + * Results: + * None. + * + * Side effects: + * The button's window may change size. + * + *---------------------------------------------------------------------- + */ + +void +TkpComputeButtonGeometry(butPtr) + register TkButton *butPtr; /* Button whose geometry may have changed. */ +{ + int width, height, avgWidth; + Tk_FontMetrics fm; + + if (butPtr->highlightWidth < 0) { + butPtr->highlightWidth = 0; + } + butPtr->inset = butPtr->highlightWidth + butPtr->borderWidth; + butPtr->indicatorSpace = 0; + + if (!boxesPtr) { + InitBoxes(); + } + + if (butPtr->image != NULL) { + Tk_SizeOfImage(butPtr->image, &width, &height); + imageOrBitmap: + if (butPtr->width > 0) { + width = butPtr->width; + } + if (butPtr->height > 0) { + height = butPtr->height; + } + if ((butPtr->type >= TYPE_CHECK_BUTTON) && butPtr->indicatorOn) { + butPtr->indicatorSpace = boxWidth * 2; + butPtr->indicatorDiameter = boxHeight; + } + } else if (butPtr->bitmap != None) { + Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height); + goto imageOrBitmap; + } else { + Tk_FreeTextLayout(butPtr->textLayout); + butPtr->textLayout = Tk_ComputeTextLayout(butPtr->tkfont, + butPtr->text, -1, butPtr->wrapLength, butPtr->justify, 0, + &butPtr->textWidth, &butPtr->textHeight); + + width = butPtr->textWidth; + height = butPtr->textHeight; + avgWidth = Tk_TextWidth(butPtr->tkfont, "0", 1); + Tk_GetFontMetrics(butPtr->tkfont, &fm); + + if (butPtr->width > 0) { + width = butPtr->width * avgWidth; + } + if (butPtr->height > 0) { + height = butPtr->height * fm.linespace; + } + + if ((butPtr->type >= TYPE_CHECK_BUTTON) && butPtr->indicatorOn) { + butPtr->indicatorDiameter = boxHeight; + butPtr->indicatorSpace = butPtr->indicatorDiameter + avgWidth; + } + + /* + * Increase the inset to allow for the focus ring. + */ + + if (butPtr->type != TYPE_LABEL) { + butPtr->inset += 3; + } + } + + /* + * When issuing the geometry request, add extra space for the indicator, + * if any, and for the border and padding, plus an extra pixel so the + * display can be offset by 1 pixel in either direction for the raised + * or lowered effect. + */ + + if ((butPtr->image == NULL) && (butPtr->bitmap == None)) { + width += 2*butPtr->padX; + height += 2*butPtr->padY; + } + if ((butPtr->type == TYPE_BUTTON) + || ((butPtr->type >= TYPE_CHECK_BUTTON) && !butPtr->indicatorOn)) { + width += 1; + height += 1; + } + Tk_GeometryRequest(butPtr->tkwin, (int) (width + butPtr->indicatorSpace + + 2*butPtr->inset), (int) (height + 2*butPtr->inset)); + Tk_SetInternalBorder(butPtr->tkwin, butPtr->inset); +} + +/* + *---------------------------------------------------------------------- + * + * ButtonProc -- + * + * This function is call by Windows whenever an event occurs on + * a button control created by Tk. + * + * Results: + * Standard Windows return value. + * + * Side effects: + * May generate events. + * + *---------------------------------------------------------------------- + */ + +static LRESULT CALLBACK +ButtonProc(hwnd, message, wParam, lParam) + HWND hwnd; + UINT message; + WPARAM wParam; + LPARAM lParam; +{ + LRESULT result; + WinButton *butPtr; + Tk_Window tkwin = Tk_HWNDToWindow(hwnd); + + if (tkwin == NULL) { + panic("ButtonProc called on an invalid HWND"); + } + butPtr = (WinButton *)((TkWindow*)tkwin)->instanceData; + + switch(message) { + case WM_ERASEBKGND: + return 0; + + case BM_GETCHECK: + if (((butPtr->info.type == TYPE_CHECK_BUTTON) + || (butPtr->info.type == TYPE_RADIO_BUTTON)) + && butPtr->info.indicatorOn) { + return (butPtr->info.flags & SELECTED) + ? BST_CHECKED : BST_UNCHECKED; + } + return 0; + + case BM_GETSTATE: { + DWORD state = 0; + if (((butPtr->info.type == TYPE_CHECK_BUTTON) + || (butPtr->info.type == TYPE_RADIO_BUTTON)) + && butPtr->info.indicatorOn) { + state = (butPtr->info.flags & SELECTED) + ? BST_CHECKED : BST_UNCHECKED; + } + if (butPtr->info.flags & GOT_FOCUS) { + state |= BST_FOCUS; + } + return state; + } + case WM_ENABLE: + break; + + case WM_PAINT: { + PAINTSTRUCT ps; + BeginPaint(hwnd, &ps); + EndPaint(hwnd, &ps); + TkpDisplayButton((ClientData)butPtr); + return 0; + } + case BN_CLICKED: { + int code; + Tcl_Interp *interp = butPtr->info.interp; + if (butPtr->info.state != tkDisabledUid) { + Tcl_Preserve((ClientData)interp); + code = TkInvokeButton((TkButton*)butPtr); + if (code != TCL_OK && code != TCL_CONTINUE + && code != TCL_BREAK) { + Tcl_AddErrorInfo(interp, "\n (button invoke)"); + Tcl_BackgroundError(interp); + } + Tcl_Release((ClientData)interp); + } + Tcl_ServiceAll(); + return 0; + } + + default: + if (Tk_TranslateWinEvent(hwnd, message, wParam, lParam, &result)) { + return result; + } + } + return DefWindowProc(hwnd, message, wParam, lParam); +} diff --git a/win/tkWinClipboard.c b/win/tkWinClipboard.c new file mode 100644 index 0000000..9d4237a --- /dev/null +++ b/win/tkWinClipboard.c @@ -0,0 +1,291 @@ +/* + * tkWinClipboard.c -- + * + * This file contains functions for managing the clipboard. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinClipboard.c 1.8 97/05/20 17:01:13 + */ + +#include "tkWinInt.h" +#include "tkSelect.h" + + +/* + *---------------------------------------------------------------------- + * + * TkSelGetSelection -- + * + * Retrieve the specified selection from another process. For + * now, only fetching XA_STRING from CLIPBOARD is supported. + * Eventually other types should be allowed. + * + * Results: + * The return value is a standard Tcl return value. + * If an error occurs (such as no selection exists) + * then an error message is left in interp->result. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkSelGetSelection(interp, tkwin, selection, target, proc, clientData) + Tcl_Interp *interp; /* Interpreter to use for reporting + * errors. */ + Tk_Window tkwin; /* Window on whose behalf to retrieve + * the selection (determines display + * from which to retrieve). */ + Atom selection; /* Selection to retrieve. */ + Atom target; /* Desired form in which selection + * is to be returned. */ + Tk_GetSelProc *proc; /* Procedure to call to process the + * selection, once it has been retrieved. */ + ClientData clientData; /* Arbitrary value to pass to proc. */ +{ + char *data, *buffer, *destPtr; + HGLOBAL handle; + int result, length; + + if ((selection == Tk_InternAtom(tkwin, "CLIPBOARD")) + && (target == XA_STRING)) { + if (OpenClipboard(NULL)) { + handle = GetClipboardData(CF_TEXT); + if (handle != NULL) { + data = GlobalLock(handle); + length = strlen(data); + buffer = ckalloc(length+1); + destPtr = buffer; + while (*data != '\0') { + if (*data != '\r') { + *destPtr = *data; + destPtr++; + } + data++; + } + *destPtr = '\0'; + GlobalUnlock(handle); + CloseClipboard(); + result = (*proc)(clientData, interp, buffer); + ckfree(buffer); + return result; + } + CloseClipboard(); + } + } + + Tcl_AppendResult(interp, Tk_GetAtomName(tkwin, selection), + " selection doesn't exist or form \"", Tk_GetAtomName(tkwin, target), + "\" not defined", (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * TkSetSelectionOwner -- + * + * This function claims ownership of the specified selection. + * If the selection is CLIPBOARD, then we empty the system + * clipboard. + * + * Results: + * None. + * + * Side effects: + * Empties the system clipboard, and claims ownership. + * + *---------------------------------------------------------------------- + */ + +void +XSetSelectionOwner(display, selection, owner, time) + Display* display; + Atom selection; + Window owner; + Time time; +{ + HWND hwnd = owner ? TkWinGetHWND(owner) : NULL; + Tk_Window tkwin; + + /* + * This is a gross hack because the Tk_InternAtom interface is broken. + * It expects a Tk_Window, even though it only needs a Tk_Display. + */ + + tkwin = (Tk_Window)tkMainWindowList->winPtr; + + if (selection == Tk_InternAtom(tkwin, "CLIPBOARD")) { + + /* + * Only claim and empty the clipboard if we aren't already the + * owner of the clipboard. + */ + + if (GetClipboardOwner() != hwnd) { + OpenClipboard(hwnd); + EmptyClipboard(); + SetClipboardData(CF_TEXT, NULL); + CloseClipboard(); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWinClipboardRender -- + * + * This function supplies the contents of the clipboard in + * response to a WM_RENDERFORMAT message. + * + * Results: + * None. + * + * Side effects: + * Sets the contents of the clipboard. + * + *---------------------------------------------------------------------- + */ + +void +TkWinClipboardRender(dispPtr, format) + TkDisplay *dispPtr; + UINT format; +{ + TkClipboardTarget *targetPtr; + TkClipboardBuffer *cbPtr; + HGLOBAL handle; + char *buffer, *p, *endPtr; + int length; + + for (targetPtr = dispPtr->clipTargetPtr; targetPtr != NULL; + targetPtr = targetPtr->nextPtr) { + if (targetPtr->type == XA_STRING) + break; + } + length = 0; + if (targetPtr != NULL) { + for (cbPtr = targetPtr->firstBufferPtr; cbPtr != NULL; + cbPtr = cbPtr->nextPtr) { + length += cbPtr->length; + for (p = cbPtr->buffer, endPtr = p + cbPtr->length; + p < endPtr; p++) { + if (*p == '\n') { + length++; + } + } + } + } + handle = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, length+1); + if (!handle) { + return; + } + buffer = GlobalLock(handle); + if (targetPtr != NULL) { + for (cbPtr = targetPtr->firstBufferPtr; cbPtr != NULL; + cbPtr = cbPtr->nextPtr) { + for (p = cbPtr->buffer, endPtr = p + cbPtr->length; + p < endPtr; p++) { + if (*p == '\n') { + *buffer++ = '\r'; + } + *buffer++ = *p; + } + } + } + *buffer = '\0'; + GlobalUnlock(handle); + SetClipboardData(CF_TEXT, handle); + return; +} + +/* + *---------------------------------------------------------------------- + * + * TkSelUpdateClipboard -- + * + * This function is called to force the clipboard to be updated + * after new data is added. + * + * Results: + * None. + * + * Side effects: + * Clears the current contents of the clipboard. + * + *---------------------------------------------------------------------- + */ + +void +TkSelUpdateClipboard(winPtr, targetPtr) + TkWindow *winPtr; + TkClipboardTarget *targetPtr; +{ + HWND hwnd = TkWinGetHWND(winPtr->window); + + OpenClipboard(hwnd); + EmptyClipboard(); + SetClipboardData(CF_TEXT, NULL); + CloseClipboard(); +} + +/* + *-------------------------------------------------------------- + * + * TkSelEventProc -- + * + * This procedure is invoked whenever a selection-related + * event occurs. + * + * Results: + * None. + * + * Side effects: + * Lots: depends on the type of event. + * + *-------------------------------------------------------------- + */ + +void +TkSelEventProc(tkwin, eventPtr) + Tk_Window tkwin; /* Window for which event was + * targeted. */ + register XEvent *eventPtr; /* X event: either SelectionClear, + * SelectionRequest, or + * SelectionNotify. */ +{ + if (eventPtr->type == SelectionClear) { + TkSelClearSelection(tkwin, eventPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkSelPropProc -- + * + * This procedure is invoked when property-change events + * occur on windows not known to the toolkit. This is a stub + * function under Windows. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkSelPropProc(eventPtr) + register XEvent *eventPtr; /* X PropertyChange event. */ +{ +} diff --git a/win/tkWinColor.c b/win/tkWinColor.c new file mode 100644 index 0000000..2cc3d09 --- /dev/null +++ b/win/tkWinColor.c @@ -0,0 +1,615 @@ +/* + * tkWinColor.c -- + * + * Functions to map color names to system color values. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * Copyright (c) 1994 Software Research Associates, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinColor.c 1.20 97/10/27 16:39:23 + */ + +#include <tkColor.h> +#include <tkWinInt.h> + +/* + * The following structure is used to keep track of each color that is + * allocated by this module. + */ + +typedef struct WinColor { + TkColor info; /* Generic color information. */ + int index; /* Index for GetSysColor(), -1 if color + * is not a "live" system color. */ +} WinColor; + +/* + * colorTable is a hash table used to look up X colors by name. + */ + +static Tcl_HashTable colorTable; + +/* + * The sysColors array contains the names and index values for the + * Windows indirect system color names. In use, all of the names + * will have the string "System" prepended, but we omit it in the table + * to save space. + */ + +typedef struct { + char *name; + int index; +} SystemColorEntry; + + +static SystemColorEntry sysColors[] = { + "3dDarkShadow", COLOR_3DDKSHADOW, + "3dLight", COLOR_3DLIGHT, + "ActiveBorder", COLOR_ACTIVEBORDER, + "ActiveCaption", COLOR_ACTIVECAPTION, + "AppWorkspace", COLOR_APPWORKSPACE, + "Background", COLOR_BACKGROUND, + "ButtonFace", COLOR_BTNFACE, + "ButtonHighlight", COLOR_BTNHIGHLIGHT, + "ButtonShadow", COLOR_BTNSHADOW, + "ButtonText", COLOR_BTNTEXT, + "CaptionText", COLOR_CAPTIONTEXT, + "DisabledText", COLOR_GRAYTEXT, + "GrayText", COLOR_GRAYTEXT, + "Highlight", COLOR_HIGHLIGHT, + "HighlightText", COLOR_HIGHLIGHTTEXT, + "InactiveBorder", COLOR_INACTIVEBORDER, + "InactiveCaption", COLOR_INACTIVECAPTION, + "InactiveCaptionText", COLOR_INACTIVECAPTIONTEXT, + "InfoBackground", COLOR_INFOBK, + "InfoText", COLOR_INFOTEXT, + "Menu", COLOR_MENU, + "MenuText", COLOR_MENUTEXT, + "Scrollbar", COLOR_SCROLLBAR, + "Window", COLOR_WINDOW, + "WindowFrame", COLOR_WINDOWFRAME, + "WindowText", COLOR_WINDOWTEXT, + NULL, 0 +}; + +static int ncolors = 0; + +/* + * Forward declarations for functions defined later in this file. + */ + +static int FindSystemColor _ANSI_ARGS_((const char *name, + XColor *colorPtr, int *indexPtr)); +static int GetColorByName _ANSI_ARGS_((char *name, XColor *color)); +static int GetColorByValue _ANSI_ARGS_((char *value, XColor *color)); + +/* + *---------------------------------------------------------------------- + * + * FindSystemColor -- + * + * This routine finds the color entry that corresponds to the + * specified color. + * + * Results: + * Returns non-zero on success. The RGB values of the XColor + * will be initialized to the proper values on success. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +FindSystemColor(name, colorPtr, indexPtr) + const char *name; /* Color name. */ + XColor *colorPtr; /* Where to store results. */ + int *indexPtr; /* Out parameter to store color index. */ +{ + int l, u, r, i; + + /* + * Count the number of elements in the color array if we haven't + * done so yet. + */ + + if (ncolors == 0) { + SystemColorEntry *ePtr; + int version; + + version = LOBYTE(LOWORD(GetVersion())); + for (ePtr = sysColors; ePtr->name != NULL; ePtr++) { + if (version < 4) { + if (ePtr->index == COLOR_3DDKSHADOW) { + ePtr->index = COLOR_BTNSHADOW; + } else if (ePtr->index == COLOR_3DLIGHT) { + ePtr->index = COLOR_BTNHIGHLIGHT; + } + } + ncolors++; + } + } + + /* + * Perform a binary search on the sorted array of colors. + */ + + l = 0; + u = ncolors - 1; + while (l <= u) { + i = (l + u) / 2; + r = strcasecmp(name, sysColors[i].name); + if (r == 0) { + break; + } else if (r < 0) { + u = i-1; + } else { + l = i+1; + } + } + if (l > u) { + return 0; + } + + *indexPtr = sysColors[i].index; + colorPtr->pixel = GetSysColor(sysColors[i].index); + colorPtr->red = GetRValue(colorPtr->pixel) << 8; + colorPtr->green = GetGValue(colorPtr->pixel) << 8; + colorPtr->blue = GetBValue(colorPtr->pixel) << 8; + colorPtr->flags = DoRed|DoGreen|DoBlue; + colorPtr->pad = 0; + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetColor -- + * + * Allocate a new TkColor for the color with the given name. + * + * Results: + * Returns a newly allocated TkColor, or NULL on failure. + * + * Side effects: + * May invalidate the colormap cache associated with tkwin upon + * allocating a new colormap entry. Allocates a new TkColor + * structure. + * + *---------------------------------------------------------------------- + */ + +TkColor * +TkpGetColor(tkwin, name) + Tk_Window tkwin; /* Window in which color will be used. */ + Tk_Uid name; /* Name of color to allocated (in form + * suitable for passing to XParseColor). */ +{ + WinColor *winColPtr; + XColor color; + int index = -1; /* -1 indicates that this is not an indirect + * sytem color. */ + + /* + * Check to see if it is a system color or an X color string. If the + * color is found, allocate a new WinColor and store the XColor and the + * system color index. + */ + + if (((strncasecmp(name, "system", 6) == 0) + && FindSystemColor(name+6, &color, &index)) + || XParseColor(Tk_Display(tkwin), Tk_Colormap(tkwin), name, + &color)) { + winColPtr = (WinColor *) ckalloc(sizeof(WinColor)); + winColPtr->info.color = color; + winColPtr->index = index; + + XAllocColor(Tk_Display(tkwin), Tk_Colormap(tkwin), + &winColPtr->info.color); + return (TkColor *) winColPtr; + } + return (TkColor *) NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetColorByValue -- + * + * Given a desired set of red-green-blue intensities for a color, + * locate a pixel value to use to draw that color in a given + * window. + * + * Results: + * The return value is a pointer to an TkColor structure that + * indicates the closest red, blue, and green intensities available + * to those specified in colorPtr, and also specifies a pixel + * value to use to draw in that color. + * + * Side effects: + * May invalidate the colormap cache for the specified window. + * Allocates a new TkColor structure. + * + *---------------------------------------------------------------------- + */ + +TkColor * +TkpGetColorByValue(tkwin, colorPtr) + Tk_Window tkwin; /* Window in which color will be used. */ + XColor *colorPtr; /* Red, green, and blue fields indicate + * desired color. */ +{ + WinColor *tkColPtr = (WinColor *) ckalloc(sizeof(WinColor)); + + tkColPtr->info.color.red = colorPtr->red; + tkColPtr->info.color.green = colorPtr->green; + tkColPtr->info.color.blue = colorPtr->blue; + tkColPtr->info.color.pixel = 0; + tkColPtr->index = -1; + XAllocColor(Tk_Display(tkwin), Tk_Colormap(tkwin), &tkColPtr->info.color); + return (TkColor *) tkColPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpFreeColor -- + * + * Release the specified color back to the system. + * + * Results: + * None + * + * Side effects: + * Invalidates the colormap cache for the colormap associated with + * the given color. + * + *---------------------------------------------------------------------- + */ + +void +TkpFreeColor(tkColPtr) + TkColor *tkColPtr; /* Color to be released. Must have been + * allocated by TkpGetColor or + * TkpGetColorByValue. */ +{ + Screen *screen = tkColPtr->screen; + + XFreeColors(DisplayOfScreen(screen), tkColPtr->colormap, + &tkColPtr->color.pixel, 1, 0L); +} + +/* + *---------------------------------------------------------------------- + * + * TkWinIndexOfColor -- + * + * Given a color, return the system color index that was used + * to create the color. + * + * Results: + * If the color was allocated using a system indirect color name, + * then the corresponding GetSysColor() index is returned. + * Otherwise, -1 is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkWinIndexOfColor(colorPtr) + XColor *colorPtr; +{ + register WinColor *winColPtr = (WinColor *) colorPtr; + if (winColPtr->info.magic == COLOR_MAGIC) { + return winColPtr->index; + } + return -1; +} + +/* + *---------------------------------------------------------------------- + * + * XAllocColor -- + * + * Find the closest available color to the specified XColor. + * + * Results: + * Updates the color argument and returns 1 on success. Otherwise + * returns 0. + * + * Side effects: + * Allocates a new color in the palette. + * + *---------------------------------------------------------------------- + */ + +int +XAllocColor(display, colormap, color) + Display* display; + Colormap colormap; + XColor* color; +{ + TkWinColormap *cmap = (TkWinColormap *) colormap; + PALETTEENTRY entry, closeEntry; + HDC dc = GetDC(NULL); + + entry.peRed = (color->red) >> 8; + entry.peGreen = (color->green) >> 8; + entry.peBlue = (color->blue) >> 8; + entry.peFlags = 0; + + if (GetDeviceCaps(dc, RASTERCAPS) & RC_PALETTE) { + unsigned long sizePalette = GetDeviceCaps(dc, SIZEPALETTE); + UINT newPixel, closePixel; + int new, refCount; + Tcl_HashEntry *entryPtr; + UINT index; + + /* + * Find the nearest existing palette entry. + */ + + newPixel = RGB(entry.peRed, entry.peGreen, entry.peBlue); + index = GetNearestPaletteIndex(cmap->palette, newPixel); + GetPaletteEntries(cmap->palette, index, 1, &closeEntry); + closePixel = RGB(closeEntry.peRed, closeEntry.peGreen, + closeEntry.peBlue); + + /* + * If this is not a duplicate, allocate a new entry. Note that + * we may get values for index that are above the current size + * of the palette. This happens because we don't shrink the size of + * the palette object when we deallocate colors so there may be + * stale values that match in the upper slots. We should ignore + * those values and just put the new color in as if the colors + * had not matched. + */ + + if ((index >= cmap->size) || (newPixel != closePixel)) { + if (cmap->size == sizePalette) { + color->red = closeEntry.peRed << 8; + color->green = closeEntry.peGreen << 8; + color->blue = closeEntry.peBlue << 8; + entry = closeEntry; + if (index >= cmap->size) { + OutputDebugString("XAllocColor: Colormap is bigger than we thought"); + } + } else { + cmap->size++; + ResizePalette(cmap->palette, cmap->size); + SetPaletteEntries(cmap->palette, cmap->size - 1, 1, &entry); + } + } + + color->pixel = PALETTERGB(entry.peRed, entry.peGreen, entry.peBlue); + entryPtr = Tcl_CreateHashEntry(&cmap->refCounts, + (char *) color->pixel, &new); + if (new) { + refCount = 1; + } else { + refCount = ((int) Tcl_GetHashValue(entryPtr)) + 1; + } + Tcl_SetHashValue(entryPtr, (ClientData)refCount); + } else { + + /* + * Determine what color will actually be used on non-colormap systems. + */ + + color->pixel = GetNearestColor(dc, + RGB(entry.peRed, entry.peGreen, entry.peBlue)); + color->red = (GetRValue(color->pixel) << 8); + color->green = (GetGValue(color->pixel) << 8); + color->blue = (GetBValue(color->pixel) << 8); + } + + ReleaseDC(NULL, dc); + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * XFreeColors -- + * + * Deallocate a block of colors. + * + * Results: + * None. + * + * Side effects: + * Removes entries for the current palette and compacts the + * remaining set. + * + *---------------------------------------------------------------------- + */ + +void +XFreeColors(display, colormap, pixels, npixels, planes) + Display* display; + Colormap colormap; + unsigned long* pixels; + int npixels; + unsigned long planes; +{ + TkWinColormap *cmap = (TkWinColormap *) colormap; + COLORREF cref; + UINT count, index, refCount; + int i; + PALETTEENTRY entry, *entries; + Tcl_HashEntry *entryPtr; + HDC dc = GetDC(NULL); + + /* + * We don't have to do anything for non-palette devices. + */ + + if (GetDeviceCaps(dc, RASTERCAPS) & RC_PALETTE) { + + /* + * This is really slow for large values of npixels. + */ + + for (i = 0; i < npixels; i++) { + entryPtr = Tcl_FindHashEntry(&cmap->refCounts, + (char *) pixels[i]); + if (!entryPtr) { + panic("Tried to free a color that isn't allocated."); + } + refCount = (int) Tcl_GetHashValue(entryPtr) - 1; + if (refCount == 0) { + cref = pixels[i] & 0x00ffffff; + index = GetNearestPaletteIndex(cmap->palette, cref); + GetPaletteEntries(cmap->palette, index, 1, &entry); + if (cref == RGB(entry.peRed, entry.peGreen, entry.peBlue)) { + count = cmap->size - index; + entries = (PALETTEENTRY *) ckalloc(sizeof(PALETTEENTRY) + * count); + GetPaletteEntries(cmap->palette, index+1, count, entries); + SetPaletteEntries(cmap->palette, index, count, entries); + ckfree((char *) entries); + cmap->size--; + } else { + panic("Tried to free a color that isn't allocated."); + } + Tcl_DeleteHashEntry(entryPtr); + } else { + Tcl_SetHashValue(entryPtr, (ClientData)refCount); + } + } + } + ReleaseDC(NULL, dc); +} + +/* + *---------------------------------------------------------------------- + * + * XCreateColormap -- + * + * Allocate a new colormap. + * + * Results: + * Returns a newly allocated colormap. + * + * Side effects: + * Allocates an empty palette and color list. + * + *---------------------------------------------------------------------- + */ + +Colormap +XCreateColormap(display, w, visual, alloc) + Display* display; + Window w; + Visual* visual; + int alloc; +{ + char logPalBuf[sizeof(LOGPALETTE) + 256 * sizeof(PALETTEENTRY)]; + LOGPALETTE *logPalettePtr; + PALETTEENTRY *entryPtr; + TkWinColormap *cmap; + Tcl_HashEntry *hashPtr; + int new; + UINT i; + HPALETTE sysPal; + + /* + * Allocate a starting palette with all of the reserved colors. + */ + + logPalettePtr = (LOGPALETTE *) logPalBuf; + logPalettePtr->palVersion = 0x300; + sysPal = (HPALETTE) GetStockObject(DEFAULT_PALETTE); + logPalettePtr->palNumEntries = GetPaletteEntries(sysPal, 0, 256, + logPalettePtr->palPalEntry); + + cmap = (TkWinColormap *) ckalloc(sizeof(TkWinColormap)); + cmap->size = logPalettePtr->palNumEntries; + cmap->stale = 0; + cmap->palette = CreatePalette(logPalettePtr); + + /* + * Add hash entries for each of the static colors. + */ + + Tcl_InitHashTable(&cmap->refCounts, TCL_ONE_WORD_KEYS); + for (i = 0; i < logPalettePtr->palNumEntries; i++) { + entryPtr = logPalettePtr->palPalEntry + i; + hashPtr = Tcl_CreateHashEntry(&cmap->refCounts, (char*) PALETTERGB( + entryPtr->peRed, entryPtr->peGreen, entryPtr->peBlue), &new); + Tcl_SetHashValue(hashPtr, (ClientData)1); + } + + return (Colormap)cmap; +} + +/* + *---------------------------------------------------------------------- + * + * XFreeColormap -- + * + * Frees the resources associated with the given colormap. + * + * Results: + * None. + * + * Side effects: + * Deletes the palette associated with the colormap. Note that + * the palette must not be selected into a device context when + * this occurs. + * + *---------------------------------------------------------------------- + */ + +void +XFreeColormap(display, colormap) + Display* display; + Colormap colormap; +{ + TkWinColormap *cmap = (TkWinColormap *) colormap; + if (!DeleteObject(cmap->palette)) { + panic("Unable to free colormap, palette is still selected."); + } + Tcl_DeleteHashTable(&cmap->refCounts); + ckfree((char *) cmap); +} + +/* + *---------------------------------------------------------------------- + * + * TkWinSelectPalette -- + * + * This function sets up the specified device context with a + * given palette. If the palette is stale, it realizes it in + * the background unless the palette is the current global + * palette. + * + * Results: + * Returns the previous palette selected into the device context. + * + * Side effects: + * May change the system palette. + * + *---------------------------------------------------------------------- + */ + +HPALETTE +TkWinSelectPalette(dc, colormap) + HDC dc; + Colormap colormap; +{ + TkWinColormap *cmap = (TkWinColormap *) colormap; + HPALETTE oldPalette; + + oldPalette = SelectPalette(dc, cmap->palette, + (cmap->palette == TkWinGetSystemPalette()) ? FALSE : TRUE); + RealizePalette(dc); + return oldPalette; +} diff --git a/win/tkWinCursor.c b/win/tkWinCursor.c new file mode 100644 index 0000000..bf81d8f --- /dev/null +++ b/win/tkWinCursor.c @@ -0,0 +1,210 @@ +/* + * tkWinCursor.c -- + * + * This file contains Win32 specific cursor related routines. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinCursor.c 1.10 97/09/02 13:21:01 + */ + +#include "tkWinInt.h" + +/* + * The following data structure contains the system specific data + * necessary to control Windows cursors. + */ + +typedef struct { + TkCursor info; /* Generic cursor info used by tkCursor.c */ + HCURSOR winCursor; /* Win32 cursor handle. */ + int system; /* 1 if cursor is a system cursor, else 0. */ +} TkWinCursor; + +/* + * The table below is used to map from the name of a predefined cursor + * to its resource identifier. + */ + +static struct CursorName { + char *name; + LPCTSTR id; +} cursorNames[] = { + {"starting", IDC_APPSTARTING}, + {"arrow", IDC_ARROW}, + {"ibeam", IDC_IBEAM}, + {"icon", IDC_ICON}, + {"no", IDC_NO}, + {"size", IDC_SIZE}, + {"size_ne_sw", IDC_SIZENESW}, + {"size_ns", IDC_SIZENS}, + {"size_nw_se", IDC_SIZENWSE}, + {"size_we", IDC_SIZEWE}, + {"uparrow", IDC_UPARROW}, + {"wait", IDC_WAIT}, + {"crosshair", IDC_CROSS}, + {"fleur", IDC_SIZE}, + {"sb_v_double_arrow", IDC_SIZENS}, + {"sb_h_double_arrow", IDC_SIZEWE}, + {"center_ptr", IDC_UPARROW}, + {"watch", IDC_WAIT}, + {"xterm", IDC_IBEAM}, + {NULL, 0} +}; + +/* + * The default cursor is used whenever no other cursor has been specified. + */ + +#define TK_DEFAULT_CURSOR IDC_ARROW + + +/* + *---------------------------------------------------------------------- + * + * TkGetCursorByName -- + * + * Retrieve a system cursor by name. + * + * Results: + * Returns a new cursor, or NULL on errors. + * + * Side effects: + * Allocates a new cursor. + * + *---------------------------------------------------------------------- + */ + +TkCursor * +TkGetCursorByName(interp, tkwin, string) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + Tk_Window tkwin; /* Window in which cursor will be used. */ + Tk_Uid string; /* Description of cursor. See manual entry + * for details on legal syntax. */ +{ + struct CursorName *namePtr; + TkWinCursor *cursorPtr; + + /* + * Check for the cursor in the system cursor set. + */ + + for (namePtr = cursorNames; namePtr->name != NULL; namePtr++) { + if (strcmp(namePtr->name, string) == 0) { + break; + } + } + + cursorPtr = (TkWinCursor *) ckalloc(sizeof(TkWinCursor)); + cursorPtr->info.cursor = (Tk_Cursor) cursorPtr; + cursorPtr->winCursor = NULL; + if (namePtr->name != NULL) { + cursorPtr->winCursor = LoadCursor(NULL, namePtr->id); + cursorPtr->system = 1; + } + if (cursorPtr->winCursor == NULL) { + cursorPtr->winCursor = LoadCursor(Tk_GetHINSTANCE(), string); + cursorPtr->system = 0; + } + if (cursorPtr->winCursor == NULL) { + ckfree((char *)cursorPtr); + Tcl_AppendResult(interp, "bad cursor spec \"", string, "\"", + (char *) NULL); + return NULL; + } else { + return (TkCursor *) cursorPtr; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkCreateCursorFromData -- + * + * Creates a cursor from the source and mask bits. + * + * Results: + * Returns a new cursor, or NULL on errors. + * + * Side effects: + * Allocates a new cursor. + * + *---------------------------------------------------------------------- + */ + +TkCursor * +TkCreateCursorFromData(tkwin, source, mask, width, height, xHot, yHot, + fgColor, bgColor) + Tk_Window tkwin; /* Window in which cursor will be used. */ + char *source; /* Bitmap data for cursor shape. */ + char *mask; /* Bitmap data for cursor mask. */ + int width, height; /* Dimensions of cursor. */ + int xHot, yHot; /* Location of hot-spot in cursor. */ + XColor fgColor; /* Foreground color for cursor. */ + XColor bgColor; /* Background color for cursor. */ +{ + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TkFreeCursor -- + * + * This procedure is called to release a cursor allocated by + * TkGetCursorByName. + * + * Results: + * None. + * + * Side effects: + * The cursor data structure is deallocated. + * + *---------------------------------------------------------------------- + */ + +void +TkFreeCursor(cursorPtr) + TkCursor *cursorPtr; +{ + TkWinCursor *winCursorPtr = (TkWinCursor *) cursorPtr; + ckfree((char *) winCursorPtr); +} + +/* + *---------------------------------------------------------------------- + * + * TkpSetCursor -- + * + * Set the global cursor. If the cursor is None, then use the + * default Tk cursor. + * + * Results: + * None. + * + * Side effects: + * Changes the mouse cursor. + * + *---------------------------------------------------------------------- + */ + +void +TkpSetCursor(cursor) + TkpCursor cursor; +{ + HCURSOR hcursor; + TkWinCursor *winCursor = (TkWinCursor *) cursor; + + if (winCursor == NULL || winCursor->winCursor == NULL) { + hcursor = LoadCursor(NULL, TK_DEFAULT_CURSOR); + } else { + hcursor = winCursor->winCursor; + } + + if (hcursor != NULL) { + SetCursor(hcursor); + } +} diff --git a/win/tkWinDefault.h b/win/tkWinDefault.h new file mode 100644 index 0000000..c82f3c8 --- /dev/null +++ b/win/tkWinDefault.h @@ -0,0 +1,456 @@ +/* + * tkWinDefault.h -- + * + * This file defines the defaults for all options for all of + * the Tk widgets. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinDefault.h 1.34 97/10/09 17:45:20 + */ + +#ifndef _TKWINDEFAULT +#define _TKWINDEFAULT + +/* + * The definitions below provide symbolic names for the default colors. + * NORMAL_BG - Normal background color. + * ACTIVE_BG - Background color when widget is active. + * SELECT_BG - Background color for selected text. + * TROUGH - Background color for troughs in scales and scrollbars. + * INDICATOR - Color for indicator when button is selected. + * DISABLED - Foreground color when widget is disabled. + */ + +#define BLACK "Black" +#define WHITE "White" + +#define CTL_FONT "{MS Sans Serif} 8" +#define NORMAL_BG "SystemButtonFace" +#define NORMAL_FG "SystemButtonText" +#define ACTIVE_BG NORMAL_BG +#define TEXT_FG "SystemWindowText" +#define SELECT_BG "SystemHighlight" +#define SELECT_FG "SystemHighlightText" +#define TROUGH "SystemScrollbar" +#define INDICATOR "SystemWindow" +#define DISABLED "SystemDisabledText" +#define MENU_BG "SystemMenu" +#define MENU_FG "SystemMenuText" +#define HIGHLIGHT "SystemWindowFrame" + +/* + * Defaults for labels, buttons, checkbuttons, and radiobuttons: + */ + +#define DEF_BUTTON_ANCHOR "center" +#define DEF_BUTTON_ACTIVE_BG_COLOR NORMAL_BG +#define DEF_BUTTON_ACTIVE_BG_MONO BLACK +#define DEF_BUTTON_ACTIVE_FG_COLOR NORMAL_FG +#define DEF_CHKRAD_ACTIVE_FG_COLOR TEXT_FG +#define DEF_BUTTON_ACTIVE_FG_MONO WHITE +#define DEF_BUTTON_BG_COLOR NORMAL_BG +#define DEF_BUTTON_BG_MONO WHITE +#define DEF_BUTTON_BITMAP "" +#define DEF_BUTTON_BORDER_WIDTH "2" +#define DEF_BUTTON_CURSOR "" +#define DEF_BUTTON_COMMAND "" +#define DEF_BUTTON_DEFAULT "disabled" +#define DEF_BUTTON_DISABLED_FG_COLOR DISABLED +#define DEF_BUTTON_DISABLED_FG_MONO "" +#define DEF_BUTTON_FG NORMAL_FG +#define DEF_CHKRAD_FG TEXT_FG +#define DEF_BUTTON_FONT CTL_FONT +#define DEF_BUTTON_HEIGHT "0" +#define DEF_BUTTON_HIGHLIGHT_BG NORMAL_BG +#define DEF_BUTTON_HIGHLIGHT HIGHLIGHT +#define DEF_LABEL_HIGHLIGHT_WIDTH "0" +#define DEF_BUTTON_HIGHLIGHT_WIDTH "1" +#define DEF_BUTTON_IMAGE (char *) NULL +#define DEF_BUTTON_INDICATOR "1" +#define DEF_BUTTON_JUSTIFY "center" +#define DEF_BUTTON_OFF_VALUE "0" +#define DEF_BUTTON_ON_VALUE "1" +#define DEF_BUTTON_PADX "1" +#define DEF_LABCHKRAD_PADX "1" +#define DEF_BUTTON_PADY "1" +#define DEF_LABCHKRAD_PADY "1" +#define DEF_BUTTON_RELIEF "raised" +#define DEF_LABCHKRAD_RELIEF "flat" +#define DEF_BUTTON_SELECT_COLOR INDICATOR +#define DEF_BUTTON_SELECT_MONO BLACK +#define DEF_BUTTON_SELECT_IMAGE (char *) NULL +#define DEF_BUTTON_STATE "normal" +#define DEF_LABEL_TAKE_FOCUS "0" +#define DEF_BUTTON_TAKE_FOCUS (char *) NULL +#define DEF_BUTTON_TEXT "" +#define DEF_BUTTON_TEXT_VARIABLE "" +#define DEF_BUTTON_UNDERLINE "-1" +#define DEF_BUTTON_VALUE "" +#define DEF_BUTTON_WIDTH "0" +#define DEF_BUTTON_WRAP_LENGTH "0" +#define DEF_RADIOBUTTON_VARIABLE "selectedButton" +#define DEF_CHECKBUTTON_VARIABLE "" + +/* + * Defaults for canvases: + */ + +#define DEF_CANVAS_BG_COLOR NORMAL_BG +#define DEF_CANVAS_BG_MONO WHITE +#define DEF_CANVAS_BORDER_WIDTH "0" +#define DEF_CANVAS_CLOSE_ENOUGH "1" +#define DEF_CANVAS_CONFINE "1" +#define DEF_CANVAS_CURSOR "" +#define DEF_CANVAS_HEIGHT "7c" +#define DEF_CANVAS_HIGHLIGHT_BG NORMAL_BG +#define DEF_CANVAS_HIGHLIGHT HIGHLIGHT +#define DEF_CANVAS_HIGHLIGHT_WIDTH "2" +#define DEF_CANVAS_INSERT_BG NORMAL_FG +#define DEF_CANVAS_INSERT_BD_COLOR "0" +#define DEF_CANVAS_INSERT_BD_MONO "0" +#define DEF_CANVAS_INSERT_OFF_TIME "300" +#define DEF_CANVAS_INSERT_ON_TIME "600" +#define DEF_CANVAS_INSERT_WIDTH "2" +#define DEF_CANVAS_RELIEF "flat" +#define DEF_CANVAS_SCROLL_REGION "" +#define DEF_CANVAS_SELECT_COLOR SELECT_BG +#define DEF_CANVAS_SELECT_MONO BLACK +#define DEF_CANVAS_SELECT_BD_COLOR "1" +#define DEF_CANVAS_SELECT_BD_MONO "0" +#define DEF_CANVAS_SELECT_FG_COLOR SELECT_FG +#define DEF_CANVAS_SELECT_FG_MONO WHITE +#define DEF_CANVAS_TAKE_FOCUS (char *) NULL +#define DEF_CANVAS_WIDTH "10c" +#define DEF_CANVAS_X_SCROLL_CMD "" +#define DEF_CANVAS_X_SCROLL_INCREMENT "0" +#define DEF_CANVAS_Y_SCROLL_CMD "" +#define DEF_CANVAS_Y_SCROLL_INCREMENT "0" + +/* + * Defaults for entries: + */ + +#define DEF_ENTRY_BG_COLOR "SystemWindow" +#define DEF_ENTRY_BG_MONO WHITE +#define DEF_ENTRY_BORDER_WIDTH "2" +#define DEF_ENTRY_CURSOR "xterm" +#define DEF_ENTRY_EXPORT_SELECTION "1" +#define DEF_ENTRY_FONT CTL_FONT +#define DEF_ENTRY_FG TEXT_FG +#define DEF_ENTRY_HIGHLIGHT_BG NORMAL_BG +#define DEF_ENTRY_HIGHLIGHT HIGHLIGHT +#define DEF_ENTRY_HIGHLIGHT_WIDTH "0" +#define DEF_ENTRY_INSERT_BG TEXT_FG +#define DEF_ENTRY_INSERT_BD_COLOR "0" +#define DEF_ENTRY_INSERT_BD_MONO "0" +#define DEF_ENTRY_INSERT_OFF_TIME "300" +#define DEF_ENTRY_INSERT_ON_TIME "600" +#define DEF_ENTRY_INSERT_WIDTH "2" +#define DEF_ENTRY_JUSTIFY "left" +#define DEF_ENTRY_RELIEF "sunken" +#define DEF_ENTRY_SCROLL_COMMAND "" +#define DEF_ENTRY_SELECT_COLOR SELECT_BG +#define DEF_ENTRY_SELECT_MONO BLACK +#define DEF_ENTRY_SELECT_BD_COLOR "0" +#define DEF_ENTRY_SELECT_BD_MONO "0" +#define DEF_ENTRY_SELECT_FG_COLOR SELECT_FG +#define DEF_ENTRY_SELECT_FG_MONO WHITE +#define DEF_ENTRY_SHOW (char *) NULL +#define DEF_ENTRY_STATE "normal" +#define DEF_ENTRY_TAKE_FOCUS (char *) NULL +#define DEF_ENTRY_TEXT_VARIABLE "" +#define DEF_ENTRY_WIDTH "20" + +/* + * Defaults for frames: + */ + +#define DEF_FRAME_BG_COLOR NORMAL_BG +#define DEF_FRAME_BG_MONO WHITE +#define DEF_FRAME_BORDER_WIDTH "0" +#define DEF_FRAME_CLASS "Frame" +#define DEF_FRAME_COLORMAP "" +#define DEF_FRAME_CONTAINER "0" +#define DEF_FRAME_CURSOR "" +#define DEF_FRAME_HEIGHT "0" +#define DEF_FRAME_HIGHLIGHT_BG NORMAL_BG +#define DEF_FRAME_HIGHLIGHT HIGHLIGHT +#define DEF_FRAME_HIGHLIGHT_WIDTH "0" +#define DEF_FRAME_RELIEF "flat" +#define DEF_FRAME_TAKE_FOCUS "0" +#define DEF_FRAME_USE "" +#define DEF_FRAME_VISUAL "" +#define DEF_FRAME_WIDTH "0" + +/* + * Defaults for listboxes: + */ + +#define DEF_LISTBOX_BG_COLOR NORMAL_BG +#define DEF_LISTBOX_BG_MONO WHITE +#define DEF_LISTBOX_BORDER_WIDTH "2" +#define DEF_LISTBOX_CURSOR "" +#define DEF_LISTBOX_EXPORT_SELECTION "1" +#define DEF_LISTBOX_FONT CTL_FONT +#define DEF_LISTBOX_FG NORMAL_FG +#define DEF_LISTBOX_HEIGHT "10" +#define DEF_LISTBOX_HIGHLIGHT_BG NORMAL_BG +#define DEF_LISTBOX_HIGHLIGHT HIGHLIGHT +#define DEF_LISTBOX_HIGHLIGHT_WIDTH "1" +#define DEF_LISTBOX_RELIEF "sunken" +#define DEF_LISTBOX_SCROLL_COMMAND "" +#define DEF_LISTBOX_SELECT_COLOR SELECT_BG +#define DEF_LISTBOX_SELECT_MONO BLACK +#define DEF_LISTBOX_SELECT_BD "1" +#define DEF_LISTBOX_SELECT_FG_COLOR SELECT_FG +#define DEF_LISTBOX_SELECT_FG_MONO WHITE +#define DEF_LISTBOX_SELECT_MODE "browse" +#define DEF_LISTBOX_SET_GRID "0" +#define DEF_LISTBOX_TAKE_FOCUS (char *) NULL +#define DEF_LISTBOX_WIDTH "20" + +/* + * Defaults for individual entries of menus: + */ + +#define DEF_MENU_ENTRY_ACTIVE_BG (char *) NULL +#define DEF_MENU_ENTRY_ACTIVE_FG (char *) NULL +#define DEF_MENU_ENTRY_ACCELERATOR (char *) NULL +#define DEF_MENU_ENTRY_BG (char *) NULL +#define DEF_MENU_ENTRY_BITMAP None +#define DEF_MENU_ENTRY_COLUMN_BREAK "0" +#define DEF_MENU_ENTRY_COMMAND (char *) NULL +#define DEF_MENU_ENTRY_FG (char *) NULL +#define DEF_MENU_ENTRY_FONT (char *) NULL +#define DEF_MENU_ENTRY_HIDE_MARGIN "0" +#define DEF_MENU_ENTRY_IMAGE (char *) NULL +#define DEF_MENU_ENTRY_INDICATOR "1" +#define DEF_MENU_ENTRY_LABEL (char *) NULL +#define DEF_MENU_ENTRY_MENU (char *) NULL +#define DEF_MENU_ENTRY_OFF_VALUE "0" +#define DEF_MENU_ENTRY_ON_VALUE "1" +#define DEF_MENU_ENTRY_SELECT_IMAGE (char *) NULL +#define DEF_MENU_ENTRY_STATE "normal" +#define DEF_MENU_ENTRY_VALUE (char *) NULL +#define DEF_MENU_ENTRY_CHECK_VARIABLE (char *) NULL +#define DEF_MENU_ENTRY_RADIO_VARIABLE "selectedButton" +#define DEF_MENU_ENTRY_SELECT (char *) NULL +#define DEF_MENU_ENTRY_UNDERLINE "-1" + +/* + * Defaults for menus overall: + */ + +#define DEF_MENU_ACTIVE_BG_COLOR SELECT_BG +#define DEF_MENU_ACTIVE_BG_MONO BLACK +#define DEF_MENU_ACTIVE_BORDER_WIDTH "0" +#define DEF_MENU_ACTIVE_FG_COLOR SELECT_FG +#define DEF_MENU_ACTIVE_FG_MONO WHITE +#define DEF_MENU_BG_COLOR MENU_BG +#define DEF_MENU_BG_MONO WHITE +#define DEF_MENU_BORDER_WIDTH "0" +#define DEF_MENU_CURSOR "arrow" +#define DEF_MENU_DISABLED_FG_COLOR DISABLED +#define DEF_MENU_DISABLED_FG_MONO "" +#define DEF_MENU_FONT CTL_FONT +#define DEF_MENU_FG MENU_FG +#define DEF_MENU_POST_COMMAND "" +#define DEF_MENU_RELIEF "flat" +#define DEF_MENU_SELECT_COLOR MENU_FG +#define DEF_MENU_SELECT_MONO BLACK +#define DEF_MENU_TAKE_FOCUS "0" +#define DEF_MENU_TEAROFF "1" +#define DEF_MENU_TEAROFF_CMD (char *) NULL +#define DEF_MENU_TITLE "" +#define DEF_MENU_TYPE "normal" + +/* + * Defaults for menubuttons: + */ + +#define DEF_MENUBUTTON_ANCHOR "center" +#define DEF_MENUBUTTON_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_MENUBUTTON_ACTIVE_BG_MONO BLACK +#define DEF_MENUBUTTON_ACTIVE_FG_COLOR NORMAL_FG +#define DEF_MENUBUTTON_ACTIVE_FG_MONO WHITE +#define DEF_MENUBUTTON_BG_COLOR NORMAL_BG +#define DEF_MENUBUTTON_BG_MONO WHITE +#define DEF_MENUBUTTON_BITMAP "" +#define DEF_MENUBUTTON_BORDER_WIDTH "2" +#define DEF_MENUBUTTON_CURSOR "" +#define DEF_MENUBUTTON_DIRECTION "below" +#define DEF_MENUBUTTON_DISABLED_FG_COLOR DISABLED +#define DEF_MENUBUTTON_DISABLED_FG_MONO "" +#define DEF_MENUBUTTON_FONT CTL_FONT +#define DEF_MENUBUTTON_FG NORMAL_FG +#define DEF_MENUBUTTON_HEIGHT "0" +#define DEF_MENUBUTTON_HIGHLIGHT_BG NORMAL_BG +#define DEF_MENUBUTTON_HIGHLIGHT HIGHLIGHT +#define DEF_MENUBUTTON_HIGHLIGHT_WIDTH "0" +#define DEF_MENUBUTTON_IMAGE (char *) NULL +#define DEF_MENUBUTTON_INDICATOR "0" +#define DEF_MENUBUTTON_JUSTIFY "center" +#define DEF_MENUBUTTON_MENU "" +#define DEF_MENUBUTTON_PADX "4p" +#define DEF_MENUBUTTON_PADY "3p" +#define DEF_MENUBUTTON_RELIEF "flat" +#define DEF_MENUBUTTON_STATE "normal" +#define DEF_MENUBUTTON_TAKE_FOCUS "0" +#define DEF_MENUBUTTON_TEXT "" +#define DEF_MENUBUTTON_TEXT_VARIABLE "" +#define DEF_MENUBUTTON_UNDERLINE "-1" +#define DEF_MENUBUTTON_WIDTH "0" +#define DEF_MENUBUTTON_WRAP_LENGTH "0" + +/* + * Defaults for messages: + */ + +#define DEF_MESSAGE_ANCHOR "center" +#define DEF_MESSAGE_ASPECT "150" +#define DEF_MESSAGE_BG_COLOR NORMAL_BG +#define DEF_MESSAGE_BG_MONO WHITE +#define DEF_MESSAGE_BORDER_WIDTH "2" +#define DEF_MESSAGE_CURSOR "" +#define DEF_MESSAGE_FG NORMAL_FG +#define DEF_MESSAGE_FONT CTL_FONT +#define DEF_MESSAGE_HIGHLIGHT_BG NORMAL_BG +#define DEF_MESSAGE_HIGHLIGHT HIGHLIGHT +#define DEF_MESSAGE_HIGHLIGHT_WIDTH "0" +#define DEF_MESSAGE_JUSTIFY "left" +#define DEF_MESSAGE_PADX "-1" +#define DEF_MESSAGE_PADY "-1" +#define DEF_MESSAGE_RELIEF "flat" +#define DEF_MESSAGE_TAKE_FOCUS "0" +#define DEF_MESSAGE_TEXT "" +#define DEF_MESSAGE_TEXT_VARIABLE "" +#define DEF_MESSAGE_WIDTH "0" + +/* + * Defaults for scales: + */ + +#define DEF_SCALE_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_SCALE_ACTIVE_BG_MONO BLACK +#define DEF_SCALE_BG_COLOR NORMAL_BG +#define DEF_SCALE_BG_MONO WHITE +#define DEF_SCALE_BIG_INCREMENT "0" +#define DEF_SCALE_BORDER_WIDTH "2" +#define DEF_SCALE_COMMAND "" +#define DEF_SCALE_CURSOR "" +#define DEF_SCALE_DIGITS "0" +#define DEF_SCALE_FONT CTL_FONT +#define DEF_SCALE_FG_COLOR NORMAL_FG +#define DEF_SCALE_FG_MONO BLACK +#define DEF_SCALE_FROM "0" +#define DEF_SCALE_HIGHLIGHT_BG NORMAL_BG +#define DEF_SCALE_HIGHLIGHT HIGHLIGHT +#define DEF_SCALE_HIGHLIGHT_WIDTH "2" +#define DEF_SCALE_LABEL "" +#define DEF_SCALE_LENGTH "100" +#define DEF_SCALE_ORIENT "vertical" +#define DEF_SCALE_RELIEF "flat" +#define DEF_SCALE_REPEAT_DELAY "300" +#define DEF_SCALE_REPEAT_INTERVAL "100" +#define DEF_SCALE_RESOLUTION "1" +#define DEF_SCALE_TROUGH_COLOR TROUGH +#define DEF_SCALE_TROUGH_MONO WHITE +#define DEF_SCALE_SHOW_VALUE "1" +#define DEF_SCALE_SLIDER_LENGTH "30" +#define DEF_SCALE_SLIDER_RELIEF "raised" +#define DEF_SCALE_STATE "normal" +#define DEF_SCALE_TAKE_FOCUS (char *) NULL +#define DEF_SCALE_TICK_INTERVAL "0" +#define DEF_SCALE_TO "100" +#define DEF_SCALE_VARIABLE "" +#define DEF_SCALE_WIDTH "15" + +/* + * Defaults for scrollbars: + */ + +#define DEF_SCROLLBAR_ACTIVE_BG_COLOR ACTIVE_BG +#define DEF_SCROLLBAR_ACTIVE_BG_MONO BLACK +#define DEF_SCROLLBAR_ACTIVE_RELIEF "raised" +#define DEF_SCROLLBAR_BG_COLOR NORMAL_BG +#define DEF_SCROLLBAR_BG_MONO WHITE +#define DEF_SCROLLBAR_BORDER_WIDTH "0" +#define DEF_SCROLLBAR_COMMAND "" +#define DEF_SCROLLBAR_CURSOR "" +#define DEF_SCROLLBAR_EL_BORDER_WIDTH "-1" +#define DEF_SCROLLBAR_HIGHLIGHT_BG NORMAL_BG +#define DEF_SCROLLBAR_HIGHLIGHT HIGHLIGHT +#define DEF_SCROLLBAR_HIGHLIGHT_WIDTH "0" +#define DEF_SCROLLBAR_JUMP "0" +#define DEF_SCROLLBAR_ORIENT "vertical" +#define DEF_SCROLLBAR_RELIEF "sunken" +#define DEF_SCROLLBAR_REPEAT_DELAY "300" +#define DEF_SCROLLBAR_REPEAT_INTERVAL "100" +#define DEF_SCROLLBAR_TAKE_FOCUS (char *) NULL +#define DEF_SCROLLBAR_TROUGH_COLOR TROUGH +#define DEF_SCROLLBAR_TROUGH_MONO WHITE +#define DEF_SCROLLBAR_WIDTH "10" + +/* + * Defaults for texts: + */ + +#define DEF_TEXT_BG_COLOR "SystemWindow" +#define DEF_TEXT_BG_MONO WHITE +#define DEF_TEXT_BORDER_WIDTH "2" +#define DEF_TEXT_CURSOR "xterm" +#define DEF_TEXT_FG TEXT_FG +#define DEF_TEXT_EXPORT_SELECTION "1" +#define DEF_TEXT_FONT CTL_FONT +#define DEF_TEXT_HEIGHT "24" +#define DEF_TEXT_HIGHLIGHT_BG NORMAL_BG +#define DEF_TEXT_HIGHLIGHT HIGHLIGHT +#define DEF_TEXT_HIGHLIGHT_WIDTH "0" +#define DEF_TEXT_INSERT_BG TEXT_FG +#define DEF_TEXT_INSERT_BD_COLOR "0" +#define DEF_TEXT_INSERT_BD_MONO "0" +#define DEF_TEXT_INSERT_OFF_TIME "300" +#define DEF_TEXT_INSERT_ON_TIME "600" +#define DEF_TEXT_INSERT_WIDTH "2" +#define DEF_TEXT_PADX "1" +#define DEF_TEXT_PADY "1" +#define DEF_TEXT_RELIEF "sunken" +#define DEF_TEXT_SELECT_COLOR SELECT_BG +#define DEF_TEXT_SELECT_MONO BLACK +#define DEF_TEXT_SELECT_BD_COLOR "0" +#define DEF_TEXT_SELECT_BD_MONO "0" +#define DEF_TEXT_SELECT_FG_COLOR SELECT_FG +#define DEF_TEXT_SELECT_FG_MONO WHITE +#define DEF_TEXT_SELECT_RELIEF "flat" +#define DEF_TEXT_SET_GRID "0" +#define DEF_TEXT_SPACING1 "0" +#define DEF_TEXT_SPACING2 "0" +#define DEF_TEXT_SPACING3 "0" +#define DEF_TEXT_STATE "normal" +#define DEF_TEXT_TABS "" +#define DEF_TEXT_TAKE_FOCUS (char *) NULL +#define DEF_TEXT_WIDTH "80" +#define DEF_TEXT_WRAP "char" +#define DEF_TEXT_XSCROLL_COMMAND "" +#define DEF_TEXT_YSCROLL_COMMAND "" + +/* + * Defaults for canvas text: + */ + +#define DEF_CANVTEXT_FONT CTL_FONT + +/* + * Defaults for toplevels (most of the defaults for frames also apply + * to toplevels): + */ + +#define DEF_TOPLEVEL_CLASS "Toplevel" +#define DEF_TOPLEVEL_MENU "" +#define DEF_TOPLEVEL_SCREEN "" + +#endif /* _TKWINDEFAULT */ diff --git a/win/tkWinDialog.c b/win/tkWinDialog.c new file mode 100644 index 0000000..7d01edb --- /dev/null +++ b/win/tkWinDialog.c @@ -0,0 +1,1050 @@ +/* + * tkWinDialog.c -- + * + * Contains the Windows implementation of the common dialog boxes. + * + * Copyright (c) 1996-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinDialog.c 1.10 97/10/21 11:29:18 + * + */ + +#include "tkWinInt.h" +#include "tkFileFilter.h" + +#include <commdlg.h> /* includes common dialog functionality */ +#include <dlgs.h> /* includes common dialog template defines */ +#include <cderr.h> /* includes the common dialog error codes */ + +#if ((TK_MAJOR_VERSION == 4) && (TK_MINOR_VERSION <= 2)) +/* + * The following function is implemented on tk4.3 and after only + */ +#define Tk_GetHWND TkWinGetHWND +#endif + +#define SAVE_FILE 0 +#define OPEN_FILE 1 + +/*---------------------------------------------------------------------- + * MsgTypeInfo -- + * + * This structure stores the type of available message box in an + * easy-to-process format. Used by th Tk_MessageBox() function + *---------------------------------------------------------------------- + */ +typedef struct MsgTypeInfo { + char * name; + int type; + int numButtons; + char * btnNames[3]; +} MsgTypeInfo; + +#define NUM_TYPES 6 + +static MsgTypeInfo +msgTypeInfo[NUM_TYPES] = { + {"abortretryignore", MB_ABORTRETRYIGNORE, 3, {"abort", "retry", "ignore"}}, + {"ok", MB_OK, 1, {"ok" }}, + {"okcancel", MB_OKCANCEL, 2, {"ok", "cancel" }}, + {"retrycancel", MB_RETRYCANCEL, 2, {"retry", "cancel" }}, + {"yesno", MB_YESNO, 2, {"yes", "no" }}, + {"yesnocancel", MB_YESNOCANCEL, 3, {"yes", "no", "cancel"}} +}; + +/* + * The following structure is used in the GetOpenFileName() and + * GetSaveFileName() calls. + */ +typedef struct _OpenFileData { + Tcl_Interp * interp; + TCHAR szFile[MAX_PATH+1]; +} OpenFileData; + +/* + * The following structure is used in the ChooseColor() call. + */ +typedef struct _ChooseColorData { + Tcl_Interp * interp; + char * title; /* Title of the color dialog */ +} ChooseColorData; + + +static int GetFileName _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, int argc, char **argv, + int isOpen)); +static UINT CALLBACK ColorDlgHookProc _ANSI_ARGS_((HWND hDlg, UINT uMsg, + WPARAM wParam, LPARAM lParam)); +static int MakeFilter _ANSI_ARGS_((Tcl_Interp *interp, + OPENFILENAME *ofnPtr, char * string)); +static int ParseFileDlgArgs _ANSI_ARGS_((Tcl_Interp * interp, + OPENFILENAME *ofnPtr, int argc, char ** argv, + int isOpen)); +static int ProcessCDError _ANSI_ARGS_((Tcl_Interp * interp, + DWORD dwErrorCode, HWND hWnd)); + +/* + *---------------------------------------------------------------------- + * + * EvalArgv -- + * + * Invokes the Tcl procedure with the arguments. argv[0] is set by + * the caller of this function. It may be different than cmdName. + * The TCL command will see argv[0], not cmdName, as its name if it + * invokes [lindex [info level 0] 0] + * + * Results: + * TCL_ERROR if the command does not exist and cannot be autoloaded. + * Otherwise, return the result of the evaluation of the command. + * + * Side effects: + * The command may be autoloaded. + * + *---------------------------------------------------------------------- + */ + +static int +EvalArgv(interp, cmdName, argc, argv) + Tcl_Interp *interp; /* Current interpreter. */ + char * cmdName; /* Name of the TCL command to call */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tcl_CmdInfo cmdInfo; + + if (!Tcl_GetCommandInfo(interp, cmdName, &cmdInfo)) { + char * cmdArgv[2]; + + /* + * This comand is not in the interpreter yet -- looks like we + * have to auto-load it + */ + if (!Tcl_GetCommandInfo(interp, "auto_load", &cmdInfo)) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "cannot execute command \"auto_load\"", + NULL); + return TCL_ERROR; + } + + cmdArgv[0] = "auto_load"; + cmdArgv[1] = cmdName; + + if ((*cmdInfo.proc)(cmdInfo.clientData, interp, 2, cmdArgv)!= TCL_OK){ + return TCL_ERROR; + } + + if (!Tcl_GetCommandInfo(interp, cmdName, &cmdInfo)) { + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "cannot auto-load command \"", + cmdName, "\"",NULL); + return TCL_ERROR; + } + } + + return (*cmdInfo.proc)(cmdInfo.clientData, interp, argc, argv); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_ChooseColorCmd -- + * + * This procedure implements the color dialog box for the Windows + * platform. See the user documentation for details on what it + * does. + * + * Results: + * See user documentation. + * + * Side effects: + * A dialog window is created the first time this procedure is called. + * This window is not destroyed and will be reused the next time the + * application invokes the "tk_chooseColor" command. + * + *---------------------------------------------------------------------- + */ + +int +Tk_ChooseColorCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window parent = Tk_MainWindow(interp); + ChooseColorData custData; + int oldMode; + CHOOSECOLOR chooseColor; + char * colorStr = NULL; + int i; + int winCode, tclCode; + XColor * colorPtr = NULL; + static inited = 0; + static long dwCustColors[16]; + static long oldColor; /* the color selected last time */ + + custData.title = NULL; + + if (!inited) { + /* + * dwCustColors stores the custom color which the user can + * modify. We store these colors in a fixed array so that the next + * time the color dialog pops up, the same set of custom colors + * remain in the dialog. + */ + for (i=0; i<16; i++) { + dwCustColors[i] = (RGB(255-i*10, i, i*10)) ; + } + oldColor = RGB(0xa0,0xa0,0xa0); + inited = 1; + } + + /* + * 1. Parse the arguments + */ + + chooseColor.lStructSize = sizeof(CHOOSECOLOR) ; + chooseColor.hwndOwner = 0; /* filled in below */ + chooseColor.hInstance = 0; + chooseColor.rgbResult = oldColor; + chooseColor.lpCustColors = (LPDWORD) dwCustColors ; + chooseColor.Flags = CC_RGBINIT | CC_FULLOPEN | CC_ENABLEHOOK; + chooseColor.lCustData = (LPARAM)&custData; + chooseColor.lpfnHook = ColorDlgHookProc; + chooseColor.lpTemplateName = NULL; + + for (i=1; i<argc; i+=2) { + int v = i+1; + int len = strlen(argv[i]); + + if (strncmp(argv[i], "-initialcolor", len)==0) { + if (v==argc) {goto arg_missing;} + + colorStr = argv[v]; + } + else if (strncmp(argv[i], "-parent", len)==0) { + if (v==argc) {goto arg_missing;} + + parent=Tk_NameToWindow(interp, argv[v], Tk_MainWindow(interp)); + if (parent == NULL) { + return TCL_ERROR; + } + } + else if (strncmp(argv[i], "-title", len)==0) { + if (v==argc) {goto arg_missing;} + + custData.title = argv[v]; + } + else { + Tcl_AppendResult(interp, "unknown option \"", + argv[i], "\", must be -initialcolor, -parent or -title", + NULL); + return TCL_ERROR; + } + } + + if (Tk_WindowId(parent) == None) { + Tk_MakeWindowExist(parent); + } + chooseColor.hwndOwner = Tk_GetHWND(Tk_WindowId(parent)); + + if (colorStr != NULL) { + colorPtr = Tk_GetColor(interp, Tk_MainWindow(interp), colorStr); + if (!colorPtr) { + return TCL_ERROR; + } + chooseColor.rgbResult = RGB((colorPtr->red/0x100), + (colorPtr->green/0x100), (colorPtr->blue/0x100)); + } + + /* + * 2. Popup the dialog + */ + + oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); + winCode = ChooseColor(&chooseColor); + (void) Tcl_SetServiceMode(oldMode); + + /* + * Clear the interp result since anything may have happened during the + * modal loop. + */ + + Tcl_ResetResult(interp); + + /* + * 3. Process the result of the dialog + */ + if (winCode) { + /* + * User has selected a color + */ + char result[100]; + + sprintf(result, "#%02x%02x%02x", + GetRValue(chooseColor.rgbResult), + GetGValue(chooseColor.rgbResult), + GetBValue(chooseColor.rgbResult)); + Tcl_AppendResult(interp, result, NULL); + tclCode = TCL_OK; + + oldColor = chooseColor.rgbResult; + } else { + /* + * User probably pressed Cancel, or an error occurred + */ + tclCode = ProcessCDError(interp, CommDlgExtendedError(), + chooseColor.hwndOwner); + } + + if (colorPtr) { + Tk_FreeColor(colorPtr); + } + + return tclCode; + + arg_missing: + Tcl_AppendResult(interp, "value for \"", argv[argc-1], "\" missing", + NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * ColorDlgHookProc -- + * + * Gets called during the execution of the color dialog. It processes + * the "interesting" messages that Windows send to the dialog. + * + * Results: + * TRUE if the message has been processed, FALSE otherwise. + * + * Side effects: + * Changes the title of the dialog window when it is popped up. + * + *---------------------------------------------------------------------- + */ + +static UINT +CALLBACK ColorDlgHookProc(hDlg, uMsg, wParam, lParam) + HWND hDlg; /* Handle to the color dialog */ + UINT uMsg; /* Type of message */ + WPARAM wParam; /* word param, interpretation depends on uMsg*/ + LPARAM lParam; /* long param, interpretation depends on uMsg*/ +{ + CHOOSECOLOR * ccPtr; + ChooseColorData * pCustData; + + switch (uMsg) { + case WM_INITDIALOG: + /* Save the pointer to CHOOSECOLOR so that we can use it later */ + SetWindowLong(hDlg, DWL_USER, lParam); + + /* Set the title string of the dialog */ + ccPtr = (CHOOSECOLOR*)lParam; + pCustData = (ChooseColorData*)(ccPtr->lCustData); + if (pCustData->title && *(pCustData->title)) { + SetWindowText(hDlg, (LPCSTR)pCustData->title); + } + + return TRUE; + } + + return FALSE; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetOpenFileCmd -- + * + * This procedure implements the "open file" dialog box for the + * Windows platform. See the user documentation for details on what + * it does. + * + * Results: + * See user documentation. + * + * Side effects: + * A dialog window is created the first this procedure is called. + * This window is not destroyed and will be reused the next time + * the application invokes the "tk_getOpenFile" or + * "tk_getSaveFile" command. + * + *---------------------------------------------------------------------- + */ + +int +Tk_GetOpenFileCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + return GetFileName(clientData, interp, argc, argv, OPEN_FILE); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetSaveFileCmd -- + * + * Same as Tk_GetOpenFileCmd but opens a "save file" dialog box + * instead + * + * Results: + * Same as Tk_GetOpenFileCmd. + * + * Side effects: + * Same as Tk_GetOpenFileCmd. + * + *---------------------------------------------------------------------- + */ + +int +Tk_GetSaveFileCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + return GetFileName(clientData, interp, argc, argv, SAVE_FILE); +} + +/* + *---------------------------------------------------------------------- + * + * GetFileName -- + * + * Calls GetOpenFileName() or GetSaveFileName(). + * + * Results: + * See user documentation. + * + * Side effects: + * See user documentation. + * + *---------------------------------------------------------------------- + */ + +static int +GetFileName(clientData, interp, argc, argv, isOpen) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ + int isOpen; /* true if we should call GetOpenFileName(), + * false if we should call GetSaveFileName() */ +{ + OPENFILENAME openFileName, *ofnPtr; + int tclCode, winCode, oldMode; + OpenFileData *custData; + char buffer[MAX_PATH+1]; + + ofnPtr = &openFileName; + + /* + * 1. Parse the arguments. + */ + if (ParseFileDlgArgs(interp, ofnPtr, argc, argv, isOpen) != TCL_OK) { + return TCL_ERROR; + } + custData = (OpenFileData*) ofnPtr->lCustData; + + /* + * 2. Call the common dialog function. + */ + oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); + GetCurrentDirectory(MAX_PATH+1, buffer); + if (isOpen) { + winCode = GetOpenFileName(ofnPtr); + } else { + winCode = GetSaveFileName(ofnPtr); + } + SetCurrentDirectory(buffer); + (void) Tcl_SetServiceMode(oldMode); + + /* + * Clear the interp result since anything may have happened during the + * modal loop. + */ + + Tcl_ResetResult(interp); + + if (ofnPtr->lpstrInitialDir != NULL) { + ckfree((char*) ofnPtr->lpstrInitialDir); + } + + /* + * 3. Process the results. + */ + if (winCode) { + char *p; + Tcl_ResetResult(interp); + + for (p = custData->szFile; p && *p; p++) { + /* + * Change the pathname to the Tcl "normalized" pathname, where + * back slashes are used instead of forward slashes + */ + if (*p == '\\') { + *p = '/'; + } + } + Tcl_AppendResult(interp, custData->szFile, NULL); + tclCode = TCL_OK; + } else { + tclCode = ProcessCDError(interp, CommDlgExtendedError(), + ofnPtr->hwndOwner); + } + + if (custData) { + ckfree((char*)custData); + } + if (ofnPtr->lpstrFilter) { + ckfree((char*)ofnPtr->lpstrFilter); + } + + return tclCode; +} + +/* + *---------------------------------------------------------------------- + * + * ParseFileDlgArgs -- + * + * Parses the arguments passed to tk_getOpenFile and tk_getSaveFile. + * + * Results: + * A standard TCL return value. + * + * Side effects: + * The OPENFILENAME structure is initialized and modified according + * to the arguments. + * + *---------------------------------------------------------------------- + */ + +static int +ParseFileDlgArgs(interp, ofnPtr, argc, argv, isOpen) + Tcl_Interp * interp; /* Current interpreter. */ + OPENFILENAME *ofnPtr; /* Info about the file dialog */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ + int isOpen; /* true if we should call GetOpenFileName(), + * false if we should call GetSaveFileName() */ +{ + OpenFileData * custData; + int i; + Tk_Window parent = Tk_MainWindow(interp); + int doneFilter = 0; + int windowsMajorVersion; + Tcl_DString buffer; + + custData = (OpenFileData*)ckalloc(sizeof(OpenFileData)); + custData->interp = interp; + strcpy(custData->szFile, ""); + + /* Fill in the OPENFILENAME structure to */ + ofnPtr->lStructSize = sizeof(OPENFILENAME); + ofnPtr->hwndOwner = 0; /* filled in below */ + ofnPtr->lpstrFilter = NULL; + ofnPtr->lpstrCustomFilter = NULL; + ofnPtr->nMaxCustFilter = 0; + ofnPtr->nFilterIndex = 0; + ofnPtr->lpstrFile = custData->szFile; + ofnPtr->nMaxFile = sizeof(custData->szFile); + ofnPtr->lpstrFileTitle = NULL; + ofnPtr->nMaxFileTitle = 0; + ofnPtr->lpstrInitialDir = NULL; + ofnPtr->lpstrTitle = NULL; + ofnPtr->nFileOffset = 0; + ofnPtr->nFileExtension = 0; + ofnPtr->lpstrDefExt = NULL; + ofnPtr->lpfnHook = NULL; + ofnPtr->lCustData = (DWORD)custData; + ofnPtr->lpTemplateName = NULL; + ofnPtr->Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST; + + windowsMajorVersion = LOBYTE(LOWORD(GetVersion())); + if (windowsMajorVersion >= 4) { + /* + * Use the "explorer" style file selection box on platforms that + * support it (Win95 and NT4.0, both have a major version number + * of 4) + */ + ofnPtr->Flags |= OFN_EXPLORER; + } + + + if (isOpen) { + ofnPtr->Flags |= OFN_FILEMUSTEXIST; + } else { + ofnPtr->Flags |= OFN_OVERWRITEPROMPT; + } + + for (i=1; i<argc; i+=2) { + int v = i+1; + int len = strlen(argv[i]); + + if (strncmp(argv[i], "-defaultextension", len)==0) { + if (v==argc) {goto arg_missing;} + + ofnPtr->lpstrDefExt = argv[v]; + if (ofnPtr->lpstrDefExt[0] == '.') { + /* Windows will insert the dot for us */ + ofnPtr->lpstrDefExt ++; + } + } + else if (strncmp(argv[i], "-filetypes", len)==0) { + if (v==argc) {goto arg_missing;} + + if (MakeFilter(interp, ofnPtr, argv[v]) != TCL_OK) { + return TCL_ERROR; + } + doneFilter = 1; + } + else if (strncmp(argv[i], "-initialdir", len)==0) { + if (v==argc) {goto arg_missing;} + + if (Tcl_TranslateFileName(interp, argv[v], &buffer) == NULL) { + return TCL_ERROR; + } + ofnPtr->lpstrInitialDir = ckalloc(Tcl_DStringLength(&buffer)+1); + strcpy((char*)ofnPtr->lpstrInitialDir, Tcl_DStringValue(&buffer)); + Tcl_DStringFree(&buffer); + } + else if (strncmp(argv[i], "-initialfile", len)==0) { + if (v==argc) {goto arg_missing;} + + if (Tcl_TranslateFileName(interp, argv[v], &buffer) == NULL) { + return TCL_ERROR; + } + strcpy(ofnPtr->lpstrFile, Tcl_DStringValue(&buffer)); + Tcl_DStringFree(&buffer); + } + else if (strncmp(argv[i], "-parent", len)==0) { + if (v==argc) {goto arg_missing;} + + parent=Tk_NameToWindow(interp, argv[v], Tk_MainWindow(interp)); + if (parent == NULL) { + return TCL_ERROR; + } + } + else if (strncmp(argv[i], "-title", len)==0) { + if (v==argc) {goto arg_missing;} + + ofnPtr->lpstrTitle = argv[v]; + } + else { + Tcl_AppendResult(interp, "unknown option \"", + argv[i], "\", must be -defaultextension, ", + "-filetypes, -initialdir, -initialfile, -parent or -title", + NULL); + return TCL_ERROR; + } + } + + if (!doneFilter) { + if (MakeFilter(interp, ofnPtr, "") != TCL_OK) { + return TCL_ERROR; + } + } + + if (Tk_WindowId(parent) == None) { + Tk_MakeWindowExist(parent); + } + ofnPtr->hwndOwner = Tk_GetHWND(Tk_WindowId(parent)); + + return TCL_OK; + + arg_missing: + Tcl_AppendResult(interp, "value for \"", argv[argc-1], "\" missing", + NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * MakeFilter -- + * + * Allocate a buffer to store the filters in a format understood by + * Windows + * + * Results: + * A standard TCL return value. + * + * Side effects: + * ofnPtr->lpstrFilter is modified. + * + *---------------------------------------------------------------------- + */ +static int MakeFilter(interp, ofnPtr, string) + Tcl_Interp *interp; /* Current interpreter. */ + OPENFILENAME *ofnPtr; /* Info about the file dialog */ + char *string; /* String value of the -filetypes option */ +{ + char *filterStr; + char *p; + int pass; + FileFilterList flist; + FileFilter *filterPtr; + + TkInitFileFilters(&flist); + if (TkGetFileFilters(interp, &flist, string, 1) != TCL_OK) { + return TCL_ERROR; + } + + if (flist.filters == NULL) { + /* + * Use "All Files (*.*) as the default filter is none is specified + */ + char *defaultFilter = "All Files (*.*)"; + + p = filterStr = (char*)ckalloc(30 * sizeof(char)); + + strcpy(p, defaultFilter); + p+= strlen(defaultFilter); + + *p++ = '\0'; + *p++ = '*'; + *p++ = '.'; + *p++ = '*'; + *p++ = '\0'; + *p++ = '\0'; + *p = '\0'; + + } else { + /* We format the filetype into a string understood by Windows: + * {"Text Documents" {.doc .txt} {TEXT}} becomes + * "Text Documents (*.doc,*.txt)\0*.doc;*.txt\0" + * + * See the Windows OPENFILENAME manual page for details on the filter + * string format. + */ + + /* + * Since we may only add asterisks (*) to the filter, we need at most + * twice the size of the string to format the filter + */ + filterStr = ckalloc(strlen(string) * 3); + + for (filterPtr = flist.filters, p = filterStr; filterPtr; + filterPtr = filterPtr->next) { + char *sep; + FileFilterClause *clausePtr; + + /* + * First, put in the name of the file type + */ + strcpy(p, filterPtr->name); + p+= strlen(filterPtr->name); + *p++ = ' '; + *p++ = '('; + + for (pass = 1; pass <= 2; pass++) { + /* + * In the first pass, we format the extensions in the + * name field. In the second pass, we format the extensions in + * the filter pattern field + */ + sep = ""; + for (clausePtr=filterPtr->clauses;clausePtr; + clausePtr=clausePtr->next) { + GlobPattern *globPtr; + + + for (globPtr=clausePtr->patterns; globPtr; + globPtr=globPtr->next) { + strcpy(p, sep); + p+= strlen(sep); + strcpy(p, globPtr->pattern); + p+= strlen(globPtr->pattern); + + if (pass==1) { + sep = ","; + } else { + sep = ";"; + } + } + } + if (pass == 1) { + if (pass == 1) { + *p ++ = ')'; + } + } + *p ++ = '\0'; + } + } + + /* + * Windows requires the filter string to be ended by two NULL + * characters. + */ + *p++ = '\0'; + *p = '\0'; + } + + if (ofnPtr->lpstrFilter != NULL) { + ckfree((char*)ofnPtr->lpstrFilter); + } + ofnPtr->lpstrFilter = filterStr; + + TkFreeFileFilters(&flist); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_MessageBoxCmd -- + * + * This procedure implements the MessageBox window for the + * Windows platform. See the user documentation for details on what + * it does. + * + * Results: + * See user documentation. + * + * Side effects: + * None. The MessageBox window will be destroy before this procedure + * returns. + * + *---------------------------------------------------------------------- + */ + +int +Tk_MessageBoxCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + int flags; + Tk_Window parent = Tk_MainWindow(interp); + HWND hWnd; + char *message = ""; + char *title = ""; + int icon = MB_ICONINFORMATION; + int type = MB_OK; + int i, j; + char *result; + int code, oldMode; + char *defaultBtn = NULL; + int defaultBtnIdx = -1; + + for (i=1; i<argc; i+=2) { + int v = i+1; + int len = strlen(argv[i]); + + if (strncmp(argv[i], "-default", len)==0) { + if (v==argc) {goto arg_missing;} + + defaultBtn = argv[v]; + } + else if (strncmp(argv[i], "-icon", len)==0) { + if (v==argc) {goto arg_missing;} + + if (strcmp(argv[v], "error") == 0) { + icon = MB_ICONERROR; + } + else if (strcmp(argv[v], "info") == 0) { + icon = MB_ICONINFORMATION; + } + else if (strcmp(argv[v], "question") == 0) { + icon = MB_ICONQUESTION; + } + else if (strcmp(argv[v], "warning") == 0) { + icon = MB_ICONWARNING; + } + else { + Tcl_AppendResult(interp, "invalid icon \"", argv[v], + "\", must be error, info, question or warning", NULL); + return TCL_ERROR; + } + } + else if (strncmp(argv[i], "-message", len)==0) { + if (v==argc) {goto arg_missing;} + + message = argv[v]; + } + else if (strncmp(argv[i], "-parent", len)==0) { + if (v==argc) {goto arg_missing;} + + parent=Tk_NameToWindow(interp, argv[v], Tk_MainWindow(interp)); + if (parent == NULL) { + return TCL_ERROR; + } + } + else if (strncmp(argv[i], "-title", len)==0) { + if (v==argc) {goto arg_missing;} + + title = argv[v]; + } + else if (strncmp(argv[i], "-type", len)==0) { + int found = 0; + + if (v==argc) {goto arg_missing;} + + for (j=0; j<NUM_TYPES; j++) { + if (strcmp(argv[v], msgTypeInfo[j].name) == 0) { + type = msgTypeInfo[j].type; + found = 1; + break; + } + } + if (!found) { + Tcl_AppendResult(interp, "invalid message box type \"", + argv[v], "\", must be abortretryignore, ok, ", + "okcancel, retrycancel, yesno or yesnocancel", NULL); + return TCL_ERROR; + } + } + else { + Tcl_AppendResult(interp, "unknown option \"", + argv[i], "\", must be -default, -icon, ", + "-message, -parent, -title or -type", NULL); + return TCL_ERROR; + } + } + + /* Make sure we have a valid hWnd to act as the parent of this message box + */ + if (Tk_WindowId(parent) == None) { + Tk_MakeWindowExist(parent); + } + hWnd = Tk_GetHWND(Tk_WindowId(parent)); + + if (defaultBtn != NULL) { + for (i=0; i<NUM_TYPES; i++) { + if (type == msgTypeInfo[i].type) { + for (j=0; j<msgTypeInfo[i].numButtons; j++) { + if (strcmp(defaultBtn, msgTypeInfo[i].btnNames[j])==0) { + defaultBtnIdx = j; + break; + } + } + if (defaultBtnIdx < 0) { + Tcl_AppendResult(interp, "invalid default button \"", + defaultBtn, "\"", NULL); + return TCL_ERROR; + } + break; + } + } + + switch (defaultBtnIdx) { + case 0: flags = MB_DEFBUTTON1; break; + case 1: flags = MB_DEFBUTTON2; break; + case 2: flags = MB_DEFBUTTON3; break; + case 3: flags = MB_DEFBUTTON4; break; + } + } else { + flags = 0; + } + + flags |= icon | type; + oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); + code = MessageBox(hWnd, message, title, flags|MB_SYSTEMMODAL); + (void) Tcl_SetServiceMode(oldMode); + + switch (code) { + case IDABORT: result = "abort"; break; + case IDCANCEL: result = "cancel"; break; + case IDIGNORE: result = "ignore"; break; + case IDNO: result = "no"; break; + case IDOK: result = "ok"; break; + case IDRETRY: result = "retry"; break; + case IDYES: result = "yes"; break; + default: result = ""; + } + + /* + * When we come to here interp->result may have been changed by some + * background scripts. Call Tcl_SetResult() to make sure that any stuff + * lingering in interp->result will not appear in the result of + * this command. + */ + + Tcl_SetResult(interp, result, TCL_STATIC); + return TCL_OK; + + arg_missing: + Tcl_AppendResult(interp, "value for \"", argv[argc-1], "\" missing", + NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * ProcessCDError -- + * + * This procedure gets called if a Windows-specific error message + * has occurred during the execution of a common dialog or the + * user has pressed the CANCEL button. + * + * Results: + * If an error has indeed happened, returns a standard TCL result + * that reports the error code in string format. If the user has + * pressed the CANCEL button (dwErrorCode == 0), resets + * interp->result to the empty string. + * + * Side effects: + * interp->result is changed. + * + *---------------------------------------------------------------------- + */ +static int ProcessCDError(interp, dwErrorCode, hWnd) + Tcl_Interp * interp; /* Current interpreter. */ + DWORD dwErrorCode; /* The Windows-specific error code */ + HWND hWnd; /* window in which the error happened*/ +{ + char *string; + + Tcl_ResetResult(interp); + + switch(dwErrorCode) { + case 0: /* User has hit CANCEL */ + return TCL_OK; + + case CDERR_DIALOGFAILURE: string="CDERR_DIALOGFAILURE"; break; + case CDERR_STRUCTSIZE: string="CDERR_STRUCTSIZE"; break; + case CDERR_INITIALIZATION: string="CDERR_INITIALIZATION"; break; + case CDERR_NOTEMPLATE: string="CDERR_NOTEMPLATE"; break; + case CDERR_NOHINSTANCE: string="CDERR_NOHINSTANCE"; break; + case CDERR_LOADSTRFAILURE: string="CDERR_LOADSTRFAILURE"; break; + case CDERR_FINDRESFAILURE: string="CDERR_FINDRESFAILURE"; break; + case CDERR_LOADRESFAILURE: string="CDERR_LOADRESFAILURE"; break; + case CDERR_LOCKRESFAILURE: string="CDERR_LOCKRESFAILURE"; break; + case CDERR_MEMALLOCFAILURE: string="CDERR_MEMALLOCFAILURE"; break; + case CDERR_MEMLOCKFAILURE: string="CDERR_MEMLOCKFAILURE"; break; + case CDERR_NOHOOK: string="CDERR_NOHOOK"; break; + case PDERR_SETUPFAILURE: string="PDERR_SETUPFAILURE"; break; + case PDERR_PARSEFAILURE: string="PDERR_PARSEFAILURE"; break; + case PDERR_RETDEFFAILURE: string="PDERR_RETDEFFAILURE"; break; + case PDERR_LOADDRVFAILURE: string="PDERR_LOADDRVFAILURE"; break; + case PDERR_GETDEVMODEFAIL: string="PDERR_GETDEVMODEFAIL"; break; + case PDERR_INITFAILURE: string="PDERR_INITFAILURE"; break; + case PDERR_NODEVICES: string="PDERR_NODEVICES"; break; + case PDERR_NODEFAULTPRN: string="PDERR_NODEFAULTPRN"; break; + case PDERR_DNDMMISMATCH: string="PDERR_DNDMMISMATCH"; break; + case PDERR_CREATEICFAILURE: string="PDERR_CREATEICFAILURE"; break; + case PDERR_PRINTERNOTFOUND: string="PDERR_PRINTERNOTFOUND"; break; + case CFERR_NOFONTS: string="CFERR_NOFONTS"; break; + case FNERR_SUBCLASSFAILURE: string="FNERR_SUBCLASSFAILURE"; break; + case FNERR_INVALIDFILENAME: string="FNERR_INVALIDFILENAME"; break; + case FNERR_BUFFERTOOSMALL: string="FNERR_BUFFERTOOSMALL"; break; + + default: + string="unknown error"; + } + + Tcl_AppendResult(interp, "Win32 internal error: ", string, NULL); + return TCL_ERROR; +} diff --git a/win/tkWinDraw.c b/win/tkWinDraw.c new file mode 100644 index 0000000..e972365 --- /dev/null +++ b/win/tkWinDraw.c @@ -0,0 +1,1264 @@ +/* + * tkWinDraw.c -- + * + * This file contains the Xlib emulation functions pertaining to + * actually drawing objects on a window. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * Copyright (c) 1994 Software Research Associates, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinDraw.c 1.30 97/03/21 11:20:05 + */ + +#include "tkWinInt.h" + +/* + * These macros convert between X's bizarre angle units to radians. + */ + +#define PI 3.14159265358979 +#define XAngleToRadians(a) ((double)(a) / 64 * PI / 180); + +/* + * Translation table between X gc functions and Win32 raster op modes. + */ + +int tkpWinRopModes[] = { + R2_BLACK, /* GXclear */ + R2_MASKPEN, /* GXand */ + R2_MASKPENNOT, /* GXandReverse */ + R2_COPYPEN, /* GXcopy */ + R2_MASKNOTPEN, /* GXandInverted */ + R2_NOT, /* GXnoop */ + R2_XORPEN, /* GXxor */ + R2_MERGEPEN, /* GXor */ + R2_NOTMERGEPEN, /* GXnor */ + R2_NOTXORPEN, /* GXequiv */ + R2_NOT, /* GXinvert */ + R2_MERGEPENNOT, /* GXorReverse */ + R2_NOTCOPYPEN, /* GXcopyInverted */ + R2_MERGENOTPEN, /* GXorInverted */ + R2_NOTMASKPEN, /* GXnand */ + R2_WHITE /* GXset */ +}; + +/* + * Translation table between X gc functions and Win32 BitBlt op modes. Some + * of the operations defined in X don't have names, so we have to construct + * new opcodes for those functions. This is arcane and probably not all that + * useful, but at least it's accurate. + */ + +#define NOTSRCAND (DWORD)0x00220326 /* dest = (NOT source) AND dest */ +#define NOTSRCINVERT (DWORD)0x00990066 /* dest = (NOT source) XOR dest */ +#define SRCORREVERSE (DWORD)0x00DD0228 /* dest = source OR (NOT dest) */ +#define SRCNAND (DWORD)0x007700E6 /* dest = NOT (source AND dest) */ + +static int bltModes[] = { + BLACKNESS, /* GXclear */ + SRCAND, /* GXand */ + SRCERASE, /* GXandReverse */ + SRCCOPY, /* GXcopy */ + NOTSRCAND, /* GXandInverted */ + PATCOPY, /* GXnoop */ + SRCINVERT, /* GXxor */ + SRCPAINT, /* GXor */ + NOTSRCERASE, /* GXnor */ + NOTSRCINVERT, /* GXequiv */ + DSTINVERT, /* GXinvert */ + SRCORREVERSE, /* GXorReverse */ + NOTSRCCOPY, /* GXcopyInverted */ + MERGEPAINT, /* GXorInverted */ + SRCNAND, /* GXnand */ + WHITENESS /* GXset */ +}; + +/* + * The following raster op uses the source bitmap as a mask for the + * pattern. This is used to draw in a foreground color but leave the + * background color transparent. + */ + +#define MASKPAT 0x00E20746 /* dest = (src & pat) | (!src & dst) */ + +/* + * The following two raster ops are used to copy the foreground and background + * bits of a source pattern as defined by a stipple used as the pattern. + */ + +#define COPYFG 0x00CA0749 /* dest = (pat & src) | (!pat & dst) */ +#define COPYBG 0x00AC0744 /* dest = (!pat & src) | (pat & dst) */ + +/* + * Macros used later in the file. + */ + +#define MIN(a,b) ((a>b) ? b : a) +#define MAX(a,b) ((a<b) ? b : a) + +/* + * The followng typedef is used to pass Windows GDI drawing functions. + */ + +typedef BOOL (CALLBACK *WinDrawFunc) _ANSI_ARGS_((HDC dc, + CONST POINT* points, int npoints)); + +/* + * Forward declarations for procedures defined in this file: + */ + +static POINT * ConvertPoints _ANSI_ARGS_((XPoint *points, int npoints, + int mode, RECT *bbox)); +static void DrawOrFillArc _ANSI_ARGS_((Display *display, + Drawable d, GC gc, int x, int y, + unsigned int width, unsigned int height, + int start, int extent, int fill)); +static void RenderObject _ANSI_ARGS_((HDC dc, GC gc, + XPoint* points, int npoints, int mode, HPEN pen, + WinDrawFunc func)); + +/* + *---------------------------------------------------------------------- + * + * TkWinGetDrawableDC -- + * + * Retrieve the DC from a drawable. + * + * Results: + * Returns the window DC for windows. Returns a new memory DC + * for pixmaps. + * + * Side effects: + * Sets up the palette for the device context, and saves the old + * device context state in the passed in TkWinDCState structure. + * + *---------------------------------------------------------------------- + */ + +HDC +TkWinGetDrawableDC(display, d, state) + Display *display; + Drawable d; + TkWinDCState* state; +{ + HDC dc; + TkWinDrawable *twdPtr = (TkWinDrawable *)d; + Colormap cmap; + + if (twdPtr->type == TWD_WINDOW) { + TkWindow *winPtr = twdPtr->window.winPtr; + + dc = GetDC(twdPtr->window.handle); + if (winPtr == NULL) { + cmap = DefaultColormap(display, DefaultScreen(display)); + } else { + cmap = winPtr->atts.colormap; + } + } else if (twdPtr->type == TWD_WINDC) { + dc = twdPtr->winDC.hdc; + cmap = DefaultColormap(display, DefaultScreen(display)); + } else { + dc = CreateCompatibleDC(NULL); + SelectObject(dc, twdPtr->bitmap.handle); + cmap = twdPtr->bitmap.colormap; + } + state->palette = TkWinSelectPalette(dc, cmap); + return dc; +} + +/* + *---------------------------------------------------------------------- + * + * TkWinReleaseDrawableDC -- + * + * Frees the resources associated with a drawable's DC. + * + * Results: + * None. + * + * Side effects: + * Restores the old bitmap handle to the memory DC for pixmaps. + * + *---------------------------------------------------------------------- + */ + +void +TkWinReleaseDrawableDC(d, dc, state) + Drawable d; + HDC dc; + TkWinDCState *state; +{ + TkWinDrawable *twdPtr = (TkWinDrawable *)d; + SelectPalette(dc, state->palette, TRUE); + RealizePalette(dc); + if (twdPtr->type == TWD_WINDOW) { + ReleaseDC(TkWinGetHWND(d), dc); + } else if (twdPtr->type == TWD_BITMAP) { + DeleteDC(dc); + } +} + +/* + *---------------------------------------------------------------------- + * + * ConvertPoints -- + * + * Convert an array of X points to an array of Win32 points. + * + * Results: + * Returns the converted array of POINTs. + * + * Side effects: + * Allocates a block of memory that should not be freed. + * + *---------------------------------------------------------------------- + */ + +static POINT * +ConvertPoints(points, npoints, mode, bbox) + XPoint *points; + int npoints; + int mode; /* CoordModeOrigin or CoordModePrevious. */ + RECT *bbox; /* Bounding box of points. */ +{ + static POINT *winPoints = NULL; /* Array of points that is reused. */ + static int nWinPoints = -1; /* Current size of point array. */ + int i; + + /* + * To avoid paying the cost of a malloc on every drawing routine, + * we reuse the last array if it is large enough. + */ + + if (npoints > nWinPoints) { + if (winPoints != NULL) { + ckfree((char *) winPoints); + } + winPoints = (POINT *) ckalloc(sizeof(POINT) * npoints); + if (winPoints == NULL) { + nWinPoints = -1; + return NULL; + } + nWinPoints = npoints; + } + + bbox->left = bbox->right = points[0].x; + bbox->top = bbox->bottom = points[0].y; + + if (mode == CoordModeOrigin) { + for (i = 0; i < npoints; i++) { + winPoints[i].x = points[i].x; + winPoints[i].y = points[i].y; + bbox->left = MIN(bbox->left, winPoints[i].x); + bbox->right = MAX(bbox->right, winPoints[i].x); + bbox->top = MIN(bbox->top, winPoints[i].y); + bbox->bottom = MAX(bbox->bottom, winPoints[i].y); + } + } else { + winPoints[0].x = points[0].x; + winPoints[0].y = points[0].y; + for (i = 1; i < npoints; i++) { + winPoints[i].x = winPoints[i-1].x + points[i].x; + winPoints[i].y = winPoints[i-1].y + points[i].y; + bbox->left = MIN(bbox->left, winPoints[i].x); + bbox->right = MAX(bbox->right, winPoints[i].x); + bbox->top = MIN(bbox->top, winPoints[i].y); + bbox->bottom = MAX(bbox->bottom, winPoints[i].y); + } + } + return winPoints; +} + +/* + *---------------------------------------------------------------------- + * + * XCopyArea -- + * + * Copies data from one drawable to another using block transfer + * routines. + * + * Results: + * None. + * + * Side effects: + * Data is moved from a window or bitmap to a second window or + * bitmap. + * + *---------------------------------------------------------------------- + */ + +void +XCopyArea(display, src, dest, gc, src_x, src_y, width, height, dest_x, dest_y) + Display* display; + Drawable src; + Drawable dest; + GC gc; + int src_x, src_y; + unsigned int width, height; + int dest_x, dest_y; +{ + HDC srcDC, destDC; + TkWinDCState srcState, destState; + TkpClipMask *clipPtr = (TkpClipMask*)gc->clip_mask; + + srcDC = TkWinGetDrawableDC(display, src, &srcState); + + if (src != dest) { + destDC = TkWinGetDrawableDC(display, dest, &destState); + } else { + destDC = srcDC; + } + + if (clipPtr && clipPtr->type == TKP_CLIP_REGION) { + SelectClipRgn(destDC, (HRGN) clipPtr->value.region); + OffsetClipRgn(destDC, gc->clip_x_origin, gc->clip_y_origin); + } + + BitBlt(destDC, dest_x, dest_y, width, height, srcDC, src_x, src_y, + bltModes[gc->function]); + + SelectClipRgn(destDC, NULL); + + if (src != dest) { + TkWinReleaseDrawableDC(dest, destDC, &destState); + } + TkWinReleaseDrawableDC(src, srcDC, &srcState); +} + +/* + *---------------------------------------------------------------------- + * + * XCopyPlane -- + * + * Copies a bitmap from a source drawable to a destination + * drawable. The plane argument specifies which bit plane of + * the source contains the bitmap. Note that this implementation + * ignores the gc->function. + * + * Results: + * None. + * + * Side effects: + * Changes the destination drawable. + * + *---------------------------------------------------------------------- + */ + +void +XCopyPlane(display, src, dest, gc, src_x, src_y, width, height, dest_x, + dest_y, plane) + Display* display; + Drawable src; + Drawable dest; + GC gc; + int src_x, src_y; + unsigned int width, height; + int dest_x, dest_y; + unsigned long plane; +{ + HDC srcDC, destDC; + TkWinDCState srcState, destState; + HBRUSH bgBrush, fgBrush, oldBrush; + TkpClipMask *clipPtr = (TkpClipMask*)gc->clip_mask; + + display->request++; + + if (plane != 1) { + panic("Unexpected plane specified for XCopyPlane"); + } + + srcDC = TkWinGetDrawableDC(display, src, &srcState); + + if (src != dest) { + destDC = TkWinGetDrawableDC(display, dest, &destState); + } else { + destDC = srcDC; + } + + if (clipPtr == NULL || clipPtr->type == TKP_CLIP_REGION) { + + /* + * Case 1: opaque bitmaps. Windows handles the conversion + * from one bit to multiple bits by setting 0 to the + * foreground color, and 1 to the background color (seems + * backwards, but there you are). + */ + + if (clipPtr && clipPtr->type == TKP_CLIP_REGION) { + SelectClipRgn(destDC, (HRGN) clipPtr->value.region); + OffsetClipRgn(destDC, gc->clip_x_origin, gc->clip_y_origin); + } + + SetBkMode(destDC, OPAQUE); + SetBkColor(destDC, gc->foreground); + SetTextColor(destDC, gc->background); + BitBlt(destDC, dest_x, dest_y, width, height, srcDC, src_x, src_y, + SRCCOPY); + + SelectClipRgn(destDC, NULL); + } else if (clipPtr->type == TKP_CLIP_PIXMAP) { + if (clipPtr->value.pixmap == src) { + + /* + * Case 2: transparent bitmaps are handled by setting the + * destination to the foreground color whenever the source + * pixel is set. + */ + + fgBrush = CreateSolidBrush(gc->foreground); + oldBrush = SelectObject(destDC, fgBrush); + BitBlt(destDC, dest_x, dest_y, width, height, srcDC, src_x, src_y, + MASKPAT); + SelectObject(destDC, oldBrush); + DeleteObject(fgBrush); + } else { + + /* + * Case 3: two arbitrary bitmaps. Copy the source rectangle + * into a color pixmap. Use the result as a brush when + * copying the clip mask into the destination. + */ + + HDC memDC, maskDC; + HBITMAP bitmap; + TkWinDCState maskState; + + fgBrush = CreateSolidBrush(gc->foreground); + bgBrush = CreateSolidBrush(gc->background); + maskDC = TkWinGetDrawableDC(display, clipPtr->value.pixmap, + &maskState); + memDC = CreateCompatibleDC(destDC); + bitmap = CreateBitmap(width, height, 1, 1, NULL); + SelectObject(memDC, bitmap); + + /* + * Set foreground bits. We create a new bitmap containing + * (source AND mask), then use it to set the foreground color + * into the destination. + */ + + BitBlt(memDC, 0, 0, width, height, srcDC, src_x, src_y, SRCCOPY); + BitBlt(memDC, 0, 0, width, height, maskDC, + dest_x - gc->clip_x_origin, dest_y - gc->clip_y_origin, + SRCAND); + oldBrush = SelectObject(destDC, fgBrush); + BitBlt(destDC, dest_x, dest_y, width, height, memDC, 0, 0, + MASKPAT); + + /* + * Set background bits. Same as foreground, except we use + * ((NOT source) AND mask) and the background brush. + */ + + BitBlt(memDC, 0, 0, width, height, srcDC, src_x, src_y, + NOTSRCCOPY); + BitBlt(memDC, 0, 0, width, height, maskDC, + dest_x - gc->clip_x_origin, dest_y - gc->clip_y_origin, + SRCAND); + SelectObject(destDC, bgBrush); + BitBlt(destDC, dest_x, dest_y, width, height, memDC, 0, 0, + MASKPAT); + + TkWinReleaseDrawableDC(clipPtr->value.pixmap, maskDC, &maskState); + SelectObject(destDC, oldBrush); + DeleteDC(memDC); + DeleteObject(bitmap); + DeleteObject(fgBrush); + DeleteObject(bgBrush); + } + } + if (src != dest) { + TkWinReleaseDrawableDC(dest, destDC, &destState); + } + TkWinReleaseDrawableDC(src, srcDC, &srcState); +} + +/* + *---------------------------------------------------------------------- + * + * TkPutImage -- + * + * Copies a subimage from an in-memory image to a rectangle of + * of the specified drawable. + * + * Results: + * None. + * + * Side effects: + * Draws the image on the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +TkPutImage(colors, ncolors, display, d, gc, image, src_x, src_y, dest_x, + dest_y, width, height) + unsigned long *colors; /* Array of pixel values used by this + * image. May be NULL. */ + int ncolors; /* Number of colors used, or 0. */ + Display* display; + Drawable d; /* Destination drawable. */ + GC gc; + XImage* image; /* Source image. */ + int src_x, src_y; /* Offset of subimage. */ + int dest_x, dest_y; /* Position of subimage origin in + * drawable. */ + unsigned int width, height; /* Dimensions of subimage. */ +{ + HDC dc, dcMem; + TkWinDCState state; + BITMAPINFO *infoPtr; + HBITMAP bitmap; + char *data; + + display->request++; + + dc = TkWinGetDrawableDC(display, d, &state); + SetROP2(dc, tkpWinRopModes[gc->function]); + dcMem = CreateCompatibleDC(dc); + + if (image->bits_per_pixel == 1) { + /* + * If the image isn't in the right format, we have to copy + * it into a new buffer in MSBFirst and word-aligned format. + */ + + if ((image->bitmap_bit_order != MSBFirst) + || (image->bitmap_pad != sizeof(WORD))) { + data = TkAlignImageData(image, sizeof(WORD), MSBFirst); + bitmap = CreateBitmap(image->width, image->height, 1, 1, data); + ckfree(data); + } else { + bitmap = CreateBitmap(image->width, image->height, 1, 1, + image->data); + } + SetTextColor(dc, gc->foreground); + SetBkColor(dc, gc->background); + } else { + int i, usePalette; + + /* + * Do not use a palette for TrueColor images. + */ + + usePalette = (image->bits_per_pixel < 16); + + if (usePalette) { + infoPtr = (BITMAPINFO*) ckalloc(sizeof(BITMAPINFOHEADER) + + sizeof(RGBQUAD)*ncolors); + } else { + infoPtr = (BITMAPINFO*) ckalloc(sizeof(BITMAPINFOHEADER)); + } + + infoPtr->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + infoPtr->bmiHeader.biWidth = image->width; + + /* + * The following code works around a bug in Win32s. CreateDIBitmap + * fails under Win32s for top-down images. So we have to reverse the + * order of the scanlines. If we are not running under Win32s, we can + * just declare the image to be top-down. + */ + + if (tkpIsWin32s) { + int y; + char *srcPtr, *dstPtr, *temp; + + temp = ckalloc((unsigned) image->bytes_per_line); + srcPtr = image->data; + dstPtr = image->data+(image->bytes_per_line * (image->height - 1)); + for (y = 0; y < (image->height/2); y++) { + memcpy(temp, srcPtr, image->bytes_per_line); + memcpy(srcPtr, dstPtr, image->bytes_per_line); + memcpy(dstPtr, temp, image->bytes_per_line); + srcPtr += image->bytes_per_line; + dstPtr -= image->bytes_per_line; + } + ckfree(temp); + infoPtr->bmiHeader.biHeight = image->height; /* Bottom-up order */ + } else { + infoPtr->bmiHeader.biHeight = -image->height; /* Top-down order */ + } + infoPtr->bmiHeader.biPlanes = 1; + infoPtr->bmiHeader.biBitCount = image->bits_per_pixel; + infoPtr->bmiHeader.biCompression = BI_RGB; + infoPtr->bmiHeader.biSizeImage = 0; + infoPtr->bmiHeader.biXPelsPerMeter = 0; + infoPtr->bmiHeader.biYPelsPerMeter = 0; + infoPtr->bmiHeader.biClrImportant = 0; + + if (usePalette) { + infoPtr->bmiHeader.biClrUsed = ncolors; + for (i = 0; i < ncolors; i++) { + infoPtr->bmiColors[i].rgbBlue = GetBValue(colors[i]); + infoPtr->bmiColors[i].rgbGreen = GetGValue(colors[i]); + infoPtr->bmiColors[i].rgbRed = GetRValue(colors[i]); + infoPtr->bmiColors[i].rgbReserved = 0; + } + } else { + infoPtr->bmiHeader.biClrUsed = 0; + } + bitmap = CreateDIBitmap(dc, &infoPtr->bmiHeader, CBM_INIT, + image->data, infoPtr, DIB_RGB_COLORS); + ckfree((char *) infoPtr); + } + bitmap = SelectObject(dcMem, bitmap); + BitBlt(dc, dest_x, dest_y, width, height, dcMem, src_x, src_y, SRCCOPY); + DeleteObject(SelectObject(dcMem, bitmap)); + DeleteDC(dcMem); + TkWinReleaseDrawableDC(d, dc, &state); +} + +/* + *---------------------------------------------------------------------- + * + * XFillRectangles -- + * + * Fill multiple rectangular areas in the given drawable. + * + * Results: + * None. + * + * Side effects: + * Draws onto the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +XFillRectangles(display, d, gc, rectangles, nrectangles) + Display* display; + Drawable d; + GC gc; + XRectangle* rectangles; + int nrectangles; +{ + HDC dc; + int i; + RECT rect; + TkWinDCState state; + HBRUSH brush; + + if (d == None) { + return; + } + + dc = TkWinGetDrawableDC(display, d, &state); + SetROP2(dc, tkpWinRopModes[gc->function]); + brush = CreateSolidBrush(gc->foreground); + + if ((gc->fill_style == FillStippled + || gc->fill_style == FillOpaqueStippled) + && gc->stipple != None) { + TkWinDrawable *twdPtr = (TkWinDrawable *)gc->stipple; + HBRUSH oldBrush, stipple; + HBITMAP oldBitmap, bitmap; + HDC dcMem; + HBRUSH bgBrush = CreateSolidBrush(gc->background); + + if (twdPtr->type != TWD_BITMAP) { + panic("unexpected drawable type in stipple"); + } + + /* + * Select stipple pattern into destination dc. + */ + + stipple = CreatePatternBrush(twdPtr->bitmap.handle); + SetBrushOrgEx(dc, gc->ts_x_origin, gc->ts_y_origin, NULL); + oldBrush = SelectObject(dc, stipple); + dcMem = CreateCompatibleDC(dc); + + /* + * For each rectangle, create a drawing surface which is the size of + * the rectangle and fill it with the background color. Then merge the + * result with the stipple pattern. + */ + + for (i = 0; i < nrectangles; i++) { + bitmap = CreateCompatibleBitmap(dc, rectangles[i].width, + rectangles[i].height); + oldBitmap = SelectObject(dcMem, bitmap); + rect.left = 0; + rect.top = 0; + rect.right = rectangles[i].width; + rect.bottom = rectangles[i].height; + FillRect(dcMem, &rect, brush); + BitBlt(dc, rectangles[i].x, rectangles[i].y, rectangles[i].width, + rectangles[i].height, dcMem, 0, 0, COPYFG); + if (gc->fill_style == FillOpaqueStippled) { + FillRect(dcMem, &rect, bgBrush); + BitBlt(dc, rectangles[i].x, rectangles[i].y, + rectangles[i].width, rectangles[i].height, dcMem, + 0, 0, COPYBG); + } + SelectObject(dcMem, oldBitmap); + DeleteObject(bitmap); + } + + DeleteDC(dcMem); + SelectObject(dc, oldBrush); + DeleteObject(stipple); + DeleteObject(bgBrush); + } else { + for (i = 0; i < nrectangles; i++) { + TkWinFillRect(dc, rectangles[i].x, rectangles[i].y, + rectangles[i].width, rectangles[i].height, gc->foreground); + } + } + DeleteObject(brush); + TkWinReleaseDrawableDC(d, dc, &state); +} + +/* + *---------------------------------------------------------------------- + * + * RenderObject -- + * + * This function draws a shape using a list of points, a + * stipple pattern, and the specified drawing function. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +RenderObject(dc, gc, points, npoints, mode, pen, func) + HDC dc; + GC gc; + XPoint* points; + int npoints; + int mode; + HPEN pen; + WinDrawFunc func; +{ + RECT rect; + HPEN oldPen; + HBRUSH oldBrush; + POINT *winPoints = ConvertPoints(points, npoints, mode, &rect); + + if ((gc->fill_style == FillStippled + || gc->fill_style == FillOpaqueStippled) + && gc->stipple != None) { + + TkWinDrawable *twdPtr = (TkWinDrawable *)gc->stipple; + HDC dcMem; + LONG width, height; + HBITMAP oldBitmap; + int i; + HBRUSH oldMemBrush; + + if (twdPtr->type != TWD_BITMAP) { + panic("unexpected drawable type in stipple"); + } + + /* + * Grow the bounding box enough to account for wide lines. + */ + + if (gc->line_width > 1) { + rect.left -= gc->line_width; + rect.top -= gc->line_width; + rect.right += gc->line_width; + rect.bottom += gc->line_width; + } + + width = rect.right - rect.left; + height = rect.bottom - rect.top; + + /* + * Select stipple pattern into destination dc. + */ + + SetBrushOrgEx(dc, gc->ts_x_origin, gc->ts_y_origin, NULL); + oldBrush = SelectObject(dc, CreatePatternBrush(twdPtr->bitmap.handle)); + + /* + * Create temporary drawing surface containing a copy of the + * destination equal in size to the bounding box of the object. + */ + + dcMem = CreateCompatibleDC(dc); + oldBitmap = SelectObject(dcMem, CreateCompatibleBitmap(dc, width, + height)); + oldPen = SelectObject(dcMem, pen); + BitBlt(dcMem, 0, 0, width, height, dc, rect.left, rect.top, SRCCOPY); + + /* + * Translate the object for rendering in the temporary drawing + * surface. + */ + + for (i = 0; i < npoints; i++) { + winPoints[i].x -= rect.left; + winPoints[i].y -= rect.top; + } + + /* + * Draw the object in the foreground color and copy it to the + * destination wherever the pattern is set. + */ + + SetPolyFillMode(dcMem, (gc->fill_rule == EvenOddRule) ? ALTERNATE + : WINDING); + oldMemBrush = SelectObject(dcMem, CreateSolidBrush(gc->foreground)); + (*func)(dcMem, winPoints, npoints); + BitBlt(dc, rect.left, rect.top, width, height, dcMem, 0, 0, COPYFG); + + /* + * If we are rendering an opaque stipple, then draw the polygon in the + * background color and copy it to the destination wherever the pattern + * is clear. + */ + + if (gc->fill_style == FillOpaqueStippled) { + DeleteObject(SelectObject(dcMem, + CreateSolidBrush(gc->background))); + (*func)(dcMem, winPoints, npoints); + BitBlt(dc, rect.left, rect.top, width, height, dcMem, 0, 0, + COPYBG); + } + + SelectObject(dcMem, oldPen); + DeleteObject(SelectObject(dcMem, oldMemBrush)); + DeleteObject(SelectObject(dcMem, oldBitmap)); + DeleteDC(dcMem); + } else { + oldPen = SelectObject(dc, pen); + oldBrush = SelectObject(dc, CreateSolidBrush(gc->foreground)); + SetROP2(dc, tkpWinRopModes[gc->function]); + + SetPolyFillMode(dc, (gc->fill_rule == EvenOddRule) ? ALTERNATE + : WINDING); + + (*func)(dc, winPoints, npoints); + + SelectObject(dc, oldPen); + } + DeleteObject(SelectObject(dc, oldBrush)); +} + +/* + *---------------------------------------------------------------------- + * + * XDrawLines -- + * + * Draw connected lines. + * + * Results: + * None. + * + * Side effects: + * Renders a series of connected lines. + * + *---------------------------------------------------------------------- + */ + +void +XDrawLines(display, d, gc, points, npoints, mode) + Display* display; + Drawable d; + GC gc; + XPoint* points; + int npoints; + int mode; +{ + HPEN pen; + TkWinDCState state; + HDC dc; + + if (d == None) { + return; + } + + dc = TkWinGetDrawableDC(display, d, &state); + + if (!tkpIsWin32s && (gc->line_width > 1)) { + LOGBRUSH lb; + DWORD style; + + lb.lbStyle = BS_SOLID; + lb.lbColor = gc->foreground; + lb.lbHatch = 0; + + style = PS_GEOMETRIC|PS_COSMETIC; + switch (gc->cap_style) { + case CapNotLast: + case CapButt: + style |= PS_ENDCAP_FLAT; + break; + case CapRound: + style |= PS_ENDCAP_ROUND; + break; + default: + style |= PS_ENDCAP_SQUARE; + break; + } + switch (gc->join_style) { + case JoinMiter: + style |= PS_JOIN_MITER; + break; + case JoinRound: + style |= PS_JOIN_ROUND; + break; + default: + style |= PS_JOIN_BEVEL; + break; + } + pen = ExtCreatePen(style, gc->line_width, &lb, 0, NULL); + } else { + pen = CreatePen(PS_SOLID, gc->line_width, gc->foreground); + } + RenderObject(dc, gc, points, npoints, mode, pen, Polyline); + DeleteObject(pen); + + TkWinReleaseDrawableDC(d, dc, &state); +} + +/* + *---------------------------------------------------------------------- + * + * XFillPolygon -- + * + * Draws a filled polygon. + * + * Results: + * None. + * + * Side effects: + * Draws a filled polygon on the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +XFillPolygon(display, d, gc, points, npoints, shape, mode) + Display* display; + Drawable d; + GC gc; + XPoint* points; + int npoints; + int shape; + int mode; +{ + HPEN pen; + TkWinDCState state; + HDC dc; + + if (d == None) { + return; + } + + dc = TkWinGetDrawableDC(display, d, &state); + + pen = GetStockObject(NULL_PEN); + RenderObject(dc, gc, points, npoints, mode, pen, Polygon); + + TkWinReleaseDrawableDC(d, dc, &state); +} + +/* + *---------------------------------------------------------------------- + * + * XDrawRectangle -- + * + * Draws a rectangle. + * + * Results: + * None. + * + * Side effects: + * Draws a rectangle on the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +XDrawRectangle(display, d, gc, x, y, width, height) + Display* display; + Drawable d; + GC gc; + int x; + int y; + unsigned int width; + unsigned int height; +{ + HPEN pen, oldPen; + TkWinDCState state; + HBRUSH oldBrush; + HDC dc; + + if (d == None) { + return; + } + + dc = TkWinGetDrawableDC(display, d, &state); + + pen = CreatePen(PS_SOLID, gc->line_width, gc->foreground); + oldPen = SelectObject(dc, pen); + oldBrush = SelectObject(dc, GetStockObject(NULL_BRUSH)); + SetROP2(dc, tkpWinRopModes[gc->function]); + + Rectangle(dc, x, y, x+width+1, y+height+1); + + DeleteObject(SelectObject(dc, oldPen)); + SelectObject(dc, oldBrush); + TkWinReleaseDrawableDC(d, dc, &state); +} + +/* + *---------------------------------------------------------------------- + * + * XDrawArc -- + * + * Draw an arc. + * + * Results: + * None. + * + * Side effects: + * Draws an arc on the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +XDrawArc(display, d, gc, x, y, width, height, start, extent) + Display* display; + Drawable d; + GC gc; + int x; + int y; + unsigned int width; + unsigned int height; + int start; + int extent; +{ + display->request++; + + DrawOrFillArc(display, d, gc, x, y, width, height, start, extent, 0); +} + +/* + *---------------------------------------------------------------------- + * + * XFillArc -- + * + * Draw a filled arc. + * + * Results: + * None. + * + * Side effects: + * Draws a filled arc on the specified drawable. + * + *---------------------------------------------------------------------- + */ + +void +XFillArc(display, d, gc, x, y, width, height, start, extent) + Display* display; + Drawable d; + GC gc; + int x; + int y; + unsigned int width; + unsigned int height; + int start; + int extent; +{ + display->request++; + + DrawOrFillArc(display, d, gc, x, y, width, height, start, extent, 1); +} + +/* + *---------------------------------------------------------------------- + * + * DrawOrFillArc -- + * + * This procedure handles the rendering of drawn or filled + * arcs and chords. + * + * Results: + * None. + * + * Side effects: + * Renders the requested arc. + * + *---------------------------------------------------------------------- + */ + +static void +DrawOrFillArc(display, d, gc, x, y, width, height, start, extent, fill) + Display *display; + Drawable d; + GC gc; + int x, y; /* left top */ + unsigned int width, height; + int start; /* start: three-o'clock (deg*64) */ + int extent; /* extent: relative (deg*64) */ + int fill; /* ==0 draw, !=0 fill */ +{ + HDC dc; + HBRUSH brush, oldBrush; + HPEN pen, oldPen; + TkWinDCState state; + int clockwise = (extent < 0); /* non-zero if clockwise */ + int xstart, ystart, xend, yend; + double radian_start, radian_end, xr, yr; + + if (d == None) { + return; + } + + dc = TkWinGetDrawableDC(display, d, &state); + + SetROP2(dc, tkpWinRopModes[gc->function]); + + /* + * Compute the absolute starting and ending angles in normalized radians. + * Swap the start and end if drawing clockwise. + */ + + start = start % (64*360); + if (start < 0) { + start += (64*360); + } + extent = (start+extent) % (64*360); + if (extent < 0) { + extent += (64*360); + } + if (clockwise) { + int tmp = start; + start = extent; + extent = tmp; + } + radian_start = XAngleToRadians(start); + radian_end = XAngleToRadians(extent); + + /* + * Now compute points on the radial lines that define the starting and + * ending angles. Be sure to take into account that the y-coordinate + * system is inverted. + */ + + xr = x + width / 2.0; + yr = y + height / 2.0; + xstart = (int)((xr + cos(radian_start)*width/2.0) + 0.5); + ystart = (int)((yr + sin(-radian_start)*height/2.0) + 0.5); + xend = (int)((xr + cos(radian_end)*width/2.0) + 0.5); + yend = (int)((yr + sin(-radian_end)*height/2.0) + 0.5); + + /* + * Now draw a filled or open figure. Note that we have to + * increase the size of the bounding box by one to account for the + * difference in pixel definitions between X and Windows. + */ + + pen = CreatePen(PS_SOLID, gc->line_width, gc->foreground); + oldPen = SelectObject(dc, pen); + if (!fill) { + /* + * Note that this call will leave a gap of one pixel at the + * end of the arc for thin arcs. We can't use ArcTo because + * it's only supported under Windows NT. + */ + + Arc(dc, x, y, x+width+1, y+height+1, xstart, ystart, xend, yend); + } else { + brush = CreateSolidBrush(gc->foreground); + oldBrush = SelectObject(dc, brush); + if (gc->arc_mode == ArcChord) { + Chord(dc, x, y, x+width+1, y+height+1, xstart, ystart, xend, yend); + } else if ( gc->arc_mode == ArcPieSlice ) { + Pie(dc, x, y, x+width+1, y+height+1, xstart, ystart, xend, yend); + } + DeleteObject(SelectObject(dc, oldBrush)); + } + DeleteObject(SelectObject(dc, oldPen)); + TkWinReleaseDrawableDC(d, dc, &state); +} + +/* + *---------------------------------------------------------------------- + * + * TkScrollWindow -- + * + * Scroll a rectangle of the specified window and accumulate + * a damage region. + * + * Results: + * Returns 0 if the scroll genereated no additional damage. + * Otherwise, sets the region that needs to be repainted after + * scrolling and returns 1. + * + * Side effects: + * Scrolls the bits in the window. + * + *---------------------------------------------------------------------- + */ + +int +TkScrollWindow(tkwin, gc, x, y, width, height, dx, dy, damageRgn) + Tk_Window tkwin; /* The window to be scrolled. */ + GC gc; /* GC for window to be scrolled. */ + int x, y, width, height; /* Position rectangle to be scrolled. */ + int dx, dy; /* Distance rectangle should be moved. */ + TkRegion damageRgn; /* Region to accumulate damage in. */ +{ + HWND hwnd = TkWinGetHWND(Tk_WindowId(tkwin)); + RECT scrollRect; + + scrollRect.left = x; + scrollRect.top = y; + scrollRect.right = x + width; + scrollRect.bottom = y + height; + return (ScrollWindowEx(hwnd, dx, dy, &scrollRect, NULL, (HRGN) damageRgn, + NULL, 0) == NULLREGION) ? 0 : 1; +} + +/* + *---------------------------------------------------------------------- + * + * TkWinFillRect -- + * + * This routine fills a rectangle with the foreground color + * from the specified GC ignoring all other GC values. This + * is the fastest way to fill a drawable with a solid color. + * + * Results: + * None. + * + * Side effects: + * Modifies the contents of the DC drawing surface. + * + *---------------------------------------------------------------------- + */ + +void +TkWinFillRect(dc, x, y, width, height, pixel) + HDC dc; + int x, y, width, height; + int pixel; +{ + RECT rect; + COLORREF oldColor; + + rect.left = x; + rect.top = y; + rect.right = x + width; + rect.bottom = y + height; + oldColor = SetBkColor(dc, (COLORREF)pixel); + SetBkMode(dc, OPAQUE); + ExtTextOut(dc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL); + SetBkColor(dc, oldColor); +} diff --git a/win/tkWinEmbed.c b/win/tkWinEmbed.c new file mode 100644 index 0000000..0dc4036 --- /dev/null +++ b/win/tkWinEmbed.c @@ -0,0 +1,645 @@ +/* + * tkWinEmbed.c -- + * + * This file contains platform specific procedures for Windows platforms + * to provide basic operations needed for application embedding (where + * one application can use as its main window an internal window from + * another application). + * + * Copyright (c) 1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinEmbed.c 1.20 97/11/05 17:47:09; + */ + +#include "tkWinInt.h" + + +/* + * One of the following structures exists for each container in this + * application. It keeps track of the container window and its + * associated embedded window. + */ + +typedef struct Container { + HWND parentHWnd; /* Windows HWND to the parent window */ + TkWindow *parentPtr; /* Tk's information about the container + * or NULL if the container isn't + * in this process. */ + HWND embeddedHWnd; /* Windows HWND to the embedded window + */ + TkWindow *embeddedPtr; /* Tk's information about the embedded + * window, or NULL if the + * embedded application isn't in + * this process. */ + struct Container *nextPtr; /* Next in list of all containers in + * this process. */ +} Container; + +static Container *firstContainerPtr = NULL; + /* First in list of all containers + * managed by this process. */ + +static void CleanupContainerList _ANSI_ARGS_(( + ClientData clientData)); +static void ContainerEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void EmbeddedEventProc _ANSI_ARGS_(( + ClientData clientData, XEvent *eventPtr)); +static void EmbedGeometryRequest _ANSI_ARGS_(( + Container*containerPtr, int width, int height)); +static void EmbedWindowDeleted _ANSI_ARGS_((TkWindow *winPtr)); + +/* + *---------------------------------------------------------------------- + * + * CleanupContainerList -- + * + * Finalizes the list of containers. + * + * Results: + * None. + * + * Side effects: + * Releases memory occupied by containers of embedded windows. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +CleanupContainerList(clientData) + ClientData clientData; +{ + Container *nextPtr; + + for (; + firstContainerPtr != (Container *) NULL; + firstContainerPtr = nextPtr) { + nextPtr = firstContainerPtr->nextPtr; + ckfree((char *) firstContainerPtr); + } + firstContainerPtr = (Container *) NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TkpTestembedCmd -- + * + * Test command for the embedding facility. + * + * Results: + * Always returns TCL_OK. + * + * Side effects: + * Currently it does not do anything. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +TkpTestembedCmd(clientData, interp, argc, argv) + ClientData clientData; + Tcl_Interp *interp; + int argc; + char **argv; +{ + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpUseWindow -- + * + * This procedure causes a Tk window to use a given Windows handle + * for a window as its underlying window, rather than a new Windows + * window being created automatically. It is invoked by an embedded + * application to specify the window in which the application is + * embedded. + * + * Results: + * The return value is normally TCL_OK. If an error occurred (such as + * if the argument does not identify a legal Windows window handle), + * the return value is TCL_ERROR and an error message is left in the + * interp->result if interp is not NULL. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpUseWindow(interp, tkwin, string) + Tcl_Interp *interp; /* If not NULL, used for error reporting + * if string is bogus. */ + Tk_Window tkwin; /* Tk window that does not yet have an + * associated X window. */ + char *string; /* String identifying an X window to use + * for tkwin; must be an integer value. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + int id; + HWND hwnd; + Container *containerPtr; + + if (winPtr->window != None) { + panic("TkpUseWindow: Already assigned a window"); + } + + if (Tcl_GetInt(interp, string, &id) != TCL_OK) { + return TCL_ERROR; + } + hwnd = (HWND) id; + + /* + * Check if the window is a valid handle. If it is invalid, return + * TCL_ERROR and potentially leave an error message in interp->result. + */ + + if (!IsWindow(hwnd)) { + if (interp != (Tcl_Interp *) NULL) { + Tcl_AppendResult(interp, "window \"", string, + "\" doesn't exist", (char *) NULL); + } + return TCL_ERROR; + } + + /* + * Store the parent window in the platform private data slot so + * TkWmMapWindow can use it when creating the wrapper window. + */ + + winPtr->privatePtr = (struct TkWindowPrivate*) hwnd; + + /* + * Create an event handler to clean up the Container structure when + * tkwin is eventually deleted. + */ + + Tk_CreateEventHandler(tkwin, StructureNotifyMask, EmbeddedEventProc, + (ClientData) winPtr); + + /* + * If this is the first container, register an exit handler so that + * things will get cleaned up at finalization. + */ + + if (firstContainerPtr == (Container *) NULL) { + Tcl_CreateExitHandler(CleanupContainerList, (ClientData) NULL); + } + + /* + * Save information about the container and the embedded window + * in a Container structure. If there is already an existing + * Container structure, it means that both container and embedded + * app. are in the same process. + */ + + for (containerPtr = firstContainerPtr; containerPtr != NULL; + containerPtr = containerPtr->nextPtr) { + if (containerPtr->parentHWnd == hwnd) { + winPtr->flags |= TK_BOTH_HALVES; + containerPtr->parentPtr->flags |= TK_BOTH_HALVES; + break; + } + } + if (containerPtr == NULL) { + containerPtr = (Container *) ckalloc(sizeof(Container)); + containerPtr->parentPtr = NULL; + containerPtr->parentHWnd = hwnd; + containerPtr->nextPtr = firstContainerPtr; + firstContainerPtr = containerPtr; + } + + /* + * embeddedHWnd is not created yet. It will be created by TkWmMapWindow(), + * which will send a TK_ATTACHWINDOW to the container window. + * TkWinEmbeddedEventProc will process this message and set the embeddedHWnd + * variable + */ + + containerPtr->embeddedPtr = winPtr; + containerPtr->embeddedHWnd = NULL; + + winPtr->flags |= TK_EMBEDDED; + winPtr->flags &= (~(TK_MAPPED)); + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpMakeContainer -- + * + * This procedure is called to indicate that a particular window will + * be a container for an embedded application. This changes certain + * aspects of the window's behavior, such as whether it will receive + * events anymore. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpMakeContainer(tkwin) + Tk_Window tkwin; +{ + TkWindow *winPtr = (TkWindow *) tkwin; + Container *containerPtr; + + /* + * If this is the first container, register an exit handler so that + * things will get cleaned up at finalization. + */ + + if (firstContainerPtr == (Container *) NULL) { + Tcl_CreateExitHandler(CleanupContainerList, (ClientData) NULL); + } + + /* + * Register the window as a container so that, for example, we can + * find out later if the embedded app. is in the same process. + */ + + Tk_MakeWindowExist(tkwin); + containerPtr = (Container *) ckalloc(sizeof(Container)); + containerPtr->parentPtr = winPtr; + containerPtr->parentHWnd = Tk_GetHWND(Tk_WindowId(tkwin)); + containerPtr->embeddedHWnd = NULL; + containerPtr->embeddedPtr = NULL; + containerPtr->nextPtr = firstContainerPtr; + firstContainerPtr = containerPtr; + winPtr->flags |= TK_CONTAINER; + + /* + * Unlike in tkUnixEmbed.c, we don't make any requests for events + * in the embedded window here. Now we just allow the embedding + * of another TK application into TK windows. When the embedded + * window makes a request, that will be done by sending to the + * container window a WM_USER message, which will be intercepted + * by TkWinContainerProc. + * + * We need to get structure events of the container itself, though. + */ + + Tk_CreateEventHandler(tkwin, StructureNotifyMask, + ContainerEventProc, (ClientData) containerPtr); +} + +/* + *---------------------------------------------------------------------- + * + * EmbeddedEventProc -- + * + * This procedure is invoked by the Tk event dispatcher when various + * useful events are received for a window that is embedded in + * another application. + * + * Results: + * None. + * + * Side effects: + * Our internal state gets cleaned up when an embedded window is + * destroyed. + * + *---------------------------------------------------------------------- + */ + +static void +EmbeddedEventProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + TkWindow *winPtr = (TkWindow *) clientData; + + if (eventPtr->type == DestroyNotify) { + EmbedWindowDeleted(winPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWinEmbeddedEventProc -- + * + * This procedure is invoked by the Tk event dispatcher when + * various useful events are received for the *children* of a + * container window. It forwards relevant information, such as + * geometry requests, from the events into the container's + * application. + * + * Results: + * None. + * + * Side effects: + * Depends on the event. For example, when ConfigureRequest events + * occur, geometry information gets set for the container window. + * + *---------------------------------------------------------------------- + */ + +LRESULT +TkWinEmbeddedEventProc(hwnd, message, wParam, lParam) + HWND hwnd; + UINT message; + WPARAM wParam; + LPARAM lParam; +{ + Container *containerPtr; + + /* + * Find the Container structure associated with the parent window. + */ + + for (containerPtr = firstContainerPtr; + containerPtr->parentHWnd != hwnd; + containerPtr = containerPtr->nextPtr) { + if (containerPtr == NULL) { + panic("TkWinContainerProc couldn't find Container record"); + } + } + + switch (message) { + case TK_ATTACHWINDOW: + /* An embedded window (either from this application or from + * another application) is trying to attach to this container. + * We attach it only if this container is not yet containing any + * window. + */ + if (containerPtr->embeddedHWnd == NULL) { + containerPtr->embeddedHWnd = (HWND)wParam; + } else { + return 0; + } + + break; + case TK_GEOMETRYREQ: + EmbedGeometryRequest(containerPtr, wParam, lParam); + break; + } + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * EmbedGeometryRequest -- + * + * This procedure is invoked when an embedded application requests + * a particular size. It processes the request (which may or may + * not actually resize the window) and reflects the results back + * to the embedded application. + * + * Results: + * None. + * + * Side effects: + * If we deny the child's size change request, a Configure event + * is synthesized to let the child know that the size is the same + * as it used to be. Events get processed while we're waiting for + * the geometry managers to do their thing. + * + *---------------------------------------------------------------------- + */ + +void +EmbedGeometryRequest(containerPtr, width, height) + Container *containerPtr; /* Information about the container window. */ + int width, height; /* Size that the child has requested. */ +{ + TkWindow * winPtr = containerPtr->parentPtr; + + /* + * Forward the requested size into our geometry management hierarchy + * via the container window. We need to send a Configure event back + * to the embedded application even if we decide not to resize + * the window; to make this happen, process all idle event handlers + * synchronously here (so that the geometry managers have had a + * chance to do whatever they want to do), and if the window's size + * didn't change then generate a configure event. + */ + Tk_GeometryRequest((Tk_Window)winPtr, width, height); + + if (containerPtr->embeddedHWnd != NULL) { + while (Tcl_DoOneEvent(TCL_IDLE_EVENTS)) { + /* Empty loop body. */ + } + + SetWindowPos(containerPtr->embeddedHWnd, NULL, + 0, 0, winPtr->changes.width, winPtr->changes.height, SWP_NOZORDER); + } +} + +/* + *---------------------------------------------------------------------- + * + * ContainerEventProc -- + * + * This procedure is invoked by the Tk event dispatcher when + * various useful events are received for the container window. + * + * Results: + * None. + * + * Side effects: + * Depends on the event. For example, when ConfigureRequest events + * occur, geometry information gets set for the container window. + * + *---------------------------------------------------------------------- + */ + +static void +ContainerEventProc(clientData, eventPtr) + ClientData clientData; /* Token for container window. */ + XEvent *eventPtr; /* ResizeRequest event. */ +{ + Container *containerPtr = (Container *)clientData; + Tk_Window tkwin = (Tk_Window)containerPtr->parentPtr; + + if (eventPtr->type == ConfigureNotify) { + if (containerPtr->embeddedPtr == NULL) { + return; + } + /* Resize the embedded window, if there is any */ + if (containerPtr->embeddedHWnd) { + SetWindowPos(containerPtr->embeddedHWnd, NULL, + 0, 0, Tk_Width(tkwin), Tk_Height(tkwin), SWP_NOZORDER); + } + } else if (eventPtr->type == DestroyNotify) { + /* The container is gone, remove it from the list */ + EmbedWindowDeleted(containerPtr->parentPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetOtherWindow -- + * + * If both the container and embedded window are in the same + * process, this procedure will return either one, given the other. + * + * Results: + * If winPtr is a container, the return value is the token for the + * embedded window, and vice versa. If the "other" window isn't in + * this process, NULL is returned. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkpGetOtherWindow(winPtr) + TkWindow *winPtr; /* Tk's structure for a container or + * embedded window. */ +{ + Container *containerPtr; + + for (containerPtr = firstContainerPtr; containerPtr != NULL; + containerPtr = containerPtr->nextPtr) { + if (containerPtr->embeddedPtr == winPtr) { + return containerPtr->parentPtr; + } else if (containerPtr->parentPtr == winPtr) { + return containerPtr->embeddedPtr; + } + } + panic("TkpGetOtherWindow couldn't find window"); + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * TkpClaimFocus -- + * + * This procedure is invoked when someone asks or the input focus + * to be put on a window in an embedded application, but the + * application doesn't currently have the focus. It requests the + * input focus from the container application. + * + * Results: + * None. + * + * Side effects: + * The input focus may change. + * + *---------------------------------------------------------------------- + */ + +void +TkpClaimFocus(topLevelPtr, force) + TkWindow *topLevelPtr; /* Top-level window containing desired + * focus window; should be embedded. */ + int force; /* One means that the container should + * claim the focus if it doesn't + * currently have it. */ +{ + HWND hwnd = GetParent(Tk_GetHWND(topLevelPtr->window)); + SendMessage(hwnd, TK_CLAIMFOCUS, (WPARAM) force, 0); +} + +/* + *---------------------------------------------------------------------- + * + * TkpRedirectKeyEvent -- + * + * This procedure is invoked when a key press or release event + * arrives for an application that does not believe it owns the + * input focus. This can happen because of embedding; for example, + * X can send an event to an embedded application when the real + * focus window is in the container application and is an ancestor + * of the container. This procedure's job is to forward the event + * back to the application where it really belongs. + * + * Results: + * None. + * + * Side effects: + * The event may get sent to a different application. + * + *---------------------------------------------------------------------- + */ + +void +TkpRedirectKeyEvent(winPtr, eventPtr) + TkWindow *winPtr; /* Window to which the event was originally + * reported. */ + XEvent *eventPtr; /* X event to redirect (should be KeyPress + * or KeyRelease). */ +{ + /* not implemented */ +} + +/* + *---------------------------------------------------------------------- + * + * EmbedWindowDeleted -- + * + * This procedure is invoked when a window involved in embedding + * (as either the container or the embedded application) is + * destroyed. It cleans up the Container structure for the window. + * + * Results: + * None. + * + * Side effects: + * A Container structure may be freed. + * + *---------------------------------------------------------------------- + */ + +static void +EmbedWindowDeleted(winPtr) + TkWindow *winPtr; /* Tk's information about window that + * was deleted. */ +{ + Container *containerPtr, *prevPtr; + + /* + * Find the Container structure for this window work. Delete the + * information about the embedded application and free the container's + * record. + */ + + prevPtr = NULL; + containerPtr = firstContainerPtr; + while (1) { + if (containerPtr->embeddedPtr == winPtr) { + containerPtr->embeddedHWnd = NULL; + containerPtr->embeddedPtr = NULL; + break; + } + if (containerPtr->parentPtr == winPtr) { + containerPtr->parentPtr = NULL; + break; + } + prevPtr = containerPtr; + containerPtr = containerPtr->nextPtr; + if (containerPtr == NULL) { + panic("EmbedWindowDeleted couldn't find window"); + } + } + if ((containerPtr->embeddedPtr == NULL) + && (containerPtr->parentPtr == NULL)) { + if (prevPtr == NULL) { + firstContainerPtr = containerPtr->nextPtr; + } else { + prevPtr->nextPtr = containerPtr->nextPtr; + } + ckfree((char *) containerPtr); + } +} diff --git a/win/tkWinFont.c b/win/tkWinFont.c new file mode 100644 index 0000000..c1d5161 --- /dev/null +++ b/win/tkWinFont.c @@ -0,0 +1,643 @@ +/* + * tkWinFont.c -- + * + * Contains the Windows implementation of the platform-independant + * font package interface. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * Copyright (c) 1994 Software Research Associates, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinFont.c 1.20 97/05/14 15:45:30 + */ + +#include "tkWinInt.h" +#include "tkFont.h" + +/* + * The following structure represents Windows' implementation of a font. + */ + +typedef struct WinFont { + TkFont font; /* Stuff used by generic font package. Must + * be first in structure. */ + HFONT hFont; /* Windows information about font. */ + HWND hwnd; /* Toplevel window of application that owns + * this font, used for getting HDC. */ + int widths[256]; /* Widths of first 256 chars in this font. */ +} WinFont; + +/* + * The following structure is used as to map between the Tcl strings + * that represent the system fonts and the numbers used by Windows. + */ + +static TkStateMap systemMap[] = { + {ANSI_FIXED_FONT, "ansifixed"}, + {ANSI_VAR_FONT, "ansi"}, + {DEVICE_DEFAULT_FONT, "device"}, + {OEM_FIXED_FONT, "oemfixed"}, + {SYSTEM_FIXED_FONT, "systemfixed"}, + {SYSTEM_FONT, "system"}, + {-1, NULL} +}; + +#define ABS(x) (((x) < 0) ? -(x) : (x)) + +static TkFont * AllocFont _ANSI_ARGS_((TkFont *tkFontPtr, + Tk_Window tkwin, HFONT hFont)); +static char * GetProperty _ANSI_ARGS_((CONST TkFontAttributes *faPtr, + CONST char *option)); +static int CALLBACK WinFontFamilyEnumProc _ANSI_ARGS_((ENUMLOGFONT *elfPtr, + NEWTEXTMETRIC *ntmPtr, int fontType, + LPARAM lParam)); + + +/* + *--------------------------------------------------------------------------- + * + * TkpGetNativeFont -- + * + * Map a platform-specific native font name to a TkFont. + * + * Results: + * The return value is a pointer to a TkFont that represents the + * native font. If a native font by the given name could not be + * found, the return value is NULL. + * + * Every call to this procedure returns a new TkFont structure, + * even if the name has already been seen before. The caller should + * call TkpDeleteFont() when the font is no longer needed. + * + * The caller is responsible for initializing the memory associated + * with the generic TkFont when this function returns and releasing + * the contents of the generic TkFont before calling TkpDeleteFont(). + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +TkFont * +TkpGetNativeFont(tkwin, name) + Tk_Window tkwin; /* For display where font will be used. */ + CONST char *name; /* Platform-specific font name. */ +{ + int object; + HFONT hFont; + + object = TkFindStateNum(NULL, NULL, systemMap, name); + if (object < 0) { + return NULL; + } + hFont = GetStockObject(object); + if (hFont == NULL) { + panic("TkpGetNativeFont: can't allocate stock font"); + } + + return AllocFont(NULL, tkwin, hFont); +} + +/* + *--------------------------------------------------------------------------- + * + * TkpGetFontFromAttributes -- + * + * Given a desired set of attributes for a font, find a font with + * the closest matching attributes. + * + * Results: + * The return value is a pointer to a TkFont that represents the + * font with the desired attributes. If a font with the desired + * attributes could not be constructed, some other font will be + * substituted automatically. NULL is never returned. + * + * Every call to this procedure returns a new TkFont structure, + * even if the specified attributes have already been seen before. + * The caller should call TkpDeleteFont() to free the platform- + * specific data when the font is no longer needed. + * + * The caller is responsible for initializing the memory associated + * with the generic TkFont when this function returns and releasing + * the contents of the generic TkFont before calling TkpDeleteFont(). + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ +TkFont * +TkpGetFontFromAttributes(tkFontPtr, tkwin, faPtr) + TkFont *tkFontPtr; /* If non-NULL, store the information in + * this existing TkFont structure, rather than + * allocating a new structure to hold the + * font; the existing contents of the font + * will be released. If NULL, a new TkFont + * structure is allocated. */ + Tk_Window tkwin; /* For display where font will be used. */ + CONST TkFontAttributes *faPtr; /* Set of attributes to match. */ +{ + LOGFONT lf; + HFONT hFont; + Window window; + HWND hwnd; + HDC hdc; + + window = Tk_WindowId(((TkWindow *) tkwin)->mainPtr->winPtr); + hwnd = (window == None) ? NULL : TkWinGetHWND(window); + + hdc = GetDC(hwnd); + lf.lfHeight = -faPtr->pointsize; + if (lf.lfHeight < 0) { + lf.lfHeight = MulDiv(lf.lfHeight, + 254 * WidthOfScreen(Tk_Screen(tkwin)), + 720 * WidthMMOfScreen(Tk_Screen(tkwin))); + } + lf.lfWidth = 0; + lf.lfEscapement = 0; + lf.lfOrientation = 0; + lf.lfWeight = (faPtr->weight == TK_FW_NORMAL) ? FW_NORMAL : FW_BOLD; + lf.lfItalic = faPtr->slant; + lf.lfUnderline = faPtr->underline; + lf.lfStrikeOut = faPtr->overstrike; + lf.lfCharSet = DEFAULT_CHARSET; + lf.lfOutPrecision = OUT_DEFAULT_PRECIS; + lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; + lf.lfQuality = DEFAULT_QUALITY; + lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; + if (faPtr->family == NULL) { + lf.lfFaceName[0] = '\0'; + } else { + lstrcpyn(lf.lfFaceName, faPtr->family, sizeof(lf.lfFaceName)); + } + ReleaseDC(hwnd, hdc); + + /* + * Replace the standard X and Mac family names with the names that + * Windows likes. + */ + + if ((stricmp(lf.lfFaceName, "Times") == 0) + || (stricmp(lf.lfFaceName, "New York") == 0)) { + strcpy(lf.lfFaceName, "Times New Roman"); + } else if ((stricmp(lf.lfFaceName, "Courier") == 0) + || (stricmp(lf.lfFaceName, "Monaco") == 0)) { + strcpy(lf.lfFaceName, "Courier New"); + } else if ((stricmp(lf.lfFaceName, "Helvetica") == 0) + || (stricmp(lf.lfFaceName, "Geneva") == 0)) { + strcpy(lf.lfFaceName, "Arial"); + } + + hFont = CreateFontIndirect(&lf); + if (hFont == NULL) { + hFont = GetStockObject(SYSTEM_FONT); + if (hFont == NULL) { + panic("TkpGetFontFromAttributes: cannot get system font"); + } + } + return AllocFont(tkFontPtr, tkwin, hFont); +} + +/* + *--------------------------------------------------------------------------- + * + * TkpDeleteFont -- + * + * Called to release a font allocated by TkpGetNativeFont() or + * TkpGetFontFromAttributes(). The caller should have already + * released the fields of the TkFont that are used exclusively by + * the generic TkFont code. + * + * Results: + * None. + * + * Side effects: + * TkFont is deallocated. + * + *--------------------------------------------------------------------------- + */ + +void +TkpDeleteFont(tkFontPtr) + TkFont *tkFontPtr; /* Token of font to be deleted. */ +{ + WinFont *fontPtr; + + fontPtr = (WinFont *) tkFontPtr; + DeleteObject(fontPtr->hFont); + ckfree((char *) fontPtr); +} + +/* + *--------------------------------------------------------------------------- + * + * TkpGetFontFamilies, WinFontEnumFamilyProc -- + * + * Return information about the font families that are available + * on the display of the given window. + * + * Results: + * interp->result is modified to hold a list of all the available + * font families. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ + +void +TkpGetFontFamilies(interp, tkwin) + Tcl_Interp *interp; /* Interp to hold result. */ + Tk_Window tkwin; /* For display to query. */ +{ + Window window; + HWND hwnd; + HDC hdc; + + window = Tk_WindowId(tkwin); + hwnd = (window == (Window) NULL) ? NULL : TkWinGetHWND(window); + + hdc = GetDC(hwnd); + EnumFontFamilies(hdc, NULL, (FONTENUMPROC) WinFontFamilyEnumProc, + (LPARAM) interp); + ReleaseDC(hwnd, hdc); +} + +/* ARGSUSED */ + +static int CALLBACK +WinFontFamilyEnumProc(elfPtr, ntmPtr, fontType, lParam) + ENUMLOGFONT *elfPtr; /* Logical-font data. */ + NEWTEXTMETRIC *ntmPtr; /* Physical-font data (not used). */ + int fontType; /* Type of font (not used). */ + LPARAM lParam; /* Interp to hold result. */ +{ + Tcl_Interp *interp; + + interp = (Tcl_Interp *) lParam; + Tcl_AppendElement(interp, elfPtr->elfLogFont.lfFaceName); + return 1; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_MeasureChars -- + * + * Determine the number of characters from the string that will fit + * in the given horizontal span. The measurement is done under the + * assumption that Tk_DrawChars() will be used to actually display + * the characters. + * + * Results: + * The return value is the number of characters from source that + * fit into the span that extends from 0 to maxLength. *lengthPtr is + * filled with the x-coordinate of the right edge of the last + * character that did fit. + * + * Side effects: + * None. + * + *--------------------------------------------------------------------------- + */ +int +Tk_MeasureChars(tkfont, source, numChars, maxLength, flags, lengthPtr) + Tk_Font tkfont; /* Font in which characters will be drawn. */ + CONST char *source; /* Characters to be displayed. Need not be + * '\0' terminated. */ + int numChars; /* Maximum number of characters to consider + * from source string. */ + int maxLength; /* If > 0, maxLength specifies the longest + * permissible line length; don't consider any + * character that would cross this + * x-position. If <= 0, then line length is + * unbounded and the flags argument is + * ignored. */ + int flags; /* Various flag bits OR-ed together: + * TK_PARTIAL_OK means include the last char + * which only partially fit on this line. + * TK_WHOLE_WORDS means stop on a word + * boundary, if possible. + * TK_AT_LEAST_ONE means return at least one + * character even if no characters fit. */ + int *lengthPtr; /* Filled with x-location just after the + * terminating character. */ +{ + WinFont *fontPtr; + HDC hdc; + HFONT hFont; + int curX, curIdx; + + /* + * On the authority of the Gates Empire, Windows does not use kerning + * or fractional character widths when displaying text on the screen. + * So that means we can safely measure individual characters or spans + * of characters and add up the widths w/o any "off-by-one pixel" + * errors. + */ + + fontPtr = (WinFont *) tkfont; + + hdc = GetDC(fontPtr->hwnd); + hFont = SelectObject(hdc, fontPtr->hFont); + + if (numChars == 0) { + curX = 0; + curIdx = 0; + } else if (maxLength <= 0) { + SIZE size; + + GetTextExtentPoint(hdc, source, numChars, &size); + curX = size.cx; + curIdx = numChars; + } else { + int newX, termX, sawNonSpace; + CONST char *term, *end, *p; + int ch; + + ch = UCHAR(*source); + newX = curX = termX = 0; + + term = source; + end = source + numChars; + + sawNonSpace = !isspace(ch); + for (p = source; ; ) { + newX += fontPtr->widths[ch]; + if (newX > maxLength) { + break; + } + curX = newX; + p++; + if (p >= end) { + term = end; + termX = curX; + break; + } + + ch = UCHAR(*p); + if (isspace(ch)) { + if (sawNonSpace) { + term = p; + termX = curX; + sawNonSpace = 0; + } + } else { + sawNonSpace = 1; + } + } + + /* + * P points to the first character that doesn't fit in the desired + * span. Use the flags to figure out what to return. + */ + + if ((flags & TK_PARTIAL_OK) && (p < end) && (curX < maxLength)) { + /* + * Include the first character that didn't quite fit in the desired + * span. The width returned will include the width of that extra + * character. + */ + + curX = newX; + p++; + } + if ((flags & TK_AT_LEAST_ONE) && (term == source) && (p < end)) { + term = p; + termX = curX; + if (term == source) { + term++; + termX = newX; + } + } else if ((p >= end) || !(flags & TK_WHOLE_WORDS)) { + term = p; + termX = curX; + } + + curX = termX; + curIdx = term - source; + } + + SelectObject(hdc, hFont); + ReleaseDC(fontPtr->hwnd, hdc); + + *lengthPtr = curX; + return curIdx; +} + +/* + *--------------------------------------------------------------------------- + * + * Tk_DrawChars -- + * + * Draw a string of characters on the screen. + * + * Results: + * None. + * + * Side effects: + * Information gets drawn on the screen. + * + *--------------------------------------------------------------------------- + */ + +void +Tk_DrawChars(display, drawable, gc, tkfont, source, numChars, x, y) + Display *display; /* Display on which to draw. */ + Drawable drawable; /* Window or pixmap in which to draw. */ + GC gc; /* Graphics context for drawing characters. */ + Tk_Font tkfont; /* Font in which characters will be drawn; + * must be the same as font used in GC. */ + CONST char *source; /* Characters to be displayed. Need not be + * '\0' terminated. All Tk meta-characters + * (tabs, control characters, and newlines) + * should be stripped out of the string that + * is passed to this function. If they are + * not stripped out, they will be displayed as + * regular printing characters. */ + int numChars; /* Number of characters in string. */ + int x, y; /* Coordinates at which to place origin of + * string when drawing. */ +{ + HDC dc; + HFONT hFont; + TkWinDCState state; + WinFont *fontPtr; + + fontPtr = (WinFont *) gc->font; + display->request++; + + if (drawable == None) { + return; + } + + dc = TkWinGetDrawableDC(display, drawable, &state); + + SetROP2(dc, tkpWinRopModes[gc->function]); + + if ((gc->fill_style == FillStippled + || gc->fill_style == FillOpaqueStippled) + && gc->stipple != None) { + TkWinDrawable *twdPtr = (TkWinDrawable *)gc->stipple; + HBRUSH oldBrush, stipple; + HBITMAP oldBitmap, bitmap; + HDC dcMem; + TEXTMETRIC tm; + SIZE size; + + if (twdPtr->type != TWD_BITMAP) { + panic("unexpected drawable type in stipple"); + } + + /* + * Select stipple pattern into destination dc. + */ + + dcMem = CreateCompatibleDC(dc); + + stipple = CreatePatternBrush(twdPtr->bitmap.handle); + SetBrushOrgEx(dc, gc->ts_x_origin, gc->ts_y_origin, NULL); + oldBrush = SelectObject(dc, stipple); + + SetTextAlign(dcMem, TA_LEFT | TA_TOP); + SetTextColor(dcMem, gc->foreground); + SetBkMode(dcMem, TRANSPARENT); + SetBkColor(dcMem, RGB(0, 0, 0)); + + hFont = SelectObject(dcMem, fontPtr->hFont); + + /* + * Compute the bounding box and create a compatible bitmap. + */ + + GetTextExtentPoint(dcMem, source, numChars, &size); + GetTextMetrics(dcMem, &tm); + size.cx -= tm.tmOverhang; + bitmap = CreateCompatibleBitmap(dc, size.cx, size.cy); + oldBitmap = SelectObject(dcMem, bitmap); + + /* + * The following code is tricky because fonts are rendered in multiple + * colors. First we draw onto a black background and copy the white + * bits. Then we draw onto a white background and copy the black bits. + * Both the foreground and background bits of the font are ANDed with + * the stipple pattern as they are copied. + */ + + PatBlt(dcMem, 0, 0, size.cx, size.cy, BLACKNESS); + TextOut(dcMem, 0, 0, source, numChars); + BitBlt(dc, x, y - tm.tmAscent, size.cx, size.cy, dcMem, + 0, 0, 0xEA02E9); + PatBlt(dcMem, 0, 0, size.cx, size.cy, WHITENESS); + TextOut(dcMem, 0, 0, source, numChars); + BitBlt(dc, x, y - tm.tmAscent, size.cx, size.cy, dcMem, + 0, 0, 0x8A0E06); + + /* + * Destroy the temporary bitmap and restore the device context. + */ + + SelectObject(dcMem, hFont); + SelectObject(dcMem, oldBitmap); + DeleteObject(bitmap); + DeleteDC(dcMem); + SelectObject(dc, oldBrush); + DeleteObject(stipple); + } else { + SetTextAlign(dc, TA_LEFT | TA_BASELINE); + SetTextColor(dc, gc->foreground); + SetBkMode(dc, TRANSPARENT); + hFont = SelectObject(dc, fontPtr->hFont); + TextOut(dc, x, y, source, numChars); + SelectObject(dc, hFont); + } + TkWinReleaseDrawableDC(drawable, dc, &state); +} + +/* + *--------------------------------------------------------------------------- + * + * AllocFont -- + * + * Helper for TkpGetNativeFont() and TkpGetFontFromAttributes(). + * Allocates and intializes the memory for a new TkFont that + * wraps the platform-specific data. + * + * Results: + * Returns pointer to newly constructed TkFont. + * + * The caller is responsible for initializing the fields of the + * TkFont that are used exclusively by the generic TkFont code, and + * for releasing those fields before calling TkpDeleteFont(). + * + * Side effects: + * Memory allocated. + * + *--------------------------------------------------------------------------- + */ + +static TkFont * +AllocFont(tkFontPtr, tkwin, hFont) + TkFont *tkFontPtr; /* If non-NULL, store the information in + * this existing TkFont structure, rather than + * allocating a new structure to hold the + * font; the existing contents of the font + * will be released. If NULL, a new TkFont + * structure is allocated. */ + Tk_Window tkwin; /* For display where font will be used. */ + HFONT hFont; /* Windows information about font. */ +{ + HWND hwnd; + WinFont *fontPtr; + HDC hdc; + TEXTMETRIC tm; + Window window; + char buf[LF_FACESIZE]; + TkFontAttributes *faPtr; + + if (tkFontPtr != NULL) { + fontPtr = (WinFont *) tkFontPtr; + DeleteObject(fontPtr->hFont); + } else { + fontPtr = (WinFont *) ckalloc(sizeof(WinFont)); + } + + window = Tk_WindowId(((TkWindow *) tkwin)->mainPtr->winPtr); + hwnd = (window == None) ? NULL : TkWinGetHWND(window); + + hdc = GetDC(hwnd); + hFont = SelectObject(hdc, hFont); + GetTextFace(hdc, sizeof(buf), buf); + GetTextMetrics(hdc, &tm); + GetCharWidth(hdc, 0, 255, fontPtr->widths); + + fontPtr->font.fid = (Font) fontPtr; + + faPtr = &fontPtr->font.fa; + faPtr->family = Tk_GetUid(buf); + faPtr->pointsize = MulDiv(tm.tmHeight - tm.tmInternalLeading, + 720 * WidthMMOfScreen(Tk_Screen(tkwin)), + 254 * WidthOfScreen(Tk_Screen(tkwin))); + faPtr->weight = (tm.tmWeight > FW_MEDIUM) ? TK_FW_BOLD : TK_FW_NORMAL; + faPtr->slant = (tm.tmItalic != 0) ? TK_FS_ITALIC : TK_FS_ROMAN; + faPtr->underline = (tm.tmUnderlined != 0) ? 1 : 0; + faPtr->overstrike = (tm.tmStruckOut != 0) ? 1 : 0; + + fontPtr->font.fm.ascent = tm.tmAscent; + fontPtr->font.fm.descent = tm.tmDescent; + fontPtr->font.fm.maxWidth = tm.tmMaxCharWidth; + fontPtr->font.fm.fixed = !(tm.tmPitchAndFamily & TMPF_FIXED_PITCH); + + hFont = SelectObject(hdc, hFont); + ReleaseDC(hwnd, hdc); + + fontPtr->hFont = hFont; + fontPtr->hwnd = hwnd; + + return (TkFont *) fontPtr; +} + diff --git a/win/tkWinImage.c b/win/tkWinImage.c new file mode 100644 index 0000000..388a58a --- /dev/null +++ b/win/tkWinImage.c @@ -0,0 +1,329 @@ +/* + * tkWinImage.c -- + * + * This file contains routines for manipulation full-color images. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinImage.c 1.13 97/07/07 11:19:45 + */ + +#include "tkWinInt.h" + +static int DestroyImage _ANSI_ARGS_((XImage* data)); +static unsigned long ImageGetPixel _ANSI_ARGS_((XImage *image, int x, int y)); +static int PutPixel _ANSI_ARGS_((XImage *image, int x, int y, + unsigned long pixel)); + +/* + *---------------------------------------------------------------------- + * + * DestroyImage -- + * + * This is a trivial wrapper around ckfree to make it possible to + * pass ckfree as a pointer. + * + * Results: + * None. + * + * Side effects: + * Deallocates the image. + * + *---------------------------------------------------------------------- + */ + +int +DestroyImage(imagePtr) + XImage *imagePtr; /* image to free */ +{ + if (imagePtr) { + if (imagePtr->data) { + ckfree((char*)imagePtr->data); + } + ckfree((char*)imagePtr); + } + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * ImageGetPixel -- + * + * Get a single pixel from an image. + * + * Results: + * Returns the 32 bit pixel value. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +unsigned long +ImageGetPixel(image, x, y) + XImage *image; + int x, y; +{ + unsigned long pixel = 0; + unsigned char *srcPtr = &(image->data[(y * image->bytes_per_line) + + ((x * image->bits_per_pixel) / NBBY)]); + + switch (image->bits_per_pixel) { + case 32: + case 24: + pixel = RGB(srcPtr[2], srcPtr[1], srcPtr[0]); + break; + case 16: + pixel = RGB(((((WORD*)srcPtr)[0]) >> 7) & 0xf8, + ((((WORD*)srcPtr)[0]) >> 2) & 0xf8, + ((((WORD*)srcPtr)[0]) << 3) & 0xf8); + break; + case 8: + pixel = srcPtr[0]; + break; + case 4: + pixel = ((x%2) ? (*srcPtr) : ((*srcPtr) >> 4)) & 0x0f; + break; + case 1: + pixel = ((*srcPtr) & (0x80 >> (x%8))) ? 1 : 0; + break; + } + return pixel; +} + +/* + *---------------------------------------------------------------------- + * + * PutPixel -- + * + * Set a single pixel in an image. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +PutPixel(image, x, y, pixel) + XImage *image; + int x, y; + unsigned long pixel; +{ + unsigned char *destPtr = &(image->data[(y * image->bytes_per_line) + + ((x * image->bits_per_pixel) / NBBY)]); + + switch (image->bits_per_pixel) { + case 32: + /* + * Pixel is DWORD: 0x00BBGGRR + */ + + destPtr[3] = 0; + case 24: + /* + * Pixel is triplet: 0xBBGGRR. + */ + + destPtr[0] = (unsigned char) GetBValue(pixel); + destPtr[1] = (unsigned char) GetGValue(pixel); + destPtr[2] = (unsigned char) GetRValue(pixel); + break; + case 16: + /* + * Pixel is WORD: 5-5-5 (R-G-B) + */ + + (*(WORD*)destPtr) = + ((GetRValue(pixel) & 0xf8) << 7) + | ((GetGValue(pixel) & 0xf8) <<2) + | ((GetBValue(pixel) & 0xf8) >> 3); + break; + case 8: + /* + * Pixel is 8-bit index into color table. + */ + + (*destPtr) = (unsigned char) pixel; + break; + case 4: + /* + * Pixel is 4-bit index in MSBFirst order. + */ + if (x%2) { + (*destPtr) = (unsigned char) (((*destPtr) & 0xf0) + | (pixel & 0x0f)); + } else { + (*destPtr) = (unsigned char) (((*destPtr) & 0x0f) + | ((pixel << 4) & 0xf0)); + } + break; + case 1: { + /* + * Pixel is bit in MSBFirst order. + */ + + int mask = (0x80 >> (x%8)); + if (pixel) { + (*destPtr) |= mask; + } else { + (*destPtr) &= ~mask; + } + } + break; + } + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * XCreateImage -- + * + * Allocates storage for a new XImage. + * + * Results: + * Returns a newly allocated XImage. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +XImage * +XCreateImage(display, visual, depth, format, offset, data, width, height, + bitmap_pad, bytes_per_line) + Display* display; + Visual* visual; + unsigned int depth; + int format; + int offset; + char* data; + unsigned int width; + unsigned int height; + int bitmap_pad; + int bytes_per_line; +{ + XImage* imagePtr = (XImage *) ckalloc(sizeof(XImage)); + imagePtr->width = width; + imagePtr->height = height; + imagePtr->xoffset = offset; + imagePtr->format = format; + imagePtr->data = data; + imagePtr->byte_order = LSBFirst; + imagePtr->bitmap_unit = 8; + imagePtr->bitmap_bit_order = MSBFirst; + imagePtr->bitmap_pad = bitmap_pad; + imagePtr->bits_per_pixel = depth; + imagePtr->depth = depth; + + /* + * Under Windows, bitmap_pad must be on an LONG data-type boundary. + */ + +#define LONGBITS (sizeof(LONG) * 8) + + bitmap_pad = (bitmap_pad + LONGBITS - 1) / LONGBITS * LONGBITS; + + /* + * Round to the nearest bitmap_pad boundary. + */ + + if (bytes_per_line) { + imagePtr->bytes_per_line = bytes_per_line; + } else { + imagePtr->bytes_per_line = (((depth * width) + + (bitmap_pad - 1)) >> 3) & ~((bitmap_pad >> 3) - 1); + } + + imagePtr->red_mask = 0; + imagePtr->green_mask = 0; + imagePtr->blue_mask = 0; + + imagePtr->f.put_pixel = PutPixel; + imagePtr->f.get_pixel = ImageGetPixel; + imagePtr->f.destroy_image = DestroyImage; + imagePtr->f.create_image = NULL; + imagePtr->f.sub_image = NULL; + imagePtr->f.add_pixel = NULL; + + return imagePtr; +} + +/* + *---------------------------------------------------------------------- + * + * XGetImage -- + * + * This function copies data from a pixmap or window into an + * XImage. + * + * Results: + * Returns a newly allocated image containing the data from the + * given rectangle of the given drawable. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +XImage * +XGetImage(display, d, x, y, width, height, plane_mask, format) + Display* display; + Drawable d; + int x; + int y; + unsigned int width; + unsigned int height; + unsigned long plane_mask; + int format; +{ + TkWinDrawable *twdPtr = (TkWinDrawable *)d; + XImage *imagePtr; + HDC dc; + char infoBuf[sizeof(BITMAPINFO) + sizeof(RGBQUAD)]; + BITMAPINFO *infoPtr = (BITMAPINFO*)infoBuf; + + if ((twdPtr->type != TWD_BITMAP) || (twdPtr->bitmap.handle == NULL) + || (format != XYPixmap) || (plane_mask != 1)) { + panic("XGetImage: not implemented"); + } + + + imagePtr = XCreateImage(display, NULL, 1, XYBitmap, 0, NULL, + width, height, 32, 0); + imagePtr->data = ckalloc(imagePtr->bytes_per_line * imagePtr->height); + + dc = GetDC(NULL); + + GetDIBits(dc, twdPtr->bitmap.handle, 0, height, NULL, + infoPtr, DIB_RGB_COLORS); + + infoPtr->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + infoPtr->bmiHeader.biWidth = width; + infoPtr->bmiHeader.biHeight = -(LONG)height; + infoPtr->bmiHeader.biPlanes = 1; + infoPtr->bmiHeader.biBitCount = 1; + infoPtr->bmiHeader.biCompression = BI_RGB; + infoPtr->bmiHeader.biCompression = 0; + infoPtr->bmiHeader.biXPelsPerMeter = 0; + infoPtr->bmiHeader.biYPelsPerMeter = 0; + infoPtr->bmiHeader.biClrUsed = 0; + infoPtr->bmiHeader.biClrImportant = 0; + + GetDIBits(dc, twdPtr->bitmap.handle, 0, height, imagePtr->data, + infoPtr, DIB_RGB_COLORS); + ReleaseDC(NULL, dc); + + return imagePtr; +} diff --git a/win/tkWinInit.c b/win/tkWinInit.c new file mode 100644 index 0000000..400f693 --- /dev/null +++ b/win/tkWinInit.c @@ -0,0 +1,121 @@ +/* + * tkWinInit.c -- + * + * This file contains Windows-specific interpreter initialization + * functions. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinInit.c 1.29 97/07/24 14:46:35 + */ + +#include "tkWinInt.h" + +/* + * The Init script (common to Windows and Unix platforms) is + * defined in tkInitScript.h + */ +#include "tkInitScript.h" + + +/* + *---------------------------------------------------------------------- + * + * TkpInit -- + * + * Performs Windows-specific interpreter initialization related to the + * tk_library variable. + * + * Results: + * A standard Tcl completion code (TCL_OK or TCL_ERROR). Also + * leaves information in interp->result. + * + * Side effects: + * Sets "tk_library" Tcl variable, runs "tk.tcl" script. + * + *---------------------------------------------------------------------- + */ + +int +TkpInit(interp) + Tcl_Interp *interp; +{ + return Tcl_Eval(interp, initScript); +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetAppName -- + * + * Retrieves the name of the current application from a platform + * specific location. For Windows, the application name is the + * root of the tail of the path contained in the tcl variable argv0. + * + * Results: + * Returns the application name in the given Tcl_DString. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpGetAppName(interp, namePtr) + Tcl_Interp *interp; + Tcl_DString *namePtr; /* A previously initialized Tcl_DString. */ +{ + int argc; + char **argv = NULL, *name, *p; + + name = Tcl_GetVar(interp, "argv0", TCL_GLOBAL_ONLY); + if (name != NULL) { + Tcl_SplitPath(name, &argc, &argv); + if (argc > 0) { + name = argv[argc-1]; + p = strrchr(name, '.'); + if (p != NULL) { + *p = '\0'; + } + } else { + name = NULL; + } + } + if ((name == NULL) || (*name == 0)) { + name = "tk"; + } + Tcl_DStringAppend(namePtr, name, -1); + if (argv != NULL) { + ckfree((char *)argv); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpDisplayWarning -- + * + * This routines is called from Tk_Main to display warning + * messages that occur during startup. + * + * Results: + * None. + * + * Side effects: + * Displays a message box. + * + *---------------------------------------------------------------------- + */ + +void +TkpDisplayWarning(msg, title) + char *msg; /* Message to be displayed. */ + char *title; /* Title of warning. */ +{ + MessageBox(NULL, msg, title, MB_OK | MB_ICONEXCLAMATION | MB_SYSTEMMODAL + | MB_SETFOREGROUND | MB_TOPMOST); +} diff --git a/win/tkWinInt.h b/win/tkWinInt.h new file mode 100644 index 0000000..f3bca19 --- /dev/null +++ b/win/tkWinInt.h @@ -0,0 +1,194 @@ +/* + * tkWinInt.h -- + * + * This file contains declarations that are shared among the + * Windows-specific parts of Tk, but aren't used by the rest of + * Tk. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinInt.h 1.34 97/09/02 13:06:20 + */ + +#ifndef _TKWININT +#define _TKWININT + +#ifndef _TKINT +#include "tkInt.h" +#endif + +/* + * Include platform specific public interfaces. + */ + +#ifndef _TKWIN +#include "tkWin.h" +#endif + +/* + * Define constants missing from older Win32 SDK header files. + */ + +#ifndef WS_EX_TOOLWINDOW +#define WS_EX_TOOLWINDOW 0x00000080L +#endif + +typedef struct TkFontAttributes TkFontAttributes; + +/* + * The TkWinDCState is used to save the state of a device context + * so that it can be restored later. + */ + +typedef struct TkWinDCState { + HPALETTE palette; +} TkWinDCState; + +/* + * The TkWinDrawable is the internal implementation of an X Drawable (either + * a Window or a Pixmap). The following constants define the valid Drawable + * types. + */ + +#define TWD_BITMAP 1 +#define TWD_WINDOW 2 +#define TWD_WINDC 3 + +typedef struct { + int type; + HWND handle; + TkWindow *winPtr; +} TkWinWindow; + +typedef struct { + int type; + HBITMAP handle; + Colormap colormap; + int depth; +} TkWinBitmap; + +typedef struct { + int type; + HDC hdc; +}TkWinDC; + +typedef union { + int type; + TkWinWindow window; + TkWinBitmap bitmap; + TkWinDC winDC; +} TkWinDrawable; + +/* + * The following macros are used to retrieve internal values from a Drawable. + */ + +#define TkWinGetHWND(w) (((TkWinDrawable *) w)->window.handle) +#define TkWinGetWinPtr(w) (((TkWinDrawable*)w)->window.winPtr) +#define TkWinGetHBITMAP(w) (((TkWinDrawable*)w)->bitmap.handle) +#define TkWinGetColormap(w) (((TkWinDrawable*)w)->bitmap.colormap) +#define TkWinGetHDC(w) (((TkWinDrawable *) w)->winDC.hdc) + +/* + * The following structure is used to encapsulate palette information. + */ + +typedef struct { + HPALETTE palette; /* Palette handle used when drawing. */ + UINT size; /* Number of entries in the palette. */ + int stale; /* 1 if palette needs to be realized, + * otherwise 0. If the palette is stale, + * then an idle handler is scheduled to + * realize the palette. */ + Tcl_HashTable refCounts; /* Hash table of palette entry reference counts + * indexed by pixel value. */ +} TkWinColormap; + +/* + * The following macro retrieves the Win32 palette from a colormap. + */ + +#define TkWinGetPalette(colormap) (((TkWinColormap *) colormap)->palette) + +/* + * The following macros define the class names for Tk Window types. + */ + +#define TK_WIN_TOPLEVEL_CLASS_NAME "TkTopLevel" +#define TK_WIN_CHILD_CLASS_NAME "TkChild" + +/* + * The following variable indicates whether we are restricted to Win32s + * GDI calls. + */ + +extern int tkpIsWin32s; + +/* + * The following variable is a translation table between X gc functions and + * Win32 raster op modes. + */ + +extern int tkpWinRopModes[]; + +/* + * The following defines are used with TkWinGetBorderPixels to get the + * extra 2 border colors from a Tk_3DBorder. + */ + +#define TK_3D_LIGHT2 TK_3D_DARK_GC+1 +#define TK_3D_DARK2 TK_3D_DARK_GC+2 + +/* + * Internal procedures used by more than one source file. + */ + +extern LRESULT CALLBACK TkWinChildProc _ANSI_ARGS_((HWND hwnd, UINT message, + WPARAM wParam, LPARAM lParam)); +extern void TkWinClipboardRender _ANSI_ARGS_((TkDisplay *dispPtr, + UINT format)); +extern LRESULT TkWinEmbeddedEventProc _ANSI_ARGS_((HWND hwnd, + UINT message, WPARAM wParam, LPARAM lParam)); +extern void TkWinFillRect _ANSI_ARGS_((HDC dc, int x, int y, + int width, int height, int pixel)); +extern COLORREF TkWinGetBorderPixels _ANSI_ARGS_((Tk_Window tkwin, + Tk_3DBorder border, int which)); +extern HDC TkWinGetDrawableDC _ANSI_ARGS_((Display *display, + Drawable d, TkWinDCState* state)); +extern int TkWinGetModifierState _ANSI_ARGS_((void)); +extern HPALETTE TkWinGetSystemPalette _ANSI_ARGS_((void)); +extern HWND TkWinGetWrapperWindow _ANSI_ARGS_((Tk_Window tkwin)); +extern int TkWinHandleMenuEvent _ANSI_ARGS_((HWND *phwnd, + UINT *pMessage, WPARAM *pwParam, LPARAM *plParam, + LRESULT *plResult)); +extern int TkWinIndexOfColor _ANSI_ARGS_((XColor *colorPtr)); +extern void TkWinPointerDeadWindow _ANSI_ARGS_((TkWindow *winPtr)); +extern void TkWinPointerEvent _ANSI_ARGS_((HWND hwnd, int x, + int y)); +extern void TkWinPointerInit _ANSI_ARGS_((void)); +extern LRESULT TkWinReflectMessage _ANSI_ARGS_((HWND hwnd, + UINT message, WPARAM wParam, LPARAM lParam)); +extern void TkWinReleaseDrawableDC _ANSI_ARGS_((Drawable d, + HDC hdc, TkWinDCState* state)); +extern LRESULT TkWinResendEvent _ANSI_ARGS_((WNDPROC wndproc, + HWND hwnd, XEvent *eventPtr)); +extern HPALETTE TkWinSelectPalette _ANSI_ARGS_((HDC dc, + Colormap colormap)); +extern void TkWinSetMenu _ANSI_ARGS_((Tk_Window tkwin, + HMENU hMenu)); +extern void TkWinSetWindowPos _ANSI_ARGS_((HWND hwnd, + HWND siblingHwnd, int pos)); +extern void TkWinUpdateCursor _ANSI_ARGS_((TkWindow *winPtr)); +extern void TkWinWmCleanup _ANSI_ARGS_((HINSTANCE hInstance)); +extern HWND TkWinWmFindEmbedAssociation _ANSI_ARGS_(( + TkWindow *winPtr)); +extern void TkWinWmStoreEmbedAssociation _ANSI_ARGS_(( + TkWindow *winPtr, HWND hwnd)); +extern void TkWinXCleanup _ANSI_ARGS_((HINSTANCE hInstance)); +extern void TkWinXInit _ANSI_ARGS_((HINSTANCE hInstance)); + +#endif /* _TKWININT */ + diff --git a/win/tkWinKey.c b/win/tkWinKey.c new file mode 100644 index 0000000..3589143 --- /dev/null +++ b/win/tkWinKey.c @@ -0,0 +1,360 @@ +/* + * tkWinKey.c -- + * + * This file contains X emulation routines for keyboard related + * functions. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinKey.c 1.9 97/06/20 15:12:39 + */ + +#include "tkWinInt.h" + +typedef struct { + unsigned int keycode; + KeySym keysym; +} Keys; + +static Keys keymap[] = { + VK_CANCEL, XK_Cancel, + VK_BACK, XK_BackSpace, + VK_TAB, XK_Tab, + VK_CLEAR, XK_Clear, + VK_RETURN, XK_Return, + VK_SHIFT, XK_Shift_L, + VK_CONTROL, XK_Control_L, + VK_MENU, XK_Alt_L, + VK_PAUSE, XK_Pause, + VK_CAPITAL, XK_Caps_Lock, + VK_ESCAPE, XK_Escape, + VK_SPACE, XK_space, + VK_PRIOR, XK_Prior, + VK_NEXT, XK_Next, + VK_END, XK_End, + VK_HOME, XK_Home, + VK_LEFT, XK_Left, + VK_UP, XK_Up, + VK_RIGHT, XK_Right, + VK_DOWN, XK_Down, + VK_SELECT, XK_Select, + VK_PRINT, XK_Print, + VK_EXECUTE, XK_Execute, + VK_INSERT, XK_Insert, + VK_DELETE, XK_Delete, + VK_HELP, XK_Help, + VK_F1, XK_F1, + VK_F2, XK_F2, + VK_F3, XK_F3, + VK_F4, XK_F4, + VK_F5, XK_F5, + VK_F6, XK_F6, + VK_F7, XK_F7, + VK_F8, XK_F8, + VK_F9, XK_F9, + VK_F10, XK_F10, + VK_F11, XK_F11, + VK_F12, XK_F12, + VK_F13, XK_F13, + VK_F14, XK_F14, + VK_F15, XK_F15, + VK_F16, XK_F16, + VK_F17, XK_F17, + VK_F18, XK_F18, + VK_F19, XK_F19, + VK_F20, XK_F20, + VK_F21, XK_F21, + VK_F22, XK_F22, + VK_F23, XK_F23, + VK_F24, XK_F24, + VK_NUMLOCK, XK_Num_Lock, + VK_SCROLL, XK_Scroll_Lock, + 0, NoSymbol +}; + + +/* + *---------------------------------------------------------------------- + * + * XLookupString -- + * + * Retrieve the string equivalent for the given keyboard event. + * + * Results: + * Returns the number of characters stored in buffer_return. + * + * Side effects: + * Retrieves the characters stored in the event and inserts them + * into buffer_return. + * + *---------------------------------------------------------------------- + */ + +int +XLookupString(event_struct, buffer_return, bytes_buffer, keysym_return, + status_in_out) + XKeyEvent* event_struct; + char* buffer_return; + int bytes_buffer; + KeySym* keysym_return; + XComposeStatus* status_in_out; +{ + int i, limit; + + if (event_struct->send_event != -1) { + /* + * This is an event generated from generic code. It has no + * nchars or trans_chars members. + */ + + int index; + KeySym keysym; + + index = 0; + if (event_struct->state & ShiftMask) { + index |= 1; + } + if (event_struct->state & Mod1Mask) { + index |= 2; + } + keysym = XKeycodeToKeysym(event_struct->display, + event_struct->keycode, index); + if (((keysym != NoSymbol) && (keysym > 0) && (keysym < 256)) + || (keysym == XK_Return) + || (keysym == XK_Tab)) { + buffer_return[0] = (char) keysym; + return 1; + } + return 0; + } + if ((event_struct->nchars <= 0) || (buffer_return == NULL)) { + return 0; + } + limit = (event_struct->nchars < bytes_buffer) ? event_struct->nchars : + bytes_buffer; + + for (i = 0; i < limit; i++) { + buffer_return[i] = event_struct->trans_chars[i]; + } + + if (keysym_return != NULL) { + *keysym_return = NoSymbol; + } + return i; +} + +/* + *---------------------------------------------------------------------- + * + * XKeycodeToKeysym -- + * + * Translate from a system-dependent keycode to a + * system-independent keysym. + * + * Results: + * Returns the translated keysym, or NoSymbol on failure. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +KeySym +XKeycodeToKeysym(display, keycode, index) + Display* display; + unsigned int keycode; + int index; +{ + Keys* key; + BYTE keys[256]; + int result; + char buf[4]; + unsigned int scancode = MapVirtualKey(keycode, 0); + + memset(keys, 0, 256); + if (index & 0x02) { + keys[VK_NUMLOCK] = 1; + } + if (index & 0x01) { + keys[VK_SHIFT] = 0x80; + } + result = ToAscii(keycode, scancode, keys, (LPWORD) buf, 0); + + /* + * Keycode mapped to a valid Latin-1 character. Since the keysyms + * for alphanumeric characters map onto Latin-1, we just return it. + */ + + if (result == 1 && buf[0] >= 0x20) { + return (KeySym) buf[0]; + } + + /* + * Keycode is a non-alphanumeric key, so we have to do the lookup. + */ + + for (key = keymap; key->keycode != 0; key++) { + if (key->keycode == keycode) { + return key->keysym; + } + } + + return NoSymbol; +} + +/* + *---------------------------------------------------------------------- + * + * XKeysymToKeycode -- + * + * Translate a keysym back into a keycode. + * + * Results: + * Returns the keycode that would generate the specified keysym. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +KeyCode +XKeysymToKeycode(display, keysym) + Display* display; + KeySym keysym; +{ + Keys* key; + SHORT result; + + if (keysym >= 0x20) { + result = VkKeyScan((char) keysym); + if (result != -1) { + return (KeyCode) (result & 0xff); + } + } + + /* + * Couldn't map the character to a virtual keycode, so do a + * table lookup. + */ + + for (key = keymap; key->keycode != 0; key++) { + if (key->keysym == keysym) { + return key->keycode; + } + } + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * XGetModifierMapping -- + * + * Fetch the current keycodes used as modifiers. + * + * Results: + * Returns a new modifier map. + * + * Side effects: + * Allocates a new modifier map data structure. + * + *---------------------------------------------------------------------- + */ + +XModifierKeymap * +XGetModifierMapping(display) + Display* display; +{ + XModifierKeymap *map = (XModifierKeymap *)ckalloc(sizeof(XModifierKeymap)); + + map->max_keypermod = 1; + map->modifiermap = (KeyCode *) ckalloc(sizeof(KeyCode)*8); + map->modifiermap[ShiftMapIndex] = VK_SHIFT; + map->modifiermap[LockMapIndex] = VK_CAPITAL; + map->modifiermap[ControlMapIndex] = VK_CONTROL; + map->modifiermap[Mod1MapIndex] = VK_NUMLOCK; + map->modifiermap[Mod2MapIndex] = VK_MENU; + map->modifiermap[Mod3MapIndex] = VK_SCROLL; + map->modifiermap[Mod4MapIndex] = 0; + map->modifiermap[Mod5MapIndex] = 0; + return map; +} + +/* + *---------------------------------------------------------------------- + * + * XFreeModifiermap -- + * + * Deallocate a modifier map that was created by + * XGetModifierMapping. + * + * Results: + * None. + * + * Side effects: + * Frees the datastructure referenced by modmap. + * + *---------------------------------------------------------------------- + */ + +void +XFreeModifiermap(modmap) + XModifierKeymap* modmap; +{ + ckfree((char *) modmap->modifiermap); + ckfree((char *) modmap); +} + +/* + *---------------------------------------------------------------------- + * + * XStringToKeysym -- + * + * Translate a keysym name to the matching keysym. + * + * Results: + * Returns the keysym. Since this is already handled by + * Tk's StringToKeysym function, we just return NoSymbol. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +KeySym +XStringToKeysym(string) + _Xconst char *string; +{ + return NoSymbol; +} + +/* + *---------------------------------------------------------------------- + * + * XKeysymToString -- + * + * Convert a keysym to character form. + * + * Results: + * Returns NULL, since Tk will have handled this already. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +char * +XKeysymToString(keysym) + KeySym keysym; +{ + return NULL; +} + + diff --git a/win/tkWinMenu.c b/win/tkWinMenu.c new file mode 100644 index 0000000..00e24b7 --- /dev/null +++ b/win/tkWinMenu.c @@ -0,0 +1,2646 @@ +/* + * tkWinMenu.c -- + * + * This module implements the Mac-platform specific features of menus. + * + * Copyright (c) 1996-1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinMenu.c 1.102 97/10/28 13:56:58 + */ + +#define OEMRESOURCE +#include <string.h> +#include "tkMenu.h" +#include "tkWinInt.h" + +/* + * The class of the window for popup menus. + */ + +#define MENU_CLASS_NAME "MenuWindowClass" + +/* + * Used to align a windows bitmap inside a rectangle + */ + +#define ALIGN_BITMAP_LEFT 0x00000001 +#define ALIGN_BITMAP_RIGHT 0x00000002 +#define ALIGN_BITMAP_TOP 0x00000004 +#define ALIGN_BITMAP_BOTTOM 0x00000008 + +/* + * Platform-specific menu flags: + * + * MENU_SYSTEM_MENU Non-zero means that the Windows menu handle + * was retrieved with GetSystemMenu and needs + * to be disposed of specially. + * MENU_RECONFIGURE_PENDING + * Non-zero means that an idle handler has + * been set up to reconfigure the Windows menu + * handle for this menu. + */ + +#define MENU_SYSTEM_MENU MENU_PLATFORM_FLAG1 +#define MENU_RECONFIGURE_PENDING MENU_PLATFORM_FLAG2 + +static int indicatorDimensions[2]; + /* The dimensions of the indicator space + * in a menu entry. Calculated at init + * time to save time. */ +static Tcl_HashTable commandTable; + /* A map of command ids to menu entries */ +static int inPostMenu; /* We cannot be re-entrant like X Windows. */ +static WORD lastCommandID; /* The last command ID we allocated. */ +static HWND menuHWND; /* A window to service popup-menu messages + * in. */ +static int oldServiceMode; /* Used while processing a menu; we need + * to set the event mode specially when we + * enter the menu processing modal loop + * and reset it when menus go away. */ +static TkMenu *modalMenuPtr; /* The menu we are processing inside the modal + * loop. We need this to reset all of the + * active items when menus go away since + * Windows does not see fit to give this + * to us when it sends its WM_MENUSELECT. */ +static OSVERSIONINFO versionInfo; + /* So we don't have to keep doing this */ +static Tcl_HashTable winMenuTable; + /* Need this to map HMENUs back to menuPtrs */ + +/* + * The following are default menu value strings. + */ + +static char borderString[5]; /* The string indicating how big the border is */ +static Tcl_DString menuFontDString; + /* A buffer to store the default menu font + * string. */ + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void DrawMenuEntryAccelerator _ANSI_ARGS_(( + 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 _ANSI_ARGS_(( + TkMenu *menuPtr, TkMenuEntry *mePtr, + Drawable d, Tk_3DBorder activeBorder, + Tk_3DBorder bgBorder, int x, int y, + int width, int heigth)); +static void DrawMenuEntryIndicator _ANSI_ARGS_(( + 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 _ANSI_ARGS_(( + 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 _ANSI_ARGS_((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 _ANSI_ARGS_((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 DrawMenuUnderline _ANSI_ARGS_((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 DrawWindowsSystemBitmap _ANSI_ARGS_(( + Display *display, Drawable drawable, + GC gc, CONST RECT *rectPtr, int bitmapID, + int alignFlags)); +static void FreeID _ANSI_ARGS_((int commandID)); +static char * GetEntryText _ANSI_ARGS_((TkMenuEntry *mePtr)); +static void GetMenuAccelGeometry _ANSI_ARGS_((TkMenu *menuPtr, + TkMenuEntry *mePtr, Tk_Font tkfont, + CONST Tk_FontMetrics *fmPtr, int *widthPtr, + int *heightPtr)); +static void GetMenuLabelGeometry _ANSI_ARGS_((TkMenuEntry *mePtr, + Tk_Font tkfont, CONST Tk_FontMetrics *fmPtr, + int *widthPtr, int *heightPtr)); +static void GetMenuIndicatorGeometry _ANSI_ARGS_(( + TkMenu *menuPtr, TkMenuEntry *mePtr, + Tk_Font tkfont, CONST Tk_FontMetrics *fmPtr, + int *widthPtr, int *heightPtr)); +static void GetMenuSeparatorGeometry _ANSI_ARGS_(( + TkMenu *menuPtr, TkMenuEntry *mePtr, + Tk_Font tkfont, CONST Tk_FontMetrics *fmPtr, + int *widthPtr, int *heightPtr)); +static void GetTearoffEntryGeometry _ANSI_ARGS_((TkMenu *menuPtr, + TkMenuEntry *mePtr, Tk_Font tkfont, + CONST Tk_FontMetrics *fmPtr, int *widthPtr, + int *heightPtr)); +static int GetNewID _ANSI_ARGS_((TkMenuEntry *mePtr, + int *menuIDPtr)); +static void MenuExitProc _ANSI_ARGS_((ClientData clientData)); +static int MenuKeyBindProc _ANSI_ARGS_(( + ClientData clientData, + Tcl_Interp *interp, XEvent *eventPtr, + Tk_Window tkwin, KeySym keySym)); +static void MenuSelectEvent _ANSI_ARGS_((TkMenu *menuPtr)); +static void ReconfigureWindowsMenu _ANSI_ARGS_(( + ClientData clientData)); +static void RecursivelyClearActiveMenu _ANSI_ARGS_(( + TkMenu *menuPtr)); +static LRESULT CALLBACK TkWinMenuProc _ANSI_ARGS_((HWND hwnd, + UINT message, WPARAM wParam, + LPARAM lParam)); + + + +/* + *---------------------------------------------------------------------- + * + * GetNewID -- + * + * Allocates a new menu id and marks it in use. + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static int +GetNewID(mePtr, menuIDPtr) + TkMenuEntry *mePtr; /* The menu we are working with */ + int *menuIDPtr; /* The resulting id */ +{ + int found = 0; + int newEntry; + Tcl_HashEntry *commandEntryPtr; + WORD returnID; + + WORD curID = lastCommandID + 1; + + /* + * The following code relies on WORD wrapping when the highest value is + * incremented. + */ + + while (curID != lastCommandID) { + commandEntryPtr = Tcl_CreateHashEntry(&commandTable, + (char *) curID, &newEntry); + if (newEntry == 1) { + found = 1; + returnID = curID; + break; + } + curID++; + } + + if (found) { + Tcl_SetHashValue(commandEntryPtr, (char *) mePtr); + *menuIDPtr = (int) returnID; + lastCommandID = returnID; + return TCL_OK; + } else { + return TCL_ERROR; + } +} + +/* + *---------------------------------------------------------------------- + * + * FreeID -- + * + * Marks the itemID as free. + * + * Results: + * None. + * + * Side effects: + * The hash table entry for the ID is cleared. + * + *---------------------------------------------------------------------- + */ + +static void +FreeID(commandID) + int commandID; +{ + Tcl_HashEntry *entryPtr = Tcl_FindHashEntry(&commandTable, + (char *) commandID); + + if (entryPtr != NULL) { + Tcl_DeleteHashEntry(entryPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpNewMenu -- + * + * Gets a new blank menu. Only the platform specific options are filled + * in. + * + * Results: + * Standard TCL error. + * + * Side effects: + * Allocates a Windows menu handle and places it in the platformData + * field of the menuPtr. + * + *---------------------------------------------------------------------- + */ + +int +TkpNewMenu(menuPtr) + TkMenu *menuPtr; /* The common structure we are making the + * platform structure for. */ +{ + HMENU winMenuHdl; + Tcl_HashEntry *hashEntryPtr; + int newEntry; + + winMenuHdl = CreatePopupMenu(); + + if (winMenuHdl == NULL) { + Tcl_AppendResult(menuPtr->interp, "No more menus can be allocated.", + (char *) NULL); + return TCL_ERROR; + } + + /* + * We hash all of the HMENU's so that we can get their menu ptrs + * back when dispatch messages. + */ + + hashEntryPtr = Tcl_CreateHashEntry(&winMenuTable, (char *) winMenuHdl, + &newEntry); + Tcl_SetHashValue(hashEntryPtr, (char *) menuPtr); + + menuPtr->platformData = (TkMenuPlatformData) winMenuHdl; + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyMenu -- + * + * Destroys platform-specific menu structures. + * + * Results: + * None. + * + * Side effects: + * All platform-specific allocations are freed up. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyMenu(menuPtr) + TkMenu *menuPtr; /* The common menu structure */ +{ + HMENU winMenuHdl = (HMENU) menuPtr->platformData; + + if (menuPtr->menuFlags & MENU_RECONFIGURE_PENDING) { + Tcl_CancelIdleCall(ReconfigureWindowsMenu, (ClientData) menuPtr); + } + + if (NULL != winMenuHdl) { + if (menuPtr->menuFlags & MENU_SYSTEM_MENU) { + TkMenuEntry *searchEntryPtr; + Tcl_HashTable *tablePtr = TkGetMenuHashTable(menuPtr->interp); + char *menuName = Tcl_GetHashKey(tablePtr, + menuPtr->menuRefPtr->hashEntryPtr); + + for (searchEntryPtr = menuPtr->menuRefPtr->parentEntryPtr; + searchEntryPtr != NULL; + searchEntryPtr = searchEntryPtr->nextCascadePtr) { + if (strcmp(searchEntryPtr->name, + menuName) == 0) { + Tk_Window parentTopLevelPtr = searchEntryPtr + ->menuPtr->parentTopLevelPtr; + + if (parentTopLevelPtr != NULL) { + GetSystemMenu(TkWinGetWrapperWindow(parentTopLevelPtr), + TRUE); + } + break; + } + } + } else { + DestroyMenu(winMenuHdl); + } + menuPtr->platformData = NULL; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyMenuEntry -- + * + * Cleans up platform-specific menu entry items. + * + * Results: + * None + * + * Side effects: + * All platform-specific allocations are freed up. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyMenuEntry(mePtr) + TkMenuEntry *mePtr; /* The entry to destroy */ +{ + TkMenu *menuPtr = mePtr->menuPtr; + HMENU winMenuHdl = (HMENU) menuPtr->platformData; + + if (NULL != winMenuHdl) { + if (!(menuPtr->menuFlags & MENU_RECONFIGURE_PENDING)) { + menuPtr->menuFlags |= MENU_RECONFIGURE_PENDING; + Tcl_DoWhenIdle(ReconfigureWindowsMenu, (ClientData) menuPtr); + } + } + FreeID((int) mePtr->platformEntryData); + mePtr->platformEntryData = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * 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. Allocates the memory with alloc. The caller + * should free the memory. + * + * Results: + * itemText points to the new text for the item. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static char * +GetEntryText(mePtr) + TkMenuEntry *mePtr; /* A pointer to the menu entry. */ +{ + char *itemText; + + if (mePtr->type == TEAROFF_ENTRY) { + itemText = ckalloc(sizeof("(Tear-off)")); + strcpy(itemText, "(Tear-off)"); + } else if (mePtr->imageString != NULL) { + itemText = ckalloc(sizeof("(Image)")); + strcpy(itemText, "(Image)"); + } else if (mePtr->bitmap != None) { + itemText = ckalloc(sizeof("(Pixmap)")); + strcpy(itemText, "(Pixmap)"); + } else if (mePtr->label == NULL || mePtr->labelLength == 0) { + itemText = ckalloc(sizeof("( )")); + strcpy(itemText, "( )"); + } else { + int size = mePtr->labelLength + 1; + int i, j; + + /* + * We have to construct the string with an ampersand + * preceeding the underline character, and a tab seperating + * the text and the accel text. We have to be careful with + * ampersands in the string. + */ + + for (i = 0; i < mePtr->labelLength; i++) { + if (mePtr->label[i] == '&') { + size++; + } + } + + if (mePtr->underline >= 0) { + size++; + if (mePtr->label[mePtr->underline] == '&') { + size++; + } + } + + if (mePtr->accelLength > 0) { + size += mePtr->accelLength + 1; + } + + for (i = 0; i < mePtr->accelLength; i++) { + if (mePtr->accel[i] == '&') { + size++; + } + } + + itemText = ckalloc(size); + + if (mePtr->labelLength == 0) { + itemText[0] = 0; + } else { + for (i = 0, j = 0; i < mePtr->labelLength; i++, j++) { + if (mePtr->label[i] == '&') { + itemText[j++] = '&'; + } + if (i == mePtr->underline) { + itemText[j++] = '&'; + } + itemText[j] = mePtr->label[i]; + } + itemText[j] = '\0'; + } + + if (mePtr->accelLength > 0) { + strcat(itemText, "\t"); + for (i = 0, j = strlen(itemText); i < mePtr->accelLength; + i++, j++) { + if (mePtr->accel[i] == '&') { + itemText[j++] = '&'; + } + itemText[j] = mePtr->accel[i]; + } + itemText[j] = '\0'; + } + } + return itemText; +} + +/* + *---------------------------------------------------------------------- + * + * ReconfigureWindowsMenu -- + * + * Tears down and rebuilds the platform-specific part of this menu. + * + * Results: + * None. + * + * Side effects: + * Configuration information get set for mePtr; old resources + * get freed, if any need it. + * + *---------------------------------------------------------------------- + */ + +static void +ReconfigureWindowsMenu( + ClientData clientData) /* The menu we are rebuilding */ +{ + TkMenu *menuPtr = (TkMenu *) clientData; + TkMenuEntry *mePtr; + HMENU winMenuHdl = (HMENU) menuPtr->platformData; + char *itemText = NULL; + LPCTSTR lpNewItem; + UINT flags; + UINT itemID; + int i, count, systemMenu = 0, base; + int width, height; + + if (NULL == winMenuHdl) { + return; + } + + /* + * Reconstruct the entire menu. Takes care of nasty system menu and index + * problem. + * + */ + + if ((menuPtr->menuType == MENUBAR) + && (menuPtr->parentTopLevelPtr != NULL)) { + width = Tk_Width(menuPtr->parentTopLevelPtr); + height = Tk_Width(menuPtr->parentTopLevelPtr); + } + + base = (menuPtr->menuFlags & MENU_SYSTEM_MENU) ? 7 : 0; + count = GetMenuItemCount(winMenuHdl); + for (i = base; i < count; i++) { + RemoveMenu(winMenuHdl, base, MF_BYPOSITION); + } + + count = menuPtr->numEntries; + for (i = 0; i < count; i++) { + mePtr = menuPtr->entries[i]; + lpNewItem = NULL; + flags = MF_BYPOSITION; + itemID = 0; + + if ((menuPtr->menuType == MENUBAR) && (mePtr->type == TEAROFF_ENTRY)) { + continue; + } + + if (mePtr->type == SEPARATOR_ENTRY) { + flags |= MF_SEPARATOR; + } else { + itemText = GetEntryText(mePtr); + if ((menuPtr->menuType == MENUBAR) + || (menuPtr->menuFlags & MENU_SYSTEM_MENU)) { + lpNewItem = itemText; + } else { + lpNewItem = (LPCTSTR) mePtr; + flags |= MF_OWNERDRAW; + } + + /* + * Set enabling and disabling correctly. + */ + + if (mePtr->state == tkDisabledUid) { + flags |= MF_DISABLED; + } + + /* + * Set the check mark for check entries and radio entries. + */ + + if (((mePtr->type == CHECK_BUTTON_ENTRY) + || (mePtr->type == RADIO_BUTTON_ENTRY)) + && (mePtr->entryFlags & ENTRY_SELECTED)) { + flags |= MF_CHECKED; + } + + if (mePtr->columnBreak) { + flags |= MF_MENUBREAK; + } + + itemID = (int) mePtr->platformEntryData; + if (mePtr->type == CASCADE_ENTRY) { + if ((mePtr->childMenuRefPtr != NULL) + && (mePtr->childMenuRefPtr->menuPtr != NULL)) { + HMENU childMenuHdl = + (HMENU) mePtr->childMenuRefPtr->menuPtr + ->platformData; + if (childMenuHdl != NULL) { + itemID = (UINT) childMenuHdl; + flags |= MF_POPUP; + } + if ((menuPtr->menuType == MENUBAR) + && !(mePtr->childMenuRefPtr->menuPtr->menuFlags + & MENU_SYSTEM_MENU)) { + TkMenuReferences *menuRefPtr; + TkMenu *systemMenuPtr = mePtr->childMenuRefPtr + ->menuPtr; + char *systemMenuName = ckalloc(strlen( + Tk_PathName(menuPtr->masterMenuPtr->tkwin)) + + strlen(".system") + 1); + + strcpy(systemMenuName, + Tk_PathName(menuPtr->masterMenuPtr->tkwin)); + strcat(systemMenuName, ".system"); + menuRefPtr = TkFindMenuReferences(menuPtr->interp, + systemMenuName); + if ((menuRefPtr != NULL) + && (menuRefPtr->menuPtr != NULL) + && (menuPtr->parentTopLevelPtr != NULL) + && (systemMenuPtr->masterMenuPtr + == menuRefPtr->menuPtr)) { + HMENU systemMenuHdl = + (HMENU) systemMenuPtr->platformData; + HWND wrapper = TkWinGetWrapperWindow(menuPtr + ->parentTopLevelPtr); + if (wrapper != NULL) { + DestroyMenu(systemMenuHdl); + systemMenuHdl = GetSystemMenu( + wrapper, FALSE); + systemMenuPtr->menuFlags |= MENU_SYSTEM_MENU; + systemMenuPtr->platformData = + (TkMenuPlatformData) systemMenuHdl; + if (!(systemMenuPtr->menuFlags + & MENU_RECONFIGURE_PENDING)) { + systemMenuPtr->menuFlags + |= MENU_RECONFIGURE_PENDING; + Tcl_DoWhenIdle(ReconfigureWindowsMenu, + (ClientData) systemMenuPtr); + } + } + } + ckfree(systemMenuName); + } + if (mePtr->childMenuRefPtr->menuPtr->menuFlags + & MENU_SYSTEM_MENU) { + systemMenu++; + } + } + } + } + if (!systemMenu) { + InsertMenu(winMenuHdl, 0xFFFFFFFF, flags, itemID, lpNewItem); + } + if (itemText != NULL) { + ckfree(itemText); + itemText = NULL; + } + } + + + if ((menuPtr->menuType == MENUBAR) + && (menuPtr->parentTopLevelPtr != NULL)) { + DrawMenuBar(TkWinGetWrapperWindow(menuPtr->parentTopLevelPtr)); + Tk_GeometryRequest(menuPtr->parentTopLevelPtr, width, height); + } + + menuPtr->menuFlags &= ~(MENU_RECONFIGURE_PENDING); +} + +/* + *---------------------------------------------------------------------- + * + * TkpPostMenu -- + * + * Posts a menu on the screen + * + * Results: + * None. + * + * Side effects: + * The menu is posted and handled. + * + *---------------------------------------------------------------------- + */ + +int +TkpPostMenu(interp, menuPtr, x, y) + Tcl_Interp *interp; + TkMenu *menuPtr; + int x; + int y; +{ + HMENU winMenuHdl = (HMENU) menuPtr->platformData; + int result, flags; + RECT noGoawayRect; + POINT point; + Tk_Window parentWindow = Tk_Parent(menuPtr->tkwin); + int oldServiceMode = Tcl_GetServiceMode(); + + inPostMenu++; + + if (menuPtr->menuFlags & MENU_RECONFIGURE_PENDING) { + Tcl_CancelIdleCall(ReconfigureWindowsMenu, (ClientData) menuPtr); + ReconfigureWindowsMenu((ClientData) menuPtr); + } + + result = TkPreprocessMenu(menuPtr); + if (result != TCL_OK) { + inPostMenu--; + return result; + } + + /* + * The post commands could have deleted the menu, which means + * we are dead and should go away. + */ + + if (menuPtr->tkwin == NULL) { + inPostMenu--; + return TCL_OK; + } + + if (NULL == parentWindow) { + noGoawayRect.top = y - 50; + noGoawayRect.bottom = y + 50; + noGoawayRect.left = x - 50; + noGoawayRect.right = x + 50; + } else { + int left, top; + Tk_GetRootCoords(parentWindow, &left, &top); + noGoawayRect.left = left; + noGoawayRect.top = top; + noGoawayRect.bottom = noGoawayRect.top + Tk_Height(parentWindow); + noGoawayRect.right = noGoawayRect.left + Tk_Width(parentWindow); + } + + Tcl_SetServiceMode(TCL_SERVICE_NONE); + + /* + * Make an assumption here. If the right button is down, + * then we want to track it. Otherwise, track the left mouse button. + */ + + flags = TPM_LEFTALIGN; + if (GetSystemMetrics(SM_SWAPBUTTON)) { + if (GetAsyncKeyState(VK_LBUTTON) < 0) { + flags |= TPM_RIGHTBUTTON; + } else { + flags |= TPM_LEFTBUTTON; + } + } else { + if (GetAsyncKeyState(VK_RBUTTON) < 0) { + flags |= TPM_RIGHTBUTTON; + } else { + flags |= TPM_LEFTBUTTON; + } + } + + TrackPopupMenu(winMenuHdl, flags, x, y, 0, + menuHWND, &noGoawayRect); + Tcl_SetServiceMode(oldServiceMode); + + GetCursorPos(&point); + Tk_PointerEvent(NULL, point.x, point.y); + + if (inPostMenu) { + inPostMenu = 0; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpMenuNewEntry -- + * + * Adds a pointer to a new menu entry structure with the platform- + * specific fields filled in. + * + * Results: + * Standard TCL error. + * + * Side effects: + * A new command ID is allocated and stored in the platformEntryData + * field of mePtr. + * + *---------------------------------------------------------------------- + */ + +int +TkpMenuNewEntry(mePtr) + TkMenuEntry *mePtr; +{ + int commandID; + TkMenu *menuPtr = mePtr->menuPtr; + + if (GetNewID(mePtr, &commandID) != TCL_OK) { + return TCL_ERROR; + } + + if (!(menuPtr->menuFlags & MENU_RECONFIGURE_PENDING)) { + menuPtr->menuFlags |= MENU_RECONFIGURE_PENDING; + Tcl_DoWhenIdle(ReconfigureWindowsMenu, (ClientData) menuPtr); + } + + mePtr->platformEntryData = (TkMenuPlatformEntryData) commandID; + + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkWinMenuProc -- + * + * The window proc for the dummy window we put popups in. This allows + * is to post a popup whether or not we know what the parent window + * is. + * + * Results: + * Returns whatever is appropriate for the message in question. + * + * Side effects: + * Normal side-effect for windows messages. + * + *---------------------------------------------------------------------- + */ + +static LRESULT CALLBACK +TkWinMenuProc(hwnd, message, wParam, lParam) + HWND hwnd; + UINT message; + WPARAM wParam; + LPARAM lParam; +{ + LRESULT lResult; + + if (!TkWinHandleMenuEvent(&hwnd, &message, &wParam, &lParam, &lResult)) { + lResult = DefWindowProc(hwnd, message, wParam, lParam); + } + return lResult; +} + +/* + *---------------------------------------------------------------------- + * + * TkWinHandleMenuEvent -- + * + * Filters out menu messages from messages passed to a top-level. + * Will respond appropriately to WM_COMMAND, WM_MENUSELECT, + * WM_MEASUREITEM, WM_DRAWITEM + * + * Result: + * Returns 1 if this handled the message; 0 if it did not. + * + * Side effects: + * All of the parameters may be modified so that the caller can + * think it is getting a different message. plResult points to + * the result that should be returned to windows from this message. + * + *---------------------------------------------------------------------- + */ + +int +TkWinHandleMenuEvent(phwnd, pMessage, pwParam, plParam, plResult) + HWND *phwnd; + UINT *pMessage; + WPARAM *pwParam; + LPARAM *plParam; + LRESULT *plResult; +{ + Tcl_HashEntry *hashEntryPtr; + int returnResult = 0; + TkMenu *menuPtr; + TkMenuEntry *mePtr; + + switch (*pMessage) { + case WM_INITMENU: + TkMenuInit(); + hashEntryPtr = Tcl_FindHashEntry(&winMenuTable, (char *) *pwParam); + if (hashEntryPtr != NULL) { + oldServiceMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); + menuPtr = (TkMenu *) Tcl_GetHashValue(hashEntryPtr); + modalMenuPtr = menuPtr; + if (menuPtr->menuFlags & MENU_RECONFIGURE_PENDING) { + Tcl_CancelIdleCall(ReconfigureWindowsMenu, + (ClientData) menuPtr); + ReconfigureWindowsMenu((ClientData) menuPtr); + } + if (!inPostMenu) { + TkPreprocessMenu(menuPtr); + } + TkActivateMenuEntry(menuPtr, -1); + *plResult = 0; + returnResult = 1; + } else { + modalMenuPtr = NULL; + } + break; + + case WM_SYSCOMMAND: + case WM_COMMAND: { + TkMenuInit(); + if (HIWORD(*pwParam) == 0) { + hashEntryPtr = Tcl_FindHashEntry(&commandTable, + (char *)LOWORD(*pwParam)); + if (hashEntryPtr != NULL) { + mePtr = (TkMenuEntry *) Tcl_GetHashValue(hashEntryPtr); + if (mePtr != NULL) { + TkMenuReferences *menuRefPtr; + TkMenuEntry *parentEntryPtr; + + /* + * We have to set the parent of this menu to be active + * if this is a submenu so that tearoffs will get the + * correct title. + */ + + menuPtr = mePtr->menuPtr; + menuRefPtr = TkFindMenuReferences(menuPtr->interp, + Tk_PathName(menuPtr->tkwin)); + if ((menuRefPtr != NULL) && (menuRefPtr->parentEntryPtr + != NULL)) { + for (parentEntryPtr = menuRefPtr->parentEntryPtr; + strcmp(parentEntryPtr->name, + Tk_PathName(menuPtr->tkwin)) != 0; + parentEntryPtr = parentEntryPtr->nextCascadePtr) { + + /* + * Empty loop body. + */ + + } + if (parentEntryPtr->menuPtr + ->entries[parentEntryPtr->index]->state + != tkDisabledUid) { + TkActivateMenuEntry(parentEntryPtr->menuPtr, + parentEntryPtr->index); + } + } + + TkInvokeMenu(mePtr->menuPtr->interp, + menuPtr, mePtr->index); + } + *plResult = 0; + returnResult = 1; + } + } + break; + } + + + case WM_MENUCHAR: { + unsigned char menuChar = (unsigned char) LOWORD(*pwParam); + hashEntryPtr = Tcl_FindHashEntry(&winMenuTable, (char *) *plParam); + if (hashEntryPtr != NULL) { + int i; + + *plResult = 0; + menuPtr = (TkMenu *) Tcl_GetHashValue(hashEntryPtr); + for (i = 0; i < menuPtr->numEntries; i++) { + int underline = menuPtr->entries[i]->underline; + if ((-1 != underline) + && (NULL != menuPtr->entries[i]->label) + && (CharUpper((LPTSTR) menuChar) + == CharUpper((LPTSTR) (unsigned char) menuPtr + ->entries[i]->label[underline]))) { + *plResult = (2 << 16) | i; + break; + } + } + returnResult = 1; + } + break; + } + + case WM_MEASUREITEM: { + LPMEASUREITEMSTRUCT itemPtr = (LPMEASUREITEMSTRUCT) *plParam; + + if (itemPtr != NULL) { + mePtr = (TkMenuEntry *) itemPtr->itemData; + menuPtr = mePtr->menuPtr; + + TkRecomputeMenu(menuPtr); + itemPtr->itemHeight = mePtr->height; + itemPtr->itemWidth = mePtr->width; + if (mePtr->hideMargin) { + itemPtr->itemWidth += 2 - indicatorDimensions[0]; + } else { + itemPtr->itemWidth += 2 * menuPtr->activeBorderWidth; + } + *plResult = 1; + returnResult = 1; + } + break; + } + + case WM_DRAWITEM: { + TkWinDrawable *twdPtr; + LPDRAWITEMSTRUCT itemPtr = (LPDRAWITEMSTRUCT) *plParam; + Tk_FontMetrics fontMetrics; + + if (itemPtr != NULL) { + mePtr = (TkMenuEntry *) itemPtr->itemData; + menuPtr = mePtr->menuPtr; + twdPtr = (TkWinDrawable *) ckalloc(sizeof(TkWinDrawable)); + twdPtr->type = TWD_WINDC; + twdPtr->winDC.hdc = itemPtr->hDC; + + if (mePtr->state != tkDisabledUid) { + if (itemPtr->itemState & ODS_SELECTED) { + TkActivateMenuEntry(menuPtr, mePtr->index); + } else { + TkActivateMenuEntry(menuPtr, -1); + } + } + + Tk_GetFontMetrics(menuPtr->tkfont, &fontMetrics); + TkpDrawMenuEntry(mePtr, (Drawable) twdPtr, menuPtr->tkfont, + &fontMetrics, itemPtr->rcItem.left, + itemPtr->rcItem.top, itemPtr->rcItem.right + - itemPtr->rcItem.left, itemPtr->rcItem.bottom + - itemPtr->rcItem.top, 0, 0); + + ckfree((char *) twdPtr); + *plResult = 1; + returnResult = 1; + } + break; + } + + case WM_MENUSELECT: { + UINT flags = HIWORD(*pwParam); + + TkMenuInit(); + + if ((flags == 0xFFFF) && (*plParam == 0)) { + Tcl_SetServiceMode(oldServiceMode); + if (modalMenuPtr != NULL) { + RecursivelyClearActiveMenu(modalMenuPtr); + } + } else { + menuPtr = NULL; + if (*plParam != 0) { + hashEntryPtr = Tcl_FindHashEntry(&winMenuTable, + (char *) *plParam); + if (hashEntryPtr != NULL) { + menuPtr = (TkMenu *) Tcl_GetHashValue(hashEntryPtr); + } + } + + if (menuPtr != NULL) { + mePtr = NULL; + if (flags != 0xFFFF) { + if (flags & MF_POPUP) { + mePtr = menuPtr->entries[LOWORD(*pwParam)]; + } else { + hashEntryPtr = Tcl_FindHashEntry(&commandTable, + (char *) LOWORD(*pwParam)); + if (hashEntryPtr != NULL) { + mePtr = (TkMenuEntry *) Tcl_GetHashValue(hashEntryPtr); + } + } + } + + if ((mePtr == NULL) || (mePtr->state == tkDisabledUid)) { + TkActivateMenuEntry(menuPtr, -1); + } else { + TkActivateMenuEntry(menuPtr, mePtr->index); + } + MenuSelectEvent(menuPtr); + Tcl_ServiceAll(); + } + } + } + } + return returnResult; +} + +/* + *---------------------------------------------------------------------- + * + * 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); + MenuSelectEvent(menuPtr); + 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); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * 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(tkwin, menuPtr) + Tk_Window tkwin; /* The window we are putting the menubar into.*/ + TkMenu *menuPtr; /* The menu we are inserting */ +{ + HMENU winMenuHdl; + + if (menuPtr != NULL) { + Tcl_HashEntry *hashEntryPtr; + int newEntry; + + winMenuHdl = (HMENU) menuPtr->platformData; + hashEntryPtr = Tcl_FindHashEntry(&winMenuTable, (char *) winMenuHdl); + Tcl_DeleteHashEntry(hashEntryPtr); + DestroyMenu(winMenuHdl); + winMenuHdl = CreateMenu(); + hashEntryPtr = Tcl_CreateHashEntry(&winMenuTable, (char *) winMenuHdl, + &newEntry); + Tcl_SetHashValue(hashEntryPtr, (char *) menuPtr); + menuPtr->platformData = (TkMenuPlatformData) winMenuHdl; + TkWinSetMenu(tkwin, winMenuHdl); + if (menuPtr->menuFlags & MENU_RECONFIGURE_PENDING) { + Tcl_DoWhenIdle(ReconfigureWindowsMenu, (ClientData) menuPtr); + menuPtr->menuFlags |= MENU_RECONFIGURE_PENDING; + } + } else { + TkWinSetMenu(tkwin, NULL); + } +} + + +/* + *---------------------------------------------------------------------- + * + * 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. + */ +{ + /* + * Nothing to do. + */ +} + +/* + *---------------------------------------------------------------------- + * + * 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 measuring */ + 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 = indicatorDimensions[0]; + if (mePtr->hideMargin) { + *widthPtr = 0; + } else { + *widthPtr = indicatorDimensions[1] - menuPtr->borderWidth; + } +} + +/* + *---------------------------------------------------------------------- + * + * GetMenuAccelGeometry -- + * + * Gets the width and height of the indicator 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 *widthPtr, /* The resulting width */ + int *heightPtr) /* The resulting height */ +{ + *heightPtr = fmPtr->linespace; + if (mePtr->type == CASCADE_ENTRY) { + *widthPtr = 0; + } else if (mePtr->accel == NULL) { + *widthPtr = 0; + } else { + *widthPtr = Tk_TextWidth(tkfont, mePtr->accel, mePtr->accelLength); + } +} + +/* + *---------------------------------------------------------------------- + * + * GetTearoffEntryGeometry -- + * + * Gets the width and height of the indicator area of a menu. + * + * Results: + * widthPtr and heightPtr are set. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +GetTearoffEntryGeometry ( + 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 *widthPtr, /* The resulting width */ + int *heightPtr) /* The resulting height */ +{ + if (menuPtr->menuType != MASTER_MENU) { + *heightPtr = 0; + } else { + *heightPtr = fmPtr->linespace; + } + *widthPtr = 0; +} + +/* + *---------------------------------------------------------------------- + * + * GetMenuSeparatorGeometry -- + * + * Gets the width and height of the indicator area of a menu. + * + * Results: + * widthPtr and heightPtr are set. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +GetMenuSeparatorGeometry ( + 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 precalcualted font metrics */ + int *widthPtr, /* The resulting width */ + int *heightPtr) /* The resulting height */ +{ + *widthPtr = 0; + *heightPtr = fmPtr->linespace; +} + +/* + *---------------------------------------------------------------------- + * + * DrawWindowsSystemBitmap -- + * + * Draws the windows system bitmap given by bitmapID into the rect + * given by rectPtr in the drawable. The bitmap is centered in the + * rectangle. It is not clipped, so if the bitmap is bigger than + * the rect it will bleed. + * + * Results: + * None. + * + * Side effects: + * Drawing occurs. Some storage is allocated and released. + * + *---------------------------------------------------------------------- + */ + +static void +DrawWindowsSystemBitmap(display, drawable, gc, rectPtr, bitmapID, alignFlags) + Display *display; /* The display we are drawing into */ + Drawable drawable; /* The drawable we are working with */ + GC gc; /* The GC to draw with */ + CONST RECT *rectPtr; /* The rectangle to draw into */ + int bitmapID; /* The windows id of the system + * bitmap to draw. */ + int alignFlags; /* How to align the bitmap inside the + * rectangle. */ +{ + TkWinDCState state; + HDC hdc = TkWinGetDrawableDC(display, drawable, &state); + HDC scratchDC; + HBITMAP bitmap; + BITMAP bm; + POINT ptSize; + POINT ptOrg; + int topOffset, leftOffset; + + SetBkColor(hdc, gc->background); + SetTextColor(hdc, gc->foreground); + + scratchDC = CreateCompatibleDC(hdc); + bitmap = LoadBitmap(NULL, MAKEINTRESOURCE(bitmapID)); + + SelectObject(scratchDC, bitmap); + SetMapMode(scratchDC, GetMapMode(hdc)); + GetObject(bitmap, sizeof(BITMAP), &bm); + ptSize.x = bm.bmWidth; + ptSize.y = bm.bmHeight; + DPtoLP(hdc, &ptSize, 1); + + ptOrg.y = ptOrg.x = 0; + DPtoLP(hdc, &ptOrg, 1); + + if (alignFlags & ALIGN_BITMAP_TOP) { + topOffset = 0; + } else if (alignFlags & ALIGN_BITMAP_BOTTOM) { + topOffset = (rectPtr->bottom - rectPtr->top) - ptSize.y; + } else { + topOffset = (rectPtr->bottom - rectPtr->top) / 2 - (ptSize.y / 2); + } + + if (alignFlags & ALIGN_BITMAP_LEFT) { + leftOffset = 0; + } else if (alignFlags & ALIGN_BITMAP_RIGHT) { + leftOffset = (rectPtr->right - rectPtr->left) - ptSize.x; + } else { + leftOffset = (rectPtr->right - rectPtr->left) / 2 - (ptSize.x / 2); + } + + BitBlt(hdc, rectPtr->left + leftOffset, rectPtr->top + topOffset, ptSize.x, + ptSize.y, scratchDC, ptOrg.x, ptOrg.y, SRCCOPY); + DeleteDC(scratchDC); + DeleteObject(bitmap); + + TkWinReleaseDrawableDC(drawable, hdc, &state); +} + +/* + *---------------------------------------------------------------------- + * + * 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(menuPtr, mePtr, d, gc, indicatorGC, tkfont, fmPtr, x, + y, width, height) + 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 with */ + GC indicatorGC; /* The gc for indicator objects */ + Tk_Font tkfont; /* The precalculated font */ + CONST Tk_FontMetrics *fmPtr; /* The precalculated font metrics */ + int x; /* Left edge */ + int y; /* Top edge */ + int width; + int height; +{ + if ((mePtr->type == CHECK_BUTTON_ENTRY || + mePtr->type == RADIO_BUTTON_ENTRY) + && mePtr->indicatorOn + && mePtr->entryFlags & ENTRY_SELECTED) { + RECT rect; + GC whichGC; + + if (mePtr->state != tkNormalUid) { + whichGC = gc; + } else { + whichGC = indicatorGC; + } + + rect.top = y; + rect.bottom = y + mePtr->height; + rect.left = menuPtr->borderWidth + menuPtr->activeBorderWidth + x; + rect.right = mePtr->indicatorSpace + x; + + if ((mePtr->state == tkDisabledUid) && (menuPtr->disabledFg != NULL) + && (versionInfo.dwMajorVersion >= 4)) { + RECT hilightRect; + COLORREF oldFgColor = whichGC->foreground; + + whichGC->foreground = GetSysColor(COLOR_3DHILIGHT); + hilightRect.top = rect.top + 1; + hilightRect.bottom = rect.bottom + 1; + hilightRect.left = rect.left + 1; + hilightRect.right = rect.right + 1; + DrawWindowsSystemBitmap(menuPtr->display, d, whichGC, + &hilightRect, OBM_CHECK, 0); + whichGC->foreground = oldFgColor; + } + + DrawWindowsSystemBitmap(menuPtr->display, d, whichGC, &rect, + OBM_CHECK, 0); + + if ((mePtr->state == tkDisabledUid) + && (menuPtr->disabledImageGC != None) + && (versionInfo.dwMajorVersion < 4)) { + XFillRectangle(menuPtr->display, d, menuPtr->disabledImageGC, + rect.left, rect.top, rect.right, rect.bottom); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuEntryAccelerator -- + * + * This procedure draws the accelerator part of a menu. We + * need to decide what to draw here. Should we replace strings + * like "Control", "Command", etc? + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +void +DrawMenuEntryAccelerator(menuPtr, mePtr, d, gc, tkfont, fmPtr, + activeBorder, x, y, width, height, drawArrow) + 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 with */ + Tk_Font tkfont; /* The precalculated font */ + CONST Tk_FontMetrics *fmPtr; /* The precalculated font metrics */ + Tk_3DBorder activeBorder; /* The border when an item is active */ + int x; /* left edge */ + int y; /* top edge */ + int width; /* Width of menu entry */ + int height; /* Height of menu entry */ + int drawArrow; /* For cascade menus, whether of not + * to draw the arraw. I cannot figure + * out Windows' algorithm for where + * to draw this. */ +{ + int baseline; + int leftEdge = x + mePtr->indicatorSpace + mePtr->labelWidth; + + baseline = y + (height + fmPtr->ascent - fmPtr->descent) / 2; + + if ((mePtr->state == tkDisabledUid) && (menuPtr->disabledFg != NULL) + && ((mePtr->accel != NULL) + || ((mePtr->type == CASCADE_ENTRY) && drawArrow))) { + if (versionInfo.dwMajorVersion >= 4) { + COLORREF oldFgColor = gc->foreground; + + gc->foreground = GetSysColor(COLOR_3DHILIGHT); + if (mePtr->accel != NULL) { + Tk_DrawChars(menuPtr->display, d, gc, tkfont, mePtr->accel, + mePtr->accelLength, leftEdge + 1, baseline + 1); + } + + if (mePtr->type == CASCADE_ENTRY) { + RECT rect; + + rect.top = y + GetSystemMetrics(SM_CYBORDER) + 1; + rect.bottom = y + height - GetSystemMetrics(SM_CYBORDER) + 1; + rect.left = x + mePtr->indicatorSpace + mePtr->labelWidth + 1; + rect.right = x + width; + DrawWindowsSystemBitmap(menuPtr->display, d, gc, &rect, + OBM_MNARROW, ALIGN_BITMAP_RIGHT); + } + gc->foreground = oldFgColor; + } + } + + if (mePtr->accel != NULL) { + Tk_DrawChars(menuPtr->display, d, gc, tkfont, mePtr->accel, + mePtr->accelLength, leftEdge, baseline); + } + + if ((mePtr->state == tkDisabledUid) + && (menuPtr->disabledImageGC != None) + && (versionInfo.dwMajorVersion < 4)) { + XFillRectangle(menuPtr->display, d, menuPtr->disabledImageGC, + leftEdge, y, width - mePtr->labelWidth + - mePtr->indicatorSpace, height); + } + + if ((mePtr->type == CASCADE_ENTRY) && drawArrow) { + RECT rect; + + rect.top = y + GetSystemMetrics(SM_CYBORDER); + rect.bottom = y + height - GetSystemMetrics(SM_CYBORDER); + rect.left = x + mePtr->indicatorSpace + mePtr->labelWidth; + rect.right = x + width - 1; + DrawWindowsSystemBitmap(menuPtr->display, d, gc, &rect, OBM_MNARROW, + ALIGN_BITMAP_RIGHT); + if ((mePtr->state == tkDisabledUid) + && (menuPtr->disabledImageGC != None) + && (versionInfo.dwMajorVersion < 4)) { + XFillRectangle(menuPtr->display, d, menuPtr->disabledImageGC, + rect.left, rect.top, rect.right, rect.bottom); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * 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(menuPtr, mePtr, d, gc, tkfont, fmPtr, x, y, width, height) + 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 with */ + Tk_Font tkfont; /* The precalculated font */ + CONST Tk_FontMetrics *fmPtr; /* The precalculated font metrics */ + int x; /* left edge */ + int y; /* top edge */ + int width; /* width of item */ + int height; /* height of item */ +{ + XPoint points[2]; + + points[0].x = x; + points[0].y = y + height / 2; + points[1].x = x + width - 1; + points[1].y = points[0].y; + Tk_Draw3DPolygon(menuPtr->tkwin, d, + menuPtr->border, points, 2, 1, TK_RELIEF_RAISED); +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuUnderline -- + * + * On appropriate platforms, draw the underline character for the + * menu. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ +static void +DrawMenuUnderline( + TkMenu *menuPtr, /* The menu to draw into */ + TkMenuEntry *mePtr, /* The entry we are drawing */ + Drawable d, /* What we are drawing into */ + GC gc, /* The gc to draw into */ + Tk_Font tkfont, /* The precalculated font */ + CONST Tk_FontMetrics *fmPtr, /* The precalculated font metrics */ + int x, /* Left Edge */ + int y, /* Top Edge */ + int width, /* Width of entry */ + int height) /* Height of entry */ +{ + if (mePtr->underline >= 0) { + Tk_UnderlineChars(menuPtr->display, d, + gc, tkfont, mePtr->label, x + mePtr->indicatorSpace, + y + (height + fmPtr->ascent - fmPtr->descent) / 2, + mePtr->underline, mePtr->underline + 1); + } +} + +/* + *-------------------------------------------------------------- + * + * MenuKeyBindProc -- + * + * This procedure is invoked when keys related to pulling + * down menus is pressed. The corresponding Windows events + * are generated and passed to DefWindowProc if appropriate. + * + * Results: + * Always returns TCL_OK. + * + * Side effects: + * The menu system may take over and process user events + * for menu input. + * + *-------------------------------------------------------------- + */ + +static int +MenuKeyBindProc(clientData, interp, eventPtr, tkwin, keySym) + ClientData clientData; /* not used in this proc */ + Tcl_Interp *interp; /* The interpreter of the receiving window. */ + XEvent *eventPtr; /* The XEvent to process */ + Tk_Window tkwin; /* The window receiving the event */ + KeySym keySym; /* The key sym that is produced. */ +{ + UINT scanCode; + UINT virtualKey; + TkWindow *winPtr = (TkWindow *)tkwin; + + if (eventPtr->type == KeyPress) { + switch (keySym) { + case XK_Alt_L: + scanCode = MapVirtualKey(VK_LMENU, 0); + CallWindowProc(DefWindowProc, Tk_GetHWND(Tk_WindowId(tkwin)), + WM_SYSKEYDOWN, VK_MENU, (scanCode << 16) + | (1 << 29)); + break; + case XK_Alt_R: + scanCode = MapVirtualKey(VK_RMENU, 0); + CallWindowProc(DefWindowProc, Tk_GetHWND(Tk_WindowId(tkwin)), + WM_SYSKEYDOWN, VK_MENU, (scanCode << 16) + | (1 << 29) | (1 << 24)); + break; + case XK_F10: + scanCode = MapVirtualKey(VK_F10, 0); + CallWindowProc(DefWindowProc, Tk_GetHWND(Tk_WindowId(tkwin)), + WM_SYSKEYDOWN, VK_F10, (scanCode << 16)); + break; + default: + virtualKey = XKeysymToKeycode(winPtr->display, keySym); + scanCode = MapVirtualKey(virtualKey, 0); + if (0 != scanCode) { + CallWindowProc(DefWindowProc, Tk_GetHWND(Tk_WindowId(tkwin)), + WM_SYSKEYDOWN, virtualKey, ((scanCode << 16) + | (1 << 29))); + } + } + } else if (eventPtr->type == KeyRelease) { + switch (keySym) { + case XK_Alt_L: + scanCode = MapVirtualKey(VK_LMENU, 0); + CallWindowProc(DefWindowProc, Tk_GetHWND(Tk_WindowId(tkwin)), + WM_SYSKEYUP, VK_MENU, (scanCode << 16) + | (1 << 29) | (1 << 30) | (1 << 31)); + break; + case XK_Alt_R: + scanCode = MapVirtualKey(VK_RMENU, 0); + CallWindowProc(DefWindowProc, Tk_GetHWND(Tk_WindowId(tkwin)), + WM_SYSKEYUP, VK_MENU, (scanCode << 16) | (1 << 24) + | (0x111 << 29) | (1 << 30) | (1 << 31)); + break; + case XK_F10: + scanCode = MapVirtualKey(VK_F10, 0); + CallWindowProc(DefWindowProc, Tk_GetHWND(Tk_WindowId(tkwin)), + WM_SYSKEYUP, VK_F10, (scanCode << 16) + | (1 << 30) | (1 << 31)); + break; + default: + virtualKey = XKeysymToKeycode(winPtr->display, keySym); + scanCode = MapVirtualKey(virtualKey, 0); + if (0 != scanCode) { + CallWindowProc(DefWindowProc, Tk_GetHWND(Tk_WindowId(tkwin)), + WM_SYSKEYUP, virtualKey, ((scanCode << 16) + | (1 << 29) | (1 << 30) | (1 << 31))); + } + } + } + return TCL_OK; +} + +/* + *-------------------------------------------------------------- + * + * 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(interp, bindingTable) + Tcl_Interp *interp; /* The interpreter to set. */ + Tk_BindingTable bindingTable; /* The table to add to. */ +{ + Tk_Uid uid = Tk_GetUid("all"); + + /* + * We need to set up the bindings for menubars. These have to + * recreate windows events, so we need to have a C-level + * binding for this. We have to generate the WM_SYSKEYDOWNS + * and WM_SYSKEYUPs appropriately. + */ + + TkCreateBindingProcedure(interp, bindingTable, (ClientData)uid, + "<Alt_L>", MenuKeyBindProc, NULL, NULL); + TkCreateBindingProcedure(interp, bindingTable, (ClientData)uid, + "<KeyRelease-Alt_L>", MenuKeyBindProc, NULL, NULL); + TkCreateBindingProcedure(interp, bindingTable, (ClientData)uid, + "<Alt_R>", MenuKeyBindProc, NULL, NULL); + TkCreateBindingProcedure(interp, bindingTable, (ClientData)uid, + "<KeyRelease-Alt_R>", MenuKeyBindProc, NULL, NULL); + TkCreateBindingProcedure(interp, bindingTable, (ClientData)uid, + "<Alt-KeyPress>", MenuKeyBindProc, NULL, NULL); + TkCreateBindingProcedure(interp, bindingTable, (ClientData)uid, + "<Alt-KeyRelease>", MenuKeyBindProc, NULL, NULL); + TkCreateBindingProcedure(interp, bindingTable, (ClientData)uid, + "<KeyPress-F10>", MenuKeyBindProc, NULL, NULL); + TkCreateBindingProcedure(interp, bindingTable, (ClientData)uid, + "<KeyRelease-F10>", MenuKeyBindProc, NULL, NULL); +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static 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 baseline; + int indicatorSpace = mePtr->indicatorSpace; + int leftEdge = x + indicatorSpace + menuPtr->activeBorderWidth; + int imageHeight, imageWidth; + + /* + * Draw label or bitmap or image for entry. + */ + + baseline = y + (height + fmPtr->ascent - fmPtr->descent) / 2; + if (mePtr->image != NULL) { + Tk_SizeOfImage(mePtr->image, &imageWidth, &imageHeight); + if ((mePtr->selectImage != NULL) + && (mePtr->entryFlags & ENTRY_SELECTED)) { + Tk_RedrawImage(mePtr->selectImage, 0, 0, + imageWidth, imageHeight, d, leftEdge, + (int) (y + (mePtr->height - imageHeight)/2)); + } else { + Tk_RedrawImage(mePtr->image, 0, 0, imageWidth, + imageHeight, d, leftEdge, + (int) (y + (mePtr->height - imageHeight)/2)); + } + } else if (mePtr->bitmap != None) { + int width, height; + + Tk_SizeOfBitmap(menuPtr->display, + mePtr->bitmap, &width, &height); + XCopyPlane(menuPtr->display, + mePtr->bitmap, d, + gc, 0, 0, (unsigned) width, (unsigned) height, leftEdge, + (int) (y + (mePtr->height - height)/2), 1); + } else { + if (mePtr->labelLength > 0) { + Tk_DrawChars(menuPtr->display, d, gc, + tkfont, mePtr->label, mePtr->labelLength, + leftEdge, baseline); + DrawMenuUnderline(menuPtr, mePtr, d, gc, tkfont, fmPtr, x, y, + width, height); + } + } + + if (mePtr->state == tkDisabledUid) { + if (menuPtr->disabledFg == NULL) { + XFillRectangle(menuPtr->display, d, menuPtr->disabledGC, x, y, + (unsigned) width, (unsigned) height); + } else if ((mePtr->image != NULL) + && (menuPtr->disabledImageGC != None)) { + XFillRectangle(menuPtr->display, d, menuPtr->disabledImageGC, + leftEdge, + (int) (y + (mePtr->height - imageHeight)/2), + (unsigned) imageWidth, (unsigned) imageHeight); + } + } +} + +/* + *-------------------------------------------------------------- + * + * 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(menuPtr) + TkMenu *menuPtr; /* Structure describing menu. */ +{ + TkpComputeStandardMenuGeometry(menuPtr); +} + +/* + *---------------------------------------------------------------------- + * + * DrawTearoffEntry -- + * + * This procedure draws the background part of a menu. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +void +DrawTearoffEntry(menuPtr, mePtr, d, gc, tkfont, fmPtr, x, y, width, height) + 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; + int y; + int width; + int height; +{ + XPoint points[2]; + int segmentWidth, maxX; + + if (menuPtr->menuType != MASTER_MENU) { + return; + } + + points[0].x = x; + points[0].y = y + height/2; + points[1].y = points[0].y; + segmentWidth = 6; + maxX = width - 1; + + 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, menuPtr->border, points, 2, 1, + TK_RELIEF_RAISED); + points[0].x += 2*segmentWidth; + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpConfigureMenuEntry -- + * + * Processes configurations for menu entries. + * + * Results: + * Returns standard TCL result. If TCL_ERROR is returned, then + * interp->result contains an error message. + * + * Side effects: + * Configuration information get set for mePtr; old resources + * get freed, if any need it. + * + *---------------------------------------------------------------------- + */ + +int +TkpConfigureMenuEntry(mePtr) + register TkMenuEntry *mePtr; /* Information about menu entry; may + * or may not already have values for + * some fields. */ +{ + TkMenu *menuPtr = mePtr->menuPtr; + + if (!(menuPtr->menuFlags & MENU_RECONFIGURE_PENDING)) { + menuPtr->menuFlags |= MENU_RECONFIGURE_PENDING; + Tcl_DoWhenIdle(ReconfigureWindowsMenu, (ClientData) menuPtr); + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * 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(mePtr, d, tkfont, menuMetricsPtr, x, y, width, height, + strictMotif, drawArrow) + 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, indicatorGC; + TkMenu *menuPtr = mePtr->menuPtr; + Tk_3DBorder bgBorder, activeBorder; + CONST Tk_FontMetrics *fmPtr; + Tk_FontMetrics entryMetrics; + int padY = (menuPtr->menuType == MENUBAR) ? 3 : 0; + int adjustedY = y + padY; + int adjustedHeight = height - 2 * padY; + + /* + * Choose the gc for drawing the foreground part of the entry. + */ + + if ((mePtr->state == tkActiveUid) + && !strictMotif) { + gc = mePtr->activeGC; + if (gc == NULL) { + gc = menuPtr->activeGC; + } + } else { + TkMenuEntry *cascadeEntryPtr; + int parentDisabled = 0; + + for (cascadeEntryPtr = menuPtr->menuRefPtr->parentEntryPtr; + cascadeEntryPtr != NULL; + cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr) { + if (strcmp(cascadeEntryPtr->name, + Tk_PathName(menuPtr->tkwin)) == 0) { + if (cascadeEntryPtr->state == tkDisabledUid) { + parentDisabled = 1; + } + break; + } + } + + if (((parentDisabled || (mePtr->state == tkDisabledUid))) + && (menuPtr->disabledFg != 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 = mePtr->border; + if (bgBorder == NULL) { + bgBorder = menuPtr->border; + } + if (strictMotif) { + activeBorder = bgBorder; + } else { + activeBorder = mePtr->activeBorder; + if (activeBorder == NULL) { + activeBorder = menuPtr->activeBorder; + } + } + + if (mePtr->tkfont == NULL) { + fmPtr = menuMetricsPtr; + } else { + tkfont = mePtr->tkfont; + 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); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static void +GetMenuLabelGeometry(mePtr, tkfont, fmPtr, widthPtr, heightPtr) + 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; + + if (mePtr->image != NULL) { + Tk_SizeOfImage(mePtr->image, widthPtr, heightPtr); + } else if (mePtr->bitmap != (Pixmap) NULL) { + Tk_SizeOfBitmap(menuPtr->display, mePtr->bitmap, widthPtr, heightPtr); + } else { + *heightPtr = fmPtr->linespace; + + if (mePtr->label != NULL) { + *widthPtr = Tk_TextWidth(tkfont, mePtr->label, mePtr->labelLength); + } else { + *widthPtr = 0; + } + } + *heightPtr += 1; +} + +/* + *---------------------------------------------------------------------- + * + * DrawMenuEntryBackground -- + * + * This procedure draws the background part of a menu. + * + * Results: + * None. + * + * Side effects: + * Commands are output to X to display the menu in its + * current mode. + * + *---------------------------------------------------------------------- + */ + +static 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 (mePtr->state == tkActiveUid) { + bgBorder = activeBorder; + } + Tk_Fill3DRectangle(menuPtr->tkwin, d, bgBorder, + x, y, width, height, 0, TK_RELIEF_FLAT); +} + +/* + *-------------------------------------------------------------- + * + * 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; + Tk_FontMetrics menuMetrics, entryMetrics, *fmPtr; + int x, y, height, width, indicatorSpace, labelWidth, accelWidth; + int windowWidth, windowHeight, accelSpace; + int i, j, lastColumnBreak = 0; + + if (menuPtr->tkwin == NULL) { + return; + } + + x = y = menuPtr->borderWidth; + indicatorSpace = labelWidth = accelWidth = 0; + windowHeight = 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. + */ + + Tk_GetFontMetrics(menuPtr->tkfont, &menuMetrics); + accelSpace = Tk_TextWidth(menuPtr->tkfont, "M", 1); + + for (i = 0; i < menuPtr->numEntries; i++) { + tkfont = menuPtr->entries[i]->tkfont; + if (tkfont == NULL) { + tkfont = menuPtr->tkfont; + fmPtr = &menuMetrics; + } else { + Tk_GetFontMetrics(tkfont, &entryMetrics); + fmPtr = &entryMetrics; + } + + if ((i > 0) && menuPtr->entries[i]->columnBreak) { + if (accelWidth != 0) { + labelWidth += accelSpace; + } + for (j = lastColumnBreak; j < i; j++) { + menuPtr->entries[j]->indicatorSpace = indicatorSpace; + menuPtr->entries[j]->labelWidth = labelWidth; + menuPtr->entries[j]->width = indicatorSpace + labelWidth + + accelWidth + 2 * menuPtr->activeBorderWidth; + menuPtr->entries[j]->x = x; + menuPtr->entries[j]->entryFlags &= ~ENTRY_LAST_COLUMN; + } + x += indicatorSpace + labelWidth + accelWidth + + 2 * menuPtr->borderWidth; + indicatorSpace = labelWidth = accelWidth = 0; + lastColumnBreak = i; + y = menuPtr->borderWidth; + } + + if (menuPtr->entries[i]->type == SEPARATOR_ENTRY) { + GetMenuSeparatorGeometry(menuPtr, menuPtr->entries[i], tkfont, + fmPtr, &width, &height); + menuPtr->entries[i]->height = height; + } else if (menuPtr->entries[i]->type == TEAROFF_ENTRY) { + GetTearoffEntryGeometry(menuPtr, menuPtr->entries[i], tkfont, + fmPtr, &width, &height); + menuPtr->entries[i]->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(menuPtr->entries[i], tkfont, fmPtr, &width, + &height); + menuPtr->entries[i]->height = height; + if (width > labelWidth) { + labelWidth = width; + } + + GetMenuAccelGeometry(menuPtr, menuPtr->entries[i], tkfont, + fmPtr, &width, &height); + if (height > menuPtr->entries[i]->height) { + menuPtr->entries[i]->height = height; + } + if (width > accelWidth) { + accelWidth = width; + } + + GetMenuIndicatorGeometry(menuPtr, menuPtr->entries[i], tkfont, + fmPtr, &width, &height); + if (height > menuPtr->entries[i]->height) { + menuPtr->entries[i]->height = height; + } + if (width > indicatorSpace) { + indicatorSpace = width; + } + + menuPtr->entries[i]->height += 2 * menuPtr->activeBorderWidth + 1; + } + menuPtr->entries[i]->y = y; + y += menuPtr->entries[i]->height; + if (y > windowHeight) { + windowHeight = y; + } + } + + if (accelWidth != 0) { + labelWidth += accelSpace; + } + for (j = lastColumnBreak; j < menuPtr->numEntries; j++) { + menuPtr->entries[j]->indicatorSpace = indicatorSpace; + menuPtr->entries[j]->labelWidth = labelWidth; + menuPtr->entries[j]->width = indicatorSpace + labelWidth + + accelWidth + 2 * menuPtr->activeBorderWidth; + menuPtr->entries[j]->x = x; + menuPtr->entries[j]->entryFlags |= ENTRY_LAST_COLUMN; + } + windowWidth = x + indicatorSpace + labelWidth + accelWidth + accelSpace + + 2 * menuPtr->activeBorderWidth + + 2 * menuPtr->borderWidth; + + + windowHeight += menuPtr->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; +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + *---------------------------------------------------------------------- + */ + +static void +MenuSelectEvent( + TkMenu *menuPtr) /* the menu we have selected. */ +{ + XVirtualEvent event; + POINTS rootPoint; + DWORD msgPos; + + event.type = VirtualEvent; + event.serial = menuPtr->display->request; + event.send_event = 0; + 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(); + + msgPos = GetMessagePos(); + rootPoint = MAKEPOINTS(msgPos); + event.x_root = rootPoint.x; + event.y_root = rootPoint.y; + event.state = TkWinGetModifierState(); + event.same_screen = 1; + event.name = Tk_GetUid("MenuSelect"); + Tk_QueueWindowEvent((XEvent *) &event, TCL_QUEUE_TAIL); +} + +/* + *---------------------------------------------------------------------- + * + * 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. + * + * 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. */ +{ + TkMenuReferences *menuRefPtr; + TkMenu *menuPtr; + + if ((menuName != NULL) && (menuName[0] != '\0')) { + menuRefPtr = TkFindMenuReferences(interp, menuName); + if ((menuRefPtr != NULL) && (menuRefPtr->menuPtr != NULL)) { + for (menuPtr = menuRefPtr->menuPtr->masterMenuPtr; menuPtr != NULL; + menuPtr = menuPtr->nextInstancePtr) { + if ((menuPtr->menuType == MENUBAR) + && !(menuPtr->menuFlags & MENU_RECONFIGURE_PENDING)) { + menuPtr->menuFlags |= MENU_RECONFIGURE_PENDING; + Tcl_DoWhenIdle(ReconfigureWindowsMenu, + (ClientData) menuPtr); + } + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * MenuExitHandler -- + * + * Throws away the utility window needed for menus and unregisters + * the class. + * + * Results: + * None. + * + * Side effects: + * Menus have to be reinitialized next time. + * + *---------------------------------------------------------------------- + */ + +static void +MenuExitHandler( + ClientData clientData) /* Not used */ +{ + DestroyWindow(menuHWND); + UnregisterClass(MENU_CLASS_NAME, Tk_GetHINSTANCE()); +} + +/* + *---------------------------------------------------------------------- + * + * TkpMenuInit -- + * + * Sets up the hash tables and the variables used by the menu package. + * + * Results: + * None. + * + * Side effects: + * lastMenuID gets initialized, and the parent hash and the command hash + * are allocated. + * + *---------------------------------------------------------------------- + */ + +void +TkpMenuInit() +{ + WNDCLASS wndClass; + char sizeString[4]; + char faceName[LF_FACESIZE]; + HDC scratchDC; + Tcl_DString boldItalicDString; + int bold = 0; + int italic = 0; + int i; + TEXTMETRIC tm; + + Tcl_InitHashTable(&winMenuTable, TCL_ONE_WORD_KEYS); + Tcl_InitHashTable(&commandTable, TCL_ONE_WORD_KEYS); + + wndClass.style = CS_OWNDC; + wndClass.lpfnWndProc = TkWinMenuProc; + wndClass.cbClsExtra = 0; + wndClass.cbWndExtra = 0; + wndClass.hInstance = Tk_GetHINSTANCE(); + wndClass.hIcon = NULL; + wndClass.hCursor = NULL; + wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wndClass.lpszMenuName = NULL; + wndClass.lpszClassName = MENU_CLASS_NAME; + RegisterClass(&wndClass); + + menuHWND = CreateWindow(MENU_CLASS_NAME, "MenuWindow", WS_POPUP, + 0, 0, 10, 10, NULL, NULL, Tk_GetHINSTANCE(), NULL); + + Tcl_CreateExitHandler(MenuExitHandler, (ClientData) NULL); + + versionInfo.dwOSVersionInfoSize = sizeof(versionInfo); + + /* + * If GetVersionEx fails, it means that the version info record + * is too big for what is compiled. Should never happen, but if + * it does, we are later than Windows 95 or NT 4.0. + */ + + if (!GetVersionEx(&versionInfo)) { + versionInfo.dwMajorVersion = 4; + } + + /* + * Set all of the default options. The loop will terminate when we run + * out of options via a break statement. + */ + + for (i = 0; ; i++) { + if (tkMenuConfigSpecs[i].type == TK_CONFIG_END) { + break; + } + + if ((strcmp(tkMenuConfigSpecs[i].dbName, + "activeBorderWidth") == 0) || + (strcmp(tkMenuConfigSpecs[i].dbName, "borderWidth") == 0)) { + int borderWidth; + + borderWidth = GetSystemMetrics(SM_CXBORDER); + if (GetSystemMetrics(SM_CYBORDER) > borderWidth) { + borderWidth = GetSystemMetrics(SM_CYBORDER); + } + sprintf(borderString, "%d", borderWidth); + tkMenuConfigSpecs[i].defValue = borderString; + } else if ((strcmp(tkMenuConfigSpecs[i].dbName, "font") == 0)) { + int pointSize; + HFONT menuFont; + + scratchDC = CreateDC("DISPLAY", NULL, NULL, NULL); + Tcl_DStringInit(&menuFontDString); + + if (versionInfo.dwMajorVersion >= 4) { + NONCLIENTMETRICS ncMetrics; + + ncMetrics.cbSize = sizeof(ncMetrics); + SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncMetrics), + &ncMetrics, 0); + menuFont = CreateFontIndirect(&ncMetrics.lfMenuFont); + } else { + menuFont = GetStockObject(SYSTEM_FONT); + } + SelectObject(scratchDC, menuFont); + GetTextMetrics(scratchDC, &tm); + GetTextFace(scratchDC, sizeof(menuFontDString), faceName); + pointSize = MulDiv(tm.tmHeight - tm.tmInternalLeading, + 72, GetDeviceCaps(scratchDC, LOGPIXELSY)); + if (tm.tmWeight >= 700) { + bold = 1; + } + if (tm.tmItalic) { + italic = 1; + } + + SelectObject(scratchDC, GetStockObject(SYSTEM_FONT)); + DeleteDC(scratchDC); + + DeleteObject(menuFont); + + Tcl_DStringAppendElement(&menuFontDString, faceName); + sprintf(sizeString, "%d", pointSize); + Tcl_DStringAppendElement(&menuFontDString, sizeString); + + if (bold == 1 || italic == 1) { + Tcl_DStringInit(&boldItalicDString); + if (bold == 1) { + Tcl_DStringAppendElement(&boldItalicDString, "bold"); + } + if (italic == 1) { + Tcl_DStringAppendElement(&boldItalicDString, "italic"); + } + Tcl_DStringAppendElement(&menuFontDString, + Tcl_DStringValue(&boldItalicDString)); + } + + tkMenuConfigSpecs[i].defValue = Tcl_DStringValue(&menuFontDString); + } + } + + /* + * Now we go ahead and get the dimensions of the check mark and the + * appropriate margins. Since this is fairly hairy, we do it here + * to save time when traversing large sets of menu items. + * + * The code below was given to me by Microsoft over the phone. It + * is the only way to insure menu items lining up, and is not + * documented. + */ + + if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { + indicatorDimensions[0] = GetSystemMetrics(SM_CYMENUCHECK); + indicatorDimensions[1] = ((GetSystemMetrics(SM_CXFIXEDFRAME) + + GetSystemMetrics(SM_CXBORDER) + + GetSystemMetrics(SM_CXMENUCHECK) + 7) & 0xFFF8) + - GetSystemMetrics(SM_CXFIXEDFRAME); + } else { + DWORD dimensions = GetMenuCheckMarkDimensions(); + indicatorDimensions[0] = HIWORD(dimensions); + indicatorDimensions[1] = LOWORD(dimensions); + } + +} diff --git a/win/tkWinPixmap.c b/win/tkWinPixmap.c new file mode 100644 index 0000000..1ca2d7e --- /dev/null +++ b/win/tkWinPixmap.c @@ -0,0 +1,184 @@ +/* + * tkWinPixmap.c -- + * + * This file contains the Xlib emulation functions pertaining to + * creating and destroying pixmaps. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinPixmap.c 1.18 97/08/06 15:36:23 + */ + +#include "tkWinInt.h" + + +/* + *---------------------------------------------------------------------- + * + * Tk_GetPixmap -- + * + * Creates an in memory drawing surface. + * + * Results: + * Returns a handle to a new pixmap. + * + * Side effects: + * Allocates a new Win32 bitmap. + * + *---------------------------------------------------------------------- + */ + +Pixmap +Tk_GetPixmap(display, d, width, height, depth) + Display* display; + Drawable d; + int width; + int height; + int depth; +{ + TkWinDrawable *newTwdPtr, *twdPtr; + int planes; + Screen *screen; + + display->request++; + + newTwdPtr = (TkWinDrawable*) ckalloc(sizeof(TkWinDrawable)); + newTwdPtr->type = TWD_BITMAP; + newTwdPtr->bitmap.depth = depth; + twdPtr = (TkWinDrawable *)d; + if (twdPtr->type != TWD_BITMAP) { + if (twdPtr->window.winPtr == NULL) { + newTwdPtr->bitmap.colormap = DefaultColormap(display, + DefaultScreen(display)); + } else { + newTwdPtr->bitmap.colormap = twdPtr->window.winPtr->atts.colormap; + } + } else { + newTwdPtr->bitmap.colormap = twdPtr->bitmap.colormap; + } + screen = &display->screens[0]; + planes = 1; + if (depth == screen->root_depth) { + planes = (int) screen->ext_data; + depth /= planes; + } + newTwdPtr->bitmap.handle = CreateBitmap(width, height, planes, depth, NULL); + + if (newTwdPtr->bitmap.handle == NULL) { + ckfree((char *) newTwdPtr); + return None; + } + + return (Pixmap)newTwdPtr; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreePixmap -- + * + * Release the resources associated with a pixmap. + * + * Results: + * None. + * + * Side effects: + * Deletes the bitmap created by Tk_GetPixmap. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreePixmap(display, pixmap) + Display* display; + Pixmap pixmap; +{ + TkWinDrawable *twdPtr = (TkWinDrawable *) pixmap; + + display->request++; + if (twdPtr != NULL) { + DeleteObject(twdPtr->bitmap.handle); + ckfree((char *)twdPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkSetPixmapColormap -- + * + * The following function is a hack used by the photo widget to + * explicitly set the colormap slot of a Pixmap. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkSetPixmapColormap(pixmap, colormap) + Pixmap pixmap; + Colormap colormap; +{ + TkWinDrawable *twdPtr = (TkWinDrawable *)pixmap; + twdPtr->bitmap.colormap = colormap; +} + +/* + *---------------------------------------------------------------------- + * + * XGetGeometry -- + * + * Retrieve the geometry of the given drawable. Note that + * this is a degenerate implementation that only returns the + * size of a pixmap. + * + * Results: + * Returns 0. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +XGetGeometry(display, d, root_return, x_return, y_return, width_return, + height_return, border_width_return, depth_return) + Display* display; + Drawable d; + Window* root_return; + int* x_return; + int* y_return; + unsigned int* width_return; + unsigned int* height_return; + unsigned int* border_width_return; + unsigned int* depth_return; +{ + TkWinDrawable *twdPtr = (TkWinDrawable *)d; + HDC dc; + BITMAPINFO info; + + if ((twdPtr->type != TWD_BITMAP) || (twdPtr->bitmap.handle == NULL)) { + panic("XGetGeometry: invalid pixmap"); + } + dc = GetDC(NULL); + info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + info.bmiHeader.biBitCount = 0; + if (!GetDIBits(dc, twdPtr->bitmap.handle, 0, 0, NULL, &info, + DIB_RGB_COLORS)) { + panic("XGetGeometry: unable to get bitmap size"); + } + ReleaseDC(NULL, dc); + + *width_return = info.bmiHeader.biWidth; + *height_return = info.bmiHeader.biHeight; + return 1; +} diff --git a/win/tkWinPointer.c b/win/tkWinPointer.c new file mode 100644 index 0000000..96661ae --- /dev/null +++ b/win/tkWinPointer.c @@ -0,0 +1,457 @@ +/* + * tkWinPointer.c -- + * + * Windows specific mouse tracking code. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinPointer.c 1.28 97/10/31 08:40:07 + */ + +#include "tkWinInt.h" + +/* + * Check for enter/leave events every MOUSE_TIMER_INTERVAL milliseconds. + */ + +#define MOUSE_TIMER_INTERVAL 250 + +/* + * Declarations of static variables used in this file. + */ + +static int captured = 0; /* 1 if mouse is currently captured. */ +static TkWindow *keyboardWinPtr = NULL; /* Current keyboard grab window. */ +static Tcl_TimerToken mouseTimer; /* Handle to the latest mouse timer. */ +static int mouseTimerSet = 0; /* 1 if the mouse timer is active. */ + +/* + * Forward declarations of procedures used in this file. + */ + +static void MouseTimerProc _ANSI_ARGS_((ClientData clientData)); + +/* + *---------------------------------------------------------------------- + * + * TkWinGetModifierState -- + * + * Return the modifier state as of the last message. + * + * Results: + * Returns the X modifier mask. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkWinGetModifierState() +{ + int state = 0; + + if (GetKeyState(VK_SHIFT) & 0x8000) { + state |= ShiftMask; + } + if (GetKeyState(VK_CONTROL) & 0x8000) { + state |= ControlMask; + } + if (GetKeyState(VK_MENU) & 0x8000) { + state |= Mod2Mask; + } + if (GetKeyState(VK_CAPITAL) & 0x0001) { + state |= LockMask; + } + if (GetKeyState(VK_NUMLOCK) & 0x0001) { + state |= Mod1Mask; + } + if (GetKeyState(VK_SCROLL) & 0x0001) { + state |= Mod3Mask; + } + if (GetKeyState(VK_LBUTTON) & 0x8000) { + state |= Button1Mask; + } + if (GetKeyState(VK_MBUTTON) & 0x8000) { + state |= Button2Mask; + } + if (GetKeyState(VK_RBUTTON) & 0x8000) { + state |= Button3Mask; + } + return state; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_PointerEvent -- + * + * This procedure is called for each pointer-related event. + * It converts the position to root coords and updates the + * global pointer state machine. It also ensures that the + * mouse timer is scheduled. + * + * Results: + * None. + * + * Side effects: + * May queue events and change the grab state. + * + *---------------------------------------------------------------------- + */ + +void +Tk_PointerEvent(hwnd, x, y) + HWND hwnd; /* Window for coords, or NULL for + * the root window. */ + int x, y; /* Coords relative to hwnd, or screen + * if hwnd is NULL. */ +{ + POINT pos; + int state; + Tk_Window tkwin; + + pos.x = x; + pos.y = y; + + /* + * Convert client coords to root coords if we were given a window. + */ + + if (hwnd) { + ClientToScreen(hwnd, &pos); + } + + /* + * If the mouse is captured, Windows will report all pointer + * events to the capture window. So, we need to determine which + * window the mouse is really over and change the event. Note + * that the computed hwnd may point to a window not owned by Tk, + * or a toplevel decorative frame, so tkwin can be NULL. + */ + + if (captured || hwnd == NULL) { + hwnd = WindowFromPoint(pos); + } + tkwin = Tk_HWNDToWindow(hwnd); + + state = TkWinGetModifierState(); + + Tk_UpdatePointer(tkwin, pos.x, pos.y, state); + + if ((captured || tkwin) && !mouseTimerSet) { + mouseTimerSet = 1; + mouseTimer = Tcl_CreateTimerHandler(MOUSE_TIMER_INTERVAL, + MouseTimerProc, NULL); + } +} + +/* + *---------------------------------------------------------------------- + * + * XGrabKeyboard -- + * + * Simulates a keyboard grab by setting the focus. + * + * Results: + * Always returns GrabSuccess. + * + * Side effects: + * Sets the keyboard focus to the specified window. + * + *---------------------------------------------------------------------- + */ + +int +XGrabKeyboard(display, grab_window, owner_events, pointer_mode, + keyboard_mode, time) + Display* display; + Window grab_window; + Bool owner_events; + int pointer_mode; + int keyboard_mode; + Time time; +{ + keyboardWinPtr = TkWinGetWinPtr(grab_window); + return GrabSuccess; +} + +/* + *---------------------------------------------------------------------- + * + * XUngrabKeyboard -- + * + * Releases the simulated keyboard grab. + * + * Results: + * None. + * + * Side effects: + * Sets the keyboard focus back to the value before the grab. + * + *---------------------------------------------------------------------- + */ + +void +XUngrabKeyboard(display, time) + Display* display; + Time time; +{ + keyboardWinPtr = NULL; +} + +/* + *---------------------------------------------------------------------- + * + * MouseTimerProc -- + * + * Check the current mouse position and look for enter/leave + * events. + * + * Results: + * None. + * + * Side effects: + * May schedule a new timer and/or generate enter/leave events. + * + *---------------------------------------------------------------------- + */ + +void +MouseTimerProc(clientData) + ClientData clientData; +{ + POINT pos; + + mouseTimerSet = 0; + + /* + * Get the current mouse position and window. Don't do anything + * if the mouse hasn't moved since the last time we looked. + */ + + GetCursorPos(&pos); + Tk_PointerEvent(NULL, pos.x, pos.y); +} + +/* + *---------------------------------------------------------------------- + * + * TkGetPointerCoords -- + * + * Fetch the position of the mouse pointer. + * + * Results: + * *xPtr and *yPtr are filled in with the root coordinates + * of the mouse pointer for the display. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkGetPointerCoords(tkwin, xPtr, yPtr) + Tk_Window tkwin; /* Window that identifies screen on which + * lookup is to be done. */ + int *xPtr, *yPtr; /* Store pointer coordinates here. */ +{ + POINT point; + + GetCursorPos(&point); + *xPtr = point.x; + *yPtr = point.y; +} + +/* + *---------------------------------------------------------------------- + * + * XQueryPointer -- + * + * Check the current state of the mouse. This is not a complete + * implementation of this function. It only computes the root + * coordinates and the current mask. + * + * Results: + * Sets root_x_return, root_y_return, and mask_return. Returns + * true on success. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Bool +XQueryPointer(display, w, root_return, child_return, root_x_return, + root_y_return, win_x_return, win_y_return, mask_return) + Display* display; + Window w; + Window* root_return; + Window* child_return; + int* root_x_return; + int* root_y_return; + int* win_x_return; + int* win_y_return; + unsigned int* mask_return; +{ + display->request++; + TkGetPointerCoords(NULL, root_x_return, root_y_return); + *mask_return = TkWinGetModifierState(); + return True; +} + +/* + *---------------------------------------------------------------------- + * + * XGetInputFocus -- + * + * Retrieves the current keyboard focus window. + * + * Results: + * Returns the current focus window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +XGetInputFocus(display, focus_return, revert_to_return) + Display *display; + Window *focus_return; + int *revert_to_return; +{ + Tk_Window tkwin = Tk_HWNDToWindow(GetFocus()); + *focus_return = tkwin ? Tk_WindowId(tkwin) : None; + *revert_to_return = RevertToParent; + display->request++; +} + +/* + *---------------------------------------------------------------------- + * + * XSetInputFocus -- + * + * Set the current focus window. + * + * Results: + * None. + * + * Side effects: + * Changes the keyboard focus and causes the selected window to + * be activated. + * + *---------------------------------------------------------------------- + */ + +void +XSetInputFocus(display, focus, revert_to, time) + Display* display; + Window focus; + int revert_to; + Time time; +{ + display->request++; + if (focus != None) { + SetFocus(Tk_GetHWND(focus)); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpChangeFocus -- + * + * This procedure is invoked to move the system focus from + * one window to another. + * + * Results: + * The return value is the serial number of the command that + * changed the focus. It may be needed by the caller to filter + * out focus change events that were queued before the command. + * If the procedure doesn't actually change the focus then + * it returns 0. + * + * Side effects: + * The official Windows focus window changes; the application's focus + * window isn't changed by this procedure. + * + *---------------------------------------------------------------------- + */ + +int +TkpChangeFocus(winPtr, force) + TkWindow *winPtr; /* Window that is to receive the X focus. */ + int force; /* Non-zero means claim the focus even + * if it didn't originally belong to + * topLevelPtr's application. */ +{ + TkDisplay *dispPtr = winPtr->dispPtr; + Window focusWindow; + int dummy, serial; + TkWindow *winPtr2; + + if (!force) { + XGetInputFocus(dispPtr->display, &focusWindow, &dummy); + winPtr2 = (TkWindow *) Tk_IdToWindow(dispPtr->display, focusWindow); + if ((winPtr2 == NULL) || (winPtr2->mainPtr != winPtr->mainPtr)) { + return 0; + } + } + + if (winPtr->window == None) { + panic("ChangeXFocus got null X window"); + } + XSetInputFocus(dispPtr->display, winPtr->window, RevertToParent, + CurrentTime); + + /* + * Remember the current serial number for the X server and issue + * a dummy server request. This marks the position at which we + * changed the focus, so we can distinguish FocusIn and FocusOut + * events on either side of the mark. + */ + + serial = NextRequest(winPtr->display); + XNoOp(winPtr->display); + return serial; +} + +/* + *---------------------------------------------------------------------- + * + * TkpSetCapture -- + * + * This function captures the mouse so that all future events + * will be reported to this window, even if the mouse is outside + * the window. If the specified window is NULL, then the mouse + * is released. + * + * Results: + * None. + * + * Side effects: + * Sets the capture flag and captures the mouse. + * + *---------------------------------------------------------------------- + */ + +void +TkpSetCapture(winPtr) + TkWindow *winPtr; /* Capture window, or NULL. */ +{ + if (winPtr) { + SetCapture(Tk_GetHWND(Tk_WindowId(winPtr))); + captured = 1; + } else { + captured = 0; + ReleaseCapture(); + } +} diff --git a/win/tkWinPort.h b/win/tkWinPort.h new file mode 100644 index 0000000..1f755a7 --- /dev/null +++ b/win/tkWinPort.h @@ -0,0 +1,117 @@ +/* + * tkWinPort.h -- + * + * This header file handles porting issues that occur because of + * differences between Windows and Unix. It should be the only + * file that contains #ifdefs to handle different flavors of OS. + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinPort.h 1.25 97/04/21 17:08:42 + */ + +#ifndef _WINPORT +#define _WINPORT + +#include <X11/Xlib.h> +#include <X11/cursorfont.h> +#include <X11/keysym.h> +#include <X11/Xatom.h> +#include <X11/Xutil.h> + +#include <malloc.h> +#include <errno.h> +#include <ctype.h> +#include <math.h> +#include <stdlib.h> +#include <string.h> +#include <limits.h> +#include <fcntl.h> +#include <io.h> +#include <sys/stat.h> +#include <time.h> + +#ifdef _MSC_VER +# define hypot _hypot +#endif /* _MSC_VER */ + +#define strncasecmp strnicmp +#define strcasecmp stricmp + +#define NBBY 8 + +#define OPEN_MAX 32 + +/* + * The following define causes Tk to use its internal keysym hash table + */ + +#define REDO_KEYSYM_LOOKUP + +/* + * The following macro checks to see whether there is buffered + * input data available for a stdio FILE. + */ + +#ifdef _MSC_VER +# define TK_READ_DATA_PENDING(f) ((f)->_cnt > 0) +#else /* _MSC_VER */ +# define TK_READ_DATA_PENDING(f) ((f)->level > 0) +#endif /* _MSC_VER */ + +/* + * The following stubs implement various calls that don't do anything + * under Windows. + */ + +#define TkFreeWindowId(dispPtr,w) +#define TkInitXId(dispPtr) +#define TkpCmapStressed(tkwin,colormap) (0) +#define XFlush(display) +#define XGrabServer(display) +#define XUngrabServer(display) +#define TkpSync(display) + +/* + * The following functions are implemented as macros under Windows. + */ + +#define XFree(data) {if ((data) != NULL) ckfree((char *) (data));} +#define XNoOp(display) {display->request++;} +#define XSynchronize(display, bool) {display->request++;} +#define XSync(display, bool) {display->request++;} +#define XVisualIDFromVisual(visual) (visual->visualid) + +/* + * The following Tk functions are implemented as macros under Windows. + */ + +#define TkGetNativeProlog(interp) TkGetProlog(interp) +#define TkpGetPixel(p) (((((p)->red >> 8) & 0xff) \ + | ((p)->green & 0xff00) | (((p)->blue << 8) & 0xff0000)) | 0x20000000) + +/* + * These calls implement native bitmaps which are not currently + * supported under Windows. The macros eliminate the calls. + */ + +#define TkpDefineNativeBitmaps() +#define TkpCreateNativeBitmap(display, source) None +#define TkpGetNativeAppBitmap(display, name, w, h) None + +/* + * Define timezone for gettimeofday. + */ + +struct timezone { + int tz_minuteswest; + int tz_dsttime; +}; + +extern int gettimeofday(struct timeval *, struct timezone *); +EXTERN void panic _ANSI_ARGS_(TCL_VARARGS(char *,format)); + +#endif /* _WINPORT */ diff --git a/win/tkWinRegion.c b/win/tkWinRegion.c new file mode 100644 index 0000000..3303022 --- /dev/null +++ b/win/tkWinRegion.c @@ -0,0 +1,179 @@ +/* + * tkWinRegion.c -- + * + * Tk Region emulation code. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinRegion.c 1.7 96/05/03 11:05:54 + */ + +#include "tkWinInt.h" + + +/* + *---------------------------------------------------------------------- + * + * TkCreateRegion -- + * + * Construct an empty region. + * + * Results: + * Returns a new region handle. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkRegion +TkCreateRegion() +{ + RECT rect; + memset(&rect, 0, sizeof(RECT)); + return (TkRegion) CreateRectRgnIndirect(&rect); +} + +/* + *---------------------------------------------------------------------- + * + * TkDestroyRegion -- + * + * Destroy the specified region. + * + * Results: + * None. + * + * Side effects: + * Frees the storage associated with the specified region. + * + *---------------------------------------------------------------------- + */ + +void +TkDestroyRegion(r) + TkRegion r; +{ + DeleteObject((HRGN) r); +} + +/* + *---------------------------------------------------------------------- + * + * TkClipBox -- + * + * Computes the bounding box of a region. + * + * Results: + * Sets rect_return to the bounding box of the region. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkClipBox(r, rect_return) + TkRegion r; + XRectangle* rect_return; +{ + RECT rect; + GetRgnBox((HRGN)r, &rect); + rect_return->x = (short) rect.left; + rect_return->y = (short) rect.top; + rect_return->width = (short) (rect.right - rect.left); + rect_return->height = (short) (rect.bottom - rect.top); +} + +/* + *---------------------------------------------------------------------- + * + * TkIntersectRegion -- + * + * Compute the intersection of two regions. + * + * Results: + * Returns the result in the dr_return region. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkIntersectRegion(sra, srb, dr_return) + TkRegion sra; + TkRegion srb; + TkRegion dr_return; +{ + CombineRgn((HRGN) dr_return, (HRGN) sra, (HRGN) srb, RGN_AND); +} + +/* + *---------------------------------------------------------------------- + * + * TkUnionRectWithRegion -- + * + * Create the union of a source region and a rectangle. + * + * Results: + * Returns the result in the dr_return region. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkUnionRectWithRegion(rectangle, src_region, dest_region_return) + XRectangle* rectangle; + TkRegion src_region; + TkRegion dest_region_return; +{ + HRGN rectRgn = CreateRectRgn(rectangle->x, rectangle->y, + rectangle->x + rectangle->width, rectangle->y + rectangle->height); + CombineRgn((HRGN) dest_region_return, (HRGN) src_region, + (HRGN) rectRgn, RGN_OR); + DeleteObject(rectRgn); +} + +/* + *---------------------------------------------------------------------- + * + * TkRectInRegion -- + * + * Test whether a given rectangle overlaps with a region. + * + * Results: + * Returns RectanglePart or RectangleOut. Note that this is + * not a complete implementation since it doesn't test for + * RectangleIn. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkRectInRegion(r, x, y, width, height) + TkRegion r; + int x; + int y; + unsigned int width; + unsigned int height; +{ + RECT rect; + rect.top = y; + rect.left = x; + rect.bottom = y+height; + rect.right = x+width; + return RectInRegion((HRGN)r, &rect) ? RectanglePart : RectangleOut; +} diff --git a/win/tkWinScrlbr.c b/win/tkWinScrlbr.c new file mode 100644 index 0000000..6c1a664 --- /dev/null +++ b/win/tkWinScrlbr.c @@ -0,0 +1,745 @@ +/* + * tkWinScrollbar.c -- + * + * This file implements the Windows specific portion of the scrollbar + * widget. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinScrlbr.c 1.19 97/08/13 17:37:49 + */ + +#include "tkWinInt.h" +#include "tkScrollbar.h" + + +/* + * The following constant is used to specify the maximum scroll position. + * This value is limited by the Win32 API to either 16-bits or 32-bits, + * depending on the context. For now we'll just use a value small + * enough to fit in 16-bits, but which gives us 4-digits of precision. + */ + +#define MAX_SCROLL 10000 + +/* + * Declaration of Windows specific scrollbar structure. + */ + +typedef struct WinScrollbar { + TkScrollbar info; /* Generic scrollbar info. */ + WNDPROC oldProc; /* Old window procedure. */ + int lastVertical; /* 1 if was vertical at last refresh. */ + HWND hwnd; /* Current window handle. */ + int winFlags; /* Various flags; see below. */ +} WinScrollbar; + +/* + * Flag bits for native scrollbars: + * + * IN_MODAL_LOOP: Non-zero means this scrollbar is in the middle + * of a modal loop. + * ALREADY_DEAD: Non-zero means this scrollbar has been + * destroyed, but has not been cleaned up. + */ + +#define IN_MODAL_LOOP 1 +#define ALREADY_DEAD 2 + +/* + * Cached system metrics used to determine scrollbar geometry. + */ + +static int initialized = 0; +static int hArrowWidth, hThumb; /* Horizontal control metrics. */ +static int vArrowWidth, vArrowHeight, vThumb; /* Vertical control metrics. */ + +/* + * This variable holds the default width for a scrollbar in string + * form for use in a Tk_ConfigSpec. + */ + +static char defWidth[8]; + +/* + * Declarations for functions defined in this file. + */ + +static Window CreateProc _ANSI_ARGS_((Tk_Window tkwin, + Window parent, ClientData instanceData)); +static void ModalLoopProc _ANSI_ARGS_((Tk_Window tkwin, + XEvent *eventPtr)); +static int ScrollbarBindProc _ANSI_ARGS_((ClientData clientData, + Tcl_Interp *interp, XEvent *eventPtr, + Tk_Window tkwin, KeySym keySym)); +static LRESULT CALLBACK ScrollbarProc _ANSI_ARGS_((HWND hwnd, UINT message, + WPARAM wParam, LPARAM lParam)); +static void UpdateScrollbar _ANSI_ARGS_(( + WinScrollbar *scrollPtr)); +static void UpdateScrollbarMetrics _ANSI_ARGS_((void)); + +/* + * The class procedure table for the scrollbar widget. + */ + +TkClassProcs tkpScrollbarProcs = { + CreateProc, /* createProc */ + NULL, /* geometryProc */ + ModalLoopProc, /* modalProc */ +}; + + +/* + *---------------------------------------------------------------------- + * + * TkpCreateScrollbar -- + * + * Allocate a new TkScrollbar structure. + * + * Results: + * Returns a newly allocated TkScrollbar structure. + * + * Side effects: + * Registers an event handler for the widget. + * + *---------------------------------------------------------------------- + */ + +TkScrollbar * +TkpCreateScrollbar(tkwin) + Tk_Window tkwin; +{ + WinScrollbar *scrollPtr; + TkWindow *winPtr = (TkWindow *)tkwin; + + if (!initialized) { + UpdateScrollbarMetrics(); + initialized = 1; + } + + scrollPtr = (WinScrollbar *) ckalloc(sizeof(WinScrollbar)); + scrollPtr->winFlags = 0; + scrollPtr->hwnd = NULL; + + Tk_CreateEventHandler(tkwin, + ExposureMask|StructureNotifyMask|FocusChangeMask, + TkScrollbarEventProc, (ClientData) scrollPtr); + + if (!Tcl_GetAssocData(winPtr->mainPtr->interp, "TkScrollbar", NULL)) { + Tcl_SetAssocData(winPtr->mainPtr->interp, "TkScrollbar", NULL, + (ClientData)1); + TkCreateBindingProcedure(winPtr->mainPtr->interp, + winPtr->mainPtr->bindingTable, + (ClientData)Tk_GetUid("Scrollbar"), "<ButtonPress>", + ScrollbarBindProc, NULL, NULL); + } + + return (TkScrollbar*) scrollPtr; +} + +/* + *---------------------------------------------------------------------- + * + * UpdateScrollbar -- + * + * This function updates the position and size of the scrollbar + * thumb based on the current settings. + * + * Results: + * None. + * + * Side effects: + * Moves the thumb. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateScrollbar(scrollPtr) + WinScrollbar *scrollPtr; +{ + SCROLLINFO scrollInfo; + double thumbSize; + + /* + * Update the current scrollbar position and shape. + */ + + scrollInfo.fMask = SIF_PAGE | SIF_POS | SIF_RANGE; + scrollInfo.cbSize = sizeof(scrollInfo); + scrollInfo.nMin = 0; + scrollInfo.nMax = MAX_SCROLL; + thumbSize = (scrollPtr->info.lastFraction - scrollPtr->info.firstFraction); + if (tkpIsWin32s) { + scrollInfo.nPage = 0; + } else { + scrollInfo.nPage = ((UINT) (thumbSize * (double) MAX_SCROLL)) + 1; + } + if (thumbSize < 1.0) { + scrollInfo.nPos = (int) + ((scrollPtr->info.firstFraction / (1.0-thumbSize)) + * (MAX_SCROLL - (scrollInfo.nPage - 1))); + } else { + scrollInfo.nPos = 0; + } + SetScrollInfo(scrollPtr->hwnd, SB_CTL, &scrollInfo, TRUE); +} + +/* + *---------------------------------------------------------------------- + * + * CreateProc -- + * + * This function creates a new Scrollbar control, subclasses + * the instance, and generates a new Window object. + * + * Results: + * Returns the newly allocated Window object, or None on failure. + * + * Side effects: + * Causes a new Scrollbar control to come into existence. + * + *---------------------------------------------------------------------- + */ + +static Window +CreateProc(tkwin, parentWin, instanceData) + Tk_Window tkwin; /* Token for window. */ + Window parentWin; /* Parent of new window. */ + ClientData instanceData; /* Scrollbar instance data. */ +{ + DWORD style; + Window window; + HWND parent; + TkWindow *winPtr; + WinScrollbar *scrollPtr = (WinScrollbar *)instanceData; + + parent = Tk_GetHWND(parentWin); + + if (scrollPtr->info.vertical) { + style = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS + | SBS_VERT | SBS_RIGHTALIGN; + } else { + style = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS + | SBS_HORZ | SBS_BOTTOMALIGN; + } + + scrollPtr->hwnd = CreateWindow("SCROLLBAR", NULL, style, + Tk_X(tkwin), Tk_Y(tkwin), Tk_Width(tkwin), Tk_Height(tkwin), + parent, NULL, Tk_GetHINSTANCE(), NULL); + + /* + * Ensure new window is inserted into the stacking order at the correct + * place. + */ + + SetWindowPos(scrollPtr->hwnd, HWND_TOP, 0, 0, 0, 0, + SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); + + for (winPtr = ((TkWindow*)tkwin)->nextPtr; winPtr != NULL; + winPtr = winPtr->nextPtr) { + if ((winPtr->window != None) && !(winPtr->flags & TK_TOP_LEVEL)) { + TkWinSetWindowPos(scrollPtr->hwnd, Tk_GetHWND(winPtr->window), + Below); + break; + } + } + + scrollPtr->lastVertical = scrollPtr->info.vertical; + scrollPtr->oldProc = (WNDPROC)SetWindowLong(scrollPtr->hwnd, GWL_WNDPROC, + (DWORD) ScrollbarProc); + window = Tk_AttachHWND(tkwin, scrollPtr->hwnd); + + UpdateScrollbar(scrollPtr); + return window; +} + +/* + *-------------------------------------------------------------- + * + * TkpDisplayScrollbar -- + * + * This procedure redraws the contents of a scrollbar window. + * It is invoked as a do-when-idle handler, so it only runs + * when there's nothing else for the application to do. + * + * Results: + * None. + * + * Side effects: + * Information appears on the screen. + * + *-------------------------------------------------------------- + */ + +void +TkpDisplayScrollbar(clientData) + ClientData clientData; /* Information about window. */ +{ + WinScrollbar *scrollPtr = (WinScrollbar *) clientData; + Tk_Window tkwin = scrollPtr->info.tkwin; + + scrollPtr->info.flags &= ~REDRAW_PENDING; + if ((tkwin == NULL) || !Tk_IsMapped(tkwin)) { + return; + } + + /* + * Destroy and recreate the scrollbar control if the orientation + * has changed. + */ + + if (scrollPtr->lastVertical != scrollPtr->info.vertical) { + HWND hwnd = Tk_GetHWND(Tk_WindowId(tkwin)); + + SetWindowLong(hwnd, GWL_WNDPROC, (DWORD) scrollPtr->oldProc); + DestroyWindow(hwnd); + + CreateProc(tkwin, Tk_WindowId(Tk_Parent(tkwin)), + (ClientData) scrollPtr); + } else { + UpdateScrollbar(scrollPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpDestroyScrollbar -- + * + * Free data structures associated with the scrollbar control. + * + * Results: + * None. + * + * Side effects: + * Restores the default control state. + * + *---------------------------------------------------------------------- + */ + +void +TkpDestroyScrollbar(scrollPtr) + TkScrollbar *scrollPtr; +{ + WinScrollbar *winScrollPtr = (WinScrollbar *)scrollPtr; + HWND hwnd = winScrollPtr->hwnd; + if (hwnd) { + SetWindowLong(hwnd, GWL_WNDPROC, (DWORD) winScrollPtr->oldProc); + if (winScrollPtr->winFlags & IN_MODAL_LOOP) { + ((TkWindow *)scrollPtr->tkwin)->flags |= TK_DONT_DESTROY_WINDOW; + SetParent(hwnd, NULL); + } + } + winScrollPtr->winFlags |= ALREADY_DEAD; +} + +/* + *---------------------------------------------------------------------- + * + * UpdateScrollbarMetrics -- + * + * This function retrieves the current system metrics for a + * scrollbar. + * + * Results: + * None. + * + * Side effects: + * Updates the geometry cache info for all scrollbars. + * + *---------------------------------------------------------------------- + */ + +void +UpdateScrollbarMetrics() +{ + Tk_ConfigSpec *specPtr; + + hArrowWidth = GetSystemMetrics(SM_CXHSCROLL); + hThumb = GetSystemMetrics(SM_CXHTHUMB); + vArrowWidth = GetSystemMetrics(SM_CXVSCROLL); + vArrowHeight = GetSystemMetrics(SM_CYVSCROLL); + vThumb = GetSystemMetrics(SM_CYVTHUMB); + + sprintf(defWidth, "%d", vArrowWidth); + for (specPtr = tkpScrollbarConfigSpecs; specPtr->type != TK_CONFIG_END; + specPtr++) { + if (specPtr->offset == Tk_Offset(TkScrollbar, width)) { + specPtr->defValue = defWidth; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkpComputeScrollbarGeometry -- + * + * After changes in a scrollbar's size or configuration, this + * procedure recomputes various geometry information used in + * displaying the scrollbar. + * + * Results: + * None. + * + * Side effects: + * The scrollbar will be displayed differently. + * + *---------------------------------------------------------------------- + */ + +void +TkpComputeScrollbarGeometry(scrollPtr) + register TkScrollbar *scrollPtr; /* Scrollbar whose geometry may + * have changed. */ +{ + int fieldLength, minThumbSize; + + /* + * Windows doesn't use focus rings on scrollbars, but we still + * perform basic sanity checks to appease backwards compatibility. + */ + + if (scrollPtr->highlightWidth < 0) { + scrollPtr->highlightWidth = 0; + } + + if (scrollPtr->vertical) { + scrollPtr->arrowLength = vArrowHeight; + fieldLength = Tk_Height(scrollPtr->tkwin); + minThumbSize = vThumb; + } else { + scrollPtr->arrowLength = hArrowWidth; + fieldLength = Tk_Width(scrollPtr->tkwin); + minThumbSize = hThumb; + } + fieldLength -= 2*scrollPtr->arrowLength; + if (fieldLength < 0) { + fieldLength = 0; + } + scrollPtr->sliderFirst = (int) ((double)fieldLength + * scrollPtr->firstFraction); + scrollPtr->sliderLast = (int) ((double)fieldLength + * scrollPtr->lastFraction); + + /* + * Adjust the slider so that some piece of it is always + * displayed in the scrollbar and so that it has at least + * a minimal width (so it can be grabbed with the mouse). + */ + + if (scrollPtr->sliderFirst > fieldLength) { + scrollPtr->sliderFirst = fieldLength; + } + if (scrollPtr->sliderFirst < 0) { + scrollPtr->sliderFirst = 0; + } + if (scrollPtr->sliderLast < (scrollPtr->sliderFirst + + minThumbSize)) { + scrollPtr->sliderLast = scrollPtr->sliderFirst + minThumbSize; + } + if (scrollPtr->sliderLast > fieldLength) { + scrollPtr->sliderLast = fieldLength; + } + scrollPtr->sliderFirst += scrollPtr->arrowLength; + scrollPtr->sliderLast += scrollPtr->arrowLength; + + /* + * Register the desired geometry for the window (leave enough space + * for the two arrows plus a minimum-size slider, plus border around + * the whole window, if any). Then arrange for the window to be + * redisplayed. + */ + + if (scrollPtr->vertical) { + Tk_GeometryRequest(scrollPtr->tkwin, + scrollPtr->width, 2*scrollPtr->arrowLength + minThumbSize); + } else { + Tk_GeometryRequest(scrollPtr->tkwin, + 2*scrollPtr->arrowLength + minThumbSize, scrollPtr->width); + } + Tk_SetInternalBorder(scrollPtr->tkwin, 0); +} + +/* + *---------------------------------------------------------------------- + * + * ScrollbarProc -- + * + * This function is call by Windows whenever an event occurs on + * a scrollbar control created by Tk. + * + * Results: + * Standard Windows return value. + * + * Side effects: + * May generate events. + * + *---------------------------------------------------------------------- + */ + +static LRESULT CALLBACK +ScrollbarProc(hwnd, message, wParam, lParam) + HWND hwnd; + UINT message; + WPARAM wParam; + LPARAM lParam; +{ + LRESULT result; + POINT point; + WinScrollbar *scrollPtr; + Tk_Window tkwin = Tk_HWNDToWindow(hwnd); + + if (tkwin == NULL) { + panic("ScrollbarProc called on an invalid HWND"); + } + scrollPtr = (WinScrollbar *)((TkWindow*)tkwin)->instanceData; + + switch(message) { + case WM_HSCROLL: + case WM_VSCROLL: { + Tcl_Interp *interp; + Tcl_DString cmdString; + int command = LOWORD(wParam); + int code; + + GetCursorPos(&point); + Tk_TranslateWinEvent(NULL, WM_MOUSEMOVE, 0, + MAKELPARAM(point.x, point.y), &result); + + if (command == SB_ENDSCROLL) { + return 0; + } + + /* + * Bail out immediately if there isn't a command to invoke. + */ + + if (scrollPtr->info.commandSize == 0) { + Tcl_ServiceAll(); + return 0; + } + + Tcl_DStringInit(&cmdString); + Tcl_DStringAppend(&cmdString, scrollPtr->info.command, + scrollPtr->info.commandSize); + + if (command == SB_LINELEFT || command == SB_LINERIGHT) { + Tcl_DStringAppendElement(&cmdString, "scroll"); + Tcl_DStringAppendElement(&cmdString, + (command == SB_LINELEFT ) ? "-1" : "1"); + Tcl_DStringAppendElement(&cmdString, "units"); + } else if (command == SB_PAGELEFT || command == SB_PAGERIGHT) { + Tcl_DStringAppendElement(&cmdString, "scroll"); + Tcl_DStringAppendElement(&cmdString, + (command == SB_PAGELEFT ) ? "-1" : "1"); + Tcl_DStringAppendElement(&cmdString, "pages"); + } else { + char valueString[TCL_DOUBLE_SPACE]; + double pos = 0.0; + switch (command) { + case SB_THUMBPOSITION: + pos = ((double)HIWORD(wParam)) / MAX_SCROLL; + break; + + case SB_THUMBTRACK: + pos = ((double)HIWORD(wParam)) / MAX_SCROLL; + break; + + case SB_TOP: + pos = 0.0; + break; + + case SB_BOTTOM: + pos = 1.0; + break; + } + sprintf(valueString, "%g", pos); + Tcl_DStringAppendElement(&cmdString, "moveto"); + Tcl_DStringAppendElement(&cmdString, valueString); + } + + interp = scrollPtr->info.interp; + code = Tcl_GlobalEval(interp, cmdString.string); + if (code != TCL_OK && code != TCL_CONTINUE && code != TCL_BREAK) { + Tcl_AddErrorInfo(interp, "\n (scrollbar command)"); + Tcl_BackgroundError(interp); + } + Tcl_DStringFree(&cmdString); + + Tcl_ServiceAll(); + return 0; + } + + default: + if (Tk_TranslateWinEvent(hwnd, message, wParam, lParam, &result)) { + return result; + } + } + return CallWindowProc(scrollPtr->oldProc, hwnd, message, wParam, lParam); +} + +/* + *---------------------------------------------------------------------- + * + * TkpConfigureScrollbar -- + * + * This procedure is called after the generic code has finished + * processing configuration options, in order to configure + * platform specific options. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpConfigureScrollbar(scrollPtr) + register TkScrollbar *scrollPtr; /* Information about widget; may or + * may not already have values for + * some fields. */ +{ +} + +/* + *-------------------------------------------------------------- + * + * ScrollbarBindProc -- + * + * This procedure is invoked when the default <ButtonPress> + * binding on the Scrollbar bind tag fires. + * + * Results: + * None. + * + * Side effects: + * The event enters a modal loop. + * + *-------------------------------------------------------------- + */ + +static int +ScrollbarBindProc(clientData, interp, eventPtr, tkwin, keySym) + ClientData clientData; + Tcl_Interp *interp; + XEvent *eventPtr; + Tk_Window tkwin; + KeySym keySym; +{ + TkWindow *winPtr = (TkWindow*)tkwin; + if (eventPtr->type == ButtonPress) { + winPtr->flags |= TK_DEFER_MODAL; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ModalLoopProc -- + * + * This function is invoked at the end of the event processing + * whenever the ScrollbarBindProc has been invoked for a ButtonPress + * event. + * + * Results: + * None. + * + * Side effects: + * Enters a modal loop. + * + *---------------------------------------------------------------------- + */ + +static void +ModalLoopProc(tkwin, eventPtr) + Tk_Window tkwin; + XEvent *eventPtr; +{ + TkWindow *winPtr = (TkWindow*)tkwin; + WinScrollbar *scrollPtr = (WinScrollbar *) winPtr->instanceData; + int oldMode; + + Tcl_Preserve((ClientData)scrollPtr); + scrollPtr->winFlags |= IN_MODAL_LOOP; + oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); + TkWinResendEvent(scrollPtr->oldProc, scrollPtr->hwnd, eventPtr); + (void) Tcl_SetServiceMode(oldMode); + scrollPtr->winFlags &= ~IN_MODAL_LOOP; + if (scrollPtr->hwnd && scrollPtr->winFlags & ALREADY_DEAD) { + DestroyWindow(scrollPtr->hwnd); + } + Tcl_Release((ClientData)scrollPtr); +} + +/* + *-------------------------------------------------------------- + * + * TkpScrollbarPosition -- + * + * Determine the scrollbar element corresponding to a + * given position. + * + * Results: + * One of TOP_ARROW, TOP_GAP, etc., indicating which element + * of the scrollbar covers the position given by (x, y). If + * (x,y) is outside the scrollbar entirely, then OUTSIDE is + * returned. + * + * Side effects: + * None. + * + *-------------------------------------------------------------- + */ + +int +TkpScrollbarPosition(scrollPtr, x, y) + register TkScrollbar *scrollPtr; /* Scrollbar widget record. */ + int x, y; /* Coordinates within scrollPtr's + * window. */ +{ + int length, width, tmp; + + if (scrollPtr->vertical) { + length = Tk_Height(scrollPtr->tkwin); + width = Tk_Width(scrollPtr->tkwin); + } else { + tmp = x; + x = y; + y = tmp; + length = Tk_Width(scrollPtr->tkwin); + width = Tk_Height(scrollPtr->tkwin); + } + + if ((x < scrollPtr->inset) || (x >= (width - scrollPtr->inset)) + || (y < scrollPtr->inset) || (y >= (length - scrollPtr->inset))) { + return OUTSIDE; + } + + /* + * All of the calculations in this procedure mirror those in + * TkpDisplayScrollbar. Be sure to keep the two consistent. + */ + + if (y < (scrollPtr->inset + scrollPtr->arrowLength)) { + return TOP_ARROW; + } + if (y < scrollPtr->sliderFirst) { + return TOP_GAP; + } + if (y < scrollPtr->sliderLast) { + return SLIDER; + } + if (y >= (length - (scrollPtr->arrowLength + scrollPtr->inset))) { + return BOTTOM_ARROW; + } + return BOTTOM_GAP; +} diff --git a/win/tkWinSend.c b/win/tkWinSend.c new file mode 100644 index 0000000..6d12ed4 --- /dev/null +++ b/win/tkWinSend.c @@ -0,0 +1,86 @@ +/* + * tkWinSend.c -- + * + * This file provides procedures that implement the "send" + * command, allowing commands to be passed from interpreter + * to interpreter. + * + * Copyright (c) 1997 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinSend.c 1.4 97/06/10 09:39:50 + */ + +#include "tkPort.h" +#include "tkInt.h" + + +/* + *-------------------------------------------------------------- + * + * Tk_SetAppName -- + * + * This procedure is called to associate an ASCII name with a Tk + * application. If the application has already been named, the + * name replaces the old one. + * + * Results: + * The return value is the name actually given to the application. + * This will normally be the same as name, but if name was already + * in use for an application then a name of the form "name #2" will + * be chosen, with a high enough number to make the name unique. + * + * Side effects: + * Registration info is saved, thereby allowing the "send" command + * to be used later to invoke commands in the application. In + * addition, the "send" command is created in the application's + * interpreter. The registration will be removed automatically + * if the interpreter is deleted or the "send" command is removed. + * + *-------------------------------------------------------------- + */ + +char * +Tk_SetAppName(tkwin, name) + Tk_Window tkwin; /* Token for any window in the application + * to be named: it is just used to identify + * the application and the display. */ + char *name; /* The name that will be used to + * refer to the interpreter in later + * "send" commands. Must be globally + * unique. */ +{ + return name; +} + +/* + *---------------------------------------------------------------------- + * + * TkGetInterpNames -- + * + * This procedure is invoked to fetch a list of all the + * interpreter names currently registered for the display + * of a particular window. + * + * Results: + * A standard Tcl return value. Interp->result will be set + * to hold a list of all the interpreter names defined for + * tkwin's display. If an error occurs, then TCL_ERROR + * is returned and interp->result will hold an error message. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkGetInterpNames(interp, tkwin) + Tcl_Interp *interp; /* Interpreter for returning a result. */ + Tk_Window tkwin; /* Window whose display is to be used + * for the lookup. */ +{ + return TCL_OK; +} diff --git a/win/tkWinWindow.c b/win/tkWinWindow.c new file mode 100644 index 0000000..2b8eb41 --- /dev/null +++ b/win/tkWinWindow.c @@ -0,0 +1,796 @@ +/* + * tkWinWindow.c -- + * + * Xlib emulation routines for Windows related to creating, + * displaying and destroying windows. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinWindow.c 1.23 97/07/01 18:14:13 + */ + +#include "tkWinInt.h" + +/* + * The windowTable maps from HWND to Tk_Window handles. + */ + +static Tcl_HashTable windowTable; + +/* + * Have statics in this module been initialized? + */ + +static int initialized = 0; + +/* + * Forward declarations for procedures defined in this file: + */ + +static void NotifyVisibility _ANSI_ARGS_((XEvent *eventPtr, + TkWindow *winPtr)); +static void StackWindow _ANSI_ARGS_((Window w, Window sibling, + int stack_mode)); + +/* + *---------------------------------------------------------------------- + * + * Tk_AttachHWND -- + * + * This function binds an HWND and a reflection procedure to + * the specified Tk_Window. + * + * Results: + * Returns an X Window that encapsulates the HWND. + * + * Side effects: + * May allocate a new X Window. Also enters the HWND into the + * global window table. + * + *---------------------------------------------------------------------- + */ + +Window +Tk_AttachHWND(tkwin, hwnd) + Tk_Window tkwin; + HWND hwnd; +{ + int new; + Tcl_HashEntry *entryPtr; + TkWinDrawable *twdPtr = (TkWinDrawable *) Tk_WindowId(tkwin); + + if (!initialized) { + Tcl_InitHashTable(&windowTable, TCL_ONE_WORD_KEYS); + initialized = 1; + } + + /* + * Allocate a new drawable if necessary. Otherwise, remove the + * previous HWND from from the window table. + */ + + if (twdPtr == NULL) { + twdPtr = (TkWinDrawable*) ckalloc(sizeof(TkWinDrawable)); + twdPtr->type = TWD_WINDOW; + twdPtr->window.winPtr = (TkWindow *) tkwin; + } else if (twdPtr->window.handle != NULL) { + entryPtr = Tcl_FindHashEntry(&windowTable, + (char *)twdPtr->window.handle); + Tcl_DeleteHashEntry(entryPtr); + } + + /* + * Insert the new HWND into the window table. + */ + + twdPtr->window.handle = hwnd; + entryPtr = Tcl_CreateHashEntry(&windowTable, (char *)hwnd, &new); + Tcl_SetHashValue(entryPtr, (ClientData)tkwin); + + return (Window)twdPtr; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_HWNDToWindow -- + * + * This function retrieves a Tk_Window from the window table + * given an HWND. + * + * Results: + * Returns the matching Tk_Window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +Tk_HWNDToWindow(hwnd) + HWND hwnd; +{ + Tcl_HashEntry *entryPtr = Tcl_FindHashEntry(&windowTable, (char*)hwnd); + if (entryPtr != NULL) { + return (Tk_Window) Tcl_GetHashValue(entryPtr); + } + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetHWND -- + * + * This function extracts the HWND from an X Window. + * + * Results: + * Returns the HWND associated with the Window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +HWND +Tk_GetHWND(window) + Window window; +{ + TkWinDrawable *twdPtr = (TkWinDrawable *) window; + return twdPtr->window.handle; +} + +/* + *---------------------------------------------------------------------- + * + * TkpPrintWindowId -- + * + * This routine stores the string representation of the + * platform dependent window handle for an X Window in the + * given buffer. + * + * Results: + * Returns the result in the specified buffer. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkpPrintWindowId(buf, window) + char *buf; /* Pointer to string large enough to hold + * the hex representation of a pointer. */ + Window window; /* Window to be printed into buffer. */ +{ + HWND hwnd = (window) ? Tk_GetHWND(window) : 0; + sprintf(buf, "0x%x", (unsigned int) hwnd); +} + +/* + *---------------------------------------------------------------------- + * + * TkpScanWindowId -- + * + * Given a string which represents the platform dependent window + * handle, produce the X Window id for the window. + * + * Results: + * The return value is normally TCL_OK; in this case *idPtr + * will be set to the X Window id equivalent to string. If + * string is improperly formed then TCL_ERROR is returned and + * an error message will be left in interp->result. If the + * number does not correspond to a Tk Window, then *idPtr will + * be set to None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpScanWindowId(interp, string, idPtr) + Tcl_Interp *interp; /* Interpreter to use for error reporting. */ + char *string; /* String containing a (possibly signed) + * integer in a form acceptable to strtol. */ + int *idPtr; /* Place to store converted result. */ +{ + int number; + Tk_Window tkwin; + + if (Tcl_GetInt(interp, string, &number) != TCL_OK) { + return TCL_ERROR; + } + tkwin = Tk_HWNDToWindow((HWND)number); + if (tkwin) { + *idPtr = Tk_WindowId(tkwin); + } else { + *idPtr = None; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TkpMakeWindow -- + * + * Creates a Windows window object based on the current attributes + * of the specified TkWindow. + * + * Results: + * Returns a pointer to a new TkWinDrawable cast to a Window. + * + * Side effects: + * Creates a new window. + * + *---------------------------------------------------------------------- + */ + +Window +TkpMakeWindow(winPtr, parent) + TkWindow *winPtr; + Window parent; +{ + HWND parentWin; + int style; + HWND hwnd; + + if (parent != None) { + parentWin = Tk_GetHWND(parent); + style = WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; + } else { + parentWin = NULL; + style = WS_POPUP | WS_CLIPCHILDREN; + } + + /* + * Create the window, then ensure that it is at the top of the + * stacking order. + */ + + hwnd = CreateWindow(TK_WIN_CHILD_CLASS_NAME, NULL, style, + Tk_X(winPtr), Tk_Y(winPtr), Tk_Width(winPtr), Tk_Height(winPtr), + parentWin, NULL, Tk_GetHINSTANCE(), NULL); + SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, + SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); + return Tk_AttachHWND((Tk_Window)winPtr, hwnd); +} + +/* + *---------------------------------------------------------------------- + * + * XDestroyWindow -- + * + * Destroys the given window. + * + * Results: + * None. + * + * Side effects: + * Sends the WM_DESTROY message to the window and then destroys + * it the Win32 resources associated with the window. + * + *---------------------------------------------------------------------- + */ + +void +XDestroyWindow(display, w) + Display* display; + Window w; +{ + Tcl_HashEntry *entryPtr; + TkWinDrawable *twdPtr = (TkWinDrawable *)w; + TkWindow *winPtr = TkWinGetWinPtr(w); + HWND hwnd = Tk_GetHWND(w); + + display->request++; + + /* + * Remove references to the window in the pointer module then + * release the drawable. + */ + + TkPointerDeadWindow(winPtr); + + entryPtr = Tcl_FindHashEntry(&windowTable, (char*)hwnd); + if (entryPtr != NULL) { + Tcl_DeleteHashEntry(entryPtr); + } + + ckfree((char *)twdPtr); + + /* + * Don't bother destroying the window if we are going to destroy + * the parent later. + */ + + if (hwnd != NULL && !(winPtr->flags & TK_DONT_DESTROY_WINDOW)) { + DestroyWindow(hwnd); + } +} + +/* + *---------------------------------------------------------------------- + * + * XMapWindow -- + * + * Cause the given window to become visible. + * + * Results: + * None + * + * Side effects: + * Causes the window state to change, and generates a MapNotify + * event. + * + *---------------------------------------------------------------------- + */ + +void +XMapWindow(display, w) + Display* display; + Window w; +{ + XEvent event; + TkWindow *parentPtr; + TkWindow *winPtr = TkWinGetWinPtr(w); + + display->request++; + + ShowWindow(TkWinGetHWND(w), SW_SHOWNORMAL); + winPtr->flags |= TK_MAPPED; + + /* + * Check to see if this window is visible now. If all of the parent + * windows up to the first toplevel are mapped, then this window and + * its mapped children have just become visible. + */ + + if (!(winPtr->flags & TK_TOP_LEVEL)) { + for (parentPtr = winPtr->parentPtr; ; + parentPtr = parentPtr->parentPtr) { + if ((parentPtr == NULL) || !(parentPtr->flags & TK_MAPPED)) { + return; + } + if (parentPtr->flags & TK_TOP_LEVEL) { + break; + } + } + } else { + event.type = MapNotify; + event.xmap.serial = display->request; + event.xmap.send_event = False; + event.xmap.display = display; + event.xmap.event = winPtr->window; + event.xmap.window = winPtr->window; + event.xmap.override_redirect = winPtr->atts.override_redirect; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + } + + /* + * Generate VisibilityNotify events for this window and its mapped + * children. + */ + + event.type = VisibilityNotify; + event.xvisibility.serial = display->request; + event.xvisibility.send_event = False; + event.xvisibility.display = display; + event.xvisibility.window = winPtr->window; + event.xvisibility.state = VisibilityUnobscured; + NotifyVisibility(&event, winPtr); +} + +/* + *---------------------------------------------------------------------- + * + * NotifyVisibility -- + * + * This function recursively notifies the mapped children of the + * specified window of a change in visibility. Note that we don't + * properly report the visibility state, since Windows does not + * provide that info. The eventPtr argument must point to an event + * that has been completely initialized except for the window slot. + * + * Results: + * None. + * + * Side effects: + * Generates lots of events. + * + *---------------------------------------------------------------------- + */ + +static void +NotifyVisibility(eventPtr, winPtr) + XEvent *eventPtr; /* Initialized VisibilityNotify event. */ + TkWindow *winPtr; /* Window to notify. */ +{ + if (winPtr->atts.event_mask & VisibilityChangeMask) { + eventPtr->xvisibility.window = winPtr->window; + Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_TAIL); + } + for (winPtr = winPtr->childList; winPtr != NULL; + winPtr = winPtr->nextPtr) { + if (winPtr->flags & TK_MAPPED) { + NotifyVisibility(eventPtr, winPtr); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * XUnmapWindow -- + * + * Cause the given window to become invisible. + * + * Results: + * None + * + * Side effects: + * Causes the window state to change, and generates an UnmapNotify + * event. + * + *---------------------------------------------------------------------- + */ + +void +XUnmapWindow(display, w) + Display* display; + Window w; +{ + XEvent event; + TkWindow *winPtr = TkWinGetWinPtr(w); + + display->request++; + + /* + * Bug fix: Don't short circuit this routine based on TK_MAPPED because + * it will be cleared before XUnmapWindow is called. + */ + + ShowWindow(TkWinGetHWND(w), SW_HIDE); + winPtr->flags &= ~TK_MAPPED; + + if (winPtr->flags & TK_TOP_LEVEL) { + event.type = UnmapNotify; + event.xunmap.serial = display->request; + event.xunmap.send_event = False; + event.xunmap.display = display; + event.xunmap.event = winPtr->window; + event.xunmap.window = winPtr->window; + event.xunmap.from_configure = False; + Tk_HandleEvent(&event); + } +} + +/* + *---------------------------------------------------------------------- + * + * XMoveResizeWindow -- + * + * Move and resize a window relative to its parent. + * + * Results: + * None. + * + * Side effects: + * Repositions and resizes the specified window. + * + *---------------------------------------------------------------------- + */ + +void +XMoveResizeWindow(display, w, x, y, width, height) + Display* display; + Window w; + int x; /* Position relative to parent. */ + int y; + unsigned int width; + unsigned int height; +{ + display->request++; + MoveWindow(TkWinGetHWND(w), x, y, width, height, TRUE); +} + +/* + *---------------------------------------------------------------------- + * + * XMoveWindow -- + * + * Move a window relative to its parent. + * + * Results: + * None. + * + * Side effects: + * Repositions the specified window. + * + *---------------------------------------------------------------------- + */ + +void +XMoveWindow(display, w, x, y) + Display* display; + Window w; + int x; + int y; +{ + TkWindow *winPtr = TkWinGetWinPtr(w); + + display->request++; + + MoveWindow(TkWinGetHWND(w), x, y, winPtr->changes.width, + winPtr->changes.height, TRUE); +} + +/* + *---------------------------------------------------------------------- + * + * XResizeWindow -- + * + * Resize a window. + * + * Results: + * None. + * + * Side effects: + * Resizes the specified window. + * + *---------------------------------------------------------------------- + */ + +void +XResizeWindow(display, w, width, height) + Display* display; + Window w; + unsigned int width; + unsigned int height; +{ + TkWindow *winPtr = TkWinGetWinPtr(w); + + display->request++; + + MoveWindow(TkWinGetHWND(w), winPtr->changes.x, winPtr->changes.y, width, + height, TRUE); +} + +/* + *---------------------------------------------------------------------- + * + * XRaiseWindow -- + * + * Change the stacking order of a window. + * + * Results: + * None. + * + * Side effects: + * Changes the stacking order of the specified window. + * + *---------------------------------------------------------------------- + */ + +void +XRaiseWindow(display, w) + Display* display; + Window w; +{ + HWND window = TkWinGetHWND(w); + + display->request++; + SetWindowPos(window, HWND_TOPMOST, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE); +} + +/* + *---------------------------------------------------------------------- + * + * XConfigureWindow -- + * + * Change the size, position, stacking, or border of the specified + * window. + * + * Results: + * None. + * + * Side effects: + * Changes the attributes of the specified window. Note that we + * ignore the passed in values and use the values stored in the + * TkWindow data structure. + * + *---------------------------------------------------------------------- + */ + +void +XConfigureWindow(display, w, value_mask, values) + Display* display; + Window w; + unsigned int value_mask; + XWindowChanges* values; +{ + TkWindow *winPtr = TkWinGetWinPtr(w); + HWND hwnd = TkWinGetHWND(w); + + display->request++; + + /* + * Change the shape and/or position of the window. + */ + + if (value_mask & (CWX|CWY|CWWidth|CWHeight)) { + MoveWindow(hwnd, winPtr->changes.x, winPtr->changes.y, + winPtr->changes.width, winPtr->changes.height, TRUE); + } + + /* + * Change the stacking order of the window. + */ + + if (value_mask & CWStackMode) { + HWND sibling; + if ((value_mask & CWSibling) && (values->sibling != None)) { + sibling = Tk_GetHWND(values->sibling); + } else { + sibling = NULL; + } + TkWinSetWindowPos(hwnd, sibling, values->stack_mode); + } +} + +/* + *---------------------------------------------------------------------- + * + * XClearWindow -- + * + * Clears the entire window to the current background color. + * + * Results: + * None. + * + * Side effects: + * Erases the current contents of the window. + * + *---------------------------------------------------------------------- + */ + +void +XClearWindow(display, w) + Display* display; + Window w; +{ + RECT rc; + HBRUSH brush; + HPALETTE oldPalette, palette; + TkWindow *winPtr; + HWND hwnd = TkWinGetHWND(w); + HDC dc = GetDC(hwnd); + + palette = TkWinGetPalette(display->screens[0].cmap); + oldPalette = SelectPalette(dc, palette, FALSE); + + display->request++; + + winPtr = TkWinGetWinPtr(w); + brush = CreateSolidBrush(winPtr->atts.background_pixel); + GetWindowRect(hwnd, &rc); + rc.right = rc.right - rc.left; + rc.bottom = rc.bottom - rc.top; + rc.left = rc.top = 0; + FillRect(dc, &rc, brush); + + DeleteObject(brush); + SelectPalette(dc, oldPalette, TRUE); + ReleaseDC(hwnd, dc); +} + +/* + *---------------------------------------------------------------------- + * + * XChangeWindowAttributes -- + * + * This function is called when the attributes on a window are + * updated. Since Tk maintains all of the window state, the only + * relevant value is the cursor. + * + * Results: + * None. + * + * Side effects: + * May cause the mouse position to be updated. + * + *---------------------------------------------------------------------- + */ + +void +XChangeWindowAttributes(display, w, valueMask, attributes) + Display* display; + Window w; + unsigned long valueMask; + XSetWindowAttributes* attributes; +{ + if (valueMask & CWCursor) { + XDefineCursor(display, w, attributes->cursor); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWinSetWindowPos -- + * + * Adjust the stacking order of a window relative to a second + * window (or NULL). + * + * Results: + * None. + * + * Side effects: + * Moves the specified window in the stacking order. + * + *---------------------------------------------------------------------- + */ + +void +TkWinSetWindowPos(hwnd, siblingHwnd, pos) + HWND hwnd; /* Window to restack. */ + HWND siblingHwnd; /* Sibling window. */ + int pos; /* One of Above or Below. */ +{ + HWND temp; + + /* + * Since Windows does not support Above mode, we place the + * specified window below the sibling and then swap them. + */ + + if (siblingHwnd) { + if (pos == Above) { + SetWindowPos(hwnd, siblingHwnd, 0, 0, 0, 0, + SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); + temp = hwnd; + hwnd = siblingHwnd; + siblingHwnd = temp; + } + } else { + siblingHwnd = (pos == Above) ? HWND_TOP : HWND_BOTTOM; + } + + SetWindowPos(hwnd, siblingHwnd, 0, 0, 0, 0, + SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); +} + +/* + *---------------------------------------------------------------------- + * + * TkpWindowWasRecentlyDeleted -- + * + * Determines whether we know if the window given as argument was + * recently deleted. Called by the generic code error handler to + * handle BadWindow events. + * + * Results: + * Always 0. We do not keep this information on Windows. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TkpWindowWasRecentlyDeleted(win, dispPtr) + Window win; + TkDisplay *dispPtr; +{ + return 0; +} diff --git a/win/tkWinWm.c b/win/tkWinWm.c new file mode 100644 index 0000000..6ec1a2a --- /dev/null +++ b/win/tkWinWm.c @@ -0,0 +1,4115 @@ +/* + * tkWinWm.c -- + * + * This module takes care of the interactions between a Tk-based + * application and the window manager. Among other things, it + * implements the "wm" command and passes geometry information + * to the window manager. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinWm.c 1.67 97/09/23 17:39:47 + */ + +#include "tkWinInt.h" + +/* + * A data structure of the following type holds information for + * each window manager protocol (such as WM_DELETE_WINDOW) for + * which a handler (i.e. a Tcl command) has been defined for a + * particular top-level window. + */ + +typedef struct ProtocolHandler { + Atom protocol; /* Identifies the protocol. */ + struct ProtocolHandler *nextPtr; + /* Next in list of protocol handlers for + * the same top-level window, or NULL for + * end of list. */ + Tcl_Interp *interp; /* Interpreter in which to invoke command. */ + char command[4]; /* Tcl command to invoke when a client + * message for this protocol arrives. + * The actual size of the structure varies + * to accommodate the needs of the actual + * command. THIS MUST BE THE LAST FIELD OF + * THE STRUCTURE. */ +} ProtocolHandler; + +#define HANDLER_SIZE(cmdLength) \ + ((unsigned) (sizeof(ProtocolHandler) - 3 + cmdLength)) + +/* + * A data structure of the following type holds window-manager-related + * information for each top-level window in an application. + */ + +typedef struct TkWmInfo { + TkWindow *winPtr; /* Pointer to main Tk information for + * this window. */ + HWND wrapper; /* This is the decorative frame window + * created by the window manager to wrap + * a toplevel window. This window is + * a direct child of the root window. */ + Tk_Uid titleUid; /* Title to display in window caption. If + * NULL, use name of widget. */ + Tk_Uid iconName; /* Name to display in icon. */ + TkWindow *masterPtr; /* Master window for TRANSIENT_FOR property, + * or NULL. */ + XWMHints hints; /* Various pieces of information for + * window manager. */ + char *leaderName; /* Path name of leader of window group + * (corresponds to hints.window_group). + * Malloc-ed. Note: this field doesn't + * get updated if leader is destroyed. */ + Tk_Window icon; /* Window to use as icon for this window, + * or NULL. */ + Tk_Window iconFor; /* Window for which this window is icon, or + * NULL if this isn't an icon for anyone. */ + + /* + * Information used to construct an XSizeHints structure for + * the window manager: + */ + + int defMinWidth, defMinHeight, defMaxWidth, defMaxHeight; + /* Default resize limits given by system. */ + int sizeHintsFlags; /* Flags word for XSizeHints structure. + * If the PBaseSize flag is set then the + * window is gridded; otherwise it isn't + * gridded. */ + int minWidth, minHeight; /* Minimum dimensions of window, in + * grid units, not pixels. */ + int maxWidth, maxHeight; /* Maximum dimensions of window, in + * grid units, not pixels, or 0 to default. */ + Tk_Window gridWin; /* Identifies the window that controls + * gridding for this top-level, or NULL if + * the top-level isn't currently gridded. */ + int widthInc, heightInc; /* Increments for size changes (# pixels + * per step). */ + struct { + int x; /* numerator */ + int y; /* denominator */ + } minAspect, maxAspect; /* Min/max aspect ratios for window. */ + int reqGridWidth, reqGridHeight; + /* The dimensions of the window (in + * grid units) requested through + * the geometry manager. */ + int gravity; /* Desired window gravity. */ + + /* + * Information used to manage the size and location of a window. + */ + + int width, height; /* Desired dimensions of window, specified + * in grid units. These values are + * set by the "wm geometry" command and by + * ConfigureNotify events (for when wm + * resizes window). -1 means user hasn't + * requested dimensions. */ + int x, y; /* Desired X and Y coordinates for window. + * These values are set by "wm geometry", + * plus by ConfigureNotify events (when wm + * moves window). These numbers are + * different than the numbers stored in + * winPtr->changes because (a) they could be + * measured from the right or bottom edge + * of the screen (see WM_NEGATIVE_X and + * WM_NEGATIVE_Y flags) and (b) if the window + * has been reparented then they refer to the + * parent rather than the window itself. */ + int borderWidth, borderHeight; + /* Width and height of window dressing, in + * pixels for the current style/exStyle. This + * includes the border on both sides of the + * window. */ + int configWidth, configHeight; + /* Dimensions passed to last request that we + * issued to change geometry of window. Used + * to eliminate redundant resize operations. */ + HMENU hMenu; /* the hMenu associated with this menu */ + DWORD style, exStyle; /* Style flags for the wrapper window. */ + + /* + * List of children of the toplevel which have private colormaps. + */ + + TkWindow **cmapList; /* Array of window with private colormaps. */ + int cmapCount; /* Number of windows in array. */ + + /* + * Miscellaneous information. + */ + + ProtocolHandler *protPtr; /* First in list of protocol handlers for + * this window (NULL means none). */ + int cmdArgc; /* Number of elements in cmdArgv below. */ + char **cmdArgv; /* Array of strings to store in the + * WM_COMMAND property. NULL means nothing + * available. */ + char *clientMachine; /* String to store in WM_CLIENT_MACHINE + * property, or NULL. */ + int flags; /* Miscellaneous flags, defined below. */ + struct TkWmInfo *nextPtr; /* Next in list of all top-level windows. */ +} WmInfo; + +/* + * Flag values for WmInfo structures: + * + * WM_NEVER_MAPPED - non-zero means window has never been + * mapped; need to update all info when + * window is first mapped. + * WM_UPDATE_PENDING - non-zero means a call to UpdateGeometryInfo + * has already been scheduled for this + * window; no need to schedule another one. + * WM_NEGATIVE_X - non-zero means x-coordinate is measured in + * pixels from right edge of screen, rather + * than from left edge. + * WM_NEGATIVE_Y - non-zero means y-coordinate is measured in + * pixels up from bottom of screen, rather than + * down from top. + * WM_UPDATE_SIZE_HINTS - non-zero means that new size hints need to be + * propagated to window manager. + * WM_SYNC_PENDING - set to non-zero while waiting for the window + * manager to respond to some state change. + * WM_MOVE_PENDING - non-zero means the application has requested + * a new position for the window, but it hasn't + * been reflected through the window manager + * yet. + * WM_COLORAMPS_EXPLICIT - non-zero means the colormap windows were + * set explicitly via "wm colormapwindows". + * WM_ADDED_TOPLEVEL_COLORMAP - non-zero means that when "wm colormapwindows" + * was called the top-level itself wasn't + * specified, so we added it implicitly at + * the end of the list. + */ + +#define WM_NEVER_MAPPED (1<<0) +#define WM_UPDATE_PENDING (1<<1) +#define WM_NEGATIVE_X (1<<2) +#define WM_NEGATIVE_Y (1<<3) +#define WM_UPDATE_SIZE_HINTS (1<<4) +#define WM_SYNC_PENDING (1<<5) +#define WM_CREATE_PENDING (1<<6) +#define WM_MOVE_PENDING (1<<7) +#define WM_COLORMAPS_EXPLICIT (1<<8) +#define WM_ADDED_TOPLEVEL_COLORMAP (1<<9) +#define WM_WIDTH_NOT_RESIZABLE (1<<10) +#define WM_HEIGHT_NOT_RESIZABLE (1<<11) + +/* + * Window styles for various types of toplevel windows. + */ + +#define WM_OVERRIDE_STYLE (WS_POPUP|WS_CLIPCHILDREN|CS_DBLCLKS) +#define EX_OVERRIDE_STYLE (WS_EX_TOOLWINDOW) + +#define WM_TOPLEVEL_STYLE (WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN|CS_DBLCLKS) +#define EX_TOPLEVEL_STYLE (0) + +#define WM_TRANSIENT_STYLE \ + (WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_CLIPSIBLINGS|CS_DBLCLKS) +#define EX_TRANSIENT_STYLE (WS_EX_TOOLWINDOW | WS_EX_DLGMODALFRAME) + +/* + * This module keeps a list of all top-level windows. + */ + +static WmInfo *firstWmPtr = NULL; /* Points to first top-level window. */ +static WmInfo *foregroundWmPtr = NULL; /* Points to the foreground window. */ + +/* + * The variable below is used to enable or disable tracing in this + * module. If tracing is enabled, then information is printed on + * standard output about interesting interactions with the window + * manager. + */ + +static int wmTracing = 0; + +/* + * The following structure is the official type record for geometry + * management of top-level windows. + */ + +static void TopLevelReqProc(ClientData dummy, Tk_Window tkwin); + +static Tk_GeomMgr wmMgrType = { + "wm", /* name */ + TopLevelReqProc, /* requestProc */ + (Tk_GeomLostSlaveProc *) NULL, /* lostSlaveProc */ +}; + +/* + * Global system palette. This value always refers to the currently + * installed foreground logical palette. + */ + +static HPALETTE systemPalette = NULL; + +/* + * Window that is being constructed. This value is set immediately + * before a call to CreateWindowEx, and is used by SetLimits. + * This is a gross hack needed to work around Windows brain damage + * where it sends the WM_GETMINMAXINFO message before the WM_CREATE + * window. + */ + +static TkWindow *createWindow = NULL; + +/* + * Flag indicating whether this module has been initialized yet. + */ + +static int initialized = 0; + +/* + * Class for toplevel windows. + */ + +static WNDCLASS toplevelClass; + +/* + * This flag is cleared when the first window is mapped in a non-iconic + * state. + */ + +static int firstWindow = 1; + +/* + * Forward declarations for procedures defined in this file: + */ + +static void ConfigureEvent _ANSI_ARGS_((TkWindow *winPtr, + XConfigureEvent *eventPtr)); +static void ConfigureTopLevel _ANSI_ARGS_((WINDOWPOS *pos)); +static void GenerateConfigureNotify _ANSI_ARGS_(( + TkWindow *winPtr)); +static void GetMaxSize _ANSI_ARGS_((WmInfo *wmPtr, + int *maxWidthPtr, int *maxHeightPtr)); +static void GetMinSize _ANSI_ARGS_((WmInfo *wmPtr, + int *minWidthPtr, int *minHeightPtr)); +static TkWindow * GetTopLevel _ANSI_ARGS_((HWND hwnd)); +static void InitWm _ANSI_ARGS_((void)); +static int InstallColormaps _ANSI_ARGS_((HWND hwnd, int message, + int isForemost)); +static void InvalidateSubTree _ANSI_ARGS_((TkWindow *winPtr, + Colormap colormap)); +static int ParseGeometry _ANSI_ARGS_((Tcl_Interp *interp, + char *string, TkWindow *winPtr)); +static void RefreshColormap _ANSI_ARGS_((Colormap colormap)); +static void SetLimits _ANSI_ARGS_((HWND hwnd, MINMAXINFO *info)); +static LRESULT CALLBACK TopLevelProc _ANSI_ARGS_((HWND hwnd, UINT message, + WPARAM wParam, LPARAM lParam)); +static void TopLevelEventProc _ANSI_ARGS_((ClientData clientData, + XEvent *eventPtr)); +static void TopLevelReqProc _ANSI_ARGS_((ClientData dummy, + Tk_Window tkwin)); +static void UpdateGeometryInfo _ANSI_ARGS_(( + ClientData clientData)); +static void UpdateWrapper _ANSI_ARGS_((TkWindow *winPtr)); +static LRESULT CALLBACK WmProc _ANSI_ARGS_((HWND hwnd, UINT message, + WPARAM wParam, LPARAM lParam)); + +/* + *---------------------------------------------------------------------- + * + * InitWm -- + * + * This routine creates the Wm toplevel decorative frame class. + * + * Results: + * None. + * + * Side effects: + * Registers a new window class. + * + *---------------------------------------------------------------------- + */ + +static void +InitWm(void) +{ + if (initialized) { + return; + } + initialized = 1; + + toplevelClass.style = CS_HREDRAW | CS_VREDRAW | CS_CLASSDC; + toplevelClass.cbClsExtra = 0; + toplevelClass.cbWndExtra = 0; + toplevelClass.hInstance = Tk_GetHINSTANCE(); + toplevelClass.hbrBackground = NULL; + toplevelClass.lpszMenuName = NULL; + toplevelClass.lpszClassName = TK_WIN_TOPLEVEL_CLASS_NAME; + toplevelClass.lpfnWndProc = WmProc; + toplevelClass.hIcon = LoadIcon(Tk_GetHINSTANCE(), "tk"); + toplevelClass.hCursor = LoadCursor(NULL, IDC_ARROW); + + if (!RegisterClass(&toplevelClass)) { + panic("Unable to register TkTopLevel class"); + } +} + +/* + *---------------------------------------------------------------------- + * + * GetTopLevel -- + * + * This function retrieves the TkWindow associated with the + * given HWND. + * + * Results: + * Returns the matching TkWindow. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static TkWindow * +GetTopLevel(hwnd) + HWND hwnd; +{ + /* + * If this function is called before the CreateWindowEx call + * has completed, then the user data slot will not have been + * set yet, so we use the global createWindow variable. + */ + + if (createWindow) { + return createWindow; + } + return (TkWindow *) GetWindowLong(hwnd, GWL_USERDATA); +} + +/* + *---------------------------------------------------------------------- + * + * SetLimits -- + * + * Updates the minimum and maximum window size constraints. + * + * Results: + * None. + * + * Side effects: + * Changes the values of the info pointer to reflect the current + * minimum and maximum size values. + * + *---------------------------------------------------------------------- + */ + +static void +SetLimits(hwnd, info) + HWND hwnd; + MINMAXINFO *info; +{ + register WmInfo *wmPtr; + int maxWidth, maxHeight; + int minWidth, minHeight; + int base; + TkWindow *winPtr = GetTopLevel(hwnd); + + if (winPtr == NULL) { + return; + } + + wmPtr = winPtr->wmInfoPtr; + + /* + * Copy latest constraint info. + */ + + wmPtr->defMinWidth = info->ptMinTrackSize.x; + wmPtr->defMinHeight = info->ptMinTrackSize.y; + wmPtr->defMaxWidth = info->ptMaxTrackSize.x; + wmPtr->defMaxHeight = info->ptMaxTrackSize.y; + + GetMaxSize(wmPtr, &maxWidth, &maxHeight); + GetMinSize(wmPtr, &minWidth, &minHeight); + + if (wmPtr->gridWin != NULL) { + base = winPtr->reqWidth - (wmPtr->reqGridWidth * wmPtr->widthInc); + if (base < 0) { + base = 0; + } + base += wmPtr->borderWidth; + info->ptMinTrackSize.x = base + (minWidth * wmPtr->widthInc); + info->ptMaxTrackSize.x = base + (maxWidth * wmPtr->widthInc); + + base = winPtr->reqHeight - (wmPtr->reqGridHeight * wmPtr->heightInc); + if (base < 0) { + base = 0; + } + base += wmPtr->borderHeight; + info->ptMinTrackSize.y = base + (minHeight * wmPtr->heightInc); + info->ptMaxTrackSize.y = base + (maxHeight * wmPtr->heightInc); + } else { + info->ptMaxTrackSize.x = maxWidth + wmPtr->borderWidth; + info->ptMaxTrackSize.y = maxHeight + wmPtr->borderHeight; + info->ptMinTrackSize.x = minWidth + wmPtr->borderWidth; + info->ptMinTrackSize.y = minHeight + wmPtr->borderHeight; + } + + /* + * If the window isn't supposed to be resizable, then set the + * minimum and maximum dimensions to be the same as the current size. + */ + + if (!(wmPtr->flags & WM_SYNC_PENDING)) { + if (wmPtr->flags & WM_WIDTH_NOT_RESIZABLE) { + info->ptMinTrackSize.x = winPtr->changes.width + + wmPtr->borderWidth; + info->ptMaxTrackSize.x = info->ptMinTrackSize.x; + } + if (wmPtr->flags & WM_HEIGHT_NOT_RESIZABLE) { + info->ptMinTrackSize.y = winPtr->changes.height + + wmPtr->borderHeight; + info->ptMaxTrackSize.y = info->ptMinTrackSize.y; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWinWmCleanup -- + * + * Unregisters classes registered by the window manager. This is + * called from the DLL main entry point when the DLL is unloaded. + * + * Results: + * None. + * + * Side effects: + * The window classes are discarded. + * + *---------------------------------------------------------------------- + */ + +void +TkWinWmCleanup(hInstance) + HINSTANCE hInstance; +{ + if (!initialized) { + return; + } + initialized = 0; + + UnregisterClass(TK_WIN_TOPLEVEL_CLASS_NAME, hInstance); +} + +/* + *-------------------------------------------------------------- + * + * TkWmNewWindow -- + * + * This procedure is invoked whenever a new top-level + * window is created. Its job is to initialize the WmInfo + * structure for the window. + * + * Results: + * None. + * + * Side effects: + * A WmInfo structure gets allocated and initialized. + * + *-------------------------------------------------------------- + */ + +void +TkWmNewWindow(winPtr) + TkWindow *winPtr; /* Newly-created top-level window. */ +{ + register WmInfo *wmPtr; + + wmPtr = (WmInfo *) ckalloc(sizeof(WmInfo)); + winPtr->wmInfoPtr = wmPtr; + wmPtr->winPtr = winPtr; + wmPtr->wrapper = NULL; + wmPtr->titleUid = NULL; + wmPtr->iconName = NULL; + wmPtr->masterPtr = NULL; + wmPtr->hints.flags = InputHint | StateHint; + wmPtr->hints.input = True; + wmPtr->hints.initial_state = NormalState; + wmPtr->hints.icon_pixmap = None; + wmPtr->hints.icon_window = None; + wmPtr->hints.icon_x = wmPtr->hints.icon_y = 0; + wmPtr->hints.icon_mask = None; + wmPtr->hints.window_group = None; + wmPtr->leaderName = NULL; + wmPtr->icon = NULL; + wmPtr->iconFor = NULL; + wmPtr->sizeHintsFlags = 0; + + /* + * Default the maximum dimensions to the size of the display. + */ + + wmPtr->defMinWidth = wmPtr->defMinHeight = 0; + wmPtr->defMaxWidth = DisplayWidth(winPtr->display, + winPtr->screenNum); + wmPtr->defMaxHeight = DisplayHeight(winPtr->display, + winPtr->screenNum); + wmPtr->minWidth = wmPtr->minHeight = 1; + wmPtr->maxWidth = wmPtr->maxHeight = 0; + wmPtr->gridWin = NULL; + wmPtr->widthInc = wmPtr->heightInc = 1; + wmPtr->minAspect.x = wmPtr->minAspect.y = 1; + wmPtr->maxAspect.x = wmPtr->maxAspect.y = 1; + wmPtr->reqGridWidth = wmPtr->reqGridHeight = -1; + wmPtr->gravity = NorthWestGravity; + wmPtr->width = -1; + wmPtr->height = -1; + wmPtr->hMenu = NULL; + wmPtr->x = winPtr->changes.x; + wmPtr->y = winPtr->changes.y; + wmPtr->borderWidth = 0; + wmPtr->borderHeight = 0; + + wmPtr->cmapList = NULL; + wmPtr->cmapCount = 0; + + wmPtr->configWidth = -1; + wmPtr->configHeight = -1; + wmPtr->protPtr = NULL; + wmPtr->cmdArgv = NULL; + wmPtr->clientMachine = NULL; + wmPtr->flags = WM_NEVER_MAPPED; + wmPtr->nextPtr = firstWmPtr; + firstWmPtr = wmPtr; + + /* + * Tk must monitor structure events for top-level windows, in order + * to detect size and position changes caused by window managers. + */ + + Tk_CreateEventHandler((Tk_Window) winPtr, StructureNotifyMask, + TopLevelEventProc, (ClientData) winPtr); + + /* + * Arrange for geometry requests to be reflected from the window + * to the window manager. + */ + + Tk_ManageGeometry((Tk_Window) winPtr, &wmMgrType, (ClientData) 0); +} + +/* + *---------------------------------------------------------------------- + * + * UpdateWrapper -- + * + * This function creates the wrapper window that contains the + * window decorations and menus for a toplevel. This function + * may be called after a window is mapped to change the window + * style. + * + * Results: + * None. + * + * Side effects: + * Destroys any old wrapper window and replaces it with a newly + * created wrapper. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateWrapper(winPtr) + TkWindow *winPtr; /* Top-level window to redecorate. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + HWND parentHWND = NULL, oldWrapper; + HWND child = TkWinGetHWND(winPtr->window); + int x, y, width, height, state; + WINDOWPLACEMENT place; + + parentHWND = NULL; + child = TkWinGetHWND(winPtr->window); + + if (winPtr->flags & TK_EMBEDDED) { + wmPtr->wrapper = (HWND) winPtr->privatePtr; + if (wmPtr->wrapper == NULL) { + panic("TkWmMapWindow: Cannot find container window"); + } + if (!IsWindow(wmPtr->wrapper)) { + panic("TkWmMapWindow: Container was destroyed"); + } + + } else { + /* + * Pick the decorative frame style. Override redirect windows get + * created as undecorated popups. Transient windows get a modal + * dialog frame. Neither override, nor transient windows appear in + * the Win95 taskbar. Note that a transient window does not resize + * by default, so we need to explicitly add the WS_THICKFRAME style + * if we want it to be resizeable. + */ + + if (winPtr->atts.override_redirect) { + wmPtr->style = WM_OVERRIDE_STYLE; + wmPtr->exStyle = EX_OVERRIDE_STYLE; + } else if (wmPtr->masterPtr) { + wmPtr->style = WM_TRANSIENT_STYLE; + wmPtr->exStyle = EX_TRANSIENT_STYLE; + parentHWND = Tk_GetHWND(Tk_WindowId(wmPtr->masterPtr)); + if (! ((wmPtr->flags & WM_WIDTH_NOT_RESIZABLE) && + (wmPtr->flags & WM_HEIGHT_NOT_RESIZABLE))) { + wmPtr->style |= WS_THICKFRAME; + } + } else { + wmPtr->style = WM_TOPLEVEL_STYLE; + wmPtr->exStyle = EX_TOPLEVEL_STYLE; + } + + /* + * Compute the geometry of the parent and child windows. + */ + + wmPtr->flags |= WM_CREATE_PENDING|WM_MOVE_PENDING; + UpdateGeometryInfo((ClientData)winPtr); + wmPtr->flags &= ~(WM_CREATE_PENDING|WM_MOVE_PENDING); + + width = wmPtr->borderWidth + winPtr->changes.width; + height = wmPtr->borderHeight + winPtr->changes.height; + + /* + * Set the initial position from the user or program specified + * location. If nothing has been specified, then let the system + * pick a location. + */ + + + if (!(wmPtr->sizeHintsFlags & (USPosition | PPosition)) + && (wmPtr->flags & WM_NEVER_MAPPED)) { + x = CW_USEDEFAULT; + y = CW_USEDEFAULT; + } else { + x = winPtr->changes.x; + y = winPtr->changes.y; + } + + /* + * Create the containing window, and set the user data to point + * to the TkWindow. + */ + + createWindow = winPtr; + wmPtr->wrapper = CreateWindowEx(wmPtr->exStyle, + TK_WIN_TOPLEVEL_CLASS_NAME, + wmPtr->titleUid, wmPtr->style, x, y, width, height, + parentHWND, NULL, Tk_GetHINSTANCE(), NULL); + SetWindowLong(wmPtr->wrapper, GWL_USERDATA, (LONG) winPtr); + createWindow = NULL; + + place.length = sizeof(WINDOWPLACEMENT); + GetWindowPlacement(wmPtr->wrapper, &place); + wmPtr->x = place.rcNormalPosition.left; + wmPtr->y = place.rcNormalPosition.top; + + TkInstallFrameMenu((Tk_Window) winPtr); + } + + /* + * Now we need to reparent the contained window and set its + * style appropriately. Be sure to update the style first so that + * Windows doesn't try to set the focus to the child window. + */ + + SetWindowLong(child, GWL_STYLE, + WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS); + if (winPtr->flags & TK_EMBEDDED) { + SetWindowLong(child, GWL_WNDPROC, (LONG) TopLevelProc); + } + oldWrapper = SetParent(child, wmPtr->wrapper); + if (oldWrapper && (oldWrapper != wmPtr->wrapper) + && (oldWrapper != GetDesktopWindow())) { + SetWindowLong(oldWrapper, GWL_USERDATA, (LONG) NULL); + DestroyWindow(oldWrapper); + } + wmPtr->flags &= ~WM_NEVER_MAPPED; + SendMessage(wmPtr->wrapper, TK_ATTACHWINDOW, (WPARAM) child, 0); + + /* + * Force an initial transition from withdrawn to the real + * initial state. + */ + + state = wmPtr->hints.initial_state; + wmPtr->hints.initial_state = WithdrawnState; + TkpWmSetState(winPtr, state); + + /* + * If we are embedded then force a mapping of the window now, + * because we do not necessarily own the wrapper and may not + * get another opportunity to map ourselves. We should not be + * in either iconified or zoomed states when we get here, so + * it is safe to just check for TK_EMBEDDED without checking + * what state we are supposed to be in (default to NormalState). + */ + + if (winPtr->flags & TK_EMBEDDED) { + XMapWindow(winPtr->display, winPtr->window); + } + + /* + * Set up menus on the wrapper if required. + */ + + if (wmPtr->hMenu != NULL) { + wmPtr->flags = WM_SYNC_PENDING; + SetMenu(wmPtr->wrapper, wmPtr->hMenu); + wmPtr->flags &= ~WM_SYNC_PENDING; + } + + /* + * If this is the first window created by the application, then + * we should activate the initial window. + */ + + if (firstWindow) { + firstWindow = 0; + SetActiveWindow(wmPtr->wrapper); + } +} + +/* + *-------------------------------------------------------------- + * + * TkWmMapWindow -- + * + * This procedure is invoked to map a top-level window. This + * module gets a chance to update all window-manager-related + * information in properties before the window manager sees + * the map event and checks the properties. It also gets to + * decide whether or not to even map the window after all. + * + * Results: + * None. + * + * Side effects: + * Properties of winPtr may get updated to provide up-to-date + * information to the window manager. The window may also get + * mapped, but it may not be if this procedure decides that + * isn't appropriate (e.g. because the window is withdrawn). + * + *-------------------------------------------------------------- + */ + +void +TkWmMapWindow(winPtr) + TkWindow *winPtr; /* Top-level window that's about to + * be mapped. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + + if (!initialized) { + InitWm(); + } + + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + if (wmPtr->hints.initial_state == WithdrawnState) { + return; + } + + /* + * Map the window in either the iconified or normal state. Note that + * we only send a map event if the window is in the normal state. + */ + + TkpWmSetState(winPtr, wmPtr->hints.initial_state); + } + + /* + * This is the first time this window has ever been mapped. + * Store all the window-manager-related information for the + * window. + */ + + if (wmPtr->titleUid == NULL) { + wmPtr->titleUid = winPtr->nameUid; + } + UpdateWrapper(winPtr); +} + +/* + *-------------------------------------------------------------- + * + * TkWmUnmapWindow -- + * + * This procedure is invoked to unmap a top-level window. The + * only thing it does special is unmap the decorative frame before + * unmapping the toplevel window. + * + * Results: + * None. + * + * Side effects: + * Unmaps the decorative frame and the window. + * + *-------------------------------------------------------------- + */ + +void +TkWmUnmapWindow(winPtr) + TkWindow *winPtr; /* Top-level window that's about to + * be unmapped. */ +{ + TkpWmSetState(winPtr, WithdrawnState); +} + +/* + *---------------------------------------------------------------------- + * + * TkpWmSetState -- + * + * Sets the window manager state for the wrapper window of a + * given toplevel window. + * + * Results: + * None. + * + * Side effects: + * May maximize, minimize, restore, or withdraw a window. + * + *---------------------------------------------------------------------- + */ + +void +TkpWmSetState(winPtr, state) + TkWindow *winPtr; /* Toplevel window to operate on. */ + int state; /* One of IconicState, ZoomState, NormalState, + * or WithdrawnState. */ +{ + WmInfo *wmPtr = winPtr->wmInfoPtr; + int cmd; + + if (wmPtr->flags & WM_NEVER_MAPPED) { + wmPtr->hints.initial_state = state; + return; + } + + wmPtr->flags |= WM_SYNC_PENDING; + if (state == WithdrawnState) { + cmd = SW_HIDE; + } else if (state == IconicState) { + cmd = SW_SHOWMINNOACTIVE; + } else if (state == NormalState) { + cmd = SW_SHOWNOACTIVATE; + } else if (state == ZoomState) { + cmd = SW_SHOWMAXIMIZED; + } + ShowWindow(wmPtr->wrapper, cmd); + wmPtr->flags &= ~WM_SYNC_PENDING; +} + +/* + *-------------------------------------------------------------- + * + * TkWmDeadWindow -- + * + * This procedure is invoked when a top-level window is + * about to be deleted. It cleans up the wm-related data + * structures for the window. + * + * Results: + * None. + * + * Side effects: + * The WmInfo structure for winPtr gets freed up. + * + *-------------------------------------------------------------- + */ + +void +TkWmDeadWindow(winPtr) + TkWindow *winPtr; /* Top-level window that's being deleted. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + WmInfo *wmPtr2; + + if (wmPtr == NULL) { + return; + } + + /* + * Clean up event related window info. + */ + + if (firstWmPtr == wmPtr) { + firstWmPtr = wmPtr->nextPtr; + } else { + register WmInfo *prevPtr; + for (prevPtr = firstWmPtr; ; prevPtr = prevPtr->nextPtr) { + if (prevPtr == NULL) { + panic("couldn't unlink window in TkWmDeadWindow"); + } + if (prevPtr->nextPtr == wmPtr) { + prevPtr->nextPtr = wmPtr->nextPtr; + break; + } + } + } + + /* + * Reset all transient windows whose master is the dead window. + */ + + for (wmPtr2 = firstWmPtr; wmPtr2 != NULL; wmPtr2 = wmPtr2->nextPtr) { + if (wmPtr2->masterPtr == winPtr) { + wmPtr2->masterPtr = NULL; + if ((wmPtr2->wrapper != None) + && !(wmPtr2->flags & (WM_NEVER_MAPPED))) { + UpdateWrapper(wmPtr2->winPtr); + } + } + } + + if (wmPtr->hints.flags & IconPixmapHint) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_pixmap); + } + if (wmPtr->hints.flags & IconMaskHint) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_mask); + } + if (wmPtr->leaderName != NULL) { + ckfree(wmPtr->leaderName); + } + if (wmPtr->icon != NULL) { + wmPtr2 = ((TkWindow *) wmPtr->icon)->wmInfoPtr; + wmPtr2->iconFor = NULL; + } + if (wmPtr->iconFor != NULL) { + wmPtr2 = ((TkWindow *) wmPtr->iconFor)->wmInfoPtr; + wmPtr2->icon = NULL; + wmPtr2->hints.flags &= ~IconWindowHint; + } + while (wmPtr->protPtr != NULL) { + ProtocolHandler *protPtr; + + protPtr = wmPtr->protPtr; + wmPtr->protPtr = protPtr->nextPtr; + Tcl_EventuallyFree((ClientData) protPtr, TCL_DYNAMIC); + } + if (wmPtr->cmdArgv != NULL) { + ckfree((char *) wmPtr->cmdArgv); + } + if (wmPtr->clientMachine != NULL) { + ckfree((char *) wmPtr->clientMachine); + } + if (wmPtr->flags & WM_UPDATE_PENDING) { + Tcl_CancelIdleCall(UpdateGeometryInfo, (ClientData) winPtr); + } + + /* + * Destroy the decorative frame window. + */ + + if (!(winPtr->flags & TK_EMBEDDED)) { + if (wmPtr->wrapper != NULL) { + DestroyWindow(wmPtr->wrapper); + } else { + DestroyWindow(Tk_GetHWND(winPtr->window)); + } + } + ckfree((char *) wmPtr); + winPtr->wmInfoPtr = NULL; +} + +/* + *-------------------------------------------------------------- + * + * TkWmSetClass -- + * + * This procedure is invoked whenever a top-level window's + * class is changed. If the window has been mapped then this + * procedure updates the window manager property for the + * class. If the window hasn't been mapped, the update is + * deferred until just before the first mapping. + * + * Results: + * None. + * + * Side effects: + * A window property may get updated. + * + *-------------------------------------------------------------- + */ + +void +TkWmSetClass(winPtr) + TkWindow *winPtr; /* Newly-created top-level window. */ +{ + return; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_WmCmd -- + * + * This procedure is invoked to process the "wm" Tcl command. + * See the user documentation for details on what it does. + * + * Results: + * A standard Tcl result. + * + * Side effects: + * See the user documentation. + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +int +Tk_WmCmd(clientData, interp, argc, argv) + ClientData clientData; /* Main window associated with + * interpreter. */ + Tcl_Interp *interp; /* Current interpreter. */ + int argc; /* Number of arguments. */ + char **argv; /* Argument strings. */ +{ + Tk_Window tkwin = (Tk_Window) clientData; + TkWindow *winPtr; + register WmInfo *wmPtr; + int c; + size_t length; + + if (argc < 2) { + wrongNumArgs: + Tcl_AppendResult(interp, "wrong # args: should be \"", + argv[0], " option window ?arg ...?\"", (char *) NULL); + return TCL_ERROR; + } + c = argv[1][0]; + length = strlen(argv[1]); + if ((c == 't') && (strncmp(argv[1], "tracing", length) == 0) + && (length >= 3)) { + if ((argc != 2) && (argc != 3)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " tracing ?boolean?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 2) { + interp->result = (wmTracing) ? "on" : "off"; + return TCL_OK; + } + return Tcl_GetBoolean(interp, argv[2], &wmTracing); + } + + if (argc < 3) { + goto wrongNumArgs; + } + winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[2], tkwin); + if (winPtr == NULL) { + return TCL_ERROR; + } + if (!(winPtr->flags & TK_TOP_LEVEL)) { + Tcl_AppendResult(interp, "window \"", winPtr->pathName, + "\" isn't a top-level window", (char *) NULL); + return TCL_ERROR; + } + wmPtr = winPtr->wmInfoPtr; + if ((c == 'a') && (strncmp(argv[1], "aspect", length) == 0)) { + int numer1, denom1, numer2, denom2; + + if ((argc != 3) && (argc != 7)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " aspect window ?minNumer minDenom ", + "maxNumer maxDenom?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & PAspect) { + sprintf(interp->result, "%d %d %d %d", wmPtr->minAspect.x, + wmPtr->minAspect.y, wmPtr->maxAspect.x, + wmPtr->maxAspect.y); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->sizeHintsFlags &= ~PAspect; + } else { + if ((Tcl_GetInt(interp, argv[3], &numer1) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &denom1) != TCL_OK) + || (Tcl_GetInt(interp, argv[5], &numer2) != TCL_OK) + || (Tcl_GetInt(interp, argv[6], &denom2) != TCL_OK)) { + return TCL_ERROR; + } + if ((numer1 <= 0) || (denom1 <= 0) || (numer2 <= 0) || + (denom2 <= 0)) { + interp->result = "aspect number can't be <= 0"; + return TCL_ERROR; + } + wmPtr->minAspect.x = numer1; + wmPtr->minAspect.y = denom1; + wmPtr->maxAspect.x = numer2; + wmPtr->maxAspect.y = denom2; + wmPtr->sizeHintsFlags |= PAspect; + } + goto updateGeom; + } else if ((c == 'c') && (strncmp(argv[1], "client", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " client window ?name?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->clientMachine != NULL) { + interp->result = wmPtr->clientMachine; + } + return TCL_OK; + } + if (argv[3][0] == 0) { + if (wmPtr->clientMachine != NULL) { + ckfree((char *) wmPtr->clientMachine); + wmPtr->clientMachine = NULL; + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XDeleteProperty(winPtr->display, winPtr->window, + Tk_InternAtom((Tk_Window) winPtr, + "WM_CLIENT_MACHINE")); + } + } + return TCL_OK; + } + if (wmPtr->clientMachine != NULL) { + ckfree((char *) wmPtr->clientMachine); + } + wmPtr->clientMachine = (char *) + ckalloc((unsigned) (strlen(argv[3]) + 1)); + strcpy(wmPtr->clientMachine, argv[3]); + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XTextProperty textProp; + if (XStringListToTextProperty(&wmPtr->clientMachine, 1, &textProp) + != 0) { + XSetWMClientMachine(winPtr->display, winPtr->window, + &textProp); + XFree((char *) textProp.value); + } + } + } else if ((c == 'c') && (strncmp(argv[1], "colormapwindows", length) == 0) + && (length >= 3)) { + TkWindow **cmapList; + TkWindow *winPtr2; + int i, windowArgc, gotToplevel; + char **windowArgv; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " colormapwindows window ?windowList?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + Tk_MakeWindowExist((Tk_Window) winPtr); + for (i = 0; i < wmPtr->cmapCount; i++) { + if ((i == (wmPtr->cmapCount-1)) + && (wmPtr->flags & WM_ADDED_TOPLEVEL_COLORMAP)) { + break; + } + Tcl_AppendElement(interp, wmPtr->cmapList[i]->pathName); + } + return TCL_OK; + } + if (Tcl_SplitList(interp, argv[3], &windowArgc, &windowArgv) + != TCL_OK) { + return TCL_ERROR; + } + cmapList = (TkWindow **) ckalloc((unsigned) + ((windowArgc+1)*sizeof(TkWindow*))); + for (i = 0; i < windowArgc; i++) { + winPtr2 = (TkWindow *) Tk_NameToWindow(interp, windowArgv[i], + tkwin); + if (winPtr2 == NULL) { + ckfree((char *) cmapList); + ckfree((char *) windowArgv); + return TCL_ERROR; + } + if (winPtr2 == winPtr) { + gotToplevel = 1; + } + if (winPtr2->window == None) { + Tk_MakeWindowExist((Tk_Window) winPtr2); + } + cmapList[i] = winPtr2; + } + if (!gotToplevel) { + wmPtr->flags |= WM_ADDED_TOPLEVEL_COLORMAP; + cmapList[windowArgc] = winPtr; + windowArgc++; + } else { + wmPtr->flags &= ~WM_ADDED_TOPLEVEL_COLORMAP; + } + wmPtr->flags |= WM_COLORMAPS_EXPLICIT; + if (wmPtr->cmapList != NULL) { + ckfree((char *)wmPtr->cmapList); + } + wmPtr->cmapList = cmapList; + wmPtr->cmapCount = windowArgc; + ckfree((char *) windowArgv); + + /* + * Now we need to force the updated colormaps to be installed. + */ + + if (wmPtr == foregroundWmPtr) { + InstallColormaps(wmPtr->wrapper, WM_QUERYNEWPALETTE, 1); + } else { + InstallColormaps(wmPtr->wrapper, WM_PALETTECHANGED, 0); + } + return TCL_OK; + } else if ((c == 'c') && (strncmp(argv[1], "command", length) == 0) + && (length >= 3)) { + int cmdArgc; + char **cmdArgv; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " command window ?value?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->cmdArgv != NULL) { + interp->result = Tcl_Merge(wmPtr->cmdArgc, wmPtr->cmdArgv); + interp->freeProc = TCL_DYNAMIC; + } + return TCL_OK; + } + if (argv[3][0] == 0) { + if (wmPtr->cmdArgv != NULL) { + ckfree((char *) wmPtr->cmdArgv); + wmPtr->cmdArgv = NULL; + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XDeleteProperty(winPtr->display, winPtr->window, + Tk_InternAtom((Tk_Window) winPtr, "WM_COMMAND")); + } + } + return TCL_OK; + } + if (Tcl_SplitList(interp, argv[3], &cmdArgc, &cmdArgv) != TCL_OK) { + return TCL_ERROR; + } + if (wmPtr->cmdArgv != NULL) { + ckfree((char *) wmPtr->cmdArgv); + } + wmPtr->cmdArgc = cmdArgc; + wmPtr->cmdArgv = cmdArgv; + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XSetCommand(winPtr->display, winPtr->window, cmdArgv, cmdArgc); + } + } else if ((c == 'd') && (strncmp(argv[1], "deiconify", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " deiconify window\"", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + Tcl_AppendResult(interp, "can't deiconify ", argv[2], + ": it is an icon for ", winPtr->pathName, (char *) NULL); + return TCL_ERROR; + } + if (winPtr->flags & TK_EMBEDDED) { + Tcl_AppendResult(interp, "can't deiconify ", winPtr->pathName, + ": it is an embedded window", (char *) NULL); + return TCL_ERROR; + } + TkpWmSetState(winPtr, NormalState); + } else if ((c == 'f') && (strncmp(argv[1], "focusmodel", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " focusmodel window ?active|passive?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + interp->result = wmPtr->hints.input ? "passive" : "active"; + return TCL_OK; + } + c = argv[3][0]; + length = strlen(argv[3]); + if ((c == 'a') && (strncmp(argv[3], "active", length) == 0)) { + wmPtr->hints.input = False; + } else if ((c == 'p') && (strncmp(argv[3], "passive", length) == 0)) { + wmPtr->hints.input = True; + } else { + Tcl_AppendResult(interp, "bad argument \"", argv[3], + "\": must be active or passive", (char *) NULL); + return TCL_ERROR; + } + } else if ((c == 'f') && (strncmp(argv[1], "frame", length) == 0) + && (length >= 2)) { + HWND hwnd; + + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " frame window\"", (char *) NULL); + return TCL_ERROR; + } + hwnd = wmPtr->wrapper; + if (hwnd == NULL) { + hwnd = Tk_GetHWND(Tk_WindowId((Tk_Window) winPtr)); + } + sprintf(interp->result, "0x%x", (unsigned int) hwnd); + } else if ((c == 'g') && (strncmp(argv[1], "geometry", length) == 0) + && (length >= 2)) { + char xSign, ySign; + int width, height; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " geometry window ?newGeometry?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + xSign = (wmPtr->flags & WM_NEGATIVE_X) ? '-' : '+'; + ySign = (wmPtr->flags & WM_NEGATIVE_Y) ? '-' : '+'; + if (wmPtr->gridWin != NULL) { + width = wmPtr->reqGridWidth + (winPtr->changes.width + - winPtr->reqWidth)/wmPtr->widthInc; + height = wmPtr->reqGridHeight + (winPtr->changes.height + - winPtr->reqHeight)/wmPtr->heightInc; + } else { + width = winPtr->changes.width; + height = winPtr->changes.height; + } + sprintf(interp->result, "%dx%d%c%d%c%d", width, height, + xSign, wmPtr->x, ySign, wmPtr->y); + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->width = -1; + wmPtr->height = -1; + goto updateGeom; + } + return ParseGeometry(interp, argv[3], winPtr); + } else if ((c == 'g') && (strncmp(argv[1], "grid", length) == 0) + && (length >= 3)) { + int reqWidth, reqHeight, widthInc, heightInc; + + if ((argc != 3) && (argc != 7)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " grid window ?baseWidth baseHeight ", + "widthInc heightInc?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & PBaseSize) { + sprintf(interp->result, "%d %d %d %d", wmPtr->reqGridWidth, + wmPtr->reqGridHeight, wmPtr->widthInc, + wmPtr->heightInc); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + /* + * Turn off gridding and reset the width and height + * to make sense as ungridded numbers. + */ + + wmPtr->sizeHintsFlags &= ~(PBaseSize|PResizeInc); + if (wmPtr->width != -1) { + wmPtr->width = winPtr->reqWidth + (wmPtr->width + - wmPtr->reqGridWidth)*wmPtr->widthInc; + wmPtr->height = winPtr->reqHeight + (wmPtr->height + - wmPtr->reqGridHeight)*wmPtr->heightInc; + } + wmPtr->widthInc = 1; + wmPtr->heightInc = 1; + } else { + if ((Tcl_GetInt(interp, argv[3], &reqWidth) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &reqHeight) != TCL_OK) + || (Tcl_GetInt(interp, argv[5], &widthInc) != TCL_OK) + || (Tcl_GetInt(interp, argv[6], &heightInc) != TCL_OK)) { + return TCL_ERROR; + } + if (reqWidth < 0) { + interp->result = "baseWidth can't be < 0"; + return TCL_ERROR; + } + if (reqHeight < 0) { + interp->result = "baseHeight can't be < 0"; + return TCL_ERROR; + } + if (widthInc < 0) { + interp->result = "widthInc can't be < 0"; + return TCL_ERROR; + } + if (heightInc < 0) { + interp->result = "heightInc can't be < 0"; + return TCL_ERROR; + } + Tk_SetGrid((Tk_Window) winPtr, reqWidth, reqHeight, widthInc, + heightInc); + } + goto updateGeom; + } else if ((c == 'g') && (strncmp(argv[1], "group", length) == 0) + && (length >= 3)) { + Tk_Window tkwin2; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " group window ?pathName?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & WindowGroupHint) { + interp->result = wmPtr->leaderName; + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->hints.flags &= ~WindowGroupHint; + if (wmPtr->leaderName != NULL) { + ckfree(wmPtr->leaderName); + } + wmPtr->leaderName = NULL; + } else { + tkwin2 = Tk_NameToWindow(interp, argv[3], tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + Tk_MakeWindowExist(tkwin2); + wmPtr->hints.window_group = Tk_WindowId(tkwin2); + wmPtr->hints.flags |= WindowGroupHint; + wmPtr->leaderName = ckalloc((unsigned) (strlen(argv[3])+1)); + strcpy(wmPtr->leaderName, argv[3]); + } + } else if ((c == 'i') && (strncmp(argv[1], "iconbitmap", length) == 0) + && (length >= 5)) { + Pixmap pixmap; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconbitmap window ?bitmap?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & IconPixmapHint) { + interp->result = Tk_NameOfBitmap(winPtr->display, + wmPtr->hints.icon_pixmap); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + if (wmPtr->hints.icon_pixmap != None) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_pixmap); + } + wmPtr->hints.flags &= ~IconPixmapHint; + } else { + pixmap = Tk_GetBitmap(interp, (Tk_Window) winPtr, + Tk_GetUid(argv[3])); + if (pixmap == None) { + return TCL_ERROR; + } + wmPtr->hints.icon_pixmap = pixmap; + wmPtr->hints.flags |= IconPixmapHint; + } + } else if ((c == 'i') && (strncmp(argv[1], "iconify", length) == 0) + && (length >= 5)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconify window\"", (char *) NULL); + return TCL_ERROR; + } + if (Tk_Attributes((Tk_Window) winPtr)->override_redirect) { + Tcl_AppendResult(interp, "can't iconify \"", winPtr->pathName, + "\": override-redirect flag is set", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->masterPtr != NULL) { + Tcl_AppendResult(interp, "can't iconify \"", winPtr->pathName, + "\": it is a transient", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + Tcl_AppendResult(interp, "can't iconify ", argv[2], + ": it is an icon for ", winPtr->pathName, (char *) NULL); + return TCL_ERROR; + } + if (winPtr->flags & TK_EMBEDDED) { + Tcl_AppendResult(interp, "can't iconify ", winPtr->pathName, + ": it is an embedded window", (char *) NULL); + return TCL_ERROR; + } + TkpWmSetState(winPtr, IconicState); + } else if ((c == 'i') && (strncmp(argv[1], "iconmask", length) == 0) + && (length >= 5)) { + Pixmap pixmap; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconmask window ?bitmap?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & IconMaskHint) { + interp->result = Tk_NameOfBitmap(winPtr->display, + wmPtr->hints.icon_mask); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + if (wmPtr->hints.icon_mask != None) { + Tk_FreeBitmap(winPtr->display, wmPtr->hints.icon_mask); + } + wmPtr->hints.flags &= ~IconMaskHint; + } else { + pixmap = Tk_GetBitmap(interp, tkwin, Tk_GetUid(argv[3])); + if (pixmap == None) { + return TCL_ERROR; + } + wmPtr->hints.icon_mask = pixmap; + wmPtr->hints.flags |= IconMaskHint; + } + } else if ((c == 'i') && (strncmp(argv[1], "iconname", length) == 0) + && (length >= 5)) { + if (argc > 4) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconname window ?newName?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + interp->result = (wmPtr->iconName != NULL) ? wmPtr->iconName : ""; + return TCL_OK; + } else { + wmPtr->iconName = Tk_GetUid(argv[3]); + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + XSetIconName(winPtr->display, winPtr->window, wmPtr->iconName); + } + } + } else if ((c == 'i') && (strncmp(argv[1], "iconposition", length) == 0) + && (length >= 5)) { + int x, y; + + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconposition window ?x y?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->hints.flags & IconPositionHint) { + sprintf(interp->result, "%d %d", wmPtr->hints.icon_x, + wmPtr->hints.icon_y); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->hints.flags &= ~IconPositionHint; + } else { + if ((Tcl_GetInt(interp, argv[3], &x) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &y) != TCL_OK)){ + return TCL_ERROR; + } + wmPtr->hints.icon_x = x; + wmPtr->hints.icon_y = y; + wmPtr->hints.flags |= IconPositionHint; + } + } else if ((c == 'i') && (strncmp(argv[1], "iconwindow", length) == 0) + && (length >= 5)) { + Tk_Window tkwin2; + WmInfo *wmPtr2; + XSetWindowAttributes atts; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " iconwindow window ?pathName?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->icon != NULL) { + interp->result = Tk_PathName(wmPtr->icon); + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->hints.flags &= ~IconWindowHint; + if (wmPtr->icon != NULL) { + /* + * Let the window use button events again, then remove + * it as icon window. + */ + + atts.event_mask = Tk_Attributes(wmPtr->icon)->event_mask + | ButtonPressMask; + Tk_ChangeWindowAttributes(wmPtr->icon, CWEventMask, &atts); + wmPtr2 = ((TkWindow *) wmPtr->icon)->wmInfoPtr; + wmPtr2->iconFor = NULL; + wmPtr2->hints.initial_state = WithdrawnState; + } + wmPtr->icon = NULL; + } else { + tkwin2 = Tk_NameToWindow(interp, argv[3], tkwin); + if (tkwin2 == NULL) { + return TCL_ERROR; + } + if (!Tk_IsTopLevel(tkwin2)) { + Tcl_AppendResult(interp, "can't use ", argv[3], + " as icon window: not at top level", (char *) NULL); + return TCL_ERROR; + } + wmPtr2 = ((TkWindow *) tkwin2)->wmInfoPtr; + if (wmPtr2->iconFor != NULL) { + Tcl_AppendResult(interp, argv[3], " is already an icon for ", + Tk_PathName(wmPtr2->iconFor), (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->icon != NULL) { + WmInfo *wmPtr3 = ((TkWindow *) wmPtr->icon)->wmInfoPtr; + wmPtr3->iconFor = NULL; + + /* + * Let the window use button events again. + */ + + atts.event_mask = Tk_Attributes(wmPtr->icon)->event_mask + | ButtonPressMask; + Tk_ChangeWindowAttributes(wmPtr->icon, CWEventMask, &atts); + } + + /* + * Disable button events in the icon window: some window + * managers (like olvwm) want to get the events themselves, + * but X only allows one application at a time to receive + * button events for a window. + */ + + atts.event_mask = Tk_Attributes(tkwin2)->event_mask + & ~ButtonPressMask; + Tk_ChangeWindowAttributes(tkwin2, CWEventMask, &atts); + Tk_MakeWindowExist(tkwin2); + wmPtr->hints.icon_window = Tk_WindowId(tkwin2); + wmPtr->hints.flags |= IconWindowHint; + wmPtr->icon = tkwin2; + wmPtr2->iconFor = (Tk_Window) winPtr; + if (!(wmPtr2->flags & WM_NEVER_MAPPED)) { + if (XWithdrawWindow(Tk_Display(tkwin2), Tk_WindowId(tkwin2), + Tk_ScreenNumber(tkwin2)) == 0) { + interp->result = + "couldn't send withdraw message to window manager"; + return TCL_ERROR; + } + } + } + } else if ((c == 'm') && (strncmp(argv[1], "maxsize", length) == 0) + && (length >= 2)) { + int width, height; + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " maxsize window ?width height?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + GetMaxSize(wmPtr, &width, &height); + sprintf(interp->result, "%d %d", width, height); + return TCL_OK; + } + if ((Tcl_GetInt(interp, argv[3], &width) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &height) != TCL_OK)) { + return TCL_ERROR; + } + wmPtr->maxWidth = width; + wmPtr->maxHeight = height; + goto updateGeom; + } else if ((c == 'm') && (strncmp(argv[1], "minsize", length) == 0) + && (length >= 2)) { + int width, height; + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " minsize window ?width height?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + GetMinSize(wmPtr, &width, &height); + sprintf(interp->result, "%d %d", width, height); + return TCL_OK; + } + if ((Tcl_GetInt(interp, argv[3], &width) != TCL_OK) + || (Tcl_GetInt(interp, argv[4], &height) != TCL_OK)) { + return TCL_ERROR; + } + wmPtr->minWidth = width; + wmPtr->minHeight = height; + goto updateGeom; + } else if ((c == 'o') + && (strncmp(argv[1], "overrideredirect", length) == 0)) { + int boolean; + XSetWindowAttributes atts; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " overrideredirect window ?boolean?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (Tk_Attributes((Tk_Window) winPtr)->override_redirect) { + interp->result = "1"; + } else { + interp->result = "0"; + } + return TCL_OK; + } + if (Tcl_GetBoolean(interp, argv[3], &boolean) != TCL_OK) { + return TCL_ERROR; + } + atts.override_redirect = (boolean) ? True : False; + Tk_ChangeWindowAttributes((Tk_Window) winPtr, CWOverrideRedirect, + &atts); + if (!(wmPtr->flags & (WM_NEVER_MAPPED) + && !(winPtr->flags & TK_EMBEDDED))) { + UpdateWrapper(winPtr); + } + } else if ((c == 'p') && (strncmp(argv[1], "positionfrom", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " positionfrom window ?user/program?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & USPosition) { + interp->result = "user"; + } else if (wmPtr->sizeHintsFlags & PPosition) { + interp->result = "program"; + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->sizeHintsFlags &= ~(USPosition|PPosition); + } else { + c = argv[3][0]; + length = strlen(argv[3]); + if ((c == 'u') && (strncmp(argv[3], "user", length) == 0)) { + wmPtr->sizeHintsFlags &= ~PPosition; + wmPtr->sizeHintsFlags |= USPosition; + } else if ((c == 'p') + && (strncmp(argv[3], "program", length) == 0)) { + wmPtr->sizeHintsFlags &= ~USPosition; + wmPtr->sizeHintsFlags |= PPosition; + } else { + Tcl_AppendResult(interp, "bad argument \"", argv[3], + "\": must be program or user", (char *) NULL); + return TCL_ERROR; + } + } + goto updateGeom; + } else if ((c == 'p') && (strncmp(argv[1], "protocol", length) == 0) + && (length >= 2)) { + register ProtocolHandler *protPtr, *prevPtr; + Atom protocol; + int cmdLength; + + if ((argc < 3) || (argc > 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " protocol window ?name? ?command?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + /* + * Return a list of all defined protocols for the window. + */ + for (protPtr = wmPtr->protPtr; protPtr != NULL; + protPtr = protPtr->nextPtr) { + Tcl_AppendElement(interp, + Tk_GetAtomName((Tk_Window) winPtr, protPtr->protocol)); + } + return TCL_OK; + } + protocol = Tk_InternAtom((Tk_Window) winPtr, argv[3]); + if (argc == 4) { + /* + * Return the command to handle a given protocol. + */ + for (protPtr = wmPtr->protPtr; protPtr != NULL; + protPtr = protPtr->nextPtr) { + if (protPtr->protocol == protocol) { + interp->result = protPtr->command; + return TCL_OK; + } + } + return TCL_OK; + } + + /* + * Delete any current protocol handler, then create a new + * one with the specified command, unless the command is + * empty. + */ + + for (protPtr = wmPtr->protPtr, prevPtr = NULL; protPtr != NULL; + prevPtr = protPtr, protPtr = protPtr->nextPtr) { + if (protPtr->protocol == protocol) { + if (prevPtr == NULL) { + wmPtr->protPtr = protPtr->nextPtr; + } else { + prevPtr->nextPtr = protPtr->nextPtr; + } + Tcl_EventuallyFree((ClientData) protPtr, TCL_DYNAMIC); + break; + } + } + cmdLength = strlen(argv[4]); + if (cmdLength > 0) { + protPtr = (ProtocolHandler *) ckalloc(HANDLER_SIZE(cmdLength)); + protPtr->protocol = protocol; + protPtr->nextPtr = wmPtr->protPtr; + wmPtr->protPtr = protPtr; + protPtr->interp = interp; + strcpy(protPtr->command, argv[4]); + } + } else if ((c == 'r') && (strncmp(argv[1], "resizable", length) == 0)) { + int width, height; + + if ((argc != 3) && (argc != 5)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " resizable window ?width height?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + sprintf(interp->result, "%d %d", + (wmPtr->flags & WM_WIDTH_NOT_RESIZABLE) ? 0 : 1, + (wmPtr->flags & WM_HEIGHT_NOT_RESIZABLE) ? 0 : 1); + return TCL_OK; + } + if ((Tcl_GetBoolean(interp, argv[3], &width) != TCL_OK) + || (Tcl_GetBoolean(interp, argv[4], &height) != TCL_OK)) { + return TCL_ERROR; + } + if (width) { + wmPtr->flags &= ~WM_WIDTH_NOT_RESIZABLE; + } else { + wmPtr->flags |= WM_WIDTH_NOT_RESIZABLE; + } + if (height) { + wmPtr->flags &= ~WM_HEIGHT_NOT_RESIZABLE; + } else { + wmPtr->flags |= WM_HEIGHT_NOT_RESIZABLE; + } + wmPtr->flags |= WM_UPDATE_SIZE_HINTS; + goto updateGeom; + } else if ((c == 's') && (strncmp(argv[1], "sizefrom", length) == 0) + && (length >= 2)) { + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " sizefrom window ?user|program?\"", + (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->sizeHintsFlags & USSize) { + interp->result = "user"; + } else if (wmPtr->sizeHintsFlags & PSize) { + interp->result = "program"; + } + return TCL_OK; + } + if (*argv[3] == '\0') { + wmPtr->sizeHintsFlags &= ~(USSize|PSize); + } else { + c = argv[3][0]; + length = strlen(argv[3]); + if ((c == 'u') && (strncmp(argv[3], "user", length) == 0)) { + wmPtr->sizeHintsFlags &= ~PSize; + wmPtr->sizeHintsFlags |= USSize; + } else if ((c == 'p') + && (strncmp(argv[3], "program", length) == 0)) { + wmPtr->sizeHintsFlags &= ~USSize; + wmPtr->sizeHintsFlags |= PSize; + } else { + Tcl_AppendResult(interp, "bad argument \"", argv[3], + "\": must be program or user", (char *) NULL); + return TCL_ERROR; + } + } + goto updateGeom; + } else if ((c == 's') && (strncmp(argv[1], "state", length) == 0) + && (length >= 2)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " state window\"", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + interp->result = "icon"; + } else { + switch (wmPtr->hints.initial_state) { + case NormalState: + interp->result = "normal"; + break; + case IconicState: + interp->result = "iconic"; + break; + case WithdrawnState: + interp->result = "withdrawn"; + break; + case ZoomState: + interp->result = "zoomed"; + break; + } + } + } else if ((c == 't') && (strncmp(argv[1], "title", length) == 0) + && (length >= 2)) { + if (argc > 4) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " title window ?newTitle?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + interp->result = (wmPtr->titleUid != NULL) ? wmPtr->titleUid + : winPtr->nameUid; + return TCL_OK; + } else { + wmPtr->titleUid = Tk_GetUid(argv[3]); + if (!(wmPtr->flags & WM_NEVER_MAPPED) && wmPtr->wrapper != NULL) { + SetWindowText(wmPtr->wrapper, wmPtr->titleUid); + } + } + } else if ((c == 't') && (strncmp(argv[1], "transient", length) == 0) + && (length >= 3)) { + TkWindow *masterPtr; + + if ((argc != 3) && (argc != 4)) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " transient window ?master?\"", (char *) NULL); + return TCL_ERROR; + } + if (argc == 3) { + if (wmPtr->masterPtr != NULL) { + Tcl_SetResult(interp, Tk_PathName(wmPtr->masterPtr), + TCL_STATIC); + } + return TCL_OK; + } + if (argv[3][0] == '\0') { + wmPtr->masterPtr = NULL; + } else { + masterPtr = (TkWindow*) Tk_NameToWindow(interp, argv[3], tkwin); + if (masterPtr == NULL) { + return TCL_ERROR; + } + if (masterPtr == winPtr) { + wmPtr->masterPtr = NULL; + } else { + Tk_MakeWindowExist((Tk_Window)masterPtr); + + /* + * Ensure that the master window is actually a Tk toplevel. + */ + + while (!(masterPtr->flags & TK_TOP_LEVEL)) { + masterPtr = masterPtr->parentPtr; + } + wmPtr->masterPtr = masterPtr; + + /* + * Ensure that the transient window is either mapped or + * unmapped like its master. + */ + + TkpWmSetState(winPtr, NormalState); + } + } + if (!(wmPtr->flags & (WM_NEVER_MAPPED) + && !(winPtr->flags & TK_EMBEDDED))) { + UpdateWrapper(winPtr); + } + } else if ((c == 'w') && (strncmp(argv[1], "withdraw", length) == 0)) { + if (argc != 3) { + Tcl_AppendResult(interp, "wrong # arguments: must be \"", + argv[0], " withdraw window\"", (char *) NULL); + return TCL_ERROR; + } + if (wmPtr->iconFor != NULL) { + Tcl_AppendResult(interp, "can't withdraw ", argv[2], + ": it is an icon for ", Tk_PathName(wmPtr->iconFor), + (char *) NULL); + return TCL_ERROR; + } + TkpWmSetState(winPtr, WithdrawnState); + } else { + Tcl_AppendResult(interp, "unknown or ambiguous option \"", argv[1], + "\": must be aspect, client, command, deiconify, ", + "focusmodel, frame, geometry, grid, group, iconbitmap, ", + "iconify, iconmask, iconname, iconposition, ", + "iconwindow, maxsize, minsize, overrideredirect, ", + "positionfrom, protocol, resizable, sizefrom, state, title, ", + "transient, or withdraw", + (char *) NULL); + return TCL_ERROR; + } + return TCL_OK; + + updateGeom: + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_SetGrid -- + * + * This procedure is invoked by a widget when it wishes to set a grid + * coordinate system that controls the size of a top-level window. + * It provides a C interface equivalent to the "wm grid" command and + * is usually asscoiated with the -setgrid option. + * + * Results: + * None. + * + * Side effects: + * Grid-related information will be passed to the window manager, so + * that the top-level window associated with tkwin will resize on + * even grid units. If some other window already controls gridding + * for the top-level window then this procedure call has no effect. + * + *---------------------------------------------------------------------- + */ + +void +Tk_SetGrid(tkwin, reqWidth, reqHeight, widthInc, heightInc) + Tk_Window tkwin; /* Token for window. New window mgr info + * will be posted for the top-level window + * associated with this window. */ + int reqWidth; /* Width (in grid units) corresponding to + * the requested geometry for tkwin. */ + int reqHeight; /* Height (in grid units) corresponding to + * the requested geometry for tkwin. */ + int widthInc, heightInc; /* Pixel increments corresponding to a + * change of one grid unit. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + register WmInfo *wmPtr; + + /* + * Find the top-level window for tkwin, plus the window manager + * information. + */ + + while (!(winPtr->flags & TK_TOP_LEVEL)) { + winPtr = winPtr->parentPtr; + } + wmPtr = winPtr->wmInfoPtr; + + if ((wmPtr->gridWin != NULL) && (wmPtr->gridWin != tkwin)) { + return; + } + + if ((wmPtr->reqGridWidth == reqWidth) + && (wmPtr->reqGridHeight == reqHeight) + && (wmPtr->widthInc == widthInc) + && (wmPtr->heightInc == heightInc) + && ((wmPtr->sizeHintsFlags & (PBaseSize|PResizeInc)) + == PBaseSize|PResizeInc)) { + return; + } + + /* + * If gridding was previously off, then forget about any window + * size requests made by the user or via "wm geometry": these are + * in pixel units and there's no easy way to translate them to + * grid units since the new requested size of the top-level window in + * pixels may not yet have been registered yet (it may filter up + * the hierarchy in DoWhenIdle handlers). However, if the window + * has never been mapped yet then just leave the window size alone: + * assume that it is intended to be in grid units but just happened + * to have been specified before this procedure was called. + */ + + if ((wmPtr->gridWin == NULL) && !(wmPtr->flags & WM_NEVER_MAPPED)) { + wmPtr->width = -1; + wmPtr->height = -1; + } + + /* + * Set the new gridding information, and start the process of passing + * all of this information to the window manager. + */ + + wmPtr->gridWin = tkwin; + wmPtr->reqGridWidth = reqWidth; + wmPtr->reqGridHeight = reqHeight; + wmPtr->widthInc = widthInc; + wmPtr->heightInc = heightInc; + wmPtr->sizeHintsFlags |= PBaseSize|PResizeInc; + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_UnsetGrid -- + * + * This procedure cancels the effect of a previous call + * to Tk_SetGrid. + * + * Results: + * None. + * + * Side effects: + * If tkwin currently controls gridding for its top-level window, + * gridding is cancelled for that top-level window; if some other + * window controls gridding then this procedure has no effect. + * + *---------------------------------------------------------------------- + */ + +void +Tk_UnsetGrid(tkwin) + Tk_Window tkwin; /* Token for window that is currently + * controlling gridding. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + register WmInfo *wmPtr; + + /* + * Find the top-level window for tkwin, plus the window manager + * information. + */ + + while (!(winPtr->flags & TK_TOP_LEVEL)) { + winPtr = winPtr->parentPtr; + } + wmPtr = winPtr->wmInfoPtr; + if (tkwin != wmPtr->gridWin) { + return; + } + + wmPtr->gridWin = NULL; + wmPtr->sizeHintsFlags &= ~(PBaseSize|PResizeInc); + if (wmPtr->width != -1) { + wmPtr->width = winPtr->reqWidth + (wmPtr->width + - wmPtr->reqGridWidth)*wmPtr->widthInc; + wmPtr->height = winPtr->reqHeight + (wmPtr->height + - wmPtr->reqGridHeight)*wmPtr->heightInc; + } + wmPtr->widthInc = 1; + wmPtr->heightInc = 1; + + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * TopLevelEventProc -- + * + * This procedure is invoked when a top-level (or other externally- + * managed window) is restructured in any way. + * + * Results: + * None. + * + * Side effects: + * Tk's internal data structures for the window get modified to + * reflect the structural change. + * + *---------------------------------------------------------------------- + */ + +static void +TopLevelEventProc(clientData, eventPtr) + ClientData clientData; /* Window for which event occurred. */ + XEvent *eventPtr; /* Event that just happened. */ +{ + register TkWindow *winPtr = (TkWindow *) clientData; + + if (eventPtr->type == DestroyNotify) { + Tk_ErrorHandler handler; + + if (!(winPtr->flags & TK_ALREADY_DEAD)) { + /* + * A top-level window was deleted externally (e.g., by the window + * manager). This is probably not a good thing, but cleanup as + * best we can. The error handler is needed because + * Tk_DestroyWindow will try to destroy the window, but of course + * it's already gone. + */ + + handler = Tk_CreateErrorHandler(winPtr->display, -1, -1, -1, + (Tk_ErrorProc *) NULL, (ClientData) NULL); + Tk_DestroyWindow((Tk_Window) winPtr); + Tk_DeleteErrorHandler(handler); + } + } + else if (eventPtr->type == ConfigureNotify) { + WmInfo *wmPtr; + wmPtr = winPtr->wmInfoPtr; + + if (winPtr->flags & TK_EMBEDDED) { + Tk_Window tkwin = (Tk_Window)winPtr; + SendMessage(wmPtr->wrapper, TK_GEOMETRYREQ, Tk_ReqWidth(tkwin), + Tk_ReqHeight(tkwin)); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TopLevelReqProc -- + * + * This procedure is invoked by the geometry manager whenever + * the requested size for a top-level window is changed. + * + * Results: + * None. + * + * Side effects: + * Arrange for the window to be resized to satisfy the request + * (this happens as a when-idle action). + * + *---------------------------------------------------------------------- + */ + + /* ARGSUSED */ +static void +TopLevelReqProc(dummy, tkwin) + ClientData dummy; /* Not used. */ + Tk_Window tkwin; /* Information about window. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + WmInfo *wmPtr; + + wmPtr = winPtr->wmInfoPtr; + if (winPtr->flags & TK_EMBEDDED) { + SendMessage(wmPtr->wrapper, TK_GEOMETRYREQ, Tk_ReqWidth(tkwin), + Tk_ReqHeight(tkwin)); + } + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } +} + +/* + *---------------------------------------------------------------------- + * + * UpdateGeometryInfo -- + * + * This procedure is invoked when a top-level window is first + * mapped, and also as a when-idle procedure, to bring the + * geometry and/or position of a top-level window back into + * line with what has been requested by the user and/or widgets. + * This procedure doesn't return until the system has + * responded to the geometry change. + * + * Results: + * None. + * + * Side effects: + * The window's size and location may change, unless the WM prevents + * that from happening. + * + *---------------------------------------------------------------------- + */ + +static void +UpdateGeometryInfo(clientData) + ClientData clientData; /* Pointer to the window's record. */ +{ + int x, y; /* Position of border on desktop. */ + int width, height; /* Size of client area. */ + RECT rect; + register TkWindow *winPtr = (TkWindow *) clientData; + register WmInfo *wmPtr = winPtr->wmInfoPtr; + + wmPtr->flags &= ~WM_UPDATE_PENDING; + + /* + * If the window is minimized or maximized, we should not update + * our geometry since it will end up with the wrong values. + * ConfigureToplevel will reschedule UpdateGeometryInfo when the + * state of the window changes. + */ + + if (IsIconic(wmPtr->wrapper) || IsZoomed(wmPtr->wrapper)) { + return; + } + + /* + * Compute the border size for the current window style. This + * size will include the resize handles, the title bar and the + * menubar. Note that this size will not be correct if the + * menubar spans multiple lines. The height will be off by a + * multiple of the menubar height. It really only measures the + * minimum size of the border. + */ + + rect.left = rect.right = rect.top = rect.bottom = 0; + AdjustWindowRectEx(&rect, wmPtr->style, wmPtr->hMenu != NULL, + wmPtr->exStyle); + wmPtr->borderWidth = rect.right - rect.left; + wmPtr->borderHeight = rect.bottom - rect.top; + + /* + * Compute the new size for the top-level window. See the + * user documentation for details on this, but the size + * requested depends on (a) the size requested internally + * by the window's widgets, (b) the size requested by the + * user in a "wm geometry" command or via wm-based interactive + * resizing (if any), and (c) whether or not the window is + * gridded. Don't permit sizes <= 0 because this upsets + * the X server. + */ + + if (wmPtr->width == -1) { + width = winPtr->reqWidth; + } else if (wmPtr->gridWin != NULL) { + width = winPtr->reqWidth + + (wmPtr->width - wmPtr->reqGridWidth)*wmPtr->widthInc; + } else { + width = wmPtr->width; + } + if (width <= 0) { + width = 1; + } + if (wmPtr->height == -1) { + height = winPtr->reqHeight; + } else if (wmPtr->gridWin != NULL) { + height = winPtr->reqHeight + + (wmPtr->height - wmPtr->reqGridHeight)*wmPtr->heightInc; + } else { + height = wmPtr->height; + } + if (height <= 0) { + height = 1; + } + + /* + * Compute the new position for the upper-left pixel of the window's + * decorative frame. This is tricky, because we need to include the + * border widths supplied by a reparented parent in this calculation, + * but can't use the parent's current overall size since that may + * change as a result of this code. + */ + + if (wmPtr->flags & WM_NEGATIVE_X) { + x = DisplayWidth(winPtr->display, winPtr->screenNum) - wmPtr->x + - (width + wmPtr->borderWidth); + } else { + x = wmPtr->x; + } + if (wmPtr->flags & WM_NEGATIVE_Y) { + y = DisplayHeight(winPtr->display, winPtr->screenNum) - wmPtr->y + - (height + wmPtr->borderHeight); + } else { + y = wmPtr->y; + } + + /* + * If this window is embedded and the container is also in this + * process, we don't need to do anything special about the + * geometry, except to make sure that the desired size is known + * by the container. Also, zero out any position information, + * since embedded windows are not allowed to move. + */ + + if (winPtr->flags & TK_BOTH_HALVES) { + wmPtr->x = wmPtr->y = 0; + wmPtr->flags &= ~(WM_NEGATIVE_X|WM_NEGATIVE_Y); + Tk_GeometryRequest((Tk_Window) TkpGetOtherWindow(winPtr), + width, height); + return; + } + + /* + * Reconfigure the window if it isn't already configured correctly. Base + * the size check on what we *asked for* last time, not what we got. + * Return immediately if there have been no changes in the requested + * geometry of the toplevel. + */ + /* TODO: need to add flag for possible menu size change */ + + if (!((wmPtr->flags & WM_MOVE_PENDING) + || (width != wmPtr->configWidth) + || (height != wmPtr->configHeight))) { + return; + } + wmPtr->flags &= ~WM_MOVE_PENDING; + + wmPtr->configWidth = width; + wmPtr->configHeight = height; + + /* + * Don't bother moving the window if we are in the process of + * creating it. Just update the geometry info based on what + * we asked for. + */ + + if (wmPtr->flags & WM_CREATE_PENDING) { + winPtr->changes.x = x; + winPtr->changes.y = y; + winPtr->changes.width = width; + winPtr->changes.height = height; + return; + } + + wmPtr->flags |= WM_SYNC_PENDING; + if (winPtr->flags & TK_EMBEDDED) { + /* + * The wrapper window is in a different process, so we need + * to send it a geometry request. This protocol assumes that + * the other process understands this Tk message, otherwise + * our requested geometry will be ignored. + */ + + SendMessage(wmPtr->wrapper, TK_GEOMETRYREQ, width, height); + } else { + int reqHeight, reqWidth; + RECT windowRect; + int menuInc = GetSystemMetrics(SM_CYMENU); + int newHeight; + + /* + * We have to keep resizing the window until we get the + * requested height in the client area. If the client + * area has zero height, then the window rect is too + * small by definition. Try increasing the border height + * and try again. Once we have a positive size, then + * we can adjust the height exactly. If the window + * rect comes back smaller than we requested, we have + * hit the maximum constraints that Windows imposes. + * Once we find a positive client size, the next size + * is the one we try no matter what. + */ + + reqHeight = height + wmPtr->borderHeight; + reqWidth = width + wmPtr->borderWidth; + + while (1) { + MoveWindow(wmPtr->wrapper, x, y, reqWidth, reqHeight, TRUE); + GetWindowRect(wmPtr->wrapper, &windowRect); + newHeight = windowRect.bottom - windowRect.top; + + /* + * If the request wasn't satisfied, we have hit an external + * constraint and must stop. + */ + + if (newHeight < reqHeight) { + break; + } + + /* + * Now check the size of the client area against our ideal. + */ + + GetClientRect(wmPtr->wrapper, &windowRect); + newHeight = windowRect.bottom - windowRect.top; + + if (newHeight == height) { + /* + * We're done. + */ + break; + } else if (newHeight > height) { + /* + * One last resize to get rid of the extra space. + */ + menuInc = newHeight - height; + reqHeight -= menuInc; + if (wmPtr->flags & WM_NEGATIVE_Y) { + y += menuInc; + } + MoveWindow(wmPtr->wrapper, x, y, reqWidth, reqHeight, TRUE); + break; + } + + /* + * We didn't get enough space to satisfy our requested + * height, so the menu must have wrapped. Increase the + * size of the window by one menu height and move the + * window if it is positioned relative to the lower right + * corner of the screen. + */ + + reqHeight += menuInc; + if (wmPtr->flags & WM_NEGATIVE_Y) { + y -= menuInc; + } + } + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + DrawMenuBar(wmPtr->wrapper); + } + } + wmPtr->flags &= ~WM_SYNC_PENDING; +} + +/* + *-------------------------------------------------------------- + * + * ParseGeometry -- + * + * This procedure parses a geometry string and updates + * information used to control the geometry of a top-level + * window. + * + * Results: + * A standard Tcl return value, plus an error message in + * interp->result if an error occurs. + * + * Side effects: + * The size and/or location of winPtr may change. + * + *-------------------------------------------------------------- + */ + +static int +ParseGeometry(interp, string, winPtr) + Tcl_Interp *interp; /* Used for error reporting. */ + char *string; /* String containing new geometry. Has the + * standard form "=wxh+x+y". */ + TkWindow *winPtr; /* Pointer to top-level window whose + * geometry is to be changed. */ +{ + register WmInfo *wmPtr = winPtr->wmInfoPtr; + int x, y, width, height, flags; + char *end; + register char *p = string; + + /* + * The leading "=" is optional. + */ + + if (*p == '=') { + p++; + } + + /* + * Parse the width and height, if they are present. Don't + * actually update any of the fields of wmPtr until we've + * successfully parsed the entire geometry string. + */ + + width = wmPtr->width; + height = wmPtr->height; + x = wmPtr->x; + y = wmPtr->y; + flags = wmPtr->flags; + if (isdigit(UCHAR(*p))) { + width = strtoul(p, &end, 10); + p = end; + if (*p != 'x') { + goto error; + } + p++; + if (!isdigit(UCHAR(*p))) { + goto error; + } + height = strtoul(p, &end, 10); + p = end; + } + + /* + * Parse the X and Y coordinates, if they are present. + */ + + if (*p != '\0') { + flags &= ~(WM_NEGATIVE_X | WM_NEGATIVE_Y); + if (*p == '-') { + flags |= WM_NEGATIVE_X; + } else if (*p != '+') { + goto error; + } + p++; + if (!isdigit(UCHAR(*p)) && (*p != '-')) { + goto error; + } + x = strtol(p, &end, 10); + p = end; + if (*p == '-') { + flags |= WM_NEGATIVE_Y; + } else if (*p != '+') { + goto error; + } + p++; + if (!isdigit(UCHAR(*p)) && (*p != '-')) { + goto error; + } + y = strtol(p, &end, 10); + if (*end != '\0') { + goto error; + } + + /* + * Assume that the geometry information came from the user, + * unless an explicit source has been specified. Otherwise + * most window managers assume that the size hints were + * program-specified and they ignore them. + */ + + if ((wmPtr->sizeHintsFlags & (USPosition|PPosition)) == 0) { + wmPtr->sizeHintsFlags |= USPosition; + } + } + + /* + * Everything was parsed OK. Update the fields of *wmPtr and + * arrange for the appropriate information to be percolated out + * to the window manager at the next idle moment. + */ + + wmPtr->width = width; + wmPtr->height = height; + wmPtr->x = x; + wmPtr->y = y; + flags |= WM_MOVE_PENDING; + wmPtr->flags = flags; + + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } + return TCL_OK; + + error: + Tcl_AppendResult(interp, "bad geometry specifier \"", + string, "\"", (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetRootCoords -- + * + * Given a token for a window, this procedure traces through the + * window's lineage to find the (virtual) root-window coordinates + * corresponding to point (0,0) in the window. + * + * Results: + * The locations pointed to by xPtr and yPtr are filled in with + * the root coordinates of the (0,0) point in tkwin. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +Tk_GetRootCoords(tkwin, xPtr, yPtr) + Tk_Window tkwin; /* Token for window. */ + int *xPtr; /* Where to store x-displacement of (0,0). */ + int *yPtr; /* Where to store y-displacement of (0,0). */ +{ + register TkWindow *winPtr = (TkWindow *) tkwin; + + /* + * If the window is mapped, let Windows figure out the translation. + */ + + if (winPtr->window != None) { + HWND hwnd = Tk_GetHWND(winPtr->window); + POINT point; + + point.x = 0; + point.y = 0; + + ClientToScreen(hwnd, &point); + + *xPtr = point.x; + *yPtr = point.y; + } else { + *xPtr = 0; + *yPtr = 0; + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_CoordsToWindow -- + * + * Given the (virtual) root coordinates of a point, this procedure + * returns the token for the top-most window covering that point, + * if there exists such a window in this application. + * + * Results: + * The return result is either a token for the window corresponding + * to rootX and rootY, or else NULL to indicate that there is no such + * window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Tk_Window +Tk_CoordsToWindow(rootX, rootY, tkwin) + int rootX, rootY; /* Coordinates of point in root window. If + * a virtual-root window manager is in use, + * these coordinates refer to the virtual + * root, not the real root. */ + Tk_Window tkwin; /* Token for any window in application; + * used to identify the display. */ +{ + POINT pos; + HWND hwnd; + TkWindow *winPtr; + + pos.x = rootX; + pos.y = rootY; + hwnd = WindowFromPoint(pos); + + winPtr = (TkWindow *) Tk_HWNDToWindow(hwnd); + if (winPtr && (winPtr->mainPtr == ((TkWindow *) tkwin)->mainPtr)) { + return (Tk_Window) winPtr; + } + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetVRootGeometry -- + * + * This procedure returns information about the virtual root + * window corresponding to a particular Tk window. + * + * Results: + * The values at xPtr, yPtr, widthPtr, and heightPtr are set + * with the offset and dimensions of the root window corresponding + * to tkwin. If tkwin is being managed by a virtual root window + * manager these values correspond to the virtual root window being + * used for tkwin; otherwise the offsets will be 0 and the + * dimensions will be those of the screen. + * + * Side effects: + * Vroot window information is refreshed if it is out of date. + * + *---------------------------------------------------------------------- + */ + +void +Tk_GetVRootGeometry(tkwin, xPtr, yPtr, widthPtr, heightPtr) + Tk_Window tkwin; /* Window whose virtual root is to be + * queried. */ + int *xPtr, *yPtr; /* Store x and y offsets of virtual root + * here. */ + int *widthPtr, *heightPtr; /* Store dimensions of virtual root here. */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + + *xPtr = 0; + *yPtr = 0; + *widthPtr = DisplayWidth(winPtr->display, winPtr->screenNum); + *heightPtr = DisplayHeight(winPtr->display, winPtr->screenNum); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_MoveToplevelWindow -- + * + * This procedure is called instead of Tk_MoveWindow to adjust + * the x-y location of a top-level window. It delays the actual + * move to a later time and keeps window-manager information + * up-to-date with the move + * + * Results: + * None. + * + * Side effects: + * The window is eventually moved so that its upper-left corner + * (actually, the upper-left corner of the window's decorative + * frame, if there is one) is at (x,y). + * + *---------------------------------------------------------------------- + */ + +void +Tk_MoveToplevelWindow(tkwin, x, y) + Tk_Window tkwin; /* Window to move. */ + int x, y; /* New location for window (within + * parent). */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + register WmInfo *wmPtr = winPtr->wmInfoPtr; + + if (!(winPtr->flags & TK_TOP_LEVEL)) { + panic("Tk_MoveToplevelWindow called with non-toplevel window"); + } + wmPtr->x = x; + wmPtr->y = y; + wmPtr->flags |= WM_MOVE_PENDING; + wmPtr->flags &= ~(WM_NEGATIVE_X|WM_NEGATIVE_Y); + if ((wmPtr->sizeHintsFlags & (USPosition|PPosition)) == 0) { + wmPtr->sizeHintsFlags |= USPosition; + } + + /* + * If the window has already been mapped, must bring its geometry + * up-to-date immediately, otherwise an event might arrive from the + * server that would overwrite wmPtr->x and wmPtr->y and lose the + * new position. + */ + + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + if (wmPtr->flags & WM_UPDATE_PENDING) { + Tcl_CancelIdleCall(UpdateGeometryInfo, (ClientData) winPtr); + } + UpdateGeometryInfo((ClientData) winPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWmProtocolEventProc -- + * + * This procedure is called by the Tk_HandleEvent whenever a + * ClientMessage event arrives whose type is "WM_PROTOCOLS". + * This procedure handles the message from the window manager + * in an appropriate fashion. + * + * Results: + * None. + * + * Side effects: + * Depends on what sort of handler, if any, was set up for the + * protocol. + * + *---------------------------------------------------------------------- + */ + +void +TkWmProtocolEventProc(winPtr, eventPtr) + TkWindow *winPtr; /* Window to which the event was sent. */ + XEvent *eventPtr; /* X event. */ +{ + WmInfo *wmPtr; + register ProtocolHandler *protPtr; + Atom protocol; + int result; + Tcl_Interp *interp; + + wmPtr = winPtr->wmInfoPtr; + if (wmPtr == NULL) { + return; + } + protocol = (Atom) eventPtr->xclient.data.l[0]; + for (protPtr = wmPtr->protPtr; protPtr != NULL; + protPtr = protPtr->nextPtr) { + if (protocol == protPtr->protocol) { + Tcl_Preserve((ClientData) protPtr); + interp = protPtr->interp; + Tcl_Preserve((ClientData) interp); + result = Tcl_GlobalEval(interp, protPtr->command); + if (result != TCL_OK) { + Tcl_AddErrorInfo(interp, "\n (command for \""); + Tcl_AddErrorInfo(interp, + Tk_GetAtomName((Tk_Window) winPtr, protocol)); + Tcl_AddErrorInfo(interp, "\" window manager protocol)"); + Tcl_BackgroundError(interp); + } + Tcl_Release((ClientData) interp); + Tcl_Release((ClientData) protPtr); + return; + } + } + + /* + * No handler was present for this protocol. If this is a + * WM_DELETE_WINDOW message then just destroy the window. + */ + + if (protocol == Tk_InternAtom((Tk_Window) winPtr, "WM_DELETE_WINDOW")) { + Tk_DestroyWindow((Tk_Window) winPtr); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWmRestackToplevel -- + * + * This procedure restacks a top-level window. + * + * Results: + * None. + * + * Side effects: + * WinPtr gets restacked as specified by aboveBelow and otherPtr. + * This procedure doesn't return until the restack has taken + * effect and the ConfigureNotify event for it has been received. + * + *---------------------------------------------------------------------- + */ + +void +TkWmRestackToplevel(winPtr, aboveBelow, otherPtr) + TkWindow *winPtr; /* Window to restack. */ + int aboveBelow; /* Gives relative position for restacking; + * must be Above or Below. */ + TkWindow *otherPtr; /* Window relative to which to restack; + * if NULL, then winPtr gets restacked + * above or below *all* siblings. */ +{ + HWND hwnd, insertAfter; + + /* + * Can't set stacking order properly until the window is on the + * screen (mapping it may give it a reparent window). + */ + + if (winPtr->window == None) { + Tk_MakeWindowExist((Tk_Window) winPtr); + } + if (winPtr->wmInfoPtr->flags & WM_NEVER_MAPPED) { + TkWmMapWindow(winPtr); + } + hwnd = (winPtr->wmInfoPtr->wrapper != NULL) + ? winPtr->wmInfoPtr->wrapper : Tk_GetHWND(winPtr->window); + + + if (otherPtr != NULL) { + if (otherPtr->window == None) { + Tk_MakeWindowExist((Tk_Window) otherPtr); + } + if (otherPtr->wmInfoPtr->flags & WM_NEVER_MAPPED) { + TkWmMapWindow(otherPtr); + } + insertAfter = (otherPtr->wmInfoPtr->wrapper != NULL) + ? otherPtr->wmInfoPtr->wrapper : Tk_GetHWND(otherPtr->window); + } else { + insertAfter = NULL; + } + + TkWinSetWindowPos(hwnd, insertAfter, aboveBelow); +} + +/* + *---------------------------------------------------------------------- + * + * TkWmAddToColormapWindows -- + * + * This procedure is called to add a given window to the + * WM_COLORMAP_WINDOWS property for its top-level, if it + * isn't already there. It is invoked by the Tk code that + * creates a new colormap, in order to make sure that colormap + * information is propagated to the window manager by default. + * + * Results: + * None. + * + * Side effects: + * WinPtr's window gets added to the WM_COLORMAP_WINDOWS + * property of its nearest top-level ancestor, unless the + * colormaps have been set explicitly with the + * "wm colormapwindows" command. + * + *---------------------------------------------------------------------- + */ + +void +TkWmAddToColormapWindows(winPtr) + TkWindow *winPtr; /* Window with a non-default colormap. + * Should not be a top-level window. */ +{ + TkWindow *topPtr; + TkWindow **oldPtr, **newPtr; + int count, i; + + if (winPtr->window == None) { + return; + } + + for (topPtr = winPtr->parentPtr; ; topPtr = topPtr->parentPtr) { + if (topPtr == NULL) { + /* + * Window is being deleted. Skip the whole operation. + */ + + return; + } + if (topPtr->flags & TK_TOP_LEVEL) { + break; + } + } + if (topPtr->wmInfoPtr->flags & WM_COLORMAPS_EXPLICIT) { + return; + } + + /* + * Make sure that the window isn't already in the list. + */ + + count = topPtr->wmInfoPtr->cmapCount; + oldPtr = topPtr->wmInfoPtr->cmapList; + + for (i = 0; i < count; i++) { + if (oldPtr[i] == winPtr) { + return; + } + } + + /* + * Make a new bigger array and use it to reset the property. + * Automatically add the toplevel itself as the last element + * of the list. + */ + + newPtr = (TkWindow **) ckalloc((unsigned) ((count+2)*sizeof(TkWindow*))); + if (count > 0) { + memcpy(newPtr, oldPtr, count * sizeof(TkWindow*)); + } + if (count == 0) { + count++; + } + newPtr[count-1] = winPtr; + newPtr[count] = topPtr; + if (oldPtr != NULL) { + ckfree((char *) oldPtr); + } + + topPtr->wmInfoPtr->cmapList = newPtr; + topPtr->wmInfoPtr->cmapCount = count+1; + + /* + * Now we need to force the updated colormaps to be installed. + */ + + if (topPtr->wmInfoPtr == foregroundWmPtr) { + InstallColormaps(topPtr->wmInfoPtr->wrapper, WM_QUERYNEWPALETTE, 1); + } else { + InstallColormaps(topPtr->wmInfoPtr->wrapper, WM_PALETTECHANGED, 0); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWmRemoveFromColormapWindows -- + * + * This procedure is called to remove a given window from the + * WM_COLORMAP_WINDOWS property for its top-level. It is invoked + * when windows are deleted. + * + * Results: + * None. + * + * Side effects: + * WinPtr's window gets removed from the WM_COLORMAP_WINDOWS + * property of its nearest top-level ancestor, unless the + * top-level itself is being deleted too. + * + *---------------------------------------------------------------------- + */ + +void +TkWmRemoveFromColormapWindows(winPtr) + TkWindow *winPtr; /* Window that may be present in + * WM_COLORMAP_WINDOWS property for its + * top-level. Should not be a top-level + * window. */ +{ + TkWindow *topPtr; + TkWindow **oldPtr; + int count, i, j; + + for (topPtr = winPtr->parentPtr; ; topPtr = topPtr->parentPtr) { + if (topPtr == NULL) { + /* + * Ancestors have been deleted, so skip the whole operation. + * Seems like this can't ever happen? + */ + + return; + } + if (topPtr->flags & TK_TOP_LEVEL) { + break; + } + } + if (topPtr->flags & TK_ALREADY_DEAD) { + /* + * Top-level is being deleted, so there's no need to cleanup + * the WM_COLORMAP_WINDOWS property. + */ + + return; + } + + /* + * Find the window and slide the following ones down to cover + * it up. + */ + + count = topPtr->wmInfoPtr->cmapCount; + oldPtr = topPtr->wmInfoPtr->cmapList; + for (i = 0; i < count; i++) { + if (oldPtr[i] == winPtr) { + for (j = i ; j < count-1; j++) { + oldPtr[j] = oldPtr[j+1]; + } + topPtr->wmInfoPtr->cmapCount = count-1; + break; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWinSetMenu-- + * + * Associcates a given HMENU to a window. + * + * Results: + * None. + * + * Side effects: + * The menu will end up being drawn in the window, and the geometry + * of the window will have to be changed. + * + *---------------------------------------------------------------------- + */ + +void +TkWinSetMenu(tkwin, hMenu) + Tk_Window tkwin; /* the window to put the menu in */ + HMENU hMenu; /* the menu to set */ +{ + TkWindow *winPtr = (TkWindow *) tkwin; + WmInfo *wmPtr = winPtr->wmInfoPtr; + + wmPtr->hMenu = hMenu; + + if (!(wmPtr->flags & TK_EMBEDDED)) { + if (!(wmPtr->flags & WM_NEVER_MAPPED)) { + int syncPending = wmPtr->flags & WM_SYNC_PENDING; + + wmPtr->flags |= WM_SYNC_PENDING; + SetMenu(wmPtr->wrapper, hMenu); + if (!syncPending) { + wmPtr->flags &= ~WM_SYNC_PENDING; + } + } + if (!(wmPtr->flags & (WM_UPDATE_PENDING|WM_NEVER_MAPPED))) { + Tcl_DoWhenIdle(UpdateGeometryInfo, (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING|WM_MOVE_PENDING; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * ConfigureTopLevel -- + * + * Generate a ConfigureNotify event based on the current position + * information. This procedure is called by TopLevelProc. + * + * Results: + * None. + * + * Side effects: + * Queues a new event. + * + *---------------------------------------------------------------------- + */ + +static void +ConfigureTopLevel(pos) + WINDOWPOS *pos; +{ + TkWindow *winPtr = GetTopLevel(pos->hwnd); + WmInfo *wmPtr; + int state; /* Current window state. */ + RECT rect; + WINDOWPLACEMENT windowPos; + + if (winPtr == NULL) { + return; + } + + wmPtr = winPtr->wmInfoPtr; + + /* + * Determine the current window state. + */ + + if (!IsWindowVisible(wmPtr->wrapper)) { + state = WithdrawnState; + } else { + windowPos.length = sizeof(WINDOWPLACEMENT); + GetWindowPlacement(wmPtr->wrapper, &windowPos); + switch (windowPos.showCmd) { + case SW_SHOWMAXIMIZED: + state = ZoomState; + break; + case SW_SHOWMINIMIZED: + state = IconicState; + break; + case SW_SHOWNORMAL: + state = NormalState; + break; + } + } + + /* + * If the state of the window just changed, be sure to update the + * child window information. + */ + + if (wmPtr->hints.initial_state != state) { + wmPtr->hints.initial_state = state; + switch (state) { + case WithdrawnState: + case IconicState: + XUnmapWindow(winPtr->display, winPtr->window); + break; + + case NormalState: + /* + * Schedule a geometry update. Since we ignore geometry + * requests while in any other state, the geometry info + * may be stale. + */ + + if (!(wmPtr->flags & WM_UPDATE_PENDING)) { + Tcl_DoWhenIdle(UpdateGeometryInfo, + (ClientData) winPtr); + wmPtr->flags |= WM_UPDATE_PENDING; + } + /* fall through */ + case ZoomState: + XMapWindow(winPtr->display, winPtr->window); + pos->flags |= SWP_NOMOVE | SWP_NOSIZE; + break; + } + } + + /* + * Don't report geometry changes in the Iconic or Withdrawn states. + */ + + if (state == WithdrawnState || state == IconicState) { + return; + } + + + /* + * Compute the current geometry of the client area, reshape the + * Tk window and generate a ConfigureNotify event. + */ + + GetClientRect(wmPtr->wrapper, &rect); + winPtr->changes.x = pos->x; + winPtr->changes.y = pos->y; + winPtr->changes.width = rect.right - rect.left; + winPtr->changes.height = rect.bottom - rect.top; + wmPtr->borderHeight = pos->cy - winPtr->changes.height; + MoveWindow(Tk_GetHWND(winPtr->window), 0, 0, + winPtr->changes.width, winPtr->changes.height, TRUE); + GenerateConfigureNotify(winPtr); + + /* + * Update window manager geometry info if needed. + */ + + if (state == NormalState) { + + /* + * Update size information from the event. There are a couple of + * tricky points here: + * + * 1. If the user changed the size externally then set wmPtr->width + * and wmPtr->height just as if a "wm geometry" command had been + * invoked with the same information. + * 2. However, if the size is changing in response to a request + * coming from us (sync is set), then don't set + * wmPtr->width or wmPtr->height (otherwise the window will stop + * tracking geometry manager requests). + */ + + if (!(wmPtr->flags & WM_SYNC_PENDING)) { + if (!(pos->flags & SWP_NOSIZE)) { + if ((wmPtr->width == -1) + && (winPtr->changes.width == winPtr->reqWidth)) { + /* + * Don't set external width, since the user didn't + * change it from what the widgets asked for. + */ + } else { + if (wmPtr->gridWin != NULL) { + wmPtr->width = wmPtr->reqGridWidth + + (winPtr->changes.width - winPtr->reqWidth) + / wmPtr->widthInc; + if (wmPtr->width < 0) { + wmPtr->width = 0; + } + } else { + wmPtr->width = winPtr->changes.width; + } + } + if ((wmPtr->height == -1) + && (winPtr->changes.height == winPtr->reqHeight)) { + /* + * Don't set external height, since the user didn't change + * it from what the widgets asked for. + */ + } else { + if (wmPtr->gridWin != NULL) { + wmPtr->height = wmPtr->reqGridHeight + + (winPtr->changes.height - winPtr->reqHeight) + / wmPtr->heightInc; + if (wmPtr->height < 0) { + wmPtr->height = 0; + } + } else { + wmPtr->height = winPtr->changes.height; + } + } + wmPtr->configWidth = winPtr->changes.width; + wmPtr->configHeight = winPtr->changes.height; + } + /* + * If the user moved the window, we should switch back + * to normal coordinates. + */ + + if (!(pos->flags & SWP_NOMOVE)) { + wmPtr->flags &= ~(WM_NEGATIVE_X | WM_NEGATIVE_Y); + } + } + + /* + * Update the wrapper window location information. + */ + + if (wmPtr->flags & WM_NEGATIVE_X) { + wmPtr->x = DisplayWidth(winPtr->display, winPtr->screenNum) + - winPtr->changes.x - (winPtr->changes.width + + wmPtr->borderWidth); + } else { + wmPtr->x = winPtr->changes.x; + } + if (wmPtr->flags & WM_NEGATIVE_Y) { + wmPtr->y = DisplayHeight(winPtr->display, winPtr->screenNum) + - winPtr->changes.y - (winPtr->changes.height + + wmPtr->borderHeight); + } else { + wmPtr->y = winPtr->changes.y; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * GenerateConfigureNotify -- + * + * Generate a ConfigureNotify event from the current geometry + * information for the specified toplevel window. + * + * Results: + * None. + * + * Side effects: + * Sends an X event. + * + *---------------------------------------------------------------------- + */ + +static void +GenerateConfigureNotify(winPtr) + TkWindow *winPtr; +{ + XEvent event; + + /* + * Generate a ConfigureNotify event. + */ + + event.type = ConfigureNotify; + event.xconfigure.serial = winPtr->display->request; + event.xconfigure.send_event = False; + event.xconfigure.display = winPtr->display; + event.xconfigure.event = winPtr->window; + event.xconfigure.window = winPtr->window; + event.xconfigure.border_width = winPtr->changes.border_width; + event.xconfigure.override_redirect = winPtr->atts.override_redirect; + event.xconfigure.x = winPtr->changes.x; + event.xconfigure.y = winPtr->changes.y; + event.xconfigure.width = winPtr->changes.width; + event.xconfigure.height = winPtr->changes.height; + event.xconfigure.above = None; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); +} + +/* + *---------------------------------------------------------------------- + * + * InstallColormaps -- + * + * Installs the colormaps associated with the toplevel which is + * currently active. + * + * Results: + * None. + * + * Side effects: + * May change the system palette and generate damage. + * + *---------------------------------------------------------------------- + */ + +static int +InstallColormaps(hwnd, message, isForemost) + HWND hwnd; /* Toplevel wrapper window whose colormaps + * should be installed. */ + int message; /* Either WM_PALETTECHANGED or + * WM_QUERYNEWPALETTE */ + int isForemost; /* 1 if window is foremost, else 0 */ +{ + int i; + HDC dc; + HPALETTE oldPalette; + TkWindow *winPtr = GetTopLevel(hwnd); + WmInfo *wmPtr; + + if (winPtr == NULL) { + return 0; + } + + wmPtr = winPtr->wmInfoPtr; + + if (message == WM_QUERYNEWPALETTE) { + /* + * Case 1: This window is about to become the foreground window, so we + * need to install the primary palette. If the system palette was + * updated, then Windows will generate a WM_PALETTECHANGED message. + * Otherwise, we have to synthesize one in order to ensure that the + * secondary palettes are installed properly. + */ + + foregroundWmPtr = wmPtr; + + if (wmPtr->cmapCount > 0) { + winPtr = wmPtr->cmapList[0]; + } + + systemPalette = TkWinGetPalette(winPtr->atts.colormap); + dc = GetDC(hwnd); + oldPalette = SelectPalette(dc, systemPalette, FALSE); + if (RealizePalette(dc)) { + RefreshColormap(winPtr->atts.colormap); + } else if (wmPtr->cmapCount > 1) { + SelectPalette(dc, oldPalette, TRUE); + RealizePalette(dc); + ReleaseDC(hwnd, dc); + SendMessage(hwnd, WM_PALETTECHANGED, (WPARAM)hwnd, + (LPARAM)NULL); + return TRUE; + } + + } else { + /* + * Window is being notified of a change in the system palette. + * If this window is the foreground window, then we should only + * install the secondary palettes, since the primary was installed + * in response to the WM_QUERYPALETTE message. Otherwise, install + * all of the palettes. + */ + + + if (!isForemost) { + if (wmPtr->cmapCount > 0) { + winPtr = wmPtr->cmapList[0]; + } + i = 1; + } else { + if (wmPtr->cmapCount <= 1) { + return TRUE; + } + winPtr = wmPtr->cmapList[1]; + i = 2; + } + dc = GetDC(hwnd); + oldPalette = SelectPalette(dc, + TkWinGetPalette(winPtr->atts.colormap), TRUE); + if (RealizePalette(dc)) { + RefreshColormap(winPtr->atts.colormap); + } + for (; i < wmPtr->cmapCount; i++) { + winPtr = wmPtr->cmapList[i]; + SelectPalette(dc, TkWinGetPalette(winPtr->atts.colormap), TRUE); + if (RealizePalette(dc)) { + RefreshColormap(winPtr->atts.colormap); + } + } + } + + SelectPalette(dc, oldPalette, TRUE); + RealizePalette(dc); + ReleaseDC(hwnd, dc); + return TRUE; +} + +/* + *---------------------------------------------------------------------- + * + * RefreshColormap -- + * + * This function is called to force all of the windows that use + * a given colormap to redraw themselves. The quickest way to + * do this is to iterate over the toplevels, looking in the + * cmapList for matches. This will quickly eliminate subtrees + * that don't use a given colormap. + * + * Results: + * None. + * + * Side effects: + * Causes damage events to be generated. + * + *---------------------------------------------------------------------- + */ + +static void +RefreshColormap(colormap) + Colormap colormap; +{ + WmInfo *wmPtr; + int i; + + for (wmPtr = firstWmPtr; wmPtr != NULL; wmPtr = wmPtr->nextPtr) { + if (wmPtr->cmapCount > 0) { + for (i = 0; i < wmPtr->cmapCount; i++) { + if ((wmPtr->cmapList[i]->atts.colormap == colormap) + && Tk_IsMapped(wmPtr->cmapList[i])) { + InvalidateSubTree(wmPtr->cmapList[i], colormap); + } + } + } else if ((wmPtr->winPtr->atts.colormap == colormap) + && Tk_IsMapped(wmPtr->winPtr)) { + InvalidateSubTree(wmPtr->winPtr, colormap); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * InvalidateSubTree -- + * + * This function recursively generates damage for a window and + * all of its mapped children that belong to the same toplevel and + * are using the specified colormap. + * + * Results: + * None. + * + * Side effects: + * Generates damage for the specified subtree. + * + *---------------------------------------------------------------------- + */ + +static void +InvalidateSubTree(winPtr, colormap) + TkWindow *winPtr; + Colormap colormap; +{ + TkWindow *childPtr; + + /* + * Generate damage for the current window if it is using the + * specified colormap. + */ + + if (winPtr->atts.colormap == colormap) { + InvalidateRect(Tk_GetHWND(winPtr->window), NULL, FALSE); + } + + for (childPtr = winPtr->childList; childPtr != NULL; + childPtr = childPtr->nextPtr) { + /* + * We can stop the descent when we hit an unmapped or + * toplevel window. + */ + + if (!Tk_IsTopLevel(childPtr) && Tk_IsMapped(childPtr)) { + InvalidateSubTree(childPtr, colormap); + } + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWinGetSystemPalette -- + * + * Retrieves the currently installed foreground palette. + * + * Results: + * Returns the global foreground palette, if there is one. + * Otherwise, returns NULL. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +HPALETTE +TkWinGetSystemPalette() +{ + return systemPalette; +} + +/* + *---------------------------------------------------------------------- + * + * GetMinSize -- + * + * This procedure computes the current minWidth and minHeight + * values for a window, taking into account the possibility + * that they may be defaulted. + * + * Results: + * The values at *minWidthPtr and *minHeightPtr are filled + * in with the minimum allowable dimensions of wmPtr's window, + * in grid units. If the requested minimum is smaller than the + * system required minimum, then this procedure computes the + * smallest size that will satisfy both the system and the + * grid constraints. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +GetMinSize(wmPtr, minWidthPtr, minHeightPtr) + WmInfo *wmPtr; /* Window manager information for the + * window. */ + int *minWidthPtr; /* Where to store the current minimum + * width of the window. */ + int *minHeightPtr; /* Where to store the current minimum + * height of the window. */ +{ + int tmp, base; + TkWindow *winPtr = wmPtr->winPtr; + + /* + * Compute the minimum width by taking the default client size + * and rounding it up to the nearest grid unit. Return the greater + * of the default minimum and the specified minimum. + */ + + tmp = wmPtr->defMinWidth - wmPtr->borderWidth; + if (tmp < 0) { + tmp = 0; + } + if (wmPtr->gridWin != NULL) { + base = winPtr->reqWidth - (wmPtr->reqGridWidth * wmPtr->widthInc); + if (base < 0) { + base = 0; + } + tmp = ((tmp - base) + wmPtr->widthInc - 1)/wmPtr->widthInc; + } + if (tmp < wmPtr->minWidth) { + tmp = wmPtr->minWidth; + } + *minWidthPtr = tmp; + + /* + * Compute the minimum height in a similar fashion. + */ + + tmp = wmPtr->defMinHeight - wmPtr->borderHeight; + if (tmp < 0) { + tmp = 0; + } + if (wmPtr->gridWin != NULL) { + base = winPtr->reqHeight - (wmPtr->reqGridHeight * wmPtr->heightInc); + if (base < 0) { + base = 0; + } + tmp = ((tmp - base) + wmPtr->heightInc - 1)/wmPtr->heightInc; + } + if (tmp < wmPtr->minHeight) { + tmp = wmPtr->minHeight; + } + *minHeightPtr = tmp; +} + +/* + *---------------------------------------------------------------------- + * + * GetMaxSize -- + * + * This procedure computes the current maxWidth and maxHeight + * values for a window, taking into account the possibility + * that they may be defaulted. + * + * Results: + * The values at *maxWidthPtr and *maxHeightPtr are filled + * in with the maximum allowable dimensions of wmPtr's window, + * in grid units. If no maximum has been specified for the + * window, then this procedure computes the largest sizes that + * will fit on the screen. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static void +GetMaxSize(wmPtr, maxWidthPtr, maxHeightPtr) + WmInfo *wmPtr; /* Window manager information for the + * window. */ + int *maxWidthPtr; /* Where to store the current maximum + * width of the window. */ + int *maxHeightPtr; /* Where to store the current maximum + * height of the window. */ +{ + int tmp; + + if (wmPtr->maxWidth > 0) { + *maxWidthPtr = wmPtr->maxWidth; + } else { + /* + * Must compute a default width. Fill up the display, leaving a + * bit of extra space for the window manager's borders. + */ + + tmp = wmPtr->defMaxWidth - wmPtr->borderWidth; + if (wmPtr->gridWin != NULL) { + /* + * Gridding is turned on; convert from pixels to grid units. + */ + + tmp = wmPtr->reqGridWidth + + (tmp - wmPtr->winPtr->reqWidth)/wmPtr->widthInc; + } + *maxWidthPtr = tmp; + } + if (wmPtr->maxHeight > 0) { + *maxHeightPtr = wmPtr->maxHeight; + } else { + tmp = wmPtr->defMaxHeight - wmPtr->borderHeight; + if (wmPtr->gridWin != NULL) { + tmp = wmPtr->reqGridHeight + + (tmp - wmPtr->winPtr->reqHeight)/wmPtr->heightInc; + } + *maxHeightPtr = tmp; + } +} + +/* + *---------------------------------------------------------------------- + * + * TopLevelProc -- + * + * Callback from Windows whenever an event occurs on a top level + * window. + * + * Results: + * Standard Windows return value. + * + * Side effects: + * Default window behavior. + * + *---------------------------------------------------------------------- + */ + +static LRESULT CALLBACK +TopLevelProc(hwnd, message, wParam, lParam) + HWND hwnd; + UINT message; + WPARAM wParam; + LPARAM lParam; +{ + if (message == WM_WINDOWPOSCHANGED) { + WINDOWPOS *pos = (WINDOWPOS *) lParam; + TkWindow *winPtr = (TkWindow *) Tk_HWNDToWindow(pos->hwnd); + + if (winPtr == NULL) { + return 0; + } + + /* + * Update the shape of the contained window. + */ + + if (!(pos->flags & SWP_NOSIZE)) { + winPtr->changes.width = pos->cx; + winPtr->changes.height = pos->cy; + } + if (!(pos->flags & SWP_NOMOVE)) { + winPtr->changes.x = pos->x; + winPtr->changes.y = pos->y; + } + + GenerateConfigureNotify(winPtr); + + Tcl_ServiceAll(); + return 0; + } + return TkWinChildProc(hwnd, message, wParam, lParam); +} + +/* + *---------------------------------------------------------------------- + * + * WmProc -- + * + * Callback from Windows whenever an event occurs on the decorative + * frame. + * + * Results: + * Standard Windows return value. + * + * Side effects: + * Default window behavior. + * + *---------------------------------------------------------------------- + */ + +static LRESULT CALLBACK +WmProc(hwnd, message, wParam, lParam) + HWND hwnd; + UINT message; + WPARAM wParam; + LPARAM lParam; +{ + static int inMoveSize = 0; + static oldMode; /* This static is set upon entering move/size mode + * and is used to reset the service mode after + * leaving move/size mode. Note that this mechanism + * assumes move/size is only one level deep. */ + LRESULT result; + TkWindow *winPtr; + + if (TkWinHandleMenuEvent(&hwnd, &message, &wParam, &lParam, &result)) { + goto done; + } + + switch (message) { + case WM_KILLFOCUS: + case WM_ERASEBKGND: + result = 0; + goto done; + + case WM_ENTERSIZEMOVE: + inMoveSize = 1; + oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); + break; + + case WM_ACTIVATE: + case WM_EXITSIZEMOVE: + if (inMoveSize) { + inMoveSize = 0; + Tcl_SetServiceMode(oldMode); + } + break; + + case WM_GETMINMAXINFO: + SetLimits(hwnd, (MINMAXINFO *) lParam); + result = 0; + goto done; + + case WM_PALETTECHANGED: + result = InstallColormaps(hwnd, WM_PALETTECHANGED, + hwnd == (HWND)wParam); + goto done; + + case WM_QUERYNEWPALETTE: + result = InstallColormaps(hwnd, WM_QUERYNEWPALETTE, TRUE); + goto done; + + case WM_WINDOWPOSCHANGED: + ConfigureTopLevel((WINDOWPOS *) lParam); + result = 0; + goto done; + + default: + break; + } + + winPtr = GetTopLevel(hwnd); + if (winPtr && winPtr->window) { + HWND child = Tk_GetHWND(winPtr->window); + if (message == WM_SETFOCUS) { + SetFocus(child); + result = 0; + } else if (!Tk_TranslateWinEvent(child, message, wParam, lParam, + &result)) { + result = DefWindowProc(hwnd, message, wParam, lParam); + } + } else { + result = DefWindowProc(hwnd, message, wParam, lParam); + } + + done: + Tcl_ServiceAll(); + return result; +} + +/* + *---------------------------------------------------------------------- + * + * TkpMakeMenuWindow -- + * + * Configure the window to be either a pull-down (or pop-up) + * menu, or as a toplevel (torn-off) menu or palette. + * + * Results: + * None. + * + * Side effects: + * Changes the style bit used to create a new Mac toplevel. + * + *---------------------------------------------------------------------- + */ + +void +TkpMakeMenuWindow(tkwin, transient) + Tk_Window tkwin; /* New window. */ + int transient; /* 1 means menu is only posted briefly as + * a popup or pulldown or cascade. 0 means + * menu is always visible, e.g. as a torn-off + * menu. Determines whether save_under and + * override_redirect should be set. */ +{ + XSetWindowAttributes atts; + + if (transient) { + atts.override_redirect = True; + atts.save_under = True; + } else { + atts.override_redirect = False; + atts.save_under = False; + } + + if ((atts.override_redirect != Tk_Attributes(tkwin)->override_redirect) + || (atts.save_under != Tk_Attributes(tkwin)->save_under)) { + Tk_ChangeWindowAttributes(tkwin, + CWOverrideRedirect|CWSaveUnder, &atts); + } + +} + +/* + *---------------------------------------------------------------------- + * + * TkWinGetWrapperWindow -- + * + * Gets the Windows HWND for a given window. + * + * Results: + * Returns the wrapper window for a Tk window. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +HWND +TkWinGetWrapperWindow( + Tk_Window tkwin) /* The window we need the wrapper from */ +{ + TkWindow *winPtr = (TkWindow *)tkwin; + return (winPtr->wmInfoPtr->wrapper); +} + + +/* + *---------------------------------------------------------------------- + * + * TkWmFocusToplevel -- + * + * This is a utility procedure invoked by focus-management code. It + * exists because of the extra wrapper windows that exist under + * Unix; its job is to map from wrapper windows to the + * corresponding toplevel windows. On PCs and Macs there are no + * wrapper windows so no mapping is necessary; this procedure just + * determines whether a window is a toplevel or not. + * + * Results: + * If winPtr is a toplevel window, returns the pointer to the + * window; otherwise returns NULL. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkWmFocusToplevel(winPtr) + TkWindow *winPtr; /* Window that received a focus-related + * event. */ +{ + if (!(winPtr->flags & TK_TOP_LEVEL)) { + return NULL; + } + return winPtr; +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetWrapperWindow -- + * + * This is a utility procedure invoked by focus-management code. It + * maps to the wrapper for a top-level, which is just the same + * as the top-level on Macs and PCs. + * + * Results: + * If winPtr is a toplevel window, returns the pointer to the + * window; otherwise returns NULL. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +TkWindow * +TkpGetWrapperWindow( + TkWindow *winPtr) /* Window that received a focus-related + * event. */ +{ + if (!(winPtr->flags & TK_TOP_LEVEL)) { + return NULL; + } + return winPtr; +} diff --git a/win/tkWinX.c b/win/tkWinX.c new file mode 100644 index 0000000..0b00186 --- /dev/null +++ b/win/tkWinX.c @@ -0,0 +1,1020 @@ +/* + * tkWinX.c -- + * + * This file contains Windows emulation procedures for X routines. + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * Copyright (c) 1994 Software Research Associates, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) tkWinX.c 1.51 97/09/02 13:06:57 + */ + +#include "tkInt.h" +#include "tkWinInt.h" + +/* + * Definitions of extern variables supplied by this file. + */ + +int tkpIsWin32s = -1; + +/* + * Declarations of static variables used in this file. + */ + +static HINSTANCE tkInstance = (HINSTANCE) NULL; + /* Global application instance handle. */ +static TkDisplay *winDisplay; /* Display that represents Windows screen. */ +static char winScreenName[] = ":0"; + /* Default name of windows display. */ +static WNDCLASS childClass; /* Window class for child windows. */ +static childClassInitialized = 0; /* Registered child class? */ + +/* + * Forward declarations of procedures used in this file. + */ + +static void GenerateXEvent _ANSI_ARGS_((HWND hwnd, UINT message, + WPARAM wParam, LPARAM lParam)); +static unsigned int GetState _ANSI_ARGS_((UINT message, WPARAM wParam, + LPARAM lParam)); +static void GetTranslatedKey _ANSI_ARGS_((XKeyEvent *xkey)); + +/* + *---------------------------------------------------------------------- + * + * TkGetServerInfo -- + * + * Given a window, this procedure returns information about + * the window server for that window. This procedure provides + * the guts of the "winfo server" command. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +TkGetServerInfo(interp, tkwin) + Tcl_Interp *interp; /* The server information is returned in + * this interpreter's result. */ + Tk_Window tkwin; /* Token for window; this selects a + * particular display and server. */ +{ + char buffer[50]; + OSVERSIONINFO info; + + info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&info); + sprintf(buffer, "Windows %d.%d %d ", info.dwMajorVersion, + info.dwMinorVersion, info.dwBuildNumber); + Tcl_AppendResult(interp, buffer, + (info.dwPlatformId == VER_PLATFORM_WIN32s) ? "Win32s" : "Win32", + (char *) NULL); +} + +/* + *---------------------------------------------------------------------- + * + * Tk_GetHINSTANCE -- + * + * Retrieves the global instance handle used by the Tk library. + * + * Results: + * Returns the global instance handle. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +HINSTANCE +Tk_GetHINSTANCE() +{ + return tkInstance; +} + +/* + *---------------------------------------------------------------------- + * + * TkWinXInit -- + * + * Initialize Xlib emulation layer. + * + * Results: + * None. + * + * Side effects: + * Sets up various data structures. + * + *---------------------------------------------------------------------- + */ + +void +TkWinXInit(hInstance) + HINSTANCE hInstance; +{ + OSVERSIONINFO info; + + info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&info); + tkpIsWin32s = (info.dwPlatformId == VER_PLATFORM_WIN32s); + + if (childClassInitialized != 0) { + return; + } + childClassInitialized = 1; + + tkInstance = hInstance; + + childClass.style = CS_HREDRAW | CS_VREDRAW | CS_CLASSDC; + childClass.cbClsExtra = 0; + childClass.cbWndExtra = 0; + childClass.hInstance = hInstance; + childClass.hbrBackground = NULL; + childClass.lpszMenuName = NULL; + + /* + * Register the Child window class. + */ + + childClass.lpszClassName = TK_WIN_CHILD_CLASS_NAME; + childClass.lpfnWndProc = TkWinChildProc; + childClass.hIcon = NULL; + childClass.hCursor = NULL; + + if (!RegisterClass(&childClass)) { + panic("Unable to register TkChild class"); + } +} + +/* + *---------------------------------------------------------------------- + * + * TkWinXCleanup -- + * + * Removes the registered classes for Tk. + * + * Results: + * None. + * + * Side effects: + * Removes window classes from the system. + * + *---------------------------------------------------------------------- + */ + +void +TkWinXCleanup(hInstance) + HINSTANCE hInstance; +{ + /* + * Clean up our own class. + */ + + if (childClassInitialized) { + childClassInitialized = 0; + UnregisterClass(TK_WIN_CHILD_CLASS_NAME, hInstance); + } + + /* + * And let the window manager clean up its own class(es). + */ + + TkWinWmCleanup(hInstance); +} + +/* + *---------------------------------------------------------------------- + * + * TkGetDefaultScreenName -- + * + * Returns the name of the screen that Tk should use during + * initialization. + * + * Results: + * Returns a statically allocated string. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +char * +TkGetDefaultScreenName(interp, screenName) + Tcl_Interp *interp; /* Not used. */ + char *screenName; /* If NULL, use default string. */ +{ + if ((screenName == NULL) || (screenName[0] == '\0')) { + screenName = winScreenName; + } + return screenName; +} + +/* + *---------------------------------------------------------------------- + * + * TkpOpenDisplay -- + * + * Create the Display structure and fill it with device + * specific information. + * + * Results: + * Returns a Display structure on success or NULL on failure. + * + * Side effects: + * Allocates a new Display structure. + * + *---------------------------------------------------------------------- + */ + +TkDisplay * +TkpOpenDisplay(display_name) + char *display_name; +{ + Screen *screen; + HDC dc; + TkWinDrawable *twdPtr; + Display *display; + + if (winDisplay != NULL) { + if (strcmp(winDisplay->display->display_name, display_name) == 0) { + return winDisplay; + } else { + return NULL; + } + } + + display = (Display *) ckalloc(sizeof(Display)); + display->display_name = (char *) ckalloc(strlen(display_name)+1); + strcpy(display->display_name, display_name); + + display->cursor_font = 1; + display->nscreens = 1; + display->request = 1; + display->qlen = 0; + + screen = (Screen *) ckalloc(sizeof(Screen)); + screen->display = display; + + dc = GetDC(NULL); + screen->width = GetDeviceCaps(dc, HORZRES); + screen->height = GetDeviceCaps(dc, VERTRES); + screen->mwidth = MulDiv(screen->width, 254, + GetDeviceCaps(dc, LOGPIXELSX) * 10); + screen->mheight = MulDiv(screen->height, 254, + GetDeviceCaps(dc, LOGPIXELSY) * 10); + + /* + * Set up the root window. + */ + + twdPtr = (TkWinDrawable*) ckalloc(sizeof(TkWinDrawable)); + if (twdPtr == NULL) { + return None; + } + twdPtr->type = TWD_WINDOW; + twdPtr->window.winPtr = NULL; + twdPtr->window.handle = NULL; + screen->root = (Window)twdPtr; + + /* + * On windows, when creating a color bitmap, need two pieces of + * information: the number of color planes and the number of + * pixels per plane. Need to remember both quantities so that + * when constructing an HBITMAP for offscreen rendering, we can + * specify the correct value for the number of planes. Otherwise + * the HBITMAP won't be compatible with the HWND and we'll just + * get blank spots copied onto the screen. + */ + + screen->ext_data = (XExtData *) GetDeviceCaps(dc, PLANES); + screen->root_depth = GetDeviceCaps(dc, BITSPIXEL) * (int) screen->ext_data; + + screen->root_visual = (Visual *) ckalloc(sizeof(Visual)); + screen->root_visual->visualid = 0; + if (GetDeviceCaps(dc, RASTERCAPS) & RC_PALETTE) { + screen->root_visual->map_entries = GetDeviceCaps(dc, SIZEPALETTE); + screen->root_visual->class = PseudoColor; + screen->root_visual->red_mask = 0x0; + screen->root_visual->green_mask = 0x0; + screen->root_visual->blue_mask = 0x0; + } else { + if (screen->root_depth == 4) { + screen->root_visual->class = StaticColor; + screen->root_visual->map_entries = 16; + } else if (screen->root_depth == 8) { + screen->root_visual->class = StaticColor; + screen->root_visual->map_entries = 256; + } else if (screen->root_depth == 12) { + screen->root_visual->class = TrueColor; + screen->root_visual->map_entries = 32; + screen->root_visual->red_mask = 0xf0; + screen->root_visual->green_mask = 0xf000; + screen->root_visual->blue_mask = 0xf00000; + } else if (screen->root_depth == 16) { + screen->root_visual->class = TrueColor; + screen->root_visual->map_entries = 64; + screen->root_visual->red_mask = 0xf8; + screen->root_visual->green_mask = 0xfc00; + screen->root_visual->blue_mask = 0xf80000; + } else if (screen->root_depth >= 24) { + screen->root_visual->class = TrueColor; + screen->root_visual->map_entries = 256; + screen->root_visual->red_mask = 0xff; + screen->root_visual->green_mask = 0xff00; + screen->root_visual->blue_mask = 0xff0000; + } + } + screen->root_visual->bits_per_rgb = screen->root_depth; + ReleaseDC(NULL, dc); + + /* + * Note that these pixel values are not palette relative. + */ + + screen->white_pixel = RGB(255, 255, 255); + screen->black_pixel = RGB(0, 0, 0); + + display->screens = screen; + display->nscreens = 1; + display->default_screen = 0; + screen->cmap = XCreateColormap(display, None, screen->root_visual, + AllocNone); + winDisplay = (TkDisplay *) ckalloc(sizeof(TkDisplay)); + winDisplay->display = display; + return winDisplay; +} + +/* + *---------------------------------------------------------------------- + * + * TkpCloseDisplay -- + * + * Closes and deallocates a Display structure created with the + * TkpOpenDisplay function. + * + * Results: + * None. + * + * Side effects: + * Frees up memory. + * + *---------------------------------------------------------------------- + */ + +void +TkpCloseDisplay(dispPtr) + TkDisplay *dispPtr; +{ + Display *display = dispPtr->display; + HWND hwnd; + + if (dispPtr != winDisplay) { + panic("TkpCloseDisplay: tried to call TkpCloseDisplay on another display"); + return; + } + + /* + * Force the clipboard to be rendered if we are the clipboard owner. + */ + + if (dispPtr->clipWindow) { + hwnd = Tk_GetHWND(Tk_WindowId(dispPtr->clipWindow)); + if (GetClipboardOwner() == hwnd) { + OpenClipboard(hwnd); + EmptyClipboard(); + TkWinClipboardRender(dispPtr, CF_TEXT); + CloseClipboard(); + } + } + + winDisplay = NULL; + + if (display->display_name != (char *) NULL) { + ckfree(display->display_name); + } + if (display->screens != (Screen *) NULL) { + if (display->screens->root_visual != NULL) { + ckfree((char *) display->screens->root_visual); + } + if (display->screens->root != None) { + ckfree((char *) display->screens->root); + } + if (display->screens->cmap != None) { + XFreeColormap(display, display->screens->cmap); + } + ckfree((char *) display->screens); + } + ckfree((char *) display); + ckfree((char *) dispPtr); +} + +/* + *---------------------------------------------------------------------- + * + * XBell -- + * + * Generate a beep. + * + * Results: + * None. + * + * Side effects: + * Plays a sounds out the system speakers. + * + *---------------------------------------------------------------------- + */ + +void +XBell(display, percent) + Display* display; + int percent; +{ + MessageBeep(MB_OK); +} + +/* + *---------------------------------------------------------------------- + * + * TkWinChildProc -- + * + * Callback from Windows whenever an event occurs on a child + * window. + * + * Results: + * Standard Windows return value. + * + * Side effects: + * May process events off the Tk event queue. + * + *---------------------------------------------------------------------- + */ + +LRESULT CALLBACK +TkWinChildProc(hwnd, message, wParam, lParam) + HWND hwnd; + UINT message; + WPARAM wParam; + LPARAM lParam; +{ + LRESULT result; + + switch (message) { + case WM_SETCURSOR: + /* + * Short circuit the WM_SETCURSOR message since we set + * the cursor elsewhere. + */ + + result = TRUE; + break; + + case WM_CREATE: + case WM_ERASEBKGND: + case WM_WINDOWPOSCHANGED: + result = 0; + break; + + case WM_PAINT: + GenerateXEvent(hwnd, message, wParam, lParam); + result = DefWindowProc(hwnd, message, wParam, lParam); + break; + + case TK_CLAIMFOCUS: + case TK_GEOMETRYREQ: + case TK_ATTACHWINDOW: + case TK_DETACHWINDOW: + result = TkWinEmbeddedEventProc(hwnd, message, wParam, lParam); + break; + + default: + if (!Tk_TranslateWinEvent(hwnd, message, wParam, lParam, + &result)) { + result = DefWindowProc(hwnd, message, wParam, lParam); + } + break; + } + + /* + * Handle any newly queued events before returning control to Windows. + */ + + Tcl_ServiceAll(); + return result; +} + +/* + *---------------------------------------------------------------------- + * + * Tk_TranslateWinEvent -- + * + * This function is called by widget window procedures to handle + * the translation from Win32 events to Tk events. + * + * Results: + * Returns 1 if the event was handled, else 0. + * + * Side effects: + * Depends on the event. + * + *---------------------------------------------------------------------- + */ + +int +Tk_TranslateWinEvent(hwnd, message, wParam, lParam, resultPtr) + HWND hwnd; + UINT message; + WPARAM wParam; + LPARAM lParam; + LRESULT *resultPtr; +{ + *resultPtr = 0; + switch (message) { + case WM_RENDERFORMAT: { + TkWindow *winPtr = (TkWindow *) Tk_HWNDToWindow(hwnd); + if (winPtr) { + TkWinClipboardRender(winPtr->dispPtr, wParam); + } + return 1; + } + + case WM_COMMAND: + case WM_NOTIFY: + case WM_VSCROLL: + case WM_HSCROLL: { + /* + * Reflect these messages back to the sender so that they + * can be handled by the window proc for the control. Note + * that we need to be careful not to reflect a message that + * is targeted to this window, or we will loop. + */ + + HWND target = (message == WM_NOTIFY) + ? ((NMHDR*)lParam)->hwndFrom : (HWND) lParam; + if (target && target != hwnd) { + *resultPtr = SendMessage(target, message, wParam, lParam); + return 1; + } + break; + } + + case WM_LBUTTONDOWN: + case WM_LBUTTONDBLCLK: + case WM_MBUTTONDOWN: + case WM_MBUTTONDBLCLK: + case WM_RBUTTONDOWN: + case WM_RBUTTONDBLCLK: + case WM_LBUTTONUP: + case WM_MBUTTONUP: + case WM_RBUTTONUP: + case WM_MOUSEMOVE: + Tk_PointerEvent(hwnd, (short) LOWORD(lParam), + (short) HIWORD(lParam)); + return 1; + + case WM_CLOSE: + case WM_SETFOCUS: + case WM_KILLFOCUS: + case WM_DESTROYCLIPBOARD: + case WM_CHAR: + case WM_SYSKEYDOWN: + case WM_SYSKEYUP: + case WM_KEYDOWN: + case WM_KEYUP: + GenerateXEvent(hwnd, message, wParam, lParam); + return 1; + } + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * GenerateXEvent -- + * + * This routine generates an X event from the corresponding + * Windows event. + * + * Results: + * None. + * + * Side effects: + * Queues one or more X events. + * + *---------------------------------------------------------------------- + */ + +static void +GenerateXEvent(hwnd, message, wParam, lParam) + HWND hwnd; + UINT message; + WPARAM wParam; + LPARAM lParam; +{ + XEvent event; + TkWindow *winPtr = (TkWindow *)Tk_HWNDToWindow(hwnd); + + if (!winPtr || winPtr->window == None) { + return; + } + + event.xany.serial = winPtr->display->request++; + event.xany.send_event = False; + event.xany.display = winPtr->display; + event.xany.window = winPtr->window; + + switch (message) { + case WM_PAINT: { + PAINTSTRUCT ps; + + event.type = Expose; + BeginPaint(hwnd, &ps); + event.xexpose.x = ps.rcPaint.left; + event.xexpose.y = ps.rcPaint.top; + event.xexpose.width = ps.rcPaint.right - ps.rcPaint.left; + event.xexpose.height = ps.rcPaint.bottom - ps.rcPaint.top; + EndPaint(hwnd, &ps); + event.xexpose.count = 0; + break; + } + + case WM_CLOSE: + event.type = ClientMessage; + event.xclient.message_type = + Tk_InternAtom((Tk_Window) winPtr, "WM_PROTOCOLS"); + event.xclient.format = 32; + event.xclient.data.l[0] = + Tk_InternAtom((Tk_Window) winPtr, "WM_DELETE_WINDOW"); + break; + + case WM_SETFOCUS: + case WM_KILLFOCUS: { + TkWindow *otherWinPtr = (TkWindow *)Tk_HWNDToWindow((HWND) wParam); + + /* + * Compare toplevel windows to avoid reporting focus + * changes within the same toplevel. + */ + + while (!(winPtr->flags & TK_TOP_LEVEL)) { + winPtr = winPtr->parentPtr; + if (winPtr == NULL) { + return; + } + } + while (otherWinPtr && !(otherWinPtr->flags & TK_TOP_LEVEL)) { + otherWinPtr = otherWinPtr->parentPtr; + } + if (otherWinPtr == winPtr) { + return; + } + + event.xany.window = winPtr->window; + event.type = (message == WM_SETFOCUS) ? FocusIn : FocusOut; + event.xfocus.mode = NotifyNormal; + event.xfocus.detail = NotifyNonlinear; + break; + } + + case WM_DESTROYCLIPBOARD: + event.type = SelectionClear; + event.xselectionclear.selection = + Tk_InternAtom((Tk_Window)winPtr, "CLIPBOARD"); + event.xselectionclear.time = TkpGetMS(); + break; + + case WM_CHAR: + case WM_SYSKEYDOWN: + case WM_SYSKEYUP: + case WM_KEYDOWN: + case WM_KEYUP: { + unsigned int state = GetState(message, wParam, lParam); + Time time = TkpGetMS(); + POINT clientPoint; + POINTS rootPoint; /* Note: POINT and POINTS are different */ + DWORD msgPos; + + /* + * Compute the screen and window coordinates of the event. + */ + + msgPos = GetMessagePos(); + rootPoint = MAKEPOINTS(msgPos); + clientPoint.x = rootPoint.x; + clientPoint.y = rootPoint.y; + ScreenToClient(hwnd, &clientPoint); + + /* + * Set up the common event fields. + */ + + event.xbutton.root = RootWindow(winPtr->display, + winPtr->screenNum); + event.xbutton.subwindow = None; + event.xbutton.x = clientPoint.x; + event.xbutton.y = clientPoint.y; + event.xbutton.x_root = rootPoint.x; + event.xbutton.y_root = rootPoint.y; + event.xbutton.state = state; + event.xbutton.time = time; + event.xbutton.same_screen = True; + + /* + * Now set up event specific fields. + */ + + switch (message) { + case WM_SYSKEYDOWN: + case WM_KEYDOWN: + /* + * Check for translated characters in the event queue. + * Setting xany.send_event to -1 indicates to the + * Windows implementation of XLookupString that this + * event was generated by windows and that the Windows + * extension xkey.trans_chars is filled with the + * characters that came from the TranslateMessage + * call. If it is not -1, xkey.keycode is the + * virtual key being sent programmatically by generic + * code. + */ + + event.type = KeyPress; + event.xany.send_event = -1; + event.xkey.keycode = wParam; + GetTranslatedKey(&event.xkey); + break; + + case WM_SYSKEYUP: + case WM_KEYUP: + /* + * We don't check for translated characters on keyup + * because Tk won't know what to do with them. Instead, we + * wait for the WM_CHAR messages which will follow. + */ + event.type = KeyRelease; + event.xkey.keycode = wParam; + event.xkey.nchars = 0; + break; + + case WM_CHAR: + /* + * Synthesize both a KeyPress and a KeyRelease. + */ + + event.type = KeyPress; + event.xany.send_event = -1; + event.xkey.keycode = 0; + event.xkey.nchars = 1; + event.xkey.trans_chars[0] = (char) wParam; + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); + event.type = KeyRelease; + break; + } + break; + } + + default: + return; + } + Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); +} + +/* + *---------------------------------------------------------------------- + * + * GetState -- + * + * This function constructs a state mask for the mouse buttons + * and modifier keys as they were before the event occured. + * + * Results: + * Returns a composite value of all the modifier and button state + * flags that were set at the time the event occurred. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static unsigned int +GetState(message, wParam, lParam) + UINT message; /* Win32 message type */ + WPARAM wParam; /* wParam of message, used if key message */ + LPARAM lParam; /* lParam of message, used if key message */ +{ + int mask; + int prevState; /* 1 if key was previously down */ + unsigned int state = TkWinGetModifierState(); + + /* + * If the event is a key press or release, we check for modifier + * keys so we can report the state of the world before the event. + */ + + if (message == WM_SYSKEYDOWN || message == WM_KEYDOWN + || message == WM_SYSKEYUP || message == WM_KEYUP) { + mask = 0; + prevState = HIWORD(lParam) & KF_REPEAT; + switch(wParam) { + case VK_SHIFT: + mask = ShiftMask; + break; + case VK_CONTROL: + mask = ControlMask; + break; + case VK_MENU: + mask = Mod2Mask; + break; + case VK_CAPITAL: + if (message == WM_SYSKEYDOWN || message == WM_KEYDOWN) { + mask = LockMask; + prevState = ((state & mask) ^ prevState) ? 0 : 1; + } + break; + case VK_NUMLOCK: + if (message == WM_SYSKEYDOWN || message == WM_KEYDOWN) { + mask = Mod1Mask; + prevState = ((state & mask) ^ prevState) ? 0 : 1; + } + break; + case VK_SCROLL: + if (message == WM_SYSKEYDOWN || message == WM_KEYDOWN) { + mask = Mod3Mask; + prevState = ((state & mask) ^ prevState) ? 0 : 1; + } + break; + } + if (prevState) { + state |= mask; + } else { + state &= ~mask; + } + } + return state; +} + +/* + *---------------------------------------------------------------------- + * + * GetTranslatedKey -- + * + * Retrieves WM_CHAR messages that are placed on the system queue + * by the TranslateMessage system call and places them in the + * given KeyPress event. + * + * Results: + * Sets the trans_chars and nchars member of the key event. + * + * Side effects: + * Removes any WM_CHAR messages waiting on the top of the system + * event queue. + * + *---------------------------------------------------------------------- + */ + +static void +GetTranslatedKey(xkey) + XKeyEvent *xkey; +{ + MSG msg; + + xkey->nchars = 0; + + while (xkey->nchars < XMaxTransChars + && PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { + if (msg.message == WM_CHAR) { + xkey->trans_chars[xkey->nchars] = (char) msg.wParam; + xkey->nchars++; + GetMessage(&msg, NULL, 0, 0); + if ((msg.message == WM_CHAR) && (msg.lParam & 0x20000000)) { + xkey->state = 0; + } + } else { + break; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * Tk_FreeXId -- + * + * This inteface is not needed under Windows. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +Tk_FreeXId(display, xid) + Display *display; + XID xid; +{ +} + +/* + *---------------------------------------------------------------------- + * + * TkWinResendEvent -- + * + * This function converts an X event into a Windows event and + * invokes the specified windo procedure. + * + * Results: + * A standard Windows result. + * + * Side effects: + * Invokes the window procedure + * + *---------------------------------------------------------------------- + */ + +LRESULT +TkWinResendEvent(wndproc, hwnd, eventPtr) + WNDPROC wndproc; + HWND hwnd; + XEvent *eventPtr; +{ + UINT msg; + WPARAM wparam; + LPARAM lparam; + + if (eventPtr->type == ButtonPress) { + switch (eventPtr->xbutton.button) { + case Button1: + msg = WM_LBUTTONDOWN; + wparam = MK_LBUTTON; + break; + case Button2: + msg = WM_MBUTTONDOWN; + wparam = MK_MBUTTON; + break; + case Button3: + msg = WM_RBUTTONDOWN; + wparam = MK_RBUTTON; + break; + default: + return 0; + } + if (eventPtr->xbutton.state & Button1Mask) { + wparam |= MK_LBUTTON; + } + if (eventPtr->xbutton.state & Button2Mask) { + wparam |= MK_MBUTTON; + } + if (eventPtr->xbutton.state & Button3Mask) { + wparam |= MK_RBUTTON; + } + if (eventPtr->xbutton.state & ShiftMask) { + wparam |= MK_SHIFT; + } + if (eventPtr->xbutton.state & ControlMask) { + wparam |= MK_CONTROL; + } + lparam = MAKELPARAM((short) eventPtr->xbutton.x, + (short) eventPtr->xbutton.y); + } else { + return 0; + } + return CallWindowProc(wndproc, hwnd, msg, wparam, lparam); +} + +/* + *---------------------------------------------------------------------- + * + * TkpGetMS -- + * + * Return a relative time in milliseconds. It doesn't matter + * when the epoch was. + * + * Results: + * Number of milliseconds. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +unsigned long +TkpGetMS() +{ + return GetCurrentTime(); +} diff --git a/win/winMain.c b/win/winMain.c new file mode 100644 index 0000000..f263339 --- /dev/null +++ b/win/winMain.c @@ -0,0 +1,323 @@ +/* + * winMain.c -- + * + * Main entry point for wish and other Tk-based applications. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) winMain.c 1.33 96/12/17 12:56:14 + */ + +#include <tk.h> +#define WIN32_LEAN_AND_MEAN +#include <windows.h> +#undef WIN32_LEAN_AND_MEAN +#include <malloc.h> +#include <locale.h> + +/* + * The following declarations refer to internal Tk routines. These + * interfaces are available for use, but are not supported. + */ + +EXTERN void TkConsoleCreate(void); +EXTERN int TkConsoleInit(Tcl_Interp *interp); + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void setargv _ANSI_ARGS_((int *argcPtr, char ***argvPtr)); +static void WishPanic _ANSI_ARGS_(TCL_VARARGS(char *,format)); + +#ifdef TK_TEST +EXTERN int Tktest_Init(Tcl_Interp *interp); +#endif /* TK_TEST */ + + +/* + *---------------------------------------------------------------------- + * + * WinMain -- + * + * Main entry point from Windows. + * + * Results: + * Returns false if initialization fails, otherwise it never + * returns. + * + * Side effects: + * Just about anything, since from here we call arbitrary Tcl code. + * + *---------------------------------------------------------------------- + */ + +int APIENTRY +WinMain(hInstance, hPrevInstance, lpszCmdLine, nCmdShow) + HINSTANCE hInstance; + HINSTANCE hPrevInstance; + LPSTR lpszCmdLine; + int nCmdShow; +{ + char **argv, *p; + int argc; + char buffer[MAX_PATH]; + + Tcl_SetPanicProc(WishPanic); + + /* + * Set up the default locale to be standard "C" locale so parsing + * is performed correctly. + */ + + setlocale(LC_ALL, "C"); + + + /* + * Increase the application queue size from default value of 8. + * At the default value, cross application SendMessage of WM_KILLFOCUS + * will fail because the handler will not be able to do a PostMessage! + * This is only needed for Windows 3.x, since NT dynamically expands + * the queue. + */ + SetMessageQueue(64); + + /* + * Create the console channels and install them as the standard + * channels. All I/O will be discarded until TkConsoleInit is + * called to attach the console to a text widget. + */ + + TkConsoleCreate(); + + setargv(&argc, &argv); + + /* + * Replace argv[0] with full pathname of executable, and forward + * slashes substituted for backslashes. + */ + + GetModuleFileName(NULL, buffer, sizeof(buffer)); + argv[0] = buffer; + for (p = buffer; *p != '\0'; p++) { + if (*p == '\\') { + *p = '/'; + } + } + + Tk_Main(argc, argv, Tcl_AppInit); + return 1; +} + + +/* + *---------------------------------------------------------------------- + * + * Tcl_AppInit -- + * + * This procedure performs application-specific initialization. + * Most applications, especially those that incorporate additional + * packages, will have their own version of this procedure. + * + * Results: + * Returns a standard Tcl completion code, and leaves an error + * message in interp->result if an error occurs. + * + * Side effects: + * Depends on the startup script. + * + *---------------------------------------------------------------------- + */ + +int +Tcl_AppInit(interp) + Tcl_Interp *interp; /* Interpreter for application. */ +{ + if (Tcl_Init(interp) == TCL_ERROR) { + goto error; + } + if (Tk_Init(interp) == TCL_ERROR) { + goto error; + } + Tcl_StaticPackage(interp, "Tk", Tk_Init, Tk_SafeInit); + + /* + * Initialize the console only if we are running as an interactive + * application. + */ + + if (TkConsoleInit(interp) == TCL_ERROR) { + goto error; + } + +#ifdef TK_TEST + if (Tktest_Init(interp) == TCL_ERROR) { + goto error; + } + Tcl_StaticPackage(interp, "Tktest", Tktest_Init, + (Tcl_PackageInitProc *) NULL); +#endif /* TK_TEST */ + + Tcl_SetVar(interp, "tcl_rcFileName", "~/wishrc.tcl", TCL_GLOBAL_ONLY); + return TCL_OK; + +error: + WishPanic(interp->result); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * WishPanic -- + * + * Display a message and exit. + * + * Results: + * None. + * + * Side effects: + * Exits the program. + * + *---------------------------------------------------------------------- + */ + +void +WishPanic TCL_VARARGS_DEF(char *,arg1) +{ + va_list argList; + char buf[1024]; + char *format; + + format = TCL_VARARGS_START(char *,arg1,argList); + vsprintf(buf, format, argList); + + MessageBeep(MB_ICONEXCLAMATION); + MessageBox(NULL, buf, "Fatal Error in Wish", + MB_ICONSTOP | MB_OK | MB_TASKMODAL | MB_SETFOREGROUND); +#ifdef _MSC_VER + _asm { + int 3 + } +#endif + ExitProcess(1); +} +/* + *------------------------------------------------------------------------- + * + * setargv -- + * + * Parse the Windows command line string into argc/argv. Done here + * because we don't trust the builtin argument parser in crt0. + * Windows applications are responsible for breaking their command + * line into arguments. + * + * 2N backslashes + quote -> N backslashes + begin quoted string + * 2N + 1 backslashes + quote -> literal + * N backslashes + non-quote -> literal + * quote + quote in a quoted string -> single quote + * quote + quote not in quoted string -> empty string + * quote -> begin quoted string + * + * Results: + * Fills argcPtr with the number of arguments and argvPtr with the + * array of arguments. + * + * Side effects: + * Memory allocated. + * + *-------------------------------------------------------------------------- + */ + +static void +setargv(argcPtr, argvPtr) + int *argcPtr; /* Filled with number of argument strings. */ + char ***argvPtr; /* Filled with argument strings (malloc'd). */ +{ + char *cmdLine, *p, *arg, *argSpace; + char **argv; + int argc, size, inquote, copy, slashes; + + cmdLine = GetCommandLine(); + + /* + * Precompute an overly pessimistic guess at the number of arguments + * in the command line by counting non-space spans. + */ + + size = 2; + for (p = cmdLine; *p != '\0'; p++) { + if (isspace(*p)) { + size++; + while (isspace(*p)) { + p++; + } + if (*p == '\0') { + break; + } + } + } + argSpace = (char *) ckalloc((unsigned) (size * sizeof(char *) + + strlen(cmdLine) + 1)); + argv = (char **) argSpace; + argSpace += size * sizeof(char *); + size--; + + p = cmdLine; + for (argc = 0; argc < size; argc++) { + argv[argc] = arg = argSpace; + while (isspace(*p)) { + p++; + } + if (*p == '\0') { + break; + } + + inquote = 0; + slashes = 0; + while (1) { + copy = 1; + while (*p == '\\') { + slashes++; + p++; + } + if (*p == '"') { + if ((slashes & 1) == 0) { + copy = 0; + if ((inquote) && (p[1] == '"')) { + p++; + copy = 1; + } else { + inquote = !inquote; + } + } + slashes >>= 1; + } + + while (slashes) { + *arg = '\\'; + arg++; + slashes--; + } + + if ((*p == '\0') || (!inquote && isspace(*p))) { + break; + } + if (copy != 0) { + *arg = *p; + arg++; + } + p++; + } + *arg = '\0'; + argSpace = arg + 1; + } + argv[argc] = NULL; + + *argcPtr = argc; + *argvPtr = argv; +} + diff --git a/xlib/X11/X.h b/xlib/X11/X.h new file mode 100644 index 0000000..55a3133 --- /dev/null +++ b/xlib/X11/X.h @@ -0,0 +1,669 @@ +/* + * $XConsortium: X.h,v 1.66 88/09/06 15:55:56 jim Exp $ + */ + +/* Definitions for the X window system likely to be used by applications */ + +#ifndef X_H +#define X_H + +/*********************************************************** +Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts, +and the Massachusetts Institute of Technology, Cambridge, Massachusetts. + + All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the names of Digital or MIT not be +used in advertising or publicity pertaining to distribution of the +software without specific, written prior permission. + +DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL +DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +******************************************************************/ +#define X_PROTOCOL 11 /* current protocol version */ +#define X_PROTOCOL_REVISION 0 /* current minor version */ + +#ifdef MAC_TCL +# define Cursor XCursor +# define Region XRegion +#endif + +/* Resources */ + +typedef unsigned long XID; + +typedef XID Window; +typedef XID Drawable; +typedef XID Font; +typedef XID Pixmap; +typedef XID Cursor; +typedef XID Colormap; +typedef XID GContext; +typedef XID KeySym; + +typedef unsigned long Mask; + +typedef unsigned long Atom; + +typedef unsigned long VisualID; + +typedef unsigned long Time; + +typedef unsigned short KeyCode; + +/***************************************************************** + * RESERVED RESOURCE AND CONSTANT DEFINITIONS + *****************************************************************/ + +#define None 0L /* universal null resource or null atom */ + +#define ParentRelative 1L /* background pixmap in CreateWindow + and ChangeWindowAttributes */ + +#define CopyFromParent 0L /* border pixmap in CreateWindow + and ChangeWindowAttributes + special VisualID and special window + class passed to CreateWindow */ + +#define PointerWindow 0L /* destination window in SendEvent */ +#define InputFocus 1L /* destination window in SendEvent */ + +#define PointerRoot 1L /* focus window in SetInputFocus */ + +#define AnyPropertyType 0L /* special Atom, passed to GetProperty */ + +#define AnyKey 0L /* special Key Code, passed to GrabKey */ + +#define AnyButton 0L /* special Button Code, passed to GrabButton */ + +#define AllTemporary 0L /* special Resource ID passed to KillClient */ + +#define CurrentTime 0L /* special Time */ + +#define NoSymbol 0L /* special KeySym */ + +/***************************************************************** + * EVENT DEFINITIONS + *****************************************************************/ + +/* Input Event Masks. Used as event-mask window attribute and as arguments + to Grab requests. Not to be confused with event names. */ + +#define NoEventMask 0L +#define KeyPressMask (1L<<0) +#define KeyReleaseMask (1L<<1) +#define ButtonPressMask (1L<<2) +#define ButtonReleaseMask (1L<<3) +#define EnterWindowMask (1L<<4) +#define LeaveWindowMask (1L<<5) +#define PointerMotionMask (1L<<6) +#define PointerMotionHintMask (1L<<7) +#define Button1MotionMask (1L<<8) +#define Button2MotionMask (1L<<9) +#define Button3MotionMask (1L<<10) +#define Button4MotionMask (1L<<11) +#define Button5MotionMask (1L<<12) +#define ButtonMotionMask (1L<<13) +#define KeymapStateMask (1L<<14) +#define ExposureMask (1L<<15) +#define VisibilityChangeMask (1L<<16) +#define StructureNotifyMask (1L<<17) +#define ResizeRedirectMask (1L<<18) +#define SubstructureNotifyMask (1L<<19) +#define SubstructureRedirectMask (1L<<20) +#define FocusChangeMask (1L<<21) +#define PropertyChangeMask (1L<<22) +#define ColormapChangeMask (1L<<23) +#define OwnerGrabButtonMask (1L<<24) + +/* Event names. Used in "type" field in XEvent structures. Not to be +confused with event masks above. They start from 2 because 0 and 1 +are reserved in the protocol for errors and replies. */ + +#define KeyPress 2 +#define KeyRelease 3 +#define ButtonPress 4 +#define ButtonRelease 5 +#define MotionNotify 6 +#define EnterNotify 7 +#define LeaveNotify 8 +#define FocusIn 9 +#define FocusOut 10 +#define KeymapNotify 11 +#define Expose 12 +#define GraphicsExpose 13 +#define NoExpose 14 +#define VisibilityNotify 15 +#define CreateNotify 16 +#define DestroyNotify 17 +#define UnmapNotify 18 +#define MapNotify 19 +#define MapRequest 20 +#define ReparentNotify 21 +#define ConfigureNotify 22 +#define ConfigureRequest 23 +#define GravityNotify 24 +#define ResizeRequest 25 +#define CirculateNotify 26 +#define CirculateRequest 27 +#define PropertyNotify 28 +#define SelectionClear 29 +#define SelectionRequest 30 +#define SelectionNotify 31 +#define ColormapNotify 32 +#define ClientMessage 33 +#define MappingNotify 34 +#define LASTEvent 35 /* must be bigger than any event # */ + + +/* Key masks. Used as modifiers to GrabButton and GrabKey, results of QueryPointer, + state in various key-, mouse-, and button-related events. */ + +#define ShiftMask (1<<0) +#define LockMask (1<<1) +#define ControlMask (1<<2) +#define Mod1Mask (1<<3) +#define Mod2Mask (1<<4) +#define Mod3Mask (1<<5) +#define Mod4Mask (1<<6) +#define Mod5Mask (1<<7) + +/* modifier names. Used to build a SetModifierMapping request or + to read a GetModifierMapping request. These correspond to the + masks defined above. */ +#define ShiftMapIndex 0 +#define LockMapIndex 1 +#define ControlMapIndex 2 +#define Mod1MapIndex 3 +#define Mod2MapIndex 4 +#define Mod3MapIndex 5 +#define Mod4MapIndex 6 +#define Mod5MapIndex 7 + + +/* button masks. Used in same manner as Key masks above. Not to be confused + with button names below. */ + +#define Button1Mask (1<<8) +#define Button2Mask (1<<9) +#define Button3Mask (1<<10) +#define Button4Mask (1<<11) +#define Button5Mask (1<<12) + +#define AnyModifier (1<<15) /* used in GrabButton, GrabKey */ + + +/* button names. Used as arguments to GrabButton and as detail in ButtonPress + and ButtonRelease events. Not to be confused with button masks above. + Note that 0 is already defined above as "AnyButton". */ + +#define Button1 1 +#define Button2 2 +#define Button3 3 +#define Button4 4 +#define Button5 5 + +/* Notify modes */ + +#define NotifyNormal 0 +#define NotifyGrab 1 +#define NotifyUngrab 2 +#define NotifyWhileGrabbed 3 + +#define NotifyHint 1 /* for MotionNotify events */ + +/* Notify detail */ + +#define NotifyAncestor 0 +#define NotifyVirtual 1 +#define NotifyInferior 2 +#define NotifyNonlinear 3 +#define NotifyNonlinearVirtual 4 +#define NotifyPointer 5 +#define NotifyPointerRoot 6 +#define NotifyDetailNone 7 + +/* Visibility notify */ + +#define VisibilityUnobscured 0 +#define VisibilityPartiallyObscured 1 +#define VisibilityFullyObscured 2 + +/* Circulation request */ + +#define PlaceOnTop 0 +#define PlaceOnBottom 1 + +/* protocol families */ + +#define FamilyInternet 0 +#define FamilyDECnet 1 +#define FamilyChaos 2 + +/* Property notification */ + +#define PropertyNewValue 0 +#define PropertyDelete 1 + +/* Color Map notification */ + +#define ColormapUninstalled 0 +#define ColormapInstalled 1 + +/* GrabPointer, GrabButton, GrabKeyboard, GrabKey Modes */ + +#define GrabModeSync 0 +#define GrabModeAsync 1 + +/* GrabPointer, GrabKeyboard reply status */ + +#define GrabSuccess 0 +#define AlreadyGrabbed 1 +#define GrabInvalidTime 2 +#define GrabNotViewable 3 +#define GrabFrozen 4 + +/* AllowEvents modes */ + +#define AsyncPointer 0 +#define SyncPointer 1 +#define ReplayPointer 2 +#define AsyncKeyboard 3 +#define SyncKeyboard 4 +#define ReplayKeyboard 5 +#define AsyncBoth 6 +#define SyncBoth 7 + +/* Used in SetInputFocus, GetInputFocus */ + +#define RevertToNone (int)None +#define RevertToPointerRoot (int)PointerRoot +#define RevertToParent 2 + +/***************************************************************** + * ERROR CODES + *****************************************************************/ + +#define Success 0 /* everything's okay */ +#define BadRequest 1 /* bad request code */ +#define BadValue 2 /* int parameter out of range */ +#define BadWindow 3 /* parameter not a Window */ +#define BadPixmap 4 /* parameter not a Pixmap */ +#define BadAtom 5 /* parameter not an Atom */ +#define BadCursor 6 /* parameter not a Cursor */ +#define BadFont 7 /* parameter not a Font */ +#define BadMatch 8 /* parameter mismatch */ +#define BadDrawable 9 /* parameter not a Pixmap or Window */ +#define BadAccess 10 /* depending on context: + - key/button already grabbed + - attempt to free an illegal + cmap entry + - attempt to store into a read-only + color map entry. + - attempt to modify the access control + list from other than the local host. + */ +#define BadAlloc 11 /* insufficient resources */ +#define BadColor 12 /* no such colormap */ +#define BadGC 13 /* parameter not a GC */ +#define BadIDChoice 14 /* choice not in range or already used */ +#define BadName 15 /* font or color name doesn't exist */ +#define BadLength 16 /* Request length incorrect */ +#define BadImplementation 17 /* server is defective */ + +#define FirstExtensionError 128 +#define LastExtensionError 255 + +/***************************************************************** + * WINDOW DEFINITIONS + *****************************************************************/ + +/* Window classes used by CreateWindow */ +/* Note that CopyFromParent is already defined as 0 above */ + +#define InputOutput 1 +#define InputOnly 2 + +/* Window attributes for CreateWindow and ChangeWindowAttributes */ + +#define CWBackPixmap (1L<<0) +#define CWBackPixel (1L<<1) +#define CWBorderPixmap (1L<<2) +#define CWBorderPixel (1L<<3) +#define CWBitGravity (1L<<4) +#define CWWinGravity (1L<<5) +#define CWBackingStore (1L<<6) +#define CWBackingPlanes (1L<<7) +#define CWBackingPixel (1L<<8) +#define CWOverrideRedirect (1L<<9) +#define CWSaveUnder (1L<<10) +#define CWEventMask (1L<<11) +#define CWDontPropagate (1L<<12) +#define CWColormap (1L<<13) +#define CWCursor (1L<<14) + +/* ConfigureWindow structure */ + +#define CWX (1<<0) +#define CWY (1<<1) +#define CWWidth (1<<2) +#define CWHeight (1<<3) +#define CWBorderWidth (1<<4) +#define CWSibling (1<<5) +#define CWStackMode (1<<6) + + +/* Bit Gravity */ + +#define ForgetGravity 0 +#define NorthWestGravity 1 +#define NorthGravity 2 +#define NorthEastGravity 3 +#define WestGravity 4 +#define CenterGravity 5 +#define EastGravity 6 +#define SouthWestGravity 7 +#define SouthGravity 8 +#define SouthEastGravity 9 +#define StaticGravity 10 + +/* Window gravity + bit gravity above */ + +#define UnmapGravity 0 + +/* Used in CreateWindow for backing-store hint */ + +#define NotUseful 0 +#define WhenMapped 1 +#define Always 2 + +/* Used in GetWindowAttributes reply */ + +#define IsUnmapped 0 +#define IsUnviewable 1 +#define IsViewable 2 + +/* Used in ChangeSaveSet */ + +#define SetModeInsert 0 +#define SetModeDelete 1 + +/* Used in ChangeCloseDownMode */ + +#define DestroyAll 0 +#define RetainPermanent 1 +#define RetainTemporary 2 + +/* Window stacking method (in configureWindow) */ + +#define Above 0 +#define Below 1 +#define TopIf 2 +#define BottomIf 3 +#define Opposite 4 + +/* Circulation direction */ + +#define RaiseLowest 0 +#define LowerHighest 1 + +/* Property modes */ + +#define PropModeReplace 0 +#define PropModePrepend 1 +#define PropModeAppend 2 + +/***************************************************************** + * GRAPHICS DEFINITIONS + *****************************************************************/ + +/* graphics functions, as in GC.alu */ + +#define GXclear 0x0 /* 0 */ +#define GXand 0x1 /* src AND dst */ +#define GXandReverse 0x2 /* src AND NOT dst */ +#define GXcopy 0x3 /* src */ +#define GXandInverted 0x4 /* NOT src AND dst */ +#define GXnoop 0x5 /* dst */ +#define GXxor 0x6 /* src XOR dst */ +#define GXor 0x7 /* src OR dst */ +#define GXnor 0x8 /* NOT src AND NOT dst */ +#define GXequiv 0x9 /* NOT src XOR dst */ +#define GXinvert 0xa /* NOT dst */ +#define GXorReverse 0xb /* src OR NOT dst */ +#define GXcopyInverted 0xc /* NOT src */ +#define GXorInverted 0xd /* NOT src OR dst */ +#define GXnand 0xe /* NOT src OR NOT dst */ +#define GXset 0xf /* 1 */ + +/* LineStyle */ + +#define LineSolid 0 +#define LineOnOffDash 1 +#define LineDoubleDash 2 + +/* capStyle */ + +#define CapNotLast 0 +#define CapButt 1 +#define CapRound 2 +#define CapProjecting 3 + +/* joinStyle */ + +#define JoinMiter 0 +#define JoinRound 1 +#define JoinBevel 2 + +/* fillStyle */ + +#define FillSolid 0 +#define FillTiled 1 +#define FillStippled 2 +#define FillOpaqueStippled 3 + +/* fillRule */ + +#define EvenOddRule 0 +#define WindingRule 1 + +/* subwindow mode */ + +#define ClipByChildren 0 +#define IncludeInferiors 1 + +/* SetClipRectangles ordering */ + +#define Unsorted 0 +#define YSorted 1 +#define YXSorted 2 +#define YXBanded 3 + +/* CoordinateMode for drawing routines */ + +#define CoordModeOrigin 0 /* relative to the origin */ +#define CoordModePrevious 1 /* relative to previous point */ + +/* Polygon shapes */ + +#define Complex 0 /* paths may intersect */ +#define Nonconvex 1 /* no paths intersect, but not convex */ +#define Convex 2 /* wholly convex */ + +/* Arc modes for PolyFillArc */ + +#define ArcChord 0 /* join endpoints of arc */ +#define ArcPieSlice 1 /* join endpoints to center of arc */ + +/* GC components: masks used in CreateGC, CopyGC, ChangeGC, OR'ed into + GC.stateChanges */ + +#define GCFunction (1L<<0) +#define GCPlaneMask (1L<<1) +#define GCForeground (1L<<2) +#define GCBackground (1L<<3) +#define GCLineWidth (1L<<4) +#define GCLineStyle (1L<<5) +#define GCCapStyle (1L<<6) +#define GCJoinStyle (1L<<7) +#define GCFillStyle (1L<<8) +#define GCFillRule (1L<<9) +#define GCTile (1L<<10) +#define GCStipple (1L<<11) +#define GCTileStipXOrigin (1L<<12) +#define GCTileStipYOrigin (1L<<13) +#define GCFont (1L<<14) +#define GCSubwindowMode (1L<<15) +#define GCGraphicsExposures (1L<<16) +#define GCClipXOrigin (1L<<17) +#define GCClipYOrigin (1L<<18) +#define GCClipMask (1L<<19) +#define GCDashOffset (1L<<20) +#define GCDashList (1L<<21) +#define GCArcMode (1L<<22) + +#define GCLastBit 22 +/***************************************************************** + * FONTS + *****************************************************************/ + +/* used in QueryFont -- draw direction */ + +#define FontLeftToRight 0 +#define FontRightToLeft 1 + +#define FontChange 255 + +/***************************************************************** + * IMAGING + *****************************************************************/ + +/* ImageFormat -- PutImage, GetImage */ + +#define XYBitmap 0 /* depth 1, XYFormat */ +#define XYPixmap 1 /* depth == drawable depth */ +#define ZPixmap 2 /* depth == drawable depth */ + +/***************************************************************** + * COLOR MAP STUFF + *****************************************************************/ + +/* For CreateColormap */ + +#define AllocNone 0 /* create map with no entries */ +#define AllocAll 1 /* allocate entire map writeable */ + + +/* Flags used in StoreNamedColor, StoreColors */ + +#define DoRed (1<<0) +#define DoGreen (1<<1) +#define DoBlue (1<<2) + +/***************************************************************** + * CURSOR STUFF + *****************************************************************/ + +/* QueryBestSize Class */ + +#define CursorShape 0 /* largest size that can be displayed */ +#define TileShape 1 /* size tiled fastest */ +#define StippleShape 2 /* size stippled fastest */ + +/***************************************************************** + * KEYBOARD/POINTER STUFF + *****************************************************************/ + +#define AutoRepeatModeOff 0 +#define AutoRepeatModeOn 1 +#define AutoRepeatModeDefault 2 + +#define LedModeOff 0 +#define LedModeOn 1 + +/* masks for ChangeKeyboardControl */ + +#define KBKeyClickPercent (1L<<0) +#define KBBellPercent (1L<<1) +#define KBBellPitch (1L<<2) +#define KBBellDuration (1L<<3) +#define KBLed (1L<<4) +#define KBLedMode (1L<<5) +#define KBKey (1L<<6) +#define KBAutoRepeatMode (1L<<7) + +#define MappingSuccess 0 +#define MappingBusy 1 +#define MappingFailed 2 + +#define MappingModifier 0 +#define MappingKeyboard 1 +#define MappingPointer 2 + +/***************************************************************** + * SCREEN SAVER STUFF + *****************************************************************/ + +#define DontPreferBlanking 0 +#define PreferBlanking 1 +#define DefaultBlanking 2 + +#define DisableScreenSaver 0 +#define DisableScreenInterval 0 + +#define DontAllowExposures 0 +#define AllowExposures 1 +#define DefaultExposures 2 + +/* for ForceScreenSaver */ + +#define ScreenSaverReset 0 +#define ScreenSaverActive 1 + +/***************************************************************** + * HOSTS AND CONNECTIONS + *****************************************************************/ + +/* for ChangeHosts */ + +#define HostInsert 0 +#define HostDelete 1 + +/* for ChangeAccessControl */ + +#define EnableAccess 1 +#define DisableAccess 0 + +/* Display classes used in opening the connection + * Note that the statically allocated ones are even numbered and the + * dynamically changeable ones are odd numbered */ + +#define StaticGray 0 +#define GrayScale 1 +#define StaticColor 2 +#define PseudoColor 3 +#define TrueColor 4 +#define DirectColor 5 + + +/* Byte order used in imageByteOrder and bitmapBitOrder */ + +#define LSBFirst 0 +#define MSBFirst 1 + +#ifdef MAC_TCL +# undef Cursor +# undef Region +#endif + +#endif /* X_H */ diff --git a/xlib/X11/Xatom.h b/xlib/X11/Xatom.h new file mode 100644 index 0000000..485a423 --- /dev/null +++ b/xlib/X11/Xatom.h @@ -0,0 +1,79 @@ +#ifndef XATOM_H +#define XATOM_H 1 + +/* THIS IS A GENERATED FILE + * + * Do not change! Changing this file implies a protocol change! + */ + +#define XA_PRIMARY ((Atom) 1) +#define XA_SECONDARY ((Atom) 2) +#define XA_ARC ((Atom) 3) +#define XA_ATOM ((Atom) 4) +#define XA_BITMAP ((Atom) 5) +#define XA_CARDINAL ((Atom) 6) +#define XA_COLORMAP ((Atom) 7) +#define XA_CURSOR ((Atom) 8) +#define XA_CUT_BUFFER0 ((Atom) 9) +#define XA_CUT_BUFFER1 ((Atom) 10) +#define XA_CUT_BUFFER2 ((Atom) 11) +#define XA_CUT_BUFFER3 ((Atom) 12) +#define XA_CUT_BUFFER4 ((Atom) 13) +#define XA_CUT_BUFFER5 ((Atom) 14) +#define XA_CUT_BUFFER6 ((Atom) 15) +#define XA_CUT_BUFFER7 ((Atom) 16) +#define XA_DRAWABLE ((Atom) 17) +#define XA_FONT ((Atom) 18) +#define XA_INTEGER ((Atom) 19) +#define XA_PIXMAP ((Atom) 20) +#define XA_POINT ((Atom) 21) +#define XA_RECTANGLE ((Atom) 22) +#define XA_RESOURCE_MANAGER ((Atom) 23) +#define XA_RGB_COLOR_MAP ((Atom) 24) +#define XA_RGB_BEST_MAP ((Atom) 25) +#define XA_RGB_BLUE_MAP ((Atom) 26) +#define XA_RGB_DEFAULT_MAP ((Atom) 27) +#define XA_RGB_GRAY_MAP ((Atom) 28) +#define XA_RGB_GREEN_MAP ((Atom) 29) +#define XA_RGB_RED_MAP ((Atom) 30) +#define XA_STRING ((Atom) 31) +#define XA_VISUALID ((Atom) 32) +#define XA_WINDOW ((Atom) 33) +#define XA_WM_COMMAND ((Atom) 34) +#define XA_WM_HINTS ((Atom) 35) +#define XA_WM_CLIENT_MACHINE ((Atom) 36) +#define XA_WM_ICON_NAME ((Atom) 37) +#define XA_WM_ICON_SIZE ((Atom) 38) +#define XA_WM_NAME ((Atom) 39) +#define XA_WM_NORMAL_HINTS ((Atom) 40) +#define XA_WM_SIZE_HINTS ((Atom) 41) +#define XA_WM_ZOOM_HINTS ((Atom) 42) +#define XA_MIN_SPACE ((Atom) 43) +#define XA_NORM_SPACE ((Atom) 44) +#define XA_MAX_SPACE ((Atom) 45) +#define XA_END_SPACE ((Atom) 46) +#define XA_SUPERSCRIPT_X ((Atom) 47) +#define XA_SUPERSCRIPT_Y ((Atom) 48) +#define XA_SUBSCRIPT_X ((Atom) 49) +#define XA_SUBSCRIPT_Y ((Atom) 50) +#define XA_UNDERLINE_POSITION ((Atom) 51) +#define XA_UNDERLINE_THICKNESS ((Atom) 52) +#define XA_STRIKEOUT_ASCENT ((Atom) 53) +#define XA_STRIKEOUT_DESCENT ((Atom) 54) +#define XA_ITALIC_ANGLE ((Atom) 55) +#define XA_X_HEIGHT ((Atom) 56) +#define XA_QUAD_WIDTH ((Atom) 57) +#define XA_WEIGHT ((Atom) 58) +#define XA_POINT_SIZE ((Atom) 59) +#define XA_RESOLUTION ((Atom) 60) +#define XA_COPYRIGHT ((Atom) 61) +#define XA_NOTICE ((Atom) 62) +#define XA_FONT_NAME ((Atom) 63) +#define XA_FAMILY_NAME ((Atom) 64) +#define XA_FULL_NAME ((Atom) 65) +#define XA_CAP_HEIGHT ((Atom) 66) +#define XA_WM_CLASS ((Atom) 67) +#define XA_WM_TRANSIENT_FOR ((Atom) 68) + +#define XA_LAST_PREDEFINED ((Atom) 68) +#endif /* XATOM_H */ diff --git a/xlib/X11/Xfuncproto.h b/xlib/X11/Xfuncproto.h new file mode 100644 index 0000000..a59379b --- /dev/null +++ b/xlib/X11/Xfuncproto.h @@ -0,0 +1,60 @@ +/* $XConsortium: Xfuncproto.h,v 1.7 91/05/13 20:49:21 rws Exp $ */ +/* + * Copyright 1989, 1991 by the Massachusetts Institute of Technology + * + * Permission to use, copy, modify, and distribute this software and its + * documentation for any purpose and without fee is hereby granted, provided + * that the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of M.I.T. not be used in advertising + * or publicity pertaining to distribution of the software without specific, + * written prior permission. M.I.T. makes no representations about the + * suitability of this software for any purpose. It is provided "as is" + * without express or implied warranty. + * + */ + +/* Definitions to make function prototypes manageable */ + +#ifndef _XFUNCPROTO_H_ +#define _XFUNCPROTO_H_ + +#ifndef NeedFunctionPrototypes +#define NeedFunctionPrototypes 1 +#endif /* NeedFunctionPrototypes */ + +#ifndef NeedVarargsPrototypes +#define NeedVarargsPrototypes 0 +#endif /* NeedVarargsPrototypes */ + +#if NeedFunctionPrototypes + +#ifndef NeedNestedPrototypes +#define NeedNestedPrototypes 1 +#endif /* NeedNestedPrototypes */ + +#ifndef _Xconst +#define _Xconst const +#endif /* _Xconst */ + +#ifndef NeedWidePrototypes +#ifdef NARROWPROTO +#define NeedWidePrototypes 0 +#else +#define NeedWidePrototypes 1 /* default to make interropt. easier */ +#endif +#endif /* NeedWidePrototypes */ + +#endif /* NeedFunctionPrototypes */ + +#ifdef __cplusplus +#define _XFUNCPROTOBEGIN extern "C" { +#define _XFUNCPROTOEND } +#endif + +#ifndef _XFUNCPROTOBEGIN +#define _XFUNCPROTOBEGIN +#define _XFUNCPROTOEND +#endif /* _XFUNCPROTOBEGIN */ + +#endif /* _XFUNCPROTO_H_ */ diff --git a/xlib/X11/Xlib.h b/xlib/X11/Xlib.h new file mode 100644 index 0000000..397bb03 --- /dev/null +++ b/xlib/X11/Xlib.h @@ -0,0 +1,4311 @@ +/* $XConsortium: Xlib.h,v 11.221 93/07/02 14:13:28 gildea Exp $ */ +/* + * Copyright 1985, 1986, 1987, 1991 by the Massachusetts Institute of Technology + * + * Permission to use, copy, modify, and distribute this software and its + * documentation for any purpose and without fee is hereby granted, provided + * that the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of M.I.T. not be used in advertising + * or publicity pertaining to distribution of the software without specific, + * written prior permission. M.I.T. makes no representations about the + * suitability of this software for any purpose. It is provided "as is" + * without express or implied warranty. + * + * X Window System is a Trademark of MIT. + * + */ + + +/* + * Xlib.h - Header definition and support file for the C subroutine + * interface library (Xlib) to the X Window System Protocol (V11). + * Structures and symbols starting with "_" are private to the library. + */ +#ifndef _XLIB_H_ +#define _XLIB_H_ + +#define XlibSpecificationRelease 5 + +#ifdef MAC_TCL +# include <X.h> +# define Cursor XCursor +# define Region XRegion +#else +# include <X11/X.h> +#endif + +/* applications should not depend on these two headers being included! */ +#ifdef MAC_TCL +#include <Xfuncproto.h> +#else +#include <X11/Xfuncproto.h> +#endif + +#ifndef X_WCHAR +#ifdef X_NOT_STDC_ENV +#define X_WCHAR +#endif +#endif + +#ifndef X_WCHAR +#include <stddef.h> +#else +/* replace this with #include or typedef appropriate for your system */ +typedef unsigned long wchar_t; +#endif + +typedef char *XPointer; + +#define Bool int +#define Status int +#define True 1 +#define False 0 + +#define QueuedAlready 0 +#define QueuedAfterReading 1 +#define QueuedAfterFlush 2 + +#define ConnectionNumber(dpy) ((dpy)->fd) +#define RootWindow(dpy, scr) (((dpy)->screens[(scr)]).root) +#define DefaultScreen(dpy) ((dpy)->default_screen) +#define DefaultRootWindow(dpy) (((dpy)->screens[(dpy)->default_screen]).root) +#define DefaultVisual(dpy, scr) (((dpy)->screens[(scr)]).root_visual) +#define DefaultGC(dpy, scr) (((dpy)->screens[(scr)]).default_gc) +#define BlackPixel(dpy, scr) (((dpy)->screens[(scr)]).black_pixel) +#define WhitePixel(dpy, scr) (((dpy)->screens[(scr)]).white_pixel) +#define AllPlanes ((unsigned long)~0L) +#define QLength(dpy) ((dpy)->qlen) +#define DisplayWidth(dpy, scr) (((dpy)->screens[(scr)]).width) +#define DisplayHeight(dpy, scr) (((dpy)->screens[(scr)]).height) +#define DisplayWidthMM(dpy, scr)(((dpy)->screens[(scr)]).mwidth) +#define DisplayHeightMM(dpy, scr)(((dpy)->screens[(scr)]).mheight) +#define DisplayPlanes(dpy, scr) (((dpy)->screens[(scr)]).root_depth) +#define DisplayCells(dpy, scr) (DefaultVisual((dpy), (scr))->map_entries) +#define ScreenCount(dpy) ((dpy)->nscreens) +#define ServerVendor(dpy) ((dpy)->vendor) +#define ProtocolVersion(dpy) ((dpy)->proto_major_version) +#define ProtocolRevision(dpy) ((dpy)->proto_minor_version) +#define VendorRelease(dpy) ((dpy)->release) +#define DisplayString(dpy) ((dpy)->display_name) +#define DefaultDepth(dpy, scr) (((dpy)->screens[(scr)]).root_depth) +#define DefaultColormap(dpy, scr)(((dpy)->screens[(scr)]).cmap) +#define BitmapUnit(dpy) ((dpy)->bitmap_unit) +#define BitmapBitOrder(dpy) ((dpy)->bitmap_bit_order) +#define BitmapPad(dpy) ((dpy)->bitmap_pad) +#define ImageByteOrder(dpy) ((dpy)->byte_order) +#define NextRequest(dpy) ((dpy)->request + 1) +#define LastKnownRequestProcessed(dpy) ((dpy)->request) + +/* macros for screen oriented applications (toolkit) */ +#define ScreenOfDisplay(dpy, scr)(&((dpy)->screens[(scr)])) +#define DefaultScreenOfDisplay(dpy) (&((dpy)->screens[(dpy)->default_screen])) +#define DisplayOfScreen(s) ((s)->display) +#define RootWindowOfScreen(s) ((s)->root) +#define BlackPixelOfScreen(s) ((s)->black_pixel) +#define WhitePixelOfScreen(s) ((s)->white_pixel) +#define DefaultColormapOfScreen(s)((s)->cmap) +#define DefaultDepthOfScreen(s) ((s)->root_depth) +#define DefaultGCOfScreen(s) ((s)->default_gc) +#define DefaultVisualOfScreen(s)((s)->root_visual) +#define WidthOfScreen(s) ((s)->width) +#define HeightOfScreen(s) ((s)->height) +#define WidthMMOfScreen(s) ((s)->mwidth) +#define HeightMMOfScreen(s) ((s)->mheight) +#define PlanesOfScreen(s) ((s)->root_depth) +#define CellsOfScreen(s) (DefaultVisualOfScreen((s))->map_entries) +#define MinCmapsOfScreen(s) ((s)->min_maps) +#define MaxCmapsOfScreen(s) ((s)->max_maps) +#define DoesSaveUnders(s) ((s)->save_unders) +#define DoesBackingStore(s) ((s)->backing_store) +#define EventMaskOfScreen(s) ((s)->root_input_mask) + +/* + * Extensions need a way to hang private data on some structures. + */ +typedef struct _XExtData { + int number; /* number returned by XRegisterExtension */ + struct _XExtData *next; /* next item on list of data for structure */ + int (*free_private)(); /* called to free private storage */ + XPointer private_data; /* data private to this extension. */ +} XExtData; + +/* + * This file contains structures used by the extension mechanism. + */ +typedef struct { /* public to extension, cannot be changed */ + int extension; /* extension number */ + int major_opcode; /* major op-code assigned by server */ + int first_event; /* first event number for the extension */ + int first_error; /* first error number for the extension */ +} XExtCodes; + +/* + * Data structure for retrieving info about pixmap formats. + */ + +typedef struct { + int depth; + int bits_per_pixel; + int scanline_pad; +} XPixmapFormatValues; + + +/* + * Data structure for setting graphics context. + */ +typedef struct { + int function; /* logical operation */ + unsigned long plane_mask;/* plane mask */ + unsigned long foreground;/* foreground pixel */ + unsigned long background;/* background pixel */ + int line_width; /* line width */ + int line_style; /* LineSolid, LineOnOffDash, LineDoubleDash */ + int cap_style; /* CapNotLast, CapButt, + CapRound, CapProjecting */ + int join_style; /* JoinMiter, JoinRound, JoinBevel */ + int fill_style; /* FillSolid, FillTiled, + FillStippled, FillOpaeueStippled */ + int fill_rule; /* EvenOddRule, WindingRule */ + int arc_mode; /* ArcChord, ArcPieSlice */ + Pixmap tile; /* tile pixmap for tiling operations */ + Pixmap stipple; /* stipple 1 plane pixmap for stipping */ + int ts_x_origin; /* offset for tile or stipple operations */ + int ts_y_origin; + Font font; /* default text font for text operations */ + int subwindow_mode; /* ClipByChildren, IncludeInferiors */ + Bool graphics_exposures;/* boolean, should exposures be generated */ + int clip_x_origin; /* origin for clipping */ + int clip_y_origin; + Pixmap clip_mask; /* bitmap clipping; other calls for rects */ + int dash_offset; /* patterned/dashed line information */ + char dashes; +} XGCValues; + +/* + * Graphics context. The contents of this structure are implementation + * dependent. A GC should be treated as opaque by application code. + */ + +typedef XGCValues *GC; + +/* + * Visual structure; contains information about colormapping possible. + */ +typedef struct { + XExtData *ext_data; /* hook for extension to hang data */ + VisualID visualid; /* visual id of this visual */ +#if defined(__cplusplus) || defined(c_plusplus) + int c_class; /* C++ class of screen (monochrome, etc.) */ +#else + int class; /* class of screen (monochrome, etc.) */ +#endif + unsigned long red_mask, green_mask, blue_mask; /* mask values */ + int bits_per_rgb; /* log base 2 of distinct color values */ + int map_entries; /* color map entries */ +} Visual; + +/* + * Depth structure; contains information for each possible depth. + */ +typedef struct { + int depth; /* this depth (Z) of the depth */ + int nvisuals; /* number of Visual types at this depth */ + Visual *visuals; /* list of visuals possible at this depth */ +} Depth; + +/* + * Information about the screen. The contents of this structure are + * implementation dependent. A Screen should be treated as opaque + * by application code. + */ +typedef struct { + XExtData *ext_data; /* hook for extension to hang data */ + struct _XDisplay *display;/* back pointer to display structure */ + Window root; /* Root window id. */ + int width, height; /* width and height of screen */ + int mwidth, mheight; /* width and height of in millimeters */ + int ndepths; /* number of depths possible */ + Depth *depths; /* list of allowable depths on the screen */ + int root_depth; /* bits per pixel */ + Visual *root_visual; /* root visual */ + GC default_gc; /* GC for the root root visual */ + Colormap cmap; /* default color map */ + unsigned long white_pixel; + unsigned long black_pixel; /* White and Black pixel values */ + int max_maps, min_maps; /* max and min color maps */ + int backing_store; /* Never, WhenMapped, Always */ + Bool save_unders; + long root_input_mask; /* initial root input mask */ +} Screen; + +/* + * Format structure; describes ZFormat data the screen will understand. + */ +typedef struct { + XExtData *ext_data; /* hook for extension to hang data */ + int depth; /* depth of this image format */ + int bits_per_pixel; /* bits/pixel at this depth */ + int scanline_pad; /* scanline must padded to this multiple */ +} ScreenFormat; + +/* + * Data structure for setting window attributes. + */ +typedef struct { + Pixmap background_pixmap; /* background or None or ParentRelative */ + unsigned long background_pixel; /* background pixel */ + Pixmap border_pixmap; /* border of the window */ + unsigned long border_pixel; /* border pixel value */ + int bit_gravity; /* one of bit gravity values */ + int win_gravity; /* one of the window gravity values */ + int backing_store; /* NotUseful, WhenMapped, Always */ + unsigned long backing_planes;/* planes to be preseved if possible */ + unsigned long backing_pixel;/* value to use in restoring planes */ + Bool save_under; /* should bits under be saved? (popups) */ + long event_mask; /* set of events that should be saved */ + long do_not_propagate_mask; /* set of events that should not propagate */ + Bool override_redirect; /* boolean value for override-redirect */ + Colormap colormap; /* color map to be associated with window */ + Cursor cursor; /* cursor to be displayed (or None) */ +} XSetWindowAttributes; + +typedef struct { + int x, y; /* location of window */ + int width, height; /* width and height of window */ + int border_width; /* border width of window */ + int depth; /* depth of window */ + Visual *visual; /* the associated visual structure */ + Window root; /* root of screen containing window */ +#if defined(__cplusplus) || defined(c_plusplus) + int c_class; /* C++ InputOutput, InputOnly*/ +#else + int class; /* InputOutput, InputOnly*/ +#endif + int bit_gravity; /* one of bit gravity values */ + int win_gravity; /* one of the window gravity values */ + int backing_store; /* NotUseful, WhenMapped, Always */ + unsigned long backing_planes;/* planes to be preserved if possible */ + unsigned long backing_pixel;/* value to be used when restoring planes */ + Bool save_under; /* boolean, should bits under be saved? */ + Colormap colormap; /* color map to be associated with window */ + Bool map_installed; /* boolean, is color map currently installed*/ + int map_state; /* IsUnmapped, IsUnviewable, IsViewable */ + long all_event_masks; /* set of events all people have interest in*/ + long your_event_mask; /* my event mask */ + long do_not_propagate_mask; /* set of events that should not propagate */ + Bool override_redirect; /* boolean value for override-redirect */ + Screen *screen; /* back pointer to correct screen */ +} XWindowAttributes; + +/* + * Data structure for host setting; getting routines. + * + */ + +typedef struct { + int family; /* for example FamilyInternet */ + int length; /* length of address, in bytes */ + char *address; /* pointer to where to find the bytes */ +} XHostAddress; + +/* + * Data structure for "image" data, used by image manipulation routines. + */ +typedef struct _XImage { + int width, height; /* size of image */ + int xoffset; /* number of pixels offset in X direction */ + int format; /* XYBitmap, XYPixmap, ZPixmap */ + char *data; /* pointer to image data */ + int byte_order; /* data byte order, LSBFirst, MSBFirst */ + int bitmap_unit; /* quant. of scanline 8, 16, 32 */ + int bitmap_bit_order; /* LSBFirst, MSBFirst */ + int bitmap_pad; /* 8, 16, 32 either XY or ZPixmap */ + int depth; /* depth of image */ + int bytes_per_line; /* accelarator to next line */ + int bits_per_pixel; /* bits per pixel (ZPixmap) */ + unsigned long red_mask; /* bits in z arrangment */ + unsigned long green_mask; + unsigned long blue_mask; + XPointer obdata; /* hook for the object routines to hang on */ + struct funcs { /* image manipulation routines */ + struct _XImage *(*create_image)(); +#if NeedFunctionPrototypes + int (*destroy_image) (struct _XImage *); + unsigned long (*get_pixel) (struct _XImage *, int, int); + int (*put_pixel) (struct _XImage *, int, int, unsigned long); + struct _XImage *(*sub_image)(struct _XImage *, int, int, unsigned int, unsigned int); + int (*add_pixel) (struct _XImage *, long); +#else + int (*destroy_image)(); + unsigned long (*get_pixel)(); + int (*put_pixel)(); + struct _XImage *(*sub_image)(); + int (*add_pixel)(); +#endif + } f; +} XImage; + +/* + * Data structure for XReconfigureWindow + */ +typedef struct { + int x, y; + int width, height; + int border_width; + Window sibling; + int stack_mode; +} XWindowChanges; + +/* + * Data structure used by color operations + */ +typedef struct { + unsigned long pixel; + unsigned short red, green, blue; + char flags; /* do_red, do_green, do_blue */ + char pad; +} XColor; + +/* + * Data structures for graphics operations. On most machines, these are + * congruent with the wire protocol structures, so reformatting the data + * can be avoided on these architectures. + */ +typedef struct { + short x1, y1, x2, y2; +} XSegment; + +typedef struct { + short x, y; +} XPoint; + +typedef struct { + short x, y; + unsigned short width, height; +} XRectangle; + +typedef struct { + short x, y; + unsigned short width, height; + short angle1, angle2; +} XArc; + + +/* Data structure for XChangeKeyboardControl */ + +typedef struct { + int key_click_percent; + int bell_percent; + int bell_pitch; + int bell_duration; + int led; + int led_mode; + int key; + int auto_repeat_mode; /* On, Off, Default */ +} XKeyboardControl; + +/* Data structure for XGetKeyboardControl */ + +typedef struct { + int key_click_percent; + int bell_percent; + unsigned int bell_pitch, bell_duration; + unsigned long led_mask; + int global_auto_repeat; + char auto_repeats[32]; +} XKeyboardState; + +/* Data structure for XGetMotionEvents. */ + +typedef struct { + Time time; + short x, y; +} XTimeCoord; + +/* Data structure for X{Set,Get}ModifierMapping */ + +typedef struct { + int max_keypermod; /* The server's max # of keys per modifier */ + KeyCode *modifiermap; /* An 8 by max_keypermod array of modifiers */ +} XModifierKeymap; + + +/* + * Display datatype maintaining display specific data. + * The contents of this structure are implementation dependent. + * A Display should be treated as opaque by application code. + */ +typedef struct _XDisplay { + XExtData *ext_data; /* hook for extension to hang data */ + struct _XFreeFuncs *free_funcs; /* internal free functions */ + int fd; /* Network socket. */ + int conn_checker; /* ugly thing used by _XEventsQueued */ + int proto_major_version;/* maj. version of server's X protocol */ + int proto_minor_version;/* minor version of servers X protocol */ + char *vendor; /* vendor of the server hardware */ + XID resource_base; /* resource ID base */ + XID resource_mask; /* resource ID mask bits */ + XID resource_id; /* allocator current ID */ + int resource_shift; /* allocator shift to correct bits */ + XID (*resource_alloc)(); /* allocator function */ + int byte_order; /* screen byte order, LSBFirst, MSBFirst */ + int bitmap_unit; /* padding and data requirements */ + int bitmap_pad; /* padding requirements on bitmaps */ + int bitmap_bit_order; /* LeastSignificant or MostSignificant */ + int nformats; /* number of pixmap formats in list */ + ScreenFormat *pixmap_format; /* pixmap format list */ + int vnumber; /* Xlib's X protocol version number. */ + int release; /* release of the server */ + struct _XSQEvent *head, *tail; /* Input event queue. */ + int qlen; /* Length of input event queue */ + unsigned long request; /* sequence number of last request. */ + char *last_req; /* beginning of last request, or dummy */ + char *buffer; /* Output buffer starting address. */ + char *bufptr; /* Output buffer index pointer. */ + char *bufmax; /* Output buffer maximum+1 address. */ + unsigned max_request_size; /* maximum number 32 bit words in request*/ + struct _XrmHashBucketRec *db; + int (*synchandler)(); /* Synchronization handler */ + char *display_name; /* "host:display" string used on this connect*/ + int default_screen; /* default screen for operations */ + int nscreens; /* number of screens on this server*/ + Screen *screens; /* pointer to list of screens */ + unsigned long motion_buffer; /* size of motion buffer */ + unsigned long flags; /* internal connection flags */ + int min_keycode; /* minimum defined keycode */ + int max_keycode; /* maximum defined keycode */ + KeySym *keysyms; /* This server's keysyms */ + XModifierKeymap *modifiermap; /* This server's modifier keymap */ + int keysyms_per_keycode;/* number of rows */ + char *xdefaults; /* contents of defaults from server */ + char *scratch_buffer; /* place to hang scratch buffer */ + unsigned long scratch_length; /* length of scratch buffer */ + int ext_number; /* extension number on this display */ + struct _XExten *ext_procs; /* extensions initialized on this display */ + /* + * the following can be fixed size, as the protocol defines how + * much address space is available. + * While this could be done using the extension vector, there + * may be MANY events processed, so a search through the extension + * list to find the right procedure for each event might be + * expensive if many extensions are being used. + */ + Bool (*event_vec[128])(); /* vector for wire to event */ + Status (*wire_vec[128])(); /* vector for event to wire */ + KeySym lock_meaning; /* for XLookupString */ + struct _XLockInfo *lock; /* multi-thread state, display lock */ + struct _XInternalAsync *async_handlers; /* for internal async */ + unsigned long bigreq_size; /* max size of big requests */ + struct _XLockPtrs *lock_fns; /* pointers to threads functions */ + /* things above this line should not move, for binary compatibility */ + struct _XKeytrans *key_bindings; /* for XLookupString */ + Font cursor_font; /* for XCreateFontCursor */ + struct _XDisplayAtoms *atoms; /* for XInternAtom */ + unsigned int mode_switch; /* keyboard group modifiers */ + struct _XContextDB *context_db; /* context database */ + Bool (**error_vec)(); /* vector for wire to error */ + /* + * Xcms information + */ + struct { + XPointer defaultCCCs; /* pointer to an array of default XcmsCCC */ + XPointer clientCmaps; /* pointer to linked list of XcmsCmapRec */ + XPointer perVisualIntensityMaps; + /* linked list of XcmsIntensityMap */ + } cms; + struct _XIMFilter *im_filters; + struct _XSQEvent *qfree; /* unallocated event queue elements */ + unsigned long next_event_serial_num; /* inserted into next queue elt */ + int (*savedsynchandler)(); /* user synchandler when Xlib usurps */ +} Display; + +#if NeedFunctionPrototypes /* prototypes require event type definitions */ +#undef _XEVENT_ +#endif +#ifndef _XEVENT_ + +#define XMaxTransChars 4 + +/* + * Definitions of specific events. + */ +typedef struct { + int type; /* of event */ + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; /* "event" window it is reported relative to */ + Window root; /* root window that the event occured on */ + Window subwindow; /* child window */ + Time time; /* milliseconds */ + int x, y; /* pointer x, y coordinates in event window */ + int x_root, y_root; /* coordinates relative to root */ + unsigned int state; /* key or button mask */ + unsigned int keycode; /* detail */ + Bool same_screen; /* same screen flag */ + char trans_chars[XMaxTransChars]; + /* translated characters */ + int nchars; +} XKeyEvent; +typedef XKeyEvent XKeyPressedEvent; +typedef XKeyEvent XKeyReleasedEvent; + +typedef struct { + int type; /* of event */ + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; /* "event" window it is reported relative to */ + Window root; /* root window that the event occured on */ + Window subwindow; /* child window */ + Time time; /* milliseconds */ + int x, y; /* pointer x, y coordinates in event window */ + int x_root, y_root; /* coordinates relative to root */ + unsigned int state; /* key or button mask */ + unsigned int button; /* detail */ + Bool same_screen; /* same screen flag */ +} XButtonEvent; +typedef XButtonEvent XButtonPressedEvent; +typedef XButtonEvent XButtonReleasedEvent; + +typedef struct { + int type; /* of event */ + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; /* "event" window reported relative to */ + Window root; /* root window that the event occured on */ + Window subwindow; /* child window */ + Time time; /* milliseconds */ + int x, y; /* pointer x, y coordinates in event window */ + int x_root, y_root; /* coordinates relative to root */ + unsigned int state; /* key or button mask */ + char is_hint; /* detail */ + Bool same_screen; /* same screen flag */ +} XMotionEvent; +typedef XMotionEvent XPointerMovedEvent; + +typedef struct { + int type; /* of event */ + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; /* "event" window reported relative to */ + Window root; /* root window that the event occured on */ + Window subwindow; /* child window */ + Time time; /* milliseconds */ + int x, y; /* pointer x, y coordinates in event window */ + int x_root, y_root; /* coordinates relative to root */ + int mode; /* NotifyNormal, NotifyGrab, NotifyUngrab */ + int detail; + /* + * NotifyAncestor, NotifyVirtual, NotifyInferior, + * NotifyNonlinear,NotifyNonlinearVirtual + */ + Bool same_screen; /* same screen flag */ + Bool focus; /* boolean focus */ + unsigned int state; /* key or button mask */ +} XCrossingEvent; +typedef XCrossingEvent XEnterWindowEvent; +typedef XCrossingEvent XLeaveWindowEvent; + +typedef struct { + int type; /* FocusIn or FocusOut */ + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; /* window of event */ + int mode; /* NotifyNormal, NotifyGrab, NotifyUngrab */ + int detail; + /* + * NotifyAncestor, NotifyVirtual, NotifyInferior, + * NotifyNonlinear,NotifyNonlinearVirtual, NotifyPointer, + * NotifyPointerRoot, NotifyDetailNone + */ +} XFocusChangeEvent; +typedef XFocusChangeEvent XFocusInEvent; +typedef XFocusChangeEvent XFocusOutEvent; + +/* generated on EnterWindow and FocusIn when KeyMapState selected */ +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; + char key_vector[32]; +} XKeymapEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; + int x, y; + int width, height; + int count; /* if non-zero, at least this many more */ +} XExposeEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Drawable drawable; + int x, y; + int width, height; + int count; /* if non-zero, at least this many more */ + int major_code; /* core is CopyArea or CopyPlane */ + int minor_code; /* not defined in the core */ +} XGraphicsExposeEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Drawable drawable; + int major_code; /* core is CopyArea or CopyPlane */ + int minor_code; /* not defined in the core */ +} XNoExposeEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; + int state; /* Visibility state */ +} XVisibilityEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window parent; /* parent of the window */ + Window window; /* window id of window created */ + int x, y; /* window location */ + int width, height; /* size of window */ + int border_width; /* border width */ + Bool override_redirect; /* creation should be overridden */ +} XCreateWindowEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window event; + Window window; +} XDestroyWindowEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window event; + Window window; + Bool from_configure; +} XUnmapEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window event; + Window window; + Bool override_redirect; /* boolean, is override set... */ +} XMapEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window parent; + Window window; +} XMapRequestEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window event; + Window window; + Window parent; + int x, y; + Bool override_redirect; +} XReparentEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window event; + Window window; + int x, y; + int width, height; + int border_width; + Window above; + Bool override_redirect; +} XConfigureEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window event; + Window window; + int x, y; +} XGravityEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; + int width, height; +} XResizeRequestEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window parent; + Window window; + int x, y; + int width, height; + int border_width; + Window above; + int detail; /* Above, Below, TopIf, BottomIf, Opposite */ + unsigned long value_mask; +} XConfigureRequestEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window event; + Window window; + int place; /* PlaceOnTop, PlaceOnBottom */ +} XCirculateEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window parent; + Window window; + int place; /* PlaceOnTop, PlaceOnBottom */ +} XCirculateRequestEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; + Atom atom; + Time time; + int state; /* NewValue, Deleted */ +} XPropertyEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; + Atom selection; + Time time; +} XSelectionClearEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window owner; + Window requestor; + Atom selection; + Atom target; + Atom property; + Time time; +} XSelectionRequestEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window requestor; + Atom selection; + Atom target; + Atom property; /* ATOM or None */ + Time time; +} XSelectionEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; + Colormap colormap; /* COLORMAP or None */ +#if defined(__cplusplus) || defined(c_plusplus) + Bool c_new; /* C++ */ +#else + Bool new; +#endif + int state; /* ColormapInstalled, ColormapUninstalled */ +} XColormapEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; + Atom message_type; + int format; + union { + char b[20]; + short s[10]; + long l[5]; + } data; +} XClientMessageEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Window window; /* unused */ + int request; /* one of MappingModifier, MappingKeyboard, + MappingPointer */ + int first_keycode; /* first keycode */ + int count; /* defines range of change w. first_keycode*/ +} XMappingEvent; + +typedef struct { + int type; + Display *display; /* Display the event was read from */ + XID resourceid; /* resource id */ + unsigned long serial; /* serial number of failed request */ + unsigned char error_code; /* error code of failed request */ + unsigned char request_code; /* Major op-code of failed request */ + unsigned char minor_code; /* Minor op-code of failed request */ +} XErrorEvent; + +typedef struct { + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display;/* Display the event was read from */ + Window window; /* window on which event was requested in event mask */ +} XAnyEvent; + +/* + * this union is defined so Xlib can always use the same sized + * event structure internally, to avoid memory fragmentation. + */ +typedef union _XEvent { + int type; /* must not be changed; first element */ + XAnyEvent xany; + XKeyEvent xkey; + XButtonEvent xbutton; + XMotionEvent xmotion; + XCrossingEvent xcrossing; + XFocusChangeEvent xfocus; + XExposeEvent xexpose; + XGraphicsExposeEvent xgraphicsexpose; + XNoExposeEvent xnoexpose; + XVisibilityEvent xvisibility; + XCreateWindowEvent xcreatewindow; + XDestroyWindowEvent xdestroywindow; + XUnmapEvent xunmap; + XMapEvent xmap; + XMapRequestEvent xmaprequest; + XReparentEvent xreparent; + XConfigureEvent xconfigure; + XGravityEvent xgravity; + XResizeRequestEvent xresizerequest; + XConfigureRequestEvent xconfigurerequest; + XCirculateEvent xcirculate; + XCirculateRequestEvent xcirculaterequest; + XPropertyEvent xproperty; + XSelectionClearEvent xselectionclear; + XSelectionRequestEvent xselectionrequest; + XSelectionEvent xselection; + XColormapEvent xcolormap; + XClientMessageEvent xclient; + XMappingEvent xmapping; + XErrorEvent xerror; + XKeymapEvent xkeymap; + long pad[24]; +} XEvent; +#endif + +#define XAllocID(dpy) ((*(dpy)->resource_alloc)((dpy))) + +/* + * per character font metric information. + */ +typedef struct { + short lbearing; /* origin to left edge of raster */ + short rbearing; /* origin to right edge of raster */ + short width; /* advance to next char's origin */ + short ascent; /* baseline to top edge of raster */ + short descent; /* baseline to bottom edge of raster */ + unsigned short attributes; /* per char flags (not predefined) */ +} XCharStruct; + +/* + * To allow arbitrary information with fonts, there are additional properties + * returned. + */ +typedef struct { + Atom name; + unsigned long card32; +} XFontProp; + +typedef struct { + XExtData *ext_data; /* hook for extension to hang data */ + Font fid; /* Font id for this font */ + unsigned direction; /* hint about direction the font is painted */ + unsigned min_char_or_byte2;/* first character */ + unsigned max_char_or_byte2;/* last character */ + unsigned min_byte1; /* first row that exists */ + unsigned max_byte1; /* last row that exists */ + Bool all_chars_exist;/* flag if all characters have non-zero size*/ + unsigned default_char; /* char to print for undefined character */ + int n_properties; /* how many properties there are */ + XFontProp *properties; /* pointer to array of additional properties*/ + XCharStruct min_bounds; /* minimum bounds over all existing char*/ + XCharStruct max_bounds; /* maximum bounds over all existing char*/ + XCharStruct *per_char; /* first_char to last_char information */ + int ascent; /* log. extent above baseline for spacing */ + int descent; /* log. descent below baseline for spacing */ +} XFontStruct; + +/* + * PolyText routines take these as arguments. + */ +typedef struct { + char *chars; /* pointer to string */ + int nchars; /* number of characters */ + int delta; /* delta between strings */ + Font font; /* font to print it in, None don't change */ +} XTextItem; + +typedef struct { /* normal 16 bit characters are two bytes */ + unsigned char byte1; + unsigned char byte2; +} XChar2b; + +typedef struct { + XChar2b *chars; /* two byte characters */ + int nchars; /* number of characters */ + int delta; /* delta between strings */ + Font font; /* font to print it in, None don't change */ +} XTextItem16; + + +typedef union { Display *display; + GC gc; + Visual *visual; + Screen *screen; + ScreenFormat *pixmap_format; + XFontStruct *font; } XEDataObject; + +typedef struct { + XRectangle max_ink_extent; + XRectangle max_logical_extent; +} XFontSetExtents; + +typedef struct _XFontSet *XFontSet; + +typedef struct { + char *chars; + int nchars; + int delta; + XFontSet font_set; +} XmbTextItem; + +typedef struct { + wchar_t *chars; + int nchars; + int delta; + XFontSet font_set; +} XwcTextItem; + +typedef void (*XIMProc)(); + +typedef struct _XIM *XIM; +typedef struct _XIC *XIC; + +typedef unsigned long XIMStyle; + +typedef struct { + unsigned short count_styles; + XIMStyle *supported_styles; +} XIMStyles; + +#define XIMPreeditArea 0x0001L +#define XIMPreeditCallbacks 0x0002L +#define XIMPreeditPosition 0x0004L +#define XIMPreeditNothing 0x0008L +#define XIMPreeditNone 0x0010L +#define XIMStatusArea 0x0100L +#define XIMStatusCallbacks 0x0200L +#define XIMStatusNothing 0x0400L +#define XIMStatusNone 0x0800L + +#define XNVaNestedList "XNVaNestedList" +#define XNClientWindow "clientWindow" +#define XNInputStyle "inputStyle" +#define XNFocusWindow "focusWindow" +#define XNResourceName "resourceName" +#define XNResourceClass "resourceClass" +#define XNGeometryCallback "geometryCallback" +#define XNFilterEvents "filterEvents" +#define XNPreeditStartCallback "preeditStartCallback" +#define XNPreeditDoneCallback "preeditDoneCallback" +#define XNPreeditDrawCallback "preeditDrawCallback" +#define XNPreeditCaretCallback "preeditCaretCallback" +#define XNPreeditAttributes "preeditAttributes" +#define XNStatusStartCallback "statusStartCallback" +#define XNStatusDoneCallback "statusDoneCallback" +#define XNStatusDrawCallback "statusDrawCallback" +#define XNStatusAttributes "statusAttributes" +#define XNArea "area" +#define XNAreaNeeded "areaNeeded" +#define XNSpotLocation "spotLocation" +#define XNColormap "colorMap" +#define XNStdColormap "stdColorMap" +#define XNForeground "foreground" +#define XNBackground "background" +#define XNBackgroundPixmap "backgroundPixmap" +#define XNFontSet "fontSet" +#define XNLineSpace "lineSpace" +#define XNCursor "cursor" + +#define XBufferOverflow -1 +#define XLookupNone 1 +#define XLookupChars 2 +#define XLookupKeySym 3 +#define XLookupBoth 4 + +#if NeedFunctionPrototypes +typedef void *XVaNestedList; +#else +typedef XPointer XVaNestedList; +#endif + +typedef struct { + XPointer client_data; + XIMProc callback; +} XIMCallback; + +typedef unsigned long XIMFeedback; + +#define XIMReverse 1 +#define XIMUnderline (1<<1) +#define XIMHighlight (1<<2) +#define XIMPrimary (1<<5) +#define XIMSecondary (1<<6) +#define XIMTertiary (1<<7) + +typedef struct _XIMText { + unsigned short length; + XIMFeedback *feedback; + Bool encoding_is_wchar; + union { + char *multi_byte; + wchar_t *wide_char; + } string; +} XIMText; + +typedef struct _XIMPreeditDrawCallbackStruct { + int caret; /* Cursor offset within pre-edit string */ + int chg_first; /* Starting change position */ + int chg_length; /* Length of the change in character count */ + XIMText *text; +} XIMPreeditDrawCallbackStruct; + +typedef enum { + XIMForwardChar, XIMBackwardChar, + XIMForwardWord, XIMBackwardWord, + XIMCaretUp, XIMCaretDown, + XIMNextLine, XIMPreviousLine, + XIMLineStart, XIMLineEnd, + XIMAbsolutePosition, + XIMDontChange +} XIMCaretDirection; + +typedef enum { + XIMIsInvisible, /* Disable caret feedback */ + XIMIsPrimary, /* UI defined caret feedback */ + XIMIsSecondary /* UI defined caret feedback */ +} XIMCaretStyle; + +typedef struct _XIMPreeditCaretCallbackStruct { + int position; /* Caret offset within pre-edit string */ + XIMCaretDirection direction; /* Caret moves direction */ + XIMCaretStyle style; /* Feedback of the caret */ +} XIMPreeditCaretCallbackStruct; + +typedef enum { + XIMTextType, + XIMBitmapType +} XIMStatusDataType; + +typedef struct _XIMStatusDrawCallbackStruct { + XIMStatusDataType type; + union { + XIMText *text; + Pixmap bitmap; + } data; +} XIMStatusDrawCallbackStruct; + +_XFUNCPROTOBEGIN + +extern XFontStruct *XLoadQueryFont( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* name */ +#endif +); + +extern XFontStruct *XQueryFont( +#if NeedFunctionPrototypes + Display* /* display */, + XID /* font_ID */ +#endif +); + + +extern XTimeCoord *XGetMotionEvents( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Time /* start */, + Time /* stop */, + int* /* nevents_return */ +#endif +); + +extern XModifierKeymap *XDeleteModifiermapEntry( +#if NeedFunctionPrototypes + XModifierKeymap* /* modmap */, +#if NeedWidePrototypes + unsigned int /* keycode_entry */, +#else + KeyCode /* keycode_entry */, +#endif + int /* modifier */ +#endif +); + +extern XModifierKeymap *XGetModifierMapping( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern XModifierKeymap *XInsertModifiermapEntry( +#if NeedFunctionPrototypes + XModifierKeymap* /* modmap */, +#if NeedWidePrototypes + unsigned int /* keycode_entry */, +#else + KeyCode /* keycode_entry */, +#endif + int /* modifier */ +#endif +); + +extern XModifierKeymap *XNewModifiermap( +#if NeedFunctionPrototypes + int /* max_keys_per_mod */ +#endif +); + +extern XImage *XCreateImage( +#if NeedFunctionPrototypes + Display* /* display */, + Visual* /* visual */, + unsigned int /* depth */, + int /* format */, + int /* offset */, + char* /* data */, + unsigned int /* width */, + unsigned int /* height */, + int /* bitmap_pad */, + int /* bytes_per_line */ +#endif +); +extern XImage *XGetImage( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */, + unsigned long /* plane_mask */, + int /* format */ +#endif +); +extern XImage *XGetSubImage( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */, + unsigned long /* plane_mask */, + int /* format */, + XImage* /* dest_image */, + int /* dest_x */, + int /* dest_y */ +#endif +); + +/* + * X function declarations. + */ +extern Display *XOpenDisplay( +#if NeedFunctionPrototypes + _Xconst char* /* display_name */ +#endif +); + +extern void XrmInitialize( +#if NeedFunctionPrototypes + void +#endif +); + +extern char *XFetchBytes( +#if NeedFunctionPrototypes + Display* /* display */, + int* /* nbytes_return */ +#endif +); +extern char *XFetchBuffer( +#if NeedFunctionPrototypes + Display* /* display */, + int* /* nbytes_return */, + int /* buffer */ +#endif +); +extern char *XGetAtomName( +#if NeedFunctionPrototypes + Display* /* display */, + Atom /* atom */ +#endif +); +extern char *XGetDefault( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* program */, + _Xconst char* /* option */ +#endif +); +extern char *XDisplayName( +#if NeedFunctionPrototypes + _Xconst char* /* string */ +#endif +); +extern char *XKeysymToString( +#if NeedFunctionPrototypes + KeySym /* keysym */ +#endif +); + +extern int (*XSynchronize( +#if NeedFunctionPrototypes + Display* /* display */, + Bool /* onoff */ +#endif +))(); +extern int (*XSetAfterFunction( +#if NeedFunctionPrototypes + Display* /* display */, + int (*) ( +#if NeedNestedPrototypes + Display* /* display */ +#endif + ) /* procedure */ +#endif +))(); +extern Atom XInternAtom( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* atom_name */, + Bool /* only_if_exists */ +#endif +); +extern Colormap XCopyColormapAndFree( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */ +#endif +); +extern Colormap XCreateColormap( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Visual* /* visual */, + int /* alloc */ +#endif +); +extern Cursor XCreatePixmapCursor( +#if NeedFunctionPrototypes + Display* /* display */, + Pixmap /* source */, + Pixmap /* mask */, + XColor* /* foreground_color */, + XColor* /* background_color */, + unsigned int /* x */, + unsigned int /* y */ +#endif +); +extern Cursor XCreateGlyphCursor( +#if NeedFunctionPrototypes + Display* /* display */, + Font /* source_font */, + Font /* mask_font */, + unsigned int /* source_char */, + unsigned int /* mask_char */, + XColor* /* foreground_color */, + XColor* /* background_color */ +#endif +); +extern Cursor XCreateFontCursor( +#if NeedFunctionPrototypes + Display* /* display */, + unsigned int /* shape */ +#endif +); +extern Font XLoadFont( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* name */ +#endif +); +extern GC XCreateGC( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + unsigned long /* valuemask */, + XGCValues* /* values */ +#endif +); +extern GContext XGContextFromGC( +#if NeedFunctionPrototypes + GC /* gc */ +#endif +); +extern void XFlushGC( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */ +#endif +); +extern Pixmap XCreatePixmap( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + unsigned int /* width */, + unsigned int /* height */, + unsigned int /* depth */ +#endif +); +extern Pixmap XCreateBitmapFromData( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + _Xconst char* /* data */, + unsigned int /* width */, + unsigned int /* height */ +#endif +); +extern Pixmap XCreatePixmapFromBitmapData( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + char* /* data */, + unsigned int /* width */, + unsigned int /* height */, + unsigned long /* fg */, + unsigned long /* bg */, + unsigned int /* depth */ +#endif +); +extern Window XCreateSimpleWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* parent */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */, + unsigned int /* border_width */, + unsigned long /* border */, + unsigned long /* background */ +#endif +); +extern Window XGetSelectionOwner( +#if NeedFunctionPrototypes + Display* /* display */, + Atom /* selection */ +#endif +); +extern Window XCreateWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* parent */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */, + unsigned int /* border_width */, + int /* depth */, + unsigned int /* class */, + Visual* /* visual */, + unsigned long /* valuemask */, + XSetWindowAttributes* /* attributes */ +#endif +); +extern Colormap *XListInstalledColormaps( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int* /* num_return */ +#endif +); +extern char **XListFonts( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* pattern */, + int /* maxnames */, + int* /* actual_count_return */ +#endif +); +extern char **XListFontsWithInfo( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* pattern */, + int /* maxnames */, + int* /* count_return */, + XFontStruct** /* info_return */ +#endif +); +extern char **XGetFontPath( +#if NeedFunctionPrototypes + Display* /* display */, + int* /* npaths_return */ +#endif +); +extern char **XListExtensions( +#if NeedFunctionPrototypes + Display* /* display */, + int* /* nextensions_return */ +#endif +); +extern Atom *XListProperties( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int* /* num_prop_return */ +#endif +); +extern XHostAddress *XListHosts( +#if NeedFunctionPrototypes + Display* /* display */, + int* /* nhosts_return */, + Bool* /* state_return */ +#endif +); +extern KeySym XKeycodeToKeysym( +#if NeedFunctionPrototypes + Display* /* display */, +#if NeedWidePrototypes + unsigned int /* keycode */, +#else + KeyCode /* keycode */, +#endif + int /* index */ +#endif +); +extern KeySym XLookupKeysym( +#if NeedFunctionPrototypes + XKeyEvent* /* key_event */, + int /* index */ +#endif +); +extern KeySym *XGetKeyboardMapping( +#if NeedFunctionPrototypes + Display* /* display */, +#if NeedWidePrototypes + unsigned int /* first_keycode */, +#else + KeyCode /* first_keycode */, +#endif + int /* keycode_count */, + int* /* keysyms_per_keycode_return */ +#endif +); +extern KeySym XStringToKeysym( +#if NeedFunctionPrototypes + _Xconst char* /* string */ +#endif +); +extern long XMaxRequestSize( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern long XExtendedMaxRequestSize( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern char *XResourceManagerString( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern char *XScreenResourceString( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); +extern unsigned long XDisplayMotionBufferSize( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern VisualID XVisualIDFromVisual( +#if NeedFunctionPrototypes + Visual* /* visual */ +#endif +); + +/* routines for dealing with extensions */ + +extern XExtCodes *XInitExtension( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* name */ +#endif +); + +extern XExtCodes *XAddExtension( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern XExtData *XFindOnExtensionList( +#if NeedFunctionPrototypes + XExtData** /* structure */, + int /* number */ +#endif +); +extern XExtData **XEHeadOfExtensionList( +#if NeedFunctionPrototypes + XEDataObject /* object */ +#endif +); + +/* these are routines for which there are also macros */ +extern Window XRootWindow( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); +extern Window XDefaultRootWindow( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern Window XRootWindowOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); +extern Visual *XDefaultVisual( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); +extern Visual *XDefaultVisualOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); +extern GC XDefaultGC( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); +extern GC XDefaultGCOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); +extern unsigned long XBlackPixel( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); +extern unsigned long XWhitePixel( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); +extern unsigned long XAllPlanes( +#if NeedFunctionPrototypes + void +#endif +); +extern unsigned long XBlackPixelOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); +extern unsigned long XWhitePixelOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); +extern unsigned long XNextRequest( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern unsigned long XLastKnownRequestProcessed( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern char *XServerVendor( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern char *XDisplayString( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern Colormap XDefaultColormap( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); +extern Colormap XDefaultColormapOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); +extern Display *XDisplayOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); +extern Screen *XScreenOfDisplay( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); +extern Screen *XDefaultScreenOfDisplay( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); +extern long XEventMaskOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern int XScreenNumberOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +typedef int (*XErrorHandler) ( /* WARNING, this type not in Xlib spec */ +#if NeedFunctionPrototypes + Display* /* display */, + XErrorEvent* /* error_event */ +#endif +); + +extern XErrorHandler XSetErrorHandler ( +#if NeedFunctionPrototypes + XErrorHandler /* handler */ +#endif +); + + +typedef int (*XIOErrorHandler) ( /* WARNING, this type not in Xlib spec */ +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern XIOErrorHandler XSetIOErrorHandler ( +#if NeedFunctionPrototypes + XIOErrorHandler /* handler */ +#endif +); + + +extern XPixmapFormatValues *XListPixmapFormats( +#if NeedFunctionPrototypes + Display* /* display */, + int* /* count_return */ +#endif +); +extern int *XListDepths( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */, + int* /* count_return */ +#endif +); + +/* ICCCM routines for things that don't require special include files; */ +/* other declarations are given in Xutil.h */ +extern Status XReconfigureWMWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int /* screen_number */, + unsigned int /* mask */, + XWindowChanges* /* changes */ +#endif +); + +extern Status XGetWMProtocols( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Atom** /* protocols_return */, + int* /* count_return */ +#endif +); +extern Status XSetWMProtocols( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Atom* /* protocols */, + int /* count */ +#endif +); +extern Status XIconifyWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int /* screen_number */ +#endif +); +extern Status XWithdrawWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int /* screen_number */ +#endif +); +extern Status XGetCommand( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + char*** /* argv_return */, + int* /* argc_return */ +#endif +); +extern Status XGetWMColormapWindows( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Window** /* windows_return */, + int* /* count_return */ +#endif +); +extern Status XSetWMColormapWindows( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Window* /* colormap_windows */, + int /* count */ +#endif +); +extern void XFreeStringList( +#if NeedFunctionPrototypes + char** /* list */ +#endif +); +extern void XSetTransientForHint( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Window /* prop_window */ +#endif +); + +/* The following are given in alphabetical order */ + +extern void XActivateScreenSaver( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XAddHost( +#if NeedFunctionPrototypes + Display* /* display */, + XHostAddress* /* host */ +#endif +); + +extern void XAddHosts( +#if NeedFunctionPrototypes + Display* /* display */, + XHostAddress* /* hosts */, + int /* num_hosts */ +#endif +); + +extern void XAddToExtensionList( +#if NeedFunctionPrototypes + struct _XExtData** /* structure */, + XExtData* /* ext_data */ +#endif +); + +extern void XAddToSaveSet( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern Status XAllocColor( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + XColor* /* screen_in_out */ +#endif +); + +extern Status XAllocColorCells( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + Bool /* contig */, + unsigned long* /* plane_masks_return */, + unsigned int /* nplanes */, + unsigned long* /* pixels_return */, + unsigned int /* npixels */ +#endif +); + +extern Status XAllocColorPlanes( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + Bool /* contig */, + unsigned long* /* pixels_return */, + int /* ncolors */, + int /* nreds */, + int /* ngreens */, + int /* nblues */, + unsigned long* /* rmask_return */, + unsigned long* /* gmask_return */, + unsigned long* /* bmask_return */ +#endif +); + +extern Status XAllocNamedColor( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + _Xconst char* /* color_name */, + XColor* /* screen_def_return */, + XColor* /* exact_def_return */ +#endif +); + +extern void XAllowEvents( +#if NeedFunctionPrototypes + Display* /* display */, + int /* event_mode */, + Time /* time */ +#endif +); + +extern void XAutoRepeatOff( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XAutoRepeatOn( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XBell( +#if NeedFunctionPrototypes + Display* /* display */, + int /* percent */ +#endif +); + +extern int XBitmapBitOrder( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern int XBitmapPad( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern int XBitmapUnit( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern int XCellsOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern void XChangeActivePointerGrab( +#if NeedFunctionPrototypes + Display* /* display */, + unsigned int /* event_mask */, + Cursor /* cursor */, + Time /* time */ +#endif +); + +extern void XChangeGC( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + unsigned long /* valuemask */, + XGCValues* /* values */ +#endif +); + +extern void XChangeKeyboardControl( +#if NeedFunctionPrototypes + Display* /* display */, + unsigned long /* value_mask */, + XKeyboardControl* /* values */ +#endif +); + +extern void XChangeKeyboardMapping( +#if NeedFunctionPrototypes + Display* /* display */, + int /* first_keycode */, + int /* keysyms_per_keycode */, + KeySym* /* keysyms */, + int /* num_codes */ +#endif +); + +extern void XChangePointerControl( +#if NeedFunctionPrototypes + Display* /* display */, + Bool /* do_accel */, + Bool /* do_threshold */, + int /* accel_numerator */, + int /* accel_denominator */, + int /* threshold */ +#endif +); + +extern void XChangeProperty( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Atom /* property */, + Atom /* type */, + int /* format */, + int /* mode */, + _Xconst unsigned char* /* data */, + int /* nelements */ +#endif +); + +extern void XChangeSaveSet( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int /* change_mode */ +#endif +); + +extern void XChangeWindowAttributes( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + unsigned long /* valuemask */, + XSetWindowAttributes* /* attributes */ +#endif +); + +extern Bool XCheckIfEvent( +#if NeedFunctionPrototypes + Display* /* display */, + XEvent* /* event_return */, + Bool (*) ( +#if NeedNestedPrototypes + Display* /* display */, + XEvent* /* event */, + XPointer /* arg */ +#endif + ) /* predicate */, + XPointer /* arg */ +#endif +); + +extern Bool XCheckMaskEvent( +#if NeedFunctionPrototypes + Display* /* display */, + long /* event_mask */, + XEvent* /* event_return */ +#endif +); + +extern Bool XCheckTypedEvent( +#if NeedFunctionPrototypes + Display* /* display */, + int /* event_type */, + XEvent* /* event_return */ +#endif +); + +extern Bool XCheckTypedWindowEvent( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int /* event_type */, + XEvent* /* event_return */ +#endif +); + +extern Bool XCheckWindowEvent( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + long /* event_mask */, + XEvent* /* event_return */ +#endif +); + +extern void XCirculateSubwindows( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int /* direction */ +#endif +); + +extern void XCirculateSubwindowsDown( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XCirculateSubwindowsUp( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XClearArea( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */, + Bool /* exposures */ +#endif +); + +extern void XClearWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XCloseDisplay( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XConfigureWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + unsigned int /* value_mask */, + XWindowChanges* /* values */ +#endif +); + +extern int XConnectionNumber( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XConvertSelection( +#if NeedFunctionPrototypes + Display* /* display */, + Atom /* selection */, + Atom /* target */, + Atom /* property */, + Window /* requestor */, + Time /* time */ +#endif +); + +extern void XCopyArea( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* src */, + Drawable /* dest */, + GC /* gc */, + int /* src_x */, + int /* src_y */, + unsigned int /* width */, + unsigned int /* height */, + int /* dest_x */, + int /* dest_y */ +#endif +); + +extern void XCopyGC( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* src */, + unsigned long /* valuemask */, + GC /* dest */ +#endif +); + +extern void XCopyPlane( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* src */, + Drawable /* dest */, + GC /* gc */, + int /* src_x */, + int /* src_y */, + unsigned int /* width */, + unsigned int /* height */, + int /* dest_x */, + int /* dest_y */, + unsigned long /* plane */ +#endif +); + +extern int XDefaultDepth( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); + +extern int XDefaultDepthOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern int XDefaultScreen( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XDefineCursor( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Cursor /* cursor */ +#endif +); + +extern void XDeleteProperty( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Atom /* property */ +#endif +); + +extern void XDestroyWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XDestroySubwindows( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern int XDoesBackingStore( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern Bool XDoesSaveUnders( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern void XDisableAccessControl( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + + +extern int XDisplayCells( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); + +extern int XDisplayHeight( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); + +extern int XDisplayHeightMM( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); + +extern void XDisplayKeycodes( +#if NeedFunctionPrototypes + Display* /* display */, + int* /* min_keycodes_return */, + int* /* max_keycodes_return */ +#endif +); + +extern int XDisplayPlanes( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); + +extern int XDisplayWidth( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); + +extern int XDisplayWidthMM( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */ +#endif +); + +extern void XDrawArc( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */, + int /* angle1 */, + int /* angle2 */ +#endif +); + +extern void XDrawArcs( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + XArc* /* arcs */, + int /* narcs */ +#endif +); + +extern void XDrawImageString( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + _Xconst char* /* string */, + int /* length */ +#endif +); + +extern void XDrawImageString16( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + _Xconst XChar2b* /* string */, + int /* length */ +#endif +); + +extern void XDrawLine( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x1 */, + int /* y1 */, + int /* x2 */, + int /* y2 */ +#endif +); + +extern void XDrawLines( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + XPoint* /* points */, + int /* npoints */, + int /* mode */ +#endif +); + +extern void XDrawPoint( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */ +#endif +); + +extern void XDrawPoints( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + XPoint* /* points */, + int /* npoints */, + int /* mode */ +#endif +); + +extern void XDrawRectangle( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */ +#endif +); + +extern void XDrawRectangles( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + XRectangle* /* rectangles */, + int /* nrectangles */ +#endif +); + +extern void XDrawSegments( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + XSegment* /* segments */, + int /* nsegments */ +#endif +); + +extern void XDrawString( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + _Xconst char* /* string */, + int /* length */ +#endif +); + +extern void XDrawString16( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + _Xconst XChar2b* /* string */, + int /* length */ +#endif +); + +extern void XDrawText( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + XTextItem* /* items */, + int /* nitems */ +#endif +); + +extern void XDrawText16( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + XTextItem16* /* items */, + int /* nitems */ +#endif +); + +extern void XEnableAccessControl( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern int XEventsQueued( +#if NeedFunctionPrototypes + Display* /* display */, + int /* mode */ +#endif +); + +extern Status XFetchName( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + char** /* window_name_return */ +#endif +); + +extern void XFillArc( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */, + int /* angle1 */, + int /* angle2 */ +#endif +); + +extern void XFillArcs( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + XArc* /* arcs */, + int /* narcs */ +#endif +); + +extern void XFillPolygon( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + XPoint* /* points */, + int /* npoints */, + int /* shape */, + int /* mode */ +#endif +); + +extern void XFillRectangle( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */ +#endif +); + +extern void XFillRectangles( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + XRectangle* /* rectangles */, + int /* nrectangles */ +#endif +); + +extern void XFlush( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XForceScreenSaver( +#if NeedFunctionPrototypes + Display* /* display */, + int /* mode */ +#endif +); + +extern void XFree( +#if NeedFunctionPrototypes + void* /* data */ +#endif +); + +extern void XFreeColormap( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */ +#endif +); + +extern void XFreeColors( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + unsigned long* /* pixels */, + int /* npixels */, + unsigned long /* planes */ +#endif +); + +extern void XFreeCursor( +#if NeedFunctionPrototypes + Display* /* display */, + Cursor /* cursor */ +#endif +); + +extern void XFreeExtensionList( +#if NeedFunctionPrototypes + char** /* list */ +#endif +); + +extern void XFreeFont( +#if NeedFunctionPrototypes + Display* /* display */, + XFontStruct* /* font_struct */ +#endif +); + +extern void XFreeFontInfo( +#if NeedFunctionPrototypes + char** /* names */, + XFontStruct* /* free_info */, + int /* actual_count */ +#endif +); + +extern void XFreeFontNames( +#if NeedFunctionPrototypes + char** /* list */ +#endif +); + +extern void XFreeFontPath( +#if NeedFunctionPrototypes + char** /* list */ +#endif +); + +extern void XFreeGC( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */ +#endif +); + +extern void XFreeModifiermap( +#if NeedFunctionPrototypes + XModifierKeymap* /* modmap */ +#endif +); + +extern void XFreePixmap( +#if NeedFunctionPrototypes + Display* /* display */, + Pixmap /* pixmap */ +#endif +); + +extern int XGeometry( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen */, + _Xconst char* /* position */, + _Xconst char* /* default_position */, + unsigned int /* bwidth */, + unsigned int /* fwidth */, + unsigned int /* fheight */, + int /* xadder */, + int /* yadder */, + int* /* x_return */, + int* /* y_return */, + int* /* width_return */, + int* /* height_return */ +#endif +); + +extern void XGetErrorDatabaseText( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* name */, + _Xconst char* /* message */, + _Xconst char* /* default_string */, + char* /* buffer_return */, + int /* length */ +#endif +); + +extern void XGetErrorText( +#if NeedFunctionPrototypes + Display* /* display */, + int /* code */, + char* /* buffer_return */, + int /* length */ +#endif +); + +extern Bool XGetFontProperty( +#if NeedFunctionPrototypes + XFontStruct* /* font_struct */, + Atom /* atom */, + unsigned long* /* value_return */ +#endif +); + +extern Status XGetGCValues( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + unsigned long /* valuemask */, + XGCValues* /* values_return */ +#endif +); + +extern Status XGetGeometry( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + Window* /* root_return */, + int* /* x_return */, + int* /* y_return */, + unsigned int* /* width_return */, + unsigned int* /* height_return */, + unsigned int* /* border_width_return */, + unsigned int* /* depth_return */ +#endif +); + +extern Status XGetIconName( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + char** /* icon_name_return */ +#endif +); + +extern void XGetInputFocus( +#if NeedFunctionPrototypes + Display* /* display */, + Window* /* focus_return */, + int* /* revert_to_return */ +#endif +); + +extern void XGetKeyboardControl( +#if NeedFunctionPrototypes + Display* /* display */, + XKeyboardState* /* values_return */ +#endif +); + +extern void XGetPointerControl( +#if NeedFunctionPrototypes + Display* /* display */, + int* /* accel_numerator_return */, + int* /* accel_denominator_return */, + int* /* threshold_return */ +#endif +); + +extern int XGetPointerMapping( +#if NeedFunctionPrototypes + Display* /* display */, + unsigned char* /* map_return */, + int /* nmap */ +#endif +); + +extern void XGetScreenSaver( +#if NeedFunctionPrototypes + Display* /* display */, + int* /* timeout_return */, + int* /* interval_return */, + int* /* prefer_blanking_return */, + int* /* allow_exposures_return */ +#endif +); + +extern Status XGetTransientForHint( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Window* /* prop_window_return */ +#endif +); + +extern int XGetWindowProperty( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Atom /* property */, + long /* long_offset */, + long /* long_length */, + Bool /* delete */, + Atom /* req_type */, + Atom* /* actual_type_return */, + int* /* actual_format_return */, + unsigned long* /* nitems_return */, + unsigned long* /* bytes_after_return */, + unsigned char** /* prop_return */ +#endif +); + +extern Status XGetWindowAttributes( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XWindowAttributes* /* window_attributes_return */ +#endif +); + +extern void XGrabButton( +#if NeedFunctionPrototypes + Display* /* display */, + unsigned int /* button */, + unsigned int /* modifiers */, + Window /* grab_window */, + Bool /* owner_events */, + unsigned int /* event_mask */, + int /* pointer_mode */, + int /* keyboard_mode */, + Window /* confine_to */, + Cursor /* cursor */ +#endif +); + +extern void XGrabKey( +#if NeedFunctionPrototypes + Display* /* display */, + int /* keycode */, + unsigned int /* modifiers */, + Window /* grab_window */, + Bool /* owner_events */, + int /* pointer_mode */, + int /* keyboard_mode */ +#endif +); + +extern int XGrabKeyboard( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* grab_window */, + Bool /* owner_events */, + int /* pointer_mode */, + int /* keyboard_mode */, + Time /* time */ +#endif +); + +extern int XGrabPointer( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* grab_window */, + Bool /* owner_events */, + unsigned int /* event_mask */, + int /* pointer_mode */, + int /* keyboard_mode */, + Window /* confine_to */, + Cursor /* cursor */, + Time /* time */ +#endif +); + +extern void XGrabServer( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern int XHeightMMOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern int XHeightOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern void XIfEvent( +#if NeedFunctionPrototypes + Display* /* display */, + XEvent* /* event_return */, + Bool (*) ( +#if NeedNestedPrototypes + Display* /* display */, + XEvent* /* event */, + XPointer /* arg */ +#endif + ) /* predicate */, + XPointer /* arg */ +#endif +); + +extern int XImageByteOrder( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XInstallColormap( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */ +#endif +); + +extern KeyCode XKeysymToKeycode( +#if NeedFunctionPrototypes + Display* /* display */, + KeySym /* keysym */ +#endif +); + +extern void XKillClient( +#if NeedFunctionPrototypes + Display* /* display */, + XID /* resource */ +#endif +); + +extern unsigned long XLastKnownRequestProcessed( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern Status XLookupColor( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + _Xconst char* /* color_name */, + XColor* /* exact_def_return */, + XColor* /* screen_def_return */ +#endif +); + +extern void XLowerWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XMapRaised( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XMapSubwindows( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XMapWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XMaskEvent( +#if NeedFunctionPrototypes + Display* /* display */, + long /* event_mask */, + XEvent* /* event_return */ +#endif +); + +extern int XMaxCmapsOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern int XMinCmapsOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern void XMoveResizeWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */ +#endif +); + +extern void XMoveWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + int /* x */, + int /* y */ +#endif +); + +extern void XNextEvent( +#if NeedFunctionPrototypes + Display* /* display */, + XEvent* /* event_return */ +#endif +); + +extern void XNoOp( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern Status XParseColor( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + _Xconst char* /* spec */, + XColor* /* exact_def_return */ +#endif +); + +extern int XParseGeometry( +#if NeedFunctionPrototypes + _Xconst char* /* parsestring */, + int* /* x_return */, + int* /* y_return */, + unsigned int* /* width_return */, + unsigned int* /* height_return */ +#endif +); + +extern void XPeekEvent( +#if NeedFunctionPrototypes + Display* /* display */, + XEvent* /* event_return */ +#endif +); + +extern void XPeekIfEvent( +#if NeedFunctionPrototypes + Display* /* display */, + XEvent* /* event_return */, + Bool (*) ( +#if NeedNestedPrototypes + Display* /* display */, + XEvent* /* event */, + XPointer /* arg */ +#endif + ) /* predicate */, + XPointer /* arg */ +#endif +); + +extern int XPending( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern int XPlanesOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ + +#endif +); + +extern int XProtocolRevision( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern int XProtocolVersion( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + + +extern void XPutBackEvent( +#if NeedFunctionPrototypes + Display* /* display */, + XEvent* /* event */ +#endif +); + +extern void XPutImage( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + XImage* /* image */, + int /* src_x */, + int /* src_y */, + int /* dest_x */, + int /* dest_y */, + unsigned int /* width */, + unsigned int /* height */ +#endif +); + +extern int XQLength( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern Status XQueryBestCursor( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + unsigned int /* width */, + unsigned int /* height */, + unsigned int* /* width_return */, + unsigned int* /* height_return */ +#endif +); + +extern Status XQueryBestSize( +#if NeedFunctionPrototypes + Display* /* display */, + int /* class */, + Drawable /* which_screen */, + unsigned int /* width */, + unsigned int /* height */, + unsigned int* /* width_return */, + unsigned int* /* height_return */ +#endif +); + +extern Status XQueryBestStipple( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* which_screen */, + unsigned int /* width */, + unsigned int /* height */, + unsigned int* /* width_return */, + unsigned int* /* height_return */ +#endif +); + +extern Status XQueryBestTile( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* which_screen */, + unsigned int /* width */, + unsigned int /* height */, + unsigned int* /* width_return */, + unsigned int* /* height_return */ +#endif +); + +extern void XQueryColor( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + XColor* /* def_in_out */ +#endif +); + +extern void XQueryColors( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + XColor* /* defs_in_out */, + int /* ncolors */ +#endif +); + +extern Bool XQueryExtension( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* name */, + int* /* major_opcode_return */, + int* /* first_event_return */, + int* /* first_error_return */ +#endif +); + +extern void XQueryKeymap( +#if NeedFunctionPrototypes + Display* /* display */, + char [32] /* keys_return */ +#endif +); + +extern Bool XQueryPointer( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Window* /* root_return */, + Window* /* child_return */, + int* /* root_x_return */, + int* /* root_y_return */, + int* /* win_x_return */, + int* /* win_y_return */, + unsigned int* /* mask_return */ +#endif +); + +extern void XQueryTextExtents( +#if NeedFunctionPrototypes + Display* /* display */, + XID /* font_ID */, + _Xconst char* /* string */, + int /* nchars */, + int* /* direction_return */, + int* /* font_ascent_return */, + int* /* font_descent_return */, + XCharStruct* /* overall_return */ +#endif +); + +extern void XQueryTextExtents16( +#if NeedFunctionPrototypes + Display* /* display */, + XID /* font_ID */, + _Xconst XChar2b* /* string */, + int /* nchars */, + int* /* direction_return */, + int* /* font_ascent_return */, + int* /* font_descent_return */, + XCharStruct* /* overall_return */ +#endif +); + +extern Status XQueryTree( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Window* /* root_return */, + Window* /* parent_return */, + Window** /* children_return */, + unsigned int* /* nchildren_return */ +#endif +); + +extern void XRaiseWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern int XReadBitmapFile( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + _Xconst char* /* filename */, + unsigned int* /* width_return */, + unsigned int* /* height_return */, + Pixmap* /* bitmap_return */, + int* /* x_hot_return */, + int* /* y_hot_return */ +#endif +); + +extern void XRebindKeysym( +#if NeedFunctionPrototypes + Display* /* display */, + KeySym /* keysym */, + KeySym* /* list */, + int /* mod_count */, + _Xconst unsigned char* /* string */, + int /* bytes_string */ +#endif +); + +extern void XRecolorCursor( +#if NeedFunctionPrototypes + Display* /* display */, + Cursor /* cursor */, + XColor* /* foreground_color */, + XColor* /* background_color */ +#endif +); + +extern void XRefreshKeyboardMapping( +#if NeedFunctionPrototypes + XMappingEvent* /* event_map */ +#endif +); + +extern void XRemoveFromSaveSet( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XRemoveHost( +#if NeedFunctionPrototypes + Display* /* display */, + XHostAddress* /* host */ +#endif +); + +extern void XRemoveHosts( +#if NeedFunctionPrototypes + Display* /* display */, + XHostAddress* /* hosts */, + int /* num_hosts */ +#endif +); + +extern void XReparentWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Window /* parent */, + int /* x */, + int /* y */ +#endif +); + +extern void XResetScreenSaver( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XResizeWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + unsigned int /* width */, + unsigned int /* height */ +#endif +); + +extern void XRestackWindows( +#if NeedFunctionPrototypes + Display* /* display */, + Window* /* windows */, + int /* nwindows */ +#endif +); + +extern void XRotateBuffers( +#if NeedFunctionPrototypes + Display* /* display */, + int /* rotate */ +#endif +); + +extern void XRotateWindowProperties( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Atom* /* properties */, + int /* num_prop */, + int /* npositions */ +#endif +); + +extern int XScreenCount( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XSelectInput( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + long /* event_mask */ +#endif +); + +extern Status XSendEvent( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Bool /* propagate */, + long /* event_mask */, + XEvent* /* event_send */ +#endif +); + +extern void XSetAccessControl( +#if NeedFunctionPrototypes + Display* /* display */, + int /* mode */ +#endif +); + +extern void XSetArcMode( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + int /* arc_mode */ +#endif +); + +extern void XSetBackground( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + unsigned long /* background */ +#endif +); + +extern void XSetClipMask( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + Pixmap /* pixmap */ +#endif +); + +extern void XSetClipOrigin( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + int /* clip_x_origin */, + int /* clip_y_origin */ +#endif +); + +extern void XSetClipRectangles( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + int /* clip_x_origin */, + int /* clip_y_origin */, + XRectangle* /* rectangles */, + int /* n */, + int /* ordering */ +#endif +); + +extern void XSetCloseDownMode( +#if NeedFunctionPrototypes + Display* /* display */, + int /* close_mode */ +#endif +); + +extern void XSetCommand( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + char** /* argv */, + int /* argc */ +#endif +); + +extern void XSetDashes( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + int /* dash_offset */, + _Xconst char* /* dash_list */, + int /* n */ +#endif +); + +extern void XSetFillRule( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + int /* fill_rule */ +#endif +); + +extern void XSetFillStyle( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + int /* fill_style */ +#endif +); + +extern void XSetFont( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + Font /* font */ +#endif +); + +extern void XSetFontPath( +#if NeedFunctionPrototypes + Display* /* display */, + char** /* directories */, + int /* ndirs */ +#endif +); + +extern void XSetForeground( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + unsigned long /* foreground */ +#endif +); + +extern void XSetFunction( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + int /* function */ +#endif +); + +extern void XSetGraphicsExposures( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + Bool /* graphics_exposures */ +#endif +); + +extern void XSetIconName( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + _Xconst char* /* icon_name */ +#endif +); + +extern void XSetInputFocus( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* focus */, + int /* revert_to */, + Time /* time */ +#endif +); + +extern void XSetLineAttributes( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + unsigned int /* line_width */, + int /* line_style */, + int /* cap_style */, + int /* join_style */ +#endif +); + +extern int XSetModifierMapping( +#if NeedFunctionPrototypes + Display* /* display */, + XModifierKeymap* /* modmap */ +#endif +); + +extern void XSetPlaneMask( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + unsigned long /* plane_mask */ +#endif +); + +extern int XSetPointerMapping( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst unsigned char* /* map */, + int /* nmap */ +#endif +); + +extern void XSetScreenSaver( +#if NeedFunctionPrototypes + Display* /* display */, + int /* timeout */, + int /* interval */, + int /* prefer_blanking */, + int /* allow_exposures */ +#endif +); + +extern void XSetSelectionOwner( +#if NeedFunctionPrototypes + Display* /* display */, + Atom /* selection */, + Window /* owner */, + Time /* time */ +#endif +); + +extern void XSetState( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + unsigned long /* foreground */, + unsigned long /* background */, + int /* function */, + unsigned long /* plane_mask */ +#endif +); + +extern void XSetStipple( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + Pixmap /* stipple */ +#endif +); + +extern void XSetSubwindowMode( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + int /* subwindow_mode */ +#endif +); + +extern void XSetTSOrigin( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + int /* ts_x_origin */, + int /* ts_y_origin */ +#endif +); + +extern void XSetTile( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + Pixmap /* tile */ +#endif +); + +extern void XSetWindowBackground( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + unsigned long /* background_pixel */ +#endif +); + +extern void XSetWindowBackgroundPixmap( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Pixmap /* background_pixmap */ +#endif +); + +extern void XSetWindowBorder( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + unsigned long /* border_pixel */ +#endif +); + +extern void XSetWindowBorderPixmap( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Pixmap /* border_pixmap */ +#endif +); + +extern void XSetWindowBorderWidth( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + unsigned int /* width */ +#endif +); + +extern void XSetWindowColormap( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + Colormap /* colormap */ +#endif +); + +extern void XStoreBuffer( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* bytes */, + int /* nbytes */, + int /* buffer */ +#endif +); + +extern void XStoreBytes( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* bytes */, + int /* nbytes */ +#endif +); + +extern void XStoreColor( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + XColor* /* color */ +#endif +); + +extern void XStoreColors( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + XColor* /* color */, + int /* ncolors */ +#endif +); + +extern void XStoreName( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + _Xconst char* /* window_name */ +#endif +); + +extern void XStoreNamedColor( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */, + _Xconst char* /* color */, + unsigned long /* pixel */, + int /* flags */ +#endif +); + +extern void XSync( +#if NeedFunctionPrototypes + Display* /* display */, + Bool /* discard */ +#endif +); + +extern void XTextExtents( +#if NeedFunctionPrototypes + XFontStruct* /* font_struct */, + _Xconst char* /* string */, + int /* nchars */, + int* /* direction_return */, + int* /* font_ascent_return */, + int* /* font_descent_return */, + XCharStruct* /* overall_return */ +#endif +); + +extern void XTextExtents16( +#if NeedFunctionPrototypes + XFontStruct* /* font_struct */, + _Xconst XChar2b* /* string */, + int /* nchars */, + int* /* direction_return */, + int* /* font_ascent_return */, + int* /* font_descent_return */, + XCharStruct* /* overall_return */ +#endif +); + +extern int XTextWidth( +#if NeedFunctionPrototypes + XFontStruct* /* font_struct */, + _Xconst char* /* string */, + int /* count */ +#endif +); + +extern int XTextWidth16( +#if NeedFunctionPrototypes + XFontStruct* /* font_struct */, + _Xconst XChar2b* /* string */, + int /* count */ +#endif +); + +extern Bool XTranslateCoordinates( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* src_w */, + Window /* dest_w */, + int /* src_x */, + int /* src_y */, + int* /* dest_x_return */, + int* /* dest_y_return */, + Window* /* child_return */ +#endif +); + +extern void XUndefineCursor( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XUngrabButton( +#if NeedFunctionPrototypes + Display* /* display */, + unsigned int /* button */, + unsigned int /* modifiers */, + Window /* grab_window */ +#endif +); + +extern void XUngrabKey( +#if NeedFunctionPrototypes + Display* /* display */, + int /* keycode */, + unsigned int /* modifiers */, + Window /* grab_window */ +#endif +); + +extern void XUngrabKeyboard( +#if NeedFunctionPrototypes + Display* /* display */, + Time /* time */ +#endif +); + +extern void XUngrabPointer( +#if NeedFunctionPrototypes + Display* /* display */, + Time /* time */ +#endif +); + +extern void XUngrabServer( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XUninstallColormap( +#if NeedFunctionPrototypes + Display* /* display */, + Colormap /* colormap */ +#endif +); + +extern void XUnloadFont( +#if NeedFunctionPrototypes + Display* /* display */, + Font /* font */ +#endif +); + +extern void XUnmapSubwindows( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern void XUnmapWindow( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern int XVendorRelease( +#if NeedFunctionPrototypes + Display* /* display */ +#endif +); + +extern void XWarpPointer( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* src_w */, + Window /* dest_w */, + int /* src_x */, + int /* src_y */, + unsigned int /* src_width */, + unsigned int /* src_height */, + int /* dest_x */, + int /* dest_y */ +#endif +); + +extern int XWidthMMOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern int XWidthOfScreen( +#if NeedFunctionPrototypes + Screen* /* screen */ +#endif +); + +extern void XWindowEvent( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + long /* event_mask */, + XEvent* /* event_return */ +#endif +); + +extern int XWriteBitmapFile( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* filename */, + Pixmap /* bitmap */, + unsigned int /* width */, + unsigned int /* height */, + int /* x_hot */, + int /* y_hot */ +#endif +); + +extern Bool XSupportsLocale( +#if NeedFunctionPrototypes + void +#endif +); + +extern char *XSetLocaleModifiers( +#if NeedFunctionPrototypes + _Xconst char* /* modifier_list */ +#endif +); + +extern XFontSet XCreateFontSet( +#if NeedFunctionPrototypes + Display* /* display */, + _Xconst char* /* base_font_name_list */, + char*** /* missing_charset_list */, + int* /* missing_charset_count */, + char** /* def_string */ +#endif +); + +extern void XFreeFontSet( +#if NeedFunctionPrototypes + Display* /* display */, + XFontSet /* font_set */ +#endif +); + +extern int XFontsOfFontSet( +#if NeedFunctionPrototypes + XFontSet /* font_set */, + XFontStruct*** /* font_struct_list */, + char*** /* font_name_list */ +#endif +); + +extern char *XBaseFontNameListOfFontSet( +#if NeedFunctionPrototypes + XFontSet /* font_set */ +#endif +); + +extern char *XLocaleOfFontSet( +#if NeedFunctionPrototypes + XFontSet /* font_set */ +#endif +); + +extern Bool XContextDependentDrawing( +#if NeedFunctionPrototypes + XFontSet /* font_set */ +#endif +); + +extern XFontSetExtents *XExtentsOfFontSet( +#if NeedFunctionPrototypes + XFontSet /* font_set */ +#endif +); + +extern int XmbTextEscapement( +#if NeedFunctionPrototypes + XFontSet /* font_set */, + _Xconst char* /* text */, + int /* bytes_text */ +#endif +); + +extern int XwcTextEscapement( +#if NeedFunctionPrototypes + XFontSet /* font_set */, + wchar_t* /* text */, + int /* num_wchars */ +#endif +); + +extern int XmbTextExtents( +#if NeedFunctionPrototypes + XFontSet /* font_set */, + _Xconst char* /* text */, + int /* bytes_text */, + XRectangle* /* overall_ink_return */, + XRectangle* /* overall_logical_return */ +#endif +); + +extern int XwcTextExtents( +#if NeedFunctionPrototypes + XFontSet /* font_set */, + wchar_t* /* text */, + int /* num_wchars */, + XRectangle* /* overall_ink_return */, + XRectangle* /* overall_logical_return */ +#endif +); + +extern Status XmbTextPerCharExtents( +#if NeedFunctionPrototypes + XFontSet /* font_set */, + _Xconst char* /* text */, + int /* bytes_text */, + XRectangle* /* ink_extents_buffer */, + XRectangle* /* logical_extents_buffer */, + int /* buffer_size */, + int* /* num_chars */, + XRectangle* /* overall_ink_return */, + XRectangle* /* overall_logical_return */ +#endif +); + +extern Status XwcTextPerCharExtents( +#if NeedFunctionPrototypes + XFontSet /* font_set */, + wchar_t* /* text */, + int /* num_wchars */, + XRectangle* /* ink_extents_buffer */, + XRectangle* /* logical_extents_buffer */, + int /* buffer_size */, + int* /* num_chars */, + XRectangle* /* overall_ink_return */, + XRectangle* /* overall_logical_return */ +#endif +); + +extern void XmbDrawText( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + XmbTextItem* /* text_items */, + int /* nitems */ +#endif +); + +extern void XwcDrawText( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + GC /* gc */, + int /* x */, + int /* y */, + XwcTextItem* /* text_items */, + int /* nitems */ +#endif +); + +extern void XmbDrawString( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + XFontSet /* font_set */, + GC /* gc */, + int /* x */, + int /* y */, + _Xconst char* /* text */, + int /* bytes_text */ +#endif +); + +extern void XwcDrawString( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + XFontSet /* font_set */, + GC /* gc */, + int /* x */, + int /* y */, + wchar_t* /* text */, + int /* num_wchars */ +#endif +); + +extern void XmbDrawImageString( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + XFontSet /* font_set */, + GC /* gc */, + int /* x */, + int /* y */, + _Xconst char* /* text */, + int /* bytes_text */ +#endif +); + +extern void XwcDrawImageString( +#if NeedFunctionPrototypes + Display* /* display */, + Drawable /* d */, + XFontSet /* font_set */, + GC /* gc */, + int /* x */, + int /* y */, + wchar_t* /* text */, + int /* num_wchars */ +#endif +); + +extern XIM XOpenIM( +#if NeedFunctionPrototypes + Display* /* dpy */, + struct _XrmHashBucketRec* /* rdb */, + char* /* res_name */, + char* /* res_class */ +#endif +); + +extern Status XCloseIM( +#if NeedFunctionPrototypes + XIM /* im */ +#endif +); + +extern char *XGetIMValues( +#if NeedVarargsPrototypes + XIM /* im */, ... +#endif +); + +extern Display *XDisplayOfIM( +#if NeedFunctionPrototypes + XIM /* im */ +#endif +); + +extern char *XLocaleOfIM( +#if NeedFunctionPrototypes + XIM /* im*/ +#endif +); + +extern XIC XCreateIC( +#if NeedVarargsPrototypes + XIM /* im */, ... +#endif +); + +extern void XDestroyIC( +#if NeedFunctionPrototypes + XIC /* ic */ +#endif +); + +extern void XSetICFocus( +#if NeedFunctionPrototypes + XIC /* ic */ +#endif +); + +extern void XUnsetICFocus( +#if NeedFunctionPrototypes + XIC /* ic */ +#endif +); + +extern wchar_t *XwcResetIC( +#if NeedFunctionPrototypes + XIC /* ic */ +#endif +); + +extern char *XmbResetIC( +#if NeedFunctionPrototypes + XIC /* ic */ +#endif +); + +extern char *XSetICValues( +#if NeedVarargsPrototypes + XIC /* ic */, ... +#endif +); + +extern char *XGetICValues( +#if NeedVarargsPrototypes + XIC /* ic */, ... +#endif +); + +extern XIM XIMOfIC( +#if NeedFunctionPrototypes + XIC /* ic */ +#endif +); + +extern Bool XFilterEvent( +#if NeedFunctionPrototypes + XEvent* /* event */, + Window /* window */ +#endif +); + +extern int XmbLookupString( +#if NeedFunctionPrototypes + XIC /* ic */, + XKeyPressedEvent* /* event */, + char* /* buffer_return */, + int /* bytes_buffer */, + KeySym* /* keysym_return */, + Status* /* status_return */ +#endif +); + +extern int XwcLookupString( +#if NeedFunctionPrototypes + XIC /* ic */, + XKeyPressedEvent* /* event */, + wchar_t* /* buffer_return */, + int /* wchars_buffer */, + KeySym* /* keysym_return */, + Status* /* status_return */ +#endif +); + +extern XVaNestedList XVaCreateNestedList( +#if NeedVarargsPrototypes + int /*unused*/, ... +#endif +); + +_XFUNCPROTOEND + +#ifdef MAC_TCL +# undef Cursor +# undef Region +#endif + +#endif /* _XLIB_H_ */ diff --git a/xlib/X11/Xutil.h b/xlib/X11/Xutil.h new file mode 100644 index 0000000..6332850 --- /dev/null +++ b/xlib/X11/Xutil.h @@ -0,0 +1,879 @@ +/* $XConsortium: Xutil.h,v 11.73 91/07/30 16:21:37 rws Exp $ */ + +/*********************************************************** +Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts, +and the Massachusetts Institute of Technology, Cambridge, Massachusetts. + + All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the names of Digital or MIT not be +used in advertising or publicity pertaining to distribution of the +software without specific, written prior permission. + +DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL +DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +******************************************************************/ + +#ifndef _XUTIL_H_ +#define _XUTIL_H_ + +/* You must include <X11/Xlib.h> before including this file */ + +#ifdef MAC_TCL +# define Region XRegion +#endif + +/* + * Bitmask returned by XParseGeometry(). Each bit tells if the corresponding + * value (x, y, width, height) was found in the parsed string. + */ +#define NoValue 0x0000 +#define XValue 0x0001 +#define YValue 0x0002 +#define WidthValue 0x0004 +#define HeightValue 0x0008 +#define AllValues 0x000F +#define XNegative 0x0010 +#define YNegative 0x0020 + +/* + * new version containing base_width, base_height, and win_gravity fields; + * used with WM_NORMAL_HINTS. + */ +typedef struct { + long flags; /* marks which fields in this structure are defined */ + int x, y; /* obsolete for new window mgrs, but clients */ + int width, height; /* should set so old wm's don't mess up */ + int min_width, min_height; + int max_width, max_height; + int width_inc, height_inc; + struct { + int x; /* numerator */ + int y; /* denominator */ + } min_aspect, max_aspect; + int base_width, base_height; /* added by ICCCM version 1 */ + int win_gravity; /* added by ICCCM version 1 */ +} XSizeHints; + +/* + * The next block of definitions are for window manager properties that + * clients and applications use for communication. + */ + +/* flags argument in size hints */ +#define USPosition (1L << 0) /* user specified x, y */ +#define USSize (1L << 1) /* user specified width, height */ + +#define PPosition (1L << 2) /* program specified position */ +#define PSize (1L << 3) /* program specified size */ +#define PMinSize (1L << 4) /* program specified minimum size */ +#define PMaxSize (1L << 5) /* program specified maximum size */ +#define PResizeInc (1L << 6) /* program specified resize increments */ +#define PAspect (1L << 7) /* program specified min and max aspect ratios */ +#define PBaseSize (1L << 8) /* program specified base for incrementing */ +#define PWinGravity (1L << 9) /* program specified window gravity */ + +/* obsolete */ +#define PAllHints (PPosition|PSize|PMinSize|PMaxSize|PResizeInc|PAspect) + + + +typedef struct { + long flags; /* marks which fields in this structure are defined */ + Bool input; /* does this application rely on the window manager to + get keyboard input? */ + int initial_state; /* see below */ + Pixmap icon_pixmap; /* pixmap to be used as icon */ + Window icon_window; /* window to be used as icon */ + int icon_x, icon_y; /* initial position of icon */ + Pixmap icon_mask; /* icon mask bitmap */ + XID window_group; /* id of related window group */ + /* this structure may be extended in the future */ +} XWMHints; + +/* definition for flags of XWMHints */ + +#define InputHint (1L << 0) +#define StateHint (1L << 1) +#define IconPixmapHint (1L << 2) +#define IconWindowHint (1L << 3) +#define IconPositionHint (1L << 4) +#define IconMaskHint (1L << 5) +#define WindowGroupHint (1L << 6) +#define AllHints (InputHint|StateHint|IconPixmapHint|IconWindowHint| \ +IconPositionHint|IconMaskHint|WindowGroupHint) + +/* definitions for initial window state */ +#define WithdrawnState 0 /* for windows that are not mapped */ +#define NormalState 1 /* most applications want to start this way */ +#define IconicState 3 /* application wants to start as an icon */ + +/* + * Obsolete states no longer defined by ICCCM + */ +#define DontCareState 0 /* don't know or care */ +#define ZoomState 2 /* application wants to start zoomed */ +#define InactiveState 4 /* application believes it is seldom used; */ + /* some wm's may put it on inactive menu */ + + +/* + * new structure for manipulating TEXT properties; used with WM_NAME, + * WM_ICON_NAME, WM_CLIENT_MACHINE, and WM_COMMAND. + */ +typedef struct { + unsigned char *value; /* same as Property routines */ + Atom encoding; /* prop type */ + int format; /* prop data format: 8, 16, or 32 */ + unsigned long nitems; /* number of data items in value */ +} XTextProperty; + +#define XNoMemory -1 +#define XLocaleNotSupported -2 +#define XConverterNotFound -3 + +typedef enum { + XStringStyle, /* STRING */ + XCompoundTextStyle, /* COMPOUND_TEXT */ + XTextStyle, /* text in owner's encoding (current locale)*/ + XStdICCTextStyle /* STRING, else COMPOUND_TEXT */ +} XICCEncodingStyle; + +typedef struct { + int min_width, min_height; + int max_width, max_height; + int width_inc, height_inc; +} XIconSize; + +typedef struct { + char *res_name; + char *res_class; +} XClassHint; + +/* + * These macros are used to give some sugar to the image routines so that + * naive people are more comfortable with them. + */ +#define XDestroyImage(ximage) \ + ((*((ximage)->f.destroy_image))((ximage))) +#define XGetPixel(ximage, x, y) \ + ((*((ximage)->f.get_pixel))((ximage), (x), (y))) +#define XPutPixel(ximage, x, y, pixel) \ + ((*((ximage)->f.put_pixel))((ximage), (x), (y), (pixel))) +#define XSubImage(ximage, x, y, width, height) \ + ((*((ximage)->f.sub_image))((ximage), (x), (y), (width), (height))) +#define XAddPixel(ximage, value) \ + ((*((ximage)->f.add_pixel))((ximage), (value))) + +/* + * Compose sequence status structure, used in calling XLookupString. + */ +typedef struct _XComposeStatus { + XPointer compose_ptr; /* state table pointer */ + int chars_matched; /* match state */ +} XComposeStatus; + +/* + * Keysym macros, used on Keysyms to test for classes of symbols + */ +#define IsKeypadKey(keysym) \ + (((unsigned)(keysym) >= XK_KP_Space) && ((unsigned)(keysym) <= XK_KP_Equal)) + +#define IsCursorKey(keysym) \ + (((unsigned)(keysym) >= XK_Home) && ((unsigned)(keysym) < XK_Select)) + +#define IsPFKey(keysym) \ + (((unsigned)(keysym) >= XK_KP_F1) && ((unsigned)(keysym) <= XK_KP_F4)) + +#define IsFunctionKey(keysym) \ + (((unsigned)(keysym) >= XK_F1) && ((unsigned)(keysym) <= XK_F35)) + +#define IsMiscFunctionKey(keysym) \ + (((unsigned)(keysym) >= XK_Select) && ((unsigned)(keysym) <= XK_Break)) + +#define IsModifierKey(keysym) \ + ((((unsigned)(keysym) >= XK_Shift_L) && ((unsigned)(keysym) <= XK_Hyper_R)) \ + || ((unsigned)(keysym) == XK_Mode_switch) \ + || ((unsigned)(keysym) == XK_Num_Lock)) +/* + * opaque reference to Region data type + */ +typedef struct _XRegion *Region; + +/* Return values from XRectInRegion() */ + +#define RectangleOut 0 +#define RectangleIn 1 +#define RectanglePart 2 + + +/* + * Information used by the visual utility routines to find desired visual + * type from the many visuals a display may support. + */ + +typedef struct { + Visual *visual; + VisualID visualid; + int screen; + int depth; +#if defined(__cplusplus) || defined(c_plusplus) + int c_class; /* C++ */ +#else + int class; +#endif + unsigned long red_mask; + unsigned long green_mask; + unsigned long blue_mask; + int colormap_size; + int bits_per_rgb; +} XVisualInfo; + +#define VisualNoMask 0x0 +#define VisualIDMask 0x1 +#define VisualScreenMask 0x2 +#define VisualDepthMask 0x4 +#define VisualClassMask 0x8 +#define VisualRedMaskMask 0x10 +#define VisualGreenMaskMask 0x20 +#define VisualBlueMaskMask 0x40 +#define VisualColormapSizeMask 0x80 +#define VisualBitsPerRGBMask 0x100 +#define VisualAllMask 0x1FF + +/* + * This defines a window manager property that clients may use to + * share standard color maps of type RGB_COLOR_MAP: + */ +typedef struct { + Colormap colormap; + unsigned long red_max; + unsigned long red_mult; + unsigned long green_max; + unsigned long green_mult; + unsigned long blue_max; + unsigned long blue_mult; + unsigned long base_pixel; + VisualID visualid; /* added by ICCCM version 1 */ + XID killid; /* added by ICCCM version 1 */ +} XStandardColormap; + +#define ReleaseByFreeingColormap ((XID) 1L) /* for killid field above */ + + +/* + * return codes for XReadBitmapFile and XWriteBitmapFile + */ +#define BitmapSuccess 0 +#define BitmapOpenFailed 1 +#define BitmapFileInvalid 2 +#define BitmapNoMemory 3 + +/**************************************************************** + * + * Context Management + * + ****************************************************************/ + + +/* Associative lookup table return codes */ + +#define XCSUCCESS 0 /* No error. */ +#define XCNOMEM 1 /* Out of memory */ +#define XCNOENT 2 /* No entry in table */ + +typedef int XContext; + +#define XUniqueContext() ((XContext) XrmUniqueQuark()) +#define XStringToContext(string) ((XContext) XrmStringToQuark(string)) + +_XFUNCPROTOBEGIN + +/* The following declarations are alphabetized. */ + +extern XClassHint *XAllocClassHint ( +#if NeedFunctionPrototypes + void +#endif +); + +extern XIconSize *XAllocIconSize ( +#if NeedFunctionPrototypes + void +#endif +); + +extern XSizeHints *XAllocSizeHints ( +#if NeedFunctionPrototypes + void +#endif +); + +extern XStandardColormap *XAllocStandardColormap ( +#if NeedFunctionPrototypes + void +#endif +); + +extern XWMHints *XAllocWMHints ( +#if NeedFunctionPrototypes + void +#endif +); + +extern void XClipBox( +#if NeedFunctionPrototypes + Region /* r */, + XRectangle* /* rect_return */ +#endif +); + +extern Region XCreateRegion( +#if NeedFunctionPrototypes + void +#endif +); + +extern char *XDefaultString( +#if NeedFunctionPrototypes + void +#endif +); + +extern int XDeleteContext( +#if NeedFunctionPrototypes + Display* /* display */, + XID /* rid */, + XContext /* context */ +#endif +); + +extern void XDestroyRegion( +#if NeedFunctionPrototypes + Region /* r */ +#endif +); + +extern void XEmptyRegion( +#if NeedFunctionPrototypes + Region /* r */ +#endif +); + +extern void XEqualRegion( +#if NeedFunctionPrototypes + Region /* r1 */, + Region /* r2 */ +#endif +); + +extern int XFindContext( +#if NeedFunctionPrototypes + Display* /* display */, + XID /* rid */, + XContext /* context */, + XPointer* /* data_return */ +#endif +); + +extern Status XGetClassHint( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XClassHint* /* class_hints_return */ +#endif +); + +extern Status XGetIconSizes( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XIconSize** /* size_list_return */, + int* /* count_return */ +#endif +); + +extern Status XGetNormalHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XSizeHints* /* hints_return */ +#endif +); + +extern Status XGetRGBColormaps( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XStandardColormap** /* stdcmap_return */, + int* /* count_return */, + Atom /* property */ +#endif +); + +extern Status XGetSizeHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XSizeHints* /* hints_return */, + Atom /* property */ +#endif +); + +extern Status XGetStandardColormap( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XStandardColormap* /* colormap_return */, + Atom /* property */ +#endif +); + +extern Status XGetTextProperty( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* window */, + XTextProperty* /* text_prop_return */, + Atom /* property */ +#endif +); + +extern XVisualInfo *XGetVisualInfo( +#if NeedFunctionPrototypes + Display* /* display */, + long /* vinfo_mask */, + XVisualInfo* /* vinfo_template */, + int* /* nitems_return */ +#endif +); + +extern Status XGetWMClientMachine( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XTextProperty* /* text_prop_return */ +#endif +); + +extern XWMHints *XGetWMHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */ +#endif +); + +extern Status XGetWMIconName( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XTextProperty* /* text_prop_return */ +#endif +); + +extern Status XGetWMName( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XTextProperty* /* text_prop_return */ +#endif +); + +extern Status XGetWMNormalHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XSizeHints* /* hints_return */, + long* /* supplied_return */ +#endif +); + +extern Status XGetWMSizeHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XSizeHints* /* hints_return */, + long* /* supplied_return */, + Atom /* property */ +#endif +); + +extern Status XGetZoomHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XSizeHints* /* zhints_return */ +#endif +); + +extern void XIntersectRegion( +#if NeedFunctionPrototypes + Region /* sra */, + Region /* srb */, + Region /* dr_return */ +#endif +); + +extern int XLookupString( +#if NeedFunctionPrototypes + XKeyEvent* /* event_struct */, + char* /* buffer_return */, + int /* bytes_buffer */, + KeySym* /* keysym_return */, + XComposeStatus* /* status_in_out */ +#endif +); + +extern Status XMatchVisualInfo( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen */, + int /* depth */, + int /* class */, + XVisualInfo* /* vinfo_return */ +#endif +); + +extern void XOffsetRegion( +#if NeedFunctionPrototypes + Region /* r */, + int /* dx */, + int /* dy */ +#endif +); + +extern Bool XPointInRegion( +#if NeedFunctionPrototypes + Region /* r */, + int /* x */, + int /* y */ +#endif +); + +extern Region XPolygonRegion( +#if NeedFunctionPrototypes + XPoint* /* points */, + int /* n */, + int /* fill_rule */ +#endif +); + +extern int XRectInRegion( +#if NeedFunctionPrototypes + Region /* r */, + int /* x */, + int /* y */, + unsigned int /* width */, + unsigned int /* height */ +#endif +); + +extern int XSaveContext( +#if NeedFunctionPrototypes + Display* /* display */, + XID /* rid */, + XContext /* context */, + _Xconst char* /* data */ +#endif +); + +extern void XSetClassHint( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XClassHint* /* class_hints */ +#endif +); + +extern void XSetIconSizes( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XIconSize* /* size_list */, + int /* count */ +#endif +); + +extern void XSetNormalHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XSizeHints* /* hints */ +#endif +); + +extern void XSetRGBColormaps( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XStandardColormap* /* stdcmaps */, + int /* count */, + Atom /* property */ +#endif +); + +extern void XSetSizeHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XSizeHints* /* hints */, + Atom /* property */ +#endif +); + +extern void XSetStandardProperties( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + _Xconst char* /* window_name */, + _Xconst char* /* icon_name */, + Pixmap /* icon_pixmap */, + char** /* argv */, + int /* argc */, + XSizeHints* /* hints */ +#endif +); + +extern void XSetTextProperty( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XTextProperty* /* text_prop */, + Atom /* property */ +#endif +); + +extern void XSetWMClientMachine( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XTextProperty* /* text_prop */ +#endif +); + +extern void XSetWMHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XWMHints* /* wm_hints */ +#endif +); + +extern void XSetWMIconName( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XTextProperty* /* text_prop */ +#endif +); + +extern void XSetWMName( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XTextProperty* /* text_prop */ +#endif +); + +extern void XSetWMNormalHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XSizeHints* /* hints */ +#endif +); + +extern void XSetWMProperties( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XTextProperty* /* window_name */, + XTextProperty* /* icon_name */, + char** /* argv */, + int /* argc */, + XSizeHints* /* normal_hints */, + XWMHints* /* wm_hints */, + XClassHint* /* class_hints */ +#endif +); + +extern void XmbSetWMProperties( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + _Xconst char* /* window_name */, + _Xconst char* /* icon_name */, + char** /* argv */, + int /* argc */, + XSizeHints* /* normal_hints */, + XWMHints* /* wm_hints */, + XClassHint* /* class_hints */ +#endif +); + +extern void XSetWMSizeHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XSizeHints* /* hints */, + Atom /* property */ +#endif +); + +extern void XSetRegion( +#if NeedFunctionPrototypes + Display* /* display */, + GC /* gc */, + Region /* r */ +#endif +); + +extern void XSetStandardColormap( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XStandardColormap* /* colormap */, + Atom /* property */ +#endif +); + +extern void XSetZoomHints( +#if NeedFunctionPrototypes + Display* /* display */, + Window /* w */, + XSizeHints* /* zhints */ +#endif +); + +extern void XShrinkRegion( +#if NeedFunctionPrototypes + Region /* r */, + int /* dx */, + int /* dy */ +#endif +); + +extern Status XStringListToTextProperty( +#if NeedFunctionPrototypes + char** /* list */, + int /* count */, + XTextProperty* /* text_prop_return */ +#endif +); + +extern void XSubtractRegion( +#if NeedFunctionPrototypes + Region /* sra */, + Region /* srb */, + Region /* dr_return */ +#endif +); + +extern int XmbTextListToTextProperty( +#if NeedFunctionPrototypes + Display* /* display */, + char** /* list */, + int /* count */, + XICCEncodingStyle /* style */, + XTextProperty* /* text_prop_return */ +#endif +); + +extern int XwcTextListToTextProperty( +#if NeedFunctionPrototypes + Display* /* display */, + wchar_t** /* list */, + int /* count */, + XICCEncodingStyle /* style */, + XTextProperty* /* text_prop_return */ +#endif +); + +extern void XwcFreeStringList( +#if NeedFunctionPrototypes + wchar_t** /* list */ +#endif +); + +extern Status XTextPropertyToStringList( +#if NeedFunctionPrototypes + XTextProperty* /* text_prop */, + char*** /* list_return */, + int* /* count_return */ +#endif +); + +extern int XmbTextPropertyToTextList( +#if NeedFunctionPrototypes + Display* /* display */, + XTextProperty* /* text_prop */, + char*** /* list_return */, + int* /* count_return */ +#endif +); + +extern int XwcTextPropertyToTextList( +#if NeedFunctionPrototypes + Display* /* display */, + XTextProperty* /* text_prop */, + wchar_t*** /* list_return */, + int* /* count_return */ +#endif +); + +extern void XUnionRectWithRegion( +#if NeedFunctionPrototypes + XRectangle* /* rectangle */, + Region /* src_region */, + Region /* dest_region_return */ +#endif +); + +extern void XUnionRegion( +#if NeedFunctionPrototypes + Region /* sra */, + Region /* srb */, + Region /* dr_return */ +#endif +); + +extern int XWMGeometry( +#if NeedFunctionPrototypes + Display* /* display */, + int /* screen_number */, + _Xconst char* /* user_geometry */, + _Xconst char* /* default_geometry */, + unsigned int /* border_width */, + XSizeHints* /* hints */, + int* /* x_return */, + int* /* y_return */, + int* /* width_return */, + int* /* height_return */, + int* /* gravity_return */ +#endif +); + +extern void XXorRegion( +#if NeedFunctionPrototypes + Region /* sra */, + Region /* srb */, + Region /* dr_return */ +#endif +); + +_XFUNCPROTOEND + +#ifdef MAC_TCL +# undef Region +#endif + +#endif /* _XUTIL_H_ */ diff --git a/xlib/X11/cursorfont.h b/xlib/X11/cursorfont.h new file mode 100644 index 0000000..617274f --- /dev/null +++ b/xlib/X11/cursorfont.h @@ -0,0 +1,79 @@ +/* $XConsortium: cursorfont.h,v 1.2 88/09/06 16:44:27 jim Exp $ */ +#define XC_num_glyphs 154 +#define XC_X_cursor 0 +#define XC_arrow 2 +#define XC_based_arrow_down 4 +#define XC_based_arrow_up 6 +#define XC_boat 8 +#define XC_bogosity 10 +#define XC_bottom_left_corner 12 +#define XC_bottom_right_corner 14 +#define XC_bottom_side 16 +#define XC_bottom_tee 18 +#define XC_box_spiral 20 +#define XC_center_ptr 22 +#define XC_circle 24 +#define XC_clock 26 +#define XC_coffee_mug 28 +#define XC_cross 30 +#define XC_cross_reverse 32 +#define XC_crosshair 34 +#define XC_diamond_cross 36 +#define XC_dot 38 +#define XC_dotbox 40 +#define XC_double_arrow 42 +#define XC_draft_large 44 +#define XC_draft_small 46 +#define XC_draped_box 48 +#define XC_exchange 50 +#define XC_fleur 52 +#define XC_gobbler 54 +#define XC_gumby 56 +#define XC_hand1 58 +#define XC_hand2 60 +#define XC_heart 62 +#define XC_icon 64 +#define XC_iron_cross 66 +#define XC_left_ptr 68 +#define XC_left_side 70 +#define XC_left_tee 72 +#define XC_leftbutton 74 +#define XC_ll_angle 76 +#define XC_lr_angle 78 +#define XC_man 80 +#define XC_middlebutton 82 +#define XC_mouse 84 +#define XC_pencil 86 +#define XC_pirate 88 +#define XC_plus 90 +#define XC_question_arrow 92 +#define XC_right_ptr 94 +#define XC_right_side 96 +#define XC_right_tee 98 +#define XC_rightbutton 100 +#define XC_rtl_logo 102 +#define XC_sailboat 104 +#define XC_sb_down_arrow 106 +#define XC_sb_h_double_arrow 108 +#define XC_sb_left_arrow 110 +#define XC_sb_right_arrow 112 +#define XC_sb_up_arrow 114 +#define XC_sb_v_double_arrow 116 +#define XC_shuttle 118 +#define XC_sizing 120 +#define XC_spider 122 +#define XC_spraycan 124 +#define XC_star 126 +#define XC_target 128 +#define XC_tcross 130 +#define XC_top_left_arrow 132 +#define XC_top_left_corner 134 +#define XC_top_right_corner 136 +#define XC_top_side 138 +#define XC_top_tee 140 +#define XC_trek 142 +#define XC_ul_angle 144 +#define XC_umbrella 146 +#define XC_ur_angle 148 +#define XC_watch 150 +#define XC_xterm 152 diff --git a/xlib/X11/keysym.h b/xlib/X11/keysym.h new file mode 100644 index 0000000..027afe0 --- /dev/null +++ b/xlib/X11/keysym.h @@ -0,0 +1,39 @@ +/* $XConsortium: keysym.h,v 1.13 91/03/13 20:09:49 rws Exp $ */ + +/*********************************************************** +Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts, +and the Massachusetts Institute of Technology, Cambridge, Massachusetts. + + All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the names of Digital or MIT not be +used in advertising or publicity pertaining to distribution of the +software without specific, written prior permission. + +DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL +DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +******************************************************************/ + +/* default keysyms */ +#define XK_MISCELLANY +#define XK_LATIN1 +#define XK_LATIN2 +#define XK_LATIN3 +#define XK_LATIN4 +#define XK_GREEK + +#ifdef MAC_TCL +#include <keysymdef.h> +#else +#include <X11/keysymdef.h> +#endif diff --git a/xlib/X11/keysymdef.h b/xlib/X11/keysymdef.h new file mode 100644 index 0000000..2c6d4a7 --- /dev/null +++ b/xlib/X11/keysymdef.h @@ -0,0 +1,1164 @@ +/* $XConsortium: keysymdef.h,v 1.15 93/04/02 10:57:36 rws Exp $ */ + +/*********************************************************** +Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts, +and the Massachusetts Institute of Technology, Cambridge, Massachusetts. + + All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the names of Digital or MIT not be +used in advertising or publicity pertaining to distribution of the +software without specific, written prior permission. + +DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL +DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +******************************************************************/ + +#define XK_VoidSymbol 0xFFFFFF /* void symbol */ + +#ifdef XK_MISCELLANY +/* + * TTY Functions, cleverly chosen to map to ascii, for convenience of + * programming, but could have been arbitrary (at the cost of lookup + * tables in client code. + */ + +#define XK_BackSpace 0xFF08 /* back space, back char */ +#define XK_Tab 0xFF09 +#define XK_Linefeed 0xFF0A /* Linefeed, LF */ +#define XK_Clear 0xFF0B +#define XK_Return 0xFF0D /* Return, enter */ +#define XK_Pause 0xFF13 /* Pause, hold */ +#define XK_Scroll_Lock 0xFF14 +#define XK_Sys_Req 0xFF15 +#define XK_Escape 0xFF1B +#define XK_Delete 0xFFFF /* Delete, rubout */ + + + +/* International & multi-key character composition */ + +#define XK_Multi_key 0xFF20 /* Multi-key character compose */ + +/* Japanese keyboard support */ + +#define XK_Kanji 0xFF21 /* Kanji, Kanji convert */ +#define XK_Muhenkan 0xFF22 /* Cancel Conversion */ +#define XK_Henkan_Mode 0xFF23 /* Start/Stop Conversion */ +#define XK_Henkan 0xFF23 /* Alias for Henkan_Mode */ +#define XK_Romaji 0xFF24 /* to Romaji */ +#define XK_Hiragana 0xFF25 /* to Hiragana */ +#define XK_Katakana 0xFF26 /* to Katakana */ +#define XK_Hiragana_Katakana 0xFF27 /* Hiragana/Katakana toggle */ +#define XK_Zenkaku 0xFF28 /* to Zenkaku */ +#define XK_Hankaku 0xFF29 /* to Hankaku */ +#define XK_Zenkaku_Hankaku 0xFF2A /* Zenkaku/Hankaku toggle */ +#define XK_Touroku 0xFF2B /* Add to Dictionary */ +#define XK_Massyo 0xFF2C /* Delete from Dictionary */ +#define XK_Kana_Lock 0xFF2D /* Kana Lock */ +#define XK_Kana_Shift 0xFF2E /* Kana Shift */ +#define XK_Eisu_Shift 0xFF2F /* Alphanumeric Shift */ +#define XK_Eisu_toggle 0xFF30 /* Alphanumeric toggle */ + +/* Cursor control & motion */ + +#define XK_Home 0xFF50 +#define XK_Left 0xFF51 /* Move left, left arrow */ +#define XK_Up 0xFF52 /* Move up, up arrow */ +#define XK_Right 0xFF53 /* Move right, right arrow */ +#define XK_Down 0xFF54 /* Move down, down arrow */ +#define XK_Prior 0xFF55 /* Prior, previous */ +#define XK_Page_Up 0xFF55 +#define XK_Next 0xFF56 /* Next */ +#define XK_Page_Down 0xFF56 +#define XK_End 0xFF57 /* EOL */ +#define XK_Begin 0xFF58 /* BOL */ + + +/* Misc Functions */ + +#define XK_Select 0xFF60 /* Select, mark */ +#define XK_Print 0xFF61 +#define XK_Execute 0xFF62 /* Execute, run, do */ +#define XK_Insert 0xFF63 /* Insert, insert here */ +#define XK_Undo 0xFF65 /* Undo, oops */ +#define XK_Redo 0xFF66 /* redo, again */ +#define XK_Menu 0xFF67 +#define XK_Find 0xFF68 /* Find, search */ +#define XK_Cancel 0xFF69 /* Cancel, stop, abort, exit */ +#define XK_Help 0xFF6A /* Help, ? */ +#define XK_Break 0xFF6B +#define XK_Mode_switch 0xFF7E /* Character set switch */ +#define XK_script_switch 0xFF7E /* Alias for mode_switch */ +#define XK_Num_Lock 0xFF7F + +/* Keypad Functions, keypad numbers cleverly chosen to map to ascii */ + +#define XK_KP_Space 0xFF80 /* space */ +#define XK_KP_Tab 0xFF89 +#define XK_KP_Enter 0xFF8D /* enter */ +#define XK_KP_F1 0xFF91 /* PF1, KP_A, ... */ +#define XK_KP_F2 0xFF92 +#define XK_KP_F3 0xFF93 +#define XK_KP_F4 0xFF94 +#define XK_KP_Home 0xFF95 +#define XK_KP_Left 0xFF96 +#define XK_KP_Up 0xFF97 +#define XK_KP_Right 0xFF98 +#define XK_KP_Down 0xFF99 +#define XK_KP_Prior 0xFF9A +#define XK_KP_Page_Up 0xFF9A +#define XK_KP_Next 0xFF9B +#define XK_KP_Page_Down 0xFF9B +#define XK_KP_End 0xFF9C +#define XK_KP_Begin 0xFF9D +#define XK_KP_Insert 0xFF9E +#define XK_KP_Delete 0xFF9F +#define XK_KP_Equal 0xFFBD /* equals */ +#define XK_KP_Multiply 0xFFAA +#define XK_KP_Add 0xFFAB +#define XK_KP_Separator 0xFFAC /* separator, often comma */ +#define XK_KP_Subtract 0xFFAD +#define XK_KP_Decimal 0xFFAE +#define XK_KP_Divide 0xFFAF + +#define XK_KP_0 0xFFB0 +#define XK_KP_1 0xFFB1 +#define XK_KP_2 0xFFB2 +#define XK_KP_3 0xFFB3 +#define XK_KP_4 0xFFB4 +#define XK_KP_5 0xFFB5 +#define XK_KP_6 0xFFB6 +#define XK_KP_7 0xFFB7 +#define XK_KP_8 0xFFB8 +#define XK_KP_9 0xFFB9 + + + +/* + * Auxilliary Functions; note the duplicate definitions for left and right + * function keys; Sun keyboards and a few other manufactures have such + * function key groups on the left and/or right sides of the keyboard. + * We've not found a keyboard with more than 35 function keys total. + */ + +#define XK_F1 0xFFBE +#define XK_F2 0xFFBF +#define XK_F3 0xFFC0 +#define XK_F4 0xFFC1 +#define XK_F5 0xFFC2 +#define XK_F6 0xFFC3 +#define XK_F7 0xFFC4 +#define XK_F8 0xFFC5 +#define XK_F9 0xFFC6 +#define XK_F10 0xFFC7 +#define XK_F11 0xFFC8 +#define XK_L1 0xFFC8 +#define XK_F12 0xFFC9 +#define XK_L2 0xFFC9 +#define XK_F13 0xFFCA +#define XK_L3 0xFFCA +#define XK_F14 0xFFCB +#define XK_L4 0xFFCB +#define XK_F15 0xFFCC +#define XK_L5 0xFFCC +#define XK_F16 0xFFCD +#define XK_L6 0xFFCD +#define XK_F17 0xFFCE +#define XK_L7 0xFFCE +#define XK_F18 0xFFCF +#define XK_L8 0xFFCF +#define XK_F19 0xFFD0 +#define XK_L9 0xFFD0 +#define XK_F20 0xFFD1 +#define XK_L10 0xFFD1 +#define XK_F21 0xFFD2 +#define XK_R1 0xFFD2 +#define XK_F22 0xFFD3 +#define XK_R2 0xFFD3 +#define XK_F23 0xFFD4 +#define XK_R3 0xFFD4 +#define XK_F24 0xFFD5 +#define XK_R4 0xFFD5 +#define XK_F25 0xFFD6 +#define XK_R5 0xFFD6 +#define XK_F26 0xFFD7 +#define XK_R6 0xFFD7 +#define XK_F27 0xFFD8 +#define XK_R7 0xFFD8 +#define XK_F28 0xFFD9 +#define XK_R8 0xFFD9 +#define XK_F29 0xFFDA +#define XK_R9 0xFFDA +#define XK_F30 0xFFDB +#define XK_R10 0xFFDB +#define XK_F31 0xFFDC +#define XK_R11 0xFFDC +#define XK_F32 0xFFDD +#define XK_R12 0xFFDD +#define XK_F33 0xFFDE +#define XK_R13 0xFFDE +#define XK_F34 0xFFDF +#define XK_R14 0xFFDF +#define XK_F35 0xFFE0 +#define XK_R15 0xFFE0 + +/* Modifiers */ + +#define XK_Shift_L 0xFFE1 /* Left shift */ +#define XK_Shift_R 0xFFE2 /* Right shift */ +#define XK_Control_L 0xFFE3 /* Left control */ +#define XK_Control_R 0xFFE4 /* Right control */ +#define XK_Caps_Lock 0xFFE5 /* Caps lock */ +#define XK_Shift_Lock 0xFFE6 /* Shift lock */ + +#define XK_Meta_L 0xFFE7 /* Left meta */ +#define XK_Meta_R 0xFFE8 /* Right meta */ +#define XK_Alt_L 0xFFE9 /* Left alt */ +#define XK_Alt_R 0xFFEA /* Right alt */ +#define XK_Super_L 0xFFEB /* Left super */ +#define XK_Super_R 0xFFEC /* Right super */ +#define XK_Hyper_L 0xFFED /* Left hyper */ +#define XK_Hyper_R 0xFFEE /* Right hyper */ +#endif /* XK_MISCELLANY */ + +/* + * Latin 1 + * Byte 3 = 0 + */ +#ifdef XK_LATIN1 +#define XK_space 0x020 +#define XK_exclam 0x021 +#define XK_quotedbl 0x022 +#define XK_numbersign 0x023 +#define XK_dollar 0x024 +#define XK_percent 0x025 +#define XK_ampersand 0x026 +#define XK_apostrophe 0x027 +#define XK_quoteright 0x027 /* deprecated */ +#define XK_parenleft 0x028 +#define XK_parenright 0x029 +#define XK_asterisk 0x02a +#define XK_plus 0x02b +#define XK_comma 0x02c +#define XK_minus 0x02d +#define XK_period 0x02e +#define XK_slash 0x02f +#define XK_0 0x030 +#define XK_1 0x031 +#define XK_2 0x032 +#define XK_3 0x033 +#define XK_4 0x034 +#define XK_5 0x035 +#define XK_6 0x036 +#define XK_7 0x037 +#define XK_8 0x038 +#define XK_9 0x039 +#define XK_colon 0x03a +#define XK_semicolon 0x03b +#define XK_less 0x03c +#define XK_equal 0x03d +#define XK_greater 0x03e +#define XK_question 0x03f +#define XK_at 0x040 +#define XK_A 0x041 +#define XK_B 0x042 +#define XK_C 0x043 +#define XK_D 0x044 +#define XK_E 0x045 +#define XK_F 0x046 +#define XK_G 0x047 +#define XK_H 0x048 +#define XK_I 0x049 +#define XK_J 0x04a +#define XK_K 0x04b +#define XK_L 0x04c +#define XK_M 0x04d +#define XK_N 0x04e +#define XK_O 0x04f +#define XK_P 0x050 +#define XK_Q 0x051 +#define XK_R 0x052 +#define XK_S 0x053 +#define XK_T 0x054 +#define XK_U 0x055 +#define XK_V 0x056 +#define XK_W 0x057 +#define XK_X 0x058 +#define XK_Y 0x059 +#define XK_Z 0x05a +#define XK_bracketleft 0x05b +#define XK_backslash 0x05c +#define XK_bracketright 0x05d +#define XK_asciicircum 0x05e +#define XK_underscore 0x05f +#define XK_grave 0x060 +#define XK_quoteleft 0x060 /* deprecated */ +#define XK_a 0x061 +#define XK_b 0x062 +#define XK_c 0x063 +#define XK_d 0x064 +#define XK_e 0x065 +#define XK_f 0x066 +#define XK_g 0x067 +#define XK_h 0x068 +#define XK_i 0x069 +#define XK_j 0x06a +#define XK_k 0x06b +#define XK_l 0x06c +#define XK_m 0x06d +#define XK_n 0x06e +#define XK_o 0x06f +#define XK_p 0x070 +#define XK_q 0x071 +#define XK_r 0x072 +#define XK_s 0x073 +#define XK_t 0x074 +#define XK_u 0x075 +#define XK_v 0x076 +#define XK_w 0x077 +#define XK_x 0x078 +#define XK_y 0x079 +#define XK_z 0x07a +#define XK_braceleft 0x07b +#define XK_bar 0x07c +#define XK_braceright 0x07d +#define XK_asciitilde 0x07e + +#define XK_nobreakspace 0x0a0 +#define XK_exclamdown 0x0a1 +#define XK_cent 0x0a2 +#define XK_sterling 0x0a3 +#define XK_currency 0x0a4 +#define XK_yen 0x0a5 +#define XK_brokenbar 0x0a6 +#define XK_section 0x0a7 +#define XK_diaeresis 0x0a8 +#define XK_copyright 0x0a9 +#define XK_ordfeminine 0x0aa +#define XK_guillemotleft 0x0ab /* left angle quotation mark */ +#define XK_notsign 0x0ac +#define XK_hyphen 0x0ad +#define XK_registered 0x0ae +#define XK_macron 0x0af +#define XK_degree 0x0b0 +#define XK_plusminus 0x0b1 +#define XK_twosuperior 0x0b2 +#define XK_threesuperior 0x0b3 +#define XK_acute 0x0b4 +#define XK_mu 0x0b5 +#define XK_paragraph 0x0b6 +#define XK_periodcentered 0x0b7 +#define XK_cedilla 0x0b8 +#define XK_onesuperior 0x0b9 +#define XK_masculine 0x0ba +#define XK_guillemotright 0x0bb /* right angle quotation mark */ +#define XK_onequarter 0x0bc +#define XK_onehalf 0x0bd +#define XK_threequarters 0x0be +#define XK_questiondown 0x0bf +#define XK_Agrave 0x0c0 +#define XK_Aacute 0x0c1 +#define XK_Acircumflex 0x0c2 +#define XK_Atilde 0x0c3 +#define XK_Adiaeresis 0x0c4 +#define XK_Aring 0x0c5 +#define XK_AE 0x0c6 +#define XK_Ccedilla 0x0c7 +#define XK_Egrave 0x0c8 +#define XK_Eacute 0x0c9 +#define XK_Ecircumflex 0x0ca +#define XK_Ediaeresis 0x0cb +#define XK_Igrave 0x0cc +#define XK_Iacute 0x0cd +#define XK_Icircumflex 0x0ce +#define XK_Idiaeresis 0x0cf +#define XK_ETH 0x0d0 +#define XK_Eth 0x0d0 /* deprecated */ +#define XK_Ntilde 0x0d1 +#define XK_Ograve 0x0d2 +#define XK_Oacute 0x0d3 +#define XK_Ocircumflex 0x0d4 +#define XK_Otilde 0x0d5 +#define XK_Odiaeresis 0x0d6 +#define XK_multiply 0x0d7 +#define XK_Ooblique 0x0d8 +#define XK_Ugrave 0x0d9 +#define XK_Uacute 0x0da +#define XK_Ucircumflex 0x0db +#define XK_Udiaeresis 0x0dc +#define XK_Yacute 0x0dd +#define XK_THORN 0x0de +#define XK_Thorn 0x0de /* deprecated */ +#define XK_ssharp 0x0df +#define XK_agrave 0x0e0 +#define XK_aacute 0x0e1 +#define XK_acircumflex 0x0e2 +#define XK_atilde 0x0e3 +#define XK_adiaeresis 0x0e4 +#define XK_aring 0x0e5 +#define XK_ae 0x0e6 +#define XK_ccedilla 0x0e7 +#define XK_egrave 0x0e8 +#define XK_eacute 0x0e9 +#define XK_ecircumflex 0x0ea +#define XK_ediaeresis 0x0eb +#define XK_igrave 0x0ec +#define XK_iacute 0x0ed +#define XK_icircumflex 0x0ee +#define XK_idiaeresis 0x0ef +#define XK_eth 0x0f0 +#define XK_ntilde 0x0f1 +#define XK_ograve 0x0f2 +#define XK_oacute 0x0f3 +#define XK_ocircumflex 0x0f4 +#define XK_otilde 0x0f5 +#define XK_odiaeresis 0x0f6 +#define XK_division 0x0f7 +#define XK_oslash 0x0f8 +#define XK_ugrave 0x0f9 +#define XK_uacute 0x0fa +#define XK_ucircumflex 0x0fb +#define XK_udiaeresis 0x0fc +#define XK_yacute 0x0fd +#define XK_thorn 0x0fe +#define XK_ydiaeresis 0x0ff +#endif /* XK_LATIN1 */ + +/* + * Latin 2 + * Byte 3 = 1 + */ + +#ifdef XK_LATIN2 +#define XK_Aogonek 0x1a1 +#define XK_breve 0x1a2 +#define XK_Lstroke 0x1a3 +#define XK_Lcaron 0x1a5 +#define XK_Sacute 0x1a6 +#define XK_Scaron 0x1a9 +#define XK_Scedilla 0x1aa +#define XK_Tcaron 0x1ab +#define XK_Zacute 0x1ac +#define XK_Zcaron 0x1ae +#define XK_Zabovedot 0x1af +#define XK_aogonek 0x1b1 +#define XK_ogonek 0x1b2 +#define XK_lstroke 0x1b3 +#define XK_lcaron 0x1b5 +#define XK_sacute 0x1b6 +#define XK_caron 0x1b7 +#define XK_scaron 0x1b9 +#define XK_scedilla 0x1ba +#define XK_tcaron 0x1bb +#define XK_zacute 0x1bc +#define XK_doubleacute 0x1bd +#define XK_zcaron 0x1be +#define XK_zabovedot 0x1bf +#define XK_Racute 0x1c0 +#define XK_Abreve 0x1c3 +#define XK_Lacute 0x1c5 +#define XK_Cacute 0x1c6 +#define XK_Ccaron 0x1c8 +#define XK_Eogonek 0x1ca +#define XK_Ecaron 0x1cc +#define XK_Dcaron 0x1cf +#define XK_Dstroke 0x1d0 +#define XK_Nacute 0x1d1 +#define XK_Ncaron 0x1d2 +#define XK_Odoubleacute 0x1d5 +#define XK_Rcaron 0x1d8 +#define XK_Uring 0x1d9 +#define XK_Udoubleacute 0x1db +#define XK_Tcedilla 0x1de +#define XK_racute 0x1e0 +#define XK_abreve 0x1e3 +#define XK_lacute 0x1e5 +#define XK_cacute 0x1e6 +#define XK_ccaron 0x1e8 +#define XK_eogonek 0x1ea +#define XK_ecaron 0x1ec +#define XK_dcaron 0x1ef +#define XK_dstroke 0x1f0 +#define XK_nacute 0x1f1 +#define XK_ncaron 0x1f2 +#define XK_odoubleacute 0x1f5 +#define XK_udoubleacute 0x1fb +#define XK_rcaron 0x1f8 +#define XK_uring 0x1f9 +#define XK_tcedilla 0x1fe +#define XK_abovedot 0x1ff +#endif /* XK_LATIN2 */ + +/* + * Latin 3 + * Byte 3 = 2 + */ + +#ifdef XK_LATIN3 +#define XK_Hstroke 0x2a1 +#define XK_Hcircumflex 0x2a6 +#define XK_Iabovedot 0x2a9 +#define XK_Gbreve 0x2ab +#define XK_Jcircumflex 0x2ac +#define XK_hstroke 0x2b1 +#define XK_hcircumflex 0x2b6 +#define XK_idotless 0x2b9 +#define XK_gbreve 0x2bb +#define XK_jcircumflex 0x2bc +#define XK_Cabovedot 0x2c5 +#define XK_Ccircumflex 0x2c6 +#define XK_Gabovedot 0x2d5 +#define XK_Gcircumflex 0x2d8 +#define XK_Ubreve 0x2dd +#define XK_Scircumflex 0x2de +#define XK_cabovedot 0x2e5 +#define XK_ccircumflex 0x2e6 +#define XK_gabovedot 0x2f5 +#define XK_gcircumflex 0x2f8 +#define XK_ubreve 0x2fd +#define XK_scircumflex 0x2fe +#endif /* XK_LATIN3 */ + + +/* + * Latin 4 + * Byte 3 = 3 + */ + +#ifdef XK_LATIN4 +#define XK_kra 0x3a2 +#define XK_kappa 0x3a2 /* deprecated */ +#define XK_Rcedilla 0x3a3 +#define XK_Itilde 0x3a5 +#define XK_Lcedilla 0x3a6 +#define XK_Emacron 0x3aa +#define XK_Gcedilla 0x3ab +#define XK_Tslash 0x3ac +#define XK_rcedilla 0x3b3 +#define XK_itilde 0x3b5 +#define XK_lcedilla 0x3b6 +#define XK_emacron 0x3ba +#define XK_gcedilla 0x3bb +#define XK_tslash 0x3bc +#define XK_ENG 0x3bd +#define XK_eng 0x3bf +#define XK_Amacron 0x3c0 +#define XK_Iogonek 0x3c7 +#define XK_Eabovedot 0x3cc +#define XK_Imacron 0x3cf +#define XK_Ncedilla 0x3d1 +#define XK_Omacron 0x3d2 +#define XK_Kcedilla 0x3d3 +#define XK_Uogonek 0x3d9 +#define XK_Utilde 0x3dd +#define XK_Umacron 0x3de +#define XK_amacron 0x3e0 +#define XK_iogonek 0x3e7 +#define XK_eabovedot 0x3ec +#define XK_imacron 0x3ef +#define XK_ncedilla 0x3f1 +#define XK_omacron 0x3f2 +#define XK_kcedilla 0x3f3 +#define XK_uogonek 0x3f9 +#define XK_utilde 0x3fd +#define XK_umacron 0x3fe +#endif /* XK_LATIN4 */ + +/* + * Katakana + * Byte 3 = 4 + */ + +#ifdef XK_KATAKANA +#define XK_overline 0x47e +#define XK_kana_fullstop 0x4a1 +#define XK_kana_openingbracket 0x4a2 +#define XK_kana_closingbracket 0x4a3 +#define XK_kana_comma 0x4a4 +#define XK_kana_conjunctive 0x4a5 +#define XK_kana_middledot 0x4a5 /* deprecated */ +#define XK_kana_WO 0x4a6 +#define XK_kana_a 0x4a7 +#define XK_kana_i 0x4a8 +#define XK_kana_u 0x4a9 +#define XK_kana_e 0x4aa +#define XK_kana_o 0x4ab +#define XK_kana_ya 0x4ac +#define XK_kana_yu 0x4ad +#define XK_kana_yo 0x4ae +#define XK_kana_tsu 0x4af +#define XK_kana_tu 0x4af /* deprecated */ +#define XK_prolongedsound 0x4b0 +#define XK_kana_A 0x4b1 +#define XK_kana_I 0x4b2 +#define XK_kana_U 0x4b3 +#define XK_kana_E 0x4b4 +#define XK_kana_O 0x4b5 +#define XK_kana_KA 0x4b6 +#define XK_kana_KI 0x4b7 +#define XK_kana_KU 0x4b8 +#define XK_kana_KE 0x4b9 +#define XK_kana_KO 0x4ba +#define XK_kana_SA 0x4bb +#define XK_kana_SHI 0x4bc +#define XK_kana_SU 0x4bd +#define XK_kana_SE 0x4be +#define XK_kana_SO 0x4bf +#define XK_kana_TA 0x4c0 +#define XK_kana_CHI 0x4c1 +#define XK_kana_TI 0x4c1 /* deprecated */ +#define XK_kana_TSU 0x4c2 +#define XK_kana_TU 0x4c2 /* deprecated */ +#define XK_kana_TE 0x4c3 +#define XK_kana_TO 0x4c4 +#define XK_kana_NA 0x4c5 +#define XK_kana_NI 0x4c6 +#define XK_kana_NU 0x4c7 +#define XK_kana_NE 0x4c8 +#define XK_kana_NO 0x4c9 +#define XK_kana_HA 0x4ca +#define XK_kana_HI 0x4cb +#define XK_kana_FU 0x4cc +#define XK_kana_HU 0x4cc /* deprecated */ +#define XK_kana_HE 0x4cd +#define XK_kana_HO 0x4ce +#define XK_kana_MA 0x4cf +#define XK_kana_MI 0x4d0 +#define XK_kana_MU 0x4d1 +#define XK_kana_ME 0x4d2 +#define XK_kana_MO 0x4d3 +#define XK_kana_YA 0x4d4 +#define XK_kana_YU 0x4d5 +#define XK_kana_YO 0x4d6 +#define XK_kana_RA 0x4d7 +#define XK_kana_RI 0x4d8 +#define XK_kana_RU 0x4d9 +#define XK_kana_RE 0x4da +#define XK_kana_RO 0x4db +#define XK_kana_WA 0x4dc +#define XK_kana_N 0x4dd +#define XK_voicedsound 0x4de +#define XK_semivoicedsound 0x4df +#define XK_kana_switch 0xFF7E /* Alias for mode_switch */ +#endif /* XK_KATAKANA */ + +/* + * Arabic + * Byte 3 = 5 + */ + +#ifdef XK_ARABIC +#define XK_Arabic_comma 0x5ac +#define XK_Arabic_semicolon 0x5bb +#define XK_Arabic_question_mark 0x5bf +#define XK_Arabic_hamza 0x5c1 +#define XK_Arabic_maddaonalef 0x5c2 +#define XK_Arabic_hamzaonalef 0x5c3 +#define XK_Arabic_hamzaonwaw 0x5c4 +#define XK_Arabic_hamzaunderalef 0x5c5 +#define XK_Arabic_hamzaonyeh 0x5c6 +#define XK_Arabic_alef 0x5c7 +#define XK_Arabic_beh 0x5c8 +#define XK_Arabic_tehmarbuta 0x5c9 +#define XK_Arabic_teh 0x5ca +#define XK_Arabic_theh 0x5cb +#define XK_Arabic_jeem 0x5cc +#define XK_Arabic_hah 0x5cd +#define XK_Arabic_khah 0x5ce +#define XK_Arabic_dal 0x5cf +#define XK_Arabic_thal 0x5d0 +#define XK_Arabic_ra 0x5d1 +#define XK_Arabic_zain 0x5d2 +#define XK_Arabic_seen 0x5d3 +#define XK_Arabic_sheen 0x5d4 +#define XK_Arabic_sad 0x5d5 +#define XK_Arabic_dad 0x5d6 +#define XK_Arabic_tah 0x5d7 +#define XK_Arabic_zah 0x5d8 +#define XK_Arabic_ain 0x5d9 +#define XK_Arabic_ghain 0x5da +#define XK_Arabic_tatweel 0x5e0 +#define XK_Arabic_feh 0x5e1 +#define XK_Arabic_qaf 0x5e2 +#define XK_Arabic_kaf 0x5e3 +#define XK_Arabic_lam 0x5e4 +#define XK_Arabic_meem 0x5e5 +#define XK_Arabic_noon 0x5e6 +#define XK_Arabic_ha 0x5e7 +#define XK_Arabic_heh 0x5e7 /* deprecated */ +#define XK_Arabic_waw 0x5e8 +#define XK_Arabic_alefmaksura 0x5e9 +#define XK_Arabic_yeh 0x5ea +#define XK_Arabic_fathatan 0x5eb +#define XK_Arabic_dammatan 0x5ec +#define XK_Arabic_kasratan 0x5ed +#define XK_Arabic_fatha 0x5ee +#define XK_Arabic_damma 0x5ef +#define XK_Arabic_kasra 0x5f0 +#define XK_Arabic_shadda 0x5f1 +#define XK_Arabic_sukun 0x5f2 +#define XK_Arabic_switch 0xFF7E /* Alias for mode_switch */ +#endif /* XK_ARABIC */ + +/* + * Cyrillic + * Byte 3 = 6 + */ +#ifdef XK_CYRILLIC +#define XK_Serbian_dje 0x6a1 +#define XK_Macedonia_gje 0x6a2 +#define XK_Cyrillic_io 0x6a3 +#define XK_Ukrainian_ie 0x6a4 +#define XK_Ukranian_je 0x6a4 /* deprecated */ +#define XK_Macedonia_dse 0x6a5 +#define XK_Ukrainian_i 0x6a6 +#define XK_Ukranian_i 0x6a6 /* deprecated */ +#define XK_Ukrainian_yi 0x6a7 +#define XK_Ukranian_yi 0x6a7 /* deprecated */ +#define XK_Cyrillic_je 0x6a8 +#define XK_Serbian_je 0x6a8 /* deprecated */ +#define XK_Cyrillic_lje 0x6a9 +#define XK_Serbian_lje 0x6a9 /* deprecated */ +#define XK_Cyrillic_nje 0x6aa +#define XK_Serbian_nje 0x6aa /* deprecated */ +#define XK_Serbian_tshe 0x6ab +#define XK_Macedonia_kje 0x6ac +#define XK_Byelorussian_shortu 0x6ae +#define XK_Cyrillic_dzhe 0x6af +#define XK_Serbian_dze 0x6af /* deprecated */ +#define XK_numerosign 0x6b0 +#define XK_Serbian_DJE 0x6b1 +#define XK_Macedonia_GJE 0x6b2 +#define XK_Cyrillic_IO 0x6b3 +#define XK_Ukrainian_IE 0x6b4 +#define XK_Ukranian_JE 0x6b4 /* deprecated */ +#define XK_Macedonia_DSE 0x6b5 +#define XK_Ukrainian_I 0x6b6 +#define XK_Ukranian_I 0x6b6 /* deprecated */ +#define XK_Ukrainian_YI 0x6b7 +#define XK_Ukranian_YI 0x6b7 /* deprecated */ +#define XK_Cyrillic_JE 0x6b8 +#define XK_Serbian_JE 0x6b8 /* deprecated */ +#define XK_Cyrillic_LJE 0x6b9 +#define XK_Serbian_LJE 0x6b9 /* deprecated */ +#define XK_Cyrillic_NJE 0x6ba +#define XK_Serbian_NJE 0x6ba /* deprecated */ +#define XK_Serbian_TSHE 0x6bb +#define XK_Macedonia_KJE 0x6bc +#define XK_Byelorussian_SHORTU 0x6be +#define XK_Cyrillic_DZHE 0x6bf +#define XK_Serbian_DZE 0x6bf /* deprecated */ +#define XK_Cyrillic_yu 0x6c0 +#define XK_Cyrillic_a 0x6c1 +#define XK_Cyrillic_be 0x6c2 +#define XK_Cyrillic_tse 0x6c3 +#define XK_Cyrillic_de 0x6c4 +#define XK_Cyrillic_ie 0x6c5 +#define XK_Cyrillic_ef 0x6c6 +#define XK_Cyrillic_ghe 0x6c7 +#define XK_Cyrillic_ha 0x6c8 +#define XK_Cyrillic_i 0x6c9 +#define XK_Cyrillic_shorti 0x6ca +#define XK_Cyrillic_ka 0x6cb +#define XK_Cyrillic_el 0x6cc +#define XK_Cyrillic_em 0x6cd +#define XK_Cyrillic_en 0x6ce +#define XK_Cyrillic_o 0x6cf +#define XK_Cyrillic_pe 0x6d0 +#define XK_Cyrillic_ya 0x6d1 +#define XK_Cyrillic_er 0x6d2 +#define XK_Cyrillic_es 0x6d3 +#define XK_Cyrillic_te 0x6d4 +#define XK_Cyrillic_u 0x6d5 +#define XK_Cyrillic_zhe 0x6d6 +#define XK_Cyrillic_ve 0x6d7 +#define XK_Cyrillic_softsign 0x6d8 +#define XK_Cyrillic_yeru 0x6d9 +#define XK_Cyrillic_ze 0x6da +#define XK_Cyrillic_sha 0x6db +#define XK_Cyrillic_e 0x6dc +#define XK_Cyrillic_shcha 0x6dd +#define XK_Cyrillic_che 0x6de +#define XK_Cyrillic_hardsign 0x6df +#define XK_Cyrillic_YU 0x6e0 +#define XK_Cyrillic_A 0x6e1 +#define XK_Cyrillic_BE 0x6e2 +#define XK_Cyrillic_TSE 0x6e3 +#define XK_Cyrillic_DE 0x6e4 +#define XK_Cyrillic_IE 0x6e5 +#define XK_Cyrillic_EF 0x6e6 +#define XK_Cyrillic_GHE 0x6e7 +#define XK_Cyrillic_HA 0x6e8 +#define XK_Cyrillic_I 0x6e9 +#define XK_Cyrillic_SHORTI 0x6ea +#define XK_Cyrillic_KA 0x6eb +#define XK_Cyrillic_EL 0x6ec +#define XK_Cyrillic_EM 0x6ed +#define XK_Cyrillic_EN 0x6ee +#define XK_Cyrillic_O 0x6ef +#define XK_Cyrillic_PE 0x6f0 +#define XK_Cyrillic_YA 0x6f1 +#define XK_Cyrillic_ER 0x6f2 +#define XK_Cyrillic_ES 0x6f3 +#define XK_Cyrillic_TE 0x6f4 +#define XK_Cyrillic_U 0x6f5 +#define XK_Cyrillic_ZHE 0x6f6 +#define XK_Cyrillic_VE 0x6f7 +#define XK_Cyrillic_SOFTSIGN 0x6f8 +#define XK_Cyrillic_YERU 0x6f9 +#define XK_Cyrillic_ZE 0x6fa +#define XK_Cyrillic_SHA 0x6fb +#define XK_Cyrillic_E 0x6fc +#define XK_Cyrillic_SHCHA 0x6fd +#define XK_Cyrillic_CHE 0x6fe +#define XK_Cyrillic_HARDSIGN 0x6ff +#endif /* XK_CYRILLIC */ + +/* + * Greek + * Byte 3 = 7 + */ + +#ifdef XK_GREEK +#define XK_Greek_ALPHAaccent 0x7a1 +#define XK_Greek_EPSILONaccent 0x7a2 +#define XK_Greek_ETAaccent 0x7a3 +#define XK_Greek_IOTAaccent 0x7a4 +#define XK_Greek_IOTAdiaeresis 0x7a5 +#define XK_Greek_OMICRONaccent 0x7a7 +#define XK_Greek_UPSILONaccent 0x7a8 +#define XK_Greek_UPSILONdieresis 0x7a9 +#define XK_Greek_OMEGAaccent 0x7ab +#define XK_Greek_accentdieresis 0x7ae +#define XK_Greek_horizbar 0x7af +#define XK_Greek_alphaaccent 0x7b1 +#define XK_Greek_epsilonaccent 0x7b2 +#define XK_Greek_etaaccent 0x7b3 +#define XK_Greek_iotaaccent 0x7b4 +#define XK_Greek_iotadieresis 0x7b5 +#define XK_Greek_iotaaccentdieresis 0x7b6 +#define XK_Greek_omicronaccent 0x7b7 +#define XK_Greek_upsilonaccent 0x7b8 +#define XK_Greek_upsilondieresis 0x7b9 +#define XK_Greek_upsilonaccentdieresis 0x7ba +#define XK_Greek_omegaaccent 0x7bb +#define XK_Greek_ALPHA 0x7c1 +#define XK_Greek_BETA 0x7c2 +#define XK_Greek_GAMMA 0x7c3 +#define XK_Greek_DELTA 0x7c4 +#define XK_Greek_EPSILON 0x7c5 +#define XK_Greek_ZETA 0x7c6 +#define XK_Greek_ETA 0x7c7 +#define XK_Greek_THETA 0x7c8 +#define XK_Greek_IOTA 0x7c9 +#define XK_Greek_KAPPA 0x7ca +#define XK_Greek_LAMDA 0x7cb +#define XK_Greek_LAMBDA 0x7cb +#define XK_Greek_MU 0x7cc +#define XK_Greek_NU 0x7cd +#define XK_Greek_XI 0x7ce +#define XK_Greek_OMICRON 0x7cf +#define XK_Greek_PI 0x7d0 +#define XK_Greek_RHO 0x7d1 +#define XK_Greek_SIGMA 0x7d2 +#define XK_Greek_TAU 0x7d4 +#define XK_Greek_UPSILON 0x7d5 +#define XK_Greek_PHI 0x7d6 +#define XK_Greek_CHI 0x7d7 +#define XK_Greek_PSI 0x7d8 +#define XK_Greek_OMEGA 0x7d9 +#define XK_Greek_alpha 0x7e1 +#define XK_Greek_beta 0x7e2 +#define XK_Greek_gamma 0x7e3 +#define XK_Greek_delta 0x7e4 +#define XK_Greek_epsilon 0x7e5 +#define XK_Greek_zeta 0x7e6 +#define XK_Greek_eta 0x7e7 +#define XK_Greek_theta 0x7e8 +#define XK_Greek_iota 0x7e9 +#define XK_Greek_kappa 0x7ea +#define XK_Greek_lamda 0x7eb +#define XK_Greek_lambda 0x7eb +#define XK_Greek_mu 0x7ec +#define XK_Greek_nu 0x7ed +#define XK_Greek_xi 0x7ee +#define XK_Greek_omicron 0x7ef +#define XK_Greek_pi 0x7f0 +#define XK_Greek_rho 0x7f1 +#define XK_Greek_sigma 0x7f2 +#define XK_Greek_finalsmallsigma 0x7f3 +#define XK_Greek_tau 0x7f4 +#define XK_Greek_upsilon 0x7f5 +#define XK_Greek_phi 0x7f6 +#define XK_Greek_chi 0x7f7 +#define XK_Greek_psi 0x7f8 +#define XK_Greek_omega 0x7f9 +#define XK_Greek_switch 0xFF7E /* Alias for mode_switch */ +#endif /* XK_GREEK */ + +/* + * Technical + * Byte 3 = 8 + */ + +#ifdef XK_TECHNICAL +#define XK_leftradical 0x8a1 +#define XK_topleftradical 0x8a2 +#define XK_horizconnector 0x8a3 +#define XK_topintegral 0x8a4 +#define XK_botintegral 0x8a5 +#define XK_vertconnector 0x8a6 +#define XK_topleftsqbracket 0x8a7 +#define XK_botleftsqbracket 0x8a8 +#define XK_toprightsqbracket 0x8a9 +#define XK_botrightsqbracket 0x8aa +#define XK_topleftparens 0x8ab +#define XK_botleftparens 0x8ac +#define XK_toprightparens 0x8ad +#define XK_botrightparens 0x8ae +#define XK_leftmiddlecurlybrace 0x8af +#define XK_rightmiddlecurlybrace 0x8b0 +#define XK_topleftsummation 0x8b1 +#define XK_botleftsummation 0x8b2 +#define XK_topvertsummationconnector 0x8b3 +#define XK_botvertsummationconnector 0x8b4 +#define XK_toprightsummation 0x8b5 +#define XK_botrightsummation 0x8b6 +#define XK_rightmiddlesummation 0x8b7 +#define XK_lessthanequal 0x8bc +#define XK_notequal 0x8bd +#define XK_greaterthanequal 0x8be +#define XK_integral 0x8bf +#define XK_therefore 0x8c0 +#define XK_variation 0x8c1 +#define XK_infinity 0x8c2 +#define XK_nabla 0x8c5 +#define XK_approximate 0x8c8 +#define XK_similarequal 0x8c9 +#define XK_ifonlyif 0x8cd +#define XK_implies 0x8ce +#define XK_identical 0x8cf +#define XK_radical 0x8d6 +#define XK_includedin 0x8da +#define XK_includes 0x8db +#define XK_intersection 0x8dc +#define XK_union 0x8dd +#define XK_logicaland 0x8de +#define XK_logicalor 0x8df +#define XK_partialderivative 0x8ef +#define XK_function 0x8f6 +#define XK_leftarrow 0x8fb +#define XK_uparrow 0x8fc +#define XK_rightarrow 0x8fd +#define XK_downarrow 0x8fe +#endif /* XK_TECHNICAL */ + +/* + * Special + * Byte 3 = 9 + */ + +#ifdef XK_SPECIAL +#define XK_blank 0x9df +#define XK_soliddiamond 0x9e0 +#define XK_checkerboard 0x9e1 +#define XK_ht 0x9e2 +#define XK_ff 0x9e3 +#define XK_cr 0x9e4 +#define XK_lf 0x9e5 +#define XK_nl 0x9e8 +#define XK_vt 0x9e9 +#define XK_lowrightcorner 0x9ea +#define XK_uprightcorner 0x9eb +#define XK_upleftcorner 0x9ec +#define XK_lowleftcorner 0x9ed +#define XK_crossinglines 0x9ee +#define XK_horizlinescan1 0x9ef +#define XK_horizlinescan3 0x9f0 +#define XK_horizlinescan5 0x9f1 +#define XK_horizlinescan7 0x9f2 +#define XK_horizlinescan9 0x9f3 +#define XK_leftt 0x9f4 +#define XK_rightt 0x9f5 +#define XK_bott 0x9f6 +#define XK_topt 0x9f7 +#define XK_vertbar 0x9f8 +#endif /* XK_SPECIAL */ + +/* + * Publishing + * Byte 3 = a + */ + +#ifdef XK_PUBLISHING +#define XK_emspace 0xaa1 +#define XK_enspace 0xaa2 +#define XK_em3space 0xaa3 +#define XK_em4space 0xaa4 +#define XK_digitspace 0xaa5 +#define XK_punctspace 0xaa6 +#define XK_thinspace 0xaa7 +#define XK_hairspace 0xaa8 +#define XK_emdash 0xaa9 +#define XK_endash 0xaaa +#define XK_signifblank 0xaac +#define XK_ellipsis 0xaae +#define XK_doubbaselinedot 0xaaf +#define XK_onethird 0xab0 +#define XK_twothirds 0xab1 +#define XK_onefifth 0xab2 +#define XK_twofifths 0xab3 +#define XK_threefifths 0xab4 +#define XK_fourfifths 0xab5 +#define XK_onesixth 0xab6 +#define XK_fivesixths 0xab7 +#define XK_careof 0xab8 +#define XK_figdash 0xabb +#define XK_leftanglebracket 0xabc +#define XK_decimalpoint 0xabd +#define XK_rightanglebracket 0xabe +#define XK_marker 0xabf +#define XK_oneeighth 0xac3 +#define XK_threeeighths 0xac4 +#define XK_fiveeighths 0xac5 +#define XK_seveneighths 0xac6 +#define XK_trademark 0xac9 +#define XK_signaturemark 0xaca +#define XK_trademarkincircle 0xacb +#define XK_leftopentriangle 0xacc +#define XK_rightopentriangle 0xacd +#define XK_emopencircle 0xace +#define XK_emopenrectangle 0xacf +#define XK_leftsinglequotemark 0xad0 +#define XK_rightsinglequotemark 0xad1 +#define XK_leftdoublequotemark 0xad2 +#define XK_rightdoublequotemark 0xad3 +#define XK_prescription 0xad4 +#define XK_minutes 0xad6 +#define XK_seconds 0xad7 +#define XK_latincross 0xad9 +#define XK_hexagram 0xada +#define XK_filledrectbullet 0xadb +#define XK_filledlefttribullet 0xadc +#define XK_filledrighttribullet 0xadd +#define XK_emfilledcircle 0xade +#define XK_emfilledrect 0xadf +#define XK_enopencircbullet 0xae0 +#define XK_enopensquarebullet 0xae1 +#define XK_openrectbullet 0xae2 +#define XK_opentribulletup 0xae3 +#define XK_opentribulletdown 0xae4 +#define XK_openstar 0xae5 +#define XK_enfilledcircbullet 0xae6 +#define XK_enfilledsqbullet 0xae7 +#define XK_filledtribulletup 0xae8 +#define XK_filledtribulletdown 0xae9 +#define XK_leftpointer 0xaea +#define XK_rightpointer 0xaeb +#define XK_club 0xaec +#define XK_diamond 0xaed +#define XK_heart 0xaee +#define XK_maltesecross 0xaf0 +#define XK_dagger 0xaf1 +#define XK_doubledagger 0xaf2 +#define XK_checkmark 0xaf3 +#define XK_ballotcross 0xaf4 +#define XK_musicalsharp 0xaf5 +#define XK_musicalflat 0xaf6 +#define XK_malesymbol 0xaf7 +#define XK_femalesymbol 0xaf8 +#define XK_telephone 0xaf9 +#define XK_telephonerecorder 0xafa +#define XK_phonographcopyright 0xafb +#define XK_caret 0xafc +#define XK_singlelowquotemark 0xafd +#define XK_doublelowquotemark 0xafe +#define XK_cursor 0xaff +#endif /* XK_PUBLISHING */ + +/* + * APL + * Byte 3 = b + */ + +#ifdef XK_APL +#define XK_leftcaret 0xba3 +#define XK_rightcaret 0xba6 +#define XK_downcaret 0xba8 +#define XK_upcaret 0xba9 +#define XK_overbar 0xbc0 +#define XK_downtack 0xbc2 +#define XK_upshoe 0xbc3 +#define XK_downstile 0xbc4 +#define XK_underbar 0xbc6 +#define XK_jot 0xbca +#define XK_quad 0xbcc +#define XK_uptack 0xbce +#define XK_circle 0xbcf +#define XK_upstile 0xbd3 +#define XK_downshoe 0xbd6 +#define XK_rightshoe 0xbd8 +#define XK_leftshoe 0xbda +#define XK_lefttack 0xbdc +#define XK_righttack 0xbfc +#endif /* XK_APL */ + +/* + * Hebrew + * Byte 3 = c + */ + +#ifdef XK_HEBREW +#define XK_hebrew_doublelowline 0xcdf +#define XK_hebrew_aleph 0xce0 +#define XK_hebrew_bet 0xce1 +#define XK_hebrew_beth 0xce1 /* deprecated */ +#define XK_hebrew_gimel 0xce2 +#define XK_hebrew_gimmel 0xce2 /* deprecated */ +#define XK_hebrew_dalet 0xce3 +#define XK_hebrew_daleth 0xce3 /* deprecated */ +#define XK_hebrew_he 0xce4 +#define XK_hebrew_waw 0xce5 +#define XK_hebrew_zain 0xce6 +#define XK_hebrew_zayin 0xce6 /* deprecated */ +#define XK_hebrew_chet 0xce7 +#define XK_hebrew_het 0xce7 /* deprecated */ +#define XK_hebrew_tet 0xce8 +#define XK_hebrew_teth 0xce8 /* deprecated */ +#define XK_hebrew_yod 0xce9 +#define XK_hebrew_finalkaph 0xcea +#define XK_hebrew_kaph 0xceb +#define XK_hebrew_lamed 0xcec +#define XK_hebrew_finalmem 0xced +#define XK_hebrew_mem 0xcee +#define XK_hebrew_finalnun 0xcef +#define XK_hebrew_nun 0xcf0 +#define XK_hebrew_samech 0xcf1 +#define XK_hebrew_samekh 0xcf1 /* deprecated */ +#define XK_hebrew_ayin 0xcf2 +#define XK_hebrew_finalpe 0xcf3 +#define XK_hebrew_pe 0xcf4 +#define XK_hebrew_finalzade 0xcf5 +#define XK_hebrew_finalzadi 0xcf5 /* deprecated */ +#define XK_hebrew_zade 0xcf6 +#define XK_hebrew_zadi 0xcf6 /* deprecated */ +#define XK_hebrew_qoph 0xcf7 +#define XK_hebrew_kuf 0xcf7 /* deprecated */ +#define XK_hebrew_resh 0xcf8 +#define XK_hebrew_shin 0xcf9 +#define XK_hebrew_taw 0xcfa +#define XK_hebrew_taf 0xcfa /* deprecated */ +#define XK_Hebrew_switch 0xFF7E /* Alias for mode_switch */ +#endif /* XK_HEBREW */ + diff --git a/xlib/xbytes.h b/xlib/xbytes.h new file mode 100644 index 0000000..6cf3d56 --- /dev/null +++ b/xlib/xbytes.h @@ -0,0 +1,58 @@ +/* + * xbytes.h -- + * + * Declaration of table to reverse bit order of bytes. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) xbytes.h 1.1 95/05/09 17:32:51 + */ + +#ifndef _XBYTES +#define _XBYTES + +/* + * The bits in a byte can be reversed so the least significant becomes + * the most significant by indexing xBitReverseTable with the byte + * to be reversed. + */ + +static unsigned char xBitReverseTable[256] = { + 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, + 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, + 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, + 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, + 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, + 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, + 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, + 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, + 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, + 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, + 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, + 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, + 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, + 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, + 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, + 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, + 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, + 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, + 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, + 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, + 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, + 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, + 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, + 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, + 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, + 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, + 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, + 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, + 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, + 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, + 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, + 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff, +}; + +#endif /* _XBYTES */ diff --git a/xlib/xcolors.c b/xlib/xcolors.c new file mode 100644 index 0000000..800d688 --- /dev/null +++ b/xlib/xcolors.c @@ -0,0 +1,911 @@ +/* + * xcolors.c -- + * + * This file contains the routines used to map from X color + * names to RGB and pixel values. + * + * Copyright (c) 1996 by Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) xcolors.c 1.6 97/09/02 09:41:50 + */ + +#include <tkInt.h> + +/* + * Define an array that defines the mapping from color names to RGB values. + * Note that this array must be kept sorted alphabetically so that the + * binary search used in XParseColor will succeed. + */ + +typedef struct { + char *name; + unsigned char red; + unsigned char green; + unsigned char blue; +} XColorEntry; + +static XColorEntry xColors[] = { + "alice blue", 240, 248, 255, + "AliceBlue", 240, 248, 255, + "antique white", 250, 235, 215, + "AntiqueWhite", 250, 235, 215, + "AntiqueWhite1", 255, 239, 219, + "AntiqueWhite2", 238, 223, 204, + "AntiqueWhite3", 205, 192, 176, + "AntiqueWhite4", 139, 131, 120, + "aquamarine", 127, 255, 212, + "aquamarine1", 127, 255, 212, + "aquamarine2", 118, 238, 198, + "aquamarine3", 102, 205, 170, + "aquamarine4", 69, 139, 116, + "azure", 240, 255, 255, + "azure1", 240, 255, 255, + "azure2", 224, 238, 238, + "azure3", 193, 205, 205, + "azure4", 131, 139, 139, + "beige", 245, 245, 220, + "bisque", 255, 228, 196, + "bisque1", 255, 228, 196, + "bisque2", 238, 213, 183, + "bisque3", 205, 183, 158, + "bisque4", 139, 125, 107, + "black", 0, 0, 0, + "blanched almond", 255, 235, 205, + "BlanchedAlmond", 255, 235, 205, + "blue", 0, 0, 255, + "blue violet", 138, 43, 226, + "blue1", 0, 0, 255, + "blue2", 0, 0, 238, + "blue3", 0, 0, 205, + "blue4", 0, 0, 139, + "BlueViolet", 138, 43, 226, + "brown", 165, 42, 42, + "brown1", 255, 64, 64, + "brown2", 238, 59, 59, + "brown3", 205, 51, 51, + "brown4", 139, 35, 35, + "burlywood", 222, 184, 135, + "burlywood1", 255, 211, 155, + "burlywood2", 238, 197, 145, + "burlywood3", 205, 170, 125, + "burlywood4", 139, 115, 85, + "cadet blue", 95, 158, 160, + "CadetBlue", 95, 158, 160, + "CadetBlue1", 152, 245, 255, + "CadetBlue2", 142, 229, 238, + "CadetBlue3", 122, 197, 205, + "CadetBlue4", 83, 134, 139, + "chartreuse", 127, 255, 0, + "chartreuse1", 127, 255, 0, + "chartreuse2", 118, 238, 0, + "chartreuse3", 102, 205, 0, + "chartreuse4", 69, 139, 0, + "chocolate", 210, 105, 30, + "chocolate1", 255, 127, 36, + "chocolate2", 238, 118, 33, + "chocolate3", 205, 102, 29, + "chocolate4", 139, 69, 19, + "coral", 255, 127, 80, + "coral1", 255, 114, 86, + "coral2", 238, 106, 80, + "coral3", 205, 91, 69, + "coral4", 139, 62, 47, + "cornflower blue", 100, 149, 237, + "CornflowerBlue", 100, 149, 237, + "cornsilk", 255, 248, 220, + "cornsilk1", 255, 248, 220, + "cornsilk2", 238, 232, 205, + "cornsilk3", 205, 200, 177, + "cornsilk4", 139, 136, 120, + "cyan", 0, 255, 255, + "cyan1", 0, 255, 255, + "cyan2", 0, 238, 238, + "cyan3", 0, 205, 205, + "cyan4", 0, 139, 139, + "dark blue", 0, 0, 139, + "dark cyan", 0, 139, 139, + "dark goldenrod", 184, 134, 11, + "dark gray", 169, 169, 169, + "dark green", 0, 100, 0, + "dark grey", 169, 169, 169, + "dark khaki", 189, 183, 107, + "dark magenta", 139, 0, 139, + "dark olive green", 85, 107, 47, + "dark orange", 255, 140, 0, + "dark orchid", 153, 50, 204, + "dark red", 139, 0, 0, + "dark salmon", 233, 150, 122, + "dark sea green", 143, 188, 143, + "dark slate blue", 72, 61, 139, + "dark slate gray", 47, 79, 79, + "dark slate grey", 47, 79, 79, + "dark turquoise", 0, 206, 209, + "dark violet", 148, 0, 211, + "DarkBlue", 0, 0, 139, + "DarkCyan", 0, 139, 139, + "DarkGoldenrod", 184, 134, 11, + "DarkGoldenrod1", 255, 185, 15, + "DarkGoldenrod2", 238, 173, 14, + "DarkGoldenrod3", 205, 149, 12, + "DarkGoldenrod4", 139, 101, 8, + "DarkGray", 169, 169, 169, + "DarkGreen", 0, 100, 0, + "DarkGrey", 169, 169, 169, + "DarkKhaki", 189, 183, 107, + "DarkMagenta", 139, 0, 139, + "DarkOliveGreen", 85, 107, 47, + "DarkOliveGreen1", 202, 255, 112, + "DarkOliveGreen2", 188, 238, 104, + "DarkOliveGreen3", 162, 205, 90, + "DarkOliveGreen4", 110, 139, 61, + "DarkOrange", 255, 140, 0, + "DarkOrange1", 255, 127, 0, + "DarkOrange2", 238, 118, 0, + "DarkOrange3", 205, 102, 0, + "DarkOrange4", 139, 69, 0, + "DarkOrchid", 153, 50, 204, + "DarkOrchid1", 191, 62, 255, + "DarkOrchid2", 178, 58, 238, + "DarkOrchid3", 154, 50, 205, + "DarkOrchid4", 104, 34, 139, + "DarkRed", 139, 0, 0, + "DarkSalmon", 233, 150, 122, + "DarkSeaGreen", 143, 188, 143, + "DarkSeaGreen1", 193, 255, 193, + "DarkSeaGreen2", 180, 238, 180, + "DarkSeaGreen3", 155, 205, 155, + "DarkSeaGreen4", 105, 139, 105, + "DarkSlateBlue", 72, 61, 139, + "DarkSlateGray", 47, 79, 79, + "DarkSlateGray1", 151, 255, 255, + "DarkSlateGray2", 141, 238, 238, + "DarkSlateGray3", 121, 205, 205, + "DarkSlateGray4", 82, 139, 139, + "DarkSlateGrey", 47, 79, 79, + "DarkTurquoise", 0, 206, 209, + "DarkViolet", 148, 0, 211, + "deep pink", 255, 20, 147, + "deep sky blue", 0, 191, 255, + "DeepPink", 255, 20, 147, + "DeepPink1", 255, 20, 147, + "DeepPink2", 238, 18, 137, + "DeepPink3", 205, 16, 118, + "DeepPink4", 139, 10, 80, + "DeepSkyBlue", 0, 191, 255, + "DeepSkyBlue1", 0, 191, 255, + "DeepSkyBlue2", 0, 178, 238, + "DeepSkyBlue3", 0, 154, 205, + "DeepSkyBlue4", 0, 104, 139, + "dim gray", 105, 105, 105, + "dim grey", 105, 105, 105, + "DimGray", 105, 105, 105, + "DimGrey", 105, 105, 105, + "dodger blue", 30, 144, 255, + "DodgerBlue", 30, 144, 255, + "DodgerBlue1", 30, 144, 255, + "DodgerBlue2", 28, 134, 238, + "DodgerBlue3", 24, 116, 205, + "DodgerBlue4", 16, 78, 139, + "firebrick", 178, 34, 34, + "firebrick1", 255, 48, 48, + "firebrick2", 238, 44, 44, + "firebrick3", 205, 38, 38, + "firebrick4", 139, 26, 26, + "floral white", 255, 250, 240, + "FloralWhite", 255, 250, 240, + "forest green", 34, 139, 34, + "ForestGreen", 34, 139, 34, + "gainsboro", 220, 220, 220, + "ghost white", 248, 248, 255, + "GhostWhite", 248, 248, 255, + "gold", 255, 215, 0, + "gold1", 255, 215, 0, + "gold2", 238, 201, 0, + "gold3", 205, 173, 0, + "gold4", 139, 117, 0, + "goldenrod", 218, 165, 32, + "goldenrod1", 255, 193, 37, + "goldenrod2", 238, 180, 34, + "goldenrod3", 205, 155, 29, + "goldenrod4", 139, 105, 20, + "gray", 190, 190, 190, + "gray0", 0, 0, 0, + "gray1", 3, 3, 3, + "gray10", 26, 26, 26, + "gray100", 255, 255, 255, + "gray11", 28, 28, 28, + "gray12", 31, 31, 31, + "gray13", 33, 33, 33, + "gray14", 36, 36, 36, + "gray15", 38, 38, 38, + "gray16", 41, 41, 41, + "gray17", 43, 43, 43, + "gray18", 46, 46, 46, + "gray19", 48, 48, 48, + "gray2", 5, 5, 5, + "gray20", 51, 51, 51, + "gray21", 54, 54, 54, + "gray22", 56, 56, 56, + "gray23", 59, 59, 59, + "gray24", 61, 61, 61, + "gray25", 64, 64, 64, + "gray26", 66, 66, 66, + "gray27", 69, 69, 69, + "gray28", 71, 71, 71, + "gray29", 74, 74, 74, + "gray3", 8, 8, 8, + "gray30", 77, 77, 77, + "gray31", 79, 79, 79, + "gray32", 82, 82, 82, + "gray33", 84, 84, 84, + "gray34", 87, 87, 87, + "gray35", 89, 89, 89, + "gray36", 92, 92, 92, + "gray37", 94, 94, 94, + "gray38", 97, 97, 97, + "gray39", 99, 99, 99, + "gray4", 10, 10, 10, + "gray40", 102, 102, 102, + "gray41", 105, 105, 105, + "gray42", 107, 107, 107, + "gray43", 110, 110, 110, + "gray44", 112, 112, 112, + "gray45", 115, 115, 115, + "gray46", 117, 117, 117, + "gray47", 120, 120, 120, + "gray48", 122, 122, 122, + "gray49", 125, 125, 125, + "gray5", 13, 13, 13, + "gray50", 127, 127, 127, + "gray51", 130, 130, 130, + "gray52", 133, 133, 133, + "gray53", 135, 135, 135, + "gray54", 138, 138, 138, + "gray55", 140, 140, 140, + "gray56", 143, 143, 143, + "gray57", 145, 145, 145, + "gray58", 148, 148, 148, + "gray59", 150, 150, 150, + "gray6", 15, 15, 15, + "gray60", 153, 153, 153, + "gray61", 156, 156, 156, + "gray62", 158, 158, 158, + "gray63", 161, 161, 161, + "gray64", 163, 163, 163, + "gray65", 166, 166, 166, + "gray66", 168, 168, 168, + "gray67", 171, 171, 171, + "gray68", 173, 173, 173, + "gray69", 176, 176, 176, + "gray7", 18, 18, 18, + "gray70", 179, 179, 179, + "gray71", 181, 181, 181, + "gray72", 184, 184, 184, + "gray73", 186, 186, 186, + "gray74", 189, 189, 189, + "gray75", 191, 191, 191, + "gray76", 194, 194, 194, + "gray77", 196, 196, 196, + "gray78", 199, 199, 199, + "gray79", 201, 201, 201, + "gray8", 20, 20, 20, + "gray80", 204, 204, 204, + "gray81", 207, 207, 207, + "gray82", 209, 209, 209, + "gray83", 212, 212, 212, + "gray84", 214, 214, 214, + "gray85", 217, 217, 217, + "gray86", 219, 219, 219, + "gray87", 222, 222, 222, + "gray88", 224, 224, 224, + "gray89", 227, 227, 227, + "gray9", 23, 23, 23, + "gray90", 229, 229, 229, + "gray91", 232, 232, 232, + "gray92", 235, 235, 235, + "gray93", 237, 237, 237, + "gray94", 240, 240, 240, + "gray95", 242, 242, 242, + "gray96", 245, 245, 245, + "gray97", 247, 247, 247, + "gray98", 250, 250, 250, + "gray99", 252, 252, 252, + "green", 0, 255, 0, + "green yellow", 173, 255, 47, + "green1", 0, 255, 0, + "green2", 0, 238, 0, + "green3", 0, 205, 0, + "green4", 0, 139, 0, + "GreenYellow", 173, 255, 47, + "grey", 190, 190, 190, + "grey0", 0, 0, 0, + "grey1", 3, 3, 3, + "grey10", 26, 26, 26, + "grey100", 255, 255, 255, + "grey11", 28, 28, 28, + "grey12", 31, 31, 31, + "grey13", 33, 33, 33, + "grey14", 36, 36, 36, + "grey15", 38, 38, 38, + "grey16", 41, 41, 41, + "grey17", 43, 43, 43, + "grey18", 46, 46, 46, + "grey19", 48, 48, 48, + "grey2", 5, 5, 5, + "grey20", 51, 51, 51, + "grey21", 54, 54, 54, + "grey22", 56, 56, 56, + "grey23", 59, 59, 59, + "grey24", 61, 61, 61, + "grey25", 64, 64, 64, + "grey26", 66, 66, 66, + "grey27", 69, 69, 69, + "grey28", 71, 71, 71, + "grey29", 74, 74, 74, + "grey3", 8, 8, 8, + "grey30", 77, 77, 77, + "grey31", 79, 79, 79, + "grey32", 82, 82, 82, + "grey33", 84, 84, 84, + "grey34", 87, 87, 87, + "grey35", 89, 89, 89, + "grey36", 92, 92, 92, + "grey37", 94, 94, 94, + "grey38", 97, 97, 97, + "grey39", 99, 99, 99, + "grey4", 10, 10, 10, + "grey40", 102, 102, 102, + "grey41", 105, 105, 105, + "grey42", 107, 107, 107, + "grey43", 110, 110, 110, + "grey44", 112, 112, 112, + "grey45", 115, 115, 115, + "grey46", 117, 117, 117, + "grey47", 120, 120, 120, + "grey48", 122, 122, 122, + "grey49", 125, 125, 125, + "grey5", 13, 13, 13, + "grey50", 127, 127, 127, + "grey51", 130, 130, 130, + "grey52", 133, 133, 133, + "grey53", 135, 135, 135, + "grey54", 138, 138, 138, + "grey55", 140, 140, 140, + "grey56", 143, 143, 143, + "grey57", 145, 145, 145, + "grey58", 148, 148, 148, + "grey59", 150, 150, 150, + "grey6", 15, 15, 15, + "grey60", 153, 153, 153, + "grey61", 156, 156, 156, + "grey62", 158, 158, 158, + "grey63", 161, 161, 161, + "grey64", 163, 163, 163, + "grey65", 166, 166, 166, + "grey66", 168, 168, 168, + "grey67", 171, 171, 171, + "grey68", 173, 173, 173, + "grey69", 176, 176, 176, + "grey7", 18, 18, 18, + "grey70", 179, 179, 179, + "grey71", 181, 181, 181, + "grey72", 184, 184, 184, + "grey73", 186, 186, 186, + "grey74", 189, 189, 189, + "grey75", 191, 191, 191, + "grey76", 194, 194, 194, + "grey77", 196, 196, 196, + "grey78", 199, 199, 199, + "grey79", 201, 201, 201, + "grey8", 20, 20, 20, + "grey80", 204, 204, 204, + "grey81", 207, 207, 207, + "grey82", 209, 209, 209, + "grey83", 212, 212, 212, + "grey84", 214, 214, 214, + "grey85", 217, 217, 217, + "grey86", 219, 219, 219, + "grey87", 222, 222, 222, + "grey88", 224, 224, 224, + "grey89", 227, 227, 227, + "grey9", 23, 23, 23, + "grey90", 229, 229, 229, + "grey91", 232, 232, 232, + "grey92", 235, 235, 235, + "grey93", 237, 237, 237, + "grey94", 240, 240, 240, + "grey95", 242, 242, 242, + "grey96", 245, 245, 245, + "grey97", 247, 247, 247, + "grey98", 250, 250, 250, + "grey99", 252, 252, 252, + "honeydew", 240, 255, 240, + "honeydew1", 240, 255, 240, + "honeydew2", 224, 238, 224, + "honeydew3", 193, 205, 193, + "honeydew4", 131, 139, 131, + "hot pink", 255, 105, 180, + "HotPink", 255, 105, 180, + "HotPink1", 255, 110, 180, + "HotPink2", 238, 106, 167, + "HotPink3", 205, 96, 144, + "HotPink4", 139, 58, 98, + "indian red", 205, 92, 92, + "IndianRed", 205, 92, 92, + "IndianRed1", 255, 106, 106, + "IndianRed2", 238, 99, 99, + "IndianRed3", 205, 85, 85, + "IndianRed4", 139, 58, 58, + "ivory", 255, 255, 240, + "ivory1", 255, 255, 240, + "ivory2", 238, 238, 224, + "ivory3", 205, 205, 193, + "ivory4", 139, 139, 131, + "khaki", 240, 230, 140, + "khaki1", 255, 246, 143, + "khaki2", 238, 230, 133, + "khaki3", 205, 198, 115, + "khaki4", 139, 134, 78, + "lavender", 230, 230, 250, + "lavender blush", 255, 240, 245, + "LavenderBlush", 255, 240, 245, + "LavenderBlush1", 255, 240, 245, + "LavenderBlush2", 238, 224, 229, + "LavenderBlush3", 205, 193, 197, + "LavenderBlush4", 139, 131, 134, + "lawn green", 124, 252, 0, + "LawnGreen", 124, 252, 0, + "lemon chiffon", 255, 250, 205, + "LemonChiffon", 255, 250, 205, + "LemonChiffon1", 255, 250, 205, + "LemonChiffon2", 238, 233, 191, + "LemonChiffon3", 205, 201, 165, + "LemonChiffon4", 139, 137, 112, + "light blue", 173, 216, 230, + "light coral", 240, 128, 128, + "light cyan", 224, 255, 255, + "light goldenrod", 238, 221, 130, + "light goldenrod yellow", 250, 250, 210, + "light gray", 211, 211, 211, + "light green", 144, 238, 144, + "light grey", 211, 211, 211, + "light pink", 255, 182, 193, + "light salmon", 255, 160, 122, + "light sea green", 32, 178, 170, + "light sky blue", 135, 206, 250, + "light slate blue", 132, 112, 255, + "light slate gray", 119, 136, 153, + "light slate grey", 119, 136, 153, + "light steel blue", 176, 196, 222, + "light yellow", 255, 255, 224, + "LightBlue", 173, 216, 230, + "LightBlue1", 191, 239, 255, + "LightBlue2", 178, 223, 238, + "LightBlue3", 154, 192, 205, + "LightBlue4", 104, 131, 139, + "LightCoral", 240, 128, 128, + "LightCyan", 224, 255, 255, + "LightCyan1", 224, 255, 255, + "LightCyan2", 209, 238, 238, + "LightCyan3", 180, 205, 205, + "LightCyan4", 122, 139, 139, + "LightGoldenrod", 238, 221, 130, + "LightGoldenrod1", 255, 236, 139, + "LightGoldenrod2", 238, 220, 130, + "LightGoldenrod3", 205, 190, 112, + "LightGoldenrod4", 139, 129, 76, + "LightGoldenrodYellow", 250, 250, 210, + "LightGray", 211, 211, 211, + "LightGreen", 144, 238, 144, + "LightGrey", 211, 211, 211, + "LightPink", 255, 182, 193, + "LightPink1", 255, 174, 185, + "LightPink2", 238, 162, 173, + "LightPink3", 205, 140, 149, + "LightPink4", 139, 95, 101, + "LightSalmon", 255, 160, 122, + "LightSalmon1", 255, 160, 122, + "LightSalmon2", 238, 149, 114, + "LightSalmon3", 205, 129, 98, + "LightSalmon4", 139, 87, 66, + "LightSeaGreen", 32, 178, 170, + "LightSkyBlue", 135, 206, 250, + "LightSkyBlue1", 176, 226, 255, + "LightSkyBlue2", 164, 211, 238, + "LightSkyBlue3", 141, 182, 205, + "LightSkyBlue4", 96, 123, 139, + "LightSlateBlue", 132, 112, 255, + "LightSlateGray", 119, 136, 153, + "LightSlateGrey", 119, 136, 153, + "LightSteelBlue", 176, 196, 222, + "LightSteelBlue1", 202, 225, 255, + "LightSteelBlue2", 188, 210, 238, + "LightSteelBlue3", 162, 181, 205, + "LightSteelBlue4", 110, 123, 139, + "LightYellow", 255, 255, 224, + "LightYellow1", 255, 255, 224, + "LightYellow2", 238, 238, 209, + "LightYellow3", 205, 205, 180, + "LightYellow4", 139, 139, 122, + "lime green", 50, 205, 50, + "LimeGreen", 50, 205, 50, + "linen", 250, 240, 230, + "magenta", 255, 0, 255, + "magenta1", 255, 0, 255, + "magenta2", 238, 0, 238, + "magenta3", 205, 0, 205, + "magenta4", 139, 0, 139, + "maroon", 176, 48, 96, + "maroon1", 255, 52, 179, + "maroon2", 238, 48, 167, + "maroon3", 205, 41, 144, + "maroon4", 139, 28, 98, + "medium aquamarine", 102, 205, 170, + "medium blue", 0, 0, 205, + "medium orchid", 186, 85, 211, + "medium purple", 147, 112, 219, + "medium sea green", 60, 179, 113, + "medium slate blue", 123, 104, 238, + "medium spring green", 0, 250, 154, + "medium turquoise", 72, 209, 204, + "medium violet red", 199, 21, 133, + "MediumAquamarine", 102, 205, 170, + "MediumBlue", 0, 0, 205, + "MediumOrchid", 186, 85, 211, + "MediumOrchid1", 224, 102, 255, + "MediumOrchid2", 209, 95, 238, + "MediumOrchid3", 180, 82, 205, + "MediumOrchid4", 122, 55, 139, + "MediumPurple", 147, 112, 219, + "MediumPurple1", 171, 130, 255, + "MediumPurple2", 159, 121, 238, + "MediumPurple3", 137, 104, 205, + "MediumPurple4", 93, 71, 139, + "MediumSeaGreen", 60, 179, 113, + "MediumSlateBlue", 123, 104, 238, + "MediumSpringGreen", 0, 250, 154, + "MediumTurquoise", 72, 209, 204, + "MediumVioletRed", 199, 21, 133, + "midnight blue", 25, 25, 112, + "MidnightBlue", 25, 25, 112, + "mint cream", 245, 255, 250, + "MintCream", 245, 255, 250, + "misty rose", 255, 228, 225, + "MistyRose", 255, 228, 225, + "MistyRose1", 255, 228, 225, + "MistyRose2", 238, 213, 210, + "MistyRose3", 205, 183, 181, + "MistyRose4", 139, 125, 123, + "moccasin", 255, 228, 181, + "navajo white", 255, 222, 173, + "NavajoWhite", 255, 222, 173, + "NavajoWhite1", 255, 222, 173, + "NavajoWhite2", 238, 207, 161, + "NavajoWhite3", 205, 179, 139, + "NavajoWhite4", 139, 121, 94, + "navy", 0, 0, 128, + "navy blue", 0, 0, 128, + "NavyBlue", 0, 0, 128, + "old lace", 253, 245, 230, + "OldLace", 253, 245, 230, + "olive drab", 107, 142, 35, + "OliveDrab", 107, 142, 35, + "OliveDrab1", 192, 255, 62, + "OliveDrab2", 179, 238, 58, + "OliveDrab3", 154, 205, 50, + "OliveDrab4", 105, 139, 34, + "orange", 255, 165, 0, + "orange red", 255, 69, 0, + "orange1", 255, 165, 0, + "orange2", 238, 154, 0, + "orange3", 205, 133, 0, + "orange4", 139, 90, 0, + "OrangeRed", 255, 69, 0, + "OrangeRed1", 255, 69, 0, + "OrangeRed2", 238, 64, 0, + "OrangeRed3", 205, 55, 0, + "OrangeRed4", 139, 37, 0, + "orchid", 218, 112, 214, + "orchid1", 255, 131, 250, + "orchid2", 238, 122, 233, + "orchid3", 205, 105, 201, + "orchid4", 139, 71, 137, + "pale goldenrod", 238, 232, 170, + "pale green", 152, 251, 152, + "pale turquoise", 175, 238, 238, + "pale violet red", 219, 112, 147, + "PaleGoldenrod", 238, 232, 170, + "PaleGreen", 152, 251, 152, + "PaleGreen1", 154, 255, 154, + "PaleGreen2", 144, 238, 144, + "PaleGreen3", 124, 205, 124, + "PaleGreen4", 84, 139, 84, + "PaleTurquoise", 175, 238, 238, + "PaleTurquoise1", 187, 255, 255, + "PaleTurquoise2", 174, 238, 238, + "PaleTurquoise3", 150, 205, 205, + "PaleTurquoise4", 102, 139, 139, + "PaleVioletRed", 219, 112, 147, + "PaleVioletRed1", 255, 130, 171, + "PaleVioletRed2", 238, 121, 159, + "PaleVioletRed3", 205, 104, 137, + "PaleVioletRed4", 139, 71, 93, + "papaya whip", 255, 239, 213, + "PapayaWhip", 255, 239, 213, + "peach puff", 255, 218, 185, + "PeachPuff", 255, 218, 185, + "PeachPuff1", 255, 218, 185, + "PeachPuff2", 238, 203, 173, + "PeachPuff3", 205, 175, 149, + "PeachPuff4", 139, 119, 101, + "peru", 205, 133, 63, + "pink", 255, 192, 203, + "pink1", 255, 181, 197, + "pink2", 238, 169, 184, + "pink3", 205, 145, 158, + "pink4", 139, 99, 108, + "plum", 221, 160, 221, + "plum1", 255, 187, 255, + "plum2", 238, 174, 238, + "plum3", 205, 150, 205, + "plum4", 139, 102, 139, + "powder blue", 176, 224, 230, + "PowderBlue", 176, 224, 230, + "purple", 160, 32, 240, + "purple1", 155, 48, 255, + "purple2", 145, 44, 238, + "purple3", 125, 38, 205, + "purple4", 85, 26, 139, + "red", 255, 0, 0, + "red1", 255, 0, 0, + "red2", 238, 0, 0, + "red3", 205, 0, 0, + "red4", 139, 0, 0, + "rosy brown", 188, 143, 143, + "RosyBrown", 188, 143, 143, + "RosyBrown1", 255, 193, 193, + "RosyBrown2", 238, 180, 180, + "RosyBrown3", 205, 155, 155, + "RosyBrown4", 139, 105, 105, + "royal blue", 65, 105, 225, + "RoyalBlue", 65, 105, 225, + "RoyalBlue1", 72, 118, 255, + "RoyalBlue2", 67, 110, 238, + "RoyalBlue3", 58, 95, 205, + "RoyalBlue4", 39, 64, 139, + "saddle brown", 139, 69, 19, + "SaddleBrown", 139, 69, 19, + "salmon", 250, 128, 114, + "salmon1", 255, 140, 105, + "salmon2", 238, 130, 98, + "salmon3", 205, 112, 84, + "salmon4", 139, 76, 57, + "sandy brown", 244, 164, 96, + "SandyBrown", 244, 164, 96, + "sea green", 46, 139, 87, + "SeaGreen", 46, 139, 87, + "SeaGreen1", 84, 255, 159, + "SeaGreen2", 78, 238, 148, + "SeaGreen3", 67, 205, 128, + "SeaGreen4", 46, 139, 87, + "seashell", 255, 245, 238, + "seashell1", 255, 245, 238, + "seashell2", 238, 229, 222, + "seashell3", 205, 197, 191, + "seashell4", 139, 134, 130, + "sienna", 160, 82, 45, + "sienna1", 255, 130, 71, + "sienna2", 238, 121, 66, + "sienna3", 205, 104, 57, + "sienna4", 139, 71, 38, + "sky blue", 135, 206, 235, + "SkyBlue", 135, 206, 235, + "SkyBlue1", 135, 206, 255, + "SkyBlue2", 126, 192, 238, + "SkyBlue3", 108, 166, 205, + "SkyBlue4", 74, 112, 139, + "slate blue", 106, 90, 205, + "slate gray", 112, 128, 144, + "slate grey", 112, 128, 144, + "SlateBlue", 106, 90, 205, + "SlateBlue1", 131, 111, 255, + "SlateBlue2", 122, 103, 238, + "SlateBlue3", 105, 89, 205, + "SlateBlue4", 71, 60, 139, + "SlateGray", 112, 128, 144, + "SlateGray1", 198, 226, 255, + "SlateGray2", 185, 211, 238, + "SlateGray3", 159, 182, 205, + "SlateGray4", 108, 123, 139, + "SlateGrey", 112, 128, 144, + "snow", 255, 250, 250, + "snow1", 255, 250, 250, + "snow2", 238, 233, 233, + "snow3", 205, 201, 201, + "snow4", 139, 137, 137, + "spring green", 0, 255, 127, + "SpringGreen", 0, 255, 127, + "SpringGreen1", 0, 255, 127, + "SpringGreen2", 0, 238, 118, + "SpringGreen3", 0, 205, 102, + "SpringGreen4", 0, 139, 69, + "steel blue", 70, 130, 180, + "SteelBlue", 70, 130, 180, + "SteelBlue1", 99, 184, 255, + "SteelBlue2", 92, 172, 238, + "SteelBlue3", 79, 148, 205, + "SteelBlue4", 54, 100, 139, + "tan", 210, 180, 140, + "tan1", 255, 165, 79, + "tan2", 238, 154, 73, + "tan3", 205, 133, 63, + "tan4", 139, 90, 43, + "thistle", 216, 191, 216, + "thistle1", 255, 225, 255, + "thistle2", 238, 210, 238, + "thistle3", 205, 181, 205, + "thistle4", 139, 123, 139, + "tomato", 255, 99, 71, + "tomato1", 255, 99, 71, + "tomato2", 238, 92, 66, + "tomato3", 205, 79, 57, + "tomato4", 139, 54, 38, + "turquoise", 64, 224, 208, + "turquoise1", 0, 245, 255, + "turquoise2", 0, 229, 238, + "turquoise3", 0, 197, 205, + "turquoise4", 0, 134, 139, + "violet", 238, 130, 238, + "violet red", 208, 32, 144, + "VioletRed", 208, 32, 144, + "VioletRed1", 255, 62, 150, + "VioletRed2", 238, 58, 140, + "VioletRed3", 205, 50, 120, + "VioletRed4", 139, 34, 82, + "wheat", 245, 222, 179, + "wheat1", 255, 231, 186, + "wheat2", 238, 216, 174, + "wheat3", 205, 186, 150, + "wheat4", 139, 126, 102, + "white", 255, 255, 255, + "white smoke", 245, 245, 245, + "WhiteSmoke", 245, 245, 245, + "yellow", 255, 255, 0, + "yellow green", 154, 205, 50, + "yellow1", 255, 255, 0, + "yellow2", 238, 238, 0, + "yellow3", 205, 205, 0, + "yellow4", 139, 139, 0, + "YellowGreen", 154, 205, 50, + NULL, 0, 0, 0 +}; + + +/* + * This value will be set to the number of colors in the color table + * the first time it is needed. + */ + +static int numXColors = 0; + +/* + * Forward declarations for functions used only in this file. + */ + +static int FindColor _ANSI_ARGS_((const char *name, XColor *colorPtr)); + +/* + *---------------------------------------------------------------------- + * + * FindColor -- + * + * This routine finds the color entry that corresponds to the + * specified color. + * + * Results: + * Returns non-zero on success. The RGB values of the XColor + * will be initialized to the proper values on success. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +static int +FindColor(name, colorPtr) + const char *name; + XColor *colorPtr; +{ + int l, u, r, i; + + /* + * Count the number of elements in the color array if we haven't + * done so yet. + */ + + if (numXColors == 0) { + XColorEntry *ePtr; + for (ePtr = xColors; ePtr->name != NULL; ePtr++) { + numXColors++; + } + } + + /* + * Perform a binary search on the sorted array of colors. + */ + + l = 0; + u = numXColors - 1; + while (l <= u) { + i = (l + u) / 2; + r = strcasecmp(name, xColors[i].name); + if (r == 0) { + break; + } else if (r < 0) { + u = i-1; + } else { + l = i+1; + } + } + if (l > u) { + return 0; + } + colorPtr->red = xColors[i].red << 8; + colorPtr->green = xColors[i].green << 8; + colorPtr->blue = xColors[i].blue << 8; + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * XParseColor -- + * + * Partial implementation of X color name parsing interface. + * + * Results: + * Returns non-zero on success. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Status +XParseColor(display, map, spec, colorPtr) + Display *display; + Colormap map; + const char* spec; + XColor *colorPtr; +{ + if (spec[0] == '#') { + char fmt[16]; + int i, red, green, blue; + + if ((i = strlen(spec+1))%3) { + return 0; + } + i /= 3; + + sprintf(fmt, "%%%dx%%%dx%%%dx", i, i, i); + if (sscanf(spec+1, fmt, &red, &green, &blue) != 3) { + return 0; + } + colorPtr->red = ((unsigned short) red) << (4 * (4 - i)); + colorPtr->green = ((unsigned short) green) << (4 * (4 - i)); + colorPtr->blue = ((unsigned short) blue) << (4 * (4 - i)); + } else { + if (!FindColor(spec, colorPtr)) { + return 0; + } + } + colorPtr->pixel = TkpGetPixel(colorPtr); + colorPtr->flags = DoRed|DoGreen|DoBlue; + colorPtr->pad = 0; + return 1; +} diff --git a/xlib/xdraw.c b/xlib/xdraw.c new file mode 100644 index 0000000..8e78011 --- /dev/null +++ b/xlib/xdraw.c @@ -0,0 +1,82 @@ +/* + * xdraw.c -- + * + * This file contains generic procedures related to X drawing + * primitives. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) xdraw.c 1.2 96/02/15 18:55:46 + */ + +#include "tk.h" + +/* + *---------------------------------------------------------------------- + * + * XDrawLine -- + * + * Draw a single line between two points in a given drawable. + * + * Results: + * None. + * + * Side effects: + * Draws a single line segment. + * + *---------------------------------------------------------------------- + */ + +void +XDrawLine(display, d, gc, x1, y1, x2, y2) + Display* display; + Drawable d; + GC gc; + int x1, y1, x2, y2; /* Coordinates of line segment. */ +{ + XPoint points[2]; + + points[0].x = x1; + points[0].y = y1; + points[1].x = x2; + points[1].y = y2; + XDrawLines(display, d, gc, points, 2, CoordModeOrigin); +} + +/* + *---------------------------------------------------------------------- + * + * XFillRectangle -- + * + * Fills a rectangular area in the given drawable. This procedure + * is implemented as a call to XFillRectangles. + * + * Results: + * None + * + * Side effects: + * Fills the specified rectangle. + * + *---------------------------------------------------------------------- + */ + +void +XFillRectangle(display, d, gc, x, y, width, height) + Display* display; + Drawable d; + GC gc; + int x; + int y; + unsigned int width; + unsigned int height; +{ + XRectangle rectangle; + rectangle.x = x; + rectangle.y = y; + rectangle.width = width; + rectangle.height = height; + XFillRectangles(display, d, gc, &rectangle, 1); +} diff --git a/xlib/xgc.c b/xlib/xgc.c new file mode 100644 index 0000000..cdd1021 --- /dev/null +++ b/xlib/xgc.c @@ -0,0 +1,353 @@ +/* + * xgc.c -- + * + * This file contains generic routines for manipulating X graphics + * contexts. + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) xgc.c 1.8 96/10/11 14:59:39 + */ + +#include <tkInt.h> + +#ifdef MAC_TCL +# include <Xlib.h> +#else +# include <X11/Xlib.h> +#endif + + +/* + *---------------------------------------------------------------------- + * + * XCreateGC -- + * + * Allocate a new GC, and initialize the specified fields. + * + * Results: + * Returns a newly allocated GC. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +GC +XCreateGC(display, d, mask, values) + Display* display; + Drawable d; + unsigned long mask; + XGCValues* values; +{ + GC gp; + + gp = (XGCValues *)ckalloc(sizeof(XGCValues)); + if (!gp) { + return None; + } + + gp->function = (mask & GCFunction) ?values->function :GXcopy; + gp->plane_mask = (mask & GCPlaneMask) ?values->plane_mask :~0; + gp->foreground = (mask & GCForeground) ?values->foreground :0; + gp->background = (mask & GCBackground) ?values->background :0xffffff; + gp->line_width = (mask & GCLineWidth) ?values->line_width :0; + gp->line_style = (mask & GCLineStyle) ?values->line_style :LineSolid; + gp->cap_style = (mask & GCCapStyle) ?values->cap_style :0; + gp->join_style = (mask & GCJoinStyle) ?values->join_style :0; + gp->fill_style = (mask & GCFillStyle) ?values->fill_style :FillSolid; + gp->fill_rule = (mask & GCFillRule) ?values->fill_rule :WindingRule; + gp->arc_mode = (mask & GCArcMode) ?values->arc_mode :ArcPieSlice; + gp->tile = (mask & GCTile) ?values->tile :None; + gp->stipple = (mask & GCStipple) ?values->stipple :None; + gp->ts_x_origin = (mask & GCTileStipXOrigin) ?values->ts_x_origin:0; + gp->ts_y_origin = (mask & GCTileStipYOrigin) ?values->ts_y_origin:0; + gp->font = (mask & GCFont) ?values->font :None; + gp->subwindow_mode = (mask & GCSubwindowMode)?values->subwindow_mode:ClipByChildren; + gp->graphics_exposures = (mask & GCGraphicsExposures)?values->graphics_exposures:True; + gp->clip_x_origin = (mask & GCClipXOrigin) ?values->clip_x_origin :0; + gp->clip_y_origin = (mask & GCClipYOrigin) ?values->clip_y_origin :0; + gp->dash_offset = (mask & GCDashOffset) ?values->dash_offset :0; + gp->dashes = (mask & GCDashList) ?values->dashes :4; + + if (mask & GCClipMask) { + gp->clip_mask = (Pixmap)ckalloc(sizeof(TkpClipMask)); + ((TkpClipMask*)gp->clip_mask)->type = TKP_CLIP_PIXMAP; + ((TkpClipMask*)gp->clip_mask)->value.pixmap = values->clip_mask; + } else { + gp->clip_mask = None; + } + + return gp; +} + +/* + *---------------------------------------------------------------------- + * + * XChangeGC -- + * + * Changes the GC components specified by valuemask for the + * specified GC. + * + * Results: + * None. + * + * Side effects: + * Updates the specified GC. + * + *---------------------------------------------------------------------- + */ + +void +XChangeGC(d, gc, mask, values) + Display * d; + GC gc; + unsigned long mask; + XGCValues *values; +{ + if (mask & GCFunction) { gc->function = values->function; } + if (mask & GCPlaneMask) { gc->plane_mask = values->plane_mask; } + if (mask & GCForeground) { gc->foreground = values->foreground; } + if (mask & GCBackground) { gc->background = values->background; } + if (mask & GCLineWidth) { gc->line_width = values->line_width; } + if (mask & GCLineStyle) { gc->line_style = values->line_style; } + if (mask & GCCapStyle) { gc->cap_style = values->cap_style; } + if (mask & GCJoinStyle) { gc->join_style = values->join_style; } + if (mask & GCFillStyle) { gc->fill_style = values->fill_style; } + if (mask & GCFillRule) { gc->fill_rule = values->fill_rule; } + if (mask & GCArcMode) { gc->arc_mode = values->arc_mode; } + if (mask & GCTile) { gc->tile = values->tile; } + if (mask & GCStipple) { gc->stipple = values->stipple; } + if (mask & GCTileStipXOrigin) { gc->ts_x_origin = values->ts_x_origin; } + if (mask & GCTileStipYOrigin) { gc->ts_y_origin = values->ts_y_origin; } + if (mask & GCFont) { gc->font = values->font; } + if (mask & GCSubwindowMode) { gc->subwindow_mode = values->subwindow_mode; } + if (mask & GCGraphicsExposures) { gc->graphics_exposures = values->graphics_exposures; } + if (mask & GCClipXOrigin) { gc->clip_x_origin = values->clip_x_origin; } + if (mask & GCClipYOrigin) { gc->clip_y_origin = values->clip_y_origin; } + if (mask & GCClipMask) { XSetClipMask(d, gc, values->clip_mask); } + if (mask & GCDashOffset) { gc->dash_offset = values->dash_offset; } + if (mask & GCDashList) { gc->dashes = values->dashes; } +} + +/* + *---------------------------------------------------------------------- + * + * XFreeGC -- + * + * Deallocates the specified graphics context. + * + * Results: + * None. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +void +XFreeGC(d, gc) + Display * d; + GC gc; +{ + if (gc != None) { + if (gc->clip_mask != None) { + ckfree((char*) gc->clip_mask); + } + ckfree((char *) gc); + } +} + +/* + *---------------------------------------------------------------------- + * + * XSetForeground, etc. -- + * + * The following functions are simply accessor functions for + * the GC slots. + * + * Results: + * None. + * + * Side effects: + * Each function sets some slot in the GC. + * + *---------------------------------------------------------------------- + */ + +void +XSetForeground(display, gc, foreground) + Display *display; + GC gc; + unsigned long foreground; +{ + gc->foreground = foreground; +} + +void +XSetBackground(display, gc, background) + Display *display; + GC gc; + unsigned long background; +{ + gc->background = background; +} + +void +XSetFunction(display, gc, function) + Display *display; + GC gc; + int function; +{ + gc->function = function; +} + +void +XSetFillRule(display, gc, fill_rule) + Display *display; + GC gc; + int fill_rule; +{ + gc->fill_rule = fill_rule; +} + +void +XSetFillStyle(display, gc, fill_style) + Display *display; + GC gc; + int fill_style; +{ + gc->fill_style = fill_style; +} + +void +XSetTSOrigin(display, gc, x, y) + Display *display; + GC gc; + int x, y; +{ + gc->ts_x_origin = x; + gc->ts_y_origin = y; +} + +void +XSetFont(display, gc, font) + Display *display; + GC gc; + Font font; +{ + gc->font = font; +} + +void +XSetArcMode(display, gc, arc_mode) + Display *display; + GC gc; + int arc_mode; +{ + gc->arc_mode = arc_mode; +} + +void +XSetStipple(display, gc, stipple) + Display *display; + GC gc; + Pixmap stipple; +{ + gc->stipple = stipple; +} + +void +XSetLineAttributes(display, gc, line_width, line_style, cap_style, + join_style) + Display *display; + GC gc; + unsigned int line_width; + int line_style; + int cap_style; + int join_style; +{ + gc->line_width = line_width; + gc->line_style = line_style; + gc->cap_style = cap_style; + gc->join_style = join_style; +} + +void +XSetClipOrigin(display, gc, clip_x_origin, clip_y_origin) + Display* display; + GC gc; + int clip_x_origin; + int clip_y_origin; +{ + gc->clip_x_origin = clip_x_origin; + gc->clip_y_origin = clip_y_origin; +} + +/* + *---------------------------------------------------------------------- + * + * TkSetRegion, XSetClipMask -- + * + * Sets the clipping region/pixmap for a GC. + * + * Note that unlike the Xlib equivalent, it is not safe to delete + * the region after setting it into the GC. The only use of + * TkSetRegion is currently in ImgPhotoDisplay, which uses the GC + * immediately. + * + * Results: + * None. + * + * Side effects: + * Allocates or dealloates a TkpClipMask. + * + *---------------------------------------------------------------------- + */ + +void +TkSetRegion(display, gc, r) + Display* display; + GC gc; + TkRegion r; +{ + if (r == None) { + if (gc->clip_mask) { + ckfree((char*) gc->clip_mask); + gc->clip_mask = None; + } + return; + } + + if (gc->clip_mask == None) { + gc->clip_mask = (Pixmap)ckalloc(sizeof(TkpClipMask)); + } + ((TkpClipMask*)gc->clip_mask)->type = TKP_CLIP_REGION; + ((TkpClipMask*)gc->clip_mask)->value.region = r; +} + +void +XSetClipMask(display, gc, pixmap) + Display* display; + GC gc; + Pixmap pixmap; +{ + if (pixmap == None) { + if (gc->clip_mask) { + ckfree((char*) gc->clip_mask); + gc->clip_mask = None; + } + return; + } + + if (gc->clip_mask == None) { + gc->clip_mask = (Pixmap)ckalloc(sizeof(TkpClipMask)); + } + ((TkpClipMask*)gc->clip_mask)->type = TKP_CLIP_PIXMAP; + ((TkpClipMask*)gc->clip_mask)->value.pixmap = pixmap; +} diff --git a/xlib/ximage.c b/xlib/ximage.c new file mode 100644 index 0000000..057e973 --- /dev/null +++ b/xlib/ximage.c @@ -0,0 +1,115 @@ +/* + * ximage.c -- + * + * X bitmap and image routines. + * + * Copyright (c) 1995 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) ximage.c 1.6 96/07/23 16:59:10 + */ + +#include "tkInt.h" + + +/* + *---------------------------------------------------------------------- + * + * XCreateBitmapFromData -- + * + * Construct a single plane pixmap from bitmap data. + * + * Results: + * Returns a new Pixmap. + * + * Side effects: + * Allocates a new bitmap and drawable. + * + *---------------------------------------------------------------------- + */ + +Pixmap +XCreateBitmapFromData(display, d, data, width, height) + Display* display; + Drawable d; + _Xconst char* data; + unsigned int width; + unsigned int height; +{ + XImage ximage; + GC gc; + Pixmap pix; + + pix = Tk_GetPixmap(display, d, width, height, 1); + gc = XCreateGC(display, pix, 0, NULL); + if (gc == NULL) { + return None; + } + ximage.height = height; + ximage.width = width; + ximage.depth = 1; + ximage.bits_per_pixel = 1; + ximage.xoffset = 0; + ximage.format = XYBitmap; + ximage.data = (char *)data; + ximage.byte_order = LSBFirst; + ximage.bitmap_unit = 8; + ximage.bitmap_bit_order = LSBFirst; + ximage.bitmap_pad = 8; + ximage.bytes_per_line = (width+7)/8; + + TkPutImage(NULL, 0, display, pix, gc, &ximage, 0, 0, 0, 0, width, height); + XFreeGC(display, gc); + return pix; +} + +/* + *---------------------------------------------------------------------- + * + * XReadBitmapFile -- + * + * Loads a bitmap image in X bitmap format into the specified + * drawable. + * + * Results: + * Sets the size, hotspot, and bitmap on success. + * + * Side effects: + * Creates a new bitmap from the file data. + * + *---------------------------------------------------------------------- + */ + +int +XReadBitmapFile(display, d, filename, width_return, height_return, + bitmap_return, x_hot_return, y_hot_return) + Display* display; + Drawable d; + _Xconst char* filename; + unsigned int* width_return; + unsigned int* height_return; + Pixmap* bitmap_return; + int* x_hot_return; + int* y_hot_return; +{ + Tcl_Interp *dummy; + char *data; + + dummy = Tcl_CreateInterp(); + + data = TkGetBitmapData(dummy, NULL, (char *) filename, + (int *) width_return, (int *) height_return, x_hot_return, + y_hot_return); + if (data == NULL) { + return BitmapFileInvalid; + } + + *bitmap_return = XCreateBitmapFromData(display, d, data, *width_return, + *height_return); + + Tcl_DeleteInterp(dummy); + ckfree(data); + return BitmapSuccess; +} diff --git a/xlib/xutil.c b/xlib/xutil.c new file mode 100644 index 0000000..1080ff9 --- /dev/null +++ b/xlib/xutil.c @@ -0,0 +1,116 @@ +/* + * xutil.c -- + * + * This function contains generic X emulation routines. + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * SCCS: @(#) xutil.c 1.10 96/04/09 23:26:21 + */ + +#include <stdlib.h> +#include <tk.h> + +#ifdef MAC_TCL +# include <Xutil.h> +# include <Xatom.h> +#else +# include <X11/Xutil.h> +# include <X11/Xatom.h> +#endif + +/* + *---------------------------------------------------------------------- + * + * XInternAtom -- + * + * This procedure simulates the XInternAtom function by calling + * Tk_Uid to get a unique id for every atom. This is only a + * partial implementation, since it doesn't work across + * applications. + * + * Results: + * A new Atom. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +Atom +XInternAtom(display, atom_name, only_if_exists) + Display* display; + _Xconst char* atom_name; + Bool only_if_exists; +{ + static Atom atom = XA_LAST_PREDEFINED; + + display->request++; + return ++atom; +} + +/* + *---------------------------------------------------------------------- + * + * XGetVisualInfo -- + * + * Returns information about the specified visual. + * + * Results: + * Returns a newly allocated XVisualInfo structure. + * + * Side effects: + * Allocates storage. + * + *---------------------------------------------------------------------- + */ + +XVisualInfo * +XGetVisualInfo(display, vinfo_mask, vinfo_template, nitems_return) + Display* display; + long vinfo_mask; + XVisualInfo* vinfo_template; + int* nitems_return; +{ + XVisualInfo *info = (XVisualInfo *)ckalloc(sizeof(XVisualInfo)); + info->visual = DefaultVisual(display, 0); + info->visualid = info->visual->visualid; + info->screen = 0; + info->depth = info->visual->bits_per_rgb; + info->class = info->visual->class; + info->colormap_size = info->visual->map_entries; + info->bits_per_rgb = info->visual->bits_per_rgb; + info->red_mask = info->visual->red_mask; + info->green_mask = info->visual->green_mask; + info->blue_mask = info->visual->blue_mask; + + if (((vinfo_mask & VisualIDMask) + && (vinfo_template->visualid != info->visualid)) + || ((vinfo_mask & VisualScreenMask) + && (vinfo_template->screen != info->screen)) + || ((vinfo_mask & VisualDepthMask) + && (vinfo_template->depth != info->depth)) + || ((vinfo_mask & VisualClassMask) + && (vinfo_template->class != info->class)) + || ((vinfo_mask & VisualColormapSizeMask) + && (vinfo_template->colormap_size != info->colormap_size)) + || ((vinfo_mask & VisualBitsPerRGBMask) + && (vinfo_template->bits_per_rgb != info->bits_per_rgb)) + || ((vinfo_mask & VisualRedMaskMask) + && (vinfo_template->red_mask != info->red_mask)) + || ((vinfo_mask & VisualGreenMaskMask) + && (vinfo_template->green_mask != info->green_mask)) + || ((vinfo_mask & VisualBlueMaskMask) + && (vinfo_template->blue_mask != info->blue_mask)) + ) { + ckfree((char *) info); + return NULL; + } + + *nitems_return = 1; + return info; +} |