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