1-- Some code snippets are adapted from the fsnotify package.
2-- http://hackage.haskell.org/package/fsnotify-0.3.0.1/
5-- Module : Streamly.Internal.FileSystem.Event.Windows
6-- Copyright : (c) 2020 Composewell Technologies
7-- (c) 2012, Mark Dittmer
8-- License : BSD-3-Clause
9-- Maintainer : streamly@composewell.com
10-- Stability : experimental
15-- Use 'watchTrees'or 'watchPaths' with a list of file system paths you want to
16-- watch as argument. It returns a stream of 'Event' representing the file
17-- system events occurring under the watched paths.
20-- {-\# LANGUAGE MagicHash #-}
21-- Stream.mapM_ (putStrLn . 'showEvent') $ 'watchTrees' [Array.fromCString\# "path"#]
24-- 'Event' is an opaque type. Accessor functions (e.g. 'showEvent' above)
25-- provided in this module are used to determine the attributes of the event.
29-- For Windows reference documentation see:
31-- * <https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-file_notify_information file notify information>
32-- * <https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw read directory changes>
34-- We try to keep the macOS\/Linux/Windows event handling APIs and defaults
35-- semantically and syntactically as close as possible.
39-- As per the Windows reference docs, the fs event notification API is
42-- * Minimum supported client: Windows XP [desktop apps | UWP apps]
43-- * Minimum supported server: Windows Server 2003 [desktop apps | UWP apps
45module Streamly.Internal.FileSystem.Event.Windows
47 -- * Subscribing to events
49 -- ** Default configuration
61 -- ** Events of Interest
62 -- *** Root Level Events
65 , setModifiedAttribute
67 , setModifiedLastWrite
81 -- ** Item CRUD events
88 -- ** Exception Conditions
96import Control.Monad.IO.Class (MonadIO(liftIO))
97import Data.Bits ((.|.), (.&.), complement)
98import Data.Functor.Identity (runIdentity)
99import Data.List.NonEmpty (NonEmpty)
100import Data.Word (Word8)
101import Foreign.C.String (peekCWStringLen)
102import Foreign.Marshal.Alloc (alloca, allocaBytes)
103import Foreign.Storable (peekByteOff)
104import Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, nullFunPtr, plusPtr)
105import Streamly.Prelude (SerialT, parallel)
106import System.Win32.File
107 ( FileNotificationFlag
111 , fILE_FLAG_BACKUP_SEMANTICS
112 , fILE_LIST_DIRECTORY
113 , fILE_NOTIFY_CHANGE_FILE_NAME
114 , fILE_NOTIFY_CHANGE_DIR_NAME
115 , fILE_NOTIFY_CHANGE_ATTRIBUTES
116 , fILE_NOTIFY_CHANGE_SIZE
117 , fILE_NOTIFY_CHANGE_LAST_WRITE
118 , fILE_NOTIFY_CHANGE_SECURITY
123import System.Win32.Types (BOOL, DWORD, HANDLE, LPVOID, LPDWORD, failIfFalse_)
124import qualified Data.List.NonEmpty as NonEmpty
125import qualified Streamly.Internal.Data.Stream.IsStream as S
126import qualified Streamly.Internal.Unicode.Stream as U
127import qualified Streamly.Internal.Data.Array.Foreign as A
128import Streamly.Internal.Data.Array.Foreign (Array)
130-- | Watch configuration, used to specify the events of interest and the
131-- behavior of the watch.
137 , createFlags :: DWORD
140-------------------------------------------------------------------------------
142-------------------------------------------------------------------------------
144-- | Whether a setting is 'On' or 'Off'.
148data Toggle = On | Off
150setFlag :: DWORD -> Toggle -> Config -> Config
151setFlag mask status cfg@Config{..} =
154 On -> createFlags .|. mask
155 Off -> createFlags .&. complement mask
156 in cfg {createFlags = flags}
158-- | Set watch event on directory recursively.
164setRecursiveMode :: BOOL -> Config -> Config
165setRecursiveMode rec cfg@Config{} = cfg {watchRec = rec}
167-- | Report when a file name is modified.
173setModifiedFileName :: Toggle -> Config -> Config
174setModifiedFileName = setFlag fILE_NOTIFY_CHANGE_FILE_NAME
176-- | Report when a directory name is modified.
182setModifiedDirName :: Toggle -> Config -> Config
183setModifiedDirName = setFlag fILE_NOTIFY_CHANGE_DIR_NAME
185-- | Report when a file attribute is modified.
191setModifiedAttribute :: Toggle -> Config -> Config
192setModifiedAttribute = setFlag fILE_NOTIFY_CHANGE_ATTRIBUTES
194-- | Report when a file size is changed.
200setModifiedSize :: Toggle -> Config -> Config
201setModifiedSize = setFlag fILE_NOTIFY_CHANGE_SIZE
203-- | Report when a file last write time is changed.
209setModifiedLastWrite :: Toggle -> Config -> Config
210setModifiedLastWrite = setFlag fILE_NOTIFY_CHANGE_LAST_WRITE
212-- | Report when a file Security attributes is changed.
218setModifiedSecurity :: Toggle -> Config -> Config
219setModifiedSecurity = setFlag fILE_NOTIFY_CHANGE_SECURITY
221-- | Set all events 'On' or 'Off'.
227setAllEvents :: Toggle -> Config -> Config
229 setModifiedFileName s
230 . setModifiedDirName s
231 . setModifiedAttribute s
233 . setModifiedLastWrite s
234 . setModifiedSecurity s
236defaultConfig :: Config
237defaultConfig = setAllEvents On $ Config {watchRec = True, createFlags = 0}
239getConfigFlag :: Config -> DWORD
240getConfigFlag Config{..} = createFlags
242getConfigRecMode :: Config -> BOOL
243getConfigRecMode Config{..} = watchRec
246 { eventFlags :: DWORD
247 , eventRelPath :: String
248 , eventRootPath :: String
249 , totalBytes :: DWORD
250 } deriving (Show, Ord, Eq)
252-- For reference documentation see:
254-- See https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-file_notify_information
255data FILE_NOTIFY_INFORMATION = FILE_NOTIFY_INFORMATION
256 { fniNextEntryOffset :: DWORD
258 , fniFileName :: String
261type LPOVERLAPPED_COMPLETION_ROUTINE =
262 FunPtr ((DWORD, DWORD, LPOVERLAPPED) -> IO ())
264-- | A handle for a watch.
265getWatchHandle :: FilePath -> IO (HANDLE, FilePath)
266getWatchHandle dir = do
271 (fILE_SHARE_READ .|. fILE_SHARE_WRITE)
272 -- Security attributes
274 -- Create mode, we want to look at an existing directory
276 -- File attribute, NOT using OVERLAPPED since we work synchronously
277 fILE_FLAG_BACKUP_SEMANTICS
282-- For reference documentation see:
284-- See https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw
285-- Note that this API uses UTF-16 for file system paths:
286-- 1. https://docs.microsoft.com/en-us/windows/win32/intl/unicode-in-the-windows-api
287-- 2. https://docs.microsoft.com/en-us/windows/win32/intl/unicode
288foreign import ccall safe
289 "windows.h ReadDirectoryChangesW" c_ReadDirectoryChangesW ::
297 -> LPOVERLAPPED_COMPLETION_ROUTINE
300readDirectoryChangesW ::
302 -> Ptr FILE_NOTIFY_INFORMATION
305 -> FileNotificationFlag
308readDirectoryChangesW h buf bufSize wst f br =
309 let res = c_ReadDirectoryChangesW
310 h (castPtr buf) bufSize wst f br nullPtr nullFunPtr
311 in failIfFalse_ "ReadDirectoryChangesW" res
313peekFNI :: Ptr FILE_NOTIFY_INFORMATION -> IO FILE_NOTIFY_INFORMATION
315 neof <- peekByteOff buf 0
316 acti <- peekByteOff buf 4
317 fnle <- peekByteOff buf 8
318 -- Note: The path is UTF-16 encoded C WChars, peekCWStringLen converts
319 -- UTF-16 to UTF-32 Char String
320 fnam <- peekCWStringLen
323 -- fnle is the length in *bytes*, and a WCHAR is 2 bytes
324 fromEnum (fnle :: DWORD) `div` 2)
325 return $ FILE_NOTIFY_INFORMATION neof acti fnam
328 Ptr FILE_NOTIFY_INFORMATION -> String -> DWORD -> IO [Event]
329readChangeEvents pfni root bytesRet = do
332 { eventFlags = fniAction fni
333 , eventRelPath = fniFileName fni
334 , eventRootPath = root
335 , totalBytes = bytesRet
337 nioff = fromEnum $ fniNextEntryOffset fni
341 else readChangeEvents (pfni `plusPtr` nioff) root bytesRet
342 return $ entry : entries
344readDirectoryChanges ::
345 String -> HANDLE -> Bool -> FileNotificationFlag -> IO [Event]
346readDirectoryChanges root h wst mask = do
347 let maxBuf = 63 * 1024
348 allocaBytes maxBuf $ \buffer -> do
350 readDirectoryChangesW h buffer (toEnum maxBuf) wst mask bret
351 bytesRet <- peekByteOff bret 0
352 readChangeEvents buffer root bytesRet
354type FileAction = DWORD
356fILE_ACTION_ADDED :: FileAction
359fILE_ACTION_REMOVED :: FileAction
360fILE_ACTION_REMOVED = 2
362fILE_ACTION_MODIFIED :: FileAction
363fILE_ACTION_MODIFIED = 3
365fILE_ACTION_RENAMED_OLD_NAME :: FileAction
366fILE_ACTION_RENAMED_OLD_NAME = 4
368fILE_ACTION_RENAMED_NEW_NAME :: FileAction
369fILE_ACTION_RENAMED_NEW_NAME = 5
371eventStreamAggr :: (HANDLE, FilePath, Config) -> SerialT IO Event
372eventStreamAggr (handle, rootPath, cfg) = do
373 let recMode = getConfigRecMode cfg
374 flagMasks = getConfigFlag cfg
375 S.concatMap S.fromList $ S.repeatM
376 $ readDirectoryChanges rootPath handle recMode flagMasks
379 NonEmpty FilePath -> Config -> SerialT IO (HANDLE, FilePath, Config)
380pathsToHandles paths cfg = do
381 let pathStream = S.fromList (NonEmpty.toList paths)
382 st2 = S.mapM getWatchHandle pathStream
383 S.map (\(h, f) -> (h, f, cfg)) st2
385-------------------------------------------------------------------------------
387-------------------------------------------------------------------------------
389utf8ToString :: Array Word8 -> FilePath
390utf8ToString = runIdentity . S.toList . U.decodeUtf8 . A.toStream
392utf8ToStringList :: NonEmpty (Array Word8) -> NonEmpty FilePath
393utf8ToStringList = NonEmpty.map utf8ToString
395-- | Close a Directory handle.
399closePathHandleStream :: SerialT IO (HANDLE, FilePath, Config) -> IO ()
400closePathHandleStream = S.mapM_ (\(h, _, _) -> closeHandle h)
402-- | Start monitoring a list of file system paths for file system events with
403-- the supplied configuration operation over the 'defaultConfig'. The
404-- paths could be files or directories. When the path is a directory, only the
405-- files and directories directly under the watched directory are monitored,
406-- contents of subdirectories are not monitored. Monitoring starts from the
407-- current time onwards.
413 -> NonEmpty (Array Word8)
415watchPathsWith f = watchTreesWith (f . setRecursiveMode False)
417-- | Like 'watchPathsWith' but uses the 'defaultConfig' options.
420-- watchPaths = watchPathsWith id
425watchPaths :: NonEmpty (Array Word8) -> SerialT IO Event
426watchPaths = watchPathsWith id
429-- Document the path treatment for Linux/Windows/macOS modules.
430-- Remove the utf-8 encoding requirement of paths? It can be encoding agnostic
431-- "\" separated bytes, the application can decide what encoding to use.
432-- Instead of always using widechar (-W) APIs can we call the underlying APIs
433-- based on the configured code page?
434-- https://docs.microsoft.com/en-us/windows/uwp/design/globalizing/use-utf8-code-page
436-- | Start monitoring a list of file system paths for file system events with
437-- the supplied configuration operation over the 'defaultConfig'. The
438-- paths could be files or directories. When the path is a directory, the
439-- whole directory tree under it is watched recursively. Monitoring starts from
440-- the current time onwards.
446 -> NonEmpty (Array Word8)
448watchTreesWith f paths =
449 S.bracket before after (S.concatMapWith parallel eventStreamAggr)
454 let cfg = f $ setRecursiveMode True defaultConfig
455 in return $ pathsToHandles (utf8ToStringList paths) cfg
456 after = liftIO . closePathHandleStream
458-- | Like 'watchTreesWith' but uses the 'defaultConfig' options.
461-- watchTrees = watchTreesWith id
464watchTrees :: NonEmpty (Array Word8) -> SerialT IO Event
465watchTrees = watchTreesWith id
467-- | Add a trailing "\" at the end of the path if there is none. Do not add a
468-- "\" if the path is empty.
470ensureTrailingSlash :: String -> String
471ensureTrailingSlash path =
476 in if x /= '\\' && x /= '/'
480getFlag :: DWORD -> Event -> Bool
481getFlag mask Event{..} = eventFlags == mask
483-- XXX Change the type to Array Word8 to make it compatible with other APIs.
485-- | Get the file system object path for which the event is generated, relative
486-- to the watched root. The path is a UTF-8 encoded array of bytes.
490getRelPath :: Event -> String
491getRelPath Event{..} = eventRelPath
493-- XXX Change the type to Array Word8 to make it compatible with other APIs.
495-- | Get the watch root directory to which this event belongs.
499getRoot :: Event -> String
500getRoot Event{..} = ensureTrailingSlash eventRootPath
502-- XXX Change the type to Array Word8 to make it compatible with other APIs.
504-- | Get the absolute file system object path for which the event is generated.
505-- The path is a UTF-8 encoded array of bytes.
509getAbsPath :: Event -> String
510getAbsPath ev = getRoot ev <> getRelPath ev
512-- XXX need to document the exact semantics of these.
514-- | File/directory created in watched directory.
518isCreated :: Event -> Bool
519isCreated = getFlag fILE_ACTION_ADDED
521-- | File/directory deleted from watched directory.
525isDeleted :: Event -> Bool
526isDeleted = getFlag fILE_ACTION_REMOVED
528-- | Generated for the original path when an object is moved from under a
529-- monitored directory.
533isMovedFrom :: Event -> Bool
534isMovedFrom = getFlag fILE_ACTION_RENAMED_OLD_NAME
536-- | Generated for the new path when an object is moved under a monitored
541isMovedTo :: Event -> Bool
542isMovedTo = getFlag fILE_ACTION_RENAMED_NEW_NAME
544-- XXX This event is generated only for files and not directories?
546-- | Determine whether the event indicates modification of an object within the
551isModified :: Event -> Bool
552isModified = getFlag fILE_ACTION_MODIFIED
554-- | If the buffer overflows, entire contents of the buffer are discarded,
555-- therefore, events are lost. The user application must scan everything under
556-- the watched paths to know the current state.
560isOverflow :: Event -> Bool
561isOverflow Event{..} = totalBytes == 0
563-------------------------------------------------------------------------------
565-------------------------------------------------------------------------------
567-- | Convert an 'Event' record to a String representation.
568showEvent :: Event -> String
569showEvent ev@Event{..} =
570 "--------------------------"
571 ++ "\nRoot = " ++ show (getRoot ev)
572 ++ "\nRelative Path = " ++ show (getRelPath ev)
573 ++ "\nAbsolute Path = " ++ show (getAbsPath ev)
574 ++ "\nFlags " ++ show eventFlags
575 ++ showev isOverflow "Overflow"
576 ++ showev isCreated "Created"
577 ++ showev isDeleted "Deleted"
578 ++ showev isModified "Modified"
579 ++ showev isMovedFrom "MovedFrom"
580 ++ showev isMovedTo "MovedTo"
583 where showev f str = if f ev then "\n" ++ str else ""
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list