]> git.lyx.org Git - lyx.git/blob - src/KeyMap.cpp
Fix functions that used functions but did not defined it
[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
21 #include "support/debug.h"
22 #include "support/docstream.h"
23 #include "support/FileName.h"
24 #include "support/filetools.h"
25 #include "support/gettext.h"
26 #include "support/Lexer.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(nullptr, nullptr);
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(nullptr, nullptr);
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         for (auto & key : table) {
112                 if (code == key.code
113                     && mod1 == key.mod.first
114                     && mod2 == key.mod.second) {
115                         // overwrite binding
116                         if (r + 1 == seq->length()) {
117                                 LYXERR(Debug::KBMAP, "Warning: New binding for '"
118                                         << to_utf8(seq->print(KeySequence::Portable))
119                                         << "' is overriding old binding...");
120                                 if (key.prefixes)
121                                         key.prefixes.reset();
122                                 key.func = func;
123                                 key.func.setOrigin(FuncRequest::KEYBOARD);
124                                 return;
125                         } else if (!key.prefixes) {
126                                 lyxerr << "Error: New binding for '"
127                                        << to_utf8(seq->print(KeySequence::Portable))
128                                        << "' is overriding old binding..."
129                                        << endl;
130                                 return;
131                         } else {
132                                 key.prefixes->bind(seq, func, r + 1);
133                                 return;
134                         }
135                 }
136         }
137
138         Table::iterator newone = table.insert(table.end(), Key());
139         newone->code = code;
140         newone->mod = seq->modifiers[r];
141         if (r + 1 == seq->length()) {
142                 newone->func = func;
143                 newone->func.setOrigin(FuncRequest::KEYBOARD);
144                 newone->prefixes.reset();
145         } else {
146                 newone->prefixes.reset(new KeyMap);
147                 newone->prefixes->bind(seq, func, r + 1);
148         }
149 }
150
151
152 void KeyMap::unbind(KeySequence * seq, FuncRequest const & func, unsigned int r)
153 {
154         KeySymbol code = seq->sequence[r];
155         if (!code.isOK())
156                 return;
157
158         KeyModifier const mod1 = seq->modifiers[r].first;
159         KeyModifier const mod2 = seq->modifiers[r].second;
160
161         // check if key is already there
162         vector <Table::iterator> removes;
163         Table::iterator end = table.end();
164         for (Table::iterator it = table.begin(); it != end; ++it) {
165                 if (code == it->code
166                     && mod1 == it->mod.first
167                     && mod2 == it->mod.second) {
168                         // remove
169                         if (r + 1 == seq->length()) {
170                                 if (it->func == func || func == FuncRequest::unknown) {
171                                         removes.push_back(it);
172                                         if (it->prefixes)
173                                                 it->prefixes.reset();
174                                 }
175                         } else if (it->prefixes) {
176                                 it->prefixes->unbind(seq, func, r + 1);
177                                 if (it->prefixes->empty())
178                                         removes.push_back(it);
179                                 return;
180                         }
181                 }
182         }
183
184         for (unsigned i = removes.size(); i > 0; --i)
185                 table.erase(removes[i-1]);
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         for (auto const & key : table) {
200                 if (code == key.code
201                     && mod1 == key.mod.first
202                     && mod2 == key.mod.second) {
203                         if (r + 1 == seq.length())
204                                 return (key.prefixes) ? FuncRequest::prefix : key.func;
205                         else if (key.prefixes)
206                                 return key.prefixes->getBinding(seq, r + 1);
207                 }
208         }
209         return FuncRequest::unknown;
210 }
211
212
213 void KeyMap::clear()
214 {
215         table.clear();
216 }
217
218
219 bool KeyMap::read(string const & bind_file, KeyMap * unbind_map, BindReadType rt, bool i18n)
220 {
221         FileName bf = i18n ? i18nLibFileSearch("bind", bind_file, "bind")
222                            : libFileSearch("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         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 == FuncRequest::unknown) {
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                         FuncRequest func;
361                         if (cmd == "*")
362                                 func = FuncRequest::unknown;
363                         else {
364                                 func = lyxaction.lookupFunc(cmd);
365                                 if (func == FuncRequest::unknown) {
366                                         lexrc.printError("BN_UNBIND: Unknown LyX function `$$Token'");
367                                         error = true;
368                                         break;
369                                 }
370                         }
371
372                         if (unbind_map)
373                                 unbind_map->bind(seq, func);
374                         else
375                                 unbind(seq, func);
376                         break;
377                 }
378
379                 case BN_BINDFILE:
380                         if (!lexrc.next()) {
381                                 lexrc.printError("BN_BINDFILE: Missing file name");
382                                 error = true;
383                                 break;
384                         }
385                         string tmp = lexrc.getString();
386                         if (prefixIs(tmp, "../")) {
387                                 tmp = split(tmp, '/');
388                                 // look in top dir
389                                 error |= !read(tmp, unbind_map, Default, false);
390                         } else
391                                 // i18n search
392                                 error |= !read(tmp, unbind_map);
393                         break;
394                 }
395
396                 // This is triggered the first time through the loop unless
397                 // we hit a format tag.
398                 if (format != LFUN_FORMAT)
399                         return FormatMismatch;
400         }
401
402         if (error) {
403                 LYXERR0("KeyMap::read: error while reading bind file:" << bind_file.absFileName());
404                 return ReadError;
405         }
406         return ReadOK;
407 }
408
409
410 void KeyMap::write(string const & bind_file, bool append, bool unbind) const
411 {
412         ofstream os(bind_file.c_str(),
413                 append ? (ios::app | ios::out) : ios::out);
414
415         if (!append)
416                 os << "## This file is automatically generated by lyx\n"
417                    << "## All modifications will be lost\n\n"
418                    << "Format " << LFUN_FORMAT << "\n\n";
419
420         string tag = unbind ? "\\unbind" : "\\bind";
421         for (auto const & bnd : listBindings(false)) {
422                 FuncCode const action = bnd.request.action();
423                 string const arg = to_utf8(bnd.request.argument());
424
425                 string cmd;
426                 if (unbind && bnd.request == FuncRequest::unknown)
427                         cmd = "*";
428                 else
429                         cmd = lyxaction.getActionName(action) + (arg.empty() ? string() : " " + arg);
430                 os << tag << " \""
431                    << to_utf8(bnd.sequence.print(KeySequence::BindFile))
432                    << "\" " << Lexer::quoteString(cmd)
433                    << "\n";
434         }
435         os << "\n";
436         os.close();
437 }
438
439
440 FuncRequest const & KeyMap::lookup(KeySymbol const & keysym,
441                   KeyModifier mod, KeySequence * seq) const
442 {
443         if (table.empty()) {
444                 seq->reset();
445                 return FuncRequest::unknown;
446         }
447
448         for (auto const & key : table) {
449                 KeyModifier mask = key.mod.second;
450                 KeyModifier check = static_cast<KeyModifier>(mod & ~mask);
451
452                 if (key.code == keysym && key.mod.first == check) {
453                         // match found
454                         if (key.prefixes) {
455                                 // this is a prefix key - set new map
456                                 seq->curmap = key.prefixes.get();
457                                 return FuncRequest::prefix;
458                         } else {
459                                 // final key - reset map
460                                 seq->reset();
461                                 return key.func;
462                         }
463                 }
464         }
465
466         // error - key not found:
467         seq->reset();
468
469         return FuncRequest::unknown;
470 }
471
472
473 docstring const KeyMap::print(bool forgui) const
474 {
475         docstring buf;
476         for (auto const & key : table) {
477                 buf += key.code.print(key.mod.first, forgui);
478                 buf += ' ';
479         }
480         return buf;
481 }
482
483
484 docstring KeyMap::printBindings(FuncRequest const & func,
485                                 KeySequence::outputFormat format,
486                                 bool const untranslated) const
487 {
488         Bindings bindings = findBindings(func);
489         if (bindings.empty())
490                 return docstring();
491
492         odocstringstream res;
493         bool firstone = true;
494         for (auto const & key : bindings) {
495                 if (!firstone)
496                         res << ", ";
497                 res << key.print(format, untranslated);
498                 firstone = true;
499         }
500         return res.str();
501 }
502
503
504 KeyMap::Bindings KeyMap::findBindings(FuncRequest const & func) const
505 {
506         return findBindings(func, KeySequence(nullptr, nullptr));
507 }
508
509
510 KeyMap::Bindings KeyMap::findBindings(FuncRequest const & func,
511                         KeySequence const & prefix) const
512 {
513         Bindings res;
514         if (table.empty())
515                 return res;
516
517         for (auto const & key : table) {
518                 if (key.prefixes) {
519                         KeySequence seq = prefix;
520                         seq.addkey(key.code, key.mod.first);
521                         Bindings res2 = key.prefixes->findBindings(func, seq);
522                         res.insert(res.end(), res2.begin(), res2.end());
523                 } else if (key.func == func) {
524                         KeySequence seq = prefix;
525                         seq.addkey(key.code, key.mod.first);
526                         res.push_back(seq);
527                 }
528         }
529
530         return res;
531 }
532
533
534 KeyMap::BindingList KeyMap::listBindings(bool unbound, KeyMap::ItemType tag) const
535 {
536         BindingList list;
537         listBindings(list, KeySequence(nullptr, nullptr), tag);
538         if (unbound) {
539                 for (auto const & name_code : lyxaction) {
540                         FuncCode action = name_code.second;
541                         bool has_action = false;
542                         for (auto const & item : list)
543                                 if (item.request.action() == action) {
544                                         has_action = true;
545                                         break;
546                                 }
547                         if (!has_action)
548                                 list.push_back(Binding(FuncRequest(action), KeySequence(nullptr, nullptr), tag));
549                 }
550         }
551         return list;
552 }
553
554
555 void KeyMap::listBindings(BindingList & list,
556         KeySequence const & prefix, KeyMap::ItemType tag) const
557 {
558         for (auto const & key : table) {
559                 // a LFUN_COMMAND_PREFIX
560                 if (key.prefixes) {
561                         KeySequence seq = prefix;
562                         seq.addkey(key.code, key.mod.first);
563                         key.prefixes->listBindings(list, seq, tag);
564                 } else {
565                         KeySequence seq = prefix;
566                         seq.addkey(key.code, key.mod.first);
567                         list.push_back(Binding(key.func, seq, tag));
568                 }
569         }
570 }
571
572
573 } // namespace lyx