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