]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
special menu hack for qt/mac
[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->fullRebreak();
396                 update();
397         } else {
398                 lyxerr << "text not available!\n";
399                 // See if we have a text in TextCache that fits
400                 // the new buffer_ with the correct width.
401                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
402                 if (bv_->text) {
403                         lyxerr << "text in cache!\n";
404                         if (lyxerr.debugging()) {
405                                 lyxerr << "Found a LyXText that fits:\n";
406                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
407                         }
408                         // Set the owner of the newly found text
409                         //      bv_->text->owner(bv_);
410                         if (lyxerr.debugging())
411                                 textcache.show(lyxerr, "resizeCurrentBuffer");
412
413                         resizeInsets(bv_);
414                 } else {
415                         lyxerr << "no text in cache!\n";
416                         bv_->text = new LyXText(bv_);
417                         resizeInsets(bv_);
418                         bv_->text->init(bv_);
419                 }
420
421                 par = bv_->text->ownerParagraphs().end();
422                 selstartpar = bv_->text->ownerParagraphs().end();
423                 selendpar = bv_->text->ownerParagraphs().end();
424         }
425
426         if (par != bv_->text->ownerParagraphs().end()) {
427                 bv_->text->selection.set(true);
428                 // At this point just to avoid the Delete-Empty-Paragraph-
429                 // Mechanism when setting the cursor.
430                 bv_->text->selection.mark(mark_set);
431                 if (selection) {
432                         bv_->text->setCursor(selstartpar, selstartpos);
433                         bv_->text->selection.cursor = bv_->text->cursor;
434                         bv_->text->setCursor(selendpar, selendpos);
435                         bv_->text->setSelection();
436                         bv_->text->setCursor(par, pos);
437                 } else {
438                         bv_->text->setCursor(par, pos);
439                         bv_->text->selection.cursor = bv_->text->cursor;
440                         bv_->text->selection.set(false);
441                 }
442                 // remake the inset locking
443                 bv_->theLockingInset(the_locking_inset);
444         }
445
446         bv_->text->top_y(screen().topCursorVisible(bv_->text));
447
448         switchKeyMap();
449         owner_->busy(false);
450
451         // reset the "Formatting..." message
452         owner_->clearMessage();
453
454         updateScrollbar();
455
456         return 0;
457 }
458
459
460 void BufferView::Pimpl::repaint()
461 {
462         // Regenerate the screen.
463         screen().redraw(bv_->text, bv_);
464 }
465
466
467 void BufferView::Pimpl::updateScrollbar()
468 {
469         if (!bv_->text) {
470                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
471                 workarea().setScrollbarParams(0, 0, 0);
472                 return;
473         }
474
475         LyXText const & t = *bv_->text;
476
477         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", top_y() "
478                 << t.top_y() << ", default height " << defaultRowHeight() << endl;
479
480         workarea().setScrollbarParams(t.height, t.top_y(), defaultRowHeight());
481 }
482
483
484 void BufferView::Pimpl::scrollDocView(int value)
485 {
486         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
487
488         if (!buffer_)
489                 return;
490
491         screen().hideCursor();
492
493         screen().draw(bv_->text, bv_, value);
494
495         if (!lyxrc.cursor_follows_scrollbar)
496                 return;
497
498         LyXText * vbt = bv_->text;
499
500         int const height = defaultRowHeight();
501         int const first = static_cast<int>((bv_->text->top_y() + height));
502         int const last = static_cast<int>((bv_->text->top_y() + workarea().workHeight() - height));
503
504         if (vbt->cursor.y() < first)
505                 vbt->setCursorFromCoordinates(0, first);
506         else if (vbt->cursor.y() > last)
507                 vbt->setCursorFromCoordinates(0, last);
508
509         owner_->updateLayoutChoice();
510 }
511
512
513 void BufferView::Pimpl::scroll(int lines)
514 {
515         if (!buffer_) {
516                 return;
517         }
518
519         LyXText const * t = bv_->text;
520         int const line_height = defaultRowHeight();
521
522         // The new absolute coordinate
523         int new_top_y = t->top_y() + lines * line_height;
524
525         // Restrict to a valid value
526         new_top_y = std::min(t->height - 4 * line_height, new_top_y);
527         new_top_y = std::max(0, new_top_y);
528
529         scrollDocView(new_top_y);
530
531         // Update the scrollbar.
532         workarea().setScrollbarParams(t->height, t->top_y(), defaultRowHeight());
533 }
534
535
536 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
537                                          key_modifier::state state)
538 {
539         bv_->owner()->getLyXFunc().processKeySym(key, state);
540
541         /* This is perhaps a bit of a hack. When we move
542          * around, or type, it's nice to be able to see
543          * the cursor immediately after the keypress. So
544          * we reset the toggle timeout and force the visibility
545          * of the cursor. Note we cannot do this inside
546          * dispatch() itself, because that's called recursively.
547          */
548         if (available()) {
549                 cursor_timeout.restart();
550                 screen().showCursor(*bv_);
551         }
552 }
553
554
555 void BufferView::Pimpl::selectionRequested()
556 {
557         static string sel;
558
559         if (!available())
560                 return;
561
562         LyXText * text = bv_->getLyXText();
563
564         if (text->selection.set() &&
565                 (!bv_->text->xsel_cache.set() ||
566                  text->selection.start != bv_->text->xsel_cache.start ||
567                  text->selection.end != bv_->text->xsel_cache.end))
568         {
569                 bv_->text->xsel_cache = text->selection;
570                 sel = text->selectionAsString(bv_->buffer(), false);
571         } else if (!text->selection.set()) {
572                 sel = string();
573                 bv_->text->xsel_cache.set(false);
574         }
575         if (!sel.empty()) {
576                 workarea().putClipboard(sel);
577         }
578 }
579
580
581 void BufferView::Pimpl::selectionLost()
582 {
583         if (available()) {
584                 screen().hideCursor();
585                 toggleSelection();
586                 bv_->getLyXText()->clearSelection();
587                 bv_->text->xsel_cache.set(false);
588         }
589 }
590
591
592 void BufferView::Pimpl::workAreaResize()
593 {
594         static int work_area_width;
595         static int work_area_height;
596
597         bool const widthChange = workarea().workWidth() != work_area_width;
598         bool const heightChange = workarea().workHeight() != work_area_height;
599
600         // update from work area
601         work_area_width = workarea().workWidth();
602         work_area_height = workarea().workHeight();
603
604         if (buffer_ != 0) {
605                 if (widthChange) {
606                         // The visible LyXView need a resize
607                         resizeCurrentBuffer();
608
609                         // Remove all texts from the textcache
610                         // This is not _really_ what we want to do. What
611                         // we really want to do is to delete in textcache
612                         // that does not have a BufferView with matching
613                         // width, but as long as we have only one BufferView
614                         // deleting all gives the same result.
615                         if (lyxerr.debugging())
616                                 textcache.show(lyxerr, "Expose delete all");
617                         textcache.clear();
618                         // FIXME: this is already done in resizeCurrentBuffer() ??
619                         resizeInsets(bv_);
620                 } else if (heightChange) {
621                         // fitCursor() ensures we don't jump back
622                         // to the start of the document on vertical
623                         // resize
624                         fitCursor();
625                 }
626         }
627
628         if (widthChange || heightChange) {
629                 repaint();
630         }
631
632         // always make sure that the scrollbar is sane.
633         updateScrollbar();
634         owner_->updateLayoutChoice();
635         return;
636 }
637
638
639 void BufferView::Pimpl::update()
640 {
641         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
642                 screen().update(*bv_);
643                 bv_->text->clearPaint();
644         }
645 }
646
647
648 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
649 {
650         if (!text->selection.set() && (f & SELECT)) {
651                 text->selection.cursor = text->cursor;
652         }
653
654         text->partialRebreak();
655
656         if (text->inset_owner) {
657                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
658                 updateInset(text->inset_owner);
659         } else {
660                 update();
661         }
662 }
663
664
665 void BufferView::Pimpl::update(BufferView::UpdateCodes f)
666 {
667         LyXText * text = bv_->text;
668
669         if (!text->selection.set() && (f & SELECT)) {
670                 text->selection.cursor = text->cursor;
671         }
672
673         text->partialRebreak();
674
675         if (text->inset_owner) {
676                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
677                 updateInset(text->inset_owner);
678         } else {
679                 update();
680         }
681 }
682
683
684 // Callback for cursor timer
685 void BufferView::Pimpl::cursorToggle()
686 {
687         if (!buffer_) {
688                 cursor_timeout.restart();
689                 return;
690         }
691
692         screen().toggleCursor(*bv_);
693
694         cursor_timeout.restart();
695 }
696
697
698 bool BufferView::Pimpl::available() const
699 {
700         if (buffer_ && bv_->text)
701                 return true;
702         return false;
703 }
704
705
706 Change const BufferView::Pimpl::getCurrentChange()
707 {
708         if (!bv_->buffer()->params.tracking_changes)
709                 return Change(Change::UNCHANGED);
710
711         LyXText * t(bv_->getLyXText());
712
713         if (!t->selection.set())
714                 return Change(Change::UNCHANGED);
715
716         LyXCursor const & cur(t->selection.start);
717         return cur.par()->lookupChangeFull(cur.pos());
718 }
719
720
721 void BufferView::Pimpl::beforeChange(LyXText * text)
722 {
723         toggleSelection();
724         text->clearSelection();
725 }
726
727
728 void BufferView::Pimpl::savePosition(unsigned int i)
729 {
730         if (i >= saved_positions_num)
731                 return;
732         saved_positions[i] = Position(buffer_->fileName(),
733                                       bv_->text->cursor.par()->id(),
734                                       bv_->text->cursor.pos());
735         if (i > 0)
736                 owner_->message(bformat(_("Saved bookmark %1$s"), tostr(i)));
737 }
738
739
740 void BufferView::Pimpl::restorePosition(unsigned int i)
741 {
742         if (i >= saved_positions_num)
743                 return;
744
745         string const fname = saved_positions[i].filename;
746
747         beforeChange(bv_->text);
748
749         if (fname != buffer_->fileName()) {
750                 Buffer * b;
751                 if (bufferlist.exists(fname))
752                         b = bufferlist.getBuffer(fname);
753                 else {
754                         b = bufferlist.newBuffer(fname);
755                         ::loadLyXFile(b, fname); // don't ask, just load it
756                 }
757                 if (b != 0)
758                         buffer(b);
759         }
760
761         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
762         if (par == buffer_->par_iterator_end())
763                 return;
764
765         bv_->text->setCursor(par.pit(),
766                              min(par->size(), saved_positions[i].par_pos));
767
768         update(BufferView::SELECT);
769         if (i > 0)
770                 owner_->message(bformat(_("Moved to bookmark %1$s"), tostr(i)));
771 }
772
773
774 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
775 {
776         if (i >= saved_positions_num)
777                 return false;
778
779         return !saved_positions[i].filename.empty();
780 }
781
782
783 void BufferView::Pimpl::switchKeyMap()
784 {
785         if (!lyxrc.rtl_support)
786                 return;
787
788         LyXText * text = bv_->getLyXText();
789         if (text->real_current_font.isRightToLeft()
790             && !(bv_->theLockingInset()
791                  && bv_->theLockingInset()->lyxCode() == Inset::ERT_CODE))
792         {
793                 if (owner_->getIntl().keymap == Intl::PRIMARY)
794                         owner_->getIntl().KeyMapSec();
795         } else {
796                 if (owner_->getIntl().keymap == Intl::SECONDARY)
797                         owner_->getIntl().KeyMapPrim();
798         }
799 }
800
801
802 void BufferView::Pimpl::insetUnlock()
803 {
804         if (bv_->theLockingInset()) {
805                 bv_->theLockingInset()->insetUnlock(bv_);
806                 bv_->theLockingInset(0);
807                 finishUndo();
808         }
809 }
810
811
812 void BufferView::Pimpl::toggleSelection(bool b)
813 {
814         if (bv_->theLockingInset())
815                 bv_->theLockingInset()->toggleSelection(bv_, b);
816         screen().toggleSelection(bv_->text, bv_, b);
817 }
818
819
820 void BufferView::Pimpl::toggleToggle()
821 {
822         screen().toggleToggle(bv_->text, bv_);
823 }
824
825
826 void BufferView::Pimpl::center()
827 {
828         LyXText * t = bv_->text;
829
830         beforeChange(t);
831         int const half_height = workarea().workHeight() / 2;
832         int new_y = 0;
833
834         if (t->cursor.y() > half_height) {
835                 new_y = t->cursor.y() - half_height;
836         }
837
838         // FIXME: look at this comment again ...
839
840         // FIXME: can we do this w/o calling screen directly ?
841         // This updates top_y() but means the fitCursor() call
842         // from the update(FITCUR) doesn't realise that we might
843         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
844         // the scrollbar to be updated as it should, so we have
845         // to do it manually. Any operation that does a center()
846         // and also might have moved top_y() must make sure to call
847         // updateScrollbar() currently. Never mind that this is a
848         // pretty obfuscated way of updating t->top_y()
849         screen().draw(t, bv_, new_y);
850
851         update(BufferView::SELECT);
852 }
853
854
855 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
856 {
857         workarea().putClipboard(stuff);
858 }
859
860
861 /*
862  * Dispatch functions for actions which can be valid for BufferView->text
863  * and/or InsetText->text!!!
864  */
865
866
867 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
868 {
869 #if 0
870         LyXCursor cursor = bv_->getLyXText()->cursor;
871         Buffer::inset_iterator it =
872                 find_if(Buffer::inset_iterator(
873                         cursor.par(), cursor.pos()),
874                         buffer_->inset_iterator_end(),
875                         lyx::compare_memfun(&Inset::lyxCode, code));
876         return it != buffer_->inset_iterator_end() ? (*it) : 0;
877 #else
878         // Ok, this is a little bit too brute force but it
879         // should work for now. Better infrastructure is comming. (Lgb)
880
881         Buffer * b = bv_->buffer();
882         LyXCursor cursor = bv_->getLyXText()->cursor;
883
884         Buffer::inset_iterator beg = b->inset_iterator_begin();
885         Buffer::inset_iterator end = b->inset_iterator_end();
886
887         bool cursor_par_seen = false;
888
889         for (; beg != end; ++beg) {
890                 if (beg.getPar() == cursor.par()) {
891                         cursor_par_seen = true;
892                 }
893                 if (cursor_par_seen) {
894                         if (beg.getPar() == cursor.par()
895                             && beg.getPos() >= cursor.pos()) {
896                                 break;
897                         } else if (beg.getPar() != cursor.par()) {
898                                 break;
899                         }
900                 }
901
902         }
903         if (beg != end) {
904                 // Now find the first inset that matches code.
905                 for (; beg != end; ++beg) {
906                         if (beg->lyxCode() == code) {
907                                 return &(*beg);
908                         }
909                 }
910         }
911         return 0;
912 #endif
913 }
914
915
916 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
917 {
918         string filename = filen;
919
920         if (filename.empty()) {
921                 // Launch a file browser
922                 string initpath = lyxrc.document_path;
923
924                 if (available()) {
925                         string const trypath = owner_->buffer()->filePath();
926                         // If directory is writeable, use this as default.
927                         if (IsDirWriteable(trypath))
928                                 initpath = trypath;
929                 }
930
931                 FileDialog fileDlg(_("Select LyX document to insert"),
932                         LFUN_FILE_INSERT,
933                         make_pair(string(_("Documents|#o#O")),
934                                   string(lyxrc.document_path)),
935                         make_pair(string(_("Examples|#E#e")),
936                                   string(AddPath(system_lyxdir, "examples"))));
937
938                 FileDialog::Result result =
939                         fileDlg.open(initpath,
940                                        _("*.lyx| LyX Documents (*.lyx)"));
941
942                 if (result.first == FileDialog::Later)
943                         return;
944
945                 filename = result.second;
946
947                 // check selected filename
948                 if (filename.empty()) {
949                         owner_->message(_("Canceled."));
950                         return;
951                 }
952         }
953
954         // get absolute path of file and add ".lyx" to the filename if
955         // necessary
956         filename = FileSearch(string(), filename, "lyx");
957
958         string const disp_fn = MakeDisplayPath(filename);
959         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
960         if (bv_->insertLyXFile(filename))
961                 owner_->message(bformat(_("Document %1$s inserted."), 
962                                         disp_fn));
963         else
964                 owner_->message(bformat(_("Could not insert document %1$s"), 
965                                         disp_fn));
966
967 #warning remove this if update() is gone
968         bv_->text->fullRebreak();
969 }
970
971
972 void BufferView::Pimpl::trackChanges()
973 {
974         Buffer * buf(bv_->buffer());
975         bool const tracking(buf->params.tracking_changes);
976
977         if (!tracking) {
978                 ParIterator const end = buf->par_iterator_end();
979                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
980                         it->trackChanges();
981                 buf->params.tracking_changes = true;
982
983                 // we cannot allow undos beyond the freeze point
984                 buf->undostack.clear();
985         } else {
986                 update(BufferView::SELECT);
987                 bv_->text->setCursor(buf->paragraphs.begin(), 0);
988 #warning changes FIXME
989                 //moveCursorUpdate(false);
990
991                 bool found = lyxfind::findNextChange(bv_);
992                 if (found) {
993                         owner_->getDialogs().show("changes");
994                         return;
995                 }
996
997                 ParIterator const end = buf->par_iterator_end();
998                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
999                         it->untrackChanges();
1000                 buf->params.tracking_changes = false;
1001         }
1002
1003         buf->redostack.clear();
1004 }
1005
1006
1007 // Doesn't go through lyxfunc, so we need to update the
1008 // layout choice etc. ourselves
1009 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & ev_in)
1010 {
1011         // e.g. Qt mouse press when no buffer
1012         if (!available())
1013                 return false;
1014
1015         screen().hideCursor();
1016
1017         // Make sure that the cached BufferView is correct.
1018         FuncRequest ev = ev_in;
1019         ev.setView(bv_);
1020
1021         bool const res = dispatch(ev);
1022
1023         // see workAreaKeyPress
1024         cursor_timeout.restart();
1025         screen().showCursor(*bv_);
1026
1027         // FIXME: we should skip these when selecting
1028         bv_->owner()->updateLayoutChoice();
1029         bv_->owner()->updateToolbar();
1030         bv_->fitCursor();
1031
1032         // slight hack: this is only called currently when
1033         // we clicked somewhere, so we force through the display
1034         // of the new status here.
1035         bv_->owner()->clearMessage();
1036
1037         return res;
1038 }
1039
1040
1041 bool BufferView::Pimpl::dispatch(FuncRequest const & ev_in)
1042 {
1043         // Make sure that the cached BufferView is correct.
1044         FuncRequest ev = ev_in;
1045         ev.setView(bv_);
1046
1047         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch:"
1048                 << " action[" << ev.action << ']'
1049                 << " arg[" << ev.argument << ']'
1050                 << " x[" << ev.x << ']'
1051                 << " y[" << ev.y << ']'
1052                 << " button[" << ev.button() << ']'
1053                 << endl;
1054
1055         LyXTextClass const & tclass = buffer_->params.getLyXTextClass();
1056
1057         switch (ev.action) {
1058
1059         case LFUN_SCROLL_INSET:
1060                 // this is not handled here as this function is only active
1061                 // if we have a locking_inset and that one is (or contains)
1062                 // a tabular-inset
1063                 break;
1064
1065         case LFUN_FILE_INSERT:
1066                 MenuInsertLyXFile(ev.argument);
1067                 break;
1068
1069         case LFUN_FILE_INSERT_ASCII_PARA:
1070                 InsertAsciiFile(bv_, ev.argument, true);
1071                 break;
1072
1073         case LFUN_FILE_INSERT_ASCII:
1074                 InsertAsciiFile(bv_, ev.argument, false);
1075                 break;
1076
1077         case LFUN_LANGUAGE:
1078                 lang(bv_, ev.argument);
1079                 switchKeyMap();
1080                 owner_->view_state_changed();
1081                 break;
1082
1083         case LFUN_EMPH:
1084                 emph(bv_);
1085                 owner_->view_state_changed();
1086                 break;
1087
1088         case LFUN_BOLD:
1089                 bold(bv_);
1090                 owner_->view_state_changed();
1091                 break;
1092
1093         case LFUN_NOUN:
1094                 noun(bv_);
1095                 owner_->view_state_changed();
1096                 break;
1097
1098         case LFUN_CODE:
1099                 code(bv_);
1100                 owner_->view_state_changed();
1101                 break;
1102
1103         case LFUN_SANS:
1104                 sans(bv_);
1105                 owner_->view_state_changed();
1106                 break;
1107
1108         case LFUN_ROMAN:
1109                 roman(bv_);
1110                 owner_->view_state_changed();
1111                 break;
1112
1113         case LFUN_DEFAULT:
1114                 styleReset(bv_);
1115                 owner_->view_state_changed();
1116                 break;
1117
1118         case LFUN_UNDERLINE:
1119                 underline(bv_);
1120                 owner_->view_state_changed();
1121                 break;
1122
1123         case LFUN_FONT_SIZE:
1124                 fontSize(bv_, ev.argument);
1125                 owner_->view_state_changed();
1126                 break;
1127
1128         case LFUN_FONT_STATE:
1129                 owner_->getLyXFunc().setMessage(currentState(bv_));
1130                 break;
1131
1132         case LFUN_INSERT_LABEL: {
1133                 // Try and generate a valid label
1134                 string const contents = ev.argument.empty() ?
1135                         getPossibleLabel(*bv_) : ev.argument;
1136                 InsetCommandParams icp("label", contents);
1137                 string data = InsetCommandMailer::params2string("label", icp);
1138                 owner_->getDialogs().show("label", data, 0);
1139         }
1140         break;
1141
1142         case LFUN_BOOKMARK_SAVE:
1143                 savePosition(strToUnsignedInt(ev.argument));
1144                 break;
1145
1146         case LFUN_BOOKMARK_GOTO:
1147                 restorePosition(strToUnsignedInt(ev.argument));
1148                 break;
1149
1150         case LFUN_REF_GOTO: {
1151                 string label = ev.argument;
1152                 if (label.empty()) {
1153                         InsetRef * inset =
1154                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1155                         if (inset) {
1156                                 label = inset->getContents();
1157                                 savePosition(0);
1158                         }
1159                 }
1160
1161                 if (!label.empty())
1162                         bv_->gotoLabel(label);
1163         }
1164         break;
1165
1166         // --- accented characters ---------------------------
1167
1168         case LFUN_UMLAUT:
1169         case LFUN_CIRCUMFLEX:
1170         case LFUN_GRAVE:
1171         case LFUN_ACUTE:
1172         case LFUN_TILDE:
1173         case LFUN_CEDILLA:
1174         case LFUN_MACRON:
1175         case LFUN_DOT:
1176         case LFUN_UNDERDOT:
1177         case LFUN_UNDERBAR:
1178         case LFUN_CARON:
1179         case LFUN_SPECIAL_CARON:
1180         case LFUN_BREVE:
1181         case LFUN_TIE:
1182         case LFUN_HUNG_UMLAUT:
1183         case LFUN_CIRCLE:
1184         case LFUN_OGONEK:
1185                 if (ev.argument.empty()) {
1186                         // As always...
1187                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1188                 } else {
1189                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1190                         owner_->getIntl().getTransManager()
1191                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
1192                         update(bv_->getLyXText(), BufferView::SELECT);
1193                 }
1194                 break;
1195
1196         case LFUN_MATH_MACRO:
1197         case LFUN_MATH_DELIM:
1198         case LFUN_INSERT_MATRIX:
1199         case LFUN_INSERT_MATH:
1200         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
1201         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
1202         case LFUN_MATH_MODE:             // Open or create an inlined math inset
1203                 mathDispatch(ev);
1204                 break;
1205
1206         case LFUN_INSET_APPLY: {
1207                 string const name = ev.getArg(0);
1208
1209                 InsetBase * inset = owner_->getDialogs().getOpenInset(name);
1210                 if (inset) {
1211                         // This works both for 'original' and 'mathed' insets.
1212                         // Note that the localDispatch performs updateInset
1213                         // also.
1214                         FuncRequest fr(bv_, LFUN_INSET_MODIFY, ev.argument);
1215                         inset->localDispatch(fr);
1216                 } else {
1217                         FuncRequest fr(bv_, LFUN_INSET_INSERT, ev.argument);
1218                         dispatch(fr);
1219                 }
1220         }
1221         break;
1222
1223         case LFUN_INSET_INSERT: {
1224                 Inset * inset = createInset(ev);
1225                 if (inset && insertInset(inset)) {
1226                         updateInset(inset);
1227
1228                         string const name = ev.getArg(0);
1229                         if (name == "bibitem") {
1230                                 // We need to do a redraw because the maximum
1231                                 // InsetBibitem width could have changed
1232 #warning please check you mean repaint() not update(),
1233 #warning and whether the repaint() is needed at all
1234                                 bv_->repaint();
1235                                 bv_->fitCursor();
1236                         }
1237                 } else {
1238                         delete inset;
1239                 }
1240         }
1241         break;
1242
1243         case LFUN_FLOAT_LIST:
1244                 if (tclass.floats().typeExist(ev.argument)) {
1245                         Inset * inset = new InsetFloatList(ev.argument);
1246                         if (!insertInset(inset, tclass.defaultLayoutName()))
1247                                 delete inset;
1248                 } else {
1249                         lyxerr << "Non-existent float type: "
1250                                << ev.argument << endl;
1251                 }
1252                 break;
1253
1254         case LFUN_LAYOUT_PARAGRAPH: {
1255                 Paragraph const * par = &*bv_->getLyXText()->cursor.par();
1256                 if (!par)
1257                         break;
1258
1259                 string data;
1260                 params2string(*par, data);
1261
1262                 data = "show\n" + data;
1263                 bv_->owner()->getDialogs().show("paragraph", data);
1264                 break;
1265         }
1266
1267         case LFUN_PARAGRAPH_UPDATE: {
1268                 if (!bv_->owner()->getDialogs().visible("paragraph"))
1269                         break;
1270                 Paragraph const * par = &*bv_->getLyXText()->cursor.par();
1271                 if (!par)
1272                         break;
1273
1274                 string data;
1275                 params2string(*par, data);
1276
1277                 // Will the paragraph accept changes from the dialog?
1278                 Inset * const inset = par->inInset();
1279                 bool const accept =
1280                         !(inset && inset->forceDefaultParagraphs(inset));
1281
1282                 data = "update " + tostr(accept) + '\n' + data;
1283                 bv_->owner()->getDialogs().update("paragraph", data);
1284                 break;
1285         }
1286
1287         case LFUN_PARAGRAPH_APPLY:
1288                 setParagraphParams(*bv_, ev.argument);
1289                 break;
1290
1291         case LFUN_THESAURUS_ENTRY:
1292         {
1293                 string arg = ev.argument;
1294
1295                 if (arg.empty()) {
1296                         arg = bv_->getLyXText()->selectionAsString(buffer_,
1297                                                                    false);
1298
1299                         // FIXME
1300                         if (arg.size() > 100 || arg.empty()) {
1301                                 // Get word or selection
1302                                 bv_->getLyXText()->selectWordWhenUnderCursor(lyx::WHOLE_WORD);
1303                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
1304                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1305                         }
1306                 }
1307
1308                 bv_->owner()->getDialogs().show("thesaurus", arg);
1309         }
1310                 break;
1311
1312         case LFUN_TRACK_CHANGES:
1313                 trackChanges();
1314                 break;
1315
1316         case LFUN_MERGE_CHANGES:
1317                 owner_->getDialogs().show("changes");
1318                 break;
1319
1320         case LFUN_ACCEPT_ALL_CHANGES: {
1321                 update(BufferView::SELECT);
1322                 bv_->text->setCursor(bv_->buffer()->paragraphs.begin(), 0);
1323 #warning FIXME changes
1324                 //moveCursorUpdate(false);
1325
1326                 while (lyxfind::findNextChange(bv_)) {
1327                         bv_->getLyXText()->acceptChange();
1328                 }
1329                 update(BufferView::SELECT);
1330                 break;
1331         }
1332
1333         case LFUN_REJECT_ALL_CHANGES: {
1334                 update(BufferView::SELECT);
1335                 bv_->text->setCursor(bv_->buffer()->paragraphs.begin(), 0);
1336 #warning FIXME changes
1337                 //moveCursorUpdate(false);
1338
1339                 while (lyxfind::findNextChange(bv_)) {
1340                         bv_->getLyXText()->rejectChange();
1341                 }
1342                 update(BufferView::SELECT);
1343                 break;
1344         }
1345
1346         case LFUN_ACCEPT_CHANGE: {
1347                 bv_->getLyXText()->acceptChange();
1348                 update(BufferView::SELECT);
1349                 break;
1350         }
1351
1352         case LFUN_REJECT_CHANGE: {
1353                 bv_->getLyXText()->rejectChange();
1354                 update(BufferView::SELECT);
1355                 break;
1356         }
1357
1358         case LFUN_UNKNOWN_ACTION:
1359                 ev.errorMessage(N_("Unknown function!"));
1360                 break;
1361
1362         default:
1363                 return bv_->getLyXText()->dispatch(FuncRequest(ev, bv_));
1364         } // end of switch
1365
1366         return true;
1367 }
1368
1369
1370 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
1371 {
1372         // if we are in a locking inset we should try to insert the
1373         // inset there otherwise this is a illegal function now
1374         if (bv_->theLockingInset()) {
1375                 if (bv_->theLockingInset()->insetAllowed(inset))
1376                         return bv_->theLockingInset()->insertInset(bv_, inset);
1377                 return false;
1378         }
1379
1380         // not quite sure if we want this...
1381         setCursorParUndo(bv_);
1382         freezeUndo();
1383
1384         beforeChange(bv_->text);
1385         if (!lout.empty()) {
1386                 update(BufferView::SELECT);
1387                 bv_->text->breakParagraph(bv_->buffer()->paragraphs);
1388                 update(BufferView::SELECT);
1389
1390                 if (!bv_->text->cursor.par()->empty()) {
1391                         bv_->text->cursorLeft(bv_);
1392
1393                         bv_->text->breakParagraph(bv_->buffer()->paragraphs);
1394                         update(BufferView::SELECT);
1395                 }
1396
1397                 string lres = lout;
1398                 LyXTextClass const & tclass =
1399                         buffer_->params.getLyXTextClass();
1400                 bool hasLayout = tclass.hasLayout(lres);
1401                 string lay = tclass.defaultLayoutName();
1402
1403                 if (hasLayout != false) {
1404                         // layout found
1405                         lay = lres;
1406                 } else {
1407                         // layout not fount using default
1408                         lay = tclass.defaultLayoutName();
1409                 }
1410
1411                 bv_->text->setLayout(lay);
1412
1413                 bv_->text->setParagraph(0, 0,
1414                                    0, 0,
1415                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
1416                                    Spacing(),
1417                                    LYX_ALIGN_LAYOUT,
1418                                    string(),
1419                                    0);
1420                 update(BufferView::SELECT);
1421         }
1422
1423         bv_->text->insertInset(inset);
1424         update(BufferView::SELECT);
1425
1426         unFreezeUndo();
1427         return true;
1428 }
1429
1430
1431 void BufferView::Pimpl::updateInset(Inset * inset)
1432 {
1433         if (!inset || !available())
1434                 return;
1435
1436         // first check for locking insets
1437         if (bv_->theLockingInset()) {
1438                 if (bv_->theLockingInset() == inset) {
1439                         if (bv_->text->updateInset(inset)) {
1440                                 update();
1441                                 updateScrollbar();
1442                                 return;
1443                         }
1444                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
1445                         if (bv_->text->updateInset(bv_->theLockingInset())) {
1446                                 update();
1447                                 updateScrollbar();
1448                                 return;
1449                         }
1450                 }
1451         }
1452
1453         // then check if the inset is a top_level inset (has no owner)
1454         // if yes do the update as always otherwise we have to update the
1455         // toplevel inset where this inset is inside
1456         Inset * tl_inset = inset;
1457         while (tl_inset->owner())
1458                 tl_inset = tl_inset->owner();
1459         if (tl_inset == inset) {
1460                 update(BufferView::UPDATE);
1461                 if (bv_->text->updateInset(inset)) {
1462                         update(BufferView::SELECT);
1463                         return;
1464                 }
1465         } else if (static_cast<UpdatableInset *>(tl_inset)
1466                            ->updateInsetInInset(bv_, inset))
1467         {
1468                 if (bv_->text->updateInset(tl_inset)) {
1469                         update();
1470                         updateScrollbar();
1471                 }
1472         }
1473 }