]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiViewSource.cpp
Use QFontMetrics information for underlines (and friends) width and position
[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 "Buffer.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "Cursor.h"
24 #include "Format.h"
25 #include "Paragraph.h"
26 #include "TexRow.h"
27
28 #include "support/debug.h"
29 #include "support/lassert.h"
30 #include "support/docstream.h"
31 #include "support/gettext.h"
32
33 #include <boost/crc.hpp>
34
35 #include <QBoxLayout>
36 #include <QSettings>
37 #include <QTextCursor>
38 #include <QTextDocument>
39 #include <QVariant>
40
41 using namespace std;
42
43 namespace lyx {
44 namespace frontend {
45
46 ViewSourceWidget::ViewSourceWidget()
47         :       bv_(0), document_(new QTextDocument(this)),
48                 highlighter_(new LaTeXHighlighter(document_)),
49                 force_getcontent_(true)
50 {
51         setupUi(this);
52
53         connect(contentsCO, SIGNAL(activated(int)),
54                 this, SLOT(contentsChanged()));
55         connect(autoUpdateCB, SIGNAL(toggled(bool)),
56                 updatePB, SLOT(setDisabled(bool)));
57         connect(autoUpdateCB, SIGNAL(toggled(bool)),
58                 this, SLOT(updateView()));
59         connect(masterPerspectiveCB, SIGNAL(toggled(bool)),
60                 this, SLOT(updateView()));
61         connect(updatePB, SIGNAL(clicked()),
62                 this, SLOT(updateView()));
63         connect(outputFormatCO, SIGNAL(activated(int)),
64                 this, SLOT(setViewFormat()));
65
66         // setting a document at this point trigger an assertion in Qt
67         // so we disable the signals here:
68         document_->blockSignals(true);
69         viewSourceTV->setDocument(document_);
70         document_->blockSignals(false);
71         viewSourceTV->setReadOnly(true);
72         ///dialog_->viewSourceTV->setAcceptRichText(false);
73         // this is personal. I think source code should be in fixed-size font
74         QFont font(guiApp->typewriterFontName());
75         font.setFixedPitch(true);
76         font.setStyleHint(QFont::TypeWriter);
77         viewSourceTV->setFont(font);
78         // again, personal taste
79         viewSourceTV->setWordWrapMode(QTextOption::NoWrap);
80 }
81
82
83 static size_t crcCheck(docstring const & s)
84 {
85         boost::crc_32_type crc;
86         crc.process_bytes(&s[0], sizeof(char_type) * s.size());
87         return crc.checksum();
88 }
89
90
91 /** get the source code of selected paragraphs, or the whole document
92         \param fullSource get full source code
93         \return true if the content has changed since last call.
94  */
95 static bool getContent(BufferView const * view, Buffer::OutputWhat output,
96                        QString & qstr, string const & format, bool force_getcontent,
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         view->buffer().getSourceCode(ostr, format, par_begin, par_end + 1,
115                                      output, master);
116         docstring s = ostr.str();
117         // FIXME THREAD
118         // Could this be private to this particular dialog? We could have
119         // more than one of these, in different windows.
120         static size_t crc = 0;
121         size_t newcrc = crcCheck(s);
122         if (newcrc == crc && !force_getcontent)
123                 return false;
124         crc = newcrc;
125         qstr = toqstr(s);
126         return true;
127 }
128
129
130 void ViewSourceWidget::setBufferView(BufferView const * bv)
131 {
132         if (bv_ != bv)
133                 force_getcontent_ = true;
134         bv_ = bv;
135         setEnabled(bv ?  true : false);
136 }
137
138
139 void ViewSourceWidget::contentsChanged()
140 {
141         if (autoUpdateCB->isChecked())
142                 updateView();
143 }
144
145
146 void ViewSourceWidget::setViewFormat()
147 {
148         view_format_ = outputFormatCO->itemData(
149               outputFormatCO->currentIndex()).toString();
150         updateView();
151 }
152
153
154 void ViewSourceWidget::updateView()
155 {
156         if (!bv_) {
157                 document_->setPlainText(QString());
158                 setEnabled(false);
159                 return;
160         }
161
162         setEnabled(true);
163
164         string const format = fromqstr(view_format_);
165
166         QString content;
167         Buffer::OutputWhat output = Buffer::CurrentParagraph;
168         if (contentsCO->currentIndex() == 1)
169                 output = Buffer::FullSource;
170         else if (contentsCO->currentIndex() == 2)
171                 output = Buffer::OnlyPreamble;
172         else if (contentsCO->currentIndex() == 3)
173                 output = Buffer::OnlyBody;
174
175         if (getContent(bv_, output, content, format,
176                       force_getcontent_, masterPerspectiveCB->isChecked()))
177                 document_->setPlainText(content);
178
179         CursorSlice beg = bv_->cursor().selectionBegin().bottom();
180         CursorSlice end = bv_->cursor().selectionEnd().bottom();
181         int const begrow = bv_->buffer().texrow().
182                 getRowFromIdPos(beg.paragraph().id(), beg.pos());
183         int endrow = bv_->buffer().texrow().
184                 getRowFromIdPos(end.paragraph().id(), end.pos());
185         int const nextendrow = bv_->buffer().texrow().
186                 getRowFromIdPos(end.paragraph().id(), end.pos() + 1);
187         if (endrow != nextendrow)
188                 endrow = nextendrow - 1;
189
190         QTextCursor c = QTextCursor(viewSourceTV->document());
191         c.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor, begrow);
192         c.select(QTextCursor::BlockUnderCursor);
193         c.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor,
194                 endrow - begrow + 1);
195         viewSourceTV->setTextCursor(c);
196 }
197
198
199 void ViewSourceWidget::updateDefaultFormat()
200 {
201         if (!bv_)
202                 return;
203
204         outputFormatCO->blockSignals(true);
205         outputFormatCO->clear();
206         outputFormatCO->addItem(qt_("Default"),
207                                 QVariant(QString("default")));
208
209         int index = 0;
210         vector<string> tmp = bv_->buffer().params().backends();
211         vector<string>::const_iterator it = tmp.begin();
212         vector<string>::const_iterator en = tmp.end();
213         for (; it != en; ++it) {
214                 string const format = *it;
215                 Format const * fmt = formats.getFormat(format);
216                 if (!fmt) {
217                         LYXERR0("Can't find format for backend " << format << "!");
218                         continue;
219                 } 
220
221                 QString const pretty = qt_(fmt->prettyname());
222                 QString const qformat = toqstr(format);
223                 outputFormatCO->addItem(pretty, QVariant(qformat));
224                 if (qformat == view_format_)
225                    index = outputFormatCO->count() -1;
226         }
227         outputFormatCO->setCurrentIndex(index);
228
229         outputFormatCO->blockSignals(false);
230 }
231
232
233 void ViewSourceWidget::resizeEvent (QResizeEvent * event)
234 {
235         QSize const & formSize = formLayout->sizeHint();
236         // minimize the size of the part that contains the buttons
237         if (width() * formSize.height() < height() * formSize.width()) {
238                 layout_->setDirection(QBoxLayout::TopToBottom);
239         } else {
240                 layout_->setDirection(QBoxLayout::LeftToRight);
241         }
242         QWidget::resizeEvent(event);
243 }
244
245
246 GuiViewSource::GuiViewSource(GuiView & parent,
247                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
248         : DockView(parent, "view-source", qt_("LaTeX Source"), area, flags)
249 {
250         widget_ = new ViewSourceWidget;
251         setWidget(widget_);
252 }
253
254
255 GuiViewSource::~GuiViewSource()
256 {
257         delete widget_;
258 }
259
260
261 void GuiViewSource::updateView()
262 {
263         if (widget_->autoUpdateCB->isChecked()) {
264                 widget_->setBufferView(bufferview());
265                 widget_->updateView();
266         }
267         widget_->masterPerspectiveCB->setEnabled(buffer().parent());
268 }
269
270
271 void GuiViewSource::enableView(bool enable)
272 {
273         widget_->setBufferView(bufferview());
274         widget_->updateDefaultFormat();
275         if (!enable)
276                 // In the opposite case, updateView() will be called anyway.
277                 widget_->updateView();
278 }
279
280
281 bool GuiViewSource::initialiseParams(string const & /*source*/)
282 {
283         setWindowTitle(title());
284         return true;
285 }
286
287
288 QString GuiViewSource::title() const
289 {
290         switch (docType()) {
291                 case LATEX:
292                         return qt_("LaTeX Source");
293                 case DOCBOOK:
294                         return qt_("DocBook Source");
295                 case LITERATE:
296                         return qt_("Literate Source");
297         }
298         LATTEST(false);
299         return QString();
300 }
301
302
303 void GuiViewSource::saveSession() const
304 {
305         Dialog::saveSession();
306         QSettings settings;
307         // see below
308         // settings.setValue(
309         //      sessionKey() + "/output", widget_->contentsCO->currentIndex());
310         settings.setValue(
311                 sessionKey() + "/autoupdate", widget_->autoUpdateCB->isChecked());
312 }
313
314
315 void GuiViewSource::restoreSession()
316 {
317         DockView::restoreSession();
318         // FIXME: Full source updating is too slow to be done at startup.
319         //widget_->outputCO-setCurrentIndex(
320         //      settings.value(sessionKey() + "/output", false).toInt());
321         widget_->contentsCO->setCurrentIndex(0);
322         QSettings settings;
323         widget_->autoUpdateCB->setChecked(
324                 settings.value(sessionKey() + "/autoupdate", true).toBool());
325         widget_->updateView();
326 }
327
328
329 Dialog * createGuiViewSource(GuiView & lv)
330 {
331         return new GuiViewSource(lv);
332 }
333
334
335 } // namespace frontend
336 } // namespace lyx
337
338 #include "moc_GuiViewSource.cpp"