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 m_staleDescriptors
.Remove(inevt
.wd
);
226 wxLogTrace(wxTRACE_FSWATCHER
,
227 "Removed wd %i from the stale-wd cache", inevt
.wd
);
231 // get watch entry for this event
232 wxFSWatchEntryDescriptors::iterator it
= m_watchMap
.find(inevt
.wd
);
233 if (it
== m_watchMap
.end())
235 // It's not in the map; check if was recently removed from it.
236 if (m_staleDescriptors
.Index(inevt
.wd
) != wxNOT_FOUND
)
238 wxLogTrace(wxTRACE_FSWATCHER
,
239 "Got an event for stale wd %i", inevt
.wd
);
243 wxFAIL_MSG("Event for unknown watch descriptor.");
246 // In any case, don't process this event: it's either for an
247 // already removed entry, or for a completely unknown one.
251 wxFSWatchEntry
& watch
= *(it
->second
);
252 int nativeFlags
= inevt
.mask
;
253 int flags
= Native2WatcherFlags(nativeFlags
);
255 // check out for error/warning condition
256 if (flags
& wxFSW_EVENT_WARNING
|| flags
& wxFSW_EVENT_ERROR
)
258 wxString errMsg
= GetErrorDescription(Watcher2NativeFlags(flags
));
259 wxFileSystemWatcherEvent
event(flags
, errMsg
);
262 // filter out ignored events and those not asked for.
263 // we never filter out warnings or exceptions
264 else if ((flags
== 0) || !(flags
& watch
.GetFlags()))
269 else if (nativeFlags
& IN_MOVE
)
271 wxInotifyCookies::iterator it
= m_cookies
.find(inevt
.cookie
);
272 if ( it
== m_cookies
.end() )
274 int size
= sizeof(inevt
) + inevt
.len
;
275 inotify_event
* e
= (inotify_event
*) operator new (size
);
276 memcpy(e
, &inevt
, size
);
278 wxInotifyCookies::value_type
val(e
->cookie
, e
);
279 m_cookies
.insert(val
);
283 inotify_event
& oldinevt
= *(it
->second
);
285 wxFileSystemWatcherEvent
event(flags
);
286 if ( inevt
.mask
& IN_MOVED_FROM
)
288 event
.SetPath(GetEventPath(watch
, inevt
));
289 event
.SetNewPath(GetEventPath(watch
, oldinevt
));
293 event
.SetPath(GetEventPath(watch
, oldinevt
));
294 event
.SetNewPath(GetEventPath(watch
, inevt
));
302 // every other kind of event
305 wxFileName path
= GetEventPath(watch
, inevt
);
306 wxFileSystemWatcherEvent
event(flags
, path
, path
);
311 void ProcessRenames()
313 wxInotifyCookies::iterator it
= m_cookies
.begin();
314 while ( it
!= m_cookies
.end() )
316 inotify_event
& inevt
= *(it
->second
);
318 wxLogTrace(wxTRACE_FSWATCHER
, "Processing pending rename events");
319 wxLogTrace(wxTRACE_FSWATCHER
, InotifyEventToString(inevt
));
321 // get watch entry for this event
322 wxFSWatchEntryDescriptors::iterator wit
= m_watchMap
.find(inevt
.wd
);
323 wxCHECK_RET(wit
!= m_watchMap
.end(),
324 "Watch descriptor not present in the watch map!");
326 wxFSWatchEntry
& watch
= *(wit
->second
);
327 int flags
= Native2WatcherFlags(inevt
.mask
);
328 wxFileName path
= GetEventPath(watch
, inevt
);
329 wxFileSystemWatcherEvent
event(flags
, path
, path
);
334 it
= m_cookies
.begin();
338 void SendEvent(wxFileSystemWatcherEvent
& evt
)
340 wxLogTrace(wxTRACE_FSWATCHER
, evt
.ToString());
341 m_watcher
->GetOwner()->ProcessEvent(evt
);
344 int ReadEventsToBuf(char* buf
, int size
)
346 wxCHECK_MSG( IsOk(), false,
347 "Inotify not initialized or invalid inotify descriptor" );
349 memset(buf
, 0, size
);
350 ssize_t left
= read(m_ifd
, buf
, size
);
353 wxLogSysError(_("Unable to read from inotify descriptor"));
358 wxLogWarning(_("EOF while reading from inotify descriptor"));
365 static wxString
InotifyEventToString(const inotify_event
& inevt
)
367 wxString mask
= (inevt
.mask
& IN_ISDIR
) ?
368 wxString::Format("IS_DIR | %u", inevt
.mask
& ~IN_ISDIR
) :
369 wxString::Format("%u", inevt
.mask
);
370 const char* name
= "";
373 return wxString::Format("Event: wd=%d, mask=%s, cookie=%u, len=%u, "
374 "name=%s", inevt
.wd
, mask
, inevt
.cookie
,
378 static wxFileName
GetEventPath(const wxFSWatchEntry
& watch
,
379 const inotify_event
& inevt
)
381 // only when dir is watched, we have non-empty e.name
382 wxFileName path
= watch
.GetPath();
383 if (path
.IsDir() && inevt
.len
)
385 path
= wxFileName(path
.GetPath(), inevt
.name
);
390 static int Watcher2NativeFlags(int WXUNUSED(flags
))
392 // TODO: it would be nice to subscribe only to the events we really need
393 return IN_ALL_EVENTS
;
396 static int Native2WatcherFlags(int flags
)
398 static const int flag_mapping
[][2] = {
399 { IN_ACCESS
, wxFSW_EVENT_ACCESS
}, // generated during read!
400 { IN_MODIFY
, wxFSW_EVENT_MODIFY
},
402 { IN_CLOSE_WRITE
, 0 },
403 { IN_CLOSE_NOWRITE
, 0 },
405 { IN_MOVED_FROM
, wxFSW_EVENT_RENAME
},
406 { IN_MOVED_TO
, wxFSW_EVENT_RENAME
},
407 { IN_CREATE
, wxFSW_EVENT_CREATE
},
408 { IN_DELETE
, wxFSW_EVENT_DELETE
},
409 { IN_DELETE_SELF
, wxFSW_EVENT_DELETE
},
410 { IN_MOVE_SELF
, wxFSW_EVENT_DELETE
},
412 { IN_UNMOUNT
, wxFSW_EVENT_ERROR
},
413 { IN_Q_OVERFLOW
, wxFSW_EVENT_WARNING
},
415 // ignored, because this is genereted mainly by watcher::Remove()
420 for ( ; i
< WXSIZEOF(flag_mapping
); ++i
) {
421 // in this mapping multiple flags at once don't happen
422 if (flags
& flag_mapping
[i
][0])
423 return flag_mapping
[i
][1];
427 wxFAIL_MSG(wxString::Format("Unknown inotify event mask %u", flags
));
432 * Returns error description for specified inotify mask
434 static const wxString
GetErrorDescription(int flag
)
439 return _("File system containing watched object was unmounted");
441 return _("Event queue overflowed");
445 wxFAIL_MSG(wxString::Format("Unknown inotify event mask %u", flag
));
446 return wxEmptyString
;
449 wxFSWSourceHandler
* m_handler
; // handler for inotify event source
450 wxFSWatchEntryDescriptors m_watchMap
; // inotify wd=>wxFSWatchEntry* map
451 wxArrayInt m_staleDescriptors
; // stores recently-removed watches
452 wxInotifyCookies m_cookies
; // map to track renames
453 wxEventLoopSource
* m_source
; // our event loop source
455 // file descriptor created by inotify_init()
460 // ============================================================================
461 // wxFSWSourceHandler implementation
462 // ============================================================================
464 // once we get signaled to read, actuall event reading occurs
465 void wxFSWSourceHandler::OnReadWaiting()
467 wxLogTrace(wxTRACE_FSWATCHER
, "--- OnReadWaiting ---");
468 m_service
->ReadEvents();
471 void wxFSWSourceHandler::OnWriteWaiting()
473 wxFAIL_MSG("We never write to inotify descriptor.");
476 void wxFSWSourceHandler::OnExceptionWaiting()
478 wxFAIL_MSG("We never receive exceptions on inotify descriptor.");
482 // ============================================================================
483 // wxInotifyFileSystemWatcher implementation
484 // ============================================================================
486 wxInotifyFileSystemWatcher::wxInotifyFileSystemWatcher()
487 : wxFileSystemWatcherBase()
492 wxInotifyFileSystemWatcher::wxInotifyFileSystemWatcher(const wxFileName
& path
,
494 : wxFileSystemWatcherBase()
506 wxInotifyFileSystemWatcher::~wxInotifyFileSystemWatcher()
510 bool wxInotifyFileSystemWatcher::Init()
512 m_service
= new wxFSWatcherImplUnix(this);
513 return m_service
->Init();
516 #endif // wxHAS_INOTIFY
518 #endif // wxUSE_FSWATCHER