]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
You've had enough time for that ol' review and I've made sure that things
[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         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
229
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->top_y(screen().topCursorVisible(bv_->text->cursor, bv_->text->top_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 << ", top_y() "
354                 << t.top_y() << ", default height " << defaultRowHeight() << endl;
355
356         workarea().setScrollbarParams(t.height, t.top_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->top_y() + height));
376         int const last = static_cast<int>((bv_->text->top_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_top_y = t->top_y() + lines * line_height;
396
397         // Restrict to a valid value
398         new_top_y = std::min(t->height - 4 * line_height, new_top_y);
399         new_top_y = std::max(0, new_top_y);
400
401         scrollDocView(new_top_y);
402
403         // Update the scrollbar.
404         workarea().setScrollbarParams(t->height, t->top_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 top_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 top_y() must make sure to call
786         // updateScrollbar() currently. Never mind that this is a
787         // pretty obfuscated way of updating t->top_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().show("changes");
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_LAYOUT_COPY:
993                 bv_->copyEnvironment();
994                 break;
995
996         case LFUN_LAYOUT_PASTE:
997                 bv_->pasteEnvironment();
998                 switchKeyMap();
999                 break;
1000
1001         case LFUN_FILE_INSERT:
1002                 MenuInsertLyXFile(ev.argument);
1003                 break;
1004
1005         case LFUN_FILE_INSERT_ASCII_PARA:
1006                 InsertAsciiFile(bv_, ev.argument, true);
1007                 break;
1008
1009         case LFUN_FILE_INSERT_ASCII:
1010                 InsertAsciiFile(bv_, ev.argument, false);
1011                 break;
1012
1013         case LFUN_LANGUAGE:
1014                 lang(bv_, ev.argument);
1015                 switchKeyMap();
1016                 owner_->view_state_changed();
1017                 break;
1018
1019         case LFUN_EMPH:
1020                 emph(bv_);
1021                 owner_->view_state_changed();
1022                 break;
1023
1024         case LFUN_BOLD:
1025                 bold(bv_);
1026                 owner_->view_state_changed();
1027                 break;
1028
1029         case LFUN_NOUN:
1030                 noun(bv_);
1031                 owner_->view_state_changed();
1032                 break;
1033
1034         case LFUN_CODE:
1035                 code(bv_);
1036                 owner_->view_state_changed();
1037                 break;
1038
1039         case LFUN_SANS:
1040                 sans(bv_);
1041                 owner_->view_state_changed();
1042                 break;
1043
1044         case LFUN_ROMAN:
1045                 roman(bv_);
1046                 owner_->view_state_changed();
1047                 break;
1048
1049         case LFUN_DEFAULT:
1050                 styleReset(bv_);
1051                 owner_->view_state_changed();
1052                 break;
1053
1054         case LFUN_UNDERLINE:
1055                 underline(bv_);
1056                 owner_->view_state_changed();
1057                 break;
1058
1059         case LFUN_FONT_SIZE:
1060                 fontSize(bv_, ev.argument);
1061                 owner_->view_state_changed();
1062                 break;
1063
1064         case LFUN_FONT_STATE:
1065                 owner_->getLyXFunc().setMessage(currentState(bv_));
1066                 break;
1067
1068         case LFUN_INSERT_LABEL: {
1069                 // Try and generate a valid label
1070                 string const contents = ev.argument.empty() ?
1071                         getPossibleLabel(*bv_) : ev.argument;
1072                 InsetCommandParams icp("label", contents);
1073                 string data = InsetCommandMailer::params2string("label", icp);
1074                 owner_->getDialogs().show("label", data, 0);
1075         }
1076         break;
1077
1078         case LFUN_BOOKMARK_SAVE:
1079                 savePosition(strToUnsignedInt(ev.argument));
1080                 break;
1081
1082         case LFUN_BOOKMARK_GOTO:
1083                 restorePosition(strToUnsignedInt(ev.argument));
1084                 break;
1085
1086         case LFUN_REF_GOTO:
1087         {
1088                 string label = ev.argument;
1089                 if (label.empty()) {
1090                         InsetRef * inset =
1091                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1092                         if (inset) {
1093                                 label = inset->getContents();
1094                                 savePosition(0);
1095                         }
1096                 }
1097
1098                 if (!label.empty()) {
1099                         //bv_->savePosition(0);
1100                         if (!bv_->gotoLabel(label))
1101                                 Alert::alert(_("Error"),
1102                                            _("Couldn't find this label"),
1103                                            _("in current document."));
1104                 }
1105         }
1106         break;
1107
1108         // --- accented characters ---------------------------
1109
1110         case LFUN_UMLAUT:
1111         case LFUN_CIRCUMFLEX:
1112         case LFUN_GRAVE:
1113         case LFUN_ACUTE:
1114         case LFUN_TILDE:
1115         case LFUN_CEDILLA:
1116         case LFUN_MACRON:
1117         case LFUN_DOT:
1118         case LFUN_UNDERDOT:
1119         case LFUN_UNDERBAR:
1120         case LFUN_CARON:
1121         case LFUN_SPECIAL_CARON:
1122         case LFUN_BREVE:
1123         case LFUN_TIE:
1124         case LFUN_HUNG_UMLAUT:
1125         case LFUN_CIRCLE:
1126         case LFUN_OGONEK:
1127                 if (ev.argument.empty()) {
1128                         // As always...
1129                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1130                 } else {
1131                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1132                         owner_->getIntl().getTransManager()
1133                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
1134                         update(bv_->getLyXText(),
1135                                BufferView::SELECT
1136                                | BufferView::FITCUR
1137                                | BufferView::CHANGE);
1138                 }
1139                 break;
1140
1141         case LFUN_MATH_MACRO:
1142         case LFUN_MATH_DELIM:
1143         case LFUN_INSERT_MATRIX:
1144         case LFUN_INSERT_MATH:
1145         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
1146         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
1147         case LFUN_MATH_MODE:             // Open or create an inlined math inset
1148         case LFUN_GREEK:                 // Insert a single greek letter
1149                 mathDispatch(ev);
1150                 break;
1151
1152         case LFUN_INSET_APPLY: {
1153                 string const name = ev.getArg(0);
1154
1155                 InsetBase * base = owner_->getDialogs().getOpenInset(name);
1156                 if (base) {
1157                         // This works both for 'original' and 'mathed' insets.
1158                         // Note that the localDispatch performs updateInset
1159                         // also.
1160                         FuncRequest fr(bv_, LFUN_INSET_MODIFY, ev.argument);
1161                         base->localDispatch(fr);
1162                 } else {
1163                         Inset * inset = createInset(ev);
1164                         if (inset && insertInset(inset)) {
1165                                 updateInset(inset, true);
1166                         } else {
1167                                 delete inset;
1168                         }
1169                 }
1170
1171                 if (name == "bibitem") {
1172                         // We need to do a redraw because the maximum
1173                         // InsetBibitem width could have changed
1174 #warning please check you mean repaint() not update(),
1175 #warning and whether the repaint() is needed at all
1176                         bv_->repaint();
1177                         bv_->fitCursor();
1178                 }
1179         }
1180         break;
1181
1182         case LFUN_FLOAT_LIST:
1183                 if (tclass.floats().typeExist(ev.argument)) {
1184                         Inset * inset = new InsetFloatList(ev.argument);
1185                         if (!insertInset(inset, tclass.defaultLayoutName()))
1186                                 delete inset;
1187                 } else {
1188                         lyxerr << "Non-existent float type: "
1189                                << ev.argument << endl;
1190                 }
1191                 break;
1192
1193         case LFUN_LAYOUT_PARAGRAPH: {
1194                 Paragraph const * par = bv_->getLyXText()->cursor.par();
1195                 if (!par)
1196                         break;
1197
1198                 string data;
1199                 params2string(*par, data);
1200
1201                 data = "show\n" + data;
1202                 bv_->owner()->getDialogs().show("paragraph", data);
1203                 break;
1204         }
1205
1206         case LFUN_PARAGRAPH_UPDATE: {
1207                 Paragraph const * par = bv_->getLyXText()->cursor.par();
1208                 if (!par)
1209                         break;
1210
1211                 string data;
1212                 params2string(*par, data);
1213
1214                 // Will the paragraph accept changes from the dialog?
1215                 Inset * const inset = par->inInset();
1216                 bool const accept =
1217                         !(inset && inset->forceDefaultParagraphs(inset));
1218
1219                 data = "update " + tostr(accept) + '\n' + data;
1220                 bv_->owner()->getDialogs().update("paragraph", data);
1221                 break;
1222         }
1223
1224         case LFUN_PARAGRAPH_APPLY:
1225                 setParagraphParams(*bv_, ev.argument);
1226                 break;
1227                 
1228         case LFUN_THESAURUS_ENTRY:
1229         {
1230                 string arg = ev.argument;
1231
1232                 if (arg.empty()) {
1233                         arg = bv_->getLyXText()->selectionAsString(buffer_,
1234                                                                    false);
1235
1236                         // FIXME
1237                         if (arg.size() > 100 || arg.empty()) {
1238                                 // Get word or selection
1239                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
1240                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
1241                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1242                         }
1243                 }
1244
1245                 bv_->owner()->getDialogs().showThesaurus(arg);
1246         }
1247                 break;
1248
1249         case LFUN_TRACK_CHANGES:
1250                 trackChanges();
1251                 break;
1252
1253         case LFUN_MERGE_CHANGES:
1254                 owner_->getDialogs().show("changes");
1255                 break;
1256
1257         case LFUN_ACCEPT_ALL_CHANGES: {
1258                 bv_->update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
1259                 bv_->text->setCursor(bv_, &(*bv_->buffer()->paragraphs.begin()), 0);
1260 #warning FIXME changes
1261                 //moveCursorUpdate(false);
1262
1263                 while (lyxfind::findNextChange(bv_)) {
1264                         bv_->getLyXText()->acceptChange(bv_);
1265                 }
1266                 update(bv_->text,
1267                         BufferView::SELECT | BufferView::FITCUR | BufferView::CHANGE);
1268                 break;
1269         }
1270
1271         case LFUN_REJECT_ALL_CHANGES: {
1272                 bv_->update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
1273                 bv_->text->setCursor(bv_, &(*bv_->buffer()->paragraphs.begin()), 0);
1274 #warning FIXME changes
1275                 //moveCursorUpdate(false);
1276
1277                 while (lyxfind::findNextChange(bv_)) {
1278                         bv_->getLyXText()->rejectChange(bv_);
1279                 }
1280                 update(bv_->text,
1281                         BufferView::SELECT | BufferView::FITCUR | BufferView::CHANGE);
1282                 break;
1283         }
1284
1285         case LFUN_ACCEPT_CHANGE: {
1286                 bv_->getLyXText()->acceptChange(bv_);
1287                 update(bv_->text,
1288                         BufferView::SELECT | BufferView::FITCUR | BufferView::CHANGE);
1289                 break;
1290         }
1291
1292         case LFUN_REJECT_CHANGE: {
1293                 bv_->getLyXText()->rejectChange(bv_);
1294                 update(bv_->text,
1295                         BufferView::SELECT | BufferView::FITCUR | BufferView::CHANGE);
1296                 break;
1297         }
1298
1299         case LFUN_UNKNOWN_ACTION:
1300                 ev.errorMessage(N_("Unknown function!"));
1301                 break;
1302
1303         default:
1304                 return bv_->getLyXText()->dispatch(FuncRequest(ev, bv_));
1305         } // end of switch
1306
1307         return true;
1308 }
1309
1310
1311 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
1312 {
1313         // if we are in a locking inset we should try to insert the
1314         // inset there otherwise this is a illegal function now
1315         if (bv_->theLockingInset()) {
1316                 if (bv_->theLockingInset()->insetAllowed(inset))
1317                         return bv_->theLockingInset()->insertInset(bv_, inset);
1318                 return false;
1319         }
1320
1321         // not quite sure if we want this...
1322         setCursorParUndo(bv_);
1323         freezeUndo();
1324
1325         beforeChange(bv_->text);
1326         if (!lout.empty()) {
1327                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1328                 bv_->text->breakParagraph(bv_, bv_->buffer()->paragraphs);
1329                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1330
1331                 if (!bv_->text->cursor.par()->empty()) {
1332                         bv_->text->cursorLeft(bv_);
1333
1334                         bv_->text->breakParagraph(bv_, bv_->buffer()->paragraphs);
1335                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1336                 }
1337
1338                 string lres = lout;
1339                 LyXTextClass const & tclass =
1340                         buffer_->params.getLyXTextClass();
1341                 bool hasLayout = tclass.hasLayout(lres);
1342                 string lay = tclass.defaultLayoutName();
1343
1344                 if (hasLayout != false) {
1345                         // layout found
1346                         lay = lres;
1347                 } else {
1348                         // layout not fount using default
1349                         lay = tclass.defaultLayoutName();
1350                 }
1351
1352                 bv_->text->setLayout(bv_, lay);
1353
1354                 bv_->text->setParagraph(bv_, 0, 0,
1355                                    0, 0,
1356                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
1357                                    Spacing(),
1358                                    LYX_ALIGN_LAYOUT,
1359                                    string(),
1360                                    0);
1361                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1362         }
1363
1364         bv_->text->insertInset(bv_, inset);
1365         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1366
1367         unFreezeUndo();
1368         return true;
1369 }
1370
1371
1372 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
1373 {
1374         if (!inset || !available())
1375                 return;
1376
1377         // first check for locking insets
1378         if (bv_->theLockingInset()) {
1379                 if (bv_->theLockingInset() == inset) {
1380                         if (bv_->text->updateInset(bv_, inset)) {
1381                                 update();
1382                                 if (mark_dirty) {
1383                                         buffer_->markDirty();
1384                                 }
1385                                 updateScrollbar();
1386                                 return;
1387                         }
1388                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
1389                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
1390                                 update();
1391                                 if (mark_dirty) {
1392                                         buffer_->markDirty();
1393                                 }
1394                                 updateScrollbar();
1395                                 return;
1396                         }
1397                 }
1398         }
1399
1400         // then check if the inset is a top_level inset (has no owner)
1401         // if yes do the update as always otherwise we have to update the
1402         // toplevel inset where this inset is inside
1403         Inset * tl_inset = inset;
1404         while (tl_inset->owner())
1405                 tl_inset = tl_inset->owner();
1406         hideCursor();
1407         if (tl_inset == inset) {
1408                 update(bv_->text, BufferView::UPDATE);
1409                 if (bv_->text->updateInset(bv_, inset)) {
1410                         if (mark_dirty) {
1411                                 update(bv_->text,
1412                                        BufferView::SELECT
1413                                        | BufferView::FITCUR
1414                                        | BufferView::CHANGE);
1415                         } else {
1416                                 update(bv_->text, SELECT);
1417                         }
1418                         return;
1419                 }
1420         } else if (static_cast<UpdatableInset *>(tl_inset)
1421                            ->updateInsetInInset(bv_, inset))
1422         {
1423                 if (bv_->text->updateInset(bv_, tl_inset)) {
1424                         update();
1425                         updateScrollbar();
1426                 }
1427         }
1428 }