aboutsummaryrefslogblamecommitdiff
path: root/emulators/libretro-pcsx2/files/3rdparty_wxwidgets3.0_src_unix_fswatcher__kqueue.cpp
blob: 55cb787cd1aee9794c018b6c2ef606a17dfdc2f0 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459










































































































































































































































































































































































































































































                                                                                          
/////////////////////////////////////////////////////////////////////////////
// Name:        src/unix/fswatcher_kqueue.cpp
// Purpose:     kqueue-based wxFileSystemWatcher implementation
// Author:      Bartosz Bekier
// Created:     2009-05-26
// Copyright:   (c) 2009 Bartosz Bekier <bartosz.bekier@gmail.com>
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#if wxUSE_FSWATCHER

#include "wx/fswatcher.h"

#ifdef wxHAS_KQUEUE

#include <inttypes.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/param.h>

#include "wx/dynarray.h"
#include "wx/evtloop.h"
#include "wx/evtloopsrc.h"

#include "wx/private/fswatcher.h"

namespace
{

// NetBSD is different as it uses intptr_t as type of kevent struct udata field
// for some reason, instead of "void*" as all the other platforms using kqueue.
#ifdef __NetBSD__
    inline intptr_t ToUdata(void* d) { return reinterpret_cast<intptr_t>(d); }
    inline void* FromUdata(intptr_t d) { return reinterpret_cast<void*>(d); }
#else
    inline void* ToUdata(void* d) { return d; }
    inline void* FromUdata(void* d) { return d; }
#endif

} // anonymous namespace

// ============================================================================
// wxFSWSourceHandler helper class
// ============================================================================

class wxFSWatcherImplKqueue;

/**
 * Handler for handling i/o from inotify descriptor
 */
class wxFSWSourceHandler : public wxEventLoopSourceHandler
{
public:
    wxFSWSourceHandler(wxFSWatcherImplKqueue* service) :
        m_service(service)
    {  }

    virtual void OnReadWaiting();
    virtual void OnWriteWaiting();
    virtual void OnExceptionWaiting();

protected:
    wxFSWatcherImplKqueue* m_service;
};

// ============================================================================
// wxFSWatcherImpl implementation & helper wxFSWSourceHandler implementation
// ============================================================================

/**
 * Helper class encapsulating inotify mechanism
 */
class wxFSWatcherImplKqueue : public wxFSWatcherImpl
{
public:
    wxFSWatcherImplKqueue(wxFileSystemWatcherBase* watcher) :
        wxFSWatcherImpl(watcher),
        m_source(NULL),
        m_kfd(-1)
    {
        m_handler = new wxFSWSourceHandler(this);
    }

    virtual ~wxFSWatcherImplKqueue()
    {
        // we close kqueue only if initialized before
        if (IsOk())
        {
            Close();
        }

        delete m_handler;
    }

    bool Init()
    {
        wxCHECK_MSG( !IsOk(), false,
                     "Kqueue appears to be already initialized" );

        wxEventLoopBase *loop = wxEventLoopBase::GetActive();
        wxCHECK_MSG( loop, false, "File system watcher needs an active loop" );

        // create kqueue
        m_kfd = kqueue();
        if (m_kfd == -1)
        {
            wxLogSysError(_("Unable to create kqueue instance"));
            return false;
        }

        // create source
        m_source = loop->AddSourceForFD(m_kfd, m_handler, wxEVENT_SOURCE_INPUT);

        return m_source != NULL;
    }

    void Close()
    {
        wxCHECK_RET( IsOk(),
                    "Kqueue not initialized or invalid kqueue descriptor" );

        if ( close(m_kfd) != 0 )
        {
            wxLogSysError(_("Error closing kqueue instance"));
        }

        wxDELETE(m_source);
    }

    virtual bool DoAdd(wxSharedPtr<wxFSWatchEntryKq> watch)
    {
        wxCHECK_MSG( IsOk(), false,
                    "Kqueue not initialized or invalid kqueue descriptor" );

        struct kevent event;
        int action = EV_ADD | EV_ENABLE | EV_CLEAR | EV_ERROR;
        int flags = Watcher2NativeFlags(watch->GetFlags());
        EV_SET( &event, watch->GetFileDescriptor(), EVFILT_VNODE, action,
                flags, 0, ToUdata(watch.get()) );

        // TODO more error conditions according to man
        // TODO best deal with the error here
        int ret = kevent(m_kfd, &event, 1, NULL, 0, NULL);
        if (ret == -1)
        {
            wxLogSysError(_("Unable to add kqueue watch"));
            return false;
        }

        return true;
    }

