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