]> git.saurik.com Git - wxWidgets.git/blob - src/unix/fswatcher_inotify.cpp
Fixed wxRichTextCtrl caret test case
[wxWidgets.git] / src / unix / fswatcher_inotify.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/fswatcher_inotify.cpp
3 // Purpose: inotify-based wxFileSystemWatcher implementation
4 // Author: Bartosz Bekier
5 // Created: 2009-05-26
6 // RCS-ID: $Id$
7 // Copyright: (c) 2009 Bartosz Bekier <bartosz.bekier@gmail.com>
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
13
14 #ifdef __BORLANDC__
15 #pragma hdrstop
16 #endif
17
18 #if wxUSE_FSWATCHER
19
20 #include "wx/fswatcher.h"
21
22 #ifdef wxHAS_INOTIFY
23
24 #include <sys/inotify.h>
25 #include <unistd.h>
26 #include "wx/private/fswatcher.h"
27
28 // ============================================================================
29 // wxFSWatcherImpl implementation & helper wxFSWSourceHandler implementation
30 // ============================================================================
31
32 // inotify watch descriptor => wxFSWatchEntry* map
33 WX_DECLARE_HASH_MAP(int, wxFSWatchEntry*, wxIntegerHash, wxIntegerEqual,
34 wxFSWatchEntryDescriptors);
35
36 // inotify event cookie => inotify_event* map
37 WX_DECLARE_HASH_MAP(int, inotify_event*, wxIntegerHash, wxIntegerEqual,
38 wxInotifyCookies);
39
40 /**
41 * Helper class encapsulating inotify mechanism
42 */
43 class wxFSWatcherImplUnix : public wxFSWatcherImpl
44 {
45 public:
46 wxFSWatcherImplUnix(wxFileSystemWatcherBase* watcher) :
47 wxFSWatcherImpl(watcher),
48 m_source(NULL),
49 m_ifd(-1)
50 {
51 m_handler = new wxFSWSourceHandler(this);
52 }
53
54 ~wxFSWatcherImplUnix()
55 {
56 // we close inotify only if initialized before
57 if (IsOk())
58 {
59 Close();
60 }
61
62 delete m_handler;
63 }
64
65 bool Init()
66 {
67 wxCHECK_MSG( !IsOk(), false, "Inotify already initialized" );
68
69 wxEventLoopBase *loop = wxEventLoopBase::GetActive();
70 wxCHECK_MSG( loop, false, "File system watcher needs an event loop" );
71
72 m_ifd = inotify_init();
73 if ( m_ifd == -1 )
74 {
75 wxLogSysError( _("Unable to create inotify instance") );
76 return false;
77 }
78
79 m_source = loop->AddSourceForFD
80 (
81 m_ifd,
82 m_handler,
83 wxEVENT_SOURCE_INPUT | wxEVENT_SOURCE_EXCEPTION
84 );
85
86 return m_source != NULL;
87 }
88
89 void Close()
90 {
91 wxCHECK_RET( IsOk(),
92 "Inotify not initialized or invalid inotify descriptor" );
93
94 wxDELETE(m_source);
95
96 if ( close(m_ifd) != 0 )
97 {
98 wxLogSysError( _("Unable to close inotify instance") );
99 }
100 }
101
102 virtual bool DoAdd(wxSharedPtr<wxFSWatchEntryUnix> watch)
103 {
104 wxCHECK_MSG( IsOk(), false,
105 "Inotify not initialized or invalid inotify descriptor" );
106
107 int wd = DoAddInotify(watch.get());
108 if (wd == -1)
109 {
110 wxLogSysError( _("Unable to add inotify watch") );
111 return false;
112 }
113
114 wxFSWatchEntryDescriptors::value_type val(wd, watch.get());
115 if (!m_watchMap.insert(val).second)
116 {
117 wxFAIL_MSG( wxString::Format( "Path %s is already watched",
118 watch->GetPath()) );
119 return false;
120 }
121
122 return true;
123 }
124
125 virtual bool DoRemove(wxSharedPtr<wxFSWatchEntryUnix> watch)
126 {
127 wxCHECK_MSG( IsOk(), false,
128 "Inotify not initialized or invalid inotify descriptor" );
129
130 int ret = DoRemoveInotify(watch.get());
131 if (ret == -1)
132 {
133 wxLogSysError( _("Unable to remove inotify watch") );
134 return false;
135 }
136
137 if (m_watchMap.erase(watch->GetWatchDescriptor()) != 1)
138 {
139 wxFAIL_MSG( wxString::Format("Path %s is not watched",
140 watch->GetPath()) );
141 }
142 // Cache the wd in case any events arrive late
143 m_staleDescriptors.Add(watch->GetWatchDescriptor());
144
145 watch->SetWatchDescriptor(-1);
146 return true;
147 }
148
149 virtual bool RemoveAll()
150 {
151 wxFSWatchEntries::iterator it = m_watches.begin();
152 for ( ; it != m_watches.end(); ++it )
153 {
154 (void) DoRemove(it->second);
155 }
156 m_watches.clear();
157 return true;
158 }
159
160 int ReadEvents()
161 {
162 wxCHECK_MSG( IsOk(), -1,
163 "Inotify not initialized or invalid inotify descriptor" );
164
165 // read events
166 // TODO differentiate depending on params
167 char buf[128 * sizeof(inotify_event)];
168 int left = ReadEventsToBuf(buf, sizeof(buf));
169 if (left == -1)
170 return -1;
171
172 // left > 0, we have events
173 char* memory = buf;
174 int event_count = 0;
175 while (left > 0) // OPT checking 'memory' would suffice
176 {
177 event_count++;
178 inotify_event* e = (inotify_event*)memory;
179
180 // process one inotify_event
181 ProcessNativeEvent(*e);
182
183 int offset = sizeof(inotify_event) + e->len;
184 left -= offset;
185 memory += offset;
186 }
187
188 // take care of unmatched renames
189 ProcessRenames();
190
191 wxLogTrace(wxTRACE_FSWATCHER, "We had %d native events", event_count);
192 return event_count;
193 }
194
195 bool IsOk() const
196 {
197 return m_source != NULL;
198 }
199
200 protected:
201 int DoAddInotify(wxFSWatchEntry* watch)
202 {
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);
207 return wd;
208 }
209
210 int DoRemoveInotify(wxFSWatchEntry* watch)
211 {
212 return inotify_rm_watch(m_ifd, watch->GetWatchDescriptor());
213 }
214
215 void ProcessNativeEvent(const inotify_event& inevt)
216 {
217 wxLogTrace(wxTRACE_FSWATCHER, InotifyEventToString(inevt));
218
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)
222 {
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);
228 return;
229 }
230
231 // get watch entry for this event
232 wxFSWatchEntryDescriptors::iterator it = m_watchMap.find(inevt.wd);
233 if (it == m_watchMap.end())
234 {
235 // It's not in the map; check if was recently removed from it.
236 if (m_staleDescriptors.Index(inevt.wd) != wxNOT_FOUND)
237 {
238 wxLogTrace(wxTRACE_FSWATCHER,
239 "Got an event for stale wd %i", inevt.wd);
240 }
241 else
242 {
243 wxFAIL_MSG("Event for unknown watch descriptor.");
244 }
245
246 // In any case, don't process this event: it's either for an
247 // already removed entry, or for a completely unknown one.
248 return;
249 }
250
251 wxFSWatchEntry& watch = *(it->second);
252 int nativeFlags = inevt.mask;
253 int flags = Native2WatcherFlags(nativeFlags);
254
255 // check out for error/warning condition
256 if (flags & wxFSW_EVENT_WARNING || flags & wxFSW_EVENT_ERROR)
257 {
258 wxString errMsg = GetErrorDescription(Watcher2NativeFlags(flags));
259 wxFileSystemWatcherEvent event(flags, errMsg);
260 SendEvent(event);
261 }
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()))
265 {
266 return;
267 }
268 // renames
269 else if (nativeFlags & IN_MOVE)
270 {
271 wxInotifyCookies::iterator it = m_cookies.find(inevt.cookie);
272 if ( it == m_cookies.end() )
273 {
274 int size = sizeof(inevt) + inevt.len;
275 inotify_event* e = (inotify_event*) operator new (size);
276 memcpy(e, &inevt, size);
277
278 wxInotifyCookies::value_type val(e->cookie, e);
279 m_cookies.insert(val);
280 }
281 else
282 {
283 inotify_event& oldinevt = *(it->second);
284
285 wxFileSystemWatcherEvent event(flags);
286 if ( inevt.mask & IN_MOVED_FROM )
287 {
288 event.SetPath(GetEventPath(watch, inevt));
289 event.SetNewPath(GetEventPath(watch, oldinevt));
290 }
291 else
292 {
293 event.SetPath(GetEventPath(watch, oldinevt));
294 event.SetNewPath(GetEventPath(watch, inevt));
295 }
296 SendEvent(event);
297
298 m_cookies.erase(it);
299 delete &oldinevt;
300 }
301 }
302 // every other kind of event
303 else
304 {
305 wxFileName path = GetEventPath(watch, inevt);
306 wxFileSystemWatcherEvent event(flags, path, path);
307 SendEvent(event);
308 }
309 }
310
311 void ProcessRenames()
312 {
313 wxInotifyCookies::iterator it = m_cookies.begin();
314 while ( it != m_cookies.end() )
315 {
316 inotify_event& inevt = *(it->second);
317
318 wxLogTrace(wxTRACE_FSWATCHER, "Processing pending rename events");
319 wxLogTrace(wxTRACE_FSWATCHER, InotifyEventToString(inevt));
320
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!");
325
326 wxFSWatchEntry& watch = *(wit->second);
327 int flags = Native2WatcherFlags(inevt.mask);
328 wxFileName path = GetEventPath(watch, inevt);
329 wxFileSystemWatcherEvent event(flags, path, path);
330 SendEvent(event);
331
332 m_cookies.erase(it);
333 delete &inevt;
334 it = m_cookies.begin();
335 }
336 }
337
338 void SendEvent(wxFileSystemWatcherEvent& evt)
339 {
340 wxLogTrace(wxTRACE_FSWATCHER, evt.ToString());
341 m_watcher->GetOwner()->ProcessEvent(evt);
342 }
343
344 int ReadEventsToBuf(char* buf, int size)
345 {
346 wxCHECK_MSG( IsOk(), false,
347 "Inotify not initialized or invalid inotify descriptor" );
348
349 memset(buf, 0, size);
350 ssize_t left = read(m_ifd, buf, size);
351 if (left == -1)
352 {
353 wxLogSysError(_("Unable to read from inotify descriptor"));
354 return -1;
355 }
356 else if (left == 0)
357 {
358 wxLogWarning(_("EOF while reading from inotify descriptor"));
359 return -1;
360 }
361
362 return left;
363 }
364
365 static wxString InotifyEventToString(const inotify_event& inevt)
366 {
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 = "";
371 if (inevt.len)
372 name = inevt.name;
373 return wxString::Format("Event: wd=%d, mask=%s, cookie=%u, len=%u, "
374 "name=%s", inevt.wd, mask, inevt.cookie,
375 inevt.len, name);
376 }
377
378 static wxFileName GetEventPath(const wxFSWatchEntry& watch,
379 const inotify_event& inevt)
380 {
381 // only when dir is watched, we have non-empty e.name
382 wxFileName path = watch.GetPath();
383 if (path.IsDir() && inevt.len)
384 {
385 path = wxFileName(path.GetPath(), inevt.name);
386 }
387 return path;
388 }
389
390 static int Watcher2NativeFlags(int WXUNUSED(flags))
391 {
392 // TODO: it would be nice to subscribe only to the events we really need
393 return IN_ALL_EVENTS;
394 }
395
396 static int Native2WatcherFlags(int flags)
397 {
398 static const int flag_mapping[][2] = {
399 { IN_ACCESS, wxFSW_EVENT_ACCESS }, // generated during read!
400 { IN_MODIFY, wxFSW_EVENT_MODIFY },
401 { IN_ATTRIB, 0 },
402 { IN_CLOSE_WRITE, 0 },
403 { IN_CLOSE_NOWRITE, 0 },
404 { IN_OPEN, 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 },
411
412 { IN_UNMOUNT, wxFSW_EVENT_ERROR },
413 { IN_Q_OVERFLOW, wxFSW_EVENT_WARNING},
414
415 // ignored, because this is genereted mainly by watcher::Remove()
416 { IN_IGNORED, 0 }
417 };
418
419 unsigned int i=0;
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];
424 }
425
426 // never reached
427 wxFAIL_MSG(wxString::Format("Unknown inotify event mask %u", flags));
428 return -1;
429 }
430
431 /**
432 * Returns error description for specified inotify mask
433 */
434 static const wxString GetErrorDescription(int flag)
435 {
436 switch ( flag )
437 {
438 case IN_UNMOUNT:
439 return _("File system containing watched object was unmounted");
440 case IN_Q_OVERFLOW:
441 return _("Event queue overflowed");
442 }
443
444 // never reached
445 wxFAIL_MSG(wxString::Format("Unknown inotify event mask %u", flag));
446 return wxEmptyString;
447 }
448
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
454
455 // file descriptor created by inotify_init()
456 int m_ifd;
457 };
458
459
460 // ============================================================================
461 // wxFSWSourceHandler implementation
462 // ============================================================================
463
464 // once we get signaled to read, actuall event reading occurs
465 void wxFSWSourceHandler::OnReadWaiting()
466 {
467 wxLogTrace(wxTRACE_FSWATCHER, "--- OnReadWaiting ---");
468 m_service->ReadEvents();
469 }
470
471 void wxFSWSourceHandler::OnWriteWaiting()
472 {
473 wxFAIL_MSG("We never write to inotify descriptor.");
474 }
475
476 void wxFSWSourceHandler::OnExceptionWaiting()
477 {
478 wxFAIL_MSG("We never receive exceptions on inotify descriptor.");
479 }
480
481
482 // ============================================================================
483 // wxInotifyFileSystemWatcher implementation
484 // ============================================================================
485
486 wxInotifyFileSystemWatcher::wxInotifyFileSystemWatcher()
487 : wxFileSystemWatcherBase()
488 {
489 Init();
490 }
491
492 wxInotifyFileSystemWatcher::wxInotifyFileSystemWatcher(const wxFileName& path,
493 int events)
494 : wxFileSystemWatcherBase()
495 {
496 if (!Init())
497 {
498 if (m_service)
499 delete m_service;
500 return;
501 }
502
503 Add(path, events);
504 }
505
506 wxInotifyFileSystemWatcher::~wxInotifyFileSystemWatcher()
507 {
508 }
509
510 bool wxInotifyFileSystemWatcher::Init()
511 {
512 m_service = new wxFSWatcherImplUnix(this);
513 return m_service->Init();
514 }
515
516 #endif // wxHAS_INOTIFY
517
518 #endif // wxUSE_FSWATCHER