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" );
97 if ( close(m_ifd
) != 0 )
99 wxLogSysError( _("Unable to close inotify instance") );
103 virtual bool DoAdd(wxSharedPtr
<wxFSWatchEntryUnix
> watch
)
105 wxCHECK_MSG( IsOk(), false,
106 "Inotify not initialized or invalid inotify descriptor" );
108 int wd
= DoAddInotify(watch
.get());
111 wxLogSysError( _("Unable to add inotify watch") );
115 wxFSWatchEntryDescriptors::value_type
val(wd
, watch
.get());
116 if (!m_watchMap
.insert(val
).second
)
118 wxFAIL_MSG( wxString::Format( "Path %s is already watched",
126 virtual bool DoRemove(wxSharedPtr
<wxFSWatchEntryUnix
> watch
)
128 wxCHECK_MSG( IsOk(), false,
129 "Inotify not initialized or invalid inotify descriptor" );
131 int ret
= DoRemoveInotify(watch
.get());
134 wxLogSysError( _("Unable to remove inotify watch") );
138 if (m_watchMap
.erase(watch
->GetWatchDescriptor()) != 1)
140 wxFAIL_MSG( wxString::Format("Path %s is not watched",
143 watch
->SetWatchDescriptor(-1);
147 virtual bool RemoveAll()
149 wxFSWatchEntries::iterator it
= m_watches
.begin();
150 for ( ; it
!= m_watches
.end(); ++it
)
152 (void) DoRemove(it
->second
);
160 wxCHECK_MSG( IsOk(), -1,
161 "Inotify not initialized or invalid inotify descriptor" );
164 // TODO differentiate depending on params
165 char buf
[128 * sizeof(inotify_event
)];
166 int left
= ReadEventsToBuf(buf
, sizeof(buf
));
170 // left > 0, we have events
173 while (left
> 0) // OPT checking 'memory' would suffice
176 inotify_event
* e
= (inotify_event
*)memory
;
178 // process one inotify_event
179 ProcessNativeEvent(*e
);
181 int offset
= sizeof(inotify_event
) + e
->len
;
186 // take care of unmatched renames
189 wxLogTrace(wxTRACE_FSWATCHER
, "We had %d native events", event_count
);
195 return m_source
!= NULL
;
199 int DoAddInotify(wxFSWatchEntry
* watch
)
201 int flags
= Watcher2NativeFlags(watch
->GetFlags());
202 int wd
= inotify_add_watch(m_ifd
, watch
->GetPath().fn_str(), flags
);
203 // finally we can set watch descriptor
204 watch
->SetWatchDescriptor(wd
);
208 int DoRemoveInotify(wxFSWatchEntry
* watch
)
210 return inotify_rm_watch(m_ifd
, watch
->GetWatchDescriptor());
213 void ProcessNativeEvent(const inotify_event
& inevt
)
215 wxLogTrace(wxTRACE_FSWATCHER
, InotifyEventToString(inevt
));
217 // after removing inotify watch we get IN_IGNORED for it, but the watch
218 // will be already removed from our list at that time
219 if (inevt
.mask
& IN_IGNORED
)
224 // get watch entry for this event
225 wxFSWatchEntryDescriptors::iterator it
= m_watchMap
.find(inevt
.wd
);
226 wxCHECK_RET(it
!= m_watchMap
.end(),
227 "Watch descriptor not present in the watch map!");
229 wxFSWatchEntry
& watch
= *(it
->second
);
230 int nativeFlags
= inevt
.mask
;
231 int flags
= Native2WatcherFlags(nativeFlags
);
233 // check out for error/warning condition
234 if (flags
& wxFSW_EVENT_WARNING
|| flags
& wxFSW_EVENT_ERROR
)
236 wxString errMsg
= GetErrorDescription(Watcher2NativeFlags(flags
));
237 wxFileSystemWatcherEvent
event(flags
, errMsg
);
240 // filter out ignored events and those not asked for.
241 // we never filter out warnings or exceptions
242 else if ((flags
== 0) || !(flags
& watch
.GetFlags()))
247 else if (nativeFlags
& IN_MOVE
)
249 wxInotifyCookies::iterator it
= m_cookies
.find(inevt
.cookie
);
250 if ( it
== m_cookies
.end() )
252 int size
= sizeof(inevt
) + inevt
.len
;
253 inotify_event
* e
= (inotify_event
*) operator new (size
);
254 memcpy(e
, &inevt
, size
);
256 wxInotifyCookies::value_type
val(e
->cookie
, e
);
257 m_cookies
.insert(val
);
261 inotify_event
& oldinevt
= *(it
->second
);
263 wxFileSystemWatcherEvent
event(flags
);
264 if ( inevt
.mask
& IN_MOVED_FROM
)
266 event
.SetPath(GetEventPath(watch
, inevt
));
267 event
.SetNewPath(GetEventPath(watch
, oldinevt
));
271 event
.SetPath(GetEventPath(watch
, oldinevt
));
272 event
.SetNewPath(GetEventPath(watch
, inevt
));
280 // every other kind of event
283 wxFileName path
= GetEventPath(watch
, inevt
);
284 wxFileSystemWatcherEvent
event(flags
, path
, path
);
289 void ProcessRenames()
291 wxInotifyCookies::iterator it
= m_cookies
.begin();
292 while ( it
!= m_cookies
.end() )
294 inotify_event
& inevt
= *(it
->second
);
296 wxLogTrace(wxTRACE_FSWATCHER
, "Processing pending rename events");
297 wxLogTrace(wxTRACE_FSWATCHER
, InotifyEventToString(inevt
));
299 // get watch entry for this event
300 wxFSWatchEntryDescriptors::iterator wit
= m_watchMap
.find(inevt
.wd
);
301 wxCHECK_RET(wit
!= m_watchMap
.end(),
302 "Watch descriptor not present in the watch map!");
304 wxFSWatchEntry
& watch
= *(wit
->second
);
305 int flags
= Native2WatcherFlags(inevt
.mask
);
306 wxFileName path
= GetEventPath(watch
, inevt
);
307 wxFileSystemWatcherEvent
event(flags
, path
, path
);
312 it
= m_cookies
.begin();
316 void SendEvent(wxFileSystemWatcherEvent
& evt
)
318 wxLogTrace(wxTRACE_FSWATCHER
, evt
.ToString());
319 m_watcher
->GetOwner()->ProcessEvent(evt
);
322 int ReadEventsToBuf(char* buf
, int size
)
324 wxCHECK_MSG( IsOk(), false,
325 "Inotify not initialized or invalid inotify descriptor" );
327 memset(buf
, 0, size
);
328 ssize_t left
= read(m_ifd
, buf
, size
);
331 wxLogSysError(_("Unable to read from inotify descriptor"));
336 wxLogWarning(_("EOF while reading from inotify descriptor"));
343 static wxString
InotifyEventToString(const inotify_event
& inevt
)
345 wxString mask
= (inevt
.mask
& IN_ISDIR
) ?
346 wxString::Format("IS_DIR | %u", inevt
.mask
& ~IN_ISDIR
) :
347 wxString::Format("%u", inevt
.mask
);
348 return wxString::Format("Event: wd=%d, mask=%s, cookie=%u, len=%u, "
349 "name=%s", inevt
.wd
, mask
, inevt
.cookie
,
350 inevt
.len
, inevt
.name
);
353 static wxFileName
GetEventPath(const wxFSWatchEntry
& watch
,
354 const inotify_event
& inevt
)
356 // only when dir is watched, we have non-empty e.name
357 wxFileName path
= watch
.GetPath();
360 path
= wxFileName(path
.GetPath(), inevt
.name
);
365 static int Watcher2NativeFlags(int WXUNUSED(flags
))
367 // TODO: it would be nice to subscribe only to the events we really need
368 return IN_ALL_EVENTS
;
371 static int Native2WatcherFlags(int flags
)
373 static const int flag_mapping
[][2] = {
374 { IN_ACCESS
, wxFSW_EVENT_ACCESS
}, // generated during read!
375 { IN_MODIFY
, wxFSW_EVENT_MODIFY
},
377 { IN_CLOSE_WRITE
, 0 },
378 { IN_CLOSE_NOWRITE
, 0 },
380 { IN_MOVED_FROM
, wxFSW_EVENT_RENAME
},
381 { IN_MOVED_TO
, wxFSW_EVENT_RENAME
},
382 { IN_CREATE
, wxFSW_EVENT_CREATE
},
383 { IN_DELETE
, wxFSW_EVENT_DELETE
},
384 { IN_DELETE_SELF
, wxFSW_EVENT_DELETE
},
385 { IN_MOVE_SELF
, wxFSW_EVENT_DELETE
},
387 { IN_UNMOUNT
, wxFSW_EVENT_ERROR
},
388 { IN_Q_OVERFLOW
, wxFSW_EVENT_WARNING
},
390 // ignored, because this is genereted mainly by watcher::Remove()
395 for ( ; i
< WXSIZEOF(flag_mapping
); ++i
) {
396 // in this mapping multiple flags at once don't happen
397 if (flags
& flag_mapping
[i
][0])
398 return flag_mapping
[i
][1];
402 wxFAIL_MSG(wxString::Format("Unknown inotify event mask %u", flags
));
407 * Returns error description for specified inotify mask
409 static const wxString
GetErrorDescription(int flag
)
414 return _("File system containing watched object was unmounted");
416 return _("Event queue overflowed");
420 wxFAIL_MSG(wxString::Format("Unknown inotify event mask %u", flag
));
421 return wxEmptyString
;
424 wxFSWSourceHandler
* m_handler
; // handler for inotify event source
425 wxFSWatchEntryDescriptors m_watchMap
; // inotify wd=>wxFSWatchEntry* map
426 wxInotifyCookies m_cookies
; // map to track renames
427 wxEventLoopSource
* m_source
; // our event loop source
429 // file descriptor created by inotify_init()
434 // ============================================================================
435 // wxFSWSourceHandler implementation
436 // ============================================================================
438 // once we get signaled to read, actuall event reading occurs
439 void wxFSWSourceHandler::OnReadWaiting()
441 wxLogTrace(wxTRACE_FSWATCHER
, "--- OnReadWaiting ---");
442 m_service
->ReadEvents();
445 void wxFSWSourceHandler::OnWriteWaiting()
447 wxFAIL_MSG("We never write to inotify descriptor.");
450 void wxFSWSourceHandler::OnExceptionWaiting()
452 wxFAIL_MSG("We never receive exceptions on inotify descriptor.");
456 // ============================================================================
457 // wxInotifyFileSystemWatcher implementation
458 // ============================================================================
460 wxInotifyFileSystemWatcher::wxInotifyFileSystemWatcher()
461 : wxFileSystemWatcherBase()
466 wxInotifyFileSystemWatcher::wxInotifyFileSystemWatcher(const wxFileName
& path
,
468 : wxFileSystemWatcherBase()
480 wxInotifyFileSystemWatcher::~wxInotifyFileSystemWatcher()
484 bool wxInotifyFileSystemWatcher::Init()
486 m_service
= new wxFSWatcherImplUnix(this);
487 return m_service
->Init();
490 #endif // wxHAS_INOTIFY
492 #endif // wxUSE_FSWATCHER