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