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