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