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