]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiViewSource.cpp
Menus: Factor Toc code
[lyx.git] / src / frontends / qt4 / GuiViewSource.cpp
1 /**
2  * \file GuiViewSource.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Bo Peng
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16 #include "GuiViewSource.h"
17 #include "LaTeXHighlighter.h"
18 #include "qt_helpers.h"
19
20 #include "BufferParams.h"
21 #include "BufferView.h"
22 #include "Cursor.h"
23 #include "Format.h"
24 #include "FuncRequest.h"
25 #include "LyX.h"
26 #include "Paragraph.h"
27 #include "TexRow.h"
28
29 #include "support/debug.h"
30 #include "support/lassert.h"
31 #include "support/docstream.h"
32 #include "support/docstring_list.h"
33 #include "support/gettext.h"
34
35 #include <boost/crc.hpp>
36
37 #include <QBoxLayout>
38 #include <QComboBox>
39 #include <QScrollBar>
40 #include <QSettings>
41 #include <QTextCursor>
42 #include <QTextDocument>
43 #include <QVariant>
44
45 using namespace std;
46
47 namespace lyx {
48 namespace frontend {
49
50 ViewSourceWidget::ViewSourceWidget(QWidget * parent)
51         :       QWidget(parent),
52                 document_(new QTextDocument(this)),
53                 highlighter_(new LaTeXHighlighter(document_))
54 {
55         setupUi(this);
56
57         connect(contentsCO, SIGNAL(activated(int)),
58                 this, SLOT(contentsChanged()));
59         connect(autoUpdateCB, SIGNAL(toggled(bool)),
60                 updatePB, SLOT(setDisabled(bool)));
61         connect(autoUpdateCB, SIGNAL(toggled(bool)),
62                 this, SLOT(contentsChanged()));
63         connect(masterPerspectiveCB, SIGNAL(toggled(bool)),
64                 this, SLOT(contentsChanged()));
65         connect(updatePB, SIGNAL(clicked()),
66                 this, SIGNAL(needUpdate()));
67         connect(outputFormatCO, SIGNAL(activated(int)),
68                 this, SLOT(setViewFormat(int)));
69
70         // setting a document at this point trigger an assertion in Qt
71         // so we disable the signals here:
72         document_->blockSignals(true);
73         viewSourceTV->setDocument(document_);
74         // reset selections
75         setText();
76         document_->blockSignals(false);
77         viewSourceTV->setReadOnly(true);
78         ///dialog_->viewSourceTV->setAcceptRichText(false);
79         // this is personal. I think source code should be in fixed-size font
80         viewSourceTV->setFont(guiApp->typewriterSystemFont());
81         // again, personal taste
82         viewSourceTV->setWordWrapMode(QTextOption::NoWrap);
83
84         // catch double click events
85         viewSourceTV->viewport()->installEventFilter(this);
86 }
87
88
89 void ViewSourceWidget::getContent(BufferView const & view,
90                         Buffer::OutputWhat output, docstring & str, string const & format,
91                         bool master)
92 {
93         // get the *top* level paragraphs that contain the cursor,
94         // or the selected text
95         pit_type par_begin;
96         pit_type par_end;
97
98         if (!view.cursor().selection()) {
99                 par_begin = view.cursor().bottom().pit();
100                 par_end = par_begin;
101         } else {
102                 par_begin = view.cursor().selectionBegin().bottom().pit();
103                 par_end = view.cursor().selectionEnd().bottom().pit();
104         }
105         if (par_begin > par_end)
106                 swap(par_begin, par_end);
107         odocstringstream ostr;
108         texrow_ = view.buffer()
109                 .getSourceCode(ostr, format, par_begin, par_end + 1, output, master);
110         //ensure that the last line can always be selected in its full width
111         str = ostr.str() + "\n";
112 }
113
114
115 bool ViewSourceWidget::setText(QString const & qstr)
116 {
117         bool const changed = document_->toPlainText() != qstr;
118         viewSourceTV->setExtraSelections(QList<QTextEdit::ExtraSelection>());
119         if (changed)
120                 document_->setPlainText(qstr);
121         return changed;
122 }
123
124
125 void ViewSourceWidget::contentsChanged()
126 {
127         if (autoUpdateCB->isChecked())
128                 Q_EMIT needUpdate();
129 }
130
131
132 void ViewSourceWidget::setViewFormat(int const index)
133 {
134         outputFormatCO->setCurrentIndex(index);
135         string format = fromqstr(outputFormatCO->itemData(index).toString());
136         if (view_format_ != format) {
137                 view_format_ = format;
138                 Q_EMIT needUpdate();
139         }
140 }
141
142
143 int ViewSourceWidget::updateDelay() const
144 {
145         const int long_delay = 400;
146         const int short_delay = 60;
147         // a shorter delay if just the current paragraph is shown
148         return (contentsCO->currentIndex() == 0) ? short_delay : long_delay;
149 }
150
151
152 void GuiViewSource::scheduleUpdate()
153 {
154         update_timer_->start(widget_->updateDelay());
155 }
156
157
158 void GuiViewSource::scheduleUpdateNow()
159 {
160         update_timer_->start(0);
161 }
162
163
164 void GuiViewSource::realUpdateView()
165 {
166         widget_->updateView(bufferview());
167         updateTitle();
168 }
169
170
171 void ViewSourceWidget::updateView(BufferView const * bv)
172 {
173         if (!bv) {
174                 setText();
175                 setEnabled(false);
176                 return;
177         }
178
179         setEnabled(true);
180
181         // we will try to get that much space around the cursor
182         int const v_margin = 3;
183         int const h_margin = 10;
184         // we will try to preserve this
185         int const h_scroll = viewSourceTV->horizontalScrollBar()->value();
186
187         Buffer::OutputWhat output = Buffer::CurrentParagraph;
188         if (contentsCO->currentIndex() == 1)
189                 output = Buffer::FullSource;
190         else if (contentsCO->currentIndex() == 2)
191                 output = Buffer::OnlyPreamble;
192         else if (contentsCO->currentIndex() == 3)
193                 output = Buffer::OnlyBody;
194
195         docstring content;
196         getContent(*bv, output, content, view_format_,
197                    masterPerspectiveCB->isChecked());
198         QString old = document_->toPlainText();
199         QString qcontent = toqstr(content);
200 #ifdef DEVEL_VERSION
201         // output tex<->row correspondences in the source panel if the "-dbg latex"
202         // option is given.
203         if (texrow_ && lyx::lyxerr.debugging(Debug::LATEX)) {
204                 QStringList list = qcontent.split(QChar('\n'));
205                 docstring_list dlist;
206                 for (QStringList::const_iterator it = list.begin(); it != list.end(); ++it)
207                         dlist.push_back(from_utf8(fromqstr(*it)));
208                 texrow_->prepend(dlist);
209                 qcontent.clear();
210                 for (docstring_list::iterator it = dlist.begin(); it != dlist.end(); ++it)
211                         qcontent += toqstr(*it) + '\n';
212         }
213 #endif
214         // prevent gotoCursor()
215         QSignalBlocker blocker(viewSourceTV);
216         bool const changed = setText(qcontent);
217
218         if (changed && !texrow_) {
219                 // position-to-row is unavailable
220                 // we jump to the first modification
221                 int length = min(old.length(), qcontent.length());
222                 int pos = 0;
223                 for (; pos < length && old.at(pos) == qcontent.at(pos); ++pos) {}
224                 QTextCursor c = QTextCursor(viewSourceTV->document());
225                 //get some space below the cursor
226                 c.setPosition(pos);
227                 c.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor,v_margin);
228                 viewSourceTV->setTextCursor(c);
229                 //get some space on the right of the cursor
230                 viewSourceTV->horizontalScrollBar()->setValue(h_scroll);
231                 c.setPosition(pos);
232                 const int block = c.blockNumber();
233                 for (int i = h_margin; i && block == c.blockNumber(); --i) {
234                         c.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor);
235                 }
236                 c.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor);
237                 viewSourceTV->setTextCursor(c);
238                 //back to the position
239                 c.setPosition(pos);
240                 //c.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor,1);
241                 viewSourceTV->setTextCursor(c);
242
243         } else if (texrow_) {
244                 // Use the available position-to-row conversion to highlight
245                 // the current selection in the source
246                 std::pair<int,int> rows = texrow_->rowFromCursor(bv->cursor());
247                 int const beg_row = rows.first;
248                 int const end_row = rows.second;
249
250                 QTextCursor c = QTextCursor(viewSourceTV->document());
251
252                 c.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor,
253                                            beg_row - 1);
254                 const int beg_sel = c.position();
255                 //get some space above the cursor
256                 c.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor,
257                                            v_margin);
258                 viewSourceTV->setTextCursor(c);
259                 c.setPosition(beg_sel, QTextCursor::MoveAnchor);
260
261                 c.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor,
262                                            end_row - beg_row +1);
263                 const int end_sel = c.position();
264                 //get some space below the cursor
265                 c.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor,
266                                            v_margin - 1);
267                 viewSourceTV->setTextCursor(c);
268                 c.setPosition(end_sel, QTextCursor::KeepAnchor);
269
270                 viewSourceTV->setTextCursor(c);
271
272                 //the real highlighting is done with an ExtraSelection
273                 QTextCharFormat format;
274                 {
275                 // We create a new color with the lightness of AlternateBase and
276                 // the hue and saturation of Highlight
277                 QPalette palette = viewSourceTV->palette();
278                 QBrush alt = palette.alternateBase();
279                 QColor high = palette.highlight().color().toHsl();
280                 QColor col = QColor::fromHsl(high.hue(),
281                                              high.hslSaturation(),
282                                              alt.color().lightness());
283                 alt.setColor(col);
284                 format.setBackground(alt);
285                 }
286                 format.setProperty(QTextFormat::FullWidthSelection, true);
287                 QTextEdit::ExtraSelection sel;
288                 sel.format = format;
289                 sel.cursor = c;
290                 viewSourceTV->setExtraSelections(
291                         QList<QTextEdit::ExtraSelection>() << sel);
292
293                 //clean up
294                 c.clearSelection();
295                 viewSourceTV->setTextCursor(c);
296                 viewSourceTV->horizontalScrollBar()->setValue(h_scroll);
297         } // else if (texrow)
298 }
299
300
301 docstring ViewSourceWidget::currentFormatName(BufferView const * bv) const
302 {
303         // Compute the actual format used
304         string const format = !bv ? ""
305                 : flavor2format(bv->buffer().params().getOutputFlavor(view_format_));
306         Format const * f = formats.getFormat(format.empty() ? view_format_ : format);
307         return f ? f->prettyname() : from_utf8(view_format_);
308 }
309
310
311 bool ViewSourceWidget::eventFilter(QObject * obj, QEvent * ev)
312 {
313         // this event filter is installed on the viewport of the QTextView
314         if (obj == viewSourceTV->viewport() &&
315             ev->type() == QEvent::MouseButtonDblClick) {
316                 goToCursor();
317                 return true;
318         }
319         return false;
320 }
321
322
323 void ViewSourceWidget::goToCursor() const
324 {
325         if (!texrow_)
326                 return;
327         int row = viewSourceTV->textCursor().blockNumber() + 1;
328         dispatch(texrow_->goToFuncFromRow(row));
329 }
330
331
332
333 void ViewSourceWidget::updateDefaultFormat(BufferView const & bv)
334 {
335         QSignalBlocker blocker(outputFormatCO);
336         outputFormatCO->clear();
337         outputFormatCO->addItem(qt_("Default"),
338                                 QVariant(QString("default")));
339
340         int index = 0;
341         vector<string> tmp = bv.buffer().params().backends();
342         vector<string>::const_iterator it = tmp.begin();
343         vector<string>::const_iterator en = tmp.end();
344         for (; it != en; ++it) {
345                 string const format = *it;
346                 Format const * fmt = formats.getFormat(format);
347                 if (!fmt) {
348                         LYXERR0("Can't find format for backend " << format << "!");
349                         continue;
350                 } 
351
352                 QString const pretty = toqstr(translateIfPossible(fmt->prettyname()));
353                 outputFormatCO->addItem(pretty, QVariant(toqstr(format)));
354                 if (format == view_format_)
355                    index = outputFormatCO->count() -1;
356         }
357         setViewFormat(index);
358 }
359
360
361 void ViewSourceWidget::resizeEvent (QResizeEvent * event)
362 {
363         QSize const & formSize = formLayout->sizeHint();
364         // minimize the size of the part that contains the buttons
365         if (width() * formSize.height() < height() * formSize.width()) {
366                 layout_->setDirection(QBoxLayout::TopToBottom);
367         } else {
368                 layout_->setDirection(QBoxLayout::LeftToRight);
369         }
370         QWidget::resizeEvent(event);
371 }
372
373 void ViewSourceWidget::saveSession(QString const & session_key) const
374 {
375         QSettings settings;
376         settings.setValue(session_key + "/output", toqstr(view_format_));
377         settings.setValue(session_key + "/contents", contentsCO->currentIndex());
378         settings.setValue(session_key + "/autoupdate", autoUpdateCB->isChecked());
379         settings.setValue(session_key + "/masterview",
380                                           masterPerspectiveCB->isChecked());
381 }
382
383
384 void ViewSourceWidget::restoreSession(QString const & session_key)
385 {
386         QSettings settings;
387         view_format_ = fromqstr(settings.value(session_key + "/output", 0)
388                                 .toString());
389         contentsCO->setCurrentIndex(settings
390                                                                 .value(session_key + "/contents", 0)
391                                                                 .toInt());
392         masterPerspectiveCB->setChecked(settings
393                                                                         .value(session_key + "/masterview", false)
394                                                                         .toBool());
395         bool const checked = settings
396                 .value(session_key + "/autoupdate", true)
397                 .toBool();
398         autoUpdateCB->setChecked(checked);
399         if (checked)
400                 Q_EMIT needUpdate();
401 }
402
403
404 GuiViewSource::GuiViewSource(GuiView & parent,
405                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
406         : DockView(parent, "view-source", qt_("Code Preview"), area, flags),
407           widget_(new ViewSourceWidget(this)),
408           update_timer_(new QTimer(this))
409 {
410         setWidget(widget_);
411
412         // setting the update timer
413         update_timer_->setSingleShot(true);
414         connect(update_timer_, SIGNAL(timeout()),
415                 this, SLOT(realUpdateView()));
416
417         connect(widget_, SIGNAL(needUpdate()), this, SLOT(scheduleUpdateNow()));
418 }
419
420
421 void GuiViewSource::onBufferViewChanged()
422 {
423         widget_->setText();
424         widget_->setEnabled((bool)bufferview());
425 }
426
427
428 void GuiViewSource::updateView()
429 {
430         if (widget_->autoUpdateCB->isChecked()) {
431                 widget_->setEnabled((bool)bufferview());
432                 scheduleUpdate();
433         }
434         widget_->masterPerspectiveCB->setEnabled(buffer().parent());
435         updateTitle();
436 }
437
438
439 void GuiViewSource::enableView(bool enable)
440 {
441         widget_->setEnabled((bool)bufferview());
442         if (bufferview())
443                 widget_->updateDefaultFormat(*bufferview());
444         if (!enable)
445                 // In the opposite case, updateView() will be called anyway.
446                 widget_->contentsChanged();
447 }
448
449
450 bool GuiViewSource::initialiseParams(string const & /*source*/)
451 {
452         updateTitle();
453         return true;
454 }
455
456
457 void GuiViewSource::updateTitle()
458 {
459         docstring const format = widget_->currentFormatName(bufferview());
460         QString const title = format.empty() ? qt_("Code Preview")
461                 : qt_("%1[[preview format name]] Preview")
462                   .arg(toqstr(translateIfPossible(format)));
463         setTitle(title);
464         setWindowTitle(title);
465 }
466
467
468 void GuiViewSource::saveSession() const
469 {
470         Dialog::saveSession();
471         widget_->saveSession(sessionKey());
472 }
473
474
475 void GuiViewSource::restoreSession()
476 {
477         DockView::restoreSession();
478         widget_->restoreSession(sessionKey());
479 }
480
481
482 Dialog * createGuiViewSource(GuiView & lv)
483 {
484         return new GuiViewSource(lv);
485 }
486
487
488 } // namespace frontend
489 } // namespace lyx
490
491 #include "moc_GuiViewSource.cpp"