]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/LayoutBox.cpp
This move out the GuiLayoutBox class out of GuiToolbar where it was a mess. The new...
[lyx.git] / src / frontends / qt4 / LayoutBox.cpp
1 /**
2  * \file qt4/LayoutBox.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author Stefan Schimanski
11  * \author Abdelrazak Younes
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "LayoutBox.h"
19
20 #include "Action.h"
21 #include "GuiView.h"
22 #include "qt_helpers.h"
23 #include "Toolbars.h"
24
25 #include "Buffer.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Cursor.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "Layout.h"
32 #include "LyXFunc.h"
33 #include "LyXRC.h"
34 #include "Paragraph.h"
35 #include "TextClass.h"
36
37 #include "insets/InsetText.h"
38
39 #include "support/debug.h"
40 #include "support/filetools.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43
44 #include <QAbstractItemDelegate>
45 #include <QAbstractTextDocumentLayout>
46 #include <QApplication>
47 #include <QComboBox>
48 #include <QFontMetrics>
49 #include <QHeaderView>
50 #include <QItemDelegate>
51 #include <QKeyEvent>
52 #include <QList>
53 #include <QListView>
54 #include <QPainter>
55 #include <QPixmap>
56 #include <QSettings>
57 #include <QSortFilterProxyModel>
58 #include <QStandardItem>
59 #include <QStandardItemModel>
60 #include <QString>
61 #include <QTextDocument>
62 #include <QTextFrame>
63 #include <QToolBar>
64 #include <QVariant>
65
66 #include "support/lassert.h"
67
68 using namespace std;
69 using namespace lyx::support;
70
71 namespace lyx {
72 namespace frontend {
73
74         
75 class LayoutItemDelegate : public QItemDelegate {
76 public:
77         ///
78         explicit LayoutItemDelegate(LayoutBox * layout)
79                 : QItemDelegate(layout), layout_(layout)
80         {}
81         ///
82         void paint(QPainter * painter, QStyleOptionViewItem const & option,
83                 QModelIndex const & index) const;
84         ///
85         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
86                 const QRect & /*rect*/, const QString & text ) const;
87         ///
88         QSize sizeHint(QStyleOptionViewItem const & opt,
89                 QModelIndex const & index) const;
90         
91 private:
92         ///
93         void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
94                 QString const & category) const;        
95         ///
96         QString underlineFilter(QString const & s) const;
97         ///
98         LayoutBox * layout_;
99 };
100
101
102 class GuiLayoutFilterModel : public QSortFilterProxyModel {
103 public:
104         ///
105         GuiLayoutFilterModel(QObject * parent = 0)
106                 : QSortFilterProxyModel(parent)
107         {}
108         
109         ///
110         void triggerLayoutChange()
111         {
112                 layoutAboutToBeChanged();
113                 layoutChanged();
114         }
115 };
116
117
118 /////////////////////////////////////////////////////////////////////
119 //
120 // LayoutBox::Private
121 //
122 /////////////////////////////////////////////////////////////////////
123
124 struct LayoutBox::Private
125 {
126         Private(LayoutBox * parent, GuiView & gv) : p(parent), owner_(gv),
127                 lastSel_(-1), visibleCategories_(0), inShowPopup_(false),
128                 layoutItemDelegate_(new LayoutItemDelegate(parent)),
129                 // set the layout model with two columns
130                 // 1st: translated layout names
131                 // 2nd: raw layout names
132                 model_(new QStandardItemModel(0, 2, p)),
133                 filterModel_(new GuiLayoutFilterModel(p))
134         {
135                 filterModel_->setSourceModel(model_);
136         }
137
138         void resetFilter() { setFilter(QString()); }
139         ///
140         void setFilter(QString const & s);
141         ///
142         void countCategories();
143         ///
144         LayoutBox * p;
145         ///
146         GuiView & owner_;
147         ///
148         DocumentClass const * text_class_;
149         ///
150         Inset const * inset_;
151         
152         /// the layout model: 1st column translated, 2nd column raw layout name
153         QStandardItemModel * model_;
154         /// the proxy model filtering \c model_
155         GuiLayoutFilterModel * filterModel_;
156         /// the (model-) index of the last successful selection
157         int lastSel_;
158         /// the character filter
159         QString filter_;
160         ///
161         LayoutItemDelegate * layoutItemDelegate_;
162         ///
163         unsigned visibleCategories_;
164         ///
165         bool inShowPopup_;
166 };
167
168
169 static QString category(QAbstractItemModel const & model, int row)
170 {
171         return model.data(model.index(row, 2), Qt::DisplayRole).toString();
172 }
173
174
175 static int headerHeight(QStyleOptionViewItem const & opt)
176 {
177         return opt.fontMetrics.height() * 8 / 10;
178 }
179
180
181 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
182                                                            QModelIndex const & index) const
183 {
184         QStyleOptionViewItem opt = option;
185
186         // default background
187         painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
188
189         // category header?
190         if (lyxrc.group_layouts) {
191                 QSortFilterProxyModel const * model =
192                         static_cast<QSortFilterProxyModel const *>(index.model());
193
194                 QString stdCat = category(*model->sourceModel(), 0);
195                 QString cat = category(*index.model(), index.row());
196
197                 // not the standard layout and not the same as in the previous line?
198                 if (stdCat != cat
199                         && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
200                         painter->save();
201
202                         // draw unselected background
203                         QStyle::State state = opt.state;
204                         opt.state = opt.state & ~QStyle::State_Selected;
205                         drawBackground(painter, opt, index);
206                         opt.state = state;
207
208                         // draw category header
209                         drawCategoryHeader(painter, opt, 
210                                 category(*index.model(), index.row()));
211
212                         // move rect down below header
213                         opt.rect.setTop(opt.rect.top() + headerHeight(opt));
214
215                         painter->restore();
216                 }
217         }
218
219         QItemDelegate::paint(painter, opt, index);
220 }
221
222
223 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
224                                                                          const QRect & /*rect*/, const QString & text ) const
225 {
226         QString utext = underlineFilter(text);
227
228         // Draw the rich text.
229         painter->save();
230         QColor col = opt.palette.text().color();
231         if (opt.state & QStyle::State_Selected)
232                 col = opt.palette.highlightedText().color();
233         QAbstractTextDocumentLayout::PaintContext context;
234         context.palette.setColor(QPalette::Text, col);
235
236         QTextDocument doc;
237         doc.setDefaultFont(opt.font);
238         doc.setHtml(utext);
239
240         QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
241         fmt.setMargin(0);
242         doc.rootFrame()->setFrameFormat(fmt);
243
244         painter->translate(opt.rect.x() + 5,
245                 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
246         doc.documentLayout()->draw(painter, context);
247         painter->restore();
248 }
249
250
251 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
252                                                                    QModelIndex const & index) const
253 {
254         QSortFilterProxyModel const * model =
255                 static_cast<QSortFilterProxyModel const *>(index.model());      
256         QSize size = QItemDelegate::sizeHint(opt, index);
257
258         /// QComboBox uses the first row height to estimate the
259         /// complete popup height during QComboBox::showPopup().
260         /// To avoid scrolling we have to sneak in space for the headers.
261         /// So we tweak this value accordingly. It's not nice, but the
262         /// only possible way it seems.
263         if (lyxrc.group_layouts && index.row() == 0 && layout_->d->inShowPopup_) {
264                 int itemHeight = size.height();
265
266                 // we have to show \c cats many headers:
267                 unsigned cats = layout_->d->visibleCategories_;
268
269                 // and we have \c n items to distribute the needed space over
270                 unsigned n = layout_->model()->rowCount();
271
272                 // so the needed average height (rounded upwards) is:
273                 size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n); 
274                 return size;
275         }
276
277         // Add space for the category headers here?
278         // Not for the standard layout though.
279         QString stdCat = category(*model->sourceModel(), 0);
280         QString cat = category(*index.model(), index.row());
281         if (lyxrc.group_layouts && stdCat != cat
282                 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
283                 size.setHeight(size.height() + headerHeight(opt));
284         }
285
286         return size;
287 }
288
289
290 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
291                                                                                         QString const & category) const
292 {
293         // slightly blended color
294         QColor lcol = opt.palette.text().color();
295         lcol.setAlpha(127);
296         painter->setPen(lcol);
297
298         // set 80% scaled, bold font
299         QFont font = opt.font;
300         font.setBold(true);
301         font.setWeight(QFont::Black);
302         font.setPointSize(opt.font.pointSize() * 8 / 10);
303         painter->setFont(font);
304
305         // draw the centered text
306         QFontMetrics fm(font);
307         int w = fm.width(category);
308         int x = opt.rect.x() + (opt.rect.width() - w) / 2;
309         int y = opt.rect.y() + fm.ascent();
310         int left = x;
311         int right = x + w;
312         painter->drawText(x, y, category);
313
314         // the vertical position of the line: middle of lower case chars
315         int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
316
317         // draw the horizontal line
318         if (!category.isEmpty()) {
319                 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
320                 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
321         } else
322                 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
323 }
324
325
326 QString LayoutItemDelegate::underlineFilter(QString const & s) const
327 {
328         QString const & f = layout_->filter();
329         if (f.isEmpty())
330                 return s;
331
332         // step through data item and put "(x)" for every matching character
333         QString r;
334         int lastp = -1;
335         layout_->filter();
336         for (int i = 0; i < f.length(); ++i) {
337                 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
338                 LASSERT(p != -1, /**/);
339                 if (lastp == p - 1 && lastp != -1) {
340                         // remove ")" and append "x)"
341                         r = r.left(r.length() - 4) + s[p] + "</u>";
342                 } else {
343                         // append "(x)"
344                         r += s.mid(lastp + 1, p - lastp - 1);
345                         r += QString("<u>") + s[p] + "</u>";
346                 }
347                 lastp = p;
348         }
349         r += s.mid(lastp + 1);
350         return r;
351 }
352
353
354 static QString charFilterRegExp(QString const & filter)
355 {
356         QString re;
357         for (int i = 0; i < filter.length(); ++i) {
358                 QChar c = filter[i];
359                 if (c.isLower())
360                         re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
361                 else
362                         re += ".*" + QRegExp::escape(c);
363         }
364         return re;
365 }
366
367
368 void LayoutBox::Private::setFilter(QString const & s)
369 {
370         bool enabled = p->view()->updatesEnabled();
371         p->view()->setUpdatesEnabled(false);
372
373         // remember old selection
374         int sel = p->currentIndex();
375         if (sel != -1)
376                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
377
378         filter_ = s;
379         filterModel_->setFilterRegExp(charFilterRegExp(filter_));
380         countCategories();
381         
382         // restore old selection
383         if (lastSel_ != -1) {
384                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
385                 if (i.isValid())
386                         p->setCurrentIndex(i.row());
387         }
388         
389         // Workaround to resize to content size
390         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
391         //        does not help.
392         if (p->view()->isVisible()) {
393                 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
394                 // the hack in the item delegate to make space for the headers.
395                 // We do not call our implementation of showPopup because that
396                 // would reset the filter again. This is only needed if the user clicks
397                 // on the QComboBox.
398                 LASSERT(!inShowPopup_, /**/);
399                 inShowPopup_ = true;
400                 p->showPopup();
401                 inShowPopup_ = false;
402
403                 // The item delegate hack is off again. So trigger a relayout of the popup.
404                 filterModel_->triggerLayoutChange();
405                 
406                 if (!s.isEmpty())
407                         owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
408                                                  "Press ESC to remove filter."),
409                                                qstring_to_ucs4(s)));
410                 else
411                         owner_.message(_("Enter characters to filter the layout list."));
412         }
413         
414         p->view()->setUpdatesEnabled(enabled);
415 }
416
417
418 LayoutBox::LayoutBox(QToolBar * bar, GuiView & owner)
419         : d(new Private(this, owner))
420 {
421         setSizeAdjustPolicy(QComboBox::AdjustToContents);
422         setFocusPolicy(Qt::ClickFocus);
423         setMinimumWidth(sizeHint().width());
424         setMaxVisibleItems(100);
425
426         setModel(d->filterModel_);
427
428         // for the filtering we have to intercept characters
429         view()->installEventFilter(this);
430         view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
431         
432         QObject::connect(this, SIGNAL(activated(int)),
433                 this, SLOT(selected(int)));
434         QObject::connect(bar, SIGNAL(iconSizeChanged(QSize)),
435                 this, SLOT(setIconSize(QSize)));
436
437         d->owner_.setLayoutDialog(this);
438         updateContents(true);
439 }
440
441
442 void LayoutBox::Private::countCategories()
443 {
444         int n = filterModel_->rowCount();
445         visibleCategories_ = 0;
446         if (n == 0 || !lyxrc.group_layouts)
447                 return;
448
449         // skip the "Standard" category
450         QString prevCat = model_->index(0, 2).data().toString(); 
451
452         // count categories
453         for (int i = 0; i < n; ++i) {
454                 QString cat = filterModel_->index(i, 2).data().toString();
455                 if (cat != prevCat)
456                         ++visibleCategories_;
457                 prevCat = cat;
458         }
459 }
460
461
462 void LayoutBox::showPopup()
463 {
464         d->owner_.message(_("Enter characters to filter the layout list."));
465
466         bool enabled = view()->updatesEnabled();
467         view()->setUpdatesEnabled(false);
468
469         d->resetFilter();
470
471         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
472         // the hack in the item delegate to make space for the headers.
473         LASSERT(!d->inShowPopup_, /**/);
474         d->inShowPopup_ = true;
475         QComboBox::showPopup();
476         d->inShowPopup_ = false;
477         
478         // The item delegate hack is off again. So trigger a relayout of the popup.
479         d->filterModel_->triggerLayoutChange();
480         
481         view()->setUpdatesEnabled(enabled);
482 }
483
484
485 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
486 {
487         if (e->type() != QEvent::KeyPress)
488                 return QComboBox::eventFilter(o, e);
489
490         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
491         bool modified = (ke->modifiers() == Qt::ControlModifier)
492                 || (ke->modifiers() == Qt::AltModifier)
493                 || (ke->modifiers() == Qt::MetaModifier);
494         
495         switch (ke->key()) {
496         case Qt::Key_Escape:
497                 if (!modified && !d->filter_.isEmpty()) {
498                         d->resetFilter();
499                         return true;
500                 }
501                 break;
502         case Qt::Key_Backspace:
503                 if (!modified) {
504                         // cut off one character
505                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
506                 }
507                 break;
508         default:
509                 if (modified || ke->text().isEmpty())
510                         break;
511                 // find chars for the filter string
512                 QString s;
513                 for (int i = 0; i < ke->text().length(); ++i) {
514                         QChar c = ke->text()[i];
515                         if (c.isLetterOrNumber()
516                             || c.isSymbol()
517                             || c.isPunct()
518                             || c.category() == QChar::Separator_Space) {
519                                 s += c;
520                         }
521                 }
522                 if (!s.isEmpty()) {
523                         // append new chars to the filter string
524                         d->setFilter(d->filter_ + s);
525                         return true;
526                 }
527                 break;
528         }
529
530         return QComboBox::eventFilter(o, e);
531 }
532
533         
534 void LayoutBox::setIconSize(QSize size)
535 {
536 #ifdef Q_WS_MACX
537         bool small = size.height() < 20;
538         setAttribute(Qt::WA_MacSmallSize, small);
539         setAttribute(Qt::WA_MacNormalSize, !small);
540 #else
541         (void)size; // suppress warning
542 #endif
543 }
544
545
546 void LayoutBox::set(docstring const & layout)
547 {
548         d->resetFilter();
549         
550         if (!d->text_class_)
551                 return;
552
553         Layout const & lay = (*d->text_class_)[layout];
554         QString newLayout = toqstr(lay.name());
555
556         // If the layout is obsolete, use the new one instead.
557         docstring const & obs = lay.obsoleted_by();
558         if (!obs.empty())
559                 newLayout = toqstr(obs);
560
561         int const curItem = currentIndex();
562         QModelIndex const mindex =
563                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
564         QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
565         if (newLayout == currentLayout) {
566                 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
567                 return;
568         }
569
570         QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
571         if (r.empty()) {
572                 LYXERR0("Trying to select non existent layout type " << newLayout);
573                 return;
574         }
575
576         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
577 }
578
579
580 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
581         bool sorted, bool sortedByCat, bool unknown)
582 {
583         QString qitem = toqstr(item);
584         // FIXME This is wrong for RTL, I'd suppose.
585         QString titem = toqstr(translateIfPossible(item) +
586                                (unknown ? _(" (unknown)") : from_ascii("")));
587         QString qcat = toqstr(translateIfPossible(category));
588
589         QList<QStandardItem *> row;
590         row.append(new QStandardItem(titem));
591         row.append(new QStandardItem(qitem));
592         row.append(new QStandardItem(qcat));
593
594         // the first entry is easy
595         int const end = d->model_->rowCount();
596         if (end == 0) {
597                 d->model_->appendRow(row);
598                 return;
599         }
600
601         // find category
602         int i = 0;
603         if (sortedByCat) {
604                 while (i < end && d->model_->item(i, 2)->text() != qcat)
605                         ++i;
606         }
607
608         // skip the Standard layout
609         if (i == 0)
610                 ++i;
611         
612         // the simple unsorted case
613         if (!sorted) {
614                 if (sortedByCat) {
615                         // jump to the end of the category group
616                         while (i < end && d->model_->item(i, 2)->text() == qcat)
617                                 ++i;
618                         d->model_->insertRow(i, row);
619                 } else
620                         d->model_->appendRow(row);
621                 return;
622         }
623
624         // find row to insert the item, after the separator if it exists
625         if (i < end) {
626                 // find alphabetic position
627                 while (i != end
628                        && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0 
629                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
630                         ++i;
631         }
632
633         d->model_->insertRow(i, row);
634 }
635
636
637 void LayoutBox::updateContents(bool reset)
638 {
639         d->resetFilter();
640         
641         Buffer const * buffer = d->owner_.buffer();
642         if (!buffer) {
643                 d->model_->clear();
644                 setEnabled(false);
645                 d->text_class_ = 0;
646                 d->inset_ = 0;
647                 return;
648         }
649
650         // we'll only update the layout list if the text class has changed
651         // or we've moved from one inset to another
652         DocumentClass const * text_class = &buffer->params().documentClass();
653         Inset const * inset = 
654                 &(d->owner_.view()->cursor().innerText()->inset());
655         if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
656                 set(d->owner_.view()->cursor().innerParagraph().layout().name());
657                 return;
658         }
659
660         d->inset_ = inset;
661         d->text_class_ = text_class;
662
663         d->model_->clear();
664         DocumentClass::const_iterator lit = d->text_class_->begin();
665         DocumentClass::const_iterator len = d->text_class_->end();
666
667         for (; lit != len; ++lit) {
668                 docstring const & name = lit->name();
669                 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
670                 // if this inset requires the empty layout, we skip the default
671                 // layout
672                 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
673                         continue;
674                 // if it doesn't require the empty layout, we skip it
675                 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
676                         continue;
677                 // obsoleted layouts are skipped as well
678                 if (!lit->obsoleted_by().empty())
679                         continue;
680                 addItemSort(name, lit->category(), lyxrc.sort_layouts, 
681                                 lyxrc.group_layouts, lit->isUnknown());
682         }
683
684         set(d->owner_.view()->cursor().innerParagraph().layout().name());
685         d->countCategories();
686         
687         // needed to recalculate size hint
688         hide();
689         setMinimumWidth(sizeHint().width());
690         setEnabled(!buffer->isReadonly() &&
691                 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
692         show();
693 }
694
695
696 void LayoutBox::selected(int index)
697 {
698         // get selection
699         QModelIndex mindex = d->filterModel_->mapToSource(
700                 d->filterModel_->index(index, 1));
701         docstring layoutName = qstring_to_ucs4(
702                 d->model_->itemFromIndex(mindex)->text());
703         d->owner_.setFocus();
704
705         if (!d->text_class_) {
706                 updateContents(false);
707                 d->resetFilter();
708                 return;
709         }
710
711         // find corresponding text class
712         if (d->text_class_->hasLayout(layoutName)) {
713                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
714                 theLyXFunc().setLyXView(&d->owner_);
715                 lyx::dispatch(func);
716                 updateContents(false);
717                 d->resetFilter();
718                 return;
719         }
720         LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
721 }
722
723
724 QString const & LayoutBox::filter() const
725 {
726         return d->filter_;
727 }
728
729 } // namespace frontend
730 } // namespace lyx
731
732 #include "moc_LayoutBox.cpp"