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