input.c revision 2e4f8982
1/* $XTermId: input.c,v 1.355 2016/05/17 12:12:51 tom Exp $ */
2
3/*
4 * Copyright 1999-2015,2016 by Thomas E. Dickey
5 *
6 *                         All Rights Reserved
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the
10 * "Software"), to deal in the Software without restriction, including
11 * without limitation the rights to use, copy, modify, merge, publish,
12 * distribute, sublicense, and/or sell copies of the Software, and to
13 * permit persons to whom the Software is furnished to do so, subject to
14 * the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included
17 * in all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22 * IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
23 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 *
27 * Except as contained in this notice, the name(s) of the above copyright
28 * holders shall not be used in advertising or otherwise to promote the
29 * sale, use or other dealings in this Software without prior written
30 * authorization.
31 *
32 *
33 * Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
34 *
35 *                         All Rights Reserved
36 *
37 * Permission to use, copy, modify, and distribute this software and its
38 * documentation for any purpose and without fee is hereby granted,
39 * provided that the above copyright notice appear in all copies and that
40 * both that copyright notice and this permission notice appear in
41 * supporting documentation, and that the name of Digital Equipment
42 * Corporation not be used in advertising or publicity pertaining to
43 * distribution of the software without specific, written prior permission.
44 *
45 *
46 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
47 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
48 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
49 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
50 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
51 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
52 * SOFTWARE.
53 */
54
55/* input.c */
56
57#include <xterm.h>
58
59#include <X11/keysym.h>
60
61#ifdef VMS
62#include <X11/keysymdef.h>
63#endif
64
65#if HAVE_X11_DECKEYSYM_H
66#include <X11/DECkeysym.h>
67#endif
68
69#if HAVE_X11_SUNKEYSYM_H
70#include <X11/Sunkeysym.h>
71#endif
72
73#if HAVE_X11_XF86KEYSYM_H
74#include <X11/XF86keysym.h>
75#endif
76
77#ifdef HAVE_XKBKEYCODETOKEYSYM
78#include <X11/XKBlib.h>
79#endif
80
81#include <X11/Xutil.h>
82#include <stdio.h>
83#include <ctype.h>
84
85#include <xutf8.h>
86
87#include <data.h>
88#include <fontutils.h>
89#include <xstrings.h>
90#include <xtermcap.h>
91
92/*
93 * Xutil.h has no macro to check for the complete set of function- and
94 * modifier-keys that might be returned.  Fake it.
95 */
96#ifdef XK_ISO_Lock
97#define IsPredefinedKey(n) ((n) >= XK_ISO_Lock && (n) <= XK_Delete)
98#else
99#define IsPredefinedKey(n) ((n) >= XK_BackSpace && (n) <= XK_Delete)
100#endif
101
102#ifdef XK_ISO_Left_Tab
103#define IsTabKey(n) ((n) == XK_Tab || (n) == XK_ISO_Left_Tab)
104#else
105#define IsTabKey(n) ((n) == XK_Tab)
106#endif
107
108#ifndef IsPrivateKeypadKey
109#define IsPrivateKeypadKey(k) (0)
110#endif
111
112#define IsBackarrowToggle(keyboard, keysym, state) \
113	((((keyboard->flags & MODE_DECBKM) == 0) \
114	    ^ ((state & ControlMask) != 0)) \
115	&& (keysym == XK_BackSpace))
116
117#define MAP(from, to) case from: result = to; break
118#define Masked(value,mask) ((value) & (unsigned) (~(mask)))
119
120#define KEYSYM_FMT "0x%04lX"	/* simplify matching <X11/keysymdef.h> */
121
122#define TEK4014_GIN(tw) (tw != 0 && TekScreenOf(tw)->TekGIN)
123
124typedef struct {
125    KeySym keysym;
126    Bool is_fkey;
127    int nbytes;
128#define STRBUFSIZE 500
129    char strbuf[STRBUFSIZE];
130} KEY_DATA;
131
132static
133const char kypd_num[] = " XXXXXXXX\tXXX\rXXXxxxxXXXXXXXXXXXXXXXXXXXXX*+,-./0123456789XXX=";
134/*                       0123456789 abc def0123456789abcdef0123456789abcdef0123456789abcd */
135static
136const char kypd_apl[] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ??????abcdefghijklmnopqrstuvwxyzXXX";
137/*                       0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcd */
138static
139const char curfinal[] = "HDACB  FE";
140
141static int decfuncvalue(KEY_DATA *);
142static void sunfuncvalue(ANSI *, KEY_DATA *);
143static void hpfuncvalue(ANSI *, KEY_DATA *);
144static void scofuncvalue(ANSI *, KEY_DATA *);
145
146static void
147AdjustAfterInput(XtermWidget xw)
148{
149    TScreen *screen = TScreenOf(xw);
150
151    if (screen->scrollkey && screen->topline != 0)
152	WindowScroll(xw, 0, False);
153    if (screen->marginbell) {
154	int col = screen->max_col - screen->nmarginbell;
155	if (screen->bellArmed >= 0) {
156	    if (screen->bellArmed == screen->cur_row) {
157		if (screen->cur_col >= col) {
158		    Bell(xw, XkbBI_MarginBell, 0);
159		    screen->bellArmed = -1;
160		}
161	    } else {
162		screen->bellArmed =
163		    screen->cur_col < col ? screen->cur_row : -1;
164	    }
165	} else if (screen->cur_col < col)
166	    screen->bellArmed = screen->cur_row;
167    }
168}
169
170/*
171 * Return true if the key is on the editing keypad.  This overlaps with
172 * IsCursorKey() and IsKeypadKey() and must be tested before those macros to
173 * distinguish it from them.
174 *
175 * VT220  emulation  uses  the  VT100  numeric  keypad as well as a 6-key
176 * editing keypad. Here's a picture of the VT220 editing keypad:
177 *      +--------+--------+--------+
178 *      | Find   | Insert | Remove |
179 *      +--------+--------+--------+
180 *      | Select | Prev   | Next   |
181 *      +--------+--------+--------+
182 *
183 * and the similar Sun and PC keypads:
184 *      +--------+--------+--------+
185 *      | Insert | Home   | PageUp |
186 *      +--------+--------+--------+
187 *      | Delete | End    | PageDn |
188 *      +--------+--------+--------+
189 */
190static Bool
191IsEditKeypad(XtermWidget xw, KeySym keysym)
192{
193    Bool result;
194
195    switch (keysym) {
196    case XK_Delete:
197	result = !xtermDeleteIsDEL(xw);
198	break;
199    case XK_Prior:
200    case XK_Next:
201    case XK_Insert:
202    case XK_Find:
203    case XK_Select:
204#ifdef DXK_Remove
205    case DXK_Remove:
206#endif
207	result = True;
208	break;
209    default:
210	result = False;
211	break;
212    }
213    return result;
214}
215
216/*
217 * Editing-keypad, plus other editing keys which are not included in the
218 * other macros.
219 */
220static Bool
221IsEditFunctionKey(XtermWidget xw, KeySym keysym)
222{
223    Bool result;
224
225    switch (keysym) {
226#ifdef XK_KP_Delete
227    case XK_KP_Delete:		/* editing key on numeric keypad */
228    case XK_KP_Insert:		/* editing key on numeric keypad */
229#endif
230#ifdef XK_ISO_Left_Tab
231    case XK_ISO_Left_Tab:
232#endif
233	result = True;
234	break;
235    default:
236	result = IsEditKeypad(xw, keysym);
237	break;
238    }
239    return result;
240}
241
242#if OPT_MOD_FKEYS
243#define IS_CTRL(n) ((n) < ANSI_SPA || ((n) >= 0x7f && (n) <= 0x9f))
244
245/*
246 * Return true if the keysym corresponds to one of the control characters,
247 * or one of the common ASCII characters that is combined with control to
248 * make a control character.
249 */
250static Bool
251IsControlInput(KEY_DATA * kd)
252{
253    return ((kd->keysym) >= 0x40 && (kd->keysym) <= 0x7f);
254}
255
256static Bool
257IsControlOutput(KEY_DATA * kd)
258{
259    return IS_CTRL(kd->keysym);
260}
261
262/*
263 * X "normally" has some built-in translations, which the user may want to
264 * suppress when processing the modifyOtherKeys resource.  In particular, the
265 * control modifier applied to some of the keyboard digits gives results for
266 * control characters.
267 *
268 * control 2   0    NUL
269 * control SPC 0    NUL
270 * control @   0    NUL
271 * control `   0    NUL
272 * control 3   0x1b ESC
273 * control 4   0x1c FS
274 * control \   0x1c FS
275 * control 5   0x1d GS
276 * control 6   0x1e RS
277 * control ^   0x1e RS
278 * control ~   0x1e RS
279 * control 7   0x1f US
280 * control /   0x1f US
281 * control _   0x1f US
282 * control 8   0x7f DEL
283 *
284 * It is possible that some other keyboards do not work for these combinations,
285 * but they do work with modifyOtherKeys=2 for the US keyboard:
286 *
287 * control `   0    NUL
288 * control [   0x1b ESC
289 * control \   0x1c FS
290 * control ]   0x1d GS
291 * control ?   0x7f DEL
292 */
293static Bool
294IsControlAlias(KEY_DATA * kd)
295{
296    Bool result = False;
297
298    if (kd->nbytes == 1) {
299	result = IS_CTRL(CharOf(kd->strbuf[0]));
300    }
301    return result;
302}
303
304/*
305 * If we are in the non-VT220/VT52 keyboard state, allow modifiers to add a
306 * parameter to the function-key control sequences.
307 *
308 * Note that we generally cannot capture the Shift-modifier for the numeric
309 * keypad since this is commonly used to act as a type of NumLock, e.g.,
310 * making the keypad send "7" (actually XK_KP_7) where the unshifted code
311 * would be Home (XK_KP_Home).  The other modifiers work, subject to the
312 * usual window-manager assignments.
313 */
314#if OPT_SUNPC_KBD
315#define LegacyAllows(code) (!is_legacy || (code & xw->keyboard.modify_now.allow_keys) != 0)
316#else
317#define LegacyAllows(code) True
318#endif
319
320static Bool
321allowModifierParm(XtermWidget xw, KEY_DATA * kd)
322{
323    TKeyboard *keyboard = &(xw->keyboard);
324    int is_legacy = (keyboard->type == keyboardIsLegacy);
325    Bool result = False;
326
327#if OPT_SUNPC_KBD
328    if (keyboard->type == keyboardIsVT220)
329	is_legacy = True;
330#endif
331
332#if OPT_VT52_MODE
333    if (TScreenOf(xw)->vtXX_level != 0)
334#endif
335    {
336	if (IsCursorKey(kd->keysym) || IsEditFunctionKey(xw, kd->keysym)) {
337	    result = LegacyAllows(2);
338	} else if (IsKeypadKey(kd->keysym)) {
339	    result = LegacyAllows(1);
340	} else if (IsFunctionKey(kd->keysym)) {
341	    result = LegacyAllows(4);
342	} else if (IsMiscFunctionKey(kd->keysym)) {
343	    result = LegacyAllows(8);
344	}
345    }
346    if (xw->keyboard.modify_now.other_keys != 0) {
347	result = True;
348    }
349    return result;
350}
351
352/*
353* Modifier codes:
354*       None                  1
355*       Shift                 2 = 1(None)+1(Shift)
356*       Alt                   3 = 1(None)+2(Alt)
357*       Alt+Shift             4 = 1(None)+1(Shift)+2(Alt)
358*       Ctrl                  5 = 1(None)+4(Ctrl)
359*       Ctrl+Shift            6 = 1(None)+1(Shift)+4(Ctrl)
360*       Ctrl+Alt              7 = 1(None)+2(Alt)+4(Ctrl)
361*       Ctrl+Alt+Shift        8 = 1(None)+1(Shift)+2(Alt)+4(Ctrl)
362*       Meta                  9 = 1(None)+8(Meta)
363*       Meta+Shift           10 = 1(None)+8(Meta)+1(Shift)
364*       Meta+Alt             11 = 1(None)+8(Meta)+2(Alt)
365*       Meta+Alt+Shift       12 = 1(None)+8(Meta)+1(Shift)+2(Alt)
366*       Meta+Ctrl            13 = 1(None)+8(Meta)+4(Ctrl)
367*       Meta+Ctrl+Shift      14 = 1(None)+8(Meta)+1(Shift)+4(Ctrl)
368*       Meta+Ctrl+Alt        15 = 1(None)+8(Meta)+2(Alt)+4(Ctrl)
369*       Meta+Ctrl+Alt+Shift  16 = 1(None)+8(Meta)+1(Shift)+2(Alt)+4(Ctrl)
370*/
371
372unsigned
373xtermParamToState(XtermWidget xw, unsigned param)
374{
375    unsigned result = 0;
376#if OPT_NUM_LOCK
377    if (param > MOD_NONE) {
378	if ((param - MOD_NONE) & MOD_SHIFT)
379	    UIntSet(result, ShiftMask);
380	if ((param - MOD_NONE) & MOD_CTRL)
381	    UIntSet(result, ControlMask);
382	if ((param - MOD_NONE) & MOD_ALT)
383	    UIntSet(result, xw->work.alt_mods);
384	if ((param - MOD_NONE) & MOD_META)
385	    UIntSet(result, xw->work.meta_mods);
386    }
387#else
388    (void) xw;
389    (void) param;
390#endif
391    TRACE(("xtermParamToState(%d) %s%s%s%s -> %#x\n", param,
392	   MODIFIER_NAME(param, MOD_SHIFT),
393	   MODIFIER_NAME(param, MOD_ALT),
394	   MODIFIER_NAME(param, MOD_CTRL),
395	   MODIFIER_NAME(param, MOD_META),
396	   result));
397    return result;
398}
399
400unsigned
401xtermStateToParam(XtermWidget xw, unsigned state)
402{
403    unsigned modify_parm = MOD_NONE;
404
405    TRACE(("xtermStateToParam %#x\n", state));
406#if OPT_NUM_LOCK
407    if (state & ShiftMask) {
408	modify_parm += MOD_SHIFT;
409	UIntClr(state, ShiftMask);
410    }
411    if (state & ControlMask) {
412	modify_parm += MOD_CTRL;
413	UIntClr(state, ControlMask);
414    }
415    if ((state & xw->work.alt_mods) != 0) {
416	modify_parm += MOD_ALT;
417	UIntClr(state, xw->work.alt_mods);
418    }
419    if ((state & xw->work.meta_mods) != 0) {
420	modify_parm += MOD_META;
421	/* UIntClr(state, xw->work.meta_mods); */
422    }
423    if (modify_parm == MOD_NONE)
424	modify_parm = 0;
425#else
426    (void) xw;
427    (void) state;
428#endif
429    TRACE(("...xtermStateToParam %d%s%s%s%s\n", modify_parm,
430	   MODIFIER_NAME(modify_parm, MOD_SHIFT),
431	   MODIFIER_NAME(modify_parm, MOD_ALT),
432	   MODIFIER_NAME(modify_parm, MOD_CTRL),
433	   MODIFIER_NAME(modify_parm, MOD_META)));
434    return modify_parm;
435}
436
437#define computeMaskedModifier(xw, state, mask) \
438	xtermStateToParam(xw, Masked(state, mask))
439
440#if OPT_NUM_LOCK
441static unsigned
442filterAltMeta(unsigned result, unsigned mask, Bool enable, KEY_DATA * kd)
443{
444    if ((result & mask) != 0) {
445	/*
446	 * metaSendsEscape makes the meta key independent of
447	 * modifyOtherKeys.
448	 */
449	if (enable) {
450	    result &= ~mask;
451	}
452	/*
453	 * A bare meta-modifier is independent of modifyOtherKeys.  If it
454	 * is combined with other modifiers, make it depend.
455	 */
456	if ((result & ~(mask)) == 0) {
457	    result &= ~mask;
458	}
459	/*
460	 * Check for special cases of control+meta which are used by some
461	 * applications, e.g., emacs.
462	 */
463	if ((IsControlInput(kd)
464	     || IsControlOutput(kd))
465	    && (result & ControlMask) != 0) {
466	    result &= ~(mask | ControlMask);
467	}
468	if (kd->keysym == XK_Return || kd->keysym == XK_Tab) {
469	    result &= ~(mask | ControlMask);
470	}
471    }
472    return result;
473}
474#endif /* OPT_NUM_LOCK */
475
476/*
477 * Single characters (not function-keys) are allowed fewer modifiers when
478 * interpreting modifyOtherKeys due to pre-existing associations with some
479 * modifiers.
480 */
481static unsigned
482allowedCharModifiers(XtermWidget xw, unsigned state, KEY_DATA * kd)
483{
484#if OPT_NUM_LOCK
485    unsigned a_or_m = (state & (xw->work.meta_mods | xw->work.alt_mods));
486#else
487    unsigned a_or_m = 0;
488#endif
489    /*
490     * Start by limiting the result to the modifiers we might want to use.
491     */
492    unsigned result = (state & (ControlMask
493				| ShiftMask
494				| a_or_m));
495
496    /*
497     * If modifyOtherKeys is off or medium (0 or 1), moderate its effects by
498     * excluding the common cases for modifiers.
499     */
500    if (xw->keyboard.modify_now.other_keys <= 1) {
501	if (IsControlInput(kd)
502	    && Masked(result, ControlMask) == 0) {
503	    /* These keys are already associated with the control-key */
504	    if (xw->keyboard.modify_now.other_keys == 0) {
505		UIntClr(result, ControlMask);
506	    }
507	} else if (kd->keysym == XK_Tab || kd->keysym == XK_Return) {
508	    /* EMPTY */ ;
509	} else if (IsControlAlias(kd)) {
510	    /* Things like "^_" work here... */
511	    if (Masked(result, (ControlMask | ShiftMask)) == 0) {
512		result = 0;
513	    }
514	} else if (!IsControlOutput(kd) && !IsPredefinedKey(kd->keysym)) {
515	    /* Printable keys are already associated with the shift-key */
516	    if (!(result & ControlMask)) {
517		UIntClr(result, ShiftMask);
518	    }
519	}
520#if OPT_NUM_LOCK
521	result = filterAltMeta(result,
522			       xw->work.meta_mods,
523			       TScreenOf(xw)->meta_sends_esc, kd);
524	if (TScreenOf(xw)->alt_is_not_meta) {
525	    result = filterAltMeta(result,
526				   xw->work.alt_mods,
527				   TScreenOf(xw)->alt_sends_esc, kd);
528	}
529#endif
530    }
531    TRACE(("...allowedCharModifiers(state=%u" FMT_MODIFIER_NAMES
532	   ", ch=" KEYSYM_FMT ") ->"
533	   "%u" FMT_MODIFIER_NAMES "\n",
534	   state, ARG_MODIFIER_NAMES(state), kd->keysym,
535	   result, ARG_MODIFIER_NAMES(result)));
536    return result;
537}
538
539/*
540 * Decide if we should generate a special escape sequence for "other" keys
541 * than cursor-, function-keys, etc., as per the modifyOtherKeys resource.
542 */
543static Bool
544ModifyOtherKeys(XtermWidget xw,
545		unsigned state,
546		KEY_DATA * kd,
547		unsigned modify_parm)
548{
549    TKeyboard *keyboard = &(xw->keyboard);
550    Bool result = False;
551
552    /*
553     * Exclude the keys already covered by a modifier.
554     */
555    if (kd->is_fkey
556	|| IsEditFunctionKey(xw, kd->keysym)
557	|| IsKeypadKey(kd->keysym)
558	|| IsCursorKey(kd->keysym)
559	|| IsPFKey(kd->keysym)
560	|| IsMiscFunctionKey(kd->keysym)
561	|| IsPrivateKeypadKey(kd->keysym)) {
562	result = False;
563    } else if (modify_parm != 0) {
564	if (IsBackarrowToggle(keyboard, kd->keysym, state)) {
565	    kd->keysym = XK_Delete;
566	    UIntClr(state, ControlMask);
567	}
568	if (!IsPredefinedKey(kd->keysym)) {
569	    state = allowedCharModifiers(xw, state, kd);
570	}
571	if (state != 0) {
572	    switch (keyboard->modify_now.other_keys) {
573	    default:
574		break;
575	    case 1:
576		switch (kd->keysym) {
577		case XK_BackSpace:
578		case XK_Delete:
579		    result = False;
580		    break;
581#ifdef XK_ISO_Left_Tab
582		case XK_ISO_Left_Tab:
583		    if (computeMaskedModifier(xw, state, ShiftMask))
584			result = True;
585		    break;
586#endif
587		case XK_Return:
588		case XK_Tab:
589		    result = (modify_parm != 0);
590		    break;
591		default:
592		    if (IsControlInput(kd)) {
593			if (state == ControlMask || state == ShiftMask) {
594			    result = False;
595			} else {
596			    result = (modify_parm != 0);
597			}
598		    } else if (IsControlAlias(kd)) {
599			if (state == ShiftMask)
600			    result = False;
601			else if (computeMaskedModifier(xw, state, ControlMask)) {
602			    result = True;
603			}
604		    } else {
605			result = True;
606		    }
607		    break;
608		}
609		break;
610	    case 2:
611		switch (kd->keysym) {
612		case XK_BackSpace:
613		    /* strip ControlMask as per IsBackarrowToggle() */
614		    if (computeMaskedModifier(xw, state, ControlMask))
615			result = True;
616		    break;
617		case XK_Delete:
618		    result = (xtermStateToParam(xw, state) != 0);
619		    break;
620#ifdef XK_ISO_Left_Tab
621		case XK_ISO_Left_Tab:
622		    if (computeMaskedModifier(xw, state, ShiftMask))
623			result = True;
624		    break;
625#endif
626		case XK_Return:
627		case XK_Tab:
628		    result = (modify_parm != 0);
629		    break;
630		default:
631		    if (IsControlInput(kd)) {
632			result = True;
633		    } else if (state == ShiftMask) {
634			result = (kd->keysym == ' ' || kd->keysym == XK_Return);
635		    } else if (computeMaskedModifier(xw, state, ShiftMask)) {
636			result = True;
637		    }
638		    break;
639		}
640		break;
641	    }
642	}
643    }
644    TRACE(("...ModifyOtherKeys(%d,%d) %s\n",
645	   keyboard->modify_now.other_keys,
646	   modify_parm,
647	   BtoS(result)));
648    return result;
649}
650
651#define APPEND_PARM(number) \
652	    reply->a_param[reply->a_nparam] = (ParmType) number; \
653	    reply->a_nparam++
654
655/*
656 * Function-key code 27 happens to not be used in the vt220-style encoding.
657 * xterm uses this to represent modified non-function-keys such as control/+ in
658 * the Sun/PC keyboard layout.  See the modifyOtherKeys resource in the manpage
659 * for more information.
660 */
661static Bool
662modifyOtherKey(ANSI *reply, int input_char, unsigned modify_parm, int format_keys)
663{
664    Bool result = False;
665
666    if (input_char >= 0) {
667	reply->a_type = ANSI_CSI;
668	if (format_keys) {
669	    APPEND_PARM(input_char);
670	    APPEND_PARM(modify_parm);
671	    reply->a_final = 'u';
672	} else {
673	    APPEND_PARM(27);
674	    APPEND_PARM(modify_parm);
675	    APPEND_PARM(input_char);
676	    reply->a_final = '~';
677	}
678
679	result = True;
680    }
681    return result;
682}
683
684static void
685modifyCursorKey(ANSI *reply, int modify, unsigned *modify_parm)
686{
687    if (*modify_parm != 0) {
688	if (modify < 0) {
689	    *modify_parm = 0;
690	}
691	if (modify > 0) {
692	    reply->a_type = ANSI_CSI;	/* SS3 should not have params */
693	}
694	if (modify > 1 && reply->a_nparam == 0) {
695	    APPEND_PARM(1);	/* force modifier to 2nd param */
696	}
697	if (modify > 2) {
698	    reply->a_pintro = '>';	/* mark this as "private" */
699	}
700    }
701}
702#else
703#define modifyCursorKey(reply, modify, parm)	/* nothing */
704#endif /* OPT_MOD_FKEYS */
705
706#if OPT_SUNPC_KBD
707/*
708 * If we have told xterm that our keyboard is really a Sun/PC keyboard, this is
709 * enough to make a reasonable approximation to DEC vt220 numeric and editing
710 * keypads.
711 */
712static KeySym
713TranslateFromSUNPC(KeySym keysym)
714{
715    /* *INDENT-OFF* */
716    static struct {
717	    KeySym before, after;
718    } table[] = {
719#ifdef DXK_Remove
720	{ XK_Delete,       DXK_Remove },
721#endif
722	{ XK_Home,         XK_Find },
723	{ XK_End,          XK_Select },
724#ifdef XK_KP_Home
725	{ XK_Delete,       XK_KP_Decimal },
726	{ XK_KP_Delete,    XK_KP_Decimal },
727	{ XK_KP_Insert,    XK_KP_0 },
728	{ XK_KP_End,       XK_KP_1 },
729	{ XK_KP_Down,      XK_KP_2 },
730	{ XK_KP_Next,      XK_KP_3 },
731	{ XK_KP_Left,      XK_KP_4 },
732	{ XK_KP_Begin,     XK_KP_5 },
733	{ XK_KP_Right,     XK_KP_6 },
734	{ XK_KP_Home,      XK_KP_7 },
735	{ XK_KP_Up,        XK_KP_8 },
736	{ XK_KP_Prior,     XK_KP_9 },
737#endif
738    };
739    /* *INDENT-ON* */
740
741    unsigned n;
742
743    for (n = 0; n < sizeof(table) / sizeof(table[0]); n++) {
744	if (table[n].before == keysym) {
745	    TRACE(("...Input keypad before was " KEYSYM_FMT "\n", keysym));
746	    keysym = table[n].after;
747	    TRACE(("...Input keypad changed to " KEYSYM_FMT "\n", keysym));
748	    break;
749	}
750    }
751    return keysym;
752}
753#endif /* OPT_SUNPC_KBD */
754
755#define VT52_KEYPAD \
756	if_OPT_VT52_MODE(screen,{ \
757		reply.a_type = ANSI_ESC; \
758		reply.a_pintro = '?'; \
759		})
760
761#define VT52_CURSOR_KEYS \
762	if_OPT_VT52_MODE(screen,{ \
763		reply.a_type = ANSI_ESC; \
764		})
765
766#undef  APPEND_PARM
767#define APPEND_PARM(number) \
768	    reply.a_param[reply.a_nparam] = (ParmType) number, \
769	    reply.a_nparam++
770
771#if OPT_MOD_FKEYS
772#define MODIFIER_PARM \
773	if (modify_parm != 0) APPEND_PARM(modify_parm)
774#else
775#define MODIFIER_PARM		/*nothing */
776#endif
777
778/*
779 * Determine if we use the \E[3~ sequence for Delete, or the legacy ^?.  We
780 * maintain the delete_is_del value as 3 states:  unspecified(2), true and
781 * false.  If unspecified, it is handled differently according to whether the
782 * legacy keyboard support is enabled, or if xterm emulates a VT220.
783 *
784 * Once the user (or application) has specified delete_is_del via resource
785 * setting, popup menu or escape sequence, it overrides the keyboard type
786 * rather than the reverse.
787 */
788Bool
789xtermDeleteIsDEL(XtermWidget xw)
790{
791    Bool result = True;
792
793    if (xw->keyboard.type == keyboardIsDefault
794	|| xw->keyboard.type == keyboardIsVT220)
795	result = (TScreenOf(xw)->delete_is_del == True);
796
797    if (xw->keyboard.type == keyboardIsLegacy)
798	result = (TScreenOf(xw)->delete_is_del != False);
799
800    TRACE(("xtermDeleteIsDEL(%d/%d) = %d\n",
801	   xw->keyboard.type,
802	   TScreenOf(xw)->delete_is_del,
803	   result));
804
805    return result;
806}
807
808static Boolean
809lookupKeyData(KEY_DATA * kd, XtermWidget xw, XKeyEvent *event)
810{
811    TScreen *screen = TScreenOf(xw);
812    Boolean result = True;
813#if OPT_I18N_SUPPORT && OPT_INPUT_METHOD
814#if OPT_MOD_FKEYS
815    TKeyboard *keyboard = &(xw->keyboard);
816#endif
817#endif
818
819    TRACE(("%s %#x\n", visibleEventType(event->type), event->keycode));
820
821    kd->keysym = 0;
822    kd->is_fkey = False;
823#if OPT_TCAP_QUERY
824    if (screen->tc_query_code >= 0) {
825	kd->keysym = (KeySym) screen->tc_query_code;
826	kd->is_fkey = screen->tc_query_fkey;
827	if (kd->keysym != XK_BackSpace) {
828	    kd->nbytes = 0;
829	    kd->strbuf[0] = 0;
830	} else {
831	    kd->nbytes = 1;
832	    kd->strbuf[0] = 8;
833	}
834    } else
835#endif
836    {
837#if OPT_I18N_SUPPORT && OPT_INPUT_METHOD
838	TInput *input = lookupTInput(xw, (Widget) xw);
839	if (input && input->xic) {
840	    Status status_return;
841#if OPT_WIDE_CHARS
842	    if (screen->utf8_mode) {
843		kd->nbytes = Xutf8LookupString(input->xic, event,
844					       kd->strbuf, (int) sizeof(kd->strbuf),
845					       &(kd->keysym), &status_return);
846	    } else
847#endif
848	    {
849		kd->nbytes = XmbLookupString(input->xic, event,
850					     kd->strbuf, (int) sizeof(kd->strbuf),
851					     &(kd->keysym), &status_return);
852	    }
853#if OPT_MOD_FKEYS
854	    /*
855	     * Fill-in some code useful with IsControlAlias():
856	     */
857	    if (status_return == XLookupBoth
858		&& kd->nbytes <= 1
859		&& !IsPredefinedKey(kd->keysym)
860		&& (keyboard->modify_now.other_keys > 1)
861		&& !IsControlInput(kd)) {
862		kd->nbytes = 1;
863		kd->strbuf[0] = (char) kd->keysym;
864	    }
865#endif /* OPT_MOD_FKEYS */
866	} else
867#endif /* OPT_I18N_SUPPORT */
868	{
869	    static XComposeStatus compose_status =
870	    {NULL, 0};
871	    kd->nbytes = XLookupString(event,
872				       kd->strbuf, (int) sizeof(kd->strbuf),
873				       &(kd->keysym), &compose_status);
874	}
875	kd->is_fkey = IsFunctionKey(kd->keysym);
876    }
877    return result;
878}
879
880void
881Input(XtermWidget xw,
882      XKeyEvent *event,
883      Bool eightbit)
884{
885    Char *string;
886
887    TKeyboard *keyboard = &(xw->keyboard);
888    TScreen *screen = TScreenOf(xw);
889
890    int j;
891    int key = False;
892    ANSI reply;
893    int dec_code;
894    unsigned modify_parm = 0;
895    int keypad_mode = ((keyboard->flags & MODE_DECKPAM) != 0);
896    unsigned evt_state = event->state;
897    unsigned mod_state;
898    KEY_DATA kd;
899
900    /* Ignore characters typed at the keyboard */
901    if (keyboard->flags & MODE_KAM)
902	return;
903
904    lookupKeyData(&kd, xw, event);
905
906    memset(&reply, 0, sizeof(reply));
907
908    TRACE(("Input keysym "
909	   KEYSYM_FMT
910	   ", %d:'%s'%s" FMT_MODIFIER_NAMES "%s%s%s%s%s%s\n",
911	   kd.keysym,
912	   kd.nbytes,
913	   visibleChars((Char *) kd.strbuf,
914			((kd.nbytes > 0)
915			 ? (unsigned) kd.nbytes
916			 : 0)),
917	   ARG_MODIFIER_NAMES(evt_state),
918	   eightbit ? " 8bit" : " 7bit",
919	   IsKeypadKey(kd.keysym) ? " KeypadKey" : "",
920	   IsCursorKey(kd.keysym) ? " CursorKey" : "",
921	   IsPFKey(kd.keysym) ? " PFKey" : "",
922	   kd.is_fkey ? " FKey" : "",
923	   IsMiscFunctionKey(kd.keysym) ? " MiscFKey" : "",
924	   IsEditFunctionKey(xw, kd.keysym) ? " EditFkey" : ""));
925
926#if OPT_SUNPC_KBD
927    /*
928     * DEC keyboards don't have keypad(+), but do have keypad(,) instead.
929     * Other (Sun, PC) keyboards commonly have keypad(+), but no keypad(,)
930     * - it's a pain for users to work around.
931     */
932    if (keyboard->type == keyboardIsVT220
933	&& (evt_state & ShiftMask) == 0) {
934	if (kd.keysym == XK_KP_Add) {
935	    kd.keysym = XK_KP_Separator;
936	    UIntClr(evt_state, ShiftMask);
937	    TRACE(("...Input keypad(+), change keysym to "
938		   KEYSYM_FMT
939		   "\n",
940		   kd.keysym));
941	}
942	if ((evt_state & ControlMask) != 0
943	    && kd.keysym == XK_KP_Separator) {
944	    kd.keysym = XK_KP_Subtract;
945	    UIntClr(evt_state, ControlMask);
946	    TRACE(("...Input control/keypad(,), change keysym to "
947		   KEYSYM_FMT
948		   "\n",
949		   kd.keysym));
950	}
951    }
952#endif
953
954    /*
955     * The keyboard tables may give us different keypad codes according to
956     * whether NumLock is pressed.  Use this check to simplify the process
957     * of determining whether we generate an escape sequence for a keypad
958     * key, or force it to the value kypd_num[].  There is no fixed
959     * modifier for this feature, so we assume that it is the one assigned
960     * to the NumLock key.
961     *
962     * This check used to try to return the contents of strbuf, but that
963     * does not work properly when a control modifier is given (trash is
964     * returned in the buffer in some cases -- perhaps an X bug).
965     */
966#if OPT_NUM_LOCK
967    if (kd.nbytes == 1
968	&& IsKeypadKey(kd.keysym)
969	&& xw->misc.real_NumLock
970	&& (xw->work.num_lock & evt_state) != 0) {
971	keypad_mode = 0;
972	TRACE(("...Input num_lock, force keypad_mode off\n"));
973    }
974#endif
975
976#if OPT_MOD_FKEYS
977    if (evt_state != 0
978	&& allowModifierParm(xw, &kd)) {
979	modify_parm = xtermStateToParam(xw, evt_state);
980    }
981
982    /*
983     * Shift-tab is often mapped to XK_ISO_Left_Tab which is classified as
984     * IsEditFunctionKey(), and the conversion does not produce any bytes.
985     * Check for this special case so we have data when handling the
986     * modifyOtherKeys resource.
987     */
988    if (keyboard->modify_now.other_keys > 1) {
989	if (IsTabKey(kd.keysym) && kd.nbytes == 0) {
990	    kd.nbytes = 1;
991	    kd.strbuf[0] = '\t';
992	}
993    }
994#ifdef XK_ISO_Left_Tab
995    else if (IsTabKey(kd.keysym)
996	     && kd.nbytes <= 1
997	     && modify_parm == (MOD_NONE + MOD_SHIFT)) {
998	kd.keysym = XK_ISO_Left_Tab;
999    }
1000#endif
1001#endif /* OPT_MOD_FKEYS */
1002
1003    /* VT300 & up: backarrow toggle */
1004    if ((kd.nbytes == 1)
1005	&& IsBackarrowToggle(keyboard, kd.keysym, evt_state)) {
1006	kd.strbuf[0] = ANSI_DEL;
1007	TRACE(("...Input backarrow changed to %d\n", kd.strbuf[0]));
1008    }
1009#if OPT_SUNPC_KBD
1010    /* make an DEC editing-keypad from a Sun or PC editing-keypad */
1011    if (keyboard->type == keyboardIsVT220
1012	&& (kd.keysym != XK_Delete || !xtermDeleteIsDEL(xw)))
1013	kd.keysym = TranslateFromSUNPC(kd.keysym);
1014    else
1015#endif
1016    {
1017#ifdef XK_KP_Home
1018	if (kd.keysym >= XK_KP_Home && kd.keysym <= XK_KP_Begin) {
1019	    TRACE(("...Input keypad before was " KEYSYM_FMT "\n", kd.keysym));
1020	    kd.keysym += (KeySym) (XK_Home - XK_KP_Home);
1021	    TRACE(("...Input keypad changed to " KEYSYM_FMT "\n", kd.keysym));
1022	}
1023#endif
1024    }
1025
1026    /*
1027     * Map the Sun afterthought-keys in as F36 and F37.
1028     */
1029#ifdef SunXK_F36
1030    if (!kd.is_fkey) {
1031	if (kd.keysym == SunXK_F36) {
1032	    kd.keysym = XK_Fn(36);
1033	    kd.is_fkey = True;
1034	}
1035	if (kd.keysym == SunXK_F37) {
1036	    kd.keysym = XK_Fn(37);
1037	    kd.is_fkey = True;
1038	}
1039    }
1040#endif
1041
1042    /*
1043     * Use the control- and shift-modifiers to obtain more function keys than
1044     * the keyboard provides.  We can do this if there is no conflicting use of
1045     * those modifiers:
1046     *
1047     * a) for VT220 keyboard, we use only the control-modifier.  The keyboard
1048     * uses shift-modifier for UDK's.
1049     *
1050     * b) for non-VT220 keyboards, we only have to check if the
1051     * modifyFunctionKeys resource is inactive.
1052     *
1053     * Thereafter, we note when we have a function-key and keep that
1054     * distinction when testing for "function-key" values.
1055     */
1056    if ((evt_state & (ControlMask | ShiftMask)) != 0
1057	&& kd.is_fkey) {
1058
1059	/* VT220 keyboard uses shift for UDK */
1060	if (keyboard->type == keyboardIsVT220
1061	    || keyboard->type == keyboardIsLegacy) {
1062
1063	    TRACE(("...map XK_F%ld", kd.keysym - XK_Fn(1) + 1));
1064	    if (evt_state & ControlMask) {
1065		kd.keysym += (KeySym) xw->misc.ctrl_fkeys;
1066		UIntClr(evt_state, ControlMask);
1067	    }
1068	    TRACE((" to XK_F%ld\n", kd.keysym - XK_Fn(1) + 1));
1069
1070	}
1071#if OPT_MOD_FKEYS
1072	else if (keyboard->modify_now.function_keys < 0) {
1073
1074	    TRACE(("...map XK_F%ld", kd.keysym - XK_Fn(1) + 1));
1075	    if (evt_state & ShiftMask) {
1076		kd.keysym += (KeySym) (xw->misc.ctrl_fkeys * 1);
1077		UIntClr(evt_state, ShiftMask);
1078	    }
1079	    if (evt_state & ControlMask) {
1080		kd.keysym += (KeySym) (xw->misc.ctrl_fkeys * 2);
1081		UIntClr(evt_state, ControlMask);
1082	    }
1083	    TRACE((" to XK_F%ld\n", kd.keysym - XK_Fn(1) + 1));
1084
1085	}
1086	/*
1087	 * Reevaluate the modifier parameter, stripping off the modifiers
1088	 * that we just used.
1089	 */
1090	if (modify_parm) {
1091	    modify_parm = xtermStateToParam(xw, evt_state);
1092	}
1093#endif /* OPT_MOD_FKEYS */
1094    }
1095
1096    /*
1097     * Test for one of the keyboard variants.
1098     */
1099    switch (keyboard->type) {
1100    case keyboardIsHP:
1101	hpfuncvalue(&reply, &kd);
1102	break;
1103    case keyboardIsSCO:
1104	scofuncvalue(&reply, &kd);
1105	break;
1106    case keyboardIsSun:
1107	sunfuncvalue(&reply, &kd);
1108	break;
1109    case keyboardIsTermcap:
1110#if OPT_TCAP_FKEYS
1111	if (xtermcapString(xw, (int) kd.keysym, evt_state))
1112	    return;
1113#endif
1114	break;
1115    case keyboardIsDefault:
1116    case keyboardIsLegacy:
1117    case keyboardIsVT220:
1118	break;
1119    }
1120
1121    if (reply.a_final) {
1122	/*
1123	 * The key symbol matches one of the variants.  Most of those are
1124	 * function-keys, though some cursor- and editing-keys are mixed in.
1125	 */
1126	modifyCursorKey(&reply,
1127			((kd.is_fkey
1128			  || IsMiscFunctionKey(kd.keysym)
1129			  || IsEditFunctionKey(xw, kd.keysym))
1130			 ? keyboard->modify_now.function_keys
1131			 : keyboard->modify_now.cursor_keys),
1132			&modify_parm);
1133	MODIFIER_PARM;
1134	unparseseq(xw, &reply);
1135    } else if (((kd.is_fkey
1136		 || IsMiscFunctionKey(kd.keysym)
1137		 || IsEditFunctionKey(xw, kd.keysym))
1138#if OPT_MOD_FKEYS
1139		&& !ModifyOtherKeys(xw, evt_state, &kd, modify_parm)
1140#endif
1141	       ) || (kd.keysym == XK_Delete
1142		     && ((modify_parm != 0)
1143			 || !xtermDeleteIsDEL(xw)))) {
1144	dec_code = decfuncvalue(&kd);
1145	if ((evt_state & ShiftMask)
1146#if OPT_SUNPC_KBD
1147	    && keyboard->type == keyboardIsVT220
1148#endif
1149	    && ((string = (Char *) udk_lookup(xw, dec_code, &kd.nbytes)) != 0)) {
1150	    UIntClr(evt_state, ShiftMask);
1151	    while (kd.nbytes-- > 0)
1152		unparseputc(xw, CharOf(*string++));
1153	}
1154	/*
1155	 * Interpret F1-F4 as PF1-PF4 for VT52, VT100
1156	 */
1157	else if (keyboard->type != keyboardIsLegacy
1158		 && (dec_code >= 11 && dec_code <= 14)) {
1159	    reply.a_type = ANSI_SS3;
1160	    VT52_CURSOR_KEYS;
1161	    reply.a_final = (Char) A2E(dec_code - 11 + E2A('P'));
1162	    modifyCursorKey(&reply,
1163			    keyboard->modify_now.function_keys,
1164			    &modify_parm);
1165	    MODIFIER_PARM;
1166	    unparseseq(xw, &reply);
1167	} else {
1168	    reply.a_type = ANSI_CSI;
1169	    reply.a_final = 0;
1170
1171#ifdef XK_ISO_Left_Tab
1172	    if (kd.keysym == XK_ISO_Left_Tab) {
1173		reply.a_nparam = 0;
1174		reply.a_final = 'Z';
1175#if OPT_MOD_FKEYS
1176		if (keyboard->modify_now.other_keys > 1
1177		    && computeMaskedModifier(xw, evt_state, ShiftMask))
1178		    modifyOtherKey(&reply, '\t', modify_parm, keyboard->format_keys);
1179#endif
1180	    } else
1181#endif /* XK_ISO_Left_Tab */
1182	    {
1183		reply.a_nparam = 1;
1184#if OPT_MOD_FKEYS
1185		if (kd.is_fkey) {
1186		    modifyCursorKey(&reply,
1187				    keyboard->modify_now.function_keys,
1188				    &modify_parm);
1189		}
1190		MODIFIER_PARM;
1191#endif
1192		reply.a_param[0] = (ParmType) dec_code;
1193		reply.a_final = '~';
1194	    }
1195	    if (reply.a_final != 0
1196		&& (reply.a_nparam == 0 || reply.a_param[0] >= 0))
1197		unparseseq(xw, &reply);
1198	}
1199	key = True;
1200    } else if (IsPFKey(kd.keysym)) {
1201	reply.a_type = ANSI_SS3;
1202	reply.a_final = (Char) ((kd.keysym - XK_KP_F1) + 'P');
1203	VT52_CURSOR_KEYS;
1204	MODIFIER_PARM;
1205	unparseseq(xw, &reply);
1206	key = True;
1207    } else if (IsKeypadKey(kd.keysym)) {
1208	if (keypad_mode) {
1209	    reply.a_type = ANSI_SS3;
1210	    reply.a_final = (Char) (kypd_apl[kd.keysym - XK_KP_Space]);
1211	    VT52_KEYPAD;
1212	    MODIFIER_PARM;
1213	    unparseseq(xw, &reply);
1214	} else {
1215	    unparseputc(xw, kypd_num[kd.keysym - XK_KP_Space]);
1216	}
1217	key = True;
1218    } else if (IsCursorKey(kd.keysym)) {
1219	if (keyboard->flags & MODE_DECCKM) {
1220	    reply.a_type = ANSI_SS3;
1221	} else {
1222	    reply.a_type = ANSI_CSI;
1223	}
1224	modifyCursorKey(&reply, keyboard->modify_now.cursor_keys, &modify_parm);
1225	reply.a_final = (Char) (curfinal[kd.keysym - XK_Home]);
1226	VT52_CURSOR_KEYS;
1227	MODIFIER_PARM;
1228	unparseseq(xw, &reply);
1229	key = True;
1230    } else if (kd.nbytes > 0) {
1231
1232#if OPT_TEK4014
1233	if (TEK4014_GIN(tekWidget)) {
1234	    TekEnqMouse(tekWidget, kd.strbuf[0]);
1235	    TekGINoff(tekWidget);
1236	    kd.nbytes--;
1237	    for (j = 0; j < kd.nbytes; ++j) {
1238		kd.strbuf[j] = kd.strbuf[j + 1];
1239	    }
1240	}
1241#endif
1242#if OPT_MOD_FKEYS
1243	if ((keyboard->modify_now.other_keys > 0)
1244	    && ModifyOtherKeys(xw, evt_state, &kd, modify_parm)
1245	    && (mod_state = allowedCharModifiers(xw, evt_state, &kd)) != 0) {
1246	    int input_char;
1247
1248	    evt_state = mod_state;
1249
1250	    modify_parm = xtermStateToParam(xw, evt_state);
1251
1252	    /*
1253	     * We want to show a keycode that corresponds to the 8-bit value
1254	     * of the key.  If the keysym is less than 256, that is good
1255	     * enough.  Special keys such as Tab may result in a value that
1256	     * is usable as well.  For the latter (special cases), try to use
1257	     * the result from the X library lookup.
1258	     */
1259	    input_char = ((kd.keysym < 256)
1260			  ? (int) kd.keysym
1261			  : ((kd.nbytes == 1)
1262			     ? CharOf(kd.strbuf[0])
1263			     : -1));
1264
1265	    TRACE(("...modifyOtherKeys %d;%d\n", modify_parm, input_char));
1266	    if (modifyOtherKey(&reply, input_char, modify_parm, keyboard->format_keys)) {
1267		unparseseq(xw, &reply);
1268	    } else {
1269		Bell(xw, XkbBI_MinorError, 0);
1270	    }
1271	} else
1272#endif /* OPT_MOD_FKEYS */
1273	{
1274	    int prefix = 0;
1275
1276#if OPT_NUM_LOCK
1277	    /*
1278	     * Send ESC if we have a META modifier and metaSendsEcape is true.
1279	     * Like eightBitInput, except that it is not associated with
1280	     * terminal settings.
1281	     */
1282	    if (kd.nbytes != 0) {
1283		if (screen->meta_sends_esc
1284		    && (evt_state & xw->work.meta_mods) != 0) {
1285		    TRACE(("...input-char is modified by META\n"));
1286		    UIntClr(evt_state, xw->work.meta_mods);
1287		    eightbit = False;
1288		    prefix = ANSI_ESC;
1289		} else if (eightbit) {
1290		    /* it might be overridden, but this helps for debugging */
1291		    TRACE(("...input-char is shifted by META\n"));
1292		}
1293		if (screen->alt_is_not_meta
1294		    && (evt_state & xw->work.alt_mods) != 0) {
1295		    UIntClr(evt_state, xw->work.alt_mods);
1296		    if (screen->alt_sends_esc) {
1297			TRACE(("...input-char is modified by ALT\n"));
1298			eightbit = False;
1299			prefix = ANSI_ESC;
1300		    } else if (!eightbit) {
1301			TRACE(("...input-char is shifted by ALT\n"));
1302			eightbit = True;
1303		    }
1304		}
1305	    }
1306#endif
1307	    /*
1308	     * If metaSendsEscape is false, fall through to this chunk, which
1309	     * implements the eightBitInput resource.
1310	     *
1311	     * It is normally executed when the user presses Meta plus a
1312	     * printable key, e.g., Meta+space.  The presence of the Meta
1313	     * modifier is not guaranteed since what really happens is the
1314	     * "insert-eight-bit" or "insert-seven-bit" action, which we
1315	     * distinguish by the eightbit parameter to this function.  So the
1316	     * eightBitInput resource really means that we use this shifting
1317	     * logic in the "insert-eight-bit" action.
1318	     */
1319	    if (eightbit && (kd.nbytes == 1) && screen->input_eight_bits) {
1320		IChar ch = CharOf(kd.strbuf[0]);
1321		if ((ch < 128) && (screen->eight_bit_meta == ebTrue)) {
1322		    kd.strbuf[0] |= (char) 0x80;
1323		    TRACE(("...input shift from %d to %d (%#x to %#x)\n",
1324			   ch, CharOf(kd.strbuf[0]),
1325			   ch, CharOf(kd.strbuf[0])));
1326#if OPT_WIDE_CHARS
1327		    if (screen->utf8_mode) {
1328			/*
1329			 * We could interpret the incoming code as "in the
1330			 * current locale", but it's simpler to treat it as
1331			 * a Unicode value to translate to UTF-8.
1332			 */
1333			ch = CharOf(kd.strbuf[0]);
1334			kd.nbytes = 2;
1335			kd.strbuf[0] = (char) (0xc0 | ((ch >> 6) & 0x3));
1336			kd.strbuf[1] = (char) (0x80 | (ch & 0x3f));
1337			TRACE(("...encoded %#x in UTF-8 as %#x,%#x\n",
1338			       ch, CharOf(kd.strbuf[0]), CharOf(kd.strbuf[1])));
1339		    }
1340#endif
1341		}
1342		eightbit = False;
1343	    }
1344#if OPT_WIDE_CHARS
1345	    if (kd.nbytes == 1)	/* cannot do NRC on UTF-8, for instance */
1346#endif
1347	    {
1348		/* VT220 & up: National Replacement Characters */
1349		if ((xw->flags & NATIONAL) != 0) {
1350		    unsigned cmp = xtermCharSetIn(screen,
1351						  CharOf(kd.strbuf[0]),
1352						  screen->keyboard_dialect[0]);
1353		    TRACE(("...input NRC %d, %s %d\n",
1354			   CharOf(kd.strbuf[0]),
1355			   (CharOf(kd.strbuf[0]) == cmp)
1356			   ? "unchanged"
1357			   : "changed to",
1358			   CharOf(cmp)));
1359		    kd.strbuf[0] = (char) cmp;
1360		} else if (eightbit) {
1361		    prefix = ANSI_ESC;
1362		} else if (kd.strbuf[0] == '?'
1363			   && (evt_state & ControlMask) != 0) {
1364		    kd.strbuf[0] = ANSI_DEL;
1365		    /* UIntClr(evt_state, ControlMask); */
1366		}
1367	    }
1368	    if (prefix != 0)
1369		unparseputc(xw, prefix);	/* escape */
1370	    for (j = 0; j < kd.nbytes; ++j)
1371		unparseputc(xw, CharOf(kd.strbuf[j]));
1372	}
1373	key = ((kd.keysym != ANSI_XOFF) && (kd.keysym != ANSI_XON));
1374    }
1375    unparse_end(xw);
1376
1377    if (key && !TEK4014_ACTIVE(xw))
1378	AdjustAfterInput(xw);
1379
1380    xtermShowPointer(xw, False);
1381    return;
1382}
1383
1384void
1385StringInput(XtermWidget xw, const Char *string, size_t nbytes)
1386{
1387    TRACE(("InputString (%s,%lu)\n",
1388	   visibleChars(string, (unsigned) nbytes),
1389	   (unsigned long) nbytes));
1390#if OPT_TEK4014
1391    if (nbytes && TEK4014_GIN(tekWidget)) {
1392	TekEnqMouse(tekWidget, *string++);
1393	TekGINoff(tekWidget);
1394	nbytes--;
1395    }
1396#endif
1397    while (nbytes-- != 0)
1398	unparseputc(xw, *string++);
1399    if (!TEK4014_ACTIVE(xw))
1400	AdjustAfterInput(xw);
1401    unparse_end(xw);
1402}
1403
1404/* These definitions are DEC-style (e.g., vt320) */
1405static int
1406decfuncvalue(KEY_DATA * kd)
1407{
1408    int result;
1409
1410    if (kd->is_fkey) {
1411	switch (kd->keysym) {
1412	    MAP(XK_Fn(1), 11);
1413	    MAP(XK_Fn(2), 12);
1414	    MAP(XK_Fn(3), 13);
1415	    MAP(XK_Fn(4), 14);
1416	    MAP(XK_Fn(5), 15);
1417	    MAP(XK_Fn(6), 17);
1418	    MAP(XK_Fn(7), 18);
1419	    MAP(XK_Fn(8), 19);
1420	    MAP(XK_Fn(9), 20);
1421	    MAP(XK_Fn(10), 21);
1422	    MAP(XK_Fn(11), 23);
1423	    MAP(XK_Fn(12), 24);
1424	    MAP(XK_Fn(13), 25);
1425	    MAP(XK_Fn(14), 26);
1426	    MAP(XK_Fn(15), 28);
1427	    MAP(XK_Fn(16), 29);
1428	    MAP(XK_Fn(17), 31);
1429	    MAP(XK_Fn(18), 32);
1430	    MAP(XK_Fn(19), 33);
1431	    MAP(XK_Fn(20), 34);
1432	default:
1433	    /* after F20 the codes are made up and do not correspond to any
1434	     * real terminal.  So they are simply numbered sequentially.
1435	     */
1436	    result = 42 + (int) (kd->keysym - XK_Fn(21));
1437	    break;
1438	}
1439    } else {
1440	switch (kd->keysym) {
1441	    MAP(XK_Find, 1);
1442	    MAP(XK_Insert, 2);
1443	    MAP(XK_Delete, 3);
1444#ifdef XK_KP_Insert
1445	    MAP(XK_KP_Insert, 2);
1446	    MAP(XK_KP_Delete, 3);
1447#endif
1448#ifdef DXK_Remove
1449	    MAP(DXK_Remove, 3);
1450#endif
1451	    MAP(XK_Select, 4);
1452	    MAP(XK_Prior, 5);
1453	    MAP(XK_Next, 6);
1454#ifdef XK_ISO_Left_Tab
1455	    MAP(XK_ISO_Left_Tab, 'Z');
1456#endif
1457	    MAP(XK_Help, 28);
1458	    MAP(XK_Menu, 29);
1459	default:
1460	    result = -1;
1461	    break;
1462	}
1463    }
1464    return result;
1465}
1466
1467static void
1468hpfuncvalue(ANSI *reply, KEY_DATA * kd)
1469{
1470#if OPT_HP_FUNC_KEYS
1471    int result;
1472
1473    if (kd->is_fkey) {
1474	switch (kd->keysym) {
1475	    MAP(XK_Fn(1), 'p');
1476	    MAP(XK_Fn(2), 'q');
1477	    MAP(XK_Fn(3), 'r');
1478	    MAP(XK_Fn(4), 's');
1479	    MAP(XK_Fn(5), 't');
1480	    MAP(XK_Fn(6), 'u');
1481	    MAP(XK_Fn(7), 'v');
1482	    MAP(XK_Fn(8), 'w');
1483	default:
1484	    result = -1;
1485	    break;
1486	}
1487    } else {
1488	switch (kd->keysym) {
1489	    MAP(XK_Up, 'A');
1490	    MAP(XK_Down, 'B');
1491	    MAP(XK_Right, 'C');
1492	    MAP(XK_Left, 'D');
1493	    MAP(XK_End, 'F');
1494	    MAP(XK_Clear, 'J');
1495	    MAP(XK_Delete, 'P');
1496	    MAP(XK_Insert, 'Q');
1497	    MAP(XK_Next, 'S');
1498	    MAP(XK_Prior, 'T');
1499	    MAP(XK_Home, 'h');
1500#ifdef XK_KP_Insert
1501	    MAP(XK_KP_Delete, 'P');
1502	    MAP(XK_KP_Insert, 'Q');
1503#endif
1504#ifdef DXK_Remove
1505	    MAP(DXK_Remove, 'P');
1506#endif
1507	    MAP(XK_Select, 'F');
1508	    MAP(XK_Find, 'h');
1509	default:
1510	    result = -1;
1511	    break;
1512	}
1513    }
1514    if (result > 0) {
1515	reply->a_type = ANSI_ESC;
1516	reply->a_final = (Char) result;
1517    }
1518#else
1519    (void) reply;
1520    (void) kd;
1521#endif /* OPT_HP_FUNC_KEYS */
1522}
1523
1524static void
1525scofuncvalue(ANSI *reply, KEY_DATA * kd)
1526{
1527#if OPT_SCO_FUNC_KEYS
1528    int result;
1529
1530    if (kd->is_fkey) {
1531	switch (kd->keysym) {
1532	    MAP(XK_Fn(1), 'M');
1533	    MAP(XK_Fn(2), 'N');
1534	    MAP(XK_Fn(3), 'O');
1535	    MAP(XK_Fn(4), 'P');
1536	    MAP(XK_Fn(5), 'Q');
1537	    MAP(XK_Fn(6), 'R');
1538	    MAP(XK_Fn(7), 'S');
1539	    MAP(XK_Fn(8), 'T');
1540	    MAP(XK_Fn(9), 'U');
1541	    MAP(XK_Fn(10), 'V');
1542	    MAP(XK_Fn(11), 'W');
1543	    MAP(XK_Fn(12), 'X');
1544	    MAP(XK_Fn(13), 'Y');
1545	    MAP(XK_Fn(14), 'Z');
1546	    MAP(XK_Fn(15), 'a');
1547	    MAP(XK_Fn(16), 'b');
1548	    MAP(XK_Fn(17), 'c');
1549	    MAP(XK_Fn(18), 'd');
1550	    MAP(XK_Fn(19), 'e');
1551	    MAP(XK_Fn(20), 'f');
1552	    MAP(XK_Fn(21), 'g');
1553	    MAP(XK_Fn(22), 'h');
1554	    MAP(XK_Fn(23), 'i');
1555	    MAP(XK_Fn(24), 'j');
1556	    MAP(XK_Fn(25), 'k');
1557	    MAP(XK_Fn(26), 'l');
1558	    MAP(XK_Fn(27), 'm');
1559	    MAP(XK_Fn(28), 'n');
1560	    MAP(XK_Fn(29), 'o');
1561	    MAP(XK_Fn(30), 'p');
1562	    MAP(XK_Fn(31), 'q');
1563	    MAP(XK_Fn(32), 'r');
1564	    MAP(XK_Fn(33), 's');
1565	    MAP(XK_Fn(34), 't');
1566	    MAP(XK_Fn(35), 'u');
1567	    MAP(XK_Fn(36), 'v');
1568	    MAP(XK_Fn(37), 'w');
1569	    MAP(XK_Fn(38), 'x');
1570	    MAP(XK_Fn(39), 'y');
1571	    MAP(XK_Fn(40), 'z');
1572	    MAP(XK_Fn(41), '@');
1573	    MAP(XK_Fn(42), '[');
1574	    MAP(XK_Fn(43), '\\');
1575	    MAP(XK_Fn(44), ']');
1576	    MAP(XK_Fn(45), '^');
1577	    MAP(XK_Fn(46), '_');
1578	    MAP(XK_Fn(47), '`');
1579	    MAP(XK_Fn(48), L_CURL);
1580	default:
1581	    result = -1;
1582	    break;
1583	}
1584    } else {
1585	switch (kd->keysym) {
1586	    MAP(XK_Up, 'A');
1587	    MAP(XK_Down, 'B');
1588	    MAP(XK_Right, 'C');
1589	    MAP(XK_Left, 'D');
1590	    MAP(XK_Begin, 'E');
1591	    MAP(XK_End, 'F');
1592	    MAP(XK_Insert, 'L');
1593	    MAP(XK_Next, 'G');
1594	    MAP(XK_Prior, 'I');
1595	    MAP(XK_Home, 'H');
1596#ifdef XK_KP_Insert
1597	    MAP(XK_KP_Insert, 'L');
1598#endif
1599	default:
1600	    result = -1;
1601	    break;
1602	}
1603    }
1604    if (result > 0) {
1605	reply->a_type = ANSI_CSI;
1606	reply->a_final = (Char) result;
1607    }
1608#else
1609    (void) reply;
1610    (void) kd;
1611#endif /* OPT_SCO_FUNC_KEYS */
1612}
1613
1614static void
1615sunfuncvalue(ANSI *reply, KEY_DATA * kd)
1616{
1617#if OPT_SUN_FUNC_KEYS
1618    ParmType result;
1619
1620    if (kd->is_fkey) {
1621	switch (kd->keysym) {
1622	    /* kf1-kf20 are numbered sequentially */
1623	    MAP(XK_Fn(1), 224);
1624	    MAP(XK_Fn(2), 225);
1625	    MAP(XK_Fn(3), 226);
1626	    MAP(XK_Fn(4), 227);
1627	    MAP(XK_Fn(5), 228);
1628	    MAP(XK_Fn(6), 229);
1629	    MAP(XK_Fn(7), 230);
1630	    MAP(XK_Fn(8), 231);
1631	    MAP(XK_Fn(9), 232);
1632	    MAP(XK_Fn(10), 233);
1633	    MAP(XK_Fn(11), 192);
1634	    MAP(XK_Fn(12), 193);
1635	    MAP(XK_Fn(13), 194);
1636	    MAP(XK_Fn(14), 195);	/* kund */
1637	    MAP(XK_Fn(15), 196);
1638	    MAP(XK_Fn(16), 197);	/* kcpy */
1639	    MAP(XK_Fn(17), 198);
1640	    MAP(XK_Fn(18), 199);
1641	    MAP(XK_Fn(19), 200);	/* kfnd */
1642	    MAP(XK_Fn(20), 201);
1643
1644	    /* kf31-kf36 are numbered sequentially */
1645	    MAP(XK_Fn(21), 208);	/* kf31 */
1646	    MAP(XK_Fn(22), 209);
1647	    MAP(XK_Fn(23), 210);
1648	    MAP(XK_Fn(24), 211);
1649	    MAP(XK_Fn(25), 212);
1650	    MAP(XK_Fn(26), 213);	/* kf36 */
1651
1652	    /* kf37-kf47 are interspersed with keypad keys */
1653	    MAP(XK_Fn(27), 214);	/* khome */
1654	    MAP(XK_Fn(28), 215);	/* kf38 */
1655	    MAP(XK_Fn(29), 216);	/* kpp */
1656	    MAP(XK_Fn(30), 217);	/* kf40 */
1657	    MAP(XK_Fn(31), 218);	/* kb2 */
1658	    MAP(XK_Fn(32), 219);	/* kf42 */
1659	    MAP(XK_Fn(33), 220);	/* kend */
1660	    MAP(XK_Fn(34), 221);	/* kf44 */
1661	    MAP(XK_Fn(35), 222);	/* knp */
1662	    MAP(XK_Fn(36), 234);	/* kf46 */
1663	    MAP(XK_Fn(37), 235);	/* kf47 */
1664	default:
1665	    result = -1;
1666	    break;
1667	}
1668    } else {
1669	switch (kd->keysym) {
1670	    MAP(XK_Help, 196);	/* khlp */
1671	    MAP(XK_Menu, 197);
1672
1673	    MAP(XK_Find, 1);
1674	    MAP(XK_Insert, 2);	/* kich1 */
1675	    MAP(XK_Delete, 3);
1676#ifdef XK_KP_Insert
1677	    MAP(XK_KP_Insert, 2);
1678	    MAP(XK_KP_Delete, 3);
1679#endif
1680#ifdef DXK_Remove
1681	    MAP(DXK_Remove, 3);
1682#endif
1683	    MAP(XK_Select, 4);
1684
1685	    MAP(XK_Prior, 216);
1686	    MAP(XK_Next, 222);
1687	    MAP(XK_Home, 214);
1688	    MAP(XK_End, 220);
1689	    MAP(XK_Begin, 218);	/* kf41=kb2 */
1690
1691	default:
1692	    result = -1;
1693	    break;
1694	}
1695    }
1696    if (result > 0) {
1697	reply->a_type = ANSI_CSI;
1698	reply->a_nparam = 1;
1699	reply->a_param[0] = result;
1700	reply->a_final = 'z';
1701    } else if (IsCursorKey(kd->keysym)) {
1702	reply->a_type = ANSI_SS3;
1703	reply->a_final = (Char) curfinal[kd->keysym - XK_Home];
1704    }
1705#else
1706    (void) reply;
1707    (void) kd;
1708#endif /* OPT_SUN_FUNC_KEYS */
1709}
1710
1711#if OPT_NUM_LOCK
1712#define isName(c) ((c) == '_' || (c) == '-' || isalnum(CharOf(c)))
1713
1714static const char *
1715skipName(const char *s)
1716{
1717    while (*s != '\0' && isName(CharOf(*s)))
1718	++s;
1719    return s;
1720}
1721
1722/*
1723 * Found a ":" in a translation, check what is past it to see if it contains
1724 * any of the insert-text action names.
1725 */
1726static Boolean
1727keyCanInsert(const char *parse)
1728{
1729    Boolean result = False;
1730    Boolean escape = False;
1731    Boolean quoted = False;
1732
1733    static const char *const table[] =
1734    {
1735	"insert",
1736	"insert-seven-bit",
1737	"insert-eight-bit",
1738	"string",
1739    };
1740    Cardinal n;
1741
1742    while (*parse != '\0' && *parse != '\n') {
1743	int ch = CharOf(*parse++);
1744	if (escape) {
1745	    escape = False;
1746	} else if (ch == '\\') {
1747	    escape = True;
1748	} else if (ch == '"') {
1749	    quoted = (Boolean) !quoted;
1750	} else if (!quoted && isName(ch)) {
1751	    const char *next = skipName(--parse);
1752	    size_t need = (size_t) (next - parse);
1753
1754	    for (n = 0; n < XtNumber(table); ++n) {
1755		if (need == strlen(table[n])
1756		    && !strncmp(parse, table[n], need)) {
1757		    result = True;
1758		    break;
1759		}
1760	    }
1761	    parse = next;
1762	}
1763
1764    }
1765    return result;
1766}
1767
1768/*
1769 * Strip the entire action, to avoid matching it.
1770 */
1771static char *
1772stripAction(char *base, char *last)
1773{
1774    while (last != base) {
1775	if (*--last == '\n') {
1776	    break;
1777	}
1778    }
1779    return last;
1780}
1781
1782static char *
1783stripBlanks(char *base, char *last)
1784{
1785    while (last != base) {
1786	int ch = CharOf(last[-1]);
1787	if (ch != ' ' && ch != '\t')
1788	    break;
1789	--last;
1790    }
1791    return last;
1792}
1793
1794/*
1795 * Strip unneeded whitespace from a translations resource, mono-casing and
1796 * returning a malloc'd copy of the result.
1797 */
1798static char *
1799stripTranslations(const char *s, Bool onlyInsert)
1800{
1801    char *dst = 0;
1802
1803    if (s != 0) {
1804	dst = TypeMallocN(char, strlen(s) + 1);
1805
1806	if (dst != 0) {
1807	    int state = 0;
1808	    int prv = 0;
1809	    char *d = dst;
1810
1811	    TRACE(("stripping:\n%s\n", s));
1812	    while (*s != '\0') {
1813		int ch = *s++;
1814		if (ch == '\n') {
1815		    if (d != dst)
1816			*d++ = (char) ch;
1817		    state = 0;
1818		} else if (strchr(":!#", ch) != 0) {
1819		    d = stripBlanks(dst, d);
1820		    if (onlyInsert && (ch == ':') && !keyCanInsert(s)) {
1821			d = stripAction(dst, d);
1822		    }
1823		    state = -1;
1824		} else if (state >= 0) {
1825		    if (isspace(CharOf(ch))) {
1826			if (state == 0 || strchr("<>~ \t", prv))
1827			    continue;
1828		    } else if (strchr("<>~", ch)) {
1829			d = stripBlanks(dst, d);
1830		    }
1831		    *d++ = x_toupper(ch);
1832		    ++state;
1833		}
1834		prv = ch;
1835	    }
1836	    *d = '\0';
1837	    TRACE(("...result:\n%s\n", dst));
1838	}
1839    }
1840    return dst;
1841}
1842
1843/*
1844 * Make a simple check to see if a given translations keyword appears in
1845 * xterm's translations resource.  It does not attempt to parse the strings,
1846 * just makes a case-independent check and ensures that the ends of the match
1847 * are on token-boundaries.
1848 *
1849 * That this can only retrieve translations that are given as resource values;
1850 * the default translations in charproc.c for example are not retrievable by
1851 * any interface to X.
1852 *
1853 * Also:  We can retrieve only the most-specified translation resource.  For
1854 * example, if the resource file specifies both "*translations" and
1855 * "XTerm*translations", we see only the latter.
1856 */
1857static Bool
1858TranslationsUseKeyword(Widget w, char **cache, const char *keyword, Bool onlyInsert)
1859{
1860    Bool result = False;
1861    char *copy;
1862    char *test;
1863
1864    if ((test = stripTranslations(keyword, onlyInsert)) != 0) {
1865	if (*cache == 0) {
1866	    String data = 0;
1867	    getKeymapResources(w, "vt100", "VT100", XtRString, &data, sizeof(data));
1868	    if (data != 0 && (copy = stripTranslations(data, onlyInsert)) != 0) {
1869		*cache = copy;
1870	    }
1871	}
1872
1873	if (*cache != 0) {
1874	    char *p = *cache;
1875	    int state = 0;
1876	    int now = ' ';
1877
1878	    while (*p != 0) {
1879		int prv = now;
1880		now = *p++;
1881		if (now == ':'
1882		    || now == '!') {
1883		    state = -1;
1884		} else if (now == '\n') {
1885		    state = 0;
1886		} else if (state >= 0) {
1887		    if (now == test[state]) {
1888			if ((state != 0
1889			     || !isName(prv))
1890			    && ((test[++state] == 0)
1891				&& !isName(*p))) {
1892			    result = True;
1893			    break;
1894			}
1895		    } else {
1896			state = 0;
1897		    }
1898		}
1899	    }
1900	}
1901	free(test);
1902    }
1903    TRACE(("TranslationsUseKeyword(%p, %s) = %d\n",
1904	   (void *) w, keyword, result));
1905    return result;
1906}
1907
1908static Bool
1909xtermHasTranslation(XtermWidget xw, const char *keyword, Bool onlyInsert)
1910{
1911    return (TranslationsUseKeyword(SHELL_OF(xw),
1912				   &(xw->keyboard.shell_translations),
1913				   keyword,
1914				   onlyInsert)
1915	    || TranslationsUseKeyword((Widget) xw,
1916				      &(xw->keyboard.xterm_translations),
1917				      keyword,
1918				      onlyInsert));
1919}
1920
1921#if OPT_EXTRA_PASTE
1922static void
1923addTranslation(XtermWidget xw, const char *fromString, const char *toString)
1924{
1925    size_t have = (xw->keyboard.extra_translations
1926		   ? strlen(xw->keyboard.extra_translations)
1927		   : 0);
1928    size_t need = (((have != 0) ? (have + 4) : 0)
1929		   + strlen(fromString)
1930		   + strlen(toString)
1931		   + 6);
1932
1933    if (!xtermHasTranslation(xw, fromString, False)) {
1934	xw->keyboard.extra_translations
1935	    = TypeRealloc(char, need, xw->keyboard.extra_translations);
1936	if ((xw->keyboard.extra_translations) != 0) {
1937	    TRACE(("adding %s: %s\n", fromString, toString));
1938	    if (have)
1939		strcat(xw->keyboard.extra_translations, " \\n\\");
1940	    sprintf(xw->keyboard.extra_translations, "%s: %s",
1941		    fromString, toString);
1942	    TRACE(("...{%s}\n", xw->keyboard.extra_translations));
1943	}
1944    }
1945}
1946#endif
1947
1948#define SaveMask(name)	xw->work.name |= (unsigned) mask;\
1949			TRACE(("SaveMask(%#x -> %s) %#x (%#x is%s modifier)\n", \
1950				(unsigned) keysym, #name, \
1951				xw->work.name, (unsigned) mask, \
1952				ModifierName((unsigned) mask)));
1953/*
1954 * Determine which modifier mask (if any) applies to the Num_Lock keysym.
1955 *
1956 * Also, determine which modifiers are associated with the ALT keys, so we can
1957 * send that information as a parameter for special keys in Sun/PC keyboard
1958 * mode.  However, if the ALT modifier is used in translations, we do not want
1959 * to confuse things by sending the parameter.
1960 */
1961void
1962VTInitModifiers(XtermWidget xw)
1963{
1964    Display *dpy = XtDisplay(xw);
1965    XModifierKeymap *keymap = XGetModifierMapping(dpy);
1966    KeySym keysym;
1967    int min_keycode, max_keycode, keysyms_per_keycode = 0;
1968
1969    if (keymap != 0) {
1970	KeySym *theMap;
1971	int keycode_count;
1972
1973	TRACE(("VTInitModifiers\n"));
1974
1975	XDisplayKeycodes(dpy, &min_keycode, &max_keycode);
1976	keycode_count = (max_keycode - min_keycode + 1);
1977	theMap = XGetKeyboardMapping(dpy,
1978				     (KeyCode) min_keycode,
1979				     keycode_count,
1980				     &keysyms_per_keycode);
1981
1982	if (theMap != 0) {
1983	    int i, j, k, l;
1984	    unsigned long mask;
1985
1986#if OPT_EXTRA_PASTE
1987	    /*
1988	     * Assume that if we can find the paste keysym in the X keyboard
1989	     * mapping that the server allows the corresponding translations
1990	     * resource.
1991	     */
1992	    int limit = (max_keycode - min_keycode) * keysyms_per_keycode;
1993	    for (i = 0; i < limit; ++i) {
1994#ifdef XF86XK_Paste
1995		if (theMap[i] == XF86XK_Paste) {
1996		    TRACE(("keyboard has XF86XK_Paste\n"));
1997		    addTranslation(xw,
1998				   ":<KeyPress> XF86Paste",
1999				   "insert-selection(SELECT, CUT_BUFFER0)");
2000		}
2001#endif
2002#ifdef SunXK_Paste
2003		if (theMap[i] == SunXK_Paste) {
2004		    TRACE(("keyboard has SunXK_Paste\n"));
2005		    addTranslation(xw,
2006				   ":<KeyPress> SunPaste",
2007				   "insert-selection(SELECT, CUT_BUFFER0)");
2008		}
2009#endif
2010	    }
2011#endif /* OPT_EXTRA_PASTE */
2012
2013	    for (i = k = 0, mask = 1; i < 8; i++, mask <<= 1) {
2014		for (j = 0; j < keymap->max_keypermod; j++) {
2015		    KeyCode code = keymap->modifiermap[k++];
2016		    if (code == 0)
2017			continue;
2018
2019		    for (l = 0; l < keysyms_per_keycode; ++l) {
2020#ifdef HAVE_XKBKEYCODETOKEYSYM
2021			keysym = XkbKeycodeToKeysym(dpy, code, 0, l);
2022#else
2023			keysym = XKeycodeToKeysym(dpy, code, l);
2024#endif
2025			if (keysym == NoSymbol) {
2026			    /* EMPTY */ ;
2027			} else if (keysym == XK_Num_Lock) {
2028			    SaveMask(num_lock);
2029			} else if (keysym == XK_Alt_L || keysym == XK_Alt_R) {
2030			    SaveMask(alt_mods);
2031			} else if (keysym == XK_Meta_L || keysym == XK_Meta_R) {
2032			    SaveMask(meta_mods);
2033			}
2034		    }
2035		}
2036	    }
2037	    XFree(theMap);
2038	}
2039
2040	/* Don't disable any mods if "alwaysUseMods" is true. */
2041	if (!xw->misc.alwaysUseMods) {
2042
2043	    /*
2044	     * Force TranslationsUseKeyword() to reload.
2045	     */
2046	    if (xw->keyboard.shell_translations) {
2047		free(xw->keyboard.shell_translations);
2048		xw->keyboard.shell_translations = 0;
2049	    }
2050	    if (xw->keyboard.xterm_translations) {
2051		free(xw->keyboard.xterm_translations);
2052		xw->keyboard.xterm_translations = 0;
2053	    }
2054
2055	    /*
2056	     * If the Alt modifier is used in translations, we would rather not
2057	     * use it to modify function-keys when NumLock is active.
2058	     */
2059	    if ((xw->work.alt_mods != 0)
2060		&& xtermHasTranslation(xw, "alt", True)) {
2061		TRACE(("ALT is used as a modifier in translations (ignore mask)\n"));
2062		xw->work.alt_mods = 0;
2063	    }
2064
2065	    /*
2066	     * If the Meta modifier is used in translations, we would rather not
2067	     * use it to modify function-keys.
2068	     */
2069	    if ((xw->work.meta_mods != 0)
2070		&& xtermHasTranslation(xw, "meta", True)) {
2071		TRACE(("META is used as a modifier in translations\n"));
2072		xw->work.meta_mods = 0;
2073	    }
2074	}
2075
2076	XFreeModifiermap(keymap);
2077    }
2078}
2079#endif /* OPT_NUM_LOCK */
2080