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