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