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