FileWatcher.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. //
  2. // Copyright (c) 2008-2017 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) && !defined(TVOS)
  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. #ifdef ATOMIC_FILEWATCHER
  54. #ifdef __linux__
  55. watchHandle_ = inotify_init();
  56. #elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  57. supported_ = IsFileWatcherSupported();
  58. #endif
  59. #endif
  60. }
  61. FileWatcher::~FileWatcher()
  62. {
  63. StopWatching();
  64. #ifdef ATOMIC_FILEWATCHER
  65. #ifdef __linux__
  66. close(watchHandle_);
  67. #endif
  68. #endif
  69. }
  70. bool FileWatcher::StartWatching(const String& pathName, bool watchSubDirs)
  71. {
  72. if (!fileSystem_)
  73. {
  74. ATOMIC_LOGERROR("No FileSystem, can not start watching");
  75. return false;
  76. }
  77. // Stop any previous watching
  78. StopWatching();
  79. #if defined(ATOMIC_FILEWATCHER) && defined(ATOMIC_THREADING)
  80. #ifdef _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. ATOMIC_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. ATOMIC_LOGDEBUG("Started watching path " + pathName);
  113. return true;
  114. }
  115. else
  116. {
  117. ATOMIC_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(), (unsigned)flags);
  123. if (handle < 0)
  124. {
  125. ATOMIC_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(), (unsigned)flags);
  145. if (handle < 0)
  146. ATOMIC_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. ATOMIC_LOGDEBUG("Started watching path " + pathName);
  157. return true;
  158. }
  159. #elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  160. if (!supported_)
  161. {
  162. ATOMIC_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. ATOMIC_LOGDEBUG("Started watching path " + pathName);
  172. return true;
  173. }
  174. else
  175. {
  176. ATOMIC_LOGERROR("Failed to start watching path " + pathName);
  177. return false;
  178. }
  179. #else
  180. ATOMIC_LOGERROR("FileWatcher not implemented, can not start watching path " + pathName);
  181. return false;
  182. #endif
  183. #else
  184. ATOMIC_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. // This is only required on Windows platform
  195. // TODO: Remove this temp write approach as it depends on user write privilege
  196. #ifdef _WIN32
  197. String dummyFileName = path_ + "dummy.tmp";
  198. File file(context_, dummyFileName, FILE_WRITE);
  199. file.Close();
  200. if (fileSystem_)
  201. fileSystem_->Delete(dummyFileName);
  202. #endif
  203. #if defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  204. // Our implementation of file watcher requires the thread to be stopped first before closing the watcher
  205. Stop();
  206. #endif
  207. #ifdef _WIN32
  208. CloseHandle((HANDLE)dirHandle_);
  209. #elif defined(__linux__)
  210. for (HashMap<int, String>::Iterator i = dirHandle_.Begin(); i != dirHandle_.End(); ++i)
  211. inotify_rm_watch(watchHandle_, i->first_);
  212. dirHandle_.Clear();
  213. #elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  214. CloseFileWatcher(watcher_);
  215. #endif
  216. #ifndef __APPLE__
  217. Stop();
  218. #endif
  219. ATOMIC_LOGDEBUG("Stopped watching path " + path_);
  220. path_.Clear();
  221. }
  222. }
  223. void FileWatcher::SetDelay(float interval)
  224. {
  225. delay_ = Max(interval, 0.0f);
  226. }
  227. void FileWatcher::ThreadFunction()
  228. {
  229. #ifdef ATOMIC_FILEWATCHER
  230. #ifdef _WIN32
  231. unsigned char buffer[BUFFERSIZE];
  232. DWORD bytesFilled = 0;
  233. while (shouldRun_)
  234. {
  235. if (ReadDirectoryChangesW((HANDLE)dirHandle_,
  236. buffer,
  237. BUFFERSIZE,
  238. watchSubDirs_,
  239. FILE_NOTIFY_CHANGE_FILE_NAME |
  240. FILE_NOTIFY_CHANGE_LAST_WRITE,
  241. &bytesFilled,
  242. 0,
  243. 0))
  244. {
  245. unsigned offset = 0;
  246. while (offset < bytesFilled)
  247. {
  248. FILE_NOTIFY_INFORMATION* record = (FILE_NOTIFY_INFORMATION*)&buffer[offset];
  249. if (record->Action == FILE_ACTION_MODIFIED || record->Action == FILE_ACTION_RENAMED_NEW_NAME)
  250. {
  251. String fileName;
  252. const wchar_t* src = record->FileName;
  253. const wchar_t* end = src + record->FileNameLength / 2;
  254. while (src < end)
  255. fileName.AppendUTF8(String::DecodeUTF16(src));
  256. fileName = GetInternalPath(fileName);
  257. AddChange(fileName);
  258. }
  259. if (!record->NextEntryOffset)
  260. break;
  261. else
  262. offset += record->NextEntryOffset;
  263. }
  264. }
  265. }
  266. #elif defined(__linux__)
  267. unsigned char buffer[BUFFERSIZE];
  268. while (shouldRun_)
  269. {
  270. int i = 0;
  271. int length = (int)read(watchHandle_, buffer, sizeof(buffer));
  272. if (length < 0)
  273. return;
  274. while (i < length)
  275. {
  276. inotify_event* event = (inotify_event*)&buffer[i];
  277. if (event->len > 0)
  278. {
  279. if (event->mask & IN_MODIFY || event->mask & IN_MOVE)
  280. {
  281. String fileName;
  282. fileName = dirHandle_[event->wd] + event->name;
  283. AddChange(fileName);
  284. }
  285. }
  286. i += sizeof(inotify_event) + event->len;
  287. }
  288. }
  289. #elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  290. while (shouldRun_)
  291. {
  292. Time::Sleep(100);
  293. String changes = ReadFileWatcher(watcher_);
  294. if (!changes.Empty())
  295. {
  296. Vector<String> fileNames = changes.Split(1);
  297. for (unsigned i = 0; i < fileNames.Size(); ++i)
  298. AddChange(fileNames[i]);
  299. }
  300. }
  301. #endif
  302. #endif
  303. }
  304. void FileWatcher::AddChange(const String& fileName)
  305. {
  306. MutexLock lock(changesMutex_);
  307. // Reset the timer associated with the filename. Will be notified once timer exceeds the delay
  308. changes_[fileName].Reset();
  309. }
  310. bool FileWatcher::GetNextChange(String& dest)
  311. {
  312. MutexLock lock(changesMutex_);
  313. unsigned delayMsec = (unsigned)(delay_ * 1000.0f);
  314. if (changes_.Empty())
  315. return false;
  316. else
  317. {
  318. for (HashMap<String, Timer>::Iterator i = changes_.Begin(); i != changes_.End(); ++i)
  319. {
  320. if (i->second_.GetMSec(false) >= delayMsec)
  321. {
  322. dest = i->first_;
  323. changes_.Erase(i);
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. }
  330. }