]> git.lyx.org Git - lyx.git/blob - src/kbmap.C
b1a8ae63876de1bff635f75127644164455093f8
[lyx.git] / src / kbmap.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-1999 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12 #include <cstring>
13 #include "support/lstrings.h"
14 #include "gettext.h"
15
16 #ifdef __GNUG__
17 #pragma implementation
18 #endif
19
20 #include "kbmap.h"
21 #include "debug.h"
22
23 // The only modifiers that we handle. We want to throw away things
24 // like NumLock. 
25 enum { ModsMask = ShiftMask | ControlMask | Mod1Mask};
26
27
28 // === static functions =================================================== 
29
30
31 /* ---F+------------------------------------------------------------------ *\
32    Function  : printKeysym
33    Called by : kb_sequence::print and printKeyMap. RVDK_PATCH_5
34    Purpose   : prints a keysym, including modifiers.
35    Parameters: key    - keysym
36                mod    - modifiers
37                buf    - string where the result goes
38                maxlen - length of string (including '\0')
39    Returns   : length of printed string if ok, 0 otherwise.
40 \* ---F------------------------------------------------------------------- */
41 static
42 void printKeysym(KeySym key, unsigned int mod, string & buf)
43 {
44         mod &= ModsMask;
45
46         char * s = XKeysymToString(key);
47         
48         if (mod & ShiftMask) buf += "S-";
49         if (mod & ControlMask) buf += "C-";
50         if (mod & Mod1Mask) buf += "M-";
51         if (s) buf += s;
52 }
53
54
55 /* ---F+------------------------------------------------------------------ *\
56    Function  : printKeyTab
57    Called by : kb_keymap::print
58    Purpose   : print the keysyms found in the given key table. RVDK_PATCH_5
59    Parameters: tabPt  - keytable pointer
60                buf    - string where the result goes
61                maxLen - length of string (including '\0')
62    Returns   : length of printed string.
63 \* ---F------------------------------------------------------------------- */
64
65 static
66 void printKeyTab(kb_key * tabPt, string & buf)
67 {
68         unsigned int ksym, mod;
69         
70         /* -------> Print each of the slots into buf. */
71         for( ; (tabPt->code & 0xffff) != NoSymbol; ++tabPt) {
72                 ksym =  tabPt->code;
73                 mod  =  tabPt->mod & 0xffff;
74                 
75                 printKeysym(ksym, mod, buf);
76                 buf += ' ';
77         }
78 }
79
80
81 // === kb_sequence methods ================================================ 
82
83 /* ---F+------------------------------------------------------------------ *\
84     Function  : kb_sequence::addkey
85     Called by : [user]
86     Purpose   : add a key to the sequence, look up in map and return action
87     Parameters: key  - keysym of key
88                 mod  - modifier mask
89                 nmod - modifier veto mask (unused now)
90     Returns   : action or -1 if error (no map defined or key not found)
91 \* ---F------------------------------------------------------------------- */
92
93 int kb_sequence::addkey(KeySym key,
94                         unsigned int mod, unsigned int nmod /*= 0*/)
95 {
96         if(length < 0) length = 0;
97
98         if(length + 1 >= size) {
99                 unsigned int * nseq = new unsigned int[size + KB_PREALLOC];
100                 size += KB_PREALLOC;
101                 memcpy(nseq, sequence, length * sizeof(unsigned int));
102                 if(sequence != staticseq) delete sequence;
103                 sequence = nseq;
104                 nseq = new unsigned int[size];
105                 memcpy(nseq, modifiers, length * sizeof(unsigned int));
106                 if(modifiers != staticmod) delete modifiers;
107                 modifiers = nseq;
108         }
109
110         modifiers[length]  = mod + (nmod << 16);
111         sequence[length++] = key;
112    
113         if(curmap)
114                 return curmap->lookup(key, mod, this);
115         
116         return -1;
117 }
118
119
120 /* ---F+------------------------------------------------------------------ *\
121     Function  : kb_sequence::parse
122     Called by : [user]
123     Purpose   : parse a string that holds a key sequence and add the keys
124     Parameters: s - string holding the key sequence
125     Returns   : 0 - if ok, error pos if error
126     Note      : Keys must be separated with whitespace;
127                 Use the keysym names used by XStringToKeysym
128                 Prefixes are S-, C-, M- for shift, control, meta
129 \* ---F------------------------------------------------------------------- */
130
131 int kb_sequence::parse(char const * s)
132 {
133         if(!s[0]) return 1;
134
135         int i = 0;
136         unsigned int mod = 0, nmod = 0;
137         while(s[i]) {
138                 if(s[i] && (s[i]) <= ' ') ++i;
139                 if(!s[i]) break;
140                 
141                 if(s[i + 1] == '-')     { // is implicit that s[i] == true
142                         switch(s[i]) {
143                         case 's': case 'S':
144                                 mod |= ShiftMask;
145                                 i += 2;
146                                 continue;
147                         case 'c': case 'C':
148                                 mod |= ControlMask;
149                                 i += 2;
150                                 continue;
151                         case 'm': case 'M':
152                                 mod |= Mod1Mask;
153                                 i += 2;
154                                 continue;
155                         default:
156                                 return i + 1;
157                         }
158                 } else if(s[i] == '~' && s[i + 1] && s[i + 2] == '-') {
159                         switch(s[i + 1]) {
160                         case 's': case 'S':
161                                 nmod |= ShiftMask;
162                                 i += 3;
163                                 continue;
164                         case 'c': case 'C':
165                                 nmod |= ControlMask;
166                                 i += 3;
167                                 continue;
168                         case 'm': case 'M':
169                                 nmod |= Mod1Mask;
170                                 i += 3;
171                                 continue;
172                         default:
173                                 return i + 2;
174                         }
175                 } else {
176                         string tbuf;
177                         int j = i;
178                         for(; s[j] && s[j] > ' '; ++j)
179                                 tbuf += s[j];    // (!!!check bounds :-)
180                         
181                         KeySym key = XStringToKeysym(tbuf.c_str());
182                         if(key == NoSymbol) {
183                                 lyxerr[Debug::KBMAP]
184                                         << "kbmap.C: No such keysym: "
185                                         << tbuf << endl;
186                                 return j;
187                         }
188                         i = j;
189                         
190                         addkey(key, mod, nmod);
191                         mod = 0;
192                         nmod = 0;
193                 }
194         }
195         return 0;
196 }
197
198
199 /* ---F+------------------------------------------------------------------ *\
200     Function  : kb_sequence::print
201     Called by : [user]
202     Purpose   : print the currently defined sequence into a string
203     Parameters: buf           - string where the result goes
204                 maxlen        - length of string (including '\0')
205                 when_defined  - only  print when sequence is real: length > 0.
206     Returns   : 0, if ok, -1 if string too long
207 \* ---F------------------------------------------------------------------- */
208
209 int kb_sequence::print(string & buf, bool when_defined) const
210 {
211         KeySym key;
212         unsigned int mod;
213         int l = length;
214         if ( l < 0 && !when_defined ) l = -l;
215         
216         for(int i = 0; i < l; ++i) {
217                 key = sequence[i];
218                 mod = modifiers[i] & 0xffff;
219
220                 printKeysym(key, mod, buf);  // RVDK_PATCH_5
221
222                 if(i + 1 < l) {  // append a blank
223                         buf += ' ';
224                 }
225         }
226         return 0;
227 }
228
229
230 /* ---F+------------------------------------------------------------------ *\
231     Function  : kb_sequence::printOptions
232     Called by : [user]
233     Purpose   : print the available key options from the current state in the
234                 sequence. RVDK_PATCH_5
235     Parameters: buf    - string where the result goes
236                 maxlen - length of string (including '\0')
237     Returns   : 0, if ok, -1 if string too long
238 \* ---F------------------------------------------------------------------- */
239
240 int kb_sequence::printOptions(string & buf) const
241 {
242         print(buf, true);
243         
244         if (!curmap) return -1;
245         buf += _("   options: ");
246         curmap->print(buf);
247         return 0;
248 }
249
250
251 /* ---F+------------------------------------------------------------------ *\
252     Function  : kb_sequence::delseq
253     Called by : [user]
254     Purpose   : mark the sequence as deleted
255     Parameters: none
256     Returns   : nothing
257 \* ---F------------------------------------------------------------------- */
258
259 void kb_sequence::delseq()
260 {
261         // negative length marks sequence as deleted, but we can still
262         // print() it or retrieve the last char using getiso()
263         length = -length;
264 }
265
266
267 /* ---F+------------------------------------------------------------------ *\
268    Function  : kb_sequence::getsym
269    Called by : [user], getiso
270    Purpose   : get the keysym of the last key in sequence
271    Parameters: none
272    Returns   : keysym
273 \* ---F------------------------------------------------------------------- */
274
275 KeySym kb_sequence::getsym()
276 {
277         int l = length;
278         if(l == 0) return NoSymbol;
279         if(l < 0) l = -l;
280         return sequence[l - 1];
281 }
282
283
284 /* ---F+------------------------------------------------------------------ *\
285     Function  : kb_sequence::getiso
286     Called by : [user]
287     Purpose   : return iso character code of last key, if any
288     Parameters: none
289     Returns   : iso code or 0 if none
290 \* ---F------------------------------------------------------------------- */
291
292 char kb_sequence::getiso()
293 {
294         int c = getsym();
295         
296         if(c > 0xff)
297                 return '\0';
298         return c;
299 }
300
301
302 /* ---F+------------------------------------------------------------------ *\
303     Function  : kb_sequence::reset
304     Called by : [user]
305     Purpose   : reset sequence to initial state. RVDK_PATCH_5
306     Parameters: none
307     Returns   : void
308 \* ---F------------------------------------------------------------------- */
309
310 void kb_sequence::reset()
311 {
312         delseq();
313         curmap = stdmap;
314         if (length > 0) length = -length;
315 }
316
317
318 // === kb_keymap methods ================================================== 
319
320 // This binds a key to an action
321 int kb_keymap::bind(char const * seq, int action)
322 {
323         kb_sequence k;
324
325         int res = k.parse(seq);
326         if (!res) {
327                 defkey(&k, action);
328         } else
329                 lyxerr[Debug::KBMAP] << "Parse error at position " << res
330                                      << " in key sequence '" << seq << "'."
331                                      << endl;
332         return res;
333 }
334
335
336 /* ---F+------------------------------------------------------------------ *\
337     Function  : kb_keymap::lookup
338     Called by : [user], kb_sequence::add()
339     Purpose   : look up a key press in a given keymap
340     Parameters: key - the keysym of the key press
341                 mod - the modifier mask of the keypress
342                 seq - the key-sequence retrieved so far
343     Returns   : user defined action; 0 for prefix key, -1 if key not found
344 \* ---F------------------------------------------------------------------- */
345
346 int kb_keymap::lookup(KeySym key, unsigned int mod, kb_sequence * seq)
347 {
348         unsigned int ksym, msk1, msk0;
349         kb_key * tab;
350
351         //suppress modifier bits we do not handle
352         mod &= ModsMask;
353
354         if(!table) {
355                 // error - no keymap defined:
356                 seq->curmap = seq->stdmap;
357                 seq->delseq();
358                 return -1;
359         }
360
361         tab = table;
362
363         // --- now search the list of keys ---
364
365         for(; (tab->code & 0xffff) != NoSymbol; ++tab) {
366                 ksym =  tab->code;
367                 msk1 =  tab->mod      & 0xffff;
368                 msk0 = (tab->mod >> 16) & 0xffff;
369
370                 if(ksym == key && (mod & ~msk0) == msk1) {
371                         // match found:
372                         if(tab->table) {
373                                 // this is a prefix key - set new map
374                                 seq->curmap = tab->table;
375                                 return 0;
376                         } else {
377                                 // final key - reset map
378                                 seq->curmap = seq->stdmap;
379                                 seq->delseq();
380                                 return tab->action; // ... and return action
381                         }
382                 }
383         }
384         
385         // error - key not found:
386         seq->curmap = seq->stdmap;
387         seq->delseq();
388         return -1;
389 }
390
391
392 /* ---F+------------------------------------------------------------------ *\
393     Function  : kb_keymap::print
394     Called by : [user]
395     Purpose   : Prints all the available keysyms. RVDK_PATCH_5
396     Parameters: buf    - string where output goes.
397                maxLen - available length in string, including `\0'.
398     Returns   : updated maxLen.
399 \* ---F------------------------------------------------------------------- */
400
401 void kb_keymap::print(string & buf) const
402 {
403         // Return when keymap has no table.
404         if (!table) return;
405    
406         // Process each of its slots recursively and return.
407         printKeyTab(table, buf);
408 }
409
410
411 /* ---F+------------------------------------------------------------------ *\
412     Function  : kb_keymap::defkey
413     Called by : [user]
414     Purpose   : define an action for a key sequence
415     Parameters: seq    - the key sequence
416                 action - the action to be defined
417                 idx    - recursion depth
418     Returns   : 0 if ok.
419 \* ---F------------------------------------------------------------------- */
420
421 int kb_keymap::defkey(kb_sequence * seq, int action, int idx /*= 0*/)
422 {
423         unsigned int code = seq->sequence[idx];
424         if(code == NoSymbol) return -1;
425
426         unsigned int modmsk = seq->modifiers[idx];
427         kb_key  * tab, ** ptab;
428         // --- get list------------------------------------------------------
429         if(!table) {
430                 // If we don't have any yet, make an empty one
431                 table = new kb_key[KB_PREALLOC];
432                 table[0].code = NoSymbol;
433                 tab   =  table;
434                 ptab  = &table;
435                 size  = KB_PREALLOC;
436         } else {
437                 tab  =  table;
438                 ptab = &table;
439         }
440
441         // --- check if key is already there --------------------------------
442
443         kb_key * t;
444         int tsize;
445         for(t = tab, tsize = 1; t->code != NoSymbol; ++t, ++tsize) {
446                 if(code == t->code && modmsk == t->mod) { // -- overwrite binding ---
447                         if(idx + 1 == seq->length) {
448                                 string buf;
449                                 seq->print(buf, true);
450                                 lyxerr[Debug::KEY]
451                                         << "Warning: New binding for '"
452                                         << buf 
453                                         << "' is overriding old binding..."
454                                         << endl;
455
456                                 if(t->table) {
457                                         delete t->table;
458                                         t->table = 0;
459                                 }
460                                 t->action = action;
461                                 return 0;
462                         } else if (!t->table) {
463                                 string buf;
464                                 seq->print(buf, true);
465                                 lyxerr << "Error: New binding for '" << buf
466                                        << "' is overriding old binding..."
467                                        << endl;
468                                 return -1;
469                         } else
470                                 return t->table->defkey(seq, action, idx + 1);
471                 }
472         }
473
474         // --- extend list if necessary -------------------------------------
475
476         if(tsize % KB_PREALLOC == 0) {
477                 kb_key * nt = new kb_key[tsize + KB_PREALLOC];
478                 // Set to 0 as table is used uninitialised later (thornley)
479                 nt[tsize].table = 0;
480                 memcpy(nt, tab, tsize * sizeof(kb_key));
481                 *ptab = nt;
482                 delete[] tab;
483                 tab = nt;
484                 if(size >= 0) size = tsize + KB_PREALLOC;
485         }
486
487         // --- add action ---------------------------------------------------
488
489         tab[tsize--].code = NoSymbol;
490         tab[tsize].code = code;
491         tab[tsize].mod  = modmsk;
492         kb_key * newone = &tab[tsize];
493         
494         // --- define rest of sequence --------------------------------------
495
496         if(idx+1 == seq->length) {
497                 newone->action = action;
498                 newone->table  = 0;
499                 return 0;
500         } else {
501                 newone->table = new kb_keymap;
502                 int res = newone->table->defkey(seq, action, idx+1);
503                 return res;
504         }
505 }
506
507
508 /* ---F+------------------------------------------------------------------ *\
509     Function  : kb_keymap::~kb_keymap
510     Called by : [destructor]
511     Purpose   : free keymap and its descendents
512     Parameters: none
513     Returns   : nothing
514 \* ---F------------------------------------------------------------------- */
515
516 kb_keymap::~kb_keymap()
517 {
518         if(!table) return;
519         for(kb_key * t = table; t->code != NoSymbol; ++t)
520                 if(t->table)
521                         delete t->table;
522         delete table;
523 }
524
525
526 string keyname(kb_key k)
527 {
528         string buf;
529         printKeysym(k.code, k.mod, buf);
530         return buf;
531 }
532
533
534 // Finds a key for a keyaction, if possible
535 string kb_keymap::findbinding(int act) const
536 {
537         string res;
538         if (!table) return res;
539
540         for(kb_key * t = table; t->code != NoSymbol; ++t) {
541                 if(t->table) {
542                         string suffix = t->table->findbinding(act);
543                         suffix = strip(suffix, ' ');
544                         suffix = strip(suffix, ']');
545                         suffix = frontStrip(suffix, '[');
546                         if (!suffix.empty()) {
547                                 res += "[" + keyname(*t) + " " + suffix + "] ";
548                         }
549                 } else if (t->action == act) {
550                         res += "[" + keyname(*t) + "] ";
551                 }
552         }
553         return res;
554 }
555
556
557 /* === End of File: kbmap.C ============================================== */