]> git.lyx.org Git - lyx.git/blob - src/kbmap.C
my changes during the holidyas...i expect some compilers to have some problems, but...
[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 #ifndef NO_HASH
349         unsigned int hashval;
350 #endif
351         unsigned int ksym, msk1, msk0;
352         kb_key * tab;
353
354         //suppress modifier bits we do not handle
355         mod &= ModsMask;
356
357         if(!table) {
358                 // error - no keymap defined:
359                 seq->curmap = seq->stdmap;
360                 seq->delseq();
361                 return -1;
362         }
363
364 #ifndef NO_HASH
365         if(size < 0) {               // --- if hash table ---
366                 hashval = ((key & 0xff) ^ ((key >> 8) & 0xff)) % KB_HASHSIZE;
367                 tab = htable[hashval];
368                 if(!tab) {
369                         seq->curmap = seq->stdmap;
370                         seq->delseq();
371                         return -1;
372                 }
373         } else                       // --- else: linear list ---
374 #endif
375                 tab = table;
376
377         // --- now search the list of keys ---
378
379         for(; (tab->code & 0xffff) != NoSymbol; ++tab) {
380                 ksym =  tab->code;
381                 msk1 =  tab->mod      & 0xffff;
382                 msk0 = (tab->mod >> 16) & 0xffff;
383
384                 if(ksym == key && (mod & ~msk0) == msk1) {
385                         // match found:
386                         if(tab->table) {
387                                 // this is a prefix key - set new map
388                                 seq->curmap = tab->table;
389                                 return 0;
390                         } else {
391                                 // final key - reset map
392                                 seq->curmap = seq->stdmap;
393                                 seq->delseq();
394                                 return tab->action; // ... and return action
395                         }
396                 }
397         }
398         
399         // error - key not found:
400         seq->curmap = seq->stdmap;
401         seq->delseq();
402         return -1;
403 }
404
405
406 /* ---F+------------------------------------------------------------------ *\
407     Function  : kb_keymap::print
408     Called by : [user]
409     Purpose   : Prints all the available keysyms. RVDK_PATCH_5
410     Parameters: buf    - string where output goes.
411                maxLen - available length in string, including `\0'.
412     Returns   : updated maxLen.
413 \* ---F------------------------------------------------------------------- */
414
415 void kb_keymap::print(string & buf) const
416 {
417         // Return when keymap has no table.
418         if (!table) return;
419    
420         // Process each of its slots recursively and return.
421 #ifndef NO_HASH
422         if ( size < 0 ) {   // Hash table
423                 for ( int ix = 0; ix < KB_HASHSIZE; ++ix ) {
424                         if ( htable[ix] ) {
425                                 printKeyTab(htable[ix], buf);
426                         }
427                 }
428         } else // Normal table
429 #endif
430                 printKeyTab(table, buf);
431 }
432
433
434 /* ---F+------------------------------------------------------------------ *\
435     Function  : kb_keymap::defkey
436     Called by : [user]
437     Purpose   : define an action for a key sequence
438     Parameters: seq    - the key sequence
439                 action - the action to be defined
440                 idx    - recursion depth
441     Returns   : 0 if ok.
442 \* ---F------------------------------------------------------------------- */
443
444 int kb_keymap::defkey(kb_sequence * seq, int action, int idx /*= 0*/)
445 {
446         unsigned int code = seq->sequence[idx];
447         if(code == NoSymbol) return -1;
448
449         unsigned int modmsk = seq->modifiers[idx];
450         kb_key  * tab, ** ptab;
451         // --- get list------------------------------------------------------
452         if(!table) {
453                 // If we don't have any yet, make an empty one
454                 table = new kb_key[KB_PREALLOC];
455                 table[0].code = NoSymbol;
456                 tab   =  table;
457                 ptab  = &table;
458                 size  = KB_PREALLOC;
459 #ifndef NO_HASH
460         } else if(size < 0) {
461                 // Hash table.
462                 int hashval = code & 0xffff;
463                 hashval = ((hashval & 0xff) ^ ((hashval >> 8) & 0xff)) % KB_HASHSIZE;
464                 tab  = htable[hashval];
465                 ptab = htable+hashval;
466                 if(!tab) {
467                         tab = new kb_key[KB_PREALLOC];
468                         tab[0].code = NoSymbol;
469                         *ptab = tab;
470                 }
471 #endif
472         } else {
473                 tab  =  table;
474                 ptab = &table;
475         }
476
477         // --- check if key is already there --------------------------------
478
479         kb_key * t;
480         int tsize;
481         for(t = tab, tsize = 1; t->code != NoSymbol; ++t, ++tsize) {
482                 if(code == t->code && modmsk == t->mod) { // -- overwrite binding ---
483                         if(idx + 1 == seq->length) {
484                                 string buf;
485                                 seq->print(buf, true);
486                                 lyxerr[Debug::KEY]
487                                         << "Warning: New binding for '"
488                                         << buf 
489                                         << "' is overriding old binding..."
490                                         << endl;
491
492                                 if(t->table) {
493                                         delete t->table;
494                                         t->table = 0;
495                                 }
496                                 t->action = action;
497                                 return 0;
498                         } else if (!t->table) {
499                                 string buf;
500                                 seq->print(buf, true);
501                                 lyxerr << "Error: New binding for '" << buf
502                                        << "' is overriding old binding..."
503                                        << endl;
504                                 return -1;
505                         } else
506                                 return t->table->defkey(seq, action, idx + 1);
507                 }
508         }
509
510         // --- extend list if necessary -------------------------------------
511
512         if(tsize % KB_PREALLOC == 0) {
513                 kb_key * nt = new kb_key[tsize + KB_PREALLOC];
514                 // Set to 0 as table is used uninitialised later (thornley)
515                 nt[tsize].table = 0;
516                 memcpy(nt, tab, tsize * sizeof(kb_key));
517                 *ptab = nt;
518                 delete[] tab;
519                 tab = nt;
520                 if(size >= 0) size = tsize + KB_PREALLOC;
521         }
522
523         // --- add action ---------------------------------------------------
524
525         tab[tsize--].code = NoSymbol;
526         tab[tsize].code = code;
527         tab[tsize].mod  = modmsk;
528         kb_key * newone = &tab[tsize];
529         
530         // --- convert list to hash table if necessary ----------------------
531
532 #ifndef NO_HASH
533         if(size >= 0 && tsize >= 32) {
534                 kb_key * oldtab = tab;
535                 kb_key ** nht = new kb_key*[KB_HASHSIZE];
536                 for(int i = 0; i < KB_HASHSIZE; ++i)
537                         nht[i] = 0;
538                 htable = nht;
539                 size   = -KB_HASHSIZE;
540                 
541                 // --- copy old keys to new hash table ---
542                 int hashval;
543                 for(kb_key * tu = oldtab; tu->code != NoSymbol; ++tu) {
544                         // copy values from oldtab to htable
545                         hashval = (tu->code & 0xffff);
546                         hashval = ((hashval & 0xff) ^ ((hashval>>8) & 0xff)) % KB_HASHSIZE;
547                         tab  = htable[hashval];
548                         
549                         if(!tab){
550                                 htable[hashval] = tab = new kb_key[KB_PREALLOC];
551                                 tab->code = NoSymbol;
552                         }
553                         int ts = 1;
554                         for(kb_key * tt = tab; tt->code != NoSymbol; ++tt)
555                                 ++ts;
556                         if(ts % KB_PREALLOC == 0){
557                                 // extend table
558                                 kb_key * nt = new kb_key[ts+KB_PREALLOC];
559                                 memcpy(nt, tab, ts * sizeof(kb_key));
560                                 htable[hashval] = nt;
561                                 delete[] tab;
562                                 tab = nt;
563                         }
564                         tab[ts--].code = NoSymbol;
565                         tab[ts].code   = tu->code;
566                         tab[ts].mod    = tu->mod;
567                         tab[ts].action = tu->action;
568                         tab[ts].table  = tu->table;
569                         
570                         if(tu == newone)
571                                 newone = &tab[ts];
572                 }
573                 delete[] oldtab;
574         }
575 #endif
576         // --- define rest of sequence --------------------------------------
577
578         if(idx+1 == seq->length) {
579                 newone->action = action;
580                 newone->table  = 0;
581                 return 0;
582         } else {
583                 newone->table = new kb_keymap;
584                 int res = newone->table->defkey(seq, action, idx+1);
585                 return res;
586         }
587 }
588
589
590 /* ---F+------------------------------------------------------------------ *\
591     Function  : kb_keymap::~kb_keymap
592     Called by : [destructor]
593     Purpose   : free keymap and its descendents
594     Parameters: none
595     Returns   : nothing
596 \* ---F------------------------------------------------------------------- */
597
598 kb_keymap::~kb_keymap()
599 {
600         if(!table) return;
601 #ifndef NO_HASH
602         if(size < 0) {
603                 for(int i = 0; i < KB_HASHSIZE; ++i) {
604                         if(htable[i]) {
605                                 for(kb_key * t = htable[i];
606                                     t->code != NoSymbol; ++t)
607                                         if(t->table)
608                                                 delete t->table;
609                                 delete htable[i];
610                         }
611                 }
612                 delete htable;
613         } else {
614 #endif
615                 for(kb_key * t = table; t->code != NoSymbol; ++t)
616                         if(t->table)
617                                 delete t->table;
618                 delete table;
619 #ifndef NO_HASH
620         }
621 #endif
622 }
623
624
625 string keyname(kb_key k)
626 {
627         string buf;
628         printKeysym(k.code, k.mod, buf);
629         return buf;
630 }
631
632
633 // Finds a key for a keyaction, if possible
634 string kb_keymap::findbinding(int act) const
635 {
636         string res;
637         if (!table) return res;
638
639 #ifndef NO_HASH
640         if (size < 0) {
641                 for(int i = 0; i < KB_HASHSIZE; ++i) {
642                         if(htable[i]) {
643                                 for(kb_key * t = htable[i];
644                                     t->code != NoSymbol; ++t) {
645                                         if(t->table) {
646                                                 string suffix = t->table->findbinding(act);
647                                                 suffix = strip(suffix, ' ');
648                                                 suffix = strip(suffix, ']');
649                                                 suffix = frontStrip(suffix, '[');
650                                                 if (!suffix.empty()) {
651                                                         res += "[" + keyname(*t) + " " + suffix + "] ";
652                                                 }
653                                         } else if (t->action == act) {
654                                                 res += "[" + keyname(*t) + "] ";
655                                         }
656                                 }
657                         }
658                 }
659         } else {
660 #endif
661                 for(kb_key * t = table; t->code != NoSymbol; ++t) {
662                         if(t->table) {
663                                 string suffix = t->table->findbinding(act);
664                                 suffix = strip(suffix, ' ');
665                                 suffix = strip(suffix, ']');
666                                 suffix = frontStrip(suffix, '[');
667                                 if (!suffix.empty()) {
668                                         res += "[" + keyname(*t) + " " + suffix + "] ";
669                                 }
670                         } else if (t->action == act) {
671                                 res += "[" + keyname(*t) + "] ";
672                         }
673                 }
674 #ifndef NO_HASH
675         }
676 #endif
677         return res;
678 }
679
680
681 /* === End of File: kbmap.C ============================================== */