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"
14 #include "support/FileName.h"
15 #include "support/lyxlib.h"
16 #include "support/Timeout.h"
18 #include <boost/bind.hpp>
19 #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()
63 void FileMonitor::reset(FileName const & file_with_path) const
65 if (pimpl_->filename_ == file_with_path)
68 bool const monitor = pimpl_->timer_.running();
72 pimpl_->filename_ = file_with_path;
79 FileName const & FileMonitor::filename() const
81 return pimpl_->filename_;
85 void FileMonitor::start() const
90 if (!pimpl_->filename_.exists())
93 pimpl_->timestamp_ = pimpl_->filename_.lastModified();
94 pimpl_->checksum_ = sum(pimpl_->filename_);
96 if (pimpl_->timestamp_ && pimpl_->checksum_) {
97 pimpl_->timer_.start();
99 pimpl_->timestamp_ = 0;
100 pimpl_->checksum_ = 0;
105 void FileMonitor::stop() const
107 pimpl_->timestamp_ = 0;
108 pimpl_->checksum_ = 0;
109 pimpl_->timer_.stop();
113 bool FileMonitor::monitoring() const
115 return pimpl_->timer_.running();
119 unsigned long FileMonitor::checksum() const
121 // If we aren't actively monitoring the file, then recompute the
122 // checksum explicitly.
123 if (!pimpl_->timer_.running() && !pimpl_->filename_.empty())
124 return sum(pimpl_->filename_);
126 return pimpl_->checksum_;
130 boost::signals::connection FileMonitor::connect(slot_type const & slot) const
132 return pimpl_->fileChanged_.connect(slot);
136 //------------------------------
137 // Implementation details follow
138 //------------------------------
141 FileMonitor::Impl::Impl(FileName const & file_with_path, int interval)
142 : filename_(file_with_path),
143 timer_(interval, Timeout::ONETIME),
147 timer_.timeout.connect(boost::bind(&Impl::monitorFile, this));
151 void FileMonitor::Impl::monitorFile()
153 bool changed = false;
155 if (!filename_.exists()) {
156 changed = timestamp_ || checksum_;
161 time_t const new_timestamp = filename_.lastModified();
163 if (new_timestamp != timestamp_) {
164 timestamp_ = new_timestamp;
166 unsigned long const new_checksum = sum(filename_);
167 if (new_checksum != checksum_) {
168 checksum_ = new_checksum;
179 } // namespace support