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