]> git.lyx.org Git - lyx.git/blob - src/MenuBackend.C
move some selection related stuff over to textcursor.C
[lyx.git] / src / MenuBackend.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  *
10  * ====================================================== */
11
12 #include <config.h>
13
14 #include "MenuBackend.h"
15 #include "lyxlex.h"
16 #include "LyXAction.h"
17 #include "debug.h"
18 #include "gettext.h"
19 #include "kbmap.h"
20 #include "lastfiles.h"
21 #include "lyxfunc.h"
22 #include "lyx_main.h" // for lastfiles
23 #include "bufferlist.h"
24 #include "buffer.h"
25 #include "format.h"
26 #include "exporter.h"
27 #include "importer.h"
28 #include "FloatList.h"
29 #include "toc.h"
30 #include "CutAndPaste.h"
31 #include "frontends/LyXView.h"
32 #include "support/LAssert.h"
33 #include "support/filetools.h"
34 #include "support/lyxfunctional.h"
35 #include "support/lstrings.h"
36 #include "support/tostr.h"
37
38 #include <algorithm>
39
40 extern BufferList bufferlist;
41 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
42
43 using std::endl;
44 using std::vector;
45 using std::max;
46 using std::pair;
47 using std::find_if;
48 using std::sort;
49
50 // This is the global menu definition
51 MenuBackend menubackend;
52
53
54 MenuItem::MenuItem(Kind kind, string const & label,
55                    string const & command, bool optional)
56         : kind_(kind), label_(label), optional_(optional)
57 {
58         switch (kind) {
59         case Separator:
60         case Documents:
61         case Lastfiles:
62         case Toc:
63         case ViewFormats:
64         case UpdateFormats:
65         case ExportFormats:
66         case ImportFormats:
67         case FloatListInsert:
68         case FloatInsert:
69         case PasteRecent:
70                 break;
71         case Command:
72                 action_ = lyxaction.LookupFunc(command);
73
74                 if (action_ == LFUN_UNKNOWN_ACTION) {
75                         lyxerr << "MenuItem(): LyX command `"
76                                << command << "' does not exist." << endl;
77                 }
78                 if (optional_)
79                         lyxerr[Debug::GUI] << "Optional item "
80                                            << command << endl;
81                 break;
82         case Submenu:
83                 submenuname_ = command;
84                 break;
85         }
86 }
87
88
89 MenuItem::MenuItem(Kind kind, string const & label, int action, bool optional)
90         : kind_(kind), label_(label), action_(action), submenuname_(),
91           optional_(optional)
92 {}
93
94
95 MenuItem::~MenuItem()
96 {}
97
98
99 void MenuItem::submenu(Menu * menu)
100 {
101         submenu_.reset(menu);
102 }
103
104
105 string const MenuItem::label() const
106 {
107         return token(label_, '|', 0);
108 }
109
110
111 string const MenuItem::shortcut() const
112 {
113         return token(label_, '|', 1);
114 }
115
116 string const MenuItem::binding() const
117 {
118         if (kind_ != Command)
119                 return string();
120
121         // Get the keys bound to this action, but keep only the
122         // first one later
123         string bindings = toplevel_keymap->findbinding(action_);
124
125         if (!bindings.empty()) {
126                 return bindings.substr(1, bindings.find(']') - 1);
127         } else
128                 return string();
129 }
130
131
132 Menu & Menu::add(MenuItem const & i, LyXView const * view)
133 {
134         if (!view) {
135                 items_.push_back(i);
136                 return *this;
137         }
138
139         switch (i.kind()) {
140         case MenuItem::Command:
141         {
142                 FuncStatus status =
143                         view->getLyXFunc().getStatus(i.action());
144                 if (status.unknown()
145                     || (status.disabled() && i.optional()))
146                         break;
147                 items_.push_back(i);
148                 items_.back().status(status);
149                 break;
150         }
151         case MenuItem::Submenu:
152         {
153                 if (i.submenu()) {
154                         bool disabled = true;
155                         for (const_iterator cit = i.submenu()->begin();
156                              cit != i.submenu()->end(); ++cit) {
157                                 if ((cit->kind() == MenuItem::Command
158                                      || cit->kind() == MenuItem::Submenu)
159                                     && !cit->status().disabled()) {
160                                         disabled = false;
161                                         break;
162                                 }
163                         }
164                         if (!disabled || !i.optional()) {
165                                 items_.push_back(i);
166                                 items_.back().status().disabled(disabled);
167                         }
168                 }
169                 else
170                         items_.push_back(i);
171                 break;
172         }
173         case MenuItem::Separator:
174                 if (!items_.empty()
175                     && items_.back().kind() != MenuItem::Separator)
176                         items_.push_back(i);
177                 break;
178         default:
179                 items_.push_back(i);
180         }
181
182         return *this;
183 }
184
185
186 Menu & Menu::read(LyXLex & lex)
187 {
188         enum Menutags {
189                 md_item = 1,
190                 md_documents,
191                 md_endmenu,
192                 md_exportformats,
193                 md_importformats,
194                 md_lastfiles,
195                 md_optitem,
196                 md_optsubmenu,
197                 md_separator,
198                 md_submenu,
199                 md_toc,
200                 md_updateformats,
201                 md_viewformats,
202                 md_floatlistinsert,
203                 md_floatinsert,
204                 md_pasterecent,
205                 md_last
206         };
207
208         struct keyword_item menutags[md_last - 1] = {
209                 { "documents", md_documents },
210                 { "end", md_endmenu },
211                 { "exportformats", md_exportformats },
212                 { "floatinsert", md_floatinsert },
213                 { "floatlistinsert", md_floatlistinsert },
214                 { "importformats", md_importformats },
215                 { "item", md_item },
216                 { "lastfiles", md_lastfiles },
217                 { "optitem", md_optitem },
218                 { "optsubmenu", md_optsubmenu },
219                 { "pasterecent", md_pasterecent },
220                 { "separator", md_separator },
221                 { "submenu", md_submenu },
222                 { "toc", md_toc },
223                 { "updateformats", md_updateformats },
224                 { "viewformats", md_viewformats }
225         };
226
227         lex.pushTable(menutags, md_last - 1);
228         if (lyxerr.debugging(Debug::PARSER))
229                 lex.printTable(lyxerr);
230
231         bool quit = false;
232         bool optional = false;
233
234         while (lex.isOK() && !quit) {
235                 switch (lex.lex()) {
236                 case md_optitem:
237                         optional = true;
238                         // fallback to md_item
239                 case md_item: {
240                         lex.next(true);
241                         string const name = _(lex.getString());
242                         lex.next(true);
243                         string const command = lex.getString();
244                         add(MenuItem(MenuItem::Command, name,
245                                      command, optional));
246                         optional = false;
247                         break;
248                 }
249
250                 case md_separator:
251                         add(MenuItem(MenuItem::Separator));
252                         break;
253
254                 case md_lastfiles:
255                         add(MenuItem(MenuItem::Lastfiles));
256                         break;
257
258                 case md_documents:
259                         add(MenuItem(MenuItem::Documents));
260                         break;
261
262                 case md_toc:
263                         add(MenuItem(MenuItem::Toc));
264                         break;
265
266                 case md_viewformats:
267                         add(MenuItem(MenuItem::ViewFormats));
268                         break;
269
270                 case md_updateformats:
271                         add(MenuItem(MenuItem::UpdateFormats));
272                         break;
273
274                 case md_exportformats:
275                         add(MenuItem(MenuItem::ExportFormats));
276                         break;
277
278                 case md_importformats:
279                         add(MenuItem(MenuItem::ImportFormats));
280                         break;
281
282                 case md_floatlistinsert:
283                         add(MenuItem(MenuItem::FloatListInsert));
284                         break;
285
286                 case md_floatinsert:
287                         add(MenuItem(MenuItem::FloatInsert));
288                         break;
289
290                 case md_pasterecent:
291                         add(MenuItem(MenuItem::PasteRecent));
292                         break;
293
294                 case md_optsubmenu:
295                         optional = true;
296                         // fallback to md_submenu
297                 case md_submenu: {
298                         lex.next(true);
299                         string const mlabel = _(lex.getString());
300                         lex.next(true);
301                         string const mname = lex.getString();
302                         add(MenuItem(MenuItem::Submenu, mlabel, mname,
303                                      optional));
304                         optional = false;
305                         break;
306                 }
307
308                 case md_endmenu:
309                         quit = true;
310                         break;
311
312                 default:
313                         lex.printError("Menu::read: "
314                                        "Unknown menu tag: `$$Token'");
315                         break;
316                 }
317         }
318         lex.popTable();
319         return *this;
320 }
321
322
323 void Menu::checkShortcuts() const
324 {
325         // This is a quadratic algorithm, but we do not care because
326         // it is used for debugging only.
327         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
328                 string shortcut = it1->shortcut();
329                 if (shortcut.empty())
330                         continue;
331                 if (!contains(it1->label(), shortcut))
332                         lyxerr << "Menu warning: menu entry \""
333                                << it1->label()
334                                << "\" does not contain shortcut `"
335                                << shortcut << '\'' << endl;
336                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
337                         if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
338                                 lyxerr << "Menu warning: menu entries "
339                                        << '"' << it1->fulllabel()
340                                        << "\" and \"" << it2->fulllabel()
341                                        << "\" share the same shortcut."
342                                        << endl;
343                         }
344                 }
345         }
346 }
347
348
349 namespace {
350
351 class compare_format {
352 public:
353         bool operator()(Format const * p1, Format const * p2) {
354                 return *p1 < *p2;
355         }
356 };
357
358 string const limit_string_length(string const & str)
359 {
360         string::size_type const max_item_length = 45;
361
362         if (str.size() > max_item_length)
363                 return str.substr(0, max_item_length - 3) + "...";
364         else
365                 return str;
366 }
367
368
369 void expandLastfiles(Menu & tomenu, LyXView const * view)
370 {
371         int ii = 1;
372         LastFiles::const_iterator lfit = lastfiles->begin();
373         LastFiles::const_iterator end = lastfiles->end();
374
375         for (; lfit != end && ii < 10; ++lfit, ++ii) {
376                 string const label = tostr(ii) + ". "
377                         + MakeDisplayPath((*lfit), 30)
378                         + '|' + tostr(ii);
379                 int const action = lyxaction.
380                         getPseudoAction(LFUN_FILE_OPEN,
381                                         (*lfit));
382                 tomenu.add(MenuItem(MenuItem::Command, label, action), view);
383         }
384 }
385
386 void expandDocuments(Menu & tomenu, LyXView const * view)
387 {
388         typedef vector<string> Strings;
389         Strings const names = bufferlist.getFileNames();
390
391         if (names.empty()) {
392                 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
393                                     LFUN_NOACTION), view);
394                 return;
395         }
396
397         int ii = 1;
398         Strings::const_iterator docit = names.begin();
399         Strings::const_iterator end = names.end();
400         for (; docit != end; ++docit, ++ii) {
401                 int const action =
402                         lyxaction.getPseudoAction(LFUN_SWITCHBUFFER, *docit);
403                 string label = MakeDisplayPath(*docit, 20);
404                 if (ii < 10)
405                         label = tostr(ii) + ". " + label + '|' + tostr(ii);
406                 tomenu.add(MenuItem(MenuItem::Command, label, action), view);
407         }
408 }
409
410
411 void expandFormats(MenuItem::Kind kind, Menu & tomenu, LyXView const * view)
412 {
413         if (!view->buffer() && kind != MenuItem::ImportFormats) {
414                 tomenu.add(MenuItem(MenuItem::Command,
415                                     _("No Documents Open!"), LFUN_NOACTION),
416                                     view);
417                 return;
418         }
419
420         typedef vector<Format const *> Formats;
421         Formats formats;
422         kb_action action;
423
424         switch (kind) {
425         case MenuItem::ImportFormats:
426                 formats = Importer::GetImportableFormats();
427                 action = LFUN_IMPORT;
428                 break;
429         case MenuItem::ViewFormats:
430                 formats = Exporter::GetExportableFormats(view->buffer(), true);
431                 action = LFUN_PREVIEW;
432                 break;
433         case MenuItem::UpdateFormats:
434                 formats = Exporter::GetExportableFormats(view->buffer(), true);
435                 action = LFUN_UPDATE;
436                 break;
437         default:
438                 formats = Exporter::GetExportableFormats(view->buffer(), false);
439                 action = LFUN_EXPORT;
440         }
441         sort(formats.begin(), formats.end(), compare_format());
442
443         Formats::const_iterator fit = formats.begin();
444         Formats::const_iterator end = formats.end();
445         for (; fit != end ; ++fit) {
446                 if ((*fit)->dummy())
447                         continue;
448                 string label = (*fit)->prettyname();
449                 // we need to hide the default graphic export formats
450                 // from the external menu, because we need them only
451                 // for the internal lyx-view and external latex run
452                 if (label == "EPS" || label == "XPM" || label == "PNG")
453                         continue;
454
455                 if (kind == MenuItem::ImportFormats) {
456                         if ((*fit)->name() == "text")
457                                 label = _("ASCII text as lines");
458                         else if ((*fit)->name() == "textparagraph")
459                                 label = _("ASCII text as paragraphs");
460                         label += "...";
461                 }
462                 if (!(*fit)->shortcut().empty())
463                         label += '|' + (*fit)->shortcut();
464                 int const action2 = lyxaction.
465                         getPseudoAction(action, (*fit)->name());
466                 tomenu.add(MenuItem(MenuItem::Command, label, action2),
467                            view);
468         }
469 }
470
471
472 void expandFloatListInsert(Menu & tomenu, LyXView const * view)
473 {
474         if (!view->buffer()) {
475                 tomenu.add(MenuItem(MenuItem::Command,
476                                     _("No Documents Open!"), LFUN_NOACTION),
477                            view);
478                 return;
479         }
480
481         FloatList const & floats =
482                 view->buffer()->params.getLyXTextClass().floats();
483         FloatList::const_iterator cit = floats.begin();
484         FloatList::const_iterator end = floats.end();
485         for (; cit != end; ++cit) {
486                 int const action =  lyxaction
487                         .getPseudoAction(LFUN_FLOAT_LIST, cit->second.type());
488                 tomenu.add(MenuItem(MenuItem::Command,
489                                     _(cit->second.listName()), action),
490                            view);
491         }
492 }
493
494
495 void expandFloatInsert(Menu & tomenu, LyXView const * view)
496 {
497         if (!view->buffer()) {
498                 tomenu.add(MenuItem(MenuItem::Command,
499                                     _("No Documents Open!"), LFUN_NOACTION),
500                            view);
501                 return;
502         }
503
504         FloatList const & floats =
505                 view->buffer()->params.getLyXTextClass().floats();
506         FloatList::const_iterator cit = floats.begin();
507         FloatList::const_iterator end = floats.end();
508         for (; cit != end; ++cit) {
509                 // normal float
510                 int const action =
511                         lyxaction.getPseudoAction(LFUN_INSET_FLOAT,
512                                                   cit->second.type());
513                 string const label = _(cit->second.name());
514                 tomenu.add(MenuItem(MenuItem::Command, label, action),
515                            view);
516         }
517 }
518
519
520 Menu::size_type const max_number_of_items = 25;
521
522 void expandToc2(Menu & tomenu, toc::Toc const & toc_list,
523                 toc::Toc::size_type from, toc::Toc::size_type to, int depth)
524 {
525         int shortcut_count = 0;
526         if (to - from <= max_number_of_items) {
527                 for (toc::Toc::size_type i = from; i < to; ++i) {
528                         int const action = toc_list[i].action();
529                         string label(4 * max(0, toc_list[i].depth - depth),' ');
530                         label += limit_string_length(toc_list[i].str);
531                         if (toc_list[i].depth == depth
532                             && ++shortcut_count <= 9) {
533                                 label += '|' + tostr(shortcut_count);
534                         }
535                         tomenu.add(MenuItem(MenuItem::Command, label, action));
536                 }
537         } else {
538                 toc::Toc::size_type pos = from;
539                 while (pos < to) {
540                         toc::Toc::size_type new_pos = pos + 1;
541                         while (new_pos < to &&
542                                toc_list[new_pos].depth > depth)
543                                 ++new_pos;
544
545                         int const action = toc_list[pos].action();
546                         string label(4 * max(0, toc_list[pos].depth - depth), ' ');
547                         label += limit_string_length(toc_list[pos].str);
548                         if (toc_list[pos].depth == depth &&
549                             ++shortcut_count <= 9)
550                                 label += '|' + tostr(shortcut_count);
551
552                         if (new_pos == pos + 1) {
553                                 tomenu.add(MenuItem(MenuItem::Command,
554                                                     label, action));
555                         } else {
556                                 MenuItem item(MenuItem::Submenu, label);
557                                 item.submenu(new Menu);
558                                 expandToc2(*item.submenu(),
559                                            toc_list, pos, new_pos, depth + 1);
560                                 tomenu.add(item);
561                         }
562                         pos = new_pos;
563                 }
564         }
565 }
566
567
568 void expandToc(Menu & tomenu, LyXView const * view)
569 {
570         // To make things very cleanly, we would have to pass view to
571         // all MenuItem constructors and to expandToc2. However, we
572         // know that all the entries in a TOC will be have status_ ==
573         // OK, so we avoid this unnecessary overhead (JMarc)
574
575         if (!view->buffer()) {
576                 tomenu.add(MenuItem(MenuItem::Command,
577                                     _("No Documents Open!"), LFUN_NOACTION),
578                            view);
579                 return;
580         }
581
582         toc::TocList toc_list = toc::getTocList(view->buffer());
583         toc::TocList::const_iterator cit = toc_list.begin();
584         toc::TocList::const_iterator end = toc_list.end();
585         for (; cit != end; ++cit) {
586                 // Handle this later
587                 if (cit->first == "TOC")
588                         continue;
589
590                 // All the rest is for floats
591                 Menu * menu = new Menu;
592                 toc::Toc::const_iterator ccit = cit->second.begin();
593                 toc::Toc::const_iterator eend = cit->second.end();
594                 for (; ccit != eend; ++ccit) {
595                         string const label = limit_string_length(ccit->str);
596                         menu->add(MenuItem(MenuItem::Command,
597                                            label, ccit->action()));
598                 }
599                 string const & floatName = cit->first;
600                 // Is the _(...) really needed here? (Lgb)
601                 MenuItem item(MenuItem::Submenu, _(floatName));
602                 item.submenu(menu);
603                 tomenu.add(item);
604         }
605
606         // Handle normal TOC
607         cit = toc_list.find("TOC");
608         if (cit == end) {
609                 tomenu.add(MenuItem(MenuItem::Command,
610                                     _("No Table of contents")),
611                            view);
612         } else {
613                 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
614         }
615 }
616
617
618 void expandPasteRecent(Menu & tomenu, LyXView const * view)
619 {
620         vector<string> const selL =
621                 CutAndPaste::availableSelections(*view->buffer());
622         
623         vector<string>::const_iterator cit = selL.begin();
624         vector<string>::const_iterator end = selL.end();
625         
626         for (unsigned int index = 0; cit != end; ++cit, ++index) {
627                 int const action = lyxaction.getPseudoAction(LFUN_PASTE,
628                                                              tostr(index));
629                 tomenu.add(MenuItem(MenuItem::Command, *cit, action));
630         }
631 }
632
633
634 } // namespace anon
635
636
637 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
638                          LyXView const * view) const
639 {
640         for (Menu::const_iterator cit = frommenu.begin();
641              cit != frommenu.end() ; ++cit) {
642                 switch (cit->kind()) {
643                 case MenuItem::Lastfiles:
644                         expandLastfiles(tomenu, view);
645                         break;
646
647                 case MenuItem::Documents:
648                         expandDocuments(tomenu, view);
649                         break;
650
651                 case MenuItem::ImportFormats:
652                 case MenuItem::ViewFormats:
653                 case MenuItem::UpdateFormats:
654                 case MenuItem::ExportFormats:
655                         expandFormats(cit->kind(), tomenu, view);
656                         break;
657
658                 case MenuItem::FloatListInsert:
659                         expandFloatListInsert(tomenu, view);
660                         break;
661
662                 case MenuItem::FloatInsert:
663                         expandFloatInsert(tomenu, view);
664                         break;
665
666                 case MenuItem::PasteRecent:
667                         expandPasteRecent(tomenu, view);
668                         break;
669
670                 case MenuItem::Toc:
671                         expandToc(tomenu, view);
672                         break;
673
674                 case MenuItem::Submenu: {
675                         MenuItem item(*cit);
676                         item.submenu(new Menu(cit->submenuname()));
677                         expand(getMenu(cit->submenuname()),
678                                *item.submenu(), view);
679                         tomenu.add(item, view);
680                 }
681                 break;
682
683                 default:
684                         tomenu.add(*cit, view);
685                 }
686         }
687
688         // we do not want the menu to end with a separator
689         if (!tomenu.empty()
690             && tomenu.items_.back().kind() == MenuItem::Separator)
691                 tomenu.items_.pop_back();
692
693         // Check whether the shortcuts are unique
694         if (lyxerr.debugging(Debug::GUI))
695                 tomenu.checkShortcuts();
696 }
697
698
699 bool Menu::hasSubmenu(string const & name) const
700 {
701         return find_if(begin(), end(),
702                        lyx::compare_memfun(&MenuItem::submenuname,
703                                            name)) != end();
704 }
705
706
707 void MenuBackend::read(LyXLex & lex)
708 {
709         enum Menutags {
710                 md_menu = 1,
711                 md_menubar,
712                 md_endmenuset,
713                 md_last
714         };
715
716         struct keyword_item menutags[md_last - 1] = {
717                 { "end", md_endmenuset },
718                 { "menu", md_menu },
719                 { "menubar", md_menubar }
720         };
721
722         //consistency check
723         if (compare_ascii_no_case(lex.getString(), "menuset")) {
724                 lyxerr << "Menubackend::read: ERROR wrong token:`"
725                        << lex.getString() << '\'' << endl;
726         }
727
728         lex.pushTable(menutags, md_last - 1);
729         if (lyxerr.debugging(Debug::PARSER))
730                 lex.printTable(lyxerr);
731
732         bool quit = false;
733
734         while (lex.isOK() && !quit) {
735                 switch (lex.lex()) {
736                 case md_menubar:
737                         menubar_.read(lex);
738                         break;
739                 case md_menu: {
740                         lex.next(true);
741                         string const name = lex.getString();
742                         if (hasMenu(name)) {
743                                 getMenu(name).read(lex);
744                         } else {
745                                 Menu menu(name);
746                                 menu.read(lex);
747                                 add(menu);
748                         }
749                         break;
750                 }
751                 case md_endmenuset:
752                         quit = true;
753                         break;
754                 default:
755                         lex.printError("menubackend::read: "
756                                        "Unknown menu tag: `$$Token'");
757                         break;
758                 }
759         }
760         lex.popTable();
761 }
762
763
764 void MenuBackend::add(Menu const & menu)
765 {
766         menulist_.push_back(menu);
767 }
768
769
770 bool MenuBackend::hasMenu(string const & name) const
771 {
772         return find_if(begin(), end(),
773                        lyx::compare_memfun(&Menu::name, name)) != end();
774 }
775
776
777 Menu const & MenuBackend::getMenu(string const & name) const
778 {
779         const_iterator cit = find_if(begin(), end(),
780                                      lyx::compare_memfun(&Menu::name, name));
781         if (cit == end())
782                 lyxerr << "No submenu named " << name << endl;
783         lyx::Assert(cit != end());
784         return (*cit);
785 }
786
787
788 Menu & MenuBackend::getMenu(string const & name)
789 {
790         MenuList::iterator it =
791                 find_if(menulist_.begin(), menulist_.end(),
792                         lyx::compare_memfun(&Menu::name, name));
793         lyx::Assert(it != menulist_.end());
794         return (*it);
795 }
796
797
798 Menu const & MenuBackend::getMenubar() const
799 {
800         return menubar_;
801 }