]> git.lyx.org Git - lyx.git/blob - src/frontends/LyXView.cpp
Fix bug 4096. Don't disconnect the buffer until we're ready to connect again.
[lyx.git] / src / frontends / LyXView.cpp
1 /**
2  * \file LyXView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "LyXView.h"
15 #include "Dialogs.h"
16 #include "Timeout.h"
17 #include "Toolbars.h"
18 #include "Menubar.h"
19 #include "WorkArea.h"
20 #include "Gui.h"
21
22 #include "Buffer.h"
23 #include "buffer_funcs.h"
24 #include "BufferList.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "bufferview_funcs.h"
28 #include "Cursor.h"
29 #include "debug.h"
30 #include "ErrorList.h"
31 #include "FuncRequest.h"
32 #include "gettext.h"
33 #include "Intl.h"
34 #include "callback.h"
35 #include "LyX.h"
36 #include "LyXFunc.h"
37 #include "LyXRC.h"
38 #include "Text.h"
39 #include "MenuBackend.h"
40 #include "Paragraph.h"
41
42 #include "controllers/ControlCommandBuffer.h"
43
44 #include "support/lstrings.h"
45 #include "support/filetools.h" // OnlyFilename()
46
47 #include <boost/bind.hpp>
48
49
50 namespace lyx {
51
52 #ifdef HAVE_SYS_TIME_H
53 # include <sys/time.h>
54 #endif
55 #ifdef HAVE_UNISTD_H
56 # include <unistd.h>
57 #endif
58
59 using frontend::WorkArea;
60
61 using support::bformat;
62 using support::FileName;
63 using support::makeDisplayPath;
64 using support::onlyFilename;
65
66 using std::endl;
67 using std::string;
68
69 using lyx::frontend::ControlCommandBuffer;
70
71 docstring current_layout;
72
73
74 LyXView::LyXView(int id)
75         : work_area_(0),
76           toolbars_(new Toolbars(*this)),
77           autosave_timeout_(new Timeout(5000)),
78           dialogs_(new Dialogs(*this)),
79           controlcommand_(new ControlCommandBuffer(*this)), id_(id)
80 {
81         // Start autosave timer
82         if (lyxrc.autosave) {
83                 autosave_timeout_->timeout.connect(boost::bind(&LyXView::autoSave, this));
84                 autosave_timeout_->setTimeout(lyxrc.autosave * 1000);
85                 autosave_timeout_->start();
86         }
87 }
88
89
90 LyXView::~LyXView()
91 {
92         disconnectBuffer();
93 }
94
95
96 // FIXME, there's only one WorkArea per LyXView possible for now.
97 void LyXView::setWorkArea(WorkArea * work_area)
98 {
99         BOOST_ASSERT(work_area);
100         work_area_ = work_area;
101         work_area_ids_.clear();
102         work_area_ids_.push_back(work_area_->id());
103 }
104
105
106 // FIXME, there's only one WorkArea per LyXView possible for now.
107 WorkArea const * LyXView::currentWorkArea() const
108 {
109         return work_area_;
110 }
111
112
113 // FIXME, there's only one WorkArea per LyXView possible for now.
114 WorkArea * LyXView::currentWorkArea()
115 {
116         return work_area_;
117 }
118
119
120 Buffer * LyXView::buffer() const
121 {
122         BOOST_ASSERT(work_area_);
123         return work_area_->bufferView().buffer();
124 }
125
126
127 void LyXView::setBuffer(Buffer * b, bool child_document)
128 {
129         busy(true);
130
131         BOOST_ASSERT(work_area_);
132         Buffer * oldBuffer = work_area_->bufferView().buffer();
133         // parentfilename will be used in case when we switch to a child
134         // document (hence when child_document is true)
135         string parentfilename;
136         if (oldBuffer)
137                 parentfilename = oldBuffer->fileName();
138
139         if (!b && theBufferList().empty())
140                 getDialogs().hideBufferDependent();
141
142         Buffer * newBuffer = work_area_->bufferView().setBuffer(b);
143
144         if (newBuffer) {
145                 //Are we closing an oldBuffer which was a child document?
146                 if (!b && oldBuffer && oldBuffer->getMasterBuffer() != oldBuffer)
147                         // Update the labels and section numbering of its master Buffer.
148                         updateLabels(*oldBuffer->getMasterBuffer());
149                 //Are we opening a new child document?
150                 else if (child_document && newBuffer->getMasterBuffer() != oldBuffer) {
151                         // Set the parent name of the child document.
152                         // This makes insertion of citations and references in the child work,
153                         // when the target is in the parent or another child document.
154                         newBuffer->setParentName(parentfilename);
155                         // Update the labels and section numbering to the new master Buffer.
156                         updateLabels(*newBuffer->getMasterBuffer());
157                 }
158                 //Now that all the updating of the old buffer has been done, we can
159                 //connect the new buffer. Note that this will also disconnect the old 
160                 //buffer, if such there is.
161                 //FIXME Is it clear that this should go right here? Or should it go
162                 //earlier before the previous if (in which case we'd remove the "else")?
163                 connectBuffer(*newBuffer);
164
165                 /* FIXME: We need to rebuild the Toc dialog before the others even
166                 if it will be rebuilt again in the next line. This avoid a crash when
167                 other dialogs are rebuilt before the Toc dialog. The reason is
168                 that closing a Buffer triggers an update of all opened dialogs
169                 when dispatching LFUN_DIALOG_UPDATE (hence the patch).
170                 The path is as following:
171                         setBuffer() -> updateBufferDependent() -> RestoreButton() -> LFUN
172                 The problem here is that the Toc dialog has not been
173                 reconstructed (because it comes after in the list of dialogs). */
174                 updateToc();
175
176                 // Buffer-dependent dialogs should be updated or
177                 // hidden. This should go here because some dialogs (eg ToC)
178                 // require bv_->text.
179                 getDialogs().updateBufferDependent(true);
180         } else
181                 //Disconnect the old buffer...there's no new one.
182                 disconnectBuffer();
183
184         if (quitting)
185                 return;
186
187         updateMenubar();
188         updateToolbars();
189         updateLayoutChoice();
190         updateWindowTitle();
191         updateStatusBar();
192         updateTab();
193         busy(false);
194         work_area_->redraw();
195 }
196
197
198 bool LyXView::loadLyXFile(FileName const & filename, bool tolastfiles,
199                 bool child_document, bool auto_open)
200 {
201         busy(true);
202
203         BOOST_ASSERT(work_area_);
204         string parentfilename;
205         Buffer * oldBuffer = work_area_->bufferView().buffer();
206         if (oldBuffer)
207                 parentfilename = oldBuffer->fileName();
208
209         Buffer * newBuffer = checkAndLoadLyXFile(filename);
210
211         if (!newBuffer) {
212                 message(_("Document not loaded."));
213                 updateStatusBar();
214                 busy(false);
215                 work_area_->redraw();
216                 return false;
217         }
218
219         if (child_document && newBuffer != oldBuffer) {
220                 // Set the parent name of the child document.
221                 // This makes insertion of citations and references in the child work,
222                 // when the target is in the parent or another child document.
223                 newBuffer->setParentName(parentfilename);
224                 message(bformat(_("Opening child document %1$s..."),
225                         makeDisplayPath(filename.absFilename())));
226         }
227
228         // Update the labels and section numbering.
229         updateLabels(*newBuffer->getMasterBuffer());
230
231         bool const parse_error = !newBuffer->errorList("Parse").empty();
232         if (parse_error || !auto_open) {
233                 setBuffer(newBuffer, child_document);
234                 showErrorList("Parse");
235         }
236
237         // scroll to the position when the file was last closed
238         if (!auto_open && lyxrc.use_lastfilepos) {
239                 pit_type pit;
240                 pos_type pos;
241                 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
242                 // if successfully move to pit (returned par_id is not zero),
243                 // update metrics and reset font
244                 if (work_area_->bufferView().moveToPosition(pit, pos, 0, 0).get<1>()) {
245                         if (work_area_->bufferView().fitCursor())
246                                 work_area_->bufferView().updateMetrics(false);
247                         newBuffer->text().setCurrentFont(work_area_->bufferView().cursor());
248                         updateMenubar();
249                         updateToolbars();
250                         updateLayoutChoice();
251                         updateStatusBar();
252                         work_area_->redraw();
253                 }
254         }
255
256         if (tolastfiles)
257                 LyX::ref().session().lastFiles().add(filename);
258
259         busy(false);
260         return true;
261 }
262
263
264 void LyXView::connectBuffer(Buffer & buf)
265 {
266         if (errorsConnection_.connected())
267                 disconnectBuffer();
268
269         BOOST_ASSERT(work_area_);
270         bufferChangedConnection_ =
271                 buf.changed.connect(
272                         boost::bind(&WorkArea::redraw, work_area_));
273
274         bufferStructureChangedConnection_ =
275                 buf.getMasterBuffer()->structureChanged.connect(
276                         boost::bind(&LyXView::updateToc, this));
277
278         errorsConnection_ =
279                 buf.errors.connect(
280                         boost::bind(&LyXView::showErrorList, this, _1));
281
282         messageConnection_ =
283                 buf.message.connect(
284                         boost::bind(&LyXView::message, this, _1));
285
286         busyConnection_ =
287                 buf.busy.connect(
288                         boost::bind(&LyXView::busy, this, _1));
289
290         titleConnection_ =
291                 buf.updateTitles.connect(
292                         boost::bind(&LyXView::updateWindowTitle, this));
293
294         timerConnection_ =
295                 buf.resetAutosaveTimers.connect(
296                         boost::bind(&LyXView::resetAutosaveTimer, this));
297
298         readonlyConnection_ =
299                 buf.readonly.connect(
300                         boost::bind(&LyXView::showReadonly, this, _1));
301
302         closingConnection_ =
303                 buf.closing.connect(
304                         boost::bind(&LyXView::setBuffer, this, (Buffer *)0, false));
305 }
306
307
308 void LyXView::disconnectBuffer()
309 {
310         errorsConnection_.disconnect();
311         bufferChangedConnection_.disconnect();
312         bufferStructureChangedConnection_.disconnect();
313         messageConnection_.disconnect();
314         busyConnection_.disconnect();
315         titleConnection_.disconnect();
316         timerConnection_.disconnect();
317         readonlyConnection_.disconnect();
318         closingConnection_.disconnect();
319         layout_changed_connection_.disconnect();
320 }
321
322
323 void LyXView::connectBufferView(BufferView & bv)
324 {
325         show_dialog_connection_ = bv.showDialog.connect(
326                         boost::bind(&LyXView::showDialog, this, _1));
327         show_dialog_with_data_connection_ = bv.showDialogWithData.connect(
328                         boost::bind(&LyXView::showDialogWithData, this, _1, _2));
329         show_inset_dialog_connection_ = bv.showInsetDialog.connect(
330                         boost::bind(&LyXView::showInsetDialog, this, _1, _2, _3));
331         update_dialog_connection_ = bv.updateDialog.connect(
332                         boost::bind(&LyXView::updateDialog, this, _1, _2));
333         layout_changed_connection_ = bv.layoutChanged.connect(
334                         boost::bind(&Toolbars::setLayout, toolbars_.get(), _1));
335 }
336
337
338 void LyXView::disconnectBufferView()
339 {
340         show_dialog_connection_.disconnect();
341         show_dialog_with_data_connection_.disconnect();
342         show_inset_dialog_connection_.disconnect();
343         update_dialog_connection_.disconnect();
344 }
345
346
347 void LyXView::showErrorList(string const & error_type)
348 {
349         ErrorList & el = buffer()->errorList(error_type);
350         if (!el.empty()) {
351                 getDialogs().show("errorlist", error_type);
352         }
353 }
354
355
356 void LyXView::showDialog(string const & name)
357 {
358         getDialogs().show(name);
359 }
360
361
362 void LyXView::showDialogWithData(string const & name, string const & data)
363 {
364         getDialogs().show(name, data);
365 }
366
367
368 void LyXView::showInsetDialog(string const & name, string const & data,
369                 Inset * inset)
370 {
371         getDialogs().show(name, data, inset);
372 }
373
374
375 void LyXView::updateDialog(string const & name, string const & data)
376 {
377         if (getDialogs().visible(name))
378                 getDialogs().update(name, data);
379 }
380
381
382 void LyXView::showReadonly(bool)
383 {
384         updateWindowTitle();
385         getDialogs().updateBufferDependent(false);
386 }
387
388
389 BufferView * LyXView::view() const
390 {
391         BOOST_ASSERT(work_area_);
392         return &work_area_->bufferView();
393 }
394
395
396 void LyXView::updateToc()
397 {
398         updateDialog("toc", "");
399 }
400
401
402 void LyXView::updateToolbars()
403 {
404         BOOST_ASSERT(work_area_);
405         bool const math =
406                 work_area_->bufferView().cursor().inMathed();
407         bool const table =
408                 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
409         bool const review =
410                 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
411                 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
412
413         toolbars_->update(math, table, review);
414         // update redaonly status of open dialogs. This could also be in
415         // updateMenubar(), but since updateToolbars() and updateMenubar()
416         // are always called together it is only here.
417         getDialogs().checkStatus();
418 }
419
420
421 ToolbarInfo * LyXView::getToolbarInfo(string const & name)
422 {
423         return toolbars_->getToolbarInfo(name);
424 }
425
426
427 void LyXView::toggleToolbarState(string const & name, bool allowauto)
428 {
429         // it is possible to get current toolbar status like this,...
430         // but I decide to obey the order of ToolbarBackend::flags
431         // and disregard real toolbar status.
432         // toolbars_->saveToolbarInfo();
433         //
434         // toggle state on/off/auto
435         toolbars_->toggleToolbarState(name, allowauto);
436         // update toolbar
437         updateToolbars();
438 }
439
440
441 void LyXView::updateMenubar()
442 {
443         menubar_->update();
444 }
445
446
447 void LyXView::autoSave()
448 {
449         LYXERR(Debug::INFO) << "Running autoSave()" << endl;
450
451         if (view()->buffer())
452                 lyx::autoSave(view());
453 }
454
455
456 void LyXView::resetAutosaveTimer()
457 {
458         if (lyxrc.autosave)
459                 autosave_timeout_->restart();
460 }
461
462
463 void LyXView::updateLayoutChoice()
464 {
465         // Don't show any layouts without a buffer
466         if (!view()->buffer()) {
467                 toolbars_->clearLayoutList();
468                 return;
469         }
470
471         // Update the layout display
472         if (toolbars_->updateLayoutList(buffer()->params().textclass)) {
473                 current_layout = buffer()->params().getTextClass().defaultLayoutName();
474         }
475
476         BOOST_ASSERT(work_area_);
477         docstring const & layout = work_area_->bufferView().cursor().
478                 innerParagraph().layout()->name();
479
480         if (layout != current_layout) {
481                 toolbars_->setLayout(layout);
482                 current_layout = layout;
483         }
484 }
485
486
487 void LyXView::updateWindowTitle()
488 {
489         docstring maximize_title = lyx::from_ascii("LyX");
490         docstring minimize_title = lyx::from_ascii("LyX");
491
492         if (view()->buffer()) {
493                 string const cur_title = buffer()->fileName();
494                 if (!cur_title.empty()) {
495                         maximize_title += ": " + makeDisplayPath(cur_title, 30);
496                         minimize_title = lyx::from_utf8(onlyFilename(cur_title));
497                         if (!buffer()->isClean()) {
498                                 maximize_title += _(" (changed)");
499                                 minimize_title += lyx::char_type('*');
500                         }
501                         if (buffer()->isReadonly())
502                                 maximize_title += _(" (read only)");
503                 }
504         }
505
506         setWindowTitle(maximize_title, minimize_title);
507         updateTab();
508 }
509
510
511 void LyXView::dispatch(FuncRequest const & cmd)
512 {
513         theLyXFunc().setLyXView(this);
514         lyx::dispatch(cmd);
515 }
516
517
518 Buffer const * const LyXView::updateInset(Inset const * inset) const
519 {
520         Buffer const * buffer_ptr = 0;
521         if (inset) {
522                 BOOST_ASSERT(work_area_);
523                 work_area_->scheduleRedraw();
524
525                 buffer_ptr = work_area_->bufferView().buffer();
526         }
527         return buffer_ptr;
528 }
529
530
531 } // namespace lyx