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