    virtual bool DoRemove(wxSharedPtr<wxFSWatchEntryKq> watch)
    {
        wxCHECK_MSG( IsOk(), false,
                    "Kqueue not initialized or invalid kqueue descriptor" );

        // TODO more error conditions according to man
        // XXX closing file descriptor removes the watch. The logic resides in
        // the watch which is not nice, but effective and simple
        if ( !watch->Close() )
        {
            wxLogSysError(_("Unable to remove kqueue watch"));
            return false;
        }

        return true;
    }

    virtual bool RemoveAll()
    {
        wxFSWatchEntries::iterator it = m_watches.begin();
        for ( ; it != m_watches.end(); ++it )
        {
            (void) DoRemove(it->second);
        }
        m_watches.clear();
        return true;
    }

    // return true if there was no error, false on error
    bool ReadEvents()
    {
        wxCHECK_MSG( IsOk(), false,
                    "Kqueue not initialized or invalid kqueue descriptor" );

        // read events
        do
        {
            struct kevent event;
            struct timespec timeout = {0, 0};
            int ret = kevent(m_kfd, NULL, 0, &event, 1, &timeout);
            if (ret == -1)
            {
                wxLogSysError(_("Unable to get events from kqueue"));
                return false;
            }
            else if (ret == 0)
            {
                return true;
            }

            // we have event, so process it
            ProcessNativeEvent(event);
        }
        while (true);

        // when ret>0 we still have events, when ret<=0 we return
        wxFAIL_MSG( "Never reached" );
        return true;
    }

    bool IsOk() const
    {
        return m_source != NULL;
    }

protected:
    // returns all new dirs/files present in the immediate level of the dir
    // pointed by watch.GetPath(). "new" means created between the last time
    // the state of watch was computed and now
    void FindChanges(wxFSWatchEntryKq& watch,
                     wxArrayString& changedFiles,
                     wxArrayInt& changedFlags)
    {
        wxFSWatchEntryKq::wxDirState old = watch.GetLastState();
        watch.RefreshState();
        wxFSWatchEntryKq::wxDirState curr = watch.GetLastState();

        // iterate over old/curr file lists and compute changes
        wxArrayString::iterator oit = old.files.begin();
        wxArrayString::iterator cit = curr.files.begin();
        for ( ; oit != old.files.end() && cit != curr.files.end(); )
        {
            if ( *cit == *oit )
            {
                ++cit;
                ++oit;
            }
            else if ( *cit <= *oit )
            {
                changedFiles.push_back(*cit);
                changedFlags.push_back(wxFSW_EVENT_CREATE);
                ++cit;
            }
            else // ( *cit > *oit )
            {
                changedFiles.push_back(*oit);
                changedFlags.push_back(wxFSW_EVENT_DELETE);
                ++oit;
            }
        }

        // border conditions
        if ( oit == old.files.end() )
        {
            for ( ; cit != curr.files.end(); ++cit )
            {
                changedFiles.push_back( *cit );
                changedFlags.push_back(wxFSW_EVENT_CREATE);
            }
        }
        else if ( cit == curr.files.end() )
        {
            for ( ; oit != old.files.end(); ++oit )
            {
                changedFiles.push_back( *oit );
                changedFlags.push_back(wxFSW_EVENT_DELETE);
            }
        }

        wxASSERT( changedFiles.size() == changedFlags.size() );

#if 0
        wxLogTrace(wxTRACE_FSWATCHER, "Changed files:");
        wxArrayString::iterator it = changedFiles.begin();
        wxArrayInt::iterator it2 = changedFlags.begin();
        for ( ; it != changedFiles.end(); ++it, ++it2)
        {
            wxString action = (*it2 == wxFSW_EVENT_CREATE) ?
                                "created" : "deleted";
            wxLogTrace(wxTRACE_FSWATCHER, wxString::Format("File: '%s' %s",
                        *it, action));
        }
#endif
    }

    void ProcessNativeEvent(const struct kevent& e)
    {
        void* const udata = FromUdata(e.udata);

        wxASSERT_MSG(udata, "Null user data associated with kevent!");
        wxLogTrace(wxTRACE_FSWATCHER, "Event: ident=%" PRIuPTR ", filter=%hd, flags=%hu, "
#if __FreeBSD_version >= 1200033
                   "fflags=%u, data=%" PRId64 ", user_data=%p",
#else
                   "fflags=%u, data=%" PRIdPTR ", user_data=%p",
#endif
                   e.ident, e.filter, e.flags, e.fflags, e.data, udata);

        // for ease of use
        wxFSWatchEntryKq& w = *(static_cast<wxFSWatchEntry*>(udata));
        int nflags = e.fflags;

        // clear ignored flags
        nflags &= ~NOTE_REVOKE;

        // TODO ignore events we didn't ask for + refactor this cascade ifs
        // check for events
        while ( nflags )
        {
            // when monitoring dir, this means create/delete
            const wxString basepath = w.GetPath();
            if ( nflags & NOTE_WRITE && wxDirExists(basepath) )
            {
                // NOTE_LINK is set when the dir was created, but we
                // don't care - we look for new names in directory
                // regardless of type. Also, clear all this, because
                // it cannot mean more by itself
                nflags &= ~(NOTE_WRITE | NOTE_ATTRIB | NOTE_LINK);

                wxArrayString changedFiles;
                wxArrayInt changedFlags;
                FindChanges(w, changedFiles, changedFlags);

                wxArrayString::iterator it = changedFiles.begin();
                wxArrayInt::iterator changeType = changedFlags.begin();
                for ( ; it != changedFiles.end(); ++it, ++changeType )
                {
                    const wxString fullpath = w.GetPath() +
                                                wxFileName::GetPathSeparator() +
                                                  *it;
                    const wxFileName path(wxDirExists(fullpath)
                                            ? wxFileName::DirName(fullpath)
                                            : wxFileName::FileName(fullpath));

                    wxFileSystemWatcherEvent event(*changeType, path, path);
                    SendEvent(event);
                }
            }
            else if ( nflags & NOTE_RENAME )
            {
                // CHECK it'd be only possible to detect name if we had
                // parent files listing which we could confront with now and
                // still we couldn't be sure we have the right name...
                nflags &= ~NOTE_RENAME;
                wxFileSystemWatcherEvent event(wxFSW_EVENT_RENAME,
                                        basepath, wxFileName());
                SendEvent(event);
            }
            else if ( nflags & NOTE_WRITE || nflags & NOTE_EXTEND )
            {
                nflags &= ~(NOTE_WRITE | NOTE_EXTEND);
                wxFileSystemWatcherEvent event(wxFSW_EVENT_MODIFY,
                                        basepath, basepath);
                SendEvent(event);
            }
            else if ( nflags & NOTE_DELETE )
            {
                nflags &= ~(NOTE_DELETE);
                wxFileSystemWatcherEvent event(wxFSW_EVENT_DELETE,
                                        basepath, basepath);
                SendEvent(event);
            }
            else if ( nflags & NOTE_ATTRIB )
            {
                nflags &= ~(NOTE_ATTRIB);
                wxFileSystemWatcherEvent event(wxFSW_EVENT_ACCESS,
                                        basepath, basepath);
                SendEvent(event);
            }

            // clear any flags that won't mean anything by themselves
            nflags &= ~(NOTE_LINK);
        }
    }

    void SendEvent(wxFileSystemWatcherEvent& evt)
    {
        m_watcher->GetOwner()->ProcessEvent(evt);
    }

    static int Watcher2NativeFlags(int WXUNUSED(flags))
    {
        // TODO: it would be better to only subscribe to what we need
        return NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND |
               NOTE_ATTRIB | NOTE_LINK | NOTE_RENAME |
               NOTE_REVOKE;
    }

    wxFSWSourceHandler* m_handler;        // handler for kqueue event source
    wxEventLoopSource* m_source;          // our event loop source

    // descriptor created by kqueue()
    int m_kfd;
};


// once we get signaled to read, actuall event reading occurs
void wxFSWSourceHandler::OnReadWaiting()
{
    wxLogTrace(wxTRACE_FSWATCHER, "--- OnReadWaiting ---");
    m_service->ReadEvents();
}

void wxFSWSourceHandler::OnWriteWaiting()
{
    wxFAIL_MSG("We never write to kqueue descriptor.");
}

void wxFSWSourceHandler::OnExceptionWaiting()
{
    wxFAIL_MSG("We never receive exceptions on kqueue descriptor.");
}


// ============================================================================
// wxKqueueFileSystemWatcher implementation
// ============================================================================

wxKqueueFileSystemWatcher::wxKqueueFileSystemWatcher()
    : wxFileSystemWatcherBase()
{
    Init();
}

wxKqueueFileSystemWatcher::wxKqueueFileSystemWatcher(const wxFileName& path,
                                                     int events)
    : wxFileSystemWatcherBase()
{
    if (!Init())
    {
        wxDELETE(m_service);
        return;
    }

    Add(path, events);
}

wxKqueueFileSystemWatcher::~wxKqueueFileSystemWatcher()
{
}

bool wxKqueueFileSystemWatcher::Init()
{
    m_service = new wxFSWatcherImplKqueue(this);
    return m_service->Init();
}

#endif // wxHAS_KQUEUE

#endif // wxUSE_FSWATCHER