FileWatcher.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. //
  2. // Copyright (c) 2008-2013 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. OBJECTTYPESTATIC(FileWatcher);
  45. FileWatcher::FileWatcher(Context* context) :
  46. Object(context),
  47. fileSystem_(GetSubsystem<FileSystem>()),
  48. watchSubDirs_(false)
  49. {
  50. #if defined(ENABLE_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(ENABLE_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(ENABLE_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. Start();
  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;
  103. dirHandle_;
  104. handle = inotify_add_watch(watchHandle_, pathName.CString(), flags);
  105. if (handle < 0)
  106. {
  107. LOGERROR("Failed to start watching path " + pathName);
  108. return false;
  109. }
  110. else
  111. {
  112. // Store the root path here when reconstructed with inotify later
  113. dirHandle_[handle] = "";
  114. path_ = AddTrailingSlash(pathName);
  115. watchSubDirs_ = watchSubDirs;
  116. if (watchSubDirs_)
  117. {
  118. Vector<String> subDirs;
  119. fileSystem_->ScanDir(subDirs, pathName, "*", SCAN_DIRS, true);
  120. for (unsigned i = 0; i < subDirs.Size(); ++i)
  121. {
  122. String subDirFullPath = AddTrailingSlash(path_ + subDirs[i]);
  123. // Don't watch ./ or ../ sub-directories
  124. if (!subDirFullPath.EndsWith("./"))
  125. {
  126. handle = inotify_add_watch(watchHandle_, subDirFullPath.CString(), flags);
  127. if (handle < 0)
  128. LOGERROR("Failed to start watching subdirectory path " + subDirFullPath);
  129. else
  130. {
  131. // Store sub-directory to reconstruct later from inotify
  132. dirHandle_[handle] = AddTrailingSlash(subDirs[i]);
  133. }
  134. }
  135. }
  136. }
  137. Start();
  138. LOGDEBUG("Started watching path " + pathName);
  139. return true;
  140. }
  141. #elif defined(__APPLE__) && !defined(IOS)
  142. if (!supported_)
  143. {
  144. LOGERROR("Individual file watching not supported by this OS version, can not start watching path " + pathName);
  145. return false;
  146. }
  147. watcher_ = CreateFileWatcher(pathName.CString(), watchSubDirs);
  148. if (watcher_)
  149. {
  150. path_ = AddTrailingSlash(pathName);
  151. watchSubDirs_ = watchSubDirs;
  152. Start();
  153. LOGDEBUG("Started watching path " + pathName);
  154. return true;
  155. }
  156. else
  157. {
  158. LOGERROR("Failed to start watching path " + pathName);
  159. return false;
  160. }
  161. #else
  162. LOGERROR("FileWatcher not implemented, can not start watching path " + pathName);
  163. return false;
  164. #endif
  165. #else
  166. LOGDEBUG("FileWatcher feature not enabled");
  167. return false;
  168. #endif
  169. }
  170. void FileWatcher::StopWatching()
  171. {
  172. if (handle_)
  173. {
  174. shouldRun_ = false;
  175. // Create and delete a dummy file to make sure the watcher loop terminates
  176. String dummyFileName = path_ + "dummy.tmp";
  177. File file(context_, dummyFileName, FILE_WRITE);
  178. file.Close();
  179. if (fileSystem_)
  180. fileSystem_->Delete(dummyFileName);
  181. Stop();
  182. #if defined(WIN32)
  183. CloseHandle((HANDLE)dirHandle_);
  184. #elif defined(__linux__)
  185. for (HashMap<int, String>::Iterator i = dirHandle_.Begin(); i != dirHandle_.End(); ++i)
  186. inotify_rm_watch(watchHandle_, i->first_);
  187. dirHandle_.Clear();
  188. #elif defined(__APPLE__) && !defined(IOS)
  189. CloseFileWatcher(watcher_);
  190. #endif
  191. LOGDEBUG("Stopped watching path " + path_);
  192. path_.Clear();
  193. }
  194. }
  195. void FileWatcher::ThreadFunction()
  196. {
  197. #if defined(ENABLE_FILEWATCHER)
  198. #if defined(WIN32)
  199. unsigned char buffer[BUFFERSIZE];
  200. DWORD bytesFilled = 0;
  201. while (shouldRun_)
  202. {
  203. if (ReadDirectoryChangesW((HANDLE)dirHandle_,
  204. buffer,
  205. BUFFERSIZE,
  206. watchSubDirs_,
  207. FILE_NOTIFY_CHANGE_FILE_NAME |
  208. FILE_NOTIFY_CHANGE_LAST_WRITE,
  209. &bytesFilled,
  210. 0,
  211. 0))
  212. {
  213. unsigned offset = 0;
  214. while (offset < bytesFilled)
  215. {
  216. FILE_NOTIFY_INFORMATION* record = (FILE_NOTIFY_INFORMATION*)&buffer[offset];
  217. if (record->Action == FILE_ACTION_MODIFIED || record->Action == FILE_ACTION_RENAMED_NEW_NAME)
  218. {
  219. String fileName;
  220. const wchar_t* src = record->FileName;
  221. const wchar_t* end = src + record->FileNameLength / 2;
  222. while (src < end)
  223. fileName.AppendUTF8(String::DecodeUTF16(src));
  224. fileName = GetInternalPath(fileName);
  225. AddChange(fileName);
  226. }
  227. if (!record->NextEntryOffset)
  228. break;
  229. else
  230. offset += record->NextEntryOffset;
  231. }
  232. }
  233. }
  234. #elif defined(__linux__)
  235. unsigned char buffer[BUFFERSIZE];
  236. while (shouldRun_)
  237. {
  238. int i = 0;
  239. int length = read(watchHandle_, buffer, sizeof(buffer));
  240. if (length < 0)
  241. return;
  242. while (i < length)
  243. {
  244. inotify_event* event = (inotify_event*)&buffer[i];
  245. if (event->len > 0)
  246. {
  247. if (event->mask & IN_MODIFY || event->mask & IN_MOVE)
  248. {
  249. String fileName;
  250. fileName = dirHandle_[event->wd] + event->name;
  251. AddChange(fileName);
  252. }
  253. }
  254. i += sizeof(inotify_event) + event->len;
  255. }
  256. }
  257. #elif defined(__APPLE__) && !defined(IOS)
  258. while (shouldRun_)
  259. {
  260. Time::Sleep(100);
  261. String changes = ReadFileWatcher(watcher_);
  262. if (!changes.Empty())
  263. {
  264. Vector<String> fileNames = changes.Split(1);
  265. for (unsigned i = 0; i < fileNames.Size(); ++i)
  266. AddChange(fileNames[i]);
  267. }
  268. }
  269. #endif
  270. #endif
  271. }
  272. void FileWatcher::AddChange(const String& fileName)
  273. {
  274. MutexLock lock(changesMutex_);
  275. // If we have 2 unprocessed modifies in a row into the same file, only record the first
  276. if (changes_.Empty() || changes_.Back() != fileName)
  277. changes_.Push(fileName);
  278. }
  279. bool FileWatcher::GetNextChange(String& dest)
  280. {
  281. MutexLock lock(changesMutex_);
  282. if (changes_.Empty())
  283. return false;
  284. else
  285. {
  286. dest = changes_.Front();
  287. changes_.Erase(changes_.Begin());
  288. return true;
  289. }
  290. }
  291. }