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