]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
980128bb1fa387508b8e2532952be76b26261a41
[lyx.git] / src / BufferView_pimpl.C
1 /**
2  * \file BufferView_pimpl.C
3  * Copyright 2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author Lars Gullik Bjønnes
7  * \author various
8  */
9
10 #include <config.h>
11
12 #include "BufferView_pimpl.h"
13 #include "bufferlist.h"
14 #include "buffer.h"
15 #include "buffer_funcs.h"
16 #include "bufferview_funcs.h"
17 #include "lfuns.h"
18 #include "debug.h"
19 #include "factory.h"
20 #include "FloatList.h"
21 #include "funcrequest.h"
22 #include "gettext.h"
23 #include "intl.h"
24 #include "iterators.h"
25 #include "Lsstream.h"
26 #include "lyx_cb.h" // added for Dispatch functions
27 #include "lyx_main.h"
28 #include "lyxfind.h"
29 #include "lyxfunc.h"
30 #include "lyxtext.h"
31 #include "lyxrc.h"
32 #include "lyxrow.h"
33 #include "lastfiles.h"
34 #include "paragraph.h"
35 #include "ParagraphParameters.h"
36 #include "TextCache.h"
37 #include "undo_funcs.h"
38
39 #include "insets/insetfloatlist.h"
40 #include "insets/insetgraphics.h"
41 #include "insets/insetinclude.h"
42 #include "insets/insetref.h"
43 #include "insets/insettext.h"
44
45 #include "frontends/Alert.h"
46 #include "frontends/Dialogs.h"
47 #include "frontends/FileDialog.h"
48 #include "frontends/LyXView.h"
49 #include "frontends/LyXScreenFactory.h"
50 #include "frontends/mouse_state.h"
51 #include "frontends/screen.h"
52 #include "frontends/WorkArea.h"
53 #include "frontends/WorkAreaFactory.h"
54
55 #include "mathed/formulabase.h"
56
57 #include "graphics/Previews.h"
58
59 #include "support/LAssert.h"
60 #include "support/tostr.h"
61 #include "support/filetools.h"
62 #include "support/path_defines.h"
63
64 #include <boost/bind.hpp>
65 #include <boost/signals/connection.hpp>
66
67 #include <unistd.h>
68 #include <sys/wait.h>
69
70
71 using std::vector;
72 using std::find_if;
73 using std::find;
74 using std::pair;
75 using std::endl;
76 using std::make_pair;
77 using std::min;
78
79 using lyx::pos_type;
80 using namespace lyx::support;
81 using namespace bv_funcs;
82
83 extern BufferList bufferlist;
84
85
86 namespace {
87
88 unsigned int const saved_positions_num = 20;
89
90 // All the below connection objects are needed because of a bug in some
91 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
92 // to these connections we avoid a segfault upon startup, and also at exit.
93 // (Lgb)
94
95 boost::signals::connection dispatchcon;
96 boost::signals::connection timecon;
97 boost::signals::connection doccon;
98 boost::signals::connection resizecon;
99 boost::signals::connection kpresscon;
100 boost::signals::connection selectioncon;
101 boost::signals::connection lostcon;
102
103
104 } // anon namespace
105
106
107 BufferView::Pimpl::Pimpl(BufferView * bv, LyXView * owner,
108              int xpos, int ypos, int width, int height)
109         : bv_(bv), owner_(owner), buffer_(0), cursor_timeout(400),
110           using_xterm_cursor(false)
111 {
112         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
113         screen_.reset(LyXScreenFactory::create(workarea()));
114
115         // Setup the signals
116         doccon = workarea().scrollDocView
117                 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
118         resizecon = workarea().workAreaResize
119                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
120         dispatchcon = workarea().dispatch
121                 .connect(boost::bind(&BufferView::Pimpl::workAreaDispatch, this, _1));
122         kpresscon = workarea().workAreaKeyPress
123                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
124         selectioncon = workarea().selectionRequested
125                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
126         lostcon = workarea().selectionLost
127                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
128
129         timecon = cursor_timeout.timeout
130                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
131         cursor_timeout.start();
132         saved_positions.resize(saved_positions_num);
133 }
134
135
136 void BufferView::Pimpl::addError(ErrorItem const & ei)
137 {
138         errorlist_.push_back(ei);
139 }
140
141
142 void BufferView::Pimpl::showReadonly(bool)
143 {
144         owner_->updateWindowTitle();
145         owner_->getDialogs().updateBufferDependent(false);
146 }
147
148
149 void BufferView::Pimpl::connectBuffer(Buffer & buf)
150 {
151         if (errorConnection_.connected())
152                 disconnectBuffer();
153
154         errorConnection_ = buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
155         messageConnection_ = buf.message.connect(boost::bind(&LyXView::message, owner_, _1));
156         busyConnection_ = buf.busy.connect(boost::bind(&LyXView::busy, owner_, _1));
157         titleConnection_ = buf.updateTitles.connect(boost::bind(&LyXView::updateWindowTitle, owner_));
158         timerConnection_ = buf.resetAutosaveTimers.connect(boost::bind(&LyXView::resetAutosaveTimer, owner_));
159         readonlyConnection_ = buf.readonly.connect(boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
160         closingConnection_ = buf.closing.connect(boost::bind(&BufferView::Pimpl::buffer, this, (Buffer *)0));
161 }
162
163
164 void BufferView::Pimpl::disconnectBuffer()
165 {
166         errorConnection_.disconnect();
167         messageConnection_.disconnect();
168         busyConnection_.disconnect();
169         titleConnection_.disconnect();
170         timerConnection_.disconnect();
171         readonlyConnection_.disconnect();
172         closingConnection_.disconnect();
173 }
174
175
176 bool BufferView::Pimpl::newFile(string const & filename,
177                                 string const & tname,
178                                 bool isNamed)
179 {
180         Buffer * b = ::newFile(filename, tname, isNamed);
181         buffer(b);
182         return true;
183 }
184
185
186 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
187 {
188         // get absolute path of file and add ".lyx" to the filename if
189         // necessary
190         string s = FileSearch(string(), filename, "lyx");
191         
192         bool const found = !s.empty();
193
194         if (!found) 
195                 s = filename;
196
197         // file already open?
198         if (bufferlist.exists(s)) {
199                 string const file = MakeDisplayPath(s, 20);
200                 string text = bformat(_("The document %1$s is already "
201                                         "loaded.\n\nDo you want to revert "
202                                         "to the saved version?"), file);
203                 int const ret = Alert::prompt(_("Revert to saved document?"),
204                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
205
206                 if (ret != 0) {
207                         buffer(bufferlist.getBuffer(s));
208                         return true;
209                 } else {
210                         // FIXME: should be LFUN_REVERT
211                         if (!bufferlist.close(bufferlist.getBuffer(s), false))
212                                 return false;
213                         // Fall through to new load. (Asger)
214                 }
215         }
216
217         Buffer * b;
218
219         if (found) {
220                 b = bufferlist.newBuffer(s);
221                 connectBuffer(*b);
222                 if (!::loadLyXFile(b, s)) {
223                         bufferlist.release(b);
224                         return false;
225                 }
226         } else {
227                 string text = bformat(_("The document %1$s does not yet "
228                                         "exist.\n\nDo you want to create "
229                                         "a new document?"), s);
230                 int const ret = Alert::prompt(_("Create new document?"),
231                          text, 0, 1, _("&Create"), _("Cancel"));
232
233                 if (ret == 0)
234                         b = ::newFile(s, string(), true);
235                 else
236                         return false;
237         }
238
239         buffer(b);
240         bv_->showErrorList(_("Parse"));
241
242         if (tolastfiles)
243                 lastfiles->newFile(b->fileName());
244
245         return true;
246 }
247
248
249 WorkArea & BufferView::Pimpl::workarea() const
250 {
251         return *workarea_.get();
252 }
253
254
255 LyXScreen & BufferView::Pimpl::screen() const
256 {
257         return *screen_.get();
258 }
259
260
261 Painter & BufferView::Pimpl::painter() const
262 {
263         return workarea().getPainter();
264 }
265
266
267 void BufferView::Pimpl::buffer(Buffer * b)
268 {
269         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
270                             << b << ')' << endl;
271         if (buffer_) {
272                 disconnectBuffer();
273                 // Put the old text into the TextCache, but
274                 // only if the buffer is still loaded.
275                 // Also set the owner of the test to 0
276                 //              bv_->text->owner(0);
277                 textcache.add(buffer_, workarea().workWidth(), bv_->text);
278                 if (lyxerr.debugging())
279                         textcache.show(lyxerr, "BufferView::buffer");
280
281                 bv_->text = 0;
282         }
283
284         // set current buffer
285         buffer_ = b;
286
287         // if we're quitting lyx, don't bother updating stuff
288         if (quitting)
289                 return;
290
291         // if we are closing the buffer, use the first buffer as current
292         if (!buffer_)
293                 buffer_ = bufferlist.first();
294
295         if (buffer_) {
296                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
297                 connectBuffer(*buffer_);
298
299                 // If we don't have a text object for this, we make one
300                 if (bv_->text == 0)
301                         resizeCurrentBuffer();
302
303                 // FIXME: needed when ?
304                 bv_->text->top_y(screen().topCursorVisible(bv_->text));
305
306                 // Buffer-dependent dialogs should be updated or
307                 // hidden. This should go here because some dialogs (eg ToC)
308                 // require bv_->text.
309                 owner_->getDialogs().updateBufferDependent(true);
310         } else {
311                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
312                 owner_->getDialogs().hideBufferDependent();
313
314                 // Also remove all remaining text's from the testcache.
315                 // (there should not be any!) (if there is any it is a
316                 // bug!)
317                 if (lyxerr.debugging())
318                         textcache.show(lyxerr, "buffer delete all");
319                 textcache.clear();
320         }
321
322         repaint();
323         updateScrollbar();
324         owner_->updateMenubar();
325         owner_->updateToolbar();
326         owner_->updateLayoutChoice();
327         owner_->updateWindowTitle();
328
329         if (buffer_) {
330                 // Don't forget to update the Layout
331                 string const layoutname =
332                         bv_->text->cursor.par()->layout()->name();
333                 owner_->setLayout(layoutname);
334         }
335
336         if (lyx::graphics::Previews::activated() && buffer_)
337                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
338 }
339
340
341 bool BufferView::Pimpl::fitCursor()
342 {
343         bool ret;
344
345         if (bv_->theLockingInset()) {
346                 bv_->theLockingInset()->fitInsetCursor(bv_);
347                 ret = true;
348         } else {
349                 ret = screen().fitCursor(bv_->text, bv_);
350         }
351
352         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
353
354         // We need to always update, in case we did a
355         // paste and we stayed anchored to a row, but
356         // the actual height of the doc changed ...
357         updateScrollbar();
358         return ret;
359 }
360
361
362 void BufferView::Pimpl::redoCurrentBuffer()
363 {
364         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
365         if (buffer_ && bv_->text) {
366                 resizeCurrentBuffer();
367                 updateScrollbar();
368                 owner_->updateLayoutChoice();
369                 repaint();
370         }
371 }
372
373
374 int BufferView::Pimpl::resizeCurrentBuffer()
375 {
376         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
377
378         ParagraphList::iterator par;
379         ParagraphList::iterator selstartpar;
380         ParagraphList::iterator selendpar;
381         UpdatableInset * the_locking_inset = 0;
382
383         pos_type pos = 0;
384         pos_type selstartpos = 0;
385         pos_type selendpos = 0;
386         bool selection = false;
387         bool mark_set  = false;
388
389         owner_->busy(true);
390
391         owner_->message(_("Formatting document..."));
392
393         if (bv_->text) {
394                 par = bv_->text->cursor.par();
395                 pos = bv_->text->cursor.pos();
396                 selstartpar = bv_->text->selection.start.par();
397                 selstartpos = bv_->text->selection.start.pos();
398                 selendpar = bv_->text->selection.end.par();
399                 selendpos = bv_->text->selection.end.pos();
400                 selection = bv_->text->selection.set();
401                 mark_set = bv_->text->selection.mark();
402                 the_locking_inset = bv_->theLockingInset();
403                 resizeInsets(bv_);
404                 bv_->text->fullRebreak();
405                 update();
406         } else {
407                 lyxerr << "text not available!\n";
408                 // See if we have a text in TextCache that fits
409                 // the new buffer_ with the correct width.
410                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
411                 if (bv_->text) {
412                         lyxerr << "text in cache!\n";
413                         if (lyxerr.debugging()) {
414                                 lyxerr << "Found a LyXText that fits:\n";
415                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
416                         }
417                         // Set the owner of the newly found text
418                         //      bv_->text->owner(bv_);
419                         if (lyxerr.debugging())
420                                 textcache.show(lyxerr, "resizeCurrentBuffer");
421
422                         resizeInsets(bv_);
423                 } else {
424                         lyxerr << "no text in cache!\n";
425                         bv_->text = new LyXText(bv_);
426                         resizeInsets(bv_);
427                         bv_->text->init(bv_);
428                 }
429
430                 par = bv_->text->ownerParagraphs().end();
431                 selstartpar = bv_->text->ownerParagraphs().end();
432                 selendpar = bv_->text->ownerParagraphs().end();
433         }
434
435         if (par != bv_->text->ownerParagraphs().end()) {
436                 bv_->text->selection.set(true);
437                 // At this point just to avoid the Delete-Empty-Paragraph-
438                 // Mechanism when setting the cursor.
439                 bv_->text->selection.mark(mark_set);
440                 if (selection) {
441                         bv_->text->setCursor(selstartpar, selstartpos);
442                         bv_->text->selection.cursor = bv_->text->cursor;
443                         bv_->text->setCursor(selendpar, selendpos);
444                         bv_->text->setSelection();
445                         bv_->text->setCursor(par, pos);
446                 } else {
447                         bv_->text->setCursor(par, pos);
448                         bv_->text->selection.cursor = bv_->text->cursor;
449                         bv_->text->selection.set(false);
450                 }
451                 // remake the inset locking
452                 bv_->theLockingInset(the_locking_inset);
453         }
454
455         bv_->text->top_y(screen().topCursorVisible(bv_->text));
456
457         switchKeyMap();
458         owner_->busy(false);
459
460         // reset the "Formatting..." message
461         owner_->clearMessage();
462
463         updateScrollbar();
464
465         return 0;
466 }
467
468
469 void BufferView::Pimpl::repaint()
470 {
471         // Regenerate the screen.
472         screen().redraw(bv_, bv_->text);
473 }
474
475
476 void BufferView::Pimpl::updateScrollbar()
477 {
478         if (!bv_->text) {
479                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
480                 workarea().setScrollbarParams(0, 0, 0);
481                 return;
482         }
483
484         LyXText const & t = *bv_->text;
485
486         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", top_y() "
487                 << t.top_y() << ", default height " << defaultRowHeight() << endl;
488
489         workarea().setScrollbarParams(t.height, t.top_y(), defaultRowHeight());
490 }
491
492
493 void BufferView::Pimpl::scrollDocView(int value)
494 {
495         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
496
497         if (!buffer_)
498                 return;
499
500         screen().hideCursor();
501
502         screen().draw(bv_->text, bv_, value);
503
504         if (!lyxrc.cursor_follows_scrollbar)
505                 return;
506
507         LyXText * vbt = bv_->text;
508
509         int const height = defaultRowHeight();
510         int const first = static_cast<int>((bv_->text->top_y() + height));
511         int const last = static_cast<int>((bv_->text->top_y() + workarea().workHeight() - height));
512
513         if (vbt->cursor.y() < first)
514                 vbt->setCursorFromCoordinates(0, first);
515         else if (vbt->cursor.y() > last)
516                 vbt->setCursorFromCoordinates(0, last);
517
518         owner_->updateLayoutChoice();
519 }
520
521
522 void BufferView::Pimpl::scroll(int lines)
523 {
524         if (!buffer_) {
525                 return;
526         }
527
528         LyXText const * t = bv_->text;
529         int const line_height = defaultRowHeight();
530
531         // The new absolute coordinate
532         int new_top_y = t->top_y() + lines * line_height;
533
534         // Restrict to a valid value
535         new_top_y = std::min(t->height - 4 * line_height, new_top_y);
536         new_top_y = std::max(0, new_top_y);
537
538         scrollDocView(new_top_y);
539
540         // Update the scrollbar.
541         workarea().setScrollbarParams(t->height, t->top_y(), defaultRowHeight());
542 }
543
544
545 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
546                                          key_modifier::state state)
547 {
548         bv_->owner()->getLyXFunc().processKeySym(key, state);
549
550         /* This is perhaps a bit of a hack. When we move
551          * around, or type, it's nice to be able to see
552          * the cursor immediately after the keypress. So
553          * we reset the toggle timeout and force the visibility
554          * of the cursor. Note we cannot do this inside
555          * dispatch() itself, because that's called recursively.
556          */
557         if (available()) {
558                 cursor_timeout.restart();
559                 screen().showCursor(*bv_);
560         }
561 }
562
563
564 void BufferView::Pimpl::selectionRequested()
565 {
566         static string sel;
567
568         if (!available())
569                 return;
570
571         LyXText * text = bv_->getLyXText();
572
573         if (text->selection.set() &&
574                 (!bv_->text->xsel_cache.set() ||
575                  text->selection.start != bv_->text->xsel_cache.start ||
576                  text->selection.end != bv_->text->xsel_cache.end))
577         {
578                 bv_->text->xsel_cache = text->selection;
579                 sel = text->selectionAsString(bv_->buffer(), false);
580         } else if (!text->selection.set()) {
581                 sel = string();
582                 bv_->text->xsel_cache.set(false);
583         }
584         if (!sel.empty()) {
585                 workarea().putClipboard(sel);
586         }
587 }
588
589
590 void BufferView::Pimpl::selectionLost()
591 {
592         if (available()) {
593                 screen().hideCursor();
594                 toggleSelection();
595                 bv_->getLyXText()->clearSelection();
596                 bv_->text->xsel_cache.set(false);
597         }
598 }
599
600
601 void BufferView::Pimpl::workAreaResize()
602 {
603         static int work_area_width;
604         static int work_area_height;
605
606         bool const widthChange = workarea().workWidth() != work_area_width;
607         bool const heightChange = workarea().workHeight() != work_area_height;
608
609         // update from work area
610         work_area_width = workarea().workWidth();
611         work_area_height = workarea().workHeight();
612
613         if (buffer_ != 0) {
614                 if (widthChange) {
615                         // The visible LyXView need a resize
616                         resizeCurrentBuffer();
617
618                         // Remove all texts from the textcache
619                         // This is not _really_ what we want to do. What
620                         // we really want to do is to delete in textcache
621                         // that does not have a BufferView with matching
622                         // width, but as long as we have only one BufferView
623                         // deleting all gives the same result.
624                         if (lyxerr.debugging())
625                                 textcache.show(lyxerr, "Expose delete all");
626                         textcache.clear();
627                         // FIXME: this is already done in resizeCurrentBuffer() ??
628                         resizeInsets(bv_);
629                 } else if (heightChange) {
630                         // fitCursor() ensures we don't jump back
631                         // to the start of the document on vertical
632                         // resize
633                         fitCursor();
634                 }
635         }
636
637         if (widthChange || heightChange) {
638                 repaint();
639         }
640
641         // always make sure that the scrollbar is sane.
642         updateScrollbar();
643         owner_->updateLayoutChoice();
644         return;
645 }
646
647
648 void BufferView::Pimpl::update()
649 {
650         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
651                 screen().update(*bv_);
652                 bv_->text->clearPaint();
653         }
654 }
655
656
657 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
658 {
659         if (!text->selection.set() && (f & SELECT)) {
660                 text->selection.cursor = text->cursor;
661         }
662
663         text->partialRebreak();
664
665         if (text->inset_owner) {
666                 text->inset_owner->setUpdateStatus(InsetText::NONE);
667                 updateInset(text->inset_owner);
668         } else {
669                 update();
670         }
671 }
672
673
674 void BufferView::Pimpl::update(BufferView::UpdateCodes f)
675 {
676         LyXText * text = bv_->text;
677
678         if (!text->selection.set() && (f & SELECT)) {
679                 text->selection.cursor = text->cursor;
680         }
681
682         text->partialRebreak();
683
684         if (text->inset_owner) {
685                 text->inset_owner->setUpdateStatus(InsetText::NONE);
686                 updateInset(text->inset_owner);
687         } else {
688                 update();
689         }
690 }
691
692
693 // Callback for cursor timer
694 void BufferView::Pimpl::cursorToggle()
695 {
696         if (!buffer_) {
697                 cursor_timeout.restart();
698                 return;
699         }
700
701         screen().toggleCursor(*bv_);
702
703         cursor_timeout.restart();
704 }
705
706
707 bool BufferView::Pimpl::available() const
708 {
709         if (buffer_ && bv_->text)
710                 return true;
711         return false;
712 }
713
714
715 Change const BufferView::Pimpl::getCurrentChange()
716 {
717         if (!bv_->buffer()->params.tracking_changes)
718                 return Change(Change::UNCHANGED);
719
720         LyXText * t(bv_->getLyXText());
721
722         if (!t->selection.set())
723                 return Change(Change::UNCHANGED);
724
725         LyXCursor const & cur(t->selection.start);
726         return cur.par()->lookupChangeFull(cur.pos());
727 }
728
729
730 void BufferView::Pimpl::beforeChange(LyXText * text)
731 {
732         toggleSelection();
733         text->clearSelection();
734 }
735
736
737 void BufferView::Pimpl::savePosition(unsigned int i)
738 {
739         if (i >= saved_positions_num)
740                 return;
741         saved_positions[i] = Position(buffer_->fileName(),
742                                       bv_->text->cursor.par()->id(),
743                                       bv_->text->cursor.pos());
744         if (i > 0)
745                 owner_->message(bformat(_("Saved bookmark %1$s"), tostr(i)));
746 }
747
748
749 void BufferView::Pimpl::restorePosition(unsigned int i)
750 {
751         if (i >= saved_positions_num)
752                 return;
753
754         string const fname = saved_positions[i].filename;
755
756         beforeChange(bv_->text);
757
758         if (fname != buffer_->fileName()) {
759                 Buffer * b;
760                 if (bufferlist.exists(fname))
761                         b = bufferlist.getBuffer(fname);
762                 else {
763                         b = bufferlist.newBuffer(fname);
764                         ::loadLyXFile(b, fname); // don't ask, just load it
765                 }
766                 if (b != 0)
767                         buffer(b);
768         }
769
770         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
771         if (par == buffer_->par_iterator_end())
772                 return;
773
774         bv_->text->setCursor(par.pit(),
775                              min(par->size(), saved_positions[i].par_pos));
776
777         update(BufferView::SELECT);
778         if (i > 0)
779                 owner_->message(bformat(_("Moved to bookmark %1$s"), tostr(i)));
780 }
781
782
783 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
784 {
785         if (i >= saved_positions_num)
786                 return false;
787
788         return !saved_positions[i].filename.empty();
789 }
790
791
792 void BufferView::Pimpl::switchKeyMap()
793 {
794         if (!lyxrc.rtl_support)
795                 return;
796
797         LyXText * text = bv_->getLyXText();
798         if (text->real_current_font.isRightToLeft()
799             && !(bv_->theLockingInset()
800                  && bv_->theLockingInset()->lyxCode() == InsetOld::ERT_CODE))
801         {
802                 if (owner_->getIntl().keymap == Intl::PRIMARY)
803                         owner_->getIntl().KeyMapSec();
804         } else {
805                 if (owner_->getIntl().keymap == Intl::SECONDARY)
806                         owner_->getIntl().KeyMapPrim();
807         }
808 }
809
810
811 void BufferView::Pimpl::insetUnlock()
812 {
813         if (bv_->theLockingInset()) {
814                 bv_->theLockingInset()->insetUnlock(bv_);
815                 bv_->theLockingInset(0);
816                 finishUndo();
817         }
818 }
819
820
821 void BufferView::Pimpl::toggleSelection(bool b)
822 {
823         screen().toggleSelection(bv_->text, bv_, b);
824 }
825
826
827 void BufferView::Pimpl::center()
828 {
829         LyXText * t = bv_->text;
830
831         beforeChange(t);
832         int const half_height = workarea().workHeight() / 2;
833         int new_y = 0;
834
835         if (t->cursor.y() > half_height) {
836                 new_y = t->cursor.y() - half_height;
837         }
838
839         // FIXME: look at this comment again ...
840
841         // FIXME: can we do this w/o calling screen directly ?
842         // This updates top_y() but means the fitCursor() call
843         // from the update(FITCUR) doesn't realise that we might
844         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
845         // the scrollbar to be updated as it should, so we have
846         // to do it manually. Any operation that does a center()
847         // and also might have moved top_y() must make sure to call
848         // updateScrollbar() currently. Never mind that this is a
849         // pretty obfuscated way of updating t->top_y()
850         screen().draw(t, bv_, new_y);
851
852         update(BufferView::SELECT);
853 }
854
855
856 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
857 {
858         workarea().putClipboard(stuff);
859 }
860
861
862 /*
863  * Dispatch functions for actions which can be valid for BufferView->text
864  * and/or InsetText->text!!!
865  */
866
867
868 InsetOld * BufferView::Pimpl::getInsetByCode(InsetOld::Code code)
869 {
870 #if 0
871         LyXCursor cursor = bv_->getLyXText()->cursor;
872         Buffer::inset_iterator it =
873                 find_if(Buffer::inset_iterator(
874                         cursor.par(), cursor.pos()),
875                         buffer_->inset_iterator_end(),
876                         lyx::compare_memfun(&Inset::lyxCode, code));
877         return it != buffer_->inset_iterator_end() ? (*it) : 0;
878 #else
879         // Ok, this is a little bit too brute force but it
880         // should work for now. Better infrastructure is comming. (Lgb)
881
882         Buffer * b = bv_->buffer();
883         LyXCursor cursor = bv_->getLyXText()->cursor;
884
885         Buffer::inset_iterator beg = b->inset_iterator_begin();
886         Buffer::inset_iterator end = b->inset_iterator_end();
887
888         bool cursor_par_seen = false;
889
890         for (; beg != end; ++beg) {
891                 if (beg.getPar() == cursor.par()) {
892                         cursor_par_seen = true;
893                 }
894                 if (cursor_par_seen) {
895                         if (beg.getPar() == cursor.par()
896                             && beg.getPos() >= cursor.pos()) {
897                                 break;
898                         } else if (beg.getPar() != cursor.par()) {
899                                 break;
900                         }
901                 }
902
903         }
904         if (beg != end) {
905                 // Now find the first inset that matches code.
906                 for (; beg != end; ++beg) {
907                         if (beg->lyxCode() == code) {
908                                 return &(*beg);
909                         }
910                 }
911         }
912         return 0;
913 #endif
914 }
915
916
917 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
918 {
919         string filename = filen;
920
921         if (filename.empty()) {
922                 // Launch a file browser
923                 string initpath = lyxrc.document_path;
924
925                 if (available()) {
926                         string const trypath = owner_->buffer()->filePath();
927                         // If directory is writeable, use this as default.
928                         if (IsDirWriteable(trypath))
929                                 initpath = trypath;
930                 }
931
932                 FileDialog fileDlg(_("Select LyX document to insert"),
933                         LFUN_FILE_INSERT,
934                         make_pair(string(_("Documents|#o#O")),
935                                   string(lyxrc.document_path)),
936                         make_pair(string(_("Examples|#E#e")),
937                                   string(AddPath(system_lyxdir(), "examples"))));
938
939                 FileDialog::Result result =
940                         fileDlg.open(initpath,
941                                        _("*.lyx| LyX Documents (*.lyx)"));
942
943                 if (result.first == FileDialog::Later)
944                         return;
945
946                 filename = result.second;
947
948                 // check selected filename
949                 if (filename.empty()) {
950                         owner_->message(_("Canceled."));
951                         return;
952                 }
953         }
954
955         // get absolute path of file and add ".lyx" to the filename if
956         // necessary
957         filename = FileSearch(string(), filename, "lyx");
958
959         string const disp_fn = MakeDisplayPath(filename);
960         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
961         if (bv_->insertLyXFile(filename))
962                 owner_->message(bformat(_("Document %1$s inserted."),
963                                         disp_fn));
964         else
965                 owner_->message(bformat(_("Could not insert document %1$s"),
966                                         disp_fn));
967 }
968
969
970 void BufferView::Pimpl::trackChanges()
971 {
972         Buffer * buf(bv_->buffer());
973         bool const tracking(buf->params.tracking_changes);
974
975         if (!tracking) {
976                 ParIterator const end = buf->par_iterator_end();
977                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
978                         it->trackChanges();
979                 buf->params.tracking_changes = true;
980
981                 // we cannot allow undos beyond the freeze point
982                 buf->undostack.clear();
983         } else {
984                 update(BufferView::SELECT);
985                 bv_->text->setCursor(buf->paragraphs.begin(), 0);
986 #warning changes FIXME
987                 //moveCursorUpdate(false);
988
989                 bool found = lyx::find::findNextChange(bv_);
990                 if (found) {
991                         owner_->getDialogs().show("changes");
992                         return;
993                 }
994
995                 ParIterator const end = buf->par_iterator_end();
996                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
997                         it->untrackChanges();
998                 buf->params.tracking_changes = false;
999         }
1000
1001         buf->redostack.clear();
1002 }
1003
1004
1005 // Doesn't go through lyxfunc, so we need to update the
1006 // layout choice etc. ourselves
1007 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & ev_in)
1008 {
1009         // e.g. Qt mouse press when no buffer
1010         if (!available())
1011                 return false;
1012
1013         screen().hideCursor();
1014
1015         // Make sure that the cached BufferView is correct.
1016         FuncRequest ev = ev_in;
1017         ev.setView(bv_);
1018
1019         bool const res = dispatch(ev);
1020
1021         // see workAreaKeyPress
1022         cursor_timeout.restart();
1023         screen().showCursor(*bv_);
1024
1025         // FIXME: we should skip these when selecting
1026         bv_->owner()->updateLayoutChoice();
1027         bv_->owner()->updateToolbar();
1028         bv_->fitCursor();
1029
1030         // slight hack: this is only called currently when
1031         // we clicked somewhere, so we force through the display
1032         // of the new status here.
1033         bv_->owner()->clearMessage();
1034
1035         return res;
1036 }
1037
1038
1039 bool BufferView::Pimpl::dispatch(FuncRequest const & ev_in)
1040 {
1041         // Make sure that the cached BufferView is correct.
1042         FuncRequest ev = ev_in;
1043         ev.setView(bv_);
1044
1045         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch:"
1046                 << " action[" << ev.action << ']'
1047                 << " arg[" << ev.argument << ']'
1048                 << " x[" << ev.x << ']'
1049                 << " y[" << ev.y << ']'
1050                 << " button[" << ev.button() << ']'
1051                 << endl;
1052
1053         LyXTextClass const & tclass = buffer_->params.getLyXTextClass();
1054
1055         switch (ev.action) {
1056
1057         case LFUN_SCROLL_INSET:
1058                 // this is not handled here as this function is only active
1059                 // if we have a locking_inset and that one is (or contains)
1060                 // a tabular-inset
1061                 break;
1062
1063         case LFUN_FILE_INSERT:
1064                 MenuInsertLyXFile(ev.argument);
1065                 break;
1066
1067         case LFUN_FILE_INSERT_ASCII_PARA:
1068                 InsertAsciiFile(bv_, ev.argument, true);
1069                 break;
1070
1071         case LFUN_FILE_INSERT_ASCII:
1072                 InsertAsciiFile(bv_, ev.argument, false);
1073                 break;
1074
1075         case LFUN_LANGUAGE:
1076                 lang(bv_, ev.argument);
1077                 switchKeyMap();
1078                 owner_->view_state_changed();
1079                 break;
1080
1081         case LFUN_EMPH:
1082                 emph(bv_);
1083                 owner_->view_state_changed();
1084                 break;
1085
1086         case LFUN_BOLD:
1087                 bold(bv_);
1088                 owner_->view_state_changed();
1089                 break;
1090
1091         case LFUN_NOUN:
1092                 noun(bv_);
1093                 owner_->view_state_changed();
1094                 break;
1095
1096         case LFUN_CODE:
1097                 code(bv_);
1098                 owner_->view_state_changed();
1099                 break;
1100
1101         case LFUN_SANS:
1102                 sans(bv_);
1103                 owner_->view_state_changed();
1104                 break;
1105
1106         case LFUN_ROMAN:
1107                 roman(bv_);
1108                 owner_->view_state_changed();
1109                 break;
1110
1111         case LFUN_DEFAULT:
1112                 styleReset(bv_);
1113                 owner_->view_state_changed();
1114                 break;
1115
1116         case LFUN_UNDERLINE:
1117                 underline(bv_);
1118                 owner_->view_state_changed();
1119                 break;
1120
1121         case LFUN_FONT_SIZE:
1122                 fontSize(bv_, ev.argument);
1123                 owner_->view_state_changed();
1124                 break;
1125
1126         case LFUN_FONT_STATE:
1127                 owner_->getLyXFunc().setMessage(currentState(bv_));
1128                 break;
1129
1130         case LFUN_INSERT_LABEL: {
1131                 // Try and generate a valid label
1132                 string const contents = ev.argument.empty() ?
1133                         getPossibleLabel(*bv_) : ev.argument;
1134                 InsetCommandParams icp("label", contents);
1135                 string data = InsetCommandMailer::params2string("label", icp);
1136                 owner_->getDialogs().show("label", data, 0);
1137         }
1138         break;
1139
1140         case LFUN_BOOKMARK_SAVE:
1141                 savePosition(strToUnsignedInt(ev.argument));
1142                 break;
1143
1144         case LFUN_BOOKMARK_GOTO:
1145                 restorePosition(strToUnsignedInt(ev.argument));
1146                 break;
1147
1148         case LFUN_REF_GOTO: {
1149                 string label = ev.argument;
1150                 if (label.empty()) {
1151                         InsetRef * inset =
1152                                 static_cast<InsetRef*>(getInsetByCode(InsetOld::REF_CODE));
1153                         if (inset) {
1154                                 label = inset->getContents();
1155                                 savePosition(0);
1156                         }
1157                 }
1158
1159                 if (!label.empty())
1160                         bv_->gotoLabel(label);
1161         }
1162         break;
1163
1164         // --- accented characters ---------------------------
1165
1166         case LFUN_UMLAUT:
1167         case LFUN_CIRCUMFLEX:
1168         case LFUN_GRAVE:
1169         case LFUN_ACUTE:
1170         case LFUN_TILDE:
1171         case LFUN_CEDILLA:
1172         case LFUN_MACRON:
1173         case LFUN_DOT:
1174         case LFUN_UNDERDOT:
1175         case LFUN_UNDERBAR:
1176         case LFUN_CARON:
1177         case LFUN_SPECIAL_CARON:
1178         case LFUN_BREVE:
1179         case LFUN_TIE:
1180         case LFUN_HUNG_UMLAUT:
1181         case LFUN_CIRCLE:
1182         case LFUN_OGONEK:
1183                 if (ev.argument.empty()) {
1184                         // As always...
1185                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1186                 } else {
1187                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1188                         owner_->getIntl().getTransManager()
1189                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
1190                         update(bv_->getLyXText(), BufferView::SELECT);
1191                 }
1192                 break;
1193
1194         case LFUN_MATH_MACRO:
1195         case LFUN_MATH_DELIM:
1196         case LFUN_INSERT_MATRIX:
1197         case LFUN_INSERT_MATH:
1198         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
1199         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
1200         case LFUN_MATH_MODE:             // Open or create an inlined math inset
1201                 mathDispatch(ev);
1202                 break;
1203
1204         case LFUN_INSET_APPLY: {
1205                 string const name = ev.getArg(0);
1206
1207                 InsetBase * inset = owner_->getDialogs().getOpenInset(name);
1208                 if (inset) {
1209                         // This works both for 'original' and 'mathed' insets.
1210                         // Note that the localDispatch performs updateInset
1211                         // also.
1212                         FuncRequest fr(bv_, LFUN_INSET_MODIFY, ev.argument);
1213                         inset->localDispatch(fr);
1214                 } else {
1215                         FuncRequest fr(bv_, LFUN_INSET_INSERT, ev.argument);
1216                         dispatch(fr);
1217                 }
1218         }
1219         break;
1220
1221         case LFUN_INSET_INSERT: {
1222                 InsetOld * inset = createInset(ev);
1223                 if (inset && insertInset(inset)) {
1224                         updateInset(inset);
1225
1226                         string const name = ev.getArg(0);
1227                         if (name == "bibitem") {
1228                                 // We need to do a redraw because the maximum
1229                                 // InsetBibitem width could have changed
1230 #warning please check you mean repaint() not update(),
1231 #warning and whether the repaint() is needed at all
1232                                 bv_->repaint();
1233                                 bv_->fitCursor();
1234                         }
1235                 } else {
1236                         delete inset;
1237                 }
1238         }
1239         break;
1240
1241         case LFUN_FLOAT_LIST:
1242                 if (tclass.floats().typeExist(ev.argument)) {
1243                         InsetOld * inset = new InsetFloatList(ev.argument);
1244                         if (!insertInset(inset, tclass.defaultLayoutName()))
1245                                 delete inset;
1246                 } else {
1247                         lyxerr << "Non-existent float type: "
1248                                << ev.argument << endl;
1249                 }
1250                 break;
1251
1252         case LFUN_LAYOUT_PARAGRAPH: {
1253                 Paragraph const * par = &*bv_->getLyXText()->cursor.par();
1254                 if (!par)
1255                         break;
1256
1257                 string data;
1258                 params2string(*par, data);
1259
1260                 data = "show\n" + data;
1261                 bv_->owner()->getDialogs().show("paragraph", data);
1262                 break;
1263         }
1264
1265         case LFUN_PARAGRAPH_UPDATE: {
1266                 if (!bv_->owner()->getDialogs().visible("paragraph"))
1267                         break;
1268                 Paragraph const * par = &*bv_->getLyXText()->cursor.par();
1269                 if (!par)
1270                         break;
1271
1272                 string data;
1273                 params2string(*par, data);
1274
1275                 // Will the paragraph accept changes from the dialog?
1276                 InsetOld * const inset = par->inInset();
1277                 bool const accept =
1278                         !(inset && inset->forceDefaultParagraphs(inset));
1279
1280                 data = "update " + tostr(accept) + '\n' + data;
1281                 bv_->owner()->getDialogs().update("paragraph", data);
1282                 break;
1283         }
1284
1285         case LFUN_PARAGRAPH_APPLY:
1286                 setParagraphParams(*bv_, ev.argument);
1287                 break;
1288
1289         case LFUN_THESAURUS_ENTRY:
1290         {
1291                 string arg = ev.argument;
1292
1293                 if (arg.empty()) {
1294                         arg = bv_->getLyXText()->selectionAsString(buffer_,
1295                                                                    false);
1296
1297                         // FIXME
1298                         if (arg.size() > 100 || arg.empty()) {
1299                                 // Get word or selection
1300                                 bv_->getLyXText()->selectWordWhenUnderCursor(lyx::WHOLE_WORD);
1301                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
1302                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1303                         }
1304                 }
1305
1306                 bv_->owner()->getDialogs().show("thesaurus", arg);
1307         }
1308                 break;
1309
1310         case LFUN_TRACK_CHANGES:
1311                 trackChanges();
1312                 break;
1313
1314         case LFUN_MERGE_CHANGES:
1315                 owner_->getDialogs().show("changes");
1316                 break;
1317
1318         case LFUN_ACCEPT_ALL_CHANGES: {
1319                 update(BufferView::SELECT);
1320                 bv_->text->setCursor(bv_->buffer()->paragraphs.begin(), 0);
1321 #warning FIXME changes
1322                 //moveCursorUpdate(false);
1323
1324                 while (lyx::find::findNextChange(bv_)) {
1325                         bv_->getLyXText()->acceptChange();
1326                 }
1327                 update(BufferView::SELECT);
1328                 break;
1329         }
1330
1331         case LFUN_REJECT_ALL_CHANGES: {
1332                 update(BufferView::SELECT);
1333                 bv_->text->setCursor(bv_->buffer()->paragraphs.begin(), 0);
1334 #warning FIXME changes
1335                 //moveCursorUpdate(false);
1336
1337                 while (lyx::find::findNextChange(bv_)) {
1338                         bv_->getLyXText()->rejectChange();
1339                 }
1340                 update(BufferView::SELECT);
1341                 break;
1342         }
1343
1344         case LFUN_ACCEPT_CHANGE: {
1345                 bv_->getLyXText()->acceptChange();
1346                 update(BufferView::SELECT);
1347                 break;
1348         }
1349
1350         case LFUN_REJECT_CHANGE: {
1351                 bv_->getLyXText()->rejectChange();
1352                 update(BufferView::SELECT);
1353                 break;
1354         }
1355
1356         case LFUN_UNKNOWN_ACTION:
1357                 ev.errorMessage(N_("Unknown function!"));
1358                 break;
1359
1360         default:
1361                 return bv_->getLyXText()->dispatch(FuncRequest(ev, bv_));
1362         } // end of switch
1363
1364         return true;
1365 }
1366
1367
1368 bool BufferView::Pimpl::insertInset(InsetOld * inset, string const & lout)
1369 {
1370         // if we are in a locking inset we should try to insert the
1371         // inset there otherwise this is a illegal function now
1372         if (bv_->theLockingInset()) {
1373                 if (bv_->theLockingInset()->insetAllowed(inset))
1374                         return bv_->theLockingInset()->insertInset(bv_, inset);
1375                 return false;
1376         }
1377
1378         // not quite sure if we want this...
1379         recordUndo(bv_, Undo::ATOMIC);
1380         freezeUndo();
1381
1382         beforeChange(bv_->text);
1383         if (!lout.empty()) {
1384                 update(BufferView::SELECT);
1385                 bv_->text->breakParagraph(bv_->buffer()->paragraphs);
1386                 update(BufferView::SELECT);
1387
1388                 if (!bv_->text->cursor.par()->empty()) {
1389                         bv_->text->cursorLeft(bv_);
1390
1391                         bv_->text->breakParagraph(bv_->buffer()->paragraphs);
1392                         update(BufferView::SELECT);
1393                 }
1394
1395                 string lres = lout;
1396                 LyXTextClass const & tclass =
1397                         buffer_->params.getLyXTextClass();
1398                 bool hasLayout = tclass.hasLayout(lres);
1399                 string lay = tclass.defaultLayoutName();
1400
1401                 if (hasLayout != false) {
1402                         // layout found
1403                         lay = lres;
1404                 } else {
1405                         // layout not fount using default
1406                         lay = tclass.defaultLayoutName();
1407                 }
1408
1409                 bv_->text->setLayout(lay);
1410
1411                 bv_->text->setParagraph(0, 0,
1412                                    0, 0,
1413                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
1414                                    Spacing(),
1415                                    LYX_ALIGN_LAYOUT,
1416                                    string(),
1417                                    0);
1418                 update(BufferView::SELECT);
1419         }
1420
1421         bv_->text->insertInset(inset);
1422         update(BufferView::SELECT);
1423
1424         unFreezeUndo();
1425         return true;
1426 }
1427
1428
1429 void BufferView::Pimpl::updateInset(InsetOld * inset)
1430 {
1431         if (!inset || !available())
1432                 return;
1433
1434         // first check for locking insets
1435         if (bv_->theLockingInset()) {
1436                 if (bv_->theLockingInset() == inset) {
1437                         if (bv_->text->updateInset(inset)) {
1438                                 update();
1439                                 updateScrollbar();
1440                                 return;
1441                         }
1442                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
1443                         if (bv_->text->updateInset(bv_->theLockingInset())) {
1444                                 update();
1445                                 updateScrollbar();
1446                                 return;
1447                         }
1448                 }
1449         }
1450
1451         // then check if the inset is a top_level inset (has no owner)
1452         // if yes do the update as always otherwise we have to update the
1453         // toplevel inset where this inset is inside
1454         InsetOld * tl_inset = inset;
1455         while (tl_inset->owner())
1456                 tl_inset = tl_inset->owner();
1457         if (tl_inset == inset) {
1458                 update(BufferView::UPDATE);
1459                 if (bv_->text->updateInset(inset)) {
1460                         update(BufferView::SELECT);
1461                         return;
1462                 }
1463         } else if (static_cast<UpdatableInset *>(tl_inset)
1464                            ->updateInsetInInset(bv_, inset))
1465         {
1466                 if (bv_->text->updateInset(tl_inset)) {
1467                         update();
1468                         updateScrollbar();
1469                 }
1470         }
1471 }