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