FileWatcher.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. //
  2. // Copyright (c) 2008-2022 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. #include "../Core/Profiler.h"
  28. #ifdef _WIN32
  29. #include <windows.h>
  30. #elif __linux__
  31. #include <sys/inotify.h>
  32. extern "C"
  33. {
  34. // Need read/close for inotify
  35. #include "unistd.h"
  36. }
  37. #elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  38. extern "C"
  39. {
  40. #include "../IO/MacFileWatcher.h"
  41. }
  42. #endif
  43. namespace Urho3D
  44. {
  45. #ifndef __APPLE__
  46. static const unsigned BUFFERSIZE = 4096;
  47. #endif
  48. FileWatcher::FileWatcher(Context* context) :
  49. Object(context),
  50. fileSystem_(GetSubsystem<FileSystem>()),
  51. delay_(1.0f),
  52. watchSubDirs_(false)
  53. {
  54. #ifdef URHO3D_FILEWATCHER
  55. #ifdef __linux__
  56. watchHandle_ = inotify_init();
  57. #elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  58. supported_ = IsFileWatcherSupported();
  59. #endif
  60. #endif
  61. }
  62. FileWatcher::~FileWatcher()
  63. {
  64. StopWatching();
  65. #ifdef URHO3D_FILEWATCHER
  66. #ifdef __linux__
  67. close(watchHandle_);
  68. #endif
  69. #endif
  70. }
  71. bool FileWatcher::StartWatching(const String& pathName, bool watchSubDirs)
  72. {
  73. if (!fileSystem_)
  74. {
  75. URHO3D_LOGERROR("No FileSystem, can not start watching");
  76. return false;
  77. }
  78. // Stop any previous watching
  79. StopWatching();
  80. #if defined(URHO3D_FILEWATCHER) && defined(URHO3D_THREADING)
  81. #ifdef _WIN32
  82. String nativePath = GetNativePath(RemoveTrailingSlash(pathName));
  83. dirHandle_ = (void*)CreateFileW(
  84. WString(nativePath).CString(),
  85. FILE_LIST_DIRECTORY,
  86. FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
  87. nullptr,
  88. OPEN_EXISTING,
  89. FILE_FLAG_BACKUP_SEMANTICS,
  90. nullptr);
  91. if (dirHandle_ != INVALID_HANDLE_VALUE)
  92. {
  93. path_ = AddTrailingSlash(pathName);
  94. watchSubDirs_ = watchSubDirs;
  95. Run();
  96. URHO3D_LOGDEBUG("Started watching path " + pathName);
  97. return true;
  98. }
  99. else
  100. {
  101. URHO3D_LOGERROR("Failed to start watching path " + pathName);
  102. return false;
  103. }
  104. #elif defined(__linux__)
  105. int flags = IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO;
  106. int handle = inotify_add_watch(watchHandle_, pathName.CString(), (unsigned)flags);
  107. if (handle < 0)
  108. {
  109. URHO3D_LOGERROR("Failed to start watching path " + pathName);
  110. return false;
  111. }
  112. else
  113. {
  114. // Store the root path here when reconstructed with inotify later
  115. dirHandle_[handle] = "";
  116. path_ = AddTrailingSlash(pathName);
  117. watchSubDirs_ = watchSubDirs;
  118. if (watchSubDirs_)
  119. {
  120. Vector<String> subDirs;
  121. fileSystem_->ScanDir(subDirs, pathName, "*", SCAN_DIRS, true);
  122. for (unsigned i = 0; i < subDirs.Size(); ++i)
  123. {
  124. String subDirFullPath = AddTrailingSlash(path_ + subDirs[i]);
  125. // Don't watch ./ or ../ sub-directories
  126. if (!subDirFullPath.EndsWith("./"))
  127. {
  128. handle = inotify_add_watch(watchHandle_, subDirFullPath.CString(), (unsigned)flags);
  129. if (handle < 0)
  130. URHO3D_LOGERROR("Failed to start watching subdirectory path " + subDirFullPath);
  131. else
  132. {
  133. // Store sub-directory to reconstruct later from inotify
  134. dirHandle_[handle] = AddTrailingSlash(subDirs[i]);
  135. }
  136. }
  137. }
  138. }
  139. Run();
  140. URHO3D_LOGDEBUG("Started watching path " + pathName);
  141. return true;
  142. }
  143. #elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  144. if (!supported_)
  145. {
  146. URHO3D_LOGERROR("Individual file watching not supported by this OS version, can not start watching path " + pathName);
  147. return false;
  148. }
  149. watcher_ = CreateFileWatcher(pathName.CString(), watchSubDirs);
  150. if (watcher_)
  151. {
  152. path_ = AddTrailingSlash(pathName);
  153. watchSubDirs_ = watchSubDirs;
  154. Run();
  155. URHO3D_LOGDEBUG("Started watching path " + pathName);
  156. return true;
  157. }
  158. else
  159. {
  160. URHO3D_LOGERROR("Failed to start watching path " + pathName);
  161. return false;
  162. }
  163. #else
  164. URHO3D_LOGERROR("FileWatcher not implemented, can not start watching path " + pathName);
  165. return false;
  166. #endif
  167. #else
  168. URHO3D_LOGDEBUG("FileWatcher feature not enabled");
  169. return false;
  170. #endif
  171. }
  172. void FileWatcher::StopWatching()
  173. {
  174. if (handle_)
  175. {
  176. shouldRun_ = false;
  177. // Create and delete a dummy file to make sure the watcher loop terminates
  178. // This is only required on Windows platform
  179. // TODO: Remove this temp write approach as it depends on user write privilege
  180. #ifdef _WIN32
  181. String dummyFileName = path_ + "dummy.tmp";
  182. File file(context_, dummyFileName, FILE_WRITE);
  183. file.Close();
  184. if (fileSystem_)
  185. fileSystem_->Delete(dummyFileName);
  186. #endif
  187. #if defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  188. // Our implementation of file watcher requires the thread to be stopped first before closing the watcher
  189. Stop();
  190. #endif
  191. #ifdef _WIN32
  192. CloseHandle((HANDLE)dirHandle_);
  193. #elif defined(__linux__)
  194. for (HashMap<int, String>::Iterator i = dirHandle_.Begin(); i != dirHandle_.End(); ++i)
  195. inotify_rm_watch(watchHandle_, i->first_);
  196. dirHandle_.Clear();
  197. #elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  198. CloseFileWatcher(watcher_);
  199. #endif
  200. #ifndef __APPLE__
  201. Stop();
  202. #endif
  203. URHO3D_LOGDEBUG("Stopped watching path " + path_);
  204. path_.Clear();
  205. }
  206. }
  207. void FileWatcher::SetDelay(float interval)
  208. {
  209. delay_ = Max(interval, 0.0f);
  210. }
  211. void FileWatcher::ThreadFunction()
  212. {
  213. #ifdef URHO3D_FILEWATCHER
  214. URHO3D_PROFILE_THREAD("FileWatcher Thread");
  215. #ifdef _WIN32
  216. unsigned char buffer[BUFFERSIZE];
  217. DWORD bytesFilled = 0;
  218. while (shouldRun_)
  219. {
  220. if (ReadDirectoryChangesW((HANDLE)dirHandle_,
  221. buffer,
  222. BUFFERSIZE,
  223. watchSubDirs_,
  224. FILE_NOTIFY_CHANGE_FILE_NAME |
  225. FILE_NOTIFY_CHANGE_LAST_WRITE,
  226. &bytesFilled,
  227. nullptr,
  228. nullptr))
  229. {
  230. unsigned offset = 0;
  231. while (offset < bytesFilled)
  232. {
  233. FILE_NOTIFY_INFORMATION* record = (FILE_NOTIFY_INFORMATION*)&buffer[offset];
  234. if (record->Action == FILE_ACTION_MODIFIED || record->Action == FILE_ACTION_RENAMED_NEW_NAME)
  235. {
  236. String fileName;
  237. const wchar_t* src = record->FileName;
  238. const wchar_t* end = src + record->FileNameLength / 2;
  239. while (src < end)
  240. fileName.AppendUTF8(String::DecodeUTF16(src));
  241. fileName = GetInternalPath(fileName);
  242. AddChange(fileName);
  243. }
  244. if (!record->NextEntryOffset)
  245. break;
  246. else
  247. offset += record->NextEntryOffset;
  248. }
  249. }
  250. }
  251. #elif defined(__linux__)
  252. unsigned char buffer[BUFFERSIZE];
  253. while (shouldRun_)
  254. {
  255. int i = 0;
  256. auto length = (int)read(watchHandle_, buffer, sizeof(buffer));
  257. if (length < 0)
  258. return;
  259. while (i < length)
  260. {
  261. auto* event = (inotify_event*)&buffer[i];
  262. if (event->len > 0)
  263. {
  264. if (event->mask & IN_MODIFY || event->mask & IN_MOVE)
  265. {
  266. String fileName;
  267. fileName = dirHandle_[event->wd] + event->name;
  268. AddChange(fileName);
  269. }
  270. }
  271. i += sizeof(inotify_event) + event->len;
  272. }
  273. }
  274. #elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  275. while (shouldRun_)
  276. {
  277. Time::Sleep(100);
  278. String changes = ReadFileWatcher(watcher_);
  279. if (!changes.Empty())
  280. {
  281. Vector<String> fileNames = changes.Split(1);
  282. for (unsigned i = 0; i < fileNames.Size(); ++i)
  283. AddChange(fileNames[i]);
  284. }
  285. }
  286. #endif
  287. #endif
  288. }
  289. void FileWatcher::AddChange(const String& fileName)
  290. {
  291. MutexLock lock(changesMutex_);
  292. // Reset the timer associated with the filename. Will be notified once timer exceeds the delay
  293. changes_[fileName].Reset();
  294. }
  295. bool FileWatcher::GetNextChange(String& dest)
  296. {
  297. MutexLock lock(changesMutex_);
  298. auto delayMsec = (unsigned)(delay_ * 1000.0f);
  299. if (changes_.Empty())
  300. return false;
  301. else
  302. {
  303. for (HashMap<String, Timer>::Iterator i = changes_.Begin(); i != changes_.End(); ++i)
  304. {
  305. if (i->second_.GetMSec(false) >= delayMsec)
  306. {
  307. dest = i->first_;
  308. changes_.Erase(i);
  309. return true;
  310. }
  311. }
  312. return false;
  313. }
  314. }
  315. }