]> git.lyx.org Git - lyx.git/blob - src/KeyMap.cpp
c8f15d1cf96534c70b295f16b7defc2bc62be856
[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.origin = 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.origin = 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                 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                 frontend::Alert::warning(_("Could not find bind file"),
226                         bformat(_("Unable to find the bind file\n%1$s.\n"
227                                   "Falling back to default."), from_utf8(bind_file)));
228                 // So try it with the default file.
229                 if (read("cua", unbind_map))
230                         return true;
231                 lyxerr << "Could not find cua bind file!";
232                 frontend::Alert::warning(_("Could not find cua bind file"),
233                                 _("Unable to find the default bind file `cua'.\n"
234                                   "Please check your installation."));
235                 return false;
236         }
237         return read(bf, unbind_map);
238 }
239
240
241 bool KeyMap::read(FileName const & bind_file, KeyMap * unbind_map)
242 {
243         enum {
244                 BN_BIND,
245                 BN_BINDFILE,
246                 BN_UNBIND,
247         };
248
249         LexerKeyword bindTags[] = {
250                 { "\\bind",      BN_BIND },
251                 { "\\bind_file", BN_BINDFILE },
252                 { "\\unbind",    BN_UNBIND },
253         };
254
255         Lexer lexrc(bindTags);
256         if (lyxerr.debugging(Debug::PARSER))
257                 lexrc.printTable(lyxerr);
258
259         lexrc.setFile(bind_file);
260         if (!lexrc.isOK()) {
261                 LYXERR0("KeyMap::read: cannot open bind file:" << bind_file.absFilename());
262                 return false;
263         }
264
265         LYXERR(Debug::KBMAP, "Reading bind file:" << bind_file.absFilename());
266
267         bool error = false;
268         while (lexrc.isOK()) {
269                 switch (lexrc.lex()) {
270
271                 case Lexer::LEX_UNDEF:
272                         lexrc.printError("Unknown tag `$$Token'");
273                         error = true;
274                         continue;
275
276                 case Lexer::LEX_FEOF:
277                         continue;
278
279                 case BN_BIND: {
280                         if (!lexrc.next()) {
281                                 lexrc.printError("BN_BIND: Missing key sequence");
282                                 error = true;
283                                 break;
284                         }
285                         string seq = lexrc.getString();
286
287                         if (!lexrc.next(true)) {
288                                 lexrc.printError("BN_BIND: missing command");
289                                 error = true;
290                                 break;
291                         }
292                         string cmd = lexrc.getString();
293
294                         FuncRequest func = lyxaction.lookupFunc(cmd);
295                         if (func.action == LFUN_UNKNOWN_ACTION) {
296                                 lexrc.printError("BN_BIND: Unknown LyX function `$$Token'");
297                                 error = true;
298                                 break;
299                         }
300
301                         bind(seq, func);
302                         break;
303                 }
304
305                 case BN_UNBIND: {
306                         if (!lexrc.next()) {
307                                 lexrc.printError("BN_UNBIND: Missing key sequence");
308                                 error = true;
309                                 break;
310                         }
311                         string seq = lexrc.getString();
312
313                         if (!lexrc.next(true)) {
314                                 lexrc.printError("BN_UNBIND: missing command");
315                                 error = true;
316                                 break;
317                         }
318                         string cmd = lexrc.getString();
319
320                         FuncRequest func = lyxaction.lookupFunc(cmd);
321                         if (func.action == LFUN_UNKNOWN_ACTION) {
322                                 lexrc.printError("BN_UNBIND: Unknown LyX"
323                                                  " function `$$Token'");
324                                 error = true;
325                                 break;
326                         }
327                         
328                         if (unbind_map)
329                                 unbind_map->bind(seq, func);
330                         else
331                                 unbind(seq, func);
332                         break;
333                 }
334
335                 case BN_BINDFILE:
336                         if (!lexrc.next()) {
337                                 lexrc.printError("BN_BINDFILE: Missing file name");
338                                 error = true;
339                                 break;
340                         }
341                         string const tmp = lexrc.getString();
342                         error |= !read(tmp, unbind_map);
343                         break;
344                 }
345         }
346
347         if (error)
348                 LYXERR0("KeyMap::read: error while reading bind file:" << bind_file.absFilename());
349         return !error;
350 }
351
352
353 void KeyMap::write(string const & bind_file, bool append, bool unbind) const
354 {
355         ofstream os(bind_file.c_str(), 
356                 append ? (ios::app | ios::out) : ios::out);
357
358         if (!append)
359                 os << "## This file is automatically generated by lyx\n"
360                    << "## All modifications will be lost\n\n";
361         
362         string tag = unbind ? "\\unbind" : "\\bind";
363         BindingList const list = listBindings(false);
364         BindingList::const_iterator it = list.begin();
365         BindingList::const_iterator it_end = list.end();
366         for (; it != it_end; ++it) {
367                 FuncCode action = it->request.action;
368                 string arg = to_utf8(it->request.argument());
369
370                 os << tag << " \""
371                                 << to_utf8(it->sequence.print(KeySequence::BindFile))
372                                 << "\" \""
373                                 << lyxaction.getActionName(action)
374                                 << (arg.empty() ? "" : " ") << arg
375                                 << "\"\n";
376         }
377         os << "\n";
378         os.close();
379 }
380
381
382 FuncRequest const & KeyMap::lookup(KeySymbol const &key,
383                   KeyModifier mod, KeySequence * seq) const
384 {
385         if (table.empty()) {
386                 seq->reset();
387                 return FuncRequest::unknown;
388         }
389
390         Table::const_iterator end = table.end();
391         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
392                 KeyModifier mask = cit->mod.second;
393                 KeyModifier check = static_cast<KeyModifier>(mod & ~mask);
394
395                 if (cit->code == key && cit->mod.first == check) {
396                         // match found
397                         if (cit->prefixes.get()) {
398                                 // this is a prefix key - set new map
399                                 seq->curmap = cit->prefixes.get();
400                                 static FuncRequest prefix(LFUN_COMMAND_PREFIX);
401                                 return prefix;
402                         } else {
403                                 // final key - reset map
404                                 seq->reset();
405                                 return cit->func;
406                         }
407                 }
408         }
409
410         // error - key not found:
411         seq->reset();
412
413         return FuncRequest::unknown;
414 }
415
416
417 docstring const KeyMap::print(bool forgui) const
418 {
419         docstring buf;
420         Table::const_iterator end = table.end();
421         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
422                 buf += cit->code.print(cit->mod.first, forgui);
423                 buf += ' ';
424         }
425         return buf;
426 }
427
428
429 docstring KeyMap::printBindings(FuncRequest const & func,
430                                 KeySequence::outputFormat format) const
431 {
432         Bindings bindings = findBindings(func);
433         if (bindings.empty())
434                 return docstring();
435         
436         odocstringstream res;
437         Bindings::const_iterator cit = bindings.begin();
438         Bindings::const_iterator cit_end = bindings.end();
439         // print the first item
440         res << cit->print(format);
441         // more than one shortcuts?
442         for (++cit; cit != cit_end; ++cit)
443                 res << ", " << cit->print(format);
444         return res.str();
445 }
446
447
448 KeyMap::Bindings KeyMap::findBindings(FuncRequest const & func) const
449 {
450         return findBindings(func, KeySequence(0, 0));
451 }
452
453
454 KeyMap::Bindings KeyMap::findBindings(FuncRequest const & func,
455                         KeySequence const & prefix) const
456 {
457         Bindings res;
458         if (table.empty())
459                 return res;
460
461         Table::const_iterator end = table.end();
462         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
463                 if (cit->prefixes.get()) {
464                         KeySequence seq = prefix;
465                         seq.addkey(cit->code, cit->mod.first);
466                         Bindings res2 = cit->prefixes->findBindings(func, seq);
467                         res.insert(res.end(), res2.begin(), res2.end());
468                 } else if (cit->func == func) {
469                         KeySequence seq = prefix;
470                         seq.addkey(cit->code, cit->mod.first);
471                         res.push_back(seq);
472                 }
473         }
474
475         return res;
476 }
477
478
479 KeyMap::BindingList KeyMap::listBindings(bool unbound, KeyMap::ItemType tag) const
480 {
481         BindingList list;
482         listBindings(list, KeySequence(0, 0), tag);
483         if (unbound) {
484                 LyXAction::const_func_iterator fit = lyxaction.func_begin();
485                 LyXAction::const_func_iterator fit_end = lyxaction.func_end();
486                 for (; fit != fit_end; ++fit) {
487                         FuncCode action = fit->second;
488                         bool has_action = false;
489                         BindingList::const_iterator it = list.begin();
490                         BindingList::const_iterator it_end = list.end();
491                         for (; it != it_end; ++it)
492                                 if (it->request.action == action) {
493                                         has_action = true;
494                                         break;
495                                 }
496                         if (!has_action)
497                                 list.push_back(Binding(FuncRequest(action), KeySequence(0, 0), tag));
498                 }       
499         }
500         return list;
501 }
502
503
504 void KeyMap::listBindings(BindingList & list,
505         KeySequence const & prefix, KeyMap::ItemType tag) const
506 {
507         Table::const_iterator it = table.begin();
508         Table::const_iterator it_end = table.end();
509         for (; it != it_end; ++it) {
510                 // a LFUN_COMMAND_PREFIX
511                 if (it->prefixes.get()) {
512                         KeySequence seq = prefix;
513                         seq.addkey(it->code, it->mod.first);
514                         it->prefixes->listBindings(list, seq, tag);
515                 } else {
516                         KeySequence seq = prefix;
517                         seq.addkey(it->code, it->mod.first);
518                         list.push_back(Binding(it->func, seq, tag));
519                 }
520         }
521 }
522
523
524 } // namespace lyx