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