2 * \file GuiViewSource.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
16 #include "GuiViewSource.h"
17 #include "LaTeXHighlighter.h"
18 #include "qt_helpers.h"
20 #include "BufferParams.h"
21 #include "BufferView.h"
24 #include "FuncRequest.h"
26 #include "Paragraph.h"
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"
35 #include <boost/crc.hpp>
41 #include <QTextCursor>
42 #include <QTextDocument>
50 ViewSourceWidget::ViewSourceWidget(QWidget * parent)
52 document_(new QTextDocument(this)),
53 highlighter_(new LaTeXHighlighter(document_))
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)));
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_);
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);
84 // catch double click events
85 viewSourceTV->viewport()->installEventFilter(this);
89 void ViewSourceWidget::getContent(BufferView const & view,
90 Buffer::OutputWhat output, docstring & str, string const & format,
93 // get the *top* level paragraphs that contain the cursor,
94 // or the selected text
98 if (!view.cursor().selection()) {
99 par_begin = view.cursor().bottom().pit();
102 par_begin = view.cursor().selectionBegin().bottom().pit();
103 par_end = view.cursor().selectionEnd().bottom().pit();
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";
115 bool ViewSourceWidget::setText(QString const & qstr)
117 bool const changed = document_->toPlainText() != qstr;
118 viewSourceTV->setExtraSelections(QList<QTextEdit::ExtraSelection>());
120 document_->setPlainText(qstr);
125 void ViewSourceWidget::contentsChanged()
127 if (autoUpdateCB->isChecked())
132 void ViewSourceWidget::setViewFormat(int const index)
134 outputFormatCO->setCurrentIndex(index);
135 string format = fromqstr(outputFormatCO->itemData(index).toString());
136 if (view_format_ != format) {
137 view_format_ = format;
143 int ViewSourceWidget::updateDelay() const
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;
152 void GuiViewSource::scheduleUpdate()
154 update_timer_->start(widget_->updateDelay());
158 void GuiViewSource::scheduleUpdateNow()
160 update_timer_->start(0);
164 void GuiViewSource::realUpdateView()
166 widget_->updateView(bufferview());
171 void ViewSourceWidget::updateView(BufferView const * bv)
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();
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;
196 getContent(*bv, output, content, view_format_,
197 masterPerspectiveCB->isChecked());
198 QString old = document_->toPlainText();
199 QString qcontent = toqstr(content);
201 // output tex<->row correspondences in the source panel if the "-dbg latex"
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);
210 for (docstring_list::iterator it = dlist.begin(); it != dlist.end(); ++it)
211 qcontent += toqstr(*it) + '\n';
214 // prevent gotoCursor()
215 QSignalBlocker blocker(viewSourceTV);
216 bool const changed = setText(qcontent);
218 if (changed && !texrow_) {
219 // position-to-row is unavailable
220 // we jump to the first modification
221 const QChar * oc = old.constData();
222 const QChar * nc = qcontent.constData();
224 while (*oc != '\0' && *nc != '\0' && *oc == *nc) {
229 QTextCursor c = QTextCursor(viewSourceTV->document());
230 //get some space below the cursor
232 c.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor,v_margin);
233 viewSourceTV->setTextCursor(c);
234 //get some space on the right of the cursor
235 viewSourceTV->horizontalScrollBar()->setValue(h_scroll);
237 const int block = c.blockNumber();
238 for (int i = h_margin; i && block == c.blockNumber(); --i) {
239 c.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor);
241 c.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor);
242 viewSourceTV->setTextCursor(c);
243 //back to the position
245 //c.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor,1);
246 viewSourceTV->setTextCursor(c);
248 } else if (texrow_) {
249 // Use the available position-to-row conversion to highlight
250 // the current selection in the source
251 std::pair<int,int> rows = texrow_->rowFromCursor(bv->cursor());
252 int const beg_row = rows.first;
253 int const end_row = rows.second;
255 QTextCursor c = QTextCursor(viewSourceTV->document());
257 c.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor,
259 const int beg_sel = c.position();
260 //get some space above the cursor
261 c.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor,
263 viewSourceTV->setTextCursor(c);
264 c.setPosition(beg_sel, QTextCursor::MoveAnchor);
266 c.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor,
267 end_row - beg_row +1);
268 const int end_sel = c.position();
269 //get some space below the cursor
270 c.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor,
272 viewSourceTV->setTextCursor(c);
273 c.setPosition(end_sel, QTextCursor::KeepAnchor);
275 viewSourceTV->setTextCursor(c);
277 //the real highlighting is done with an ExtraSelection
278 QTextCharFormat format;
280 // We create a new color with the lightness of AlternateBase and
281 // the hue and saturation of Highlight
282 QPalette palette = viewSourceTV->palette();
283 QBrush alt = palette.alternateBase();
284 QColor high = palette.highlight().color().toHsl();
285 QColor col = QColor::fromHsl(high.hue(),
286 high.hslSaturation(),
287 alt.color().lightness());
289 format.setBackground(alt);
291 format.setProperty(QTextFormat::FullWidthSelection, true);
292 QTextEdit::ExtraSelection sel;
295 viewSourceTV->setExtraSelections(
296 QList<QTextEdit::ExtraSelection>() << sel);
300 viewSourceTV->setTextCursor(c);
301 viewSourceTV->horizontalScrollBar()->setValue(h_scroll);
302 } // else if (texrow)
306 docstring ViewSourceWidget::currentFormatName(BufferView const * bv) const
308 // Compute the actual format used
309 string const format = !bv ? ""
310 : flavor2format(bv->buffer().params().getOutputFlavor(view_format_));
311 Format const * f = formats.getFormat(format.empty() ? view_format_ : format);
312 return f ? f->prettyname() : from_utf8(view_format_);
316 bool ViewSourceWidget::eventFilter(QObject * obj, QEvent * ev)
318 // this event filter is installed on the viewport of the QTextView
319 if (obj == viewSourceTV->viewport() &&
320 ev->type() == QEvent::MouseButtonDblClick) {
328 void ViewSourceWidget::goToCursor() const
332 int row = viewSourceTV->textCursor().blockNumber() + 1;
333 dispatch(texrow_->goToFuncFromRow(row));
338 void ViewSourceWidget::updateDefaultFormat(BufferView const & bv)
340 QSignalBlocker blocker(outputFormatCO);
341 outputFormatCO->clear();
342 outputFormatCO->addItem(qt_("Default"),
343 QVariant(QString("default")));
346 vector<string> tmp = bv.buffer().params().backends();
347 vector<string>::const_iterator it = tmp.begin();
348 vector<string>::const_iterator en = tmp.end();
349 for (; it != en; ++it) {
350 string const format = *it;
351 Format const * fmt = formats.getFormat(format);
353 LYXERR0("Can't find format for backend " << format << "!");
357 QString const pretty = toqstr(translateIfPossible(fmt->prettyname()));
358 outputFormatCO->addItem(pretty, QVariant(toqstr(format)));
359 if (format == view_format_)
360 index = outputFormatCO->count() -1;
362 setViewFormat(index);
366 void ViewSourceWidget::resizeEvent (QResizeEvent * event)
368 QSize const & formSize = formLayout->sizeHint();
369 // minimize the size of the part that contains the buttons
370 if (width() * formSize.height() < height() * formSize.width()) {
371 layout_->setDirection(QBoxLayout::TopToBottom);
373 layout_->setDirection(QBoxLayout::LeftToRight);
375 QWidget::resizeEvent(event);
378 void ViewSourceWidget::saveSession(QString const & session_key) const
381 settings.setValue(session_key + "/output", toqstr(view_format_));
382 settings.setValue(session_key + "/contents", contentsCO->currentIndex());
383 settings.setValue(session_key + "/autoupdate", autoUpdateCB->isChecked());
384 settings.setValue(session_key + "/masterview",
385 masterPerspectiveCB->isChecked());
389 void ViewSourceWidget::restoreSession(QString const & session_key)
392 view_format_ = fromqstr(settings.value(session_key + "/output", 0)
394 contentsCO->setCurrentIndex(settings
395 .value(session_key + "/contents", 0)
397 masterPerspectiveCB->setChecked(settings
398 .value(session_key + "/masterview", false)
400 bool const checked = settings
401 .value(session_key + "/autoupdate", true)
403 autoUpdateCB->setChecked(checked);
409 GuiViewSource::GuiViewSource(GuiView & parent,
410 Qt::DockWidgetArea area, Qt::WindowFlags flags)
411 : DockView(parent, "view-source", qt_("Code Preview"), area, flags),
412 widget_(new ViewSourceWidget(this)),
413 update_timer_(new QTimer(this))
417 // setting the update timer
418 update_timer_->setSingleShot(true);
419 connect(update_timer_, SIGNAL(timeout()),
420 this, SLOT(realUpdateView()));
422 connect(widget_, SIGNAL(needUpdate()), this, SLOT(scheduleUpdateNow()));
426 void GuiViewSource::onBufferViewChanged()
429 widget_->setEnabled((bool)bufferview());
433 void GuiViewSource::updateView()
435 if (widget_->autoUpdateCB->isChecked()) {
436 widget_->setEnabled((bool)bufferview());
439 widget_->masterPerspectiveCB->setEnabled(buffer().parent());
444 void GuiViewSource::enableView(bool enable)
446 widget_->setEnabled((bool)bufferview());
448 widget_->updateDefaultFormat(*bufferview());
450 // In the opposite case, updateView() will be called anyway.
451 widget_->contentsChanged();
455 bool GuiViewSource::initialiseParams(string const & /*source*/)
462 void GuiViewSource::updateTitle()
464 docstring const format = widget_->currentFormatName(bufferview());
465 QString const title = format.empty() ? qt_("Code Preview")
466 : qt_("%1[[preview format name]] Preview")
467 .arg(toqstr(translateIfPossible(format)));
469 setWindowTitle(title);
473 void GuiViewSource::saveSession() const
475 Dialog::saveSession();
476 widget_->saveSession(sessionKey());
480 void GuiViewSource::restoreSession()
482 DockView::restoreSession();
483 widget_->restoreSession(sessionKey());
487 Dialog * createGuiViewSource(GuiView & lv)
489 return new GuiViewSource(lv);
493 } // namespace frontend
496 #include "moc_GuiViewSource.cpp"