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