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