]> git.lyx.org Git - features.git/blob - src/BufferView_pimpl.C
Fix clipboard/selection encoding
[features.git] / src / BufferView_pimpl.C
1 /**
2  * \file BufferView_pimpl.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Alfredo Braunstein
8  * \author Lars Gullik Bjønnes
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  * \author Abdelrazak Younes
16  *
17  * Full author contact details are available in file CREDITS.
18  */
19
20 #include <config.h>
21
22 #include "BufferView_pimpl.h"
23 #include "buffer.h"
24 #include "buffer_funcs.h"
25 #include "bufferlist.h"
26 #include "bufferparams.h"
27 #include "coordcache.h"
28 #include "cursor.h"
29 #include "CutAndPaste.h"
30 #include "debug.h"
31 #include "dispatchresult.h"
32 #include "errorlist.h"
33 #include "factory.h"
34 #include "FloatList.h"
35 #include "funcrequest.h"
36 #include "FuncStatus.h"
37 #include "gettext.h"
38 #include "intl.h"
39 #include "insetiterator.h"
40 #include "LaTeXFeatures.h"
41 #include "lyx_cb.h" // added for Dispatch functions
42 #include "lyx_main.h"
43 #include "lyxfind.h"
44 #include "lyxfunc.h"
45 #include "lyxtext.h"
46 #include "lyxrc.h"
47 #include "session.h"
48 #include "metricsinfo.h"
49 #include "paragraph.h"
50 #include "paragraph_funcs.h"
51 #include "ParagraphParameters.h"
52 #include "pariterator.h"
53 #include "toc.h"
54 #include "undo.h"
55 #include "vspace.h"
56
57 #include "insets/insetbibtex.h"
58 #include "insets/insetref.h"
59 #include "insets/insettext.h"
60
61 #include "frontends/Alert.h"
62 #include "frontends/Dialogs.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/font_metrics.h"
65 #include "frontends/Gui.h"
66 #include "frontends/LyXView.h"
67 #include "frontends/Selection.h"
68
69 #include "graphics/Previews.h"
70
71 #include "support/convert.h"
72 #include "support/filefilterlist.h"
73 #include "support/filetools.h"
74 #include "support/package.h"
75 #include "support/types.h"
76
77 #include <boost/bind.hpp>
78 #include <boost/current_function.hpp>
79
80 #include <functional>
81 #include <vector>
82
83 using lyx::frontend::Clipboard;
84 using lyx::frontend::Gui;
85
86 using lyx::docstring;
87 using lyx::pos_type;
88
89 using lyx::support::addPath;
90 using lyx::support::bformat;
91 using lyx::support::FileFilterList;
92 using lyx::support::fileSearch;
93 using lyx::support::isDirWriteable;
94 using lyx::support::makeDisplayPath;
95 using lyx::support::makeAbsPath;
96 using lyx::support::package;
97
98 using std::endl;
99 using std::istringstream;
100 using std::make_pair;
101 using std::min;
102 using std::max;
103 using std::string;
104 using std::mem_fun_ref;
105 using std::vector;
106
107 extern BufferList bufferlist;
108
109
110 namespace {
111
112 unsigned int const saved_positions_num = 20;
113
114
115 /// Return an inset of this class if it exists at the current cursor position
116 template <class T>
117 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
118 {
119         T * inset = 0;
120         DocIterator it = cur;
121         if (it.nextInset() &&
122             it.nextInset()->lyxCode() == code) {
123                 inset = static_cast<T*>(it.nextInset());
124         }
125         return inset;
126 }
127
128 } // anon namespace
129
130
131 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner)
132         : bv_(&bv), owner_(owner), buffer_(0), wh_(0),
133           cursor_(bv),
134           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
135 {
136         xsel_cache_.set = false;
137
138         saved_positions.resize(saved_positions_num);
139         // load saved bookmarks
140         lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
141         for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
142                 bm != bmList.end(); ++bm)
143                 if (bm->get<0>() < saved_positions_num)
144                         saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
145         // and then clear them
146         bmList.clear();
147 }
148
149
150 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
151 {
152         // Get absolute path of file and add ".lyx"
153         // to the filename if necessary
154         string s = fileSearch(string(), filename, "lyx");
155
156         bool const found = !s.empty();
157
158         if (!found)
159                 s = filename;
160
161         // File already open?
162         if (bufferlist.exists(s)) {
163                 string const file = makeDisplayPath(s, 20);
164                 string text = bformat(_("The document %1$s is already "
165                                         "loaded.\n\nDo you want to revert "
166                                         "to the saved version?"), file);
167                 int const ret = Alert::prompt(_("Revert to saved document?"),
168                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
169
170                 if (ret != 0) {
171                         setBuffer(bufferlist.getBuffer(s));
172                         return true;
173                 }
174                 // FIXME: should be LFUN_REVERT
175                 if (!bufferlist.close(bufferlist.getBuffer(s), false))
176                         return false;
177                 // Fall through to new load. (Asger)
178         }
179
180         Buffer * b = 0;
181
182         if (found) {
183                 b = bufferlist.newBuffer(s);
184                 if (!::loadLyXFile(b, s)) {
185                         bufferlist.release(b);
186                         return false;
187                 }
188         } else {
189                 string text = bformat(_("The document %1$s does not yet "
190                                         "exist.\n\nDo you want to create "
191                                         "a new document?"), s);
192                 int const ret = Alert::prompt(_("Create new document?"),
193                          text, 0, 1, _("&Create"), _("Cancel"));
194
195                 if (ret == 0) {
196                         b = newFile(s, string(), true);
197                         if (!b)
198                                 return false;
199                 } else
200                         return false;
201         }
202
203         setBuffer(b);
204         // Send the "errors" signal in case of parsing errors
205         b->errors("Parse");
206
207         // scroll to the position when the file was last closed
208         if (lyxrc.use_lastfilepos) {
209                 lyx::pit_type pit;
210                 lyx::pos_type pos;
211                 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
212                 // I am not sure how to separate the following part to a function
213                 // so I will leave this to Lars.
214                 //
215                 // check pit since the document may be externally changed.
216                 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
217                         ParIterator it = b->par_iterator_begin();
218                         ParIterator const end = b->par_iterator_end();
219                         for (; it != end; ++it)
220                                 if (it.pit() == pit) {
221                                         // restored pos may be bigger than it->size
222                                         bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
223                                         bv_->update(Update::FitCursor);
224                                         break;
225                                 }
226                 }
227         }
228
229         if (tolastfiles)
230                 LyX::ref().session().addLastFile(b->fileName());
231
232         return true;
233 }
234
235
236 int BufferView::Pimpl::width() const
237 {
238         return width_;
239 }
240
241
242 int BufferView::Pimpl::height() const
243 {
244         return height_;
245 }
246
247
248 void BufferView::Pimpl::setBuffer(Buffer * b)
249 {
250         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
251                             << "[ b = " << b << "]" << endl;
252
253         if (buffer_) {
254                 // Save the actual cursor position and anchor inside the
255                 // buffer so that it can be restored in case we rechange
256                 // to this buffer later on.
257                 buffer_->saveCursor(cursor_.selectionBegin(),
258                                     cursor_.selectionEnd());
259                 // current buffer is going to be switched-off, save cursor pos
260                 LyX::ref().session().saveFilePosition(buffer_->fileName(),
261                         boost::tie(cursor_.pit(), cursor_.pos()) );
262         }
263
264         // If we're quitting lyx, don't bother updating stuff
265         if (quitting) {
266                 buffer_ = 0;
267                 return;
268         }
269
270         // If we are closing current buffer, switch to the first in
271         // buffer list.
272         if (!b) {
273                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
274                                     << " No Buffer!" << endl;
275                 // We are closing the buffer, use the first buffer as current
276                 buffer_ = bufferlist.first();
277         } else {
278                 // Set current buffer
279                 buffer_ = b;
280         }
281
282         // Reset old cursor
283         cursor_ = LCursor(*bv_);
284         anchor_ref_ = 0;
285         offset_ref_ = 0;
286
287         if (buffer_) {
288                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
289                                     << "Buffer addr: " << buffer_ << endl;
290                 cursor_.push(buffer_->inset());
291                 cursor_.resetAnchor();
292                 buffer_->text().init(bv_);
293                 buffer_->text().setCurrentFont(cursor_);
294                 if (buffer_->getCursor().size() > 0 &&
295                     buffer_->getAnchor().size() > 0)
296                 {
297                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
298                         cursor_.resetAnchor();
299                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
300                         cursor_.setSelection();
301                 }
302         }
303
304         update();
305
306         if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
307                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
308 }
309
310
311 void BufferView::Pimpl::resizeCurrentBuffer()
312 {
313         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
314
315         LyXText * text = bv_->text();
316         if (!text)
317                 return;
318
319         text->init(bv_);
320         update();
321         switchKeyMap();
322 }
323
324
325 void BufferView::Pimpl::updateScrollbar()
326 {
327         if (!bv_->text()) {
328                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
329                                      << " no text in updateScrollbar" << endl;
330                 scrollbarParameters_.reset();
331                 return;
332         }
333
334         LyXText & t = *bv_->text();
335         int const parsize = int(t.paragraphs().size() - 1);
336         if (anchor_ref_ >  parsize)  {
337                 anchor_ref_ = parsize;
338                 offset_ref_ = 0;
339         }
340
341         lyxerr[Debug::GUI]
342                 << BOOST_CURRENT_FUNCTION
343                 << " Updating scrollbar: height: " << t.paragraphs().size()
344                 << " curr par: " << cursor_.bottom().pit()
345                 << " default height " << defaultRowHeight() << endl;
346
347         // It would be better to fix the scrollbar to understand
348         // values in [0..1] and divide everything by wh
349
350         // estimated average paragraph height:
351         if (wh_ == 0)
352                 wh_ = height_ / 4;
353         int h = t.getPar(anchor_ref_).height();
354
355         // Normalize anchor/offset (MV):
356         while (offset_ref_ > h && anchor_ref_ < parsize) {
357                 anchor_ref_++;
358                 offset_ref_ -= h;
359                 h = t.getPar(anchor_ref_).height();
360         }
361         // Look at paragraph heights on-screen
362         int sumh = 0;
363         int nh = 0;
364         for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
365                 if (sumh > height_)
366                         break;
367                 int const h2 = t.getPar(pit).height();
368                 sumh += h2;
369                 nh++;
370         }
371         int const hav = sumh / nh;
372         // More realistic average paragraph height
373         if (hav > wh_)
374                 wh_ = hav;
375
376         scrollbarParameters_.height = (parsize + 1) * wh_;
377         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
378         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
379 }
380
381
382 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
383 {
384         return scrollbarParameters_;
385 }
386
387
388 void BufferView::Pimpl::scrollDocView(int value)
389 {
390         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
391                            << "[ value = " << value << "]" << endl;
392
393         if (!buffer_)
394                 return;
395
396         LyXText & t = *bv_->text();
397
398         float const bar = value / float(wh_ * t.paragraphs().size());
399
400         anchor_ref_ = int(bar * t.paragraphs().size());
401         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
402                 anchor_ref_ = int(t.paragraphs().size()) - 1;
403         t.redoParagraph(anchor_ref_);
404         int const h = t.getPar(anchor_ref_).height();
405         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
406 }
407
408
409 void BufferView::Pimpl::setCursorFromScrollbar()
410 {
411         LyXText & t = *bv_->text();
412
413         int const height = 2 * defaultRowHeight();
414         int const first = height;
415         int const last = height_ - height;
416         LCursor & cur = cursor_;
417
418         bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
419
420         switch (st) {
421         case bv_funcs::CUR_ABOVE:
422                 t.setCursorFromCoordinates(cur, 0, first);
423                 cur.clearSelection();
424                 break;
425         case bv_funcs::CUR_BELOW:
426                 t.setCursorFromCoordinates(cur, 0, last);
427                 cur.clearSelection();
428                 break;
429         case bv_funcs::CUR_INSIDE:
430                 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
431                 int const newy = min(last, max(y, first));
432                 if (y != newy) {
433                         cur.reset(buffer_->inset());
434                         t.setCursorFromCoordinates(cur, 0, newy);
435                 }
436         }
437 }
438
439
440 void BufferView::Pimpl::scroll(int /*lines*/)
441 {
442 //      if (!buffer_)
443 //              return;
444 //
445 //      LyXText const * t = bv_->text();
446 //      int const line_height = defaultRowHeight();
447 //
448 //      // The new absolute coordinate
449 //      int new_top_y = top_y() + lines * line_height;
450 //
451 //      // Restrict to a valid value
452 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
453 //      new_top_y = std::max(0, new_top_y);
454 //
455 //      scrollDocView(new_top_y);
456 //
457 //      // Update the scrollbar.
458 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
459 }
460
461
462 void BufferView::Pimpl::selectionRequested()
463 {
464         static docstring sel;
465
466         if (!available())
467                 return;
468
469         LCursor & cur = cursor_;
470
471         if (!cur.selection()) {
472                 xsel_cache_.set = false;
473                 return;
474         }
475
476         if (!xsel_cache_.set ||
477             cur.top() != xsel_cache_.cursor ||
478             cur.anchor_.top() != xsel_cache_.anchor)
479         {
480                 xsel_cache_.cursor = cur.top();
481                 xsel_cache_.anchor = cur.anchor_.top();
482                 xsel_cache_.set = cur.selection();
483                 sel = cur.selectionAsString(false);
484                 if (!sel.empty())
485                         owner_->gui().selection().put(sel);
486         }
487 }
488
489
490 void BufferView::Pimpl::selectionLost()
491 {
492         if (available()) {
493                 cursor_.clearSelection();
494                 xsel_cache_.set = false;
495         }
496 }
497
498
499 void BufferView::Pimpl::workAreaResize(int width, int height)
500 {
501         bool const widthChange = width != width_;
502         bool const heightChange = height != height_;
503
504         // Update from work area
505         width_ = width;
506         height_ = height;
507
508         if (buffer_ && widthChange) {
509                 // The WorkArea content needs a resize
510                 resizeCurrentBuffer();
511         }
512
513         if (widthChange || heightChange)
514                 update();
515 }
516
517
518 bool BufferView::Pimpl::fitCursor()
519 {
520         if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
521                 LyXFont const font = cursor_.getFont();
522                 int const asc = font_metrics::maxAscent(font);
523                 int const des = font_metrics::maxDescent(font);
524                 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
525                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
526                         return false;
527         }
528         center();
529         return true;
530 }
531
532
533 bool BufferView::Pimpl::multiParSel()
534 {
535         if (!cursor_.selection())
536                 return false;
537         bool ret = multiparsel_cache_;
538         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
539         // Either this, or previous selection spans paragraphs
540         return ret || multiparsel_cache_;
541 }
542
543
544 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
545 {
546         return metrics_info_;
547 }
548
549
550 bool BufferView::Pimpl::update(Update::flags flags)
551 {
552         // This is close to a hot-path.
553         if (lyxerr.debugging(Debug::DEBUG)) {
554                 lyxerr[Debug::DEBUG]
555                         << BOOST_CURRENT_FUNCTION
556                         << "[fitcursor = " << (flags & Update::FitCursor)
557                         << ", forceupdate = " << (flags & Update::Force)
558                         << ", singlepar = " << (flags & Update::SinglePar)
559                         << "]  buffer: " << buffer_ << endl;
560         }
561
562         // Check needed to survive LyX startup
563         if (!buffer_)
564                 return false;
565
566         // Update macro store
567         buffer_->buildMacros();
568
569         // First drawing step
570         updateMetrics(flags & Update::SinglePar);
571
572         // The second drawing step is done in WorkArea::redraw() if needed.
573         bool const need_second_step =
574                 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
575                 && (fitCursor() || multiParSel());
576
577         return need_second_step;
578 }
579
580
581 bool BufferView::Pimpl::available() const
582 {
583         return buffer_ && bv_->text();
584 }
585
586
587 Change const BufferView::Pimpl::getCurrentChange()
588 {
589         if (!buffer_->params().tracking_changes)
590                 return Change(Change::UNCHANGED);
591
592         LyXText * text = bv_->getLyXText();
593         LCursor & cur = cursor_;
594
595         if (!cur.selection())
596                 return Change(Change::UNCHANGED);
597
598         return text->getPar(cur.selBegin().pit()).
599                         lookupChange(cur.selBegin().pos());
600 }
601
602
603 void BufferView::Pimpl::savePosition(unsigned int i)
604 {
605         if (i >= saved_positions_num)
606                 return;
607         BOOST_ASSERT(cursor_.inTexted());
608         saved_positions[i] = Position(buffer_->fileName(),
609                                       cursor_.paragraph().id(),
610                                       cursor_.pos());
611         if (i > 0)
612                 // emit message signal.
613                 bv_->message(bformat(_("Saved bookmark %1$d"), i));
614 }
615
616
617 void BufferView::Pimpl::restorePosition(unsigned int i)
618 {
619         if (i >= saved_positions_num)
620                 return;
621
622         string const fname = saved_positions[i].filename;
623
624         cursor_.clearSelection();
625
626         if (fname != buffer_->fileName()) {
627                 Buffer * b = 0;
628                 if (bufferlist.exists(fname))
629                         b = bufferlist.getBuffer(fname);
630                 else {
631                         b = bufferlist.newBuffer(fname);
632                         // Don't ask, just load it
633                         ::loadLyXFile(b, fname);
634                 }
635                 if (b)
636                         setBuffer(b);
637         }
638
639         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
640         if (par == buffer_->par_iterator_end())
641                 return;
642
643         bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
644
645         if (i > 0)
646                 // emit message signal.
647                 bv_->message(bformat(_("Moved to bookmark %1$d"), i));
648 }
649
650
651 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
652 {
653         return i < saved_positions_num && !saved_positions[i].filename.empty();
654 }
655
656
657 void BufferView::Pimpl::saveSavedPositions()
658 {
659         // save bookmarks. It is better to use the pit interface
660         // but I do not know how to effectively convert between
661         // par_id and pit.
662         for (unsigned int i=1; i < saved_positions_num; ++i) {
663                 if ( isSavedPosition(i) )
664                         LyX::ref().session().saveBookmark( boost::tie(
665                                 i,
666                                 saved_positions[i].filename,
667                                 saved_positions[i].par_id,
668                                 saved_positions[i].par_pos) );
669         }
670 }
671
672
673 void BufferView::Pimpl::switchKeyMap()
674 {
675         if (!lyxrc.rtl_support)
676                 return;
677
678         Intl & intl = owner_->getIntl();
679         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
680                 if (intl.keymap == Intl::PRIMARY)
681                         intl.keyMapSec();
682         } else {
683                 if (intl.keymap == Intl::SECONDARY)
684                         intl.keyMapPrim();
685         }
686 }
687
688
689 void BufferView::Pimpl::center()
690 {
691         CursorSlice & bot = cursor_.bottom();
692         lyx::pit_type const pit = bot.pit();
693         bot.text()->redoParagraph(pit);
694         Paragraph const & par = bot.text()->paragraphs()[pit];
695         anchor_ref_ = pit;
696         offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
697                 + par.ascent() - height_ / 2;
698 }
699
700
701 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
702 {
703         BOOST_ASSERT(cursor_.inTexted());
704         string filename = filenm;
705
706         if (filename.empty()) {
707                 // Launch a file browser
708                 string initpath = lyxrc.document_path;
709
710                 if (available()) {
711                         string const trypath = buffer_->filePath();
712                         // If directory is writeable, use this as default.
713                         if (isDirWriteable(trypath))
714                                 initpath = trypath;
715                 }
716
717                 FileDialog fileDlg(_("Select LyX document to insert"),
718                         LFUN_FILE_INSERT,
719                         make_pair(string(_("Documents|#o#O")),
720                                   string(lyxrc.document_path)),
721                         make_pair(string(_("Examples|#E#e")),
722                                   string(addPath(package().system_support(), "examples"))));
723
724                 FileDialog::Result result =
725                         fileDlg.open(initpath,
726                                      FileFilterList(_("LyX Documents (*.lyx)")),
727                                      string());
728
729                 if (result.first == FileDialog::Later)
730                         return;
731
732                 filename = result.second;
733
734                 // check selected filename
735                 if (filename.empty()) {
736                         // emit message signal.
737                         bv_->message(_("Canceled."));
738                         return;
739                 }
740         }
741
742         // Get absolute path of file and add ".lyx"
743         // to the filename if necessary
744         filename = fileSearch(string(), filename, "lyx");
745
746         string const disp_fn = makeDisplayPath(filename);
747         // emit message signal.
748         bv_->message(bformat(_("Inserting document %1$s..."), disp_fn));
749
750         string res;
751         Buffer buf("", false);
752         if (::loadLyXFile(&buf, makeAbsPath(filename))) {
753                 ErrorList & el = buffer_->errorList("Parse");
754                 // Copy the inserted document error list into the current buffer one.
755                 el = buf.errorList("Parse");
756                 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
757                                              buf.params().textclass, el);
758                 res = _("Document %1$s inserted.");
759         } else
760                 res = _("Could not insert document %1$s");
761
762         // emit message signal.
763         bv_->message(bformat(res, disp_fn));
764         buffer_->errors("Parse");
765         resizeCurrentBuffer();
766 }
767
768
769 void BufferView::Pimpl::trackChanges()
770 {
771         bool const tracking = buffer_->params().tracking_changes;
772
773         if (!tracking) {
774                 for_each(buffer_->par_iterator_begin(),
775                          buffer_->par_iterator_end(),
776                          bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
777                 buffer_->params().tracking_changes = true;
778
779                 // We cannot allow undos beyond the freeze point
780                 buffer_->undostack().clear();
781         } else {
782                 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
783                 if (lyx::find::findNextChange(bv_)) {
784                         owner_->getDialogs().show("changes");
785                         return;
786                 }
787
788                 for_each(buffer_->par_iterator_begin(),
789                          buffer_->par_iterator_end(),
790                          mem_fun_ref(&Paragraph::untrackChanges));
791
792                 buffer_->params().tracking_changes = false;
793         }
794
795         buffer_->redostack().clear();
796 }
797
798
799 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
800 {
801         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
802
803         // This is only called for mouse related events including
804         // LFUN_FILE_OPEN generated by drag-and-drop.
805         FuncRequest cmd = cmd0;
806
807         if (!buffer_)
808                 return false;
809
810         LCursor cur(*bv_);
811         cur.push(buffer_->inset());
812         cur.selection() = cursor_.selection();
813
814         // Doesn't go through lyxfunc, so we need to update
815         // the layout choice etc. ourselves
816
817         // E.g. Qt mouse press when no buffer
818         if (!available())
819                 return false;
820
821         // Either the inset under the cursor or the
822         // surrounding LyXText will handle this event.
823
824         // Build temporary cursor.
825         cmd.y = min(max(cmd.y, -1), height_);
826         InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
827         //lyxerr << BOOST_CURRENT_FUNCTION
828         //       << " * hit inset at tip: " << inset << endl;
829         //lyxerr << BOOST_CURRENT_FUNCTION
830         //       << " * created temp cursor:" << cur << endl;
831
832         // Put anchor at the same position.
833         cur.resetAnchor();
834
835         // Try to dispatch to an non-editable inset near this position
836         // via the temp cursor. If the inset wishes to change the real
837         // cursor it has to do so explicitly by using
838         //  cur.bv().cursor() = cur;  (or similar)
839         if (inset)
840                 inset->dispatch(cur, cmd);
841
842         // Now dispatch to the temporary cursor. If the real cursor should
843         // be modified, the inset's dispatch has to do so explicitly.
844         if (!cur.result().dispatched())
845                 cur.dispatch(cmd);
846
847         if (cur.result().dispatched()) {
848                 // Redraw if requested or necessary.
849                 if (cur.result().update())
850                         update(Update::FitCursor | Update::Force);
851                 else
852                         update(Update::FitCursor | Update::MultiParSel);
853         }
854
855         return true;
856 }
857
858
859 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
860 {
861         FuncStatus flag;
862
863         switch (cmd.action) {
864
865         case LFUN_UNDO:
866                 flag.enabled(!buffer_->undostack().empty());
867                 break;
868         case LFUN_REDO:
869                 flag.enabled(!buffer_->redostack().empty());
870                 break;
871         case LFUN_FILE_INSERT:
872         case LFUN_FILE_INSERT_ASCII_PARA:
873         case LFUN_FILE_INSERT_ASCII:
874         case LFUN_BOOKMARK_SAVE:
875                 // FIXME: Actually, these LFUNS should be moved to LyXText
876                 flag.enabled(cursor_.inTexted());
877                 break;
878         case LFUN_FONT_STATE:
879         case LFUN_LABEL_INSERT:
880         case LFUN_PARAGRAPH_GOTO:
881         // FIXME handle non-trivially
882         case LFUN_OUTLINE_UP:
883         case LFUN_OUTLINE_DOWN:
884         case LFUN_OUTLINE_IN:
885         case LFUN_OUTLINE_OUT:
886         case LFUN_NOTE_NEXT:
887         case LFUN_REFERENCE_NEXT:
888         case LFUN_WORD_FIND:
889         case LFUN_WORD_REPLACE:
890         case LFUN_MARK_OFF:
891         case LFUN_MARK_ON:
892         case LFUN_MARK_TOGGLE:
893         case LFUN_SCREEN_RECENTER:
894         case LFUN_BIBTEX_DATABASE_ADD:
895         case LFUN_BIBTEX_DATABASE_DEL:
896         case LFUN_WORDS_COUNT:
897         case LFUN_NEXT_INSET_TOGGLE:
898                 flag.enabled(true);
899                 break;
900
901         case LFUN_LABEL_GOTO: {
902                 flag.enabled(!cmd.argument().empty()
903                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
904                 break;
905         }
906
907         case LFUN_BOOKMARK_GOTO:
908                 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
909                 break;
910         case LFUN_CHANGES_TRACK:
911                 flag.enabled(true);
912                 flag.setOnOff(buffer_->params().tracking_changes);
913                 break;
914
915         case LFUN_CHANGES_OUTPUT: {
916                 OutputParams runparams;
917                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
918                 flag.enabled(buffer_ && buffer_->params().tracking_changes
919                         && features.isAvailable("dvipost"));
920                 flag.setOnOff(buffer_->params().output_changes);
921                 break;
922         }
923
924         case LFUN_CHANGES_MERGE:
925         case LFUN_CHANGE_ACCEPT: // what about these two
926         case LFUN_CHANGE_REJECT: // what about these two
927         case LFUN_ALL_CHANGES_ACCEPT:
928         case LFUN_ALL_CHANGES_REJECT:
929                 flag.enabled(buffer_ && buffer_->params().tracking_changes);
930                 break;
931
932         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
933                 flag.setOnOff(buffer_->params().compressed);
934                 break;
935         }
936
937         default:
938                 flag.enabled(false);
939         }
940
941         return flag;
942 }
943
944
945
946 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
947 {
948         //lyxerr << BOOST_CURRENT_FUNCTION
949         //       << [ cmd = " << cmd << "]" << endl;
950
951         // Make sure that the cached BufferView is correct.
952         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
953                 << " action[" << cmd.action << ']'
954                 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
955                 << " x[" << cmd.x << ']'
956                 << " y[" << cmd.y << ']'
957                 << " button[" << cmd.button() << ']'
958                 << endl;
959
960         LCursor & cur = cursor_;
961
962         switch (cmd.action) {
963
964         case LFUN_UNDO:
965                 if (available()) {
966                         cur.message(_("Undo"));
967                         cur.clearSelection();
968                         if (!textUndo(*bv_))
969                                 cur.message(_("No further undo information"));
970                         update();
971                         switchKeyMap();
972                 }
973                 break;
974
975         case LFUN_REDO:
976                 if (available()) {
977                         cur.message(_("Redo"));
978                         cur.clearSelection();
979                         if (!textRedo(*bv_))
980                                 cur.message(_("No further redo information"));
981                         update();
982                         switchKeyMap();
983                 }
984                 break;
985
986         case LFUN_FILE_INSERT:
987                 // FIXME: We don't know the encoding of filenames
988                 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
989                 break;
990
991         case LFUN_FILE_INSERT_ASCII_PARA:
992                 // FIXME: We don't know the encoding of filenames
993                 insertAsciiFile(bv_, lyx::to_utf8(cmd.argument()), true);
994                 break;
995
996         case LFUN_FILE_INSERT_ASCII:
997                 // FIXME: We don't know the encoding of filenames
998                 insertAsciiFile(bv_, lyx::to_utf8(cmd.argument()), false);
999                 break;
1000
1001         case LFUN_FONT_STATE:
1002                 cur.message(cur.currentState());
1003                 break;
1004
1005         case LFUN_BOOKMARK_SAVE:
1006                 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
1007                 break;
1008
1009         case LFUN_BOOKMARK_GOTO:
1010                 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
1011                 break;
1012
1013         case LFUN_LABEL_GOTO: {
1014                 string label = lyx::to_utf8(cmd.argument());
1015                 if (label.empty()) {
1016                         InsetRef * inset =
1017                                 getInsetByCode<InsetRef>(cursor_,
1018                                                          InsetBase::REF_CODE);
1019                         if (inset) {
1020                                 label = inset->getContents();
1021                                 savePosition(0);
1022                         }
1023                 }
1024
1025                 if (!label.empty())
1026                         bv_->gotoLabel(label);
1027                 break;
1028         }
1029
1030         case LFUN_PARAGRAPH_GOTO: {
1031                 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
1032                 ParIterator par = buffer_->getParFromID(id);
1033                 if (par == buffer_->par_iterator_end()) {
1034                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1035                                             << id << ']' << endl;
1036                         break;
1037                 } else {
1038                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1039                                             << " found." << endl;
1040                 }
1041
1042                 // Set the cursor
1043                 bv_->setCursor(makeDocIterator(par, 0));
1044
1045                 update();
1046                 switchKeyMap();
1047                 break;
1048         }
1049
1050         case LFUN_OUTLINE_UP:
1051                 lyx::toc::outline(lyx::toc::Up, cursor_);
1052                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1053                 updateLabels(*buffer_);
1054                 break;
1055         case LFUN_OUTLINE_DOWN:
1056                 lyx::toc::outline(lyx::toc::Down, cursor_);
1057                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1058                 updateLabels(*buffer_);
1059                 break;
1060         case LFUN_OUTLINE_IN:
1061                 lyx::toc::outline(lyx::toc::In, cursor_);
1062                 updateLabels(*buffer_);
1063                 break;
1064         case LFUN_OUTLINE_OUT:
1065                 lyx::toc::outline(lyx::toc::Out, cursor_);
1066                 updateLabels(*buffer_);
1067                 break;
1068
1069         case LFUN_NOTE_NEXT:
1070                 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1071                 break;
1072
1073         case LFUN_REFERENCE_NEXT: {
1074                 vector<InsetBase_code> tmp;
1075                 tmp.push_back(InsetBase::LABEL_CODE);
1076                 tmp.push_back(InsetBase::REF_CODE);
1077                 bv_funcs::gotoInset(bv_, tmp, true);
1078                 break;
1079         }
1080
1081         case LFUN_CHANGES_TRACK:
1082                 trackChanges();
1083                 break;
1084
1085         case LFUN_CHANGES_OUTPUT: {
1086                 bool const state = buffer_->params().output_changes;
1087                 buffer_->params().output_changes = !state;
1088                 break;
1089         }
1090
1091         case LFUN_CHANGES_MERGE:
1092                 if (lyx::find::findNextChange(bv_))
1093                         owner_->getDialogs().show("changes");
1094                 break;
1095
1096         case LFUN_ALL_CHANGES_ACCEPT: {
1097                 cursor_.reset(buffer_->inset());
1098 #ifdef WITH_WARNINGS
1099 #warning FIXME changes
1100 #endif
1101                 while (lyx::find::findNextChange(bv_))
1102                         bv_->getLyXText()->acceptChange(cursor_);
1103                 update();
1104                 break;
1105         }
1106
1107         case LFUN_ALL_CHANGES_REJECT: {
1108                 cursor_.reset(buffer_->inset());
1109 #ifdef WITH_WARNINGS
1110 #warning FIXME changes
1111 #endif
1112                 while (lyx::find::findNextChange(bv_))
1113                         bv_->getLyXText()->rejectChange(cursor_);
1114                 break;
1115         }
1116
1117         case LFUN_WORD_FIND:
1118                 lyx::find::find(bv_, cmd);
1119                 break;
1120
1121         case LFUN_WORD_REPLACE:
1122                 lyx::find::replace(bv_, cmd);
1123                 break;
1124
1125         case LFUN_MARK_OFF:
1126                 cur.clearSelection();
1127                 cur.resetAnchor();
1128                 cur.message(N_("Mark off"));
1129                 break;
1130
1131         case LFUN_MARK_ON:
1132                 cur.clearSelection();
1133                 cur.mark() = true;
1134                 cur.resetAnchor();
1135                 cur.message(N_("Mark on"));
1136                 break;
1137
1138         case LFUN_MARK_TOGGLE:
1139                 cur.clearSelection();
1140                 if (cur.mark()) {
1141                         cur.mark() = false;
1142                         cur.message(N_("Mark removed"));
1143                 } else {
1144                         cur.mark() = true;
1145                         cur.message(N_("Mark set"));
1146                 }
1147                 cur.resetAnchor();
1148                 break;
1149
1150         case LFUN_SCREEN_RECENTER:
1151                 center();
1152                 break;
1153
1154         case LFUN_BIBTEX_DATABASE_ADD: {
1155                 LCursor tmpcur = cursor_;
1156                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1157                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1158                                                 InsetBase::BIBTEX_CODE);
1159                 if (inset) {
1160                         if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
1161                                 buffer_->updateBibfilesCache();
1162                 }
1163                 break;
1164         }
1165
1166         case LFUN_BIBTEX_DATABASE_DEL: {
1167                 LCursor tmpcur = cursor_;
1168                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1169                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1170                                                 InsetBase::BIBTEX_CODE);
1171                 if (inset) {
1172                         if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
1173                                 buffer_->updateBibfilesCache();
1174                 }
1175                 break;
1176         }
1177
1178         case LFUN_WORDS_COUNT: {
1179                 DocIterator from, to;
1180                 if (cur.selection()) {
1181                         from = cur.selectionBegin();
1182                         to = cur.selectionEnd();
1183                 } else {
1184                         from = doc_iterator_begin(buffer_->inset());
1185                         to = doc_iterator_end(buffer_->inset());
1186                 }
1187                 int const count = countWords(from, to);
1188                 string message;
1189                 if (count != 1) {
1190                         if (cur.selection())
1191                                 message = bformat(_("%1$d words in selection."),
1192                                           count);
1193                                 else
1194                                         message = bformat(_("%1$d words in document."),
1195                                                           count);
1196                 }
1197                 else {
1198                         if (cur.selection())
1199                                 message = _("One word in selection.");
1200                         else
1201                                 message = _("One word in document.");
1202                 }
1203
1204                 Alert::information(_("Count words"), message);
1205         }
1206                 break;
1207
1208         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1209                 // turn compression on/off
1210                 buffer_->params().compressed = !buffer_->params().compressed;
1211                 break;
1212
1213         case LFUN_NEXT_INSET_TOGGLE: {
1214                 // this is the real function we want to invoke
1215                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1216                 // if there is an inset at cursor, see whether it
1217                 // wants to toggle.
1218                 InsetBase * inset = cur.nextInset();
1219                 if (inset && inset->isActive()) {
1220                         LCursor tmpcur = cur;
1221                         tmpcur.pushLeft(*inset);
1222                         inset->dispatch(tmpcur, tmpcmd);
1223                         if (tmpcur.result().dispatched()) {
1224                                 cur.dispatched();
1225                         }
1226                 }
1227                 // if it did not work, try the underlying inset.
1228                 if (!cur.result().dispatched())
1229                         cur.dispatch(tmpcmd);
1230
1231                 if (cur.result().dispatched()) 
1232                         cur.clearSelection();
1233                 
1234                 break;
1235         }
1236
1237         default:
1238                 return false;
1239         }
1240
1241         return true;
1242 }
1243
1244
1245 void BufferView::Pimpl::updateMetrics(bool singlepar)
1246 {
1247         // Remove old position cache
1248         theCoords.clear();
1249         BufferView & bv = *bv_;
1250         LyXText * const text = bv.text();
1251         lyx::pit_type size = int(text->paragraphs().size());
1252
1253         if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1254                 anchor_ref_ = int(text->paragraphs().size() - 1);
1255                 offset_ref_ = 0;
1256         }
1257
1258         lyx::pit_type const pit = anchor_ref_;
1259         int pit1 = pit;
1260         int pit2 = pit;
1261         size_t const npit = text->paragraphs().size();
1262
1263         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1264         // the (main text, not inset!) paragraph containing the cursor.
1265         // (if this paragraph contains insets etc., rebreaking will
1266         // recursively descend)
1267         if (!singlepar || pit == cursor_.bottom().pit())
1268                 text->redoParagraph(pit);
1269         int y0 = text->getPar(pit).ascent() - offset_ref_;
1270
1271         // Redo paragraphs above anchor if necessary; again, in Single Par
1272         // mode, only if we encounter the (main text) one having the cursor.
1273         int y1 = y0;
1274         while (y1 > 0 && pit1 > 0) {
1275                 y1 -= text->getPar(pit1).ascent();
1276                 --pit1;
1277                 if (!singlepar || pit1 == cursor_.bottom().pit())
1278                         text->redoParagraph(pit1);
1279                 y1 -= text->getPar(pit1).descent();
1280         }
1281
1282
1283         // Take care of ascent of first line
1284         y1 -= text->getPar(pit1).ascent();
1285
1286         // Normalize anchor for next time
1287         anchor_ref_ = pit1;
1288         offset_ref_ = -y1;
1289
1290         // Grey at the beginning is ugly
1291         if (pit1 == 0 && y1 > 0) {
1292                 y0 -= y1;
1293                 y1 = 0;
1294                 anchor_ref_ = 0;
1295         }
1296
1297         // Redo paragraphs below the anchor if necessary. Single par mode:
1298         // only the one containing the cursor if encountered.
1299         int y2 = y0;
1300         while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1301                 y2 += text->getPar(pit2).descent();
1302                 ++pit2;
1303                 if (!singlepar || pit2 == cursor_.bottom().pit())
1304                         text->redoParagraph(pit2);
1305                 y2 += text->getPar(pit2).ascent();
1306         }
1307
1308         // Take care of descent of last line
1309         y2 += text->getPar(pit2).descent();
1310
1311         // The coordinates of all these paragraphs are correct, cache them
1312         int y = y1;
1313         CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1314         for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1315                 Paragraph const & par = text->getPar(pit);
1316                 y += par.ascent();
1317                 parPos[pit] = Point(0, y);
1318                 if (singlepar && pit == cursor_.bottom().pit()) {
1319                         // In Single Paragraph mode, collect here the
1320                         // y1 and y2 of the (one) paragraph the cursor is in
1321                         y1 = y - par.ascent();
1322                         y2 = y + par.descent();
1323                 }
1324                 y += par.descent();
1325         }
1326
1327         if (singlepar) {
1328                 // collect cursor paragraph iter bounds
1329                 pit1 = cursor_.bottom().pit();
1330                 pit2 = cursor_.bottom().pit();
1331         }
1332
1333         lyxerr[Debug::DEBUG]
1334                 << BOOST_CURRENT_FUNCTION
1335                 << " y1: " << y1
1336                 << " y2: " << y2
1337                 << " pit1: " << pit1
1338                 << " pit2: " << pit2
1339                 << " npit: " << npit
1340                 << " singlepar: " << singlepar
1341                 << "size: " << size
1342                 << endl;
1343
1344         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1345 }