]> git.lyx.org Git - lyx.git/blob - src/MenuBackend.C
f3f7fff25a51573932fba928bdf8f15504efe7ba
[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                 if (!(*fit)->shortcut().empty())
382                         label += "|" + (*fit)->shortcut();
383                 int const action2 = lyxaction.
384                         getPseudoAction(action, (*fit)->name());
385                 tomenu.add(MenuItem(MenuItem::Command, label, action2));
386         }
387 }
388
389
390 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
391 {
392         if (!buf) {
393                 tomenu.add(MenuItem(MenuItem::Command,
394                                     _("No Documents Open!"), LFUN_NOACTION));
395                 return;
396         }
397
398         FloatList const & floats = buf->params.getLyXTextClass().floats();
399         FloatList::const_iterator cit = floats.begin();
400         FloatList::const_iterator end = floats.end();
401         for (; cit != end; ++cit) {
402                 int const action =  lyxaction
403                         .getPseudoAction(LFUN_FLOAT_LIST, cit->second.type());
404                 tomenu.add(MenuItem(MenuItem::Command,
405                                     _(cit->second.listName()),
406                                     action));
407         }
408 }
409
410
411 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
412 {
413         if (!buf) {
414                 tomenu.add(MenuItem(MenuItem::Command,
415                                     _("No Documents Open!"), LFUN_NOACTION));
416                 return;
417         }
418
419         FloatList const & floats = buf->params.getLyXTextClass().floats();
420         FloatList::const_iterator cit = floats.begin();
421         FloatList::const_iterator end = floats.end();
422         for (; cit != end; ++cit) {
423                 // normal float
424                 int const action =
425                         lyxaction.getPseudoAction(LFUN_INSET_FLOAT,
426                                                   cit->second.type());
427                 string const label = _(cit->second.name());
428                 tomenu.add(MenuItem(MenuItem::Command, label, action));
429         }
430 }
431
432
433 Menu::size_type const max_number_of_items = 25;
434
435 void expandToc2(Menu & tomenu, toc::Toc const & toc_list,
436                 toc::Toc::size_type from, toc::Toc::size_type to, int depth)
437 {
438         int shortcut_count = 0;
439         if (to - from <= max_number_of_items) {
440                 for (toc::Toc::size_type i = from; i < to; ++i) {
441                         int const action = toc_list[i].action();
442                         string label(4 * max(0, toc_list[i].depth - depth),' ');
443                         label += limit_string_length(toc_list[i].str);
444                         if (toc_list[i].depth == depth
445                             && ++shortcut_count <= 9) {
446                                 label += "|" + tostr(shortcut_count);
447                         }
448                         tomenu.add(MenuItem(MenuItem::Command, label, action));
449                 }
450         } else {
451                 toc::Toc::size_type pos = from;
452                 while (pos < to) {
453                         toc::Toc::size_type new_pos = pos + 1;
454                         while (new_pos < to &&
455                                toc_list[new_pos].depth > depth)
456                                 ++new_pos;
457
458                         int const action = toc_list[pos].action();
459                         string label(4 * max(0, toc_list[pos].depth - depth), ' ');
460                         label += limit_string_length(toc_list[pos].str);
461                         if (toc_list[pos].depth == depth &&
462                             ++shortcut_count <= 9)
463                                 label += '|' + tostr(shortcut_count);
464
465                         if (new_pos == pos + 1) {
466                                 tomenu.add(MenuItem(MenuItem::Command,
467                                                     label, action));
468                         } else {
469                                 MenuItem item(MenuItem::Submenu, label);
470                                 item.submenu(new Menu);
471                                 expandToc2(*item.submenu(),
472                                            toc_list, pos, new_pos, depth + 1);
473                                 tomenu.add(item);
474                         }
475                         pos = new_pos;
476                 }
477         }
478 }
479
480
481 void expandToc(Menu & tomenu, Buffer const * buf)
482 {
483         FloatList const & floats = buf->params.getLyXTextClass().floats();
484         toc::TocList toc_list = toc::getTocList(buf);
485         toc::TocList::const_iterator cit = toc_list.begin();
486         toc::TocList::const_iterator end = toc_list.end();
487         for (; cit != end; ++cit) {
488                 // Handle this later
489                 if (cit->first == "TOC") continue;
490
491                 // All the rest is for floats
492                 Menu * menu = new Menu;
493                 toc::Toc::const_iterator ccit = cit->second.begin();
494                 toc::Toc::const_iterator eend = cit->second.end();
495                 for (; ccit != eend; ++ccit) {
496                         string const label = limit_string_length(ccit->str);
497                         menu->add(MenuItem(MenuItem::Command,
498                                            label, ccit->action()));
499                 }
500                 MenuItem item(MenuItem::Submenu,
501                               floats[cit->first]->second.name());
502                 item.submenu(menu);
503                 tomenu.add(item);
504         }
505
506         // Handle normal TOC
507         cit = toc_list.find("TOC");
508         if (cit == end) {
509                 tomenu.add(MenuItem(MenuItem::Command,
510                                     _("No Table of contents")));
511         } else {
512                 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
513         }
514 }
515
516
517 } // namespace anon
518
519
520 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
521                          Buffer const * buf) const
522 {
523         for (Menu::const_iterator cit = frommenu.begin();
524              cit != frommenu.end() ; ++cit) {
525                 switch (cit->kind()) {
526                 case MenuItem::Lastfiles:
527                         expandLastfiles(tomenu);
528                         break;
529
530                 case MenuItem::Documents:
531                         expandDocuments(tomenu);
532                         break;
533
534                 case MenuItem::ImportFormats:
535                 case MenuItem::ViewFormats:
536                 case MenuItem::UpdateFormats:
537                 case MenuItem::ExportFormats:
538                         expandFormats(cit->kind(), tomenu, buf);
539                         break;
540
541                 case MenuItem::FloatListInsert:
542                         expandFloatListInsert(tomenu, buf);
543                         break;
544
545                 case MenuItem::FloatInsert:
546                         expandFloatInsert(tomenu, buf);
547                         break;
548
549                 case MenuItem::Toc:
550                         expandToc(tomenu, buf);
551                         break;
552
553                 case MenuItem::Submenu: {
554                         MenuItem item(*cit);
555                         item.submenu(new Menu(cit->submenuname()));
556                         expand(getMenu(cit->submenuname()),
557                                *item.submenu(), buf);
558                         tomenu.add(item);
559                 }
560                 break;
561
562                 default:
563                         tomenu.add(*cit);
564                 }
565         }
566
567         // Check whether the shortcuts are unique
568         if (lyxerr.debugging(Debug::GUI))
569                 tomenu.checkShortcuts();
570 }
571
572
573 bool Menu::hasSubmenu(string const & name) const
574 {
575         return find_if(begin(), end(),
576                        lyx::compare_memfun(&MenuItem::submenuname,
577                                            name)) != end();
578 }
579
580
581 void MenuBackend::read(LyXLex & lex)
582 {
583         enum Menutags {
584                 md_menu = 1,
585                 md_menubar,
586                 md_endmenuset,
587                 md_last
588         };
589
590         struct keyword_item menutags[md_last - 1] = {
591                 { "end", md_endmenuset },
592                 { "menu", md_menu },
593                 { "menubar", md_menubar }
594         };
595
596         //consistency check
597         if (compare_ascii_no_case(lex.getString(), "menuset")) {
598                 lyxerr << "Menubackend::read: ERROR wrong token:`"
599                        << lex.getString() << '\'' << endl;
600         }
601
602         lex.pushTable(menutags, md_last - 1);
603         if (lyxerr.debugging(Debug::PARSER))
604                 lex.printTable(lyxerr);
605
606         bool quit = false;
607
608         while (lex.isOK() && !quit) {
609                 switch (lex.lex()) {
610                 case md_menubar:
611                         menubar_.read(lex);
612                         break;
613                 case md_menu: {
614                         lex.next(true);
615                         string const name = lex.getString();
616                         if (hasMenu(name)) {
617                                 getMenu(name).read(lex);
618                         } else {
619                                 Menu menu(name);
620                                 menu.read(lex);
621                                 add(menu);
622                         }
623                         break;
624                 }
625                 case md_endmenuset:
626                         quit = true;
627                         break;
628                 default:
629                         lex.printError("menubackend::read: "
630                                        "Unknown menu tag: `$$Token'");
631                         break;
632                 }
633         }
634         lex.popTable();
635 }
636
637
638 void MenuBackend::defaults()
639 {
640         menulist_.clear();
641
642         lyxerr[Debug::GUI] << "MenuBackend::defaults: using default values"
643                            << endl;
644
645         Menu file("file");
646         file
647                 .add(MenuItem(MenuItem::Command, _("New...|N"), "buffer-new"))
648                 .add(MenuItem(MenuItem::Command, _("Open...|O"), "file-open"))
649                 .add(MenuItem(MenuItem::Submenu, _("Import|I"), "import"))
650                 .add(MenuItem(MenuItem::Command, _("Quit|Q"), "lyx-quit"))
651                 .add(MenuItem(MenuItem::Separator))
652                 .add(MenuItem(MenuItem::Lastfiles));
653         add(file);
654
655         Menu import("import");
656         import
657                 .add(MenuItem(MenuItem::Command,
658                               _("LaTeX...|L"), "buffer-import latex"))
659                 .add(MenuItem(MenuItem::Command,
660                               _("LinuxDoc...|L"), "buffer-import linuxdoc"));
661         add(import);
662
663         Menu edit("edit");
664         edit
665                 .add(MenuItem(MenuItem::Command, _("Cut"), "cut"))
666                 .add(MenuItem(MenuItem::Command, _("Copy"), "copy"))
667                 .add(MenuItem(MenuItem::Command, _("Paste"), "paste"))
668                 .add(MenuItem(MenuItem::Command, _("Emphasize"), "font-emph"));
669         add(edit);
670
671         Menu documents("documents");
672         documents.add(MenuItem(MenuItem::Documents));
673         add(documents);
674
675         menubar_.add(MenuItem(MenuItem::Submenu, _("File|F"), "file"))
676                 .add(MenuItem(MenuItem::Submenu, _("Edit|E"), "edit"))
677                 .add(MenuItem(MenuItem::Submenu,
678                               _("Documents|D"), "documents"));
679
680 }
681
682
683 void MenuBackend::add(Menu const & menu)
684 {
685         menulist_.push_back(menu);
686 }
687
688
689 bool MenuBackend::hasMenu(string const & name) const
690 {
691         return find_if(begin(), end(),
692                        lyx::compare_memfun(&Menu::name, name)) != end();
693 }
694
695
696 Menu const & MenuBackend::getMenu(string const & name) const
697 {
698         const_iterator cit = find_if(begin(), end(),
699                                      lyx::compare_memfun(&Menu::name, name));
700         if (cit == end())
701                 lyxerr << "No submenu named " << name << endl;
702         lyx::Assert(cit != end());
703         return (*cit);
704 }
705
706
707 Menu & MenuBackend::getMenu(string const & name)
708 {
709         MenuList::iterator it =
710                 find_if(menulist_.begin(), menulist_.end(),
711                         lyx::compare_memfun(&Menu::name, name));
712         lyx::Assert(it != menulist_.end());
713         return (*it);
714 }
715
716
717 Menu const & MenuBackend::getMenubar() const
718 {
719         return menubar_;
720 }