3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
8 * Full author contact details are available in file CREDITS
13 #include "FileMonitor.h"
15 #include "frontends/Timeout.h"
17 #include "support/FileInfo.h"
18 #include "support/lyxlib.h"
20 #include <boost/bind.hpp>
21 #include <boost/signals/trackable.hpp>
23 struct FileMonitor::Impl : public boost::signals::trackable {
26 Impl(string const & file_with_path, int interval);
37 /// This signal is emitted if the file is modified (has a new checksum).
38 boost::signal0<void> fileChanged_;
40 /** We use these to ascertain whether a file (once loaded successfully)
45 unsigned long checksum_;
49 FileMonitor::FileMonitor(string const & file_with_path, int interval)
50 : pimpl_(new Impl(file_with_path, interval))
54 FileMonitor::~FileMonitor()
58 void FileMonitor::reset(string const & file_with_path) const
60 if (pimpl_->filename_ == file_with_path)
63 bool const monitor = pimpl_->timer_.running();
67 pimpl_->filename_ = file_with_path;
74 string const & FileMonitor::filename() const
76 return pimpl_->filename_;
80 void FileMonitor::start() const
85 FileInfo finfo(pimpl_->filename_);
89 pimpl_->timestamp_ = finfo.getModificationTime();
90 pimpl_->checksum_ = lyx::sum(pimpl_->filename_);
92 if (pimpl_->timestamp_ && pimpl_->checksum_) {
93 pimpl_->timer_.start();
95 pimpl_->timestamp_ = 0;
96 pimpl_->checksum_ = 0;
101 void FileMonitor::stop() const
103 pimpl_->timestamp_ = 0;
104 pimpl_->checksum_ = 0;
105 pimpl_->timer_.stop();
109 bool FileMonitor::monitoring() const
111 return pimpl_->timer_.running();
115 unsigned long FileMonitor::checksum() const
117 // If we aren't actively monitoring the file, then recompute the
118 // checksum explicitly.
119 if (!pimpl_->timer_.running() && !pimpl_->filename_.empty())
120 return lyx::sum(pimpl_->filename_);
122 return pimpl_->checksum_;
126 boost::signals::connection FileMonitor::connect(slot_type const & slot) const
128 return pimpl_->fileChanged_.connect(slot);
132 //------------------------------
133 // Implementation details follow
134 //------------------------------
137 FileMonitor::Impl::Impl(string const & file_with_path, int interval)
138 : filename_(file_with_path),
139 timer_(interval, Timeout::ONETIME),
143 timer_.timeout.connect(boost::bind(&Impl::monitorFile, this));
147 void FileMonitor::Impl::monitorFile()
149 bool changed = false;
151 FileInfo finfo(filename_);
153 changed = timestamp_ || checksum_;
158 time_t const new_timestamp = finfo.getModificationTime();
160 if (new_timestamp != timestamp_) {
161 timestamp_ = new_timestamp;
163 unsigned long const new_checksum = lyx::sum(filename_);
164 if (new_checksum != checksum_) {
165 checksum_ = new_checksum;