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>
28 class FileMonitor::Impl : public boost::signals::trackable {
32 Impl(FileName const & file_with_path, int interval);
43 /// This signal is emitted if the file is modified (has a new checksum).
44 FileMonitor::FileChangedSig fileChanged_;
46 /** We use these to ascertain whether a file (once loaded successfully)
51 unsigned long checksum_;
55 FileMonitor::FileMonitor(FileName const & file_with_path, int interval)
56 : pimpl_(new Impl(file_with_path, interval))
60 FileMonitor::~FileMonitor()
66 void FileMonitor::reset(FileName 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 FileName const & FileMonitor::filename() const
84 return pimpl_->filename_;
88 void FileMonitor::start() const
93 if (!pimpl_->filename_.exists())
96 pimpl_->timestamp_ = pimpl_->filename_.lastModified();
97 pimpl_->checksum_ = pimpl_->filename_.checksum();
99 if (pimpl_->timestamp_ && pimpl_->checksum_) {
100 pimpl_->timer_.start();
102 pimpl_->timestamp_ = 0;
103 pimpl_->checksum_ = 0;
108 void FileMonitor::stop() const
110 pimpl_->timestamp_ = 0;
111 pimpl_->checksum_ = 0;
112 pimpl_->timer_.stop();
116 bool FileMonitor::monitoring() const
118 return pimpl_->timer_.running();
122 unsigned long FileMonitor::checksum() const
124 // If we aren't actively monitoring the file, then recompute the
125 // checksum explicitly.
126 if (!pimpl_->timer_.running() && !pimpl_->filename_.empty())
127 return pimpl_->filename_.checksum();
129 return pimpl_->checksum_;
133 boost::signals::connection FileMonitor::connect(slot_type const & slot) const
135 return pimpl_->fileChanged_.connect(slot);
139 //------------------------------
140 // Implementation details follow
141 //------------------------------
144 FileMonitor::Impl::Impl(FileName const & file_with_path, int interval)
145 : filename_(file_with_path),
146 timer_(interval, Timeout::ONETIME),
150 timer_.timeout.connect(boost::bind(&Impl::monitorFile, this));
154 void FileMonitor::Impl::monitorFile()
156 bool changed = false;
158 if (!filename_.exists()) {
159 changed = timestamp_ || checksum_;
164 time_t const new_timestamp = filename_.lastModified();
166 if (new_timestamp != timestamp_) {
167 timestamp_ = new_timestamp;
169 unsigned long const new_checksum = filename_.checksum();
170 if (new_checksum != checksum_) {
171 checksum_ = new_checksum;
182 } // namespace support