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