FileWatcher.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. dirHandle_ = (void*)CreateFileW(
  83. WString(nativePath).CString(),
  84. FILE_LIST_DIRECTORY,
  85. FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
  86. 0,
  87. OPEN_EXISTING,
  88. FILE_FLAG_BACKUP_SEMANTICS,
  89. 0);
  90. if (dirHandle_ != INVALID_HANDLE_VALUE)
  91. {
  92. path_ = AddTrailingSlash(pathName);
  93. watchSubDirs_ = watchSubDirs;
  94. Run();
  95. LOGDEBUG("Started watching path " + pathName);
  96. return true;
  97. }
  98. else
  99. {
  100. LOGERROR("Failed to start watching path " + pathName);
  101. return false;
  102. }
  103. #elif defined(__linux__)
  104. int flags = IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO;
  105. int handle = inotify_add_watch(watchHandle_, pathName.CString(), (uint32_t)flags);
  106. if (handle < 0)
  107. {
  108. LOGERROR("Failed to start watching path " + pathName);
  109. return false;
  110. }
  111. else
  112. {
  113. // Store the root path here when reconstructed with inotify later
  114. dirHandle_[handle] = "";
  115. path_ = AddTrailingSlash(pathName);
  116. watchSubDirs_ = watchSubDirs;
  117. if (watchSubDirs_)
  118. {
  119. Vector<String> subDirs;
  120. fileSystem_->ScanDir(subDirs, pathName, "*", SCAN_DIRS, true);
  121. for (unsigned i = 0; i < subDirs.Size(); ++i)
  122. {
  123. String subDirFullPath = AddTrailingSlash(path_ + subDirs[i]);
  124. // Don't watch ./ or ../ sub-directories
  125. if (!subDirFullPath.EndsWith("./"))
  126. {
  127. handle = inotify_add_watch(watchHandle_, subDirFullPath.CString(), (uint32_t)flags);
  128. if (handle < 0)
  129. LOGERROR("Failed to start watching subdirectory path " + subDirFullPath);
  130. else
  131. {
  132. // Store sub-directory to reconstruct later from inotify
  133. dirHandle_[handle] = AddTrailingSlash(subDirs[i]);
  134. }
  135. }
  136. }
  137. }
  138. Run();
  139. LOGDEBUG("Started watching path " + pathName);
  140. return true;
  141. }
  142. #elif defined(__APPLE__) && !defined(IOS)
  143. if (!supported_)
  144. {
  145. LOGERROR("Individual file watching not supported by this OS version, can not start watching path " + pathName);
  146. return false;
  147. }
  148. watcher_ = CreateFileWatcher(pathName.CString(), watchSubDirs);
  149. if (watcher_)
  150. {
  151. path_ = AddTrailingSlash(pathName);
  152. watchSubDirs_ = watchSubDirs;
  153. Run();
  154. LOGDEBUG("Started watching path " + pathName);
  155. return true;
  156. }
  157. else
  158. {
  159. LOGERROR("Failed to start watching path " + pathName);
  160. return false;
  161. }
  162. #else
  163. LOGERROR("FileWatcher not implemented, can not start watching path " + pathName);
  164. return false;
  165. #endif
  166. #else
  167. LOGDEBUG("FileWatcher feature not enabled");
  168. return false;
  169. #endif
  170. }
  171. void FileWatcher::StopWatching()
  172. {
  173. if (handle_)
  174. {
  175. shouldRun_ = false;
  176. // Create and delete a dummy file to make sure the watcher loop terminates
  177. String dummyFileName = path_ + "dummy.tmp";
  178. File file(context_, dummyFileName, FILE_WRITE);
  179. file.Close();
  180. if (fileSystem_)
  181. fileSystem_->Delete(dummyFileName);
  182. Stop();
  183. #if defined(WIN32)
  184. CloseHandle((HANDLE)dirHandle_);
  185. #elif defined(__linux__)
  186. for (HashMap<int, String>::Iterator i = dirHandle_.Begin(); i != dirHandle_.End(); ++i)
  187. inotify_rm_watch(watchHandle_, i->first_);
  188. dirHandle_.Clear();
  189. #elif defined(__APPLE__) && !defined(IOS)
  190. CloseFileWatcher(watcher_);
  191. #endif
  192. LOGDEBUG("Stopped watching path " + path_);
  193. path_.Clear();
  194. }
  195. }
  196. void FileWatcher::SetDelay(float interval)
  197. {
  198. delay_ = Max(interval, 0.0f);
  199. }
  200. void FileWatcher::ThreadFunction()
  201. {
  202. #if defined(ATOMIC_FILEWATCHER)
  203. #if defined(WIN32)
  204. unsigned char buffer[BUFFERSIZE];
  205. DWORD bytesFilled = 0;
  206. while (shouldRun_)
  207. {
  208. if (ReadDirectoryChangesW((HANDLE)dirHandle_,
  209. buffer,
  210. BUFFERSIZE,
  211. watchSubDirs_,
  212. FILE_NOTIFY_CHANGE_FILE_NAME |
  213. FILE_NOTIFY_CHANGE_LAST_WRITE,
  214. &bytesFilled,
  215. 0,
  216. 0))
  217. {
  218. unsigned offset = 0;
  219. while (offset < bytesFilled)
  220. {
  221. FILE_NOTIFY_INFORMATION* record = (FILE_NOTIFY_INFORMATION*)&buffer[offset];
  222. if (record->Action == FILE_ACTION_MODIFIED || record->Action == FILE_ACTION_RENAMED_NEW_NAME)
  223. {
  224. String fileName;
  225. const wchar_t* src = record->FileName;
  226. const wchar_t* end = src + record->FileNameLength / 2;
  227. while (src < end)
  228. fileName.AppendUTF8(String::DecodeUTF16(src));
  229. fileName = GetInternalPath(fileName);
  230. AddChange(fileName);
  231. }
  232. if (!record->NextEntryOffset)
  233. break;
  234. else
  235. offset += record->NextEntryOffset;
  236. }
  237. }
  238. }
  239. #elif defined(__linux__)
  240. unsigned char buffer[BUFFERSIZE];
  241. while (shouldRun_)
  242. {
  243. int i = 0;
  244. int length = (int)read(watchHandle_, buffer, sizeof(buffer));
  245. if (length < 0)
  246. return;
  247. while (i < length)
  248. {
  249. inotify_event* event = (inotify_event*)&buffer[i];
  250. if (event->len > 0)
  251. {
  252. if (event->mask & IN_MODIFY || event->mask & IN_MOVE)
  253. {
  254. String fileName;
  255. fileName = dirHandle_[event->wd] + event->name;
  256. AddChange(fileName);
  257. }
  258. }
  259. i += sizeof(inotify_event) + event->len;
  260. }
  261. }
  262. #elif defined(__APPLE__) && !defined(IOS)
  263. while (shouldRun_)
  264. {
  265. Time::Sleep(100);
  266. String changes = ReadFileWatcher(watcher_);
  267. if (!changes.Empty())
  268. {
  269. Vector<String> fileNames = changes.Split(1);
  270. for (unsigned i = 0; i < fileNames.Size(); ++i)
  271. AddChange(fileNames[i]);
  272. }
  273. }
  274. #endif
  275. #endif
  276. }
  277. void FileWatcher::AddChange(const String& fileName)
  278. {
  279. MutexLock lock(changesMutex_);
  280. // Reset the timer associated with the filename. Will be notified once timer exceeds the delay
  281. changes_[fileName].Reset();
  282. }
  283. bool FileWatcher::GetNextChange(String& dest)
  284. {
  285. MutexLock lock(changesMutex_);
  286. unsigned delayMsec = (unsigned)(delay_ * 1000.0f);
  287. if (changes_.Empty())
  288. return false;
  289. else
  290. {
  291. for (HashMap<String, Timer>::Iterator i = changes_.Begin(); i != changes_.End(); ++i)
  292. {
  293. if (i->second_.GetMSec(false) >= delayMsec)
  294. {
  295. dest = i->first_;
  296. changes_.Erase(i);
  297. return true;
  298. }
  299. }
  300. return false;
  301. }
  302. }
  303. }