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