2 * \file FileMonitor.cpp
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"
15 #include "support/FileName.h"
16 #include "support/lyxlib.h"
17 #include "support/Timeout.h"
19 #include <boost/bind.hpp>
20 #include <boost/signals/trackable.hpp>
27 class FileMonitor::Impl : public boost::signals::trackable {
31 Impl(FileName const & file_with_path, int interval);
42 /// This signal is emitted if the file is modified (has a new checksum).
43 FileMonitor::FileChangedSig fileChanged_;
45 /** We use these to ascertain whether a file (once loaded successfully)
50 unsigned long checksum_;
54 FileMonitor::FileMonitor(FileName const & file_with_path, int interval)
55 : pimpl_(new Impl(file_with_path, interval))
59 FileMonitor::~FileMonitor()
65 void FileMonitor::reset(FileName const & file_with_path) const
67 if (pimpl_->filename_ == file_with_path)
70 bool const monitor = pimpl_->timer_.running();
74 pimpl_->filename_ = file_with_path;
81 FileName const & FileMonitor::filename() const
83 return pimpl_->filename_;
87 void FileMonitor::start() const
92 if (!pimpl_->filename_.exists())
95 pimpl_->timestamp_ = pimpl_->filename_.lastModified();
96 pimpl_->checksum_ = pimpl_->filename_.checksum();
98 if (pimpl_->timestamp_ && pimpl_->checksum_) {
99 pimpl_->timer_.start();
101 pimpl_->timestamp_ = 0;
102 pimpl_->checksum_ = 0;
107 void FileMonitor::stop() const
109 pimpl_->timestamp_ = 0;
110 pimpl_->checksum_ = 0;
111 pimpl_->timer_.stop();
115 bool FileMonitor::monitoring() const
117 return pimpl_->timer_.running();
121 unsigned long FileMonitor::checksum() const
123 // If we aren't actively monitoring the file, then recompute the
124 // checksum explicitly.
125 if (!pimpl_->timer_.running() && !pimpl_->filename_.empty())
126 return pimpl_->filename_.checksum();
128 return pimpl_->checksum_;
132 boost::signals::connection FileMonitor::connect(slot_type const & slot) const
134 return pimpl_->fileChanged_.connect(slot);
138 //------------------------------
139 // Implementation details follow
140 //------------------------------
143 FileMonitor::Impl::Impl(FileName const & file_with_path, int interval)
144 : filename_(file_with_path),
145 timer_(interval, Timeout::ONETIME),
149 timer_.timeout.connect(boost::bind(&Impl::monitorFile, this));
153 void FileMonitor::Impl::monitorFile()
155 bool changed = false;
157 if (!filename_.exists()) {
158 changed = timestamp_ || checksum_;
163 time_t const new_timestamp = filename_.lastModified();
165 if (new_timestamp != timestamp_) {
166 timestamp_ = new_timestamp;
168 unsigned long const new_checksum = filename_.checksum();
169 if (new_checksum != checksum_) {
170 checksum_ = new_checksum;
181 } // namespace support