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