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