FileWatcher.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. #ifdef WIN32
  28. #include <windows.h>
  29. #elif __linux__
  30. #include <sys/inotify.h>
  31. extern "C" {
  32. // Need read/close for inotify
  33. #include "unistd.h"
  34. }
  35. #endif
  36. namespace Urho3D
  37. {
  38. static const unsigned BUFFERSIZE = 4096;
  39. OBJECTTYPESTATIC(FileWatcher);
  40. FileWatcher::FileWatcher(Context* context) :
  41. Object(context),
  42. fileSystem_(GetSubsystem<FileSystem>()),
  43. watchSubDirs_(false)
  44. {
  45. #if defined(ENABLE_FILEWATCHER)
  46. #if defined(__linux__)
  47. watchHandle_ = inotify_init();
  48. #endif
  49. #endif
  50. }
  51. FileWatcher::~FileWatcher()
  52. {
  53. StopWatching();
  54. #if defined(ENABLE_FILEWATCHER)
  55. #if defined(__linux__)
  56. close(watchHandle_);
  57. #endif
  58. #endif
  59. }
  60. bool FileWatcher::StartWatching(const String& pathName, bool watchSubDirs)
  61. {
  62. if (!fileSystem_)
  63. {
  64. LOGERROR("No FileSystem, can not start watching");
  65. return false;
  66. }
  67. // Stop any previous watching
  68. StopWatching();
  69. #if defined(ENABLE_FILEWATCHER)
  70. #if defined(WIN32)
  71. String nativePath = GetNativePath(RemoveTrailingSlash(pathName));
  72. dirHandle_ = (void*)CreateFileW(
  73. WString(nativePath).CString(),
  74. FILE_LIST_DIRECTORY,
  75. FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
  76. 0,
  77. OPEN_EXISTING,
  78. FILE_FLAG_BACKUP_SEMANTICS,
  79. 0);
  80. if (dirHandle_ != INVALID_HANDLE_VALUE)
  81. {
  82. path_ = AddTrailingSlash(pathName);
  83. watchSubDirs_ = watchSubDirs;
  84. Start();
  85. LOGDEBUG("Started watching path " + pathName);
  86. return true;
  87. }
  88. else
  89. {
  90. LOGERROR("Failed to start watching path " + pathName);
  91. return false;
  92. }
  93. #elif defined(__linux__)
  94. //String nativePath = GetNativePath(RemoveTrailingSlash(pathName));
  95. int flags = IN_CREATE|IN_DELETE|IN_MODIFY|IN_MOVED_FROM|IN_MOVED_TO;
  96. int handle;
  97. dirHandle_;
  98. handle = inotify_add_watch(watchHandle_, pathName.CString(), flags);
  99. if (handle < 0)
  100. {
  101. LOGERROR("Failed to start watching path " + pathName);
  102. return false;
  103. }
  104. else
  105. {
  106. // Store the root path here when reconstructed with inotify later
  107. dirHandle_[handle] = "";
  108. path_ = AddTrailingSlash(pathName);
  109. watchSubDirs_ = watchSubDirs;
  110. if (watchSubDirs_)
  111. {
  112. Vector<String> subDirs;
  113. fileSystem_->ScanDir(subDirs, pathName, "*", SCAN_DIRS, true);
  114. for (unsigned i = 0; i < subDirs.Size(); ++i)
  115. {
  116. String subDirFullPath = AddTrailingSlash(path_ + subDirs[i]);
  117. // Don't watch ./ or ../ sub-directories
  118. if (!subDirFullPath.EndsWith("./"))
  119. {
  120. handle = inotify_add_watch(watchHandle_, subDirFullPath.CString(), flags);
  121. if (handle < 0)
  122. LOGERROR("Failed to start watching subdirectory path " + subDirFullPath);
  123. else
  124. {
  125. // Store sub-directory to reconstruct later from inotify
  126. dirHandle_[handle] = AddTrailingSlash(subDirs[i]);
  127. }
  128. }
  129. }
  130. }
  131. Start();
  132. LOGDEBUG("Started watching path " + pathName);
  133. return true;
  134. }
  135. #endif
  136. #else
  137. /// \todo Implement on Unix-like systems
  138. LOGERROR("FileWatcher not implemented, can not start watching path " + pathName);
  139. return false;
  140. #endif
  141. }
  142. void FileWatcher::StopWatching()
  143. {
  144. if (handle_)
  145. {
  146. shouldRun_ = false;
  147. // Create and delete a dummy file to make sure the watcher loop terminates
  148. String dummyFileName = path_ + "dummy.tmp";
  149. File file(context_, dummyFileName, FILE_WRITE);
  150. file.Close();
  151. if (fileSystem_)
  152. fileSystem_->Delete(dummyFileName);
  153. Stop();
  154. #if defined(WIN32)
  155. CloseHandle((HANDLE)dirHandle_);
  156. #elif defined(__linux__)
  157. for (HashMap<int, String>::Iterator i = dirHandle_.Begin(); i != dirHandle_.End(); ++i)
  158. inotify_rm_watch(watchHandle_, i->first_);
  159. dirHandle_.Clear();
  160. #endif
  161. LOGDEBUG("Stopped watching path " + path_);
  162. path_.Clear();
  163. }
  164. }
  165. void FileWatcher::ThreadFunction()
  166. {
  167. #if defined(ENABLE_FILEWATCHER)
  168. #if defined(WIN32)
  169. unsigned char buffer[BUFFERSIZE];
  170. DWORD bytesFilled = 0;
  171. while (shouldRun_)
  172. {
  173. if (ReadDirectoryChangesW((HANDLE)dirHandle_,
  174. buffer,
  175. BUFFERSIZE,
  176. watchSubDirs_,
  177. FILE_NOTIFY_CHANGE_FILE_NAME |
  178. FILE_NOTIFY_CHANGE_LAST_WRITE,
  179. &bytesFilled,
  180. 0,
  181. 0))
  182. {
  183. unsigned offset = 0;
  184. while (offset < bytesFilled)
  185. {
  186. FILE_NOTIFY_INFORMATION* record = (FILE_NOTIFY_INFORMATION*)&buffer[offset];
  187. if (record->Action == FILE_ACTION_MODIFIED || record->Action == FILE_ACTION_RENAMED_NEW_NAME)
  188. {
  189. String fileName;
  190. const wchar_t* src = record->FileName;
  191. const wchar_t* end = src + record->FileNameLength / 2;
  192. while (src < end)
  193. fileName.AppendUTF8(String::DecodeUTF16(src));
  194. fileName = GetInternalPath(fileName);
  195. {
  196. MutexLock lock(changesMutex_);
  197. // If we have 2 unprocessed modifies in a row into the same file, only record the first
  198. if (changes_.Empty() || changes_.Back() != fileName)
  199. changes_.Push(fileName);
  200. }
  201. }
  202. if (!record->NextEntryOffset)
  203. break;
  204. else
  205. offset += record->NextEntryOffset;
  206. }
  207. }
  208. }
  209. #elif defined(__linux__)
  210. unsigned char buffer[BUFFERSIZE];
  211. while (shouldRun_)
  212. {
  213. int i = 0;
  214. int length = read(watchHandle_, buffer, sizeof(buffer));
  215. if (length < 0)
  216. return;
  217. while (i < length)
  218. {
  219. inotify_event* event = (inotify_event*)&buffer[i];
  220. if (event->len > 0)
  221. {
  222. if (event->mask & IN_MODIFY || event->mask & IN_MOVE)
  223. {
  224. String fileName;
  225. fileName = dirHandle_[event->wd] + event->name;
  226. {
  227. MutexLock lock(changesMutex_);
  228. // If we have 2 unprocessed modifies in a row into the same file, only record the first
  229. if (changes_.Empty() || changes_.Back() != fileName)
  230. changes_.Push(fileName);
  231. }
  232. }
  233. }
  234. i += sizeof(inotify_event) + event->len;
  235. }
  236. }
  237. #endif
  238. #endif
  239. }
  240. bool FileWatcher::GetNextChange(String& dest)
  241. {
  242. MutexLock lock(changesMutex_);
  243. if (changes_.Empty())
  244. return false;
  245. else
  246. {
  247. dest = changes_.Front();
  248. changes_.Erase(changes_.Begin());
  249. return true;
  250. }
  251. }
  252. }