FileWatcher.cpp 9.7 KB

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