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