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