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