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 int length = min(old.length(), qcontent.length());
223 for (; pos < length && old.at(pos) == qcontent.at(pos); ++pos) {}
224 QTextCursor c = QTextCursor(viewSourceTV->document());
225 //get some space below the cursor
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);
232 const int block = c.blockNumber();
233 for (int i = h_margin; i && block == c.blockNumber(); --i) {
234 c.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor);
236 c.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor);
237 viewSourceTV->setTextCursor(c);
238 //back to the position
240 //c.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor,1);
241 viewSourceTV->setTextCursor(c);
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;
250 QTextCursor c = QTextCursor(viewSourceTV->document());
252 c.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor,
254 const int beg_sel = c.position();
255 //get some space above the cursor
256 c.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor,
258 viewSourceTV->setTextCursor(c);
259 c.setPosition(beg_sel, QTextCursor::MoveAnchor);
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,
267 viewSourceTV->setTextCursor(c);
268 c.setPosition(end_sel, QTextCursor::KeepAnchor);
270 viewSourceTV->setTextCursor(c);
272 //the real highlighting is done with an ExtraSelection
273 QTextCharFormat format;
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());
284 format.setBackground(alt);
286 format.setProperty(QTextFormat::FullWidthSelection, true);
287 QTextEdit::ExtraSelection sel;
290 viewSourceTV->setExtraSelections(
291 QList<QTextEdit::ExtraSelection>() << sel);
295 viewSourceTV->setTextCursor(c);
296 viewSourceTV->horizontalScrollBar()->setValue(h_scroll);
297 } // else if (texrow)
301 docstring ViewSourceWidget::currentFormatName(BufferView const * bv) const
303 // Compute the actual format used
304 string const format = !bv ? ""
305 : flavor2format(bv->buffer().params().getOutputFlavor(view_format_));
306 Format const * f = theFormats().getFormat(format.empty() ? view_format_ : format);
307 return f ? f->prettyname() : from_utf8(view_format_);
311 bool ViewSourceWidget::eventFilter(QObject * obj, QEvent * ev)
313 // this event filter is installed on the viewport of the QTextView
314 if (obj == viewSourceTV->viewport() &&
315 ev->type() == QEvent::MouseButtonDblClick) {
323 void ViewSourceWidget::goToCursor() const
327 int row = viewSourceTV->textCursor().blockNumber() + 1;
328 dispatch(texrow_->goToFuncFromRow(row));
333 void ViewSourceWidget::updateDefaultFormat(BufferView const & bv)
335 QSignalBlocker blocker(outputFormatCO);
336 outputFormatCO->clear();
337 outputFormatCO->addItem(qt_("Default"),
338 QVariant(QString("default")));
341 for (string const & fmt_name : bv.buffer().params().backends()) {
342 Format const * fmt = theFormats().getFormat(fmt_name);
344 LYXERR0("Can't find format for backend " << fmt_name << "!");
347 QString const pretty = toqstr(translateIfPossible(fmt->prettyname()));
348 outputFormatCO->addItem(pretty, QVariant(toqstr(fmt_name)));
349 if (fmt_name == view_format_)
350 index = outputFormatCO->count() - 1;
352 setViewFormat(index);
356 void ViewSourceWidget::resizeEvent (QResizeEvent * event)
358 QSize const & formSize = formLayout->sizeHint();
359 // minimize the size of the part that contains the buttons
360 if (width() * formSize.height() < height() * formSize.width()) {
361 layout_->setDirection(QBoxLayout::TopToBottom);
363 layout_->setDirection(QBoxLayout::LeftToRight);
365 QWidget::resizeEvent(event);
369 void ViewSourceWidget::saveSession(QString const & session_key) const
372 settings.setValue(session_key + "/output", toqstr(view_format_));
373 settings.setValue(session_key + "/contents", contentsCO->currentIndex());
374 settings.setValue(session_key + "/autoupdate", autoUpdateCB->isChecked());
375 settings.setValue(session_key + "/masterview",
376 masterPerspectiveCB->isChecked());
380 void ViewSourceWidget::restoreSession(QString const & session_key)
383 view_format_ = fromqstr(settings.value(session_key + "/output", 0)
385 contentsCO->setCurrentIndex(settings
386 .value(session_key + "/contents", 0)
388 masterPerspectiveCB->setChecked(settings
389 .value(session_key + "/masterview", false)
391 bool const checked = settings
392 .value(session_key + "/autoupdate", true)
394 autoUpdateCB->setChecked(checked);
400 GuiViewSource::GuiViewSource(GuiView & parent,
401 Qt::DockWidgetArea area, Qt::WindowFlags flags)
402 : DockView(parent, "view-source", qt_("Code Preview"), area, flags),
403 widget_(new ViewSourceWidget(this)),
404 update_timer_(new QTimer(this))
408 // setting the update timer
409 update_timer_->setSingleShot(true);
410 connect(update_timer_, SIGNAL(timeout()),
411 this, SLOT(realUpdateView()));
413 connect(widget_, SIGNAL(needUpdate()), this, SLOT(scheduleUpdateNow()));
417 void GuiViewSource::onBufferViewChanged()
420 widget_->setEnabled((bool)bufferview());
424 void GuiViewSource::updateView()
426 if (widget_->autoUpdateCB->isChecked()) {
427 widget_->setEnabled((bool)bufferview());
430 widget_->masterPerspectiveCB->setEnabled(buffer().parent());
435 void GuiViewSource::enableView(bool enable)
437 widget_->setEnabled((bool)bufferview());
439 widget_->updateDefaultFormat(*bufferview());
441 // In the opposite case, updateView() will be called anyway.
442 widget_->contentsChanged();
446 bool GuiViewSource::initialiseParams(string const & /*source*/)
453 void GuiViewSource::updateTitle()
455 docstring const format = widget_->currentFormatName(bufferview());
456 QString const title = format.empty() ? qt_("Code Preview")
457 : qt_("%1[[preview format name]] Preview")
458 .arg(toqstr(translateIfPossible(format)));
460 setWindowTitle(title);
464 void GuiViewSource::saveSession() const
466 Dialog::saveSession();
467 widget_->saveSession(sessionKey());
471 void GuiViewSource::restoreSession()
473 DockView::restoreSession();
474 widget_->restoreSession(sessionKey());
478 Dialog * createGuiViewSource(GuiView & lv)
480 return new GuiViewSource(lv);
484 } // namespace frontend
487 #include "moc_GuiViewSource.cpp"