FileWatcher.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #pragma once
  4. #include "../Core/Mutex.h"
  5. #include "../Core/Object.h"
  6. #include "../Core/Thread.h"
  7. #include "../Core/Timer.h"
  8. namespace Urho3D
  9. {
  10. class FileSystem;
  11. /// Watches a directory and its subdirectories for files being modified.
  12. class URHO3D_API FileWatcher : public Object, public Thread
  13. {
  14. URHO3D_OBJECT(FileWatcher, Object);
  15. public:
  16. /// Construct.
  17. explicit FileWatcher(Context* context);
  18. /// Destruct.
  19. ~FileWatcher() override;
  20. /// Directory watching loop.
  21. void ThreadFunction() override;
  22. /// Start watching a directory. Return true if successful.
  23. bool StartWatching(const String& pathName, bool watchSubDirs);
  24. /// Stop watching the directory.
  25. void StopWatching();
  26. /// Set the delay in seconds before file changes are notified. This (hopefully) avoids notifying when a file save is still in progress. Default 1 second.
  27. void SetDelay(float interval);
  28. /// Add a file change into the changes queue.
  29. void AddChange(const String& fileName);
  30. /// Return a file change (true if was found, false if not).
  31. bool GetNextChange(String& dest);
  32. /// Return the path being watched, or empty if not watching.
  33. const String& GetPath() const { return path_; }
  34. /// Return the delay in seconds for notifying file changes.
  35. float GetDelay() const { return delay_; }
  36. private:
  37. /// Filesystem.
  38. SharedPtr<FileSystem> fileSystem_;
  39. /// The path being watched.
  40. String path_;
  41. /// Pending changes. These will be returned and removed from the list when their timer has exceeded the delay.
  42. HashMap<String, Timer> changes_;
  43. /// Mutex for the change buffer.
  44. Mutex changesMutex_;
  45. /// Delay in seconds for notifying changes.
  46. float delay_;
  47. /// Watch subdirectories flag.
  48. bool watchSubDirs_;
  49. #ifdef _WIN32
  50. /// Directory handle for the path being watched.
  51. void* dirHandle_;
  52. #elif __linux__
  53. /// HashMap for the directory and sub-directories (needed for inotify's int handles).
  54. HashMap<int, String> dirHandle_;
  55. /// Linux inotify needs a handle.
  56. int watchHandle_;
  57. #elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  58. /// Flag indicating whether the running OS supports individual file watching.
  59. bool supported_;
  60. /// Pointer to internal MacFileWatcher delegate.
  61. void* watcher_;
  62. #endif
  63. };
  64. }