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 "support/FileMonitor.h"
14 #include "support/FileInfo.h"
15 #include "support/lyxlib.h"
17 // FIXME Interface violation
18 #include "frontends/Timeout.h"
20 #include <boost/bind.hpp>
21 #include <boost/signals/trackable.hpp>
30 class FileMonitor::Impl : public boost::signals::trackable {
34 Impl(string const & file_with_path, int interval);
45 /// This signal is emitted if the file is modified (has a new checksum).
46 FileMonitor::FileChangedSig fileChanged_;
48 /** We use these to ascertain whether a file (once loaded successfully)
53 unsigned long checksum_;
57 FileMonitor::FileMonitor(string const & file_with_path, int interval)
58 : pimpl_(new Impl(file_with_path, interval))
62 FileMonitor::~FileMonitor()
66 void FileMonitor::reset(string const & file_with_path) const
68 if (pimpl_->filename_ == file_with_path)
71 bool const monitor = pimpl_->timer_.running();
75 pimpl_->filename_ = file_with_path;
82 string const & FileMonitor::filename() const
84 return pimpl_->filename_;
88 void FileMonitor::start() const
93 FileInfo finfo(pimpl_->filename_);
97 pimpl_->timestamp_ = finfo.getModificationTime();
98 pimpl_->checksum_ = sum(pimpl_->filename_);
100 if (pimpl_->timestamp_ && pimpl_->checksum_) {
101 pimpl_->timer_.start();
103 pimpl_->timestamp_ = 0;
104 pimpl_->checksum_ = 0;
109 void FileMonitor::stop() const
111 pimpl_->timestamp_ = 0;
112 pimpl_->checksum_ = 0;
113 pimpl_->timer_.stop();
117 bool FileMonitor::monitoring() const
119 return pimpl_->timer_.running();
123 unsigned long FileMonitor::checksum() const
125 // If we aren't actively monitoring the file, then recompute the
126 // checksum explicitly.
127 if (!pimpl_->timer_.running() && !pimpl_->filename_.empty())
128 return sum(pimpl_->filename_);
130 return pimpl_->checksum_;
134 boost::signals::connection FileMonitor::connect(slot_type const & slot) const
136 return pimpl_->fileChanged_.connect(slot);
140 //------------------------------
141 // Implementation details follow
142 //------------------------------
145 FileMonitor::Impl::Impl(string const & file_with_path, int interval)
146 : filename_(file_with_path),
147 timer_(interval, Timeout::ONETIME),
151 timer_.timeout.connect(boost::bind(&Impl::monitorFile, this));
155 void FileMonitor::Impl::monitorFile()
157 bool changed = false;
159 FileInfo finfo(filename_);
161 changed = timestamp_ || checksum_;
166 time_t const new_timestamp = finfo.getModificationTime();
168 if (new_timestamp != timestamp_) {
169 timestamp_ = new_timestamp;
171 unsigned long const new_checksum = sum(filename_);
172 if (new_checksum != checksum_) {
173 checksum_ = new_checksum;
184 } // namespace support