1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/fswatcher_inotify.cpp
3 // Purpose: inotify-based wxFileSystemWatcher implementation
4 // Author: Bartosz Bekier
7 // Copyright: (c) 2009 Bartosz Bekier <bartosz.bekier@gmail.com>
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
20 #include "wx/fswatcher.h"
24 #include <sys/inotify.h>
26 #include "wx/private/fswatcher.h"
28 // ============================================================================
29 // wxFSWatcherImpl implementation & helper wxFSWSourceHandler implementation
30 // ============================================================================
32 // inotify watch descriptor => wxFSWatchEntry* map
33 WX_DECLARE_HASH_MAP(int, wxFSWatchEntry
*, wxIntegerHash
, wxIntegerEqual
,
34 wxFSWatchEntryDescriptors
);
36 // inotify event cookie => inotify_event* map
37 WX_DECLARE_HASH_MAP(int, inotify_event
*, wxIntegerHash
, wxIntegerEqual
,
41 * Helper class encapsulating inotify mechanism
43 class wxFSWatcherImplUnix
: public wxFSWatcherImpl
46 wxFSWatcherImplUnix(wxFileSystemWatcherBase
* watcher
) :
47 wxFSWatcherImpl(watcher
),
51 m_handler
= new wxFSWSourceHandler(this);
54 ~wxFSWatcherImplUnix()
56 // we close inotify only if initialized before
67 wxCHECK_MSG( !IsOk(), false, "Inotify already initialized" );
69 wxEventLoopBase
*loop
= wxEventLoopBase
::GetActive();
70 wxCHECK_MSG( loop
, false, "File system watcher needs an event loop" );
72 m_ifd
= inotify_init();
75 wxLogSysError( _("Unable to create inotify instance") );
79 m_source
= loop
->AddSourceForFD
83 wxEVENT_SOURCE_INPUT
| wxEVENT_SOURCE_EXCEPTION
86 return m_source
!= NULL
;
92 "Inotify not initialized or invalid inotify descriptor" );
96 if ( close(m_ifd
) != 0 )
98 wxLogSysError( _("Unable to close inotify instance") );
102 virtual bool DoAdd(wxSharedPtr
<wxFSWatchEntryUnix
> watch
)
104 wxCHECK_MSG( IsOk(), false,
105 "Inotify not initialized or invalid inotify descriptor" );
107 int wd
= DoAddInotify(watch
.get());
110 wxLogSysError( _("Unable to add inotify watch") );
114 wxFSWatchEntryDescriptors
::value_type
val(wd
, watch
.get());
115 if (!m_watchMap
.insert(val
).second
)
117 wxFAIL_MSG( wxString
::Format( "Path %s is already watched",
125 virtual bool DoRemove(wxSharedPtr
<wxFSWatchEntryUnix
> watch
)
127 wxCHECK_MSG( IsOk(), false,
128 "Inotify not initialized or invalid inotify descriptor" );
130 int ret
= DoRemoveInotify(watch
.get());
133 wxLogSysError( _("Unable to remove inotify watch") );
137 if (m_watchMap
.erase(watch
->GetWatchDescriptor()) != 1)
139 wxFAIL_MSG( wxString
::Format("Path %s is not watched",
142 // Cache the wd in case any events arrive late
143 m_staleDescriptors
.Add(watch
->GetWatchDescriptor());
145 watch
->SetWatchDescriptor(-1);
149 virtual bool RemoveAll()
151 wxFSWatchEntries
::iterator it
= m_watches
.begin();
152 for ( ; it
!= m_watches
.end(); ++it
)
154 (void) DoRemove(it
->second
);
162 wxCHECK_MSG( IsOk(), -1,
163 "Inotify not initialized or invalid inotify descriptor" );
166 // TODO differentiate depending on params
167 char buf
[128 * sizeof(inotify_event
)];
168 int left
= ReadEventsToBuf(buf
, sizeof(buf
));
172 // left > 0, we have events
175 while (left
> 0) // OPT checking 'memory' would suffice
178 inotify_event
* e
= (inotify_event
*)memory
;
180 // process one inotify_event
181 ProcessNativeEvent(*e
);
183 int offset
= sizeof(inotify_event
) + e
->len
;
188 // take care of unmatched renames
191 wxLogTrace(wxTRACE_FSWATCHER
, "We had %d native events", event_count
);
197 return m_source
!= NULL
;
201 int DoAddInotify(wxFSWatchEntry
* watch
)
203 int flags
= Watcher2NativeFlags(watch
->GetFlags());
204 int wd
= inotify_add_watch(m_ifd
, watch
->GetPath().fn_str(), flags
);
205 // finally we can set watch descriptor
206 watch
->SetWatchDescriptor(wd
);
210 int DoRemoveInotify(wxFSWatchEntry
* watch
)
212 return inotify_rm_watch(m_ifd
, watch
->GetWatchDescriptor());
215 void ProcessNativeEvent(const inotify_event
& inevt
)
217 wxLogTrace(wxTRACE_FSWATCHER
, InotifyEventToString(inevt
));
219 // after removing inotify watch we get IN_IGNORED for it, but the watch
220 // will be already removed from our list at that time
221 if (inevt
.mask
& IN_IGNORED
)
223 // It is now safe to remove it from the stale descriptors too, we
224 // won't get any more events for it.
225 // However if we're here because a dir that we're still watching
226 // has just been deleted, its wd won't be on this list
227 const int pos
= m_staleDescriptors
.Index(inevt
.wd
);
228 if ( pos
!= wxNOT_FOUND
)
230 m_staleDescriptors
.RemoveAt(static_cast<size_t>(pos
));
231 wxLogTrace(wxTRACE_FSWATCHER
,
232 "Removed wd %i from the stale-wd cache", inevt
.wd
);
237 // get watch entry for this event
238 wxFSWatchEntryDescriptors
::iterator it
= m_watchMap
.find(inevt
.wd
);
239 if (it
== m_watchMap
.end())
241 // It's not in the map; check if was recently removed from it.
242 if (m_staleDescriptors
.Index(inevt
.wd
) != wxNOT_FOUND
)
244 wxLogTrace(wxTRACE_FSWATCHER
,
245 "Got an event for stale wd %i", inevt
.wd
);
249 wxFAIL_MSG("Event for unknown watch descriptor.");
252 // In any case, don't process this event: it's either for an
253 // already removed entry, or for a completely unknown one.
257 wxFSWatchEntry
& watch
= *(it
->second
);
258 int nativeFlags
= inevt
.mask
;
259 int flags
= Native2WatcherFlags(nativeFlags
);
261 // check out for error/warning condition
262 if (flags
& wxFSW_EVENT_WARNING
|| flags
& wxFSW_EVENT_ERROR
)
264 wxString errMsg
= GetErrorDescription(Watcher2NativeFlags(flags
));
265 wxFileSystemWatcherEvent
event(flags
, errMsg
);
268 // filter out ignored events and those not asked for.
269 // we never filter out warnings or exceptions
270 else if ((flags
== 0) || !(flags
& watch
.GetFlags()))
275 else if (nativeFlags
& IN_MOVE
)
277 wxInotifyCookies
::iterator it2
= m_cookies
.find(inevt
.cookie
);
278 if ( it2
== m_cookies
.end() )
280 int size
= sizeof(inevt
) + inevt
.len
;
281 inotify_event
* e
= (inotify_event
*) operator new (size
);
282 memcpy(e
, &inevt
, size
);
284 wxInotifyCookies
::value_type
val(e
->cookie
, e
);
285 m_cookies
.insert(val
);
289 inotify_event
& oldinevt
= *(it2
->second
);
291 // Tell the owner, in case it's interested
292 // If there's a filespec, assume he's not
293 if ( watch
.GetFilespec().empty() )
295 wxFileSystemWatcherEvent
event(flags
);
296 if ( inevt
.mask
& IN_MOVED_FROM
)
298 event
.SetPath(GetEventPath(watch
, inevt
));
299 event
.SetNewPath(GetEventPath(watch
, oldinevt
));
303 event
.SetPath(GetEventPath(watch
, oldinevt
));
304 event
.SetNewPath(GetEventPath(watch
, inevt
));
309 m_cookies
.erase(it2
);
313 // every other kind of event
316 wxFileName path
= GetEventPath(watch
, inevt
);
317 // For files, check that it matches any filespec
318 if ( MatchesFilespec(path
, watch
.GetFilespec()) )
320 wxFileSystemWatcherEvent
event(flags
, path
, path
);
326 void ProcessRenames()
328 wxInotifyCookies
::iterator it
= m_cookies
.begin();
329 while ( it
!= m_cookies
.end() )
331 inotify_event
& inevt
= *(it
->second
);
333 wxLogTrace(wxTRACE_FSWATCHER
, "Processing pending rename events");
334 wxLogTrace(wxTRACE_FSWATCHER
, InotifyEventToString(inevt
));
336 // get watch entry for this event
337 wxFSWatchEntryDescriptors
::iterator wit
= m_watchMap
.find(inevt
.wd
);
338 wxCHECK_RET(wit
!= m_watchMap
.end(),
339 "Watch descriptor not present in the watch map!");
341 // Tell the owner, in case it's interested
342 // If there's a filespec, assume he's not
343 wxFSWatchEntry
& watch
= *(wit
->second
);
344 if ( watch
.GetFilespec().empty() )
346 int flags
= Native2WatcherFlags(inevt
.mask
);
347 wxFileName path
= GetEventPath(watch
, inevt
);
349 wxFileSystemWatcherEvent
event(flags
, path
, path
);
356 it
= m_cookies
.begin();
360 void SendEvent(wxFileSystemWatcherEvent
& evt
)
362 wxLogTrace(wxTRACE_FSWATCHER
, evt
.ToString());
363 m_watcher
->GetOwner()->ProcessEvent(evt
);
366 int ReadEventsToBuf(char* buf
, int size
)
368 wxCHECK_MSG( IsOk(), false,
369 "Inotify not initialized or invalid inotify descriptor" );
371 memset(buf
, 0, size
);
372 ssize_t left
= read(m_ifd
, buf
, size
);
375 wxLogSysError(_("Unable to read from inotify descriptor"));
380 wxLogWarning(_("EOF while reading from inotify descriptor"));
387 static wxString
InotifyEventToString(const inotify_event
& inevt
)
389 wxString mask
= (inevt
.mask
& IN_ISDIR
) ?
390 wxString
::Format("IS_DIR | %u", inevt
.mask
& ~IN_ISDIR
) :
391 wxString
::Format("%u", inevt
.mask
);
392 const char* name
= "";
395 return wxString
::Format("Event: wd=%d, mask=%s, cookie=%u, len=%u, "
396 "name=%s", inevt
.wd
, mask
, inevt
.cookie
,
400 static wxFileName
GetEventPath(const wxFSWatchEntry
& watch
,
401 const inotify_event
& inevt
)
403 // only when dir is watched, we have non-empty e.name
404 wxFileName path
= watch
.GetPath();
405 if (path
.IsDir() && inevt
.len
)
407 path
= wxFileName(path
.GetPath(), inevt
.name
);
412 static int Watcher2NativeFlags(int WXUNUSED(flags
))
414 // TODO: it would be nice to subscribe only to the events we really need
415 return IN_ALL_EVENTS
;
418 static int Native2WatcherFlags(int flags
)
420 static const int flag_mapping
[][2] = {
421 { IN_ACCESS
, wxFSW_EVENT_ACCESS
}, // generated during read!
422 { IN_MODIFY
, wxFSW_EVENT_MODIFY
},
424 { IN_CLOSE_WRITE
, 0 },
425 { IN_CLOSE_NOWRITE
, 0 },
427 { IN_MOVED_FROM
, wxFSW_EVENT_RENAME
},
428 { IN_MOVED_TO
, wxFSW_EVENT_RENAME
},
429 { IN_CREATE
, wxFSW_EVENT_CREATE
},
430 { IN_DELETE
, wxFSW_EVENT_DELETE
},
431 { IN_DELETE_SELF
, wxFSW_EVENT_DELETE
},
432 { IN_MOVE_SELF
, wxFSW_EVENT_DELETE
},
434 { IN_UNMOUNT
, wxFSW_EVENT_ERROR
},
435 { IN_Q_OVERFLOW
, wxFSW_EVENT_WARNING
},
437 // ignored, because this is genereted mainly by watcher::Remove()
442 for ( ; i
< WXSIZEOF(flag_mapping
); ++i
) {
443 // in this mapping multiple flags at once don't happen
444 if (flags
& flag_mapping
[i
][0])
445 return flag_mapping
[i
][1];
449 wxFAIL_MSG(wxString
::Format("Unknown inotify event mask %u", flags
));
454 * Returns error description for specified inotify mask
456 static const wxString
GetErrorDescription(int flag
)
461 return _("File system containing watched object was unmounted");
463 return _("Event queue overflowed");
467 wxFAIL_MSG(wxString
::Format("Unknown inotify event mask %u", flag
));
468 return wxEmptyString
;
471 wxFSWSourceHandler
* m_handler
; // handler for inotify event source
472 wxFSWatchEntryDescriptors m_watchMap
; // inotify wd=>wxFSWatchEntry* map
473 wxArrayInt m_staleDescriptors
; // stores recently-removed watches
474 wxInotifyCookies m_cookies
; // map to track renames
475 wxEventLoopSource
* m_source
; // our event loop source
477 // file descriptor created by inotify_init()
482 // ============================================================================
483 // wxFSWSourceHandler implementation
484 // ============================================================================
486 // once we get signaled to read, actuall event reading occurs
487 void wxFSWSourceHandler
::OnReadWaiting()
489 wxLogTrace(wxTRACE_FSWATCHER
, "--- OnReadWaiting ---");
490 m_service
->ReadEvents();
493 void wxFSWSourceHandler
::OnWriteWaiting()
495 wxFAIL_MSG("We never write to inotify descriptor.");
498 void wxFSWSourceHandler
::OnExceptionWaiting()
500 wxFAIL_MSG("We never receive exceptions on inotify descriptor.");
504 // ============================================================================
505 // wxInotifyFileSystemWatcher implementation
506 // ============================================================================
508 wxInotifyFileSystemWatcher
::wxInotifyFileSystemWatcher()
509 : wxFileSystemWatcherBase()
514 wxInotifyFileSystemWatcher
::wxInotifyFileSystemWatcher(const wxFileName
& path
,
516 : wxFileSystemWatcherBase()
528 wxInotifyFileSystemWatcher
::~wxInotifyFileSystemWatcher()
532 bool wxInotifyFileSystemWatcher
::Init()
534 m_service
= new wxFSWatcherImplUnix(this);
535 return m_service
->Init();
538 #endif // wxHAS_INOTIFY
540 #endif // wxUSE_FSWATCHER