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