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