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