]> git.lyx.org Git - lyx.git/blob - src/KeyMap.cpp
Avoid full metrics computation with Update:FitCursor
[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         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         vector <Table::iterator> removes;
164         Table::iterator end = table.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 || func == FuncRequest::unknown) {
172                                         removes.push_back(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                                         removes.push_back(it);
180                                 return;
181                         }
182                 }
183         }
184
185         for (unsigned i = removes.size(); i > 0; --i)
186                 table.erase(removes[i-1]);
187 }
188
189
190 FuncRequest KeyMap::getBinding(KeySequence const & seq, unsigned int r)
191 {
192         KeySymbol code = seq.sequence[r];
193         if (!code.isOK())
194                 return FuncRequest::unknown;
195
196         KeyModifier const mod1 = seq.modifiers[r].first;
197         KeyModifier const mod2 = seq.modifiers[r].second;
198
199         // check if key is already there
200         Table::iterator end = table.end();
201         for (Table::iterator it = table.begin(); it != end; ++it) {
202                 if (code == it->code
203                     && mod1 == it->mod.first
204                     && mod2 == it->mod.second) {
205                         if (r + 1 == seq.length())
206                                 return (it->prefixes) ? FuncRequest::prefix : it->func;
207                         else if (it->prefixes)
208                                 return it->prefixes->getBinding(seq, r + 1);
209                 }
210         }
211         return FuncRequest::unknown;
212 }
213
214
215 void KeyMap::clear()
216 {
217         table.clear();
218 }
219
220
221 bool KeyMap::read(string const & bind_file, KeyMap * unbind_map, BindReadType rt, bool i18n)
222 {
223         FileName bf = i18n ? i18nLibFileSearch("bind", bind_file, "bind")
224                            : libFileSearch("bind", bind_file, "bind");
225         if (bf.empty()) {
226                 if (rt == MissingOK)
227                         return true;
228
229                 lyxerr << "Could not find bind file: " << bind_file;
230                 if (rt == Default) {
231                         frontend::Alert::warning(_("Could not find bind file"),
232                                 bformat(_("Unable to find the bind file\n%1$s.\n"
233                                                 "Please check your installation."), from_utf8(bind_file)));
234                         return false;
235                 }
236
237                 static string const defaultBindfile = "cua";
238                 if (bind_file == defaultBindfile) {
239                         frontend::Alert::warning(_("Could not find `cua.bind' file"),
240                                 _("Unable to find the default bind file `cua.bind'.\n"
241                                    "Please check your installation."));
242                         return false;
243                 }
244
245                 // Try it with the default file.
246                 frontend::Alert::warning(_("Could not find bind file"),
247                         bformat(_("Unable to find the bind file\n%1$s.\n"
248                                   "Falling back to default."), from_utf8(bind_file)));
249                 return read(defaultBindfile, unbind_map);
250         }
251         return read(bf, unbind_map);
252 }
253
254
255 bool KeyMap::read(FileName const & bind_file, KeyMap * unbind_map)
256 {
257         ReturnValues retval = readWithoutConv(bind_file, unbind_map);
258         if (retval != FormatMismatch)
259                 return retval == ReadOK;
260
261         LYXERR(Debug::FILES, "Converting bind file to " << LFUN_FORMAT);
262         TempFile tmp("convert_bind");
263         FileName const tempfile = tmp.name();
264         bool const success = prefs2prefs(bind_file, tempfile, true);
265         if (!success) {
266                 LYXERR0 ("Unable to convert " << bind_file <<
267                         " to format " << LFUN_FORMAT);
268                 return false;
269         }
270         retval = readWithoutConv(tempfile, unbind_map);
271         return retval == ReadOK;
272 }
273
274
275 KeyMap::ReturnValues KeyMap::readWithoutConv(FileName const & bind_file, KeyMap * unbind_map)
276 {
277         enum {
278                 BN_BIND,
279                 BN_BINDFILE,
280                 BN_FORMAT,
281                 BN_UNBIND
282         };
283
284         LexerKeyword bindTags[] = {
285                 { "\\bind",      BN_BIND },
286                 { "\\bind_file", BN_BINDFILE },
287                 { "\\unbind",    BN_UNBIND },
288                 { "format",      BN_FORMAT }
289         };
290
291         Lexer lexrc(bindTags);
292         if (lyxerr.debugging(Debug::PARSER))
293                 lexrc.printTable(lyxerr);
294
295         lexrc.setFile(bind_file);
296         if (!lexrc.isOK()) {
297                 LYXERR0("KeyMap::read: cannot open bind file:" << bind_file.absFileName());
298                 return FileError;
299         }
300
301         LYXERR(Debug::KBMAP, "Reading bind file:" << bind_file.absFileName());
302
303         // format of pre-2.0 bind files, before this tag was introduced.
304         int format = 0;
305         bool error = false;
306         while (lexrc.isOK()) {
307                 switch (lexrc.lex()) {
308
309                 case Lexer::LEX_UNDEF:
310                         lexrc.printError("Unknown tag `$$Token'");
311                         error = true;
312                         continue;
313
314                 case Lexer::LEX_FEOF:
315                         continue;
316
317                 case BN_FORMAT:
318                         if (lexrc.next())
319                                 format = lexrc.getInteger();
320                         break;
321
322                 case BN_BIND: {
323                         if (!lexrc.next()) {
324                                 lexrc.printError("BN_BIND: Missing key sequence");
325                                 error = true;
326                                 break;
327                         }
328                         string seq = lexrc.getString();
329
330                         if (!lexrc.next(true)) {
331                                 lexrc.printError("BN_BIND: missing command");
332                                 error = true;
333                                 break;
334                         }
335                         string cmd = lexrc.getString();
336
337                         FuncRequest func = lyxaction.lookupFunc(cmd);
338                         if (func == FuncRequest::unknown) {
339                                 lexrc.printError("BN_BIND: Unknown LyX function `$$Token'");
340                                 error = true;
341                                 break;
342                         }
343
344                         bind(seq, func);
345                         break;
346                 }
347
348                 case BN_UNBIND: {
349                         if (!lexrc.next()) {
350                                 lexrc.printError("BN_UNBIND: Missing key sequence");
351                                 error = true;
352                                 break;
353                         }
354                         string seq = lexrc.getString();
355
356                         if (!lexrc.next(true)) {
357                                 lexrc.printError("BN_UNBIND: missing command");
358                                 error = true;
359                                 break;
360                         }
361                         string cmd = lexrc.getString();
362                         FuncRequest func;
363                         if (cmd == "*")
364                                 func = FuncRequest::unknown;
365                         else {
366                                 func = lyxaction.lookupFunc(cmd);
367                                 if (func == FuncRequest::unknown) {
368                                         lexrc.printError("BN_UNBIND: Unknown LyX function `$$Token'");
369                                         error = true;
370                                         break;
371                                 }
372                         }
373
374                         if (unbind_map)
375                                 unbind_map->bind(seq, func);
376                         else
377                                 unbind(seq, func);
378                         break;
379                 }
380
381                 case BN_BINDFILE:
382                         if (!lexrc.next()) {
383                                 lexrc.printError("BN_BINDFILE: Missing file name");
384                                 error = true;
385                                 break;
386                         }
387                         string tmp = lexrc.getString();
388                         if (prefixIs(tmp, "../")) {
389                                 tmp = split(tmp, '/');
390                                 // look in top dir
391                                 error |= !read(tmp, unbind_map, Default, false);
392                         } else
393                                 // i18n search
394                                 error |= !read(tmp, unbind_map);
395                         break;
396                 }
397
398                 // This is triggered the first time through the loop unless
399                 // we hit a format tag.
400                 if (format != LFUN_FORMAT)
401                         return FormatMismatch;
402         }
403
404         if (error) {
405                 LYXERR0("KeyMap::read: error while reading bind file:" << bind_file.absFileName());
406                 return ReadError;
407         }
408         return ReadOK;
409 }
410
411
412 void KeyMap::write(string const & bind_file, bool append, bool unbind) const
413 {
414         ofstream os(bind_file.c_str(),
415                 append ? (ios::app | ios::out) : ios::out);
416
417         if (!append)
418                 os << "## This file is automatically generated by lyx\n"
419                    << "## All modifications will be lost\n\n"
420                    << "Format " << LFUN_FORMAT << "\n\n";
421
422         string tag = unbind ? "\\unbind" : "\\bind";
423         for (auto const & bnd : listBindings(false)) {
424                 FuncCode const action = bnd.request.action();
425                 string const arg = to_utf8(bnd.request.argument());
426
427                 string cmd;
428                 if (unbind && bnd.request == FuncRequest::unknown)
429                         cmd = "*";
430                 else
431                         cmd = lyxaction.getActionName(action) + (arg.empty() ? string() : " " + arg);
432                 os << tag << " \""
433                    << to_utf8(bnd.sequence.print(KeySequence::BindFile))
434                    << "\" " << Lexer::quoteString(cmd)
435                    << "\n";
436         }
437         os << "\n";
438         os.close();
439 }
440
441
442 FuncRequest const & KeyMap::lookup(KeySymbol const &key,
443                   KeyModifier mod, KeySequence * seq) const
444 {
445         if (table.empty()) {
446                 seq->reset();
447                 return FuncRequest::unknown;
448         }
449
450         Table::const_iterator end = table.end();
451         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
452                 KeyModifier mask = cit->mod.second;
453                 KeyModifier check = static_cast<KeyModifier>(mod & ~mask);
454
455                 if (cit->code == key && cit->mod.first == check) {
456                         // match found
457                         if (cit->prefixes) {
458                                 // this is a prefix key - set new map
459                                 seq->curmap = cit->prefixes.get();
460                                 return FuncRequest::prefix;
461                         } else {
462                                 // final key - reset map
463                                 seq->reset();
464                                 return cit->func;
465                         }
466                 }
467         }
468
469         // error - key not found:
470         seq->reset();
471
472         return FuncRequest::unknown;
473 }
474
475
476 docstring const KeyMap::print(bool forgui) const
477 {
478         docstring buf;
479         Table::const_iterator end = table.end();
480         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
481                 buf += cit->code.print(cit->mod.first, forgui);
482                 buf += ' ';
483         }
484         return buf;
485 }
486
487
488 docstring KeyMap::printBindings(FuncRequest const & func,
489                                 KeySequence::outputFormat format,
490                                 bool const untranslated) const
491 {
492         Bindings bindings = findBindings(func);
493         if (bindings.empty())
494                 return docstring();
495
496         odocstringstream res;
497         Bindings::const_iterator cit = bindings.begin();
498         Bindings::const_iterator cit_end = bindings.end();
499         // print the first item
500         res << cit->print(format, untranslated);
501         // more than one shortcuts?
502         for (++cit; cit != cit_end; ++cit)
503                 res << ", " << cit->print(format, untranslated);
504         return res.str();
505 }
506
507
508 KeyMap::Bindings KeyMap::findBindings(FuncRequest const & func) const
509 {
510         return findBindings(func, KeySequence(nullptr, nullptr));
511 }
512
513
514 KeyMap::Bindings KeyMap::findBindings(FuncRequest const & func,
515                         KeySequence const & prefix) const
516 {
517         Bindings res;
518         if (table.empty())
519                 return res;
520
521         Table::const_iterator end = table.end();
522         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
523                 if (cit->prefixes) {
524                         KeySequence seq = prefix;
525                         seq.addkey(cit->code, cit->mod.first);
526                         Bindings res2 = cit->prefixes->findBindings(func, seq);
527                         res.insert(res.end(), res2.begin(), res2.end());
528                 } else if (cit->func == func) {
529                         KeySequence seq = prefix;
530                         seq.addkey(cit->code, cit->mod.first);
531                         res.push_back(seq);
532                 }
533         }
534
535         return res;
536 }
537
538
539 KeyMap::BindingList KeyMap::listBindings(bool unbound, KeyMap::ItemType tag) const
540 {
541         BindingList list;
542         listBindings(list, KeySequence(nullptr, nullptr), tag);
543         if (unbound) {
544                 for (auto const & name_code : lyxaction) {
545                         FuncCode action = name_code.second;
546                         bool has_action = false;
547                         BindingList::const_iterator bit = list.begin();
548                         BindingList::const_iterator const ben = list.end();
549                         for (; bit != ben; ++bit)
550                                 if (bit->request.action() == action) {
551                                         has_action = true;
552                                         break;
553                                 }
554                         if (!has_action)
555                                 list.push_back(Binding(FuncRequest(action), KeySequence(nullptr, nullptr), tag));
556                 }
557         }
558         return list;
559 }
560
561
562 void KeyMap::listBindings(BindingList & list,
563         KeySequence const & prefix, KeyMap::ItemType tag) const
564 {
565         Table::const_iterator it = table.begin();
566         Table::const_iterator it_end = table.end();
567         for (; it != it_end; ++it) {
568                 // a LFUN_COMMAND_PREFIX
569                 if (it->prefixes) {
570                         KeySequence seq = prefix;
571                         seq.addkey(it->code, it->mod.first);
572                         it->prefixes->listBindings(list, seq, tag);
573                 } else {
574                         KeySequence seq = prefix;
575                         seq.addkey(it->code, it->mod.first);
576                         list.push_back(Binding(it->func, seq, tag));
577                 }
578         }
579 }
580
581
582 } // namespace lyx