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