]> git.lyx.org Git - lyx.git/blob - src/KeyMap.cpp
61e4562cf09dc85a5702b596046a62e9d927a562
[lyx.git] / src / KeyMap.cpp
1 /**
2  * \file KeyMap.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jean-Marc Lasgouttes
8  * \author John Levon
9  * \author André Pönitz
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "KeyMap.h"
17
18 #include "KeySequence.h"
19 #include "LyXAction.h"
20 #include "Lexer.h"
21
22 #include "support/debug.h"
23 #include "support/docstream.h"
24 #include "support/FileName.h"
25 #include "support/filetools.h"
26 #include "support/gettext.h"
27 #include "support/lstrings.h"
28
29 #include "frontends/alert.h"
30
31 #include <fstream>
32 #include <sstream>
33 #include <utility>
34
35 using namespace std;
36 using namespace lyx::support;
37
38 namespace lyx {
39
40
41 string const KeyMap::printKeySym(KeySymbol const & key, KeyModifier mod)
42 {
43         string buf;
44
45         string const s = key.getSymbolName();
46
47         if (mod & ControlModifier)
48                 buf += "C-";
49         if (mod & AltModifier)
50                 buf += "M-";
51         if (mod & ShiftModifier)
52                 buf += "S-";
53
54         buf += s;
55         return buf;
56 }
57
58
59 size_t KeyMap::bind(string const & seq, FuncRequest const & func)
60 {
61         LYXERR(Debug::KBMAP, "BIND: Sequence `" << seq << "' Action `"
62                << func.action() << '\'');
63
64         KeySequence k(0, 0);
65
66         string::size_type const res = k.parse(seq);
67         if (res == string::npos) {
68                 bind(&k, func);
69         } else {
70                 LYXERR(Debug::KBMAP, "Parse error at position " << res
71                                      << " in key sequence '" << seq << "'.");
72         }
73
74         return res == string::npos ? 0 : res;
75 }
76
77
78 size_t KeyMap::unbind(string const & seq, FuncRequest const & func)
79 {
80         KeySequence k(0, 0);
81
82         string::size_type const res = k.parse(seq);
83         if (res == string::npos)
84                 unbind(&k, func);
85         else
86                 LYXERR(Debug::KBMAP, "Parse error at position " << res
87                                      << " in key sequence '" << seq << "'.");
88         return res == string::npos ? 0 : res;
89 }
90
91
92 void KeyMap::bind(KeySequence * seq, FuncRequest const & func, unsigned int r)
93 {
94         KeySymbol code = seq->sequence[r];
95         if (!code.isOK())
96                 return;
97
98         KeyModifier const mod1 = seq->modifiers[r].first;
99         KeyModifier const mod2 = seq->modifiers[r].second;
100
101         // check if key is already there
102         Table::iterator end = table.end();
103         for (Table::iterator it = table.begin(); it != end; ++it) {
104                 if (code == it->code
105                     && mod1 == it->mod.first
106                     && mod2 == it->mod.second) {
107                         // overwrite binding
108                         if (r + 1 == seq->length()) {
109                                 LYXERR(Debug::KBMAP, "Warning: New binding for '"
110                                         << to_utf8(seq->print(KeySequence::Portable))
111                                         << "' is overriding old binding...");
112                                 if (it->prefixes.get()) {
113                                         it->prefixes.reset();
114                                 }
115                                 it->func = func;
116                                 it->func.setOrigin(FuncRequest::KEYBOARD);
117                                 return;
118                         } else if (!it->prefixes.get()) {
119                                 lyxerr << "Error: New binding for '"
120                                        << to_utf8(seq->print(KeySequence::Portable))
121                                        << "' is overriding old binding..."
122                                        << endl;
123                                 return;
124                         } else {
125                                 it->prefixes->bind(seq, func, r + 1);
126                                 return;
127                         }
128                 }
129         }
130
131         Table::iterator newone = table.insert(table.end(), Key());
132         newone->code = code;
133         newone->mod = seq->modifiers[r];
134         if (r + 1 == seq->length()) {
135                 newone->func = func;
136                 newone->func.setOrigin(FuncRequest::KEYBOARD);
137                 newone->prefixes.reset();
138         } else {
139                 newone->prefixes.reset(new KeyMap);
140                 newone->prefixes->bind(seq, func, r + 1);
141         }
142 }
143
144
145 void KeyMap::unbind(KeySequence * seq, FuncRequest const & func, unsigned int r)
146 {
147         KeySymbol code = seq->sequence[r];
148         if (!code.isOK())
149                 return;
150
151         KeyModifier const mod1 = seq->modifiers[r].first;
152         KeyModifier const mod2 = seq->modifiers[r].second;
153
154         // check if key is already there
155         Table::iterator end = table.end();
156         Table::iterator remove = end;
157         for (Table::iterator it = table.begin(); it != end; ++it) {
158                 if (code == it->code
159                     && mod1 == it->mod.first
160                     && mod2 == it->mod.second) {
161                         // remove
162                         if (r + 1 == seq->length()) {
163                                 if (it->func == func) {
164                                         remove = it;
165                                         if (it->prefixes.get())
166                                                 it->prefixes.reset();
167                                 }
168                         } else if (it->prefixes.get()) {
169                                 it->prefixes->unbind(seq, func, r + 1);
170                                 if (it->prefixes->empty())
171                                         remove = it;
172                                 return;
173                         }
174                 }
175         }
176         if (remove != end)
177                 table.erase(remove);
178 }
179
180
181 FuncRequest KeyMap::getBinding(KeySequence const & seq, unsigned int r)
182 {
183         KeySymbol code = seq.sequence[r];
184         if (!code.isOK())
185                 return FuncRequest::unknown;
186
187         KeyModifier const mod1 = seq.modifiers[r].first;
188         KeyModifier const mod2 = seq.modifiers[r].second;
189
190         // check if key is already there
191         Table::iterator end = table.end();
192         for (Table::iterator it = table.begin(); it != end; ++it) {
193                 if (code == it->code
194                     && mod1 == it->mod.first
195                     && mod2 == it->mod.second) {
196                         if (r + 1 == seq.length())
197                                 return it->func;
198                         else if (it->prefixes.get())
199                                 return it->prefixes->getBinding(seq, r + 1);
200                 }
201         }
202         return FuncRequest::unknown;
203 }
204
205
206 void KeyMap::clear()
207 {
208         table.clear();
209 }
210
211
212 bool KeyMap::read(string const & bind_file, KeyMap * unbind_map, BindReadType rt)
213 {
214         FileName bf = i18nLibFileSearch("bind", bind_file, "bind");
215         if (bf.empty()) {
216                 if (rt == MissingOK)
217                         return true;
218
219                 lyxerr << "Could not find bind file: " << bind_file;
220                 if (rt == Default) {
221                         frontend::Alert::warning(_("Could not find bind file"),
222                                 bformat(_("Unable to find the bind file\n%1$s.\n"
223                                                 "Please check your installation."), from_utf8(bind_file)));
224                         return false;
225                 }
226
227                 static string const defaultBindfile = "cua";
228                 if (bind_file == defaultBindfile) {
229                         frontend::Alert::warning(_("Could not find `cua.bind' file"),
230                                 _("Unable to find the default bind file `cua.bind'.\n"
231                                    "Please check your installation."));
232                         return false;
233                 }
234
235                 // Try it with the default file.
236                 frontend::Alert::warning(_("Could not find bind file"),
237                         bformat(_("Unable to find the bind file\n%1$s.\n"
238                                   "Falling back to default."), from_utf8(bind_file)));
239                 return read(defaultBindfile, unbind_map);
240         }
241         return read(bf, unbind_map);
242 }
243
244
245 bool KeyMap::read(FileName const & bind_file, KeyMap * unbind_map)
246 {
247         enum {
248                 BN_BIND,
249                 BN_BINDFILE,
250                 BN_UNBIND,
251         };
252
253         LexerKeyword bindTags[] = {
254                 { "\\bind",      BN_BIND },
255                 { "\\bind_file", BN_BINDFILE },
256                 { "\\unbind",    BN_UNBIND },
257         };
258
259         Lexer lexrc(bindTags);
260         if (lyxerr.debugging(Debug::PARSER))
261                 lexrc.printTable(lyxerr);
262
263         lexrc.setFile(bind_file);
264         if (!lexrc.isOK()) {
265                 LYXERR0("KeyMap::read: cannot open bind file:" << bind_file.absFileName());
266                 return false;
267         }
268
269         LYXERR(Debug::KBMAP, "Reading bind file:" << bind_file.absFileName());
270
271         bool error = false;
272         while (lexrc.isOK()) {
273                 switch (lexrc.lex()) {
274
275                 case Lexer::LEX_UNDEF:
276                         lexrc.printError("Unknown tag `$$Token'");
277                         error = true;
278                         continue;
279
280                 case Lexer::LEX_FEOF:
281                         continue;
282
283                 case BN_BIND: {
284                         if (!lexrc.next()) {
285                                 lexrc.printError("BN_BIND: Missing key sequence");
286                                 error = true;
287                                 break;
288                         }
289                         string seq = lexrc.getString();
290
291                         if (!lexrc.next(true)) {
292                                 lexrc.printError("BN_BIND: missing command");
293                                 error = true;
294                                 break;
295                         }
296                         string cmd = lexrc.getString();
297
298                         FuncRequest func = lyxaction.lookupFunc(cmd);
299                         if (func.action() == LFUN_UNKNOWN_ACTION) {
300                                 lexrc.printError("BN_BIND: Unknown LyX function `$$Token'");
301                                 error = true;
302                                 break;
303                         }
304
305                         bind(seq, func);
306                         break;
307                 }
308
309                 case BN_UNBIND: {
310                         if (!lexrc.next()) {
311                                 lexrc.printError("BN_UNBIND: Missing key sequence");
312                                 error = true;
313                                 break;
314                         }
315                         string seq = lexrc.getString();
316
317                         if (!lexrc.next(true)) {
318                                 lexrc.printError("BN_UNBIND: missing command");
319                                 error = true;
320                                 break;
321                         }
322                         string cmd = lexrc.getString();
323
324                         FuncRequest func = lyxaction.lookupFunc(cmd);
325                         if (func.action() == LFUN_UNKNOWN_ACTION) {
326                                 lexrc.printError("BN_UNBIND: Unknown LyX"
327                                                  " function `$$Token'");
328                                 error = true;
329                                 break;
330                         }
331                         
332                         if (unbind_map)
333                                 unbind_map->bind(seq, func);
334                         else
335                                 unbind(seq, func);
336                         break;
337                 }
338
339                 case BN_BINDFILE:
340                         if (!lexrc.next()) {
341                                 lexrc.printError("BN_BINDFILE: Missing file name");
342                                 error = true;
343                                 break;
344                         }
345                         string const tmp = lexrc.getString();
346                         error |= !read(tmp, unbind_map);
347                         break;
348                 }
349         }
350
351         if (error)
352                 LYXERR0("KeyMap::read: error while reading bind file:" << bind_file.absFileName());
353         return !error;
354 }
355
356
357 void KeyMap::write(string const & bind_file, bool append, bool unbind) const
358 {
359         ofstream os(bind_file.c_str(), 
360                 append ? (ios::app | ios::out) : ios::out);
361
362         if (!append)
363                 os << "## This file is automatically generated by lyx\n"
364                    << "## All modifications will be lost\n\n";
365         
366         string tag = unbind ? "\\unbind" : "\\bind";
367         BindingList const list = listBindings(false);
368         BindingList::const_iterator it = list.begin();
369         BindingList::const_iterator it_end = list.end();
370         for (; it != it_end; ++it) {
371                 FuncCode action = it->request.action();
372                 string arg = to_utf8(it->request.argument());
373
374                 string const cmd = lyxaction.getActionName(action)
375                         + (arg.empty() ? string() : " " + arg) ;
376                 os << tag << " \""
377                    << to_utf8(it->sequence.print(KeySequence::BindFile))
378                    << "\" " << Lexer::quoteString(cmd)
379                    << "\n";
380         }
381         os << "\n";
382         os.close();
383 }
384
385
386 FuncRequest const & KeyMap::lookup(KeySymbol const &key,
387                   KeyModifier mod, KeySequence * seq) const
388 {
389         if (table.empty()) {
390                 seq->reset();
391                 return FuncRequest::unknown;
392         }
393
394         Table::const_iterator end = table.end();
395         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
396                 KeyModifier mask = cit->mod.second;
397                 KeyModifier check = static_cast<KeyModifier>(mod & ~mask);
398
399                 if (cit->code == key && cit->mod.first == check) {
400                         // match found
401                         if (cit->prefixes.get()) {
402                                 // this is a prefix key - set new map
403                                 seq->curmap = cit->prefixes.get();
404                                 static FuncRequest prefix(LFUN_COMMAND_PREFIX);
405                                 return prefix;
406                         } else {
407                                 // final key - reset map
408                                 seq->reset();
409                                 return cit->func;
410                         }
411                 }
412         }
413
414         // error - key not found:
415         seq->reset();
416
417         return FuncRequest::unknown;
418 }
419
420
421 docstring const KeyMap::print(bool forgui) const
422 {
423         docstring buf;
424         Table::const_iterator end = table.end();
425         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
426                 buf += cit->code.print(cit->mod.first, forgui);
427                 buf += ' ';
428         }
429         return buf;
430 }
431
432
433 docstring KeyMap::printBindings(FuncRequest const & func,
434                                 KeySequence::outputFormat format) const
435 {
436         Bindings bindings = findBindings(func);
437         if (bindings.empty())
438                 return docstring();
439         
440         odocstringstream res;
441         Bindings::const_iterator cit = bindings.begin();
442         Bindings::const_iterator cit_end = bindings.end();
443         // print the first item
444         res << cit->print(format);
445         // more than one shortcuts?
446         for (++cit; cit != cit_end; ++cit)
447                 res << ", " << cit->print(format);
448         return res.str();
449 }
450
451
452 KeyMap::Bindings KeyMap::findBindings(FuncRequest const & func) const
453 {
454         return findBindings(func, KeySequence(0, 0));
455 }
456
457
458 KeyMap::Bindings KeyMap::findBindings(FuncRequest const & func,
459                         KeySequence const & prefix) const
460 {
461         Bindings res;
462         if (table.empty())
463                 return res;
464
465         Table::const_iterator end = table.end();
466         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
467                 if (cit->prefixes.get()) {
468                         KeySequence seq = prefix;
469                         seq.addkey(cit->code, cit->mod.first);
470                         Bindings res2 = cit->prefixes->findBindings(func, seq);
471                         res.insert(res.end(), res2.begin(), res2.end());
472                 } else if (cit->func == func) {
473                         KeySequence seq = prefix;
474                         seq.addkey(cit->code, cit->mod.first);
475                         res.push_back(seq);
476                 }
477         }
478
479         return res;
480 }
481
482
483 KeyMap::BindingList KeyMap::listBindings(bool unbound, KeyMap::ItemType tag) const
484 {
485         BindingList list;
486         listBindings(list, KeySequence(0, 0), tag);
487         if (unbound) {
488                 LyXAction::const_iterator fit = lyxaction.func_begin();
489                 LyXAction::const_iterator const fen = lyxaction.func_end();
490                 for (; fit != fen; ++fit) {
491                         FuncCode action = fit->second;
492                         bool has_action = false;
493                         BindingList::const_iterator bit = list.begin();
494                         BindingList::const_iterator const ben = list.end();
495                         for (; bit != ben; ++bit)
496                                 if (bit->request.action() == action) {
497                                         has_action = true;
498                                         break;
499                                 }
500                         if (!has_action)
501                                 list.push_back(Binding(FuncRequest(action), KeySequence(0, 0), tag));
502                 }       
503         }
504         return list;
505 }
506
507
508 void KeyMap::listBindings(BindingList & list,
509         KeySequence const & prefix, KeyMap::ItemType tag) const
510 {
511         Table::const_iterator it = table.begin();
512         Table::const_iterator it_end = table.end();
513         for (; it != it_end; ++it) {
514                 // a LFUN_COMMAND_PREFIX
515                 if (it->prefixes.get()) {
516                         KeySequence seq = prefix;
517                         seq.addkey(it->code, it->mod.first);
518                         it->prefixes->listBindings(list, seq, tag);
519                 } else {
520                         KeySequence seq = prefix;
521                         seq.addkey(it->code, it->mod.first);
522                         list.push_back(Binding(it->func, seq, tag));
523                 }
524         }
525 }
526
527
528 } // namespace lyx