FileWatcher.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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)
  37. extern "C"
  38. {
  39. #include "../IO/MacFileWatcher.h"
  40. }
  41. #endif
  42. namespace Urho3D
  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 URHO3D_FILEWATCHER
  54. #ifdef __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. #ifdef URHO3D_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. URHO3D_LOGERROR("No FileSystem, can not start watching");
  75. return false;
  76. }
  77. // Stop any previous watching
  78. StopWatching();
  79. #if defined(URHO3D_FILEWATCHER) && defined(URHO3D_THREADING)
  80. #ifdef _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. URHO3D_LOGDEBUG("Started watching path " + pathName);
  96. return true;
  97. }
  98. else
  99. {
  100. URHO3D_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(), (unsigned)flags);
  106. if (handle < 0)
  107. {
  108. URHO3D_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(), (unsigned)flags);
  128. if (handle < 0)
  129. URHO3D_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. URHO3D_LOGDEBUG("Started watching path " + pathName);
  140. return true;
  141. }
  142. #elif defined(__APPLE__) && !defined(IOS)
  143. if (!supported_)
  144. {
  145. URHO3D_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. URHO3D_LOGDEBUG("Started watching path " + pathName);
  155. return true;
  156. }
  157. else
  158. {
  159. URHO3D_LOGERROR("Failed to start watching path " + pathName);
  160. return false;
  161. }
  162. #else
  163. URHO3D_LOGERROR("FileWatcher not implemented, can not start watching path " + pathName);
  164. return false;
  165. #endif
  166. #else
  167. URHO3D_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. // This is only required on Windows platform
  178. // TODO: Remove this temp write approach as it depends on user write privilege
  179. #ifdef _WIN32
  180. String dummyFileName = path_ + "dummy.tmp";
  181. File file(context_, dummyFileName, FILE_WRITE);
  182. file.Close();
  183. if (fileSystem_)
  184. fileSystem_->Delete(dummyFileName);
  185. #endif
  186. #if defined(__APPLE__) && !defined(IOS)
  187. // Our implementation of file watcher requires the thread to be stopped first before closing the watcher
  188. Stop();
  189. #endif
  190. #ifdef _WIN32
  191. CloseHandle((HANDLE)dirHandle_);
  192. #elif defined(__linux__)
  193. for (HashMap<int, String>::Iterator i = dirHandle_.Begin(); i != dirHandle_.End(); ++i)
  194. inotify_rm_watch(watchHandle_, i->first_);
  195. dirHandle_.Clear();
  196. #elif defined(__APPLE__) && !defined(IOS)
  197. CloseFileWatcher(watcher_);
  198. #endif
  199. #ifndef __APPLE__
  200. Stop();
  201. #endif
  202. URHO3D_LOGDEBUG("Stopped watching path " + path_);
  203. path_.Clear();
  204. }
  205. }
  206. void FileWatcher::SetDelay(float interval)
  207. {
  208. delay_ = Max(interval, 0.0f);
  209. }
  210. void FileWatcher::ThreadFunction()
  211. {
  212. #ifdef URHO3D_FILEWATCHER
  213. #ifdef _WIN32
  214. unsigned char buffer[BUFFERSIZE];
  215. DWORD bytesFilled = 0;
  216. while (shouldRun_)
  217. {
  218. if (ReadDirectoryChangesW((HANDLE)dirHandle_,
  219. buffer,
  220. BUFFERSIZE,
  221. watchSubDirs_,
  222. FILE_NOTIFY_CHANGE_FILE_NAME |
  223. FILE_NOTIFY_CHANGE_LAST_WRITE,
  224. &bytesFilled,
  225. 0,
  226. 0))
  227. {
  228. unsigned offset = 0;
  229. while (offset < bytesFilled)
  230. {
  231. FILE_NOTIFY_INFORMATION* record = (FILE_NOTIFY_INFORMATION*)&buffer[offset];
  232. if (record->Action == FILE_ACTION_MODIFIED || record->Action == FILE_ACTION_RENAMED_NEW_NAME)
  233. {
  234. String fileName;
  235. const wchar_t* src = record->FileName;
  236. const wchar_t* end = src + record->FileNameLength / 2;
  237. while (src < end)
  238. fileName.AppendUTF8(String::DecodeUTF16(src));
  239. fileName = GetInternalPath(fileName);
  240. AddChange(fileName);
  241. }
  242. if (!record->NextEntryOffset)
  243. break;
  244. else
  245. offset += record->NextEntryOffset;
  246. }
  247. }
  248. }
  249. #elif defined(__linux__)
  250. unsigned char buffer[BUFFERSIZE];
  251. while (shouldRun_)
  252. {
  253. int i = 0;
  254. int length = (int)read(watchHandle_, buffer, sizeof(buffer));
  255. if (length < 0)
  256. return;
  257. while (i < length)
  258. {
  259. inotify_event* event = (inotify_event*)&buffer[i];
  260. if (event->len > 0)
  261. {
  262. if (event->mask & IN_MODIFY || event->mask & IN_MOVE)
  263. {
  264. String fileName;
  265. fileName = dirHandle_[event->wd] + event->name;
  266. AddChange(fileName);
  267. }
  268. }
  269. i += sizeof(inotify_event) + event->len;
  270. }
  271. }
  272. #elif defined(__APPLE__) && !defined(IOS)
  273. while (shouldRun_)
  274. {
  275. Time::Sleep(100);
  276. String changes = ReadFileWatcher(watcher_);
  277. if (!changes.Empty())
  278. {
  279. Vector<String> fileNames = changes.Split(1);
  280. for (unsigned i = 0; i < fileNames.Size(); ++i)
  281. AddChange(fileNames[i]);
  282. }
  283. }
  284. #endif
  285. #endif
  286. }
  287. void FileWatcher::AddChange(const String& fileName)
  288. {
  289. MutexLock lock(changesMutex_);
  290. // Reset the timer associated with the filename. Will be notified once timer exceeds the delay
  291. changes_[fileName].Reset();
  292. }
  293. bool FileWatcher::GetNextChange(String& dest)
  294. {
  295. MutexLock lock(changesMutex_);
  296. unsigned delayMsec = (unsigned)(delay_ * 1000.0f);
  297. if (changes_.Empty())
  298. return false;
  299. else
  300. {
  301. for (HashMap<String, Timer>::Iterator i = changes_.Begin(); i != changes_.End(); ++i)
  302. {
  303. if (i->second_.GetMSec(false) >= delayMsec)
  304. {
  305. dest = i->first_;
  306. changes_.Erase(i);
  307. return true;
  308. }
  309. }
  310. return false;
  311. }
  312. }
  313. }