]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/LayoutBox.cpp
* fix spelling in comments to please John.
[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         updateContents(true);
418 }
419
420
421 void LayoutBox::Private::countCategories()
422 {
423         int n = filterModel_->rowCount();
424         visibleCategories_ = 0;
425         if (n == 0 || !lyxrc.group_layouts)
426                 return;
427
428         // skip the "Standard" category
429         QString prevCat = model_->index(0, 2).data().toString(); 
430
431         // count categories
432         for (int i = 0; i < n; ++i) {
433                 QString cat = filterModel_->index(i, 2).data().toString();
434                 if (cat != prevCat)
435                         ++visibleCategories_;
436                 prevCat = cat;
437         }
438 }
439
440
441 void LayoutBox::showPopup()
442 {
443         d->owner_.message(_("Enter characters to filter the layout list."));
444
445         bool enabled = view()->updatesEnabled();
446         view()->setUpdatesEnabled(false);
447
448         d->resetFilter();
449
450         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
451         // the hack in the item delegate to make space for the headers.
452         LASSERT(!d->inShowPopup_, /**/);
453         d->inShowPopup_ = true;
454         QComboBox::showPopup();
455         d->inShowPopup_ = false;
456         
457         // The item delegate hack is off again. So trigger a relayout of the popup.
458         d->filterModel_->triggerLayoutChange();
459         
460         view()->setUpdatesEnabled(enabled);
461 }
462
463
464 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
465 {
466         if (e->type() != QEvent::KeyPress)
467                 return QComboBox::eventFilter(o, e);
468
469         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
470         bool modified = (ke->modifiers() == Qt::ControlModifier)
471                 || (ke->modifiers() == Qt::AltModifier)
472                 || (ke->modifiers() == Qt::MetaModifier);
473         
474         switch (ke->key()) {
475         case Qt::Key_Escape:
476                 if (!modified && !d->filter_.isEmpty()) {
477                         d->resetFilter();
478                         return true;
479                 }
480                 break;
481         case Qt::Key_Backspace:
482                 if (!modified) {
483                         // cut off one character
484                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
485                 }
486                 break;
487         default:
488                 if (modified || ke->text().isEmpty())
489                         break;
490                 // find chars for the filter string
491                 QString s;
492                 for (int i = 0; i < ke->text().length(); ++i) {
493                         QChar c = ke->text()[i];
494                         if (c.isLetterOrNumber()
495                             || c.isSymbol()
496                             || c.isPunct()
497                             || c.category() == QChar::Separator_Space) {
498                                 s += c;
499                         }
500                 }
501                 if (!s.isEmpty()) {
502                         // append new chars to the filter string
503                         d->setFilter(d->filter_ + s);
504                         return true;
505                 }
506                 break;
507         }
508
509         return QComboBox::eventFilter(o, e);
510 }
511
512         
513 void LayoutBox::setIconSize(QSize size)
514 {
515 #ifdef Q_WS_MACX
516         bool small = size.height() < 20;
517         setAttribute(Qt::WA_MacSmallSize, small);
518         setAttribute(Qt::WA_MacNormalSize, !small);
519 #else
520         (void)size; // suppress warning
521 #endif
522 }
523
524
525 void LayoutBox::set(docstring const & layout)
526 {
527         d->resetFilter();
528         
529         if (!d->text_class_)
530                 return;
531
532         Layout const & lay = (*d->text_class_)[layout];
533         QString newLayout = toqstr(lay.name());
534
535         // If the layout is obsolete, use the new one instead.
536         docstring const & obs = lay.obsoleted_by();
537         if (!obs.empty())
538                 newLayout = toqstr(obs);
539
540         int const curItem = currentIndex();
541         QModelIndex const mindex =
542                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
543         QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
544         if (newLayout == currentLayout) {
545                 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
546                 return;
547         }
548
549         QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
550         if (r.empty()) {
551                 LYXERR0("Trying to select non existent layout type " << newLayout);
552                 return;
553         }
554
555         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
556 }
557
558
559 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
560         bool sorted, bool sortedByCat, bool unknown)
561 {
562         QString qitem = toqstr(item);
563         // FIXME This is wrong for RTL, I'd suppose.
564         QString titem = toqstr(translateIfPossible(item) +
565                                (unknown ? _(" (unknown)") : from_ascii("")));
566         QString qcat = toqstr(translateIfPossible(category));
567
568         QList<QStandardItem *> row;
569         row.append(new QStandardItem(titem));
570         row.append(new QStandardItem(qitem));
571         row.append(new QStandardItem(qcat));
572
573         // the first entry is easy
574         int const end = d->model_->rowCount();
575         if (end == 0) {
576                 d->model_->appendRow(row);
577                 return;
578         }
579
580         // find category
581         int i = 0;
582         if (sortedByCat) {
583                 while (i < end && d->model_->item(i, 2)->text() != qcat)
584                         ++i;
585         }
586
587         // skip the Standard layout
588         if (i == 0)
589                 ++i;
590         
591         // the simple unsorted case
592         if (!sorted) {
593                 if (sortedByCat) {
594                         // jump to the end of the category group
595                         while (i < end && d->model_->item(i, 2)->text() == qcat)
596                                 ++i;
597                         d->model_->insertRow(i, row);
598                 } else
599                         d->model_->appendRow(row);
600                 return;
601         }
602
603         // find row to insert the item, after the separator if it exists
604         if (i < end) {
605                 // find alphabetic position
606                 while (i != end
607                        && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0 
608                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
609                         ++i;
610         }
611
612         d->model_->insertRow(i, row);
613 }
614
615
616 void LayoutBox::updateContents(bool reset)
617 {
618         d->resetFilter();
619         BufferView const * bv = d->owner_.currentBufferView();
620         if (!bv) {
621                 d->model_->clear();
622                 setEnabled(false);
623                 d->text_class_ = 0;
624                 d->inset_ = 0;
625                 return;
626         }
627         // we'll only update the layout list if the text class has changed
628         // or we've moved from one inset to another
629         DocumentClass const * text_class = &(bv->buffer().params().documentClass());
630         Inset const * inset = &(bv->cursor().innerText()->inset());
631         if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
632                 set(bv->cursor().innerParagraph().layout().name());
633                 return;
634         }
635
636         d->inset_ = inset;
637         d->text_class_ = text_class;
638
639         d->model_->clear();
640         DocumentClass::const_iterator lit = d->text_class_->begin();
641         DocumentClass::const_iterator len = d->text_class_->end();
642
643         for (; lit != len; ++lit) {
644                 docstring const & name = lit->name();
645                 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
646                 // if this inset requires the empty layout, we skip the default
647                 // layout
648                 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
649                         continue;
650                 // if it doesn't require the empty layout, we skip it
651                 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
652                         continue;
653                 // obsoleted layouts are skipped as well
654                 if (!lit->obsoleted_by().empty())
655                         continue;
656                 addItemSort(name, lit->category(), lyxrc.sort_layouts, 
657                                 lyxrc.group_layouts, lit->isUnknown());
658         }
659
660         set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
661         d->countCategories();
662         
663         // needed to recalculate size hint
664         hide();
665         setMinimumWidth(sizeHint().width());
666         setEnabled(!bv->buffer().isReadonly() &&
667                 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
668         show();
669 }
670
671
672 void LayoutBox::selected(int index)
673 {
674         // get selection
675         QModelIndex mindex = d->filterModel_->mapToSource(
676                 d->filterModel_->index(index, 1));
677         docstring layoutName = qstring_to_ucs4(
678                 d->model_->itemFromIndex(mindex)->text());
679         d->owner_.setFocus();
680
681         if (!d->text_class_) {
682                 updateContents(false);
683                 d->resetFilter();
684                 return;
685         }
686
687         // find corresponding text class
688         if (d->text_class_->hasLayout(layoutName)) {
689                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
690                 lyx::dispatch(func);
691                 updateContents(false);
692                 d->resetFilter();
693                 return;
694         }
695         LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
696 }
697
698
699 QString const & LayoutBox::filter() const
700 {
701         return d->filter_;
702 }
703
704 } // namespace frontend
705 } // namespace lyx
706
707 #include "moc_LayoutBox.cpp"