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