FileWatcher.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../IO/File.h"
  24. #include "../IO/FileSystem.h"
  25. #include "../IO/FileWatcher.h"
  26. #include "../IO/Log.h"
  27. #ifdef WIN32
  28. #include <windows.h>
  29. #elif __linux__
  30. #include <sys/inotify.h>
  31. extern "C"
  32. {
  33. // Need read/close for inotify
  34. #include "unistd.h"
  35. }
  36. #elif defined(__APPLE__) && !defined(IOS)
  37. extern "C"
  38. {
  39. #include "../IO/MacFileWatcher.h"
  40. }
  41. #endif
  42. namespace Atomic
  43. {
  44. #ifndef __APPLE__
  45. static const unsigned BUFFERSIZE = 4096;
  46. #endif
  47. FileWatcher::FileWatcher(Context* context) :
  48. Object(context),
  49. fileSystem_(GetSubsystem<FileSystem>()),
  50. delay_(1.0f),
  51. watchSubDirs_(false)
  52. {
  53. #if defined(ATOMIC_FILEWATCHER)
  54. #if defined(__linux__)
  55. watchHandle_ = inotify_init();
  56. #elif defined(__APPLE__) && !defined(IOS)
  57. supported_ = IsFileWatcherSupported();
  58. #endif
  59. #endif
  60. }
  61. FileWatcher::~FileWatcher()
  62. {
  63. StopWatching();
  64. #if defined(ATOMIC_FILEWATCHER)
  65. #if defined(__linux__)
  66. close(watchHandle_);
  67. #endif
  68. #endif
  69. }
  70. bool FileWatcher::StartWatching(const String& pathName, bool watchSubDirs)
  71. {
  72. if (!fileSystem_)
  73. {
  74. LOGERROR("No FileSystem, can not start watching");
  75. return false;
  76. }
  77. // Stop any previous watching
  78. StopWatching();
  79. #if defined(ATOMIC_FILEWATCHER)
  80. #if defined(WIN32)
  81. String nativePath = GetNativePath(RemoveTrailingSlash(pathName));
  82. // ATOMIC BEGIN
  83. // Create a dummy file to make sure the path is writeable, otherwise we would hang at exit
  84. // This isn't terribly elegant, though avoids a cluser of Windows security API
  85. String dummyFileName = nativePath + "/" + "dummy.tmp";
  86. File file(context_, dummyFileName, FILE_WRITE);
  87. if (file.IsOpen())
  88. {
  89. file.Close();
  90. if (fileSystem_)
  91. fileSystem_->Delete(dummyFileName);
  92. }
  93. else
  94. {
  95. LOGDEBUGF("FileWatcher::StartWatching - Ignoring non-writable path %s", nativePath.CString());
  96. return false;
  97. }
  98. // ATOMIC END
  99. dirHandle_ = (void*)CreateFileW(
  100. WString(nativePath).CString(),
  101. FILE_LIST_DIRECTORY,
  102. FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
  103. 0,
  104. OPEN_EXISTING,
  105. FILE_FLAG_BACKUP_SEMANTICS,
  106. 0);
  107. if (dirHandle_ != INVALID_HANDLE_VALUE)
  108. {
  109. path_ = AddTrailingSlash(pathName);
  110. watchSubDirs_ = watchSubDirs;
  111. Run();
  112. LOGDEBUG("Started watching path " + pathName);
  113. return true;
  114. }
  115. else
  116. {
  117. LOGERROR("Failed to start watching path " + pathName);
  118. return false;
  119. }
  120. #elif defined(__linux__)
  121. int flags = IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO;
  122. int handle = inotify_add_watch(watchHandle_, pathName.CString(), (uint32_t)flags);
  123. if (handle < 0)
  124. {
  125. LOGERROR("Failed to start watching path " + pathName);
  126. return false;
  127. }
  128. else
  129. {
  130. // Store the root path here when reconstructed with inotify later
  131. dirHandle_[handle] = "";
  132. path_ = AddTrailingSlash(pathName);
  133. watchSubDirs_ = watchSubDirs;
  134. if (watchSubDirs_)
  135. {
  136. Vector<String> subDirs;
  137. fileSystem_->ScanDir(subDirs, pathName, "*", SCAN_DIRS, true);
  138. for (unsigned i = 0; i < subDirs.Size(); ++i)
  139. {
  140. String subDirFullPath = AddTrailingSlash(path_ + subDirs[i]);
  141. // Don't watch ./ or ../ sub-directories
  142. if (!subDirFullPath.EndsWith("./"))
  143. {
  144. handle = inotify_add_watch(watchHandle_, subDirFullPath.CString(), (uint32_t)flags);
  145. if (handle < 0)
  146. LOGERROR("Failed to start watching subdirectory path " + subDirFullPath);
  147. else
  148. {
  149. // Store sub-directory to reconstruct later from inotify
  150. dirHandle_[handle] = AddTrailingSlash(subDirs[i]);
  151. }
  152. }
  153. }
  154. }
  155. Run();
  156. LOGDEBUG("Started watching path " + pathName);
  157. return true;
  158. }
  159. #elif defined(__APPLE__) && !defined(IOS)
  160. if (!supported_)
  161. {
  162. LOGERROR("Individual file watching not supported by this OS version, can not start watching path " + pathName);
  163. return false;
  164. }
  165. watcher_ = CreateFileWatcher(pathName.CString(), watchSubDirs);
  166. if (watcher_)
  167. {
  168. path_ = AddTrailingSlash(pathName);
  169. watchSubDirs_ = watchSubDirs;
  170. Run();
  171. LOGDEBUG("Started watching path " + pathName);
  172. return true;
  173. }
  174. else
  175. {
  176. LOGERROR("Failed to start watching path " + pathName);
  177. return false;
  178. }
  179. #else
  180. LOGERROR("FileWatcher not implemented, can not start watching path " + pathName);
  181. return false;
  182. #endif
  183. #else
  184. LOGDEBUG("FileWatcher feature not enabled");
  185. return false;
  186. #endif
  187. }
  188. void FileWatcher::StopWatching()
  189. {
  190. if (handle_)
  191. {
  192. shouldRun_ = false;
  193. // Create and delete a dummy file to make sure the watcher loop terminates
  194. String dummyFileName = path_ + "dummy.tmp";
  195. File file(context_, dummyFileName, FILE_WRITE);
  196. file.Close();
  197. if (fileSystem_)
  198. fileSystem_->Delete(dummyFileName);
  199. Stop();
  200. #if defined(WIN32)
  201. CloseHandle((HANDLE)dirHandle_);
  202. #elif defined(__linux__)
  203. for (HashMap<int, String>::Iterator i = dirHandle_.Begin(); i != dirHandle_.End(); ++i)
  204. inotify_rm_watch(watchHandle_, i->first_);
  205. dirHandle_.Clear();
  206. #elif defined(__APPLE__) && !defined(IOS)
  207. CloseFileWatcher(watcher_);
  208. #endif
  209. LOGDEBUG("Stopped watching path " + path_);
  210. path_.Clear();
  211. }
  212. }
  213. void FileWatcher::SetDelay(float interval)
  214. {
  215. delay_ = Max(interval, 0.0f);
  216. }
  217. void FileWatcher::ThreadFunction()
  218. {
  219. #if defined(ATOMIC_FILEWATCHER)
  220. #if defined(WIN32)
  221. unsigned char buffer[BUFFERSIZE];
  222. DWORD bytesFilled = 0;
  223. while (shouldRun_)
  224. {
  225. if (ReadDirectoryChangesW((HANDLE)dirHandle_,
  226. buffer,
  227. BUFFERSIZE,
  228. watchSubDirs_,
  229. FILE_NOTIFY_CHANGE_FILE_NAME |
  230. FILE_NOTIFY_CHANGE_LAST_WRITE,
  231. &bytesFilled,
  232. 0,
  233. 0))
  234. {
  235. unsigned offset = 0;
  236. while (offset < bytesFilled)
  237. {
  238. FILE_NOTIFY_INFORMATION* record = (FILE_NOTIFY_INFORMATION*)&buffer[offset];
  239. if (record->Action == FILE_ACTION_MODIFIED || record->Action == FILE_ACTION_RENAMED_NEW_NAME)
  240. {
  241. String fileName;
  242. const wchar_t* src = record->FileName;
  243. const wchar_t* end = src + record->FileNameLength / 2;
  244. while (src < end)
  245. fileName.AppendUTF8(String::DecodeUTF16(src));
  246. fileName = GetInternalPath(fileName);
  247. AddChange(fileName);
  248. }
  249. if (!record->NextEntryOffset)
  250. break;
  251. else
  252. offset += record->NextEntryOffset;
  253. }
  254. }
  255. }
  256. #elif defined(__linux__)
  257. unsigned char buffer[BUFFERSIZE];
  258. while (shouldRun_)
  259. {
  260. int i = 0;
  261. int length = (int)read(watchHandle_, buffer, sizeof(buffer));
  262. if (length < 0)
  263. return;
  264. while (i < length)
  265. {
  266. inotify_event* event = (inotify_event*)&buffer[i];
  267. if (event->len > 0)
  268. {
  269. if (event->mask & IN_MODIFY || event->mask & IN_MOVE)
  270. {
  271. String fileName;
  272. fileName = dirHandle_[event->wd] + event->name;
  273. AddChange(fileName);
  274. }
  275. }
  276. i += sizeof(inotify_event) + event->len;
  277. }
  278. }
  279. #elif defined(__APPLE__) && !defined(IOS)
  280. while (shouldRun_)
  281. {
  282. Time::Sleep(100);
  283. String changes = ReadFileWatcher(watcher_);
  284. if (!changes.Empty())
  285. {
  286. Vector<String> fileNames = changes.Split(1);
  287. for (unsigned i = 0; i < fileNames.Size(); ++i)
  288. AddChange(fileNames[i]);
  289. }
  290. }
  291. #endif
  292. #endif
  293. }
  294. void FileWatcher::AddChange(const String& fileName)
  295. {
  296. MutexLock lock(changesMutex_);
  297. // Reset the timer associated with the filename. Will be notified once timer exceeds the delay
  298. changes_[fileName].Reset();
  299. }
  300. bool FileWatcher::GetNextChange(String& dest)
  301. {
  302. MutexLock lock(changesMutex_);
  303. unsigned delayMsec = (unsigned)(delay_ * 1000.0f);
  304. if (changes_.Empty())
  305. return false;
  306. else
  307. {
  308. for (HashMap<String, Timer>::Iterator i = changes_.Begin(); i != changes_.End(); ++i)
  309. {
  310. if (i->second_.GetMSec(false) >= delayMsec)
  311. {
  312. dest = i->first_;
  313. changes_.Erase(i);
  314. return true;
  315. }
  316. }
  317. return false;
  318. }
  319. }
  320. }