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