summaryrefslogtreecommitdiffstats
path: root/src/corelib/io/qfilesystemwatcher_win.cpp
blob: cdb79e7c97db3559dbc8edd0c5e7676324da7879 (plain)
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qfilesystemwatcher.h"
#include "qfilesystemwatcher_win_p.h"

#ifndef QT_NO_FILESYSTEMWATCHER

#include <qdebug.h>
#include <qfileinfo.h>
#include <qstringlist.h>
#include <qset.h>
#include <qdatetime.h>
#include <qdir.h>
#include <qtextstream.h>

#include <qt_windows.h>

#ifndef Q_OS_WINRT
#  include <qabstractnativeeventfilter.h>
#  include <qcoreapplication.h>
#  include <qdir.h>
#  include <private/qeventdispatcher_win_p.h>
#  include <dbt.h>
#  include <algorithm>
#  include <vector>
#endif // !Q_OS_WINRT

QT_BEGIN_NAMESPACE

// #define WINQFSW_DEBUG
#ifdef WINQFSW_DEBUG
#  define DEBUG qDebug
#else
#  define DEBUG if (false) qDebug
#endif

static Qt::HANDLE createChangeNotification(const QString &path, uint flags)
{
    // Volume and folder paths need a trailing slash for proper notification
    // (e.g. "c:" -> "c:/").
    QString nativePath = QDir::toNativeSeparators(path);
    if ((flags & FILE_NOTIFY_CHANGE_ATTRIBUTES) == 0 && !nativePath.endsWith(QLatin1Char('\\')))
        nativePath.append(QLatin1Char('\\'));
    const HANDLE result = FindFirstChangeNotification(reinterpret_cast<const wchar_t *>(nativePath.utf16()),
                                                      FALSE, flags);
    DEBUG() << __FUNCTION__ << nativePath << hex <<showbase << flags << "returns" << result;
    return result;
}

#ifndef Q_OS_WINRT
///////////
// QWindowsRemovableDriveListener
// Listen for the various WM_DEVICECHANGE message indicating drive addition/removal
// requests and removals.
///////////
class QWindowsRemovableDriveListener : public QObject, public QAbstractNativeEventFilter
{
    Q_OBJECT
public:
    // Device UUids as declared in ioevent.h (GUID_IO_VOLUME_LOCK, ...)
    enum VolumeUuid { UnknownUuid, UuidIoVolumeLock, UuidIoVolumeLockFailed,
                      UuidIoVolumeUnlock, UuidIoMediaRemoval };

    struct RemovableDriveEntry {
        HDEVNOTIFY devNotify;
        wchar_t drive;
    };

    explicit QWindowsRemovableDriveListener(QObject *parent = nullptr);
    ~QWindowsRemovableDriveListener();

    // Call from QFileSystemWatcher::addPaths() to set up notifications on drives
    void addPath(const QString &path);

    bool nativeEventFilter(const QByteArray &, void *messageIn, long *) override;

signals:
    void driveAdded();
    void driveRemoved(); // Some drive removed
    void driveRemoved(const QString &); // Watched/known drive removed
    void driveLockForRemoval(const QString &);
    void driveLockForRemovalFailed(const QString &);

private:
    static VolumeUuid volumeUuid(const UUID &needle);
    void handleDbtCustomEvent(const MSG *msg);
    void handleDbtDriveArrivalRemoval(const MSG *msg);

    std::vector<RemovableDriveEntry> m_removableDrives;
    quintptr m_lastMessageHash;
};

QWindowsRemovableDriveListener::QWindowsRemovableDriveListener(QObject *parent)
    : QObject(parent)
    , m_lastMessageHash(0)
{
}

static void stopDeviceNotification(QWindowsRemovableDriveListener::RemovableDriveEntry &e)
{
    UnregisterDeviceNotification(e.devNotify);
    e.devNotify = 0;
}

template <class Iterator> // Search sequence of RemovableDriveEntry for HDEVNOTIFY.
static inline Iterator findByHDevNotify(Iterator i1, Iterator i2, HDEVNOTIFY hdevnotify)
{
    return std::find_if(i1, i2,
                        [hdevnotify] (const QWindowsRemovableDriveListener::RemovableDriveEntry &e) { return e.devNotify == hdevnotify; });
}

QWindowsRemovableDriveListener::~QWindowsRemovableDriveListener()
{
    std::for_each(m_removableDrives.begin(), m_removableDrives.end(), stopDeviceNotification);
}

static QString pathFromEntry(const QWindowsRemovableDriveListener::RemovableDriveEntry &re)
{
    QString path = QStringLiteral("A:/");
    path[0] = QChar::fromLatin1(re.drive);
    return path;
}

// Handle WM_DEVICECHANGE+DBT_CUSTOMEVENT, which is sent based on the registration
// on the volume handle with QEventDispatcherWin32's message window in the class.
// Capture the GUID_IO_VOLUME_LOCK indicating the drive is to be removed.
QWindowsRemovableDriveListener::VolumeUuid QWindowsRemovableDriveListener::volumeUuid(const UUID &needle)
{
    static const struct VolumeUuidMapping // UUIDs from IoEvent.h (missing in MinGW)
    {
        VolumeUuid v;
        UUID uuid;
    } mapping[] = {
        { UuidIoVolumeLock, // GUID_IO_VOLUME_LOCK
          {0x50708874, 0xc9af, 0x11d1, {0x8f, 0xef, 0x0, 0xa0, 0xc9, 0xa0, 0x6d, 0x32}} },
        { UuidIoVolumeLockFailed, // GUID_IO_VOLUME_LOCK_FAILED
          {0xae2eed10, 0x0ba8, 0x11d2, {0x8f, 0xfb, 0x0, 0xa0, 0xc9, 0xa0, 0x6d, 0x32}} },
        { UuidIoVolumeUnlock, // GUID_IO_VOLUME_UNLOCK
          {0x9a8c3d68, 0xd0cb, 0x11d1, {0x8f, 0xef, 0x0, 0xa0, 0xc9, 0xa0, 0x6d, 0x32}} },
        { UuidIoMediaRemoval, // GUID_IO_MEDIA_REMOVAL
          {0xd07433c1, 0xa98e, 0x11d2, {0x91, 0x7a, 0x0, 0xa0, 0xc9, 0x06, 0x8f, 0xf3}} }
    };

    static const VolumeUuidMapping *end = mapping + sizeof(mapping) / sizeof(mapping[0]);
    const VolumeUuidMapping *m =
        std::find_if(mapping, end, [&needle] (const VolumeUuidMapping &m) { return IsEqualGUID(m.uuid, needle); });
    return m != end ? m->v : UnknownUuid;
}

inline void QWindowsRemovableDriveListener::handleDbtCustomEvent(const MSG *msg)
{
    const DEV_BROADCAST_HDR *broadcastHeader = reinterpret_cast<const DEV_BROADCAST_HDR *>(msg->lParam);
    if (broadcastHeader->dbch_devicetype != DBT_DEVTYP_HANDLE)
        return;
    const DEV_BROADCAST_HANDLE *broadcastHandle = reinterpret_cast<const DEV_BROADCAST_HANDLE *>(broadcastHeader);
    const auto it = findByHDevNotify(m_removableDrives.cbegin(), m_removableDrives.cend(),
                                     broadcastHandle->dbch_hdevnotify);
    if (it == m_removableDrives.cend())
        return;
    switch (volumeUuid(broadcastHandle->dbch_eventguid)) {
    case UuidIoVolumeLock: // Received for removable USB media
        emit driveLockForRemoval(pathFromEntry(*it));
        break;
    case UuidIoVolumeLockFailed:
        emit driveLockForRemovalFailed(pathFromEntry(*it));
        break;
    case UuidIoVolumeUnlock:
        break;
    case UuidIoMediaRemoval: // Received for optical drives
        break;
    default:
        break;
    }
}

// Handle WM_DEVICECHANGE+DBT_DEVICEARRIVAL/DBT_DEVICEREMOVECOMPLETE which are
// sent to all top level windows and cannot be registered for (that is, their
// triggering depends on top level windows being present)
inline void QWindowsRemovableDriveListener::handleDbtDriveArrivalRemoval(const MSG *msg)
{
    const DEV_BROADCAST_HDR *broadcastHeader = reinterpret_cast<const DEV_BROADCAST_HDR *>(msg->lParam);
    switch (broadcastHeader->dbch_devicetype) {
    case DBT_DEVTYP_HANDLE: // WM_DEVICECHANGE/DBT_DEVTYP_HANDLE is sent for our registered drives.
        if (msg->wParam == DBT_DEVICEREMOVECOMPLETE) {
            const DEV_BROADCAST_HANDLE *broadcastHandle = reinterpret_cast<const DEV_BROADCAST_HANDLE *>(broadcastHeader);
            const auto it = findByHDevNotify(m_removableDrives.begin(), m_removableDrives.end(),
                                           broadcastHandle->dbch_hdevnotify);
            // Emit for removable USB drives we were registered for.
            if (it != m_removableDrives.end()) {
                emit driveRemoved(pathFromEntry(*it));
                stopDeviceNotification(*it);
                m_removableDrives.erase(it);
            }
        }
        break;
    case DBT_DEVTYP_VOLUME: {
        const DEV_BROADCAST_VOLUME *broadcastVolume = reinterpret_cast<const DEV_BROADCAST_VOLUME *>(broadcastHeader);
        // WM_DEVICECHANGE/DBT_DEVTYP_VOLUME messages are sent to all toplevel windows. Compare a hash value to ensure
        // it is handled only once.
        const quintptr newHash = reinterpret_cast<quintptr>(broadcastVolume) + msg->wParam
            + quintptr(broadcastVolume->dbcv_flags) + quintptr(broadcastVolume->dbcv_unitmask);
        if (newHash == m_lastMessageHash)
            return;
        m_lastMessageHash = newHash;
        // Check for DBTF_MEDIA (inserted/Removed Optical drives). Ignore for now.
        if (broadcastVolume->dbcv_flags & DBTF_MEDIA)
            return;
        // Continue with plugged in USB media where dbcv_flags=0.
        switch (msg->wParam) {
        case DBT_DEVICEARRIVAL:
            emit driveAdded();
            break;
        case DBT_DEVICEREMOVECOMPLETE: // See above for handling of drives registered with watchers
            emit driveRemoved();
            break;
        }
    }
        break;
    }
}

bool QWindowsRemovableDriveListener::nativeEventFilter(const QByteArray &, void *messageIn, long *)
{
    const MSG *msg = reinterpret_cast<const MSG *>(messageIn);
    if (msg->message == WM_DEVICECHANGE) {
        switch (msg->wParam) {
        case DBT_CUSTOMEVENT:
            handleDbtCustomEvent(msg);
            break;
        case DBT_DEVICEARRIVAL:
        case DBT_DEVICEREMOVECOMPLETE:
            handleDbtDriveArrivalRemoval(msg);
            break;
        }
    }
    return false;
}

// Set up listening for WM_DEVICECHANGE+DBT_CUSTOMEVENT for a removable drive path,
void QWindowsRemovableDriveListener::addPath(const QString &p)
{
    const wchar_t drive = p.size() >= 2 && p.at(0).isLetter() && p.at(1) == QLatin1Char(':')
        ? wchar_t(p.at(0).toUpper().unicode()) : L'\0';
    if (!drive)
        return;
    // Already listening?
    if (std::any_of(m_removableDrives.cbegin(), m_removableDrives.cend(),
                    [drive](const RemovableDriveEntry &e) { return e.drive == drive; })) {
        return;
    }

    wchar_t devicePath[8] = L"\\\\.\\A:\\";
    devicePath[4] = drive;
    RemovableDriveEntry re;
    re.drive = drive;
    if (GetDriveTypeW(devicePath + 4) != DRIVE_REMOVABLE)
        return;
    const HANDLE volumeHandle =
        CreateFile(devicePath, FILE_READ_ATTRIBUTES,
                   FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, 0,
                   OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, //  Volume requires BACKUP_SEMANTICS
                   0);
    if (volumeHandle == INVALID_HANDLE_VALUE) {
        qErrnoWarning("CreateFile %s failed.",
                      qPrintable(QString::fromWCharArray(devicePath)));
        return;
    }

    DEV_BROADCAST_HANDLE notify;
    ZeroMemory(&notify, sizeof(notify));
    notify.dbch_size = sizeof(notify);
    notify.dbch_devicetype = DBT_DEVTYP_HANDLE;
    notify.dbch_handle = volumeHandle;
    QEventDispatcherWin32 *winEventDispatcher = static_cast<QEventDispatcherWin32 *>(QCoreApplication::eventDispatcher());
    re.devNotify = RegisterDeviceNotification(winEventDispatcher->internalHwnd(),
                                              &notify, DEVICE_NOTIFY_WINDOW_HANDLE);
    // Empirically found: The notifications also work when the handle is immediately
    // closed. Do it here to avoid having to close/reopen in lock message handling.
    CloseHandle(volumeHandle);
    if (!re.devNotify) {
        qErrnoWarning("RegisterDeviceNotification %s failed.",
                      qPrintable(QString::fromWCharArray(devicePath)));
        return;
    }

    m_removableDrives.push_back(re);
}
#endif // !Q_OS_WINRT

///////////
// QWindowsFileSystemWatcherEngine
///////////
QWindowsFileSystemWatcherEngine::Handle::Handle()
    : handle(INVALID_HANDLE_VALUE), flags(0u)
{
}

QWindowsFileSystemWatcherEngine::QWindowsFileSystemWatcherEngine(QObject *parent)
    : QFileSystemWatcherEngine(parent)
{
#ifndef Q_OS_WINRT
    if (QAbstractEventDispatcher *eventDispatcher = QCoreApplication::eventDispatcher()) {
        m_driveListener = new QWindowsRemovableDriveListener(this);
        eventDispatcher->installNativeEventFilter(m_driveListener);
        parent->setProperty("_q_driveListener",
                            QVariant::fromValue(static_cast<QObject *>(m_driveListener)));
        QObject::connect(m_driveListener, &QWindowsRemovableDriveListener::driveLockForRemoval,
                         this, &QWindowsFileSystemWatcherEngine::driveLockForRemoval);
        QObject::connect(m_driveListener, &QWindowsRemovableDriveListener::driveLockForRemovalFailed,
                         this, &QWindowsFileSystemWatcherEngine::driveLockForRemovalFailed);
        QObject::connect(m_driveListener,
                         QOverload<const QString &>::of(&QWindowsRemovableDriveListener::driveRemoved),
                         this, &QWindowsFileSystemWatcherEngine::driveRemoved);
    } else {
        qWarning("QFileSystemWatcher: Removable drive notification will not work"
                 " if there is no QCoreApplication instance.");
    }
#endif // !Q_OS_WINRT
}

QWindowsFileSystemWatcherEngine::~QWindowsFileSystemWatcherEngine()
{
    for (auto *thread : qAsConst(threads))
        thread->stop();
    for (auto *thread : qAsConst(threads))
        thread->wait();
    qDeleteAll(threads);
}

QStringList QWindowsFileSystemWatcherEngine::addPaths(const QStringList &paths,
                                                       QStringList *files,
                                                       QStringList *directories)
{
    DEBUG() << "Adding" << paths.count() << "to existing" << (files->count() + directories->count()) << "watchers";
    QStringList p = paths;
    QMutableListIterator<QString> it(p);
    while (it.hasNext()) {
        QString path = it.next();
        QString normalPath = path;
        if ((normalPath.endsWith(QLatin1Char('/')) && !normalPath.endsWith(QLatin1String(":/")))
            || (normalPath.endsWith(QLatin1Char('\\')) && !normalPath.endsWith(QLatin1String(":\\")))) {
            normalPath.chop(1);
        }
        QFileInfo fileInfo(normalPath);
        if (!fileInfo.exists())
            continue;

        bool isDir = fileInfo.isDir();
        if (isDir) {
            if (directories->contains(path))
                continue;
        } else {
            if (files->contains(path))
                continue;
        }

        DEBUG() << "Looking for a thread/handle for" << normalPath;

        const QString absolutePath = isDir ? fileInfo.absoluteFilePath() : fileInfo.absolutePath();
        const uint flags = isDir
                           ? (FILE_NOTIFY_CHANGE_DIR_NAME
                              | FILE_NOTIFY_CHANGE_FILE_NAME)
                           : (FILE_NOTIFY_CHANGE_DIR_NAME
                              | FILE_NOTIFY_CHANGE_FILE_NAME
                              | FILE_NOTIFY_CHANGE_ATTRIBUTES
                              | FILE_NOTIFY_CHANGE_SIZE
                              | FILE_NOTIFY_CHANGE_LAST_WRITE
                              | FILE_NOTIFY_CHANGE_SECURITY);

        QWindowsFileSystemWatcherEngine::PathInfo pathInfo;
        pathInfo.absolutePath = absolutePath;
        pathInfo.isDir = isDir;
        pathInfo.path = path;
        pathInfo = fileInfo;

        // Look for a thread
        QWindowsFileSystemWatcherEngineThread *thread = 0;
        QWindowsFileSystemWatcherEngine::Handle handle;
        QList<QWindowsFileSystemWatcherEngineThread *>::const_iterator jt, end;
        end = threads.constEnd();
        for(jt = threads.constBegin(); jt != end; ++jt) {
            thread = *jt;
            QMutexLocker locker(&(thread->mutex));

            const auto hit = thread->handleForDir.find(QFileSystemWatcherPathKey(absolutePath));
            if (hit != thread->handleForDir.end() && hit.value().flags < flags) {
                // Requesting to add a file whose directory has been added previously.
                // Recreate the notification handle to add the missing notification attributes
                // for files (FILE_NOTIFY_CHANGE_ATTRIBUTES...)
                DEBUG() << "recreating" << absolutePath << hex << showbase << hit.value().flags
                    << "->" << flags;
                const Qt::HANDLE fileHandle = createChangeNotification(absolutePath, flags);
                if (fileHandle != INVALID_HANDLE_VALUE) {
                    const int index = thread->handles.indexOf(hit.value().handle);
                    const auto pit = thread->pathInfoForHandle.find(hit.value().handle);
                    Q_ASSERT(index != -1);
                    Q_ASSERT(pit != thread->pathInfoForHandle.end());
                    FindCloseChangeNotification(hit.value().handle);
                    thread->handles[index] = hit.value().handle = fileHandle;
                    hit.value().flags = flags;
                    thread->pathInfoForHandle.insert(fileHandle, pit.value());
                    thread->pathInfoForHandle.erase(pit);
                }
            }
            // In addition, check on flags for sufficient notification attributes
            if (hit != thread->handleForDir.end() && hit.value().flags >= flags) {
                handle = hit.value();
                // found a thread now insert...
                DEBUG() << "Found a thread" << thread;

                QWindowsFileSystemWatcherEngineThread::PathInfoHash &h =
                    thread->pathInfoForHandle[handle.handle];
                const QFileSystemWatcherPathKey key(fileInfo.absoluteFilePath());
                if (!h.contains(key)) {
                    thread->pathInfoForHandle[handle.handle].insert(key, pathInfo);
                    if (isDir)
                        directories->append(path);
                    else
                        files->append(path);
                }
                it.remove();
                thread->wakeup();
                break;
            }
        }

        // no thread found, first create a handle
        if (handle.handle == INVALID_HANDLE_VALUE) {
            DEBUG() << "No thread found";
            handle.handle = createChangeNotification(absolutePath, flags);
            handle.flags = flags;
            if (handle.handle == INVALID_HANDLE_VALUE)
                continue;

            // now look for a thread to insert
            bool found = false;
            for (QWindowsFileSystemWatcherEngineThread *thread : qAsConst(threads)) {
                QMutexLocker locker(&(thread->mutex));
                if (thread->handles.count() < MAXIMUM_WAIT_OBJECTS) {
                    DEBUG() << "Added handle" << handle.handle << "for" << absolutePath << "to watch" << fileInfo.absoluteFilePath()
                            << "to existing thread " << thread;
                    thread->handles.append(handle.handle);
                    thread->handleForDir.insert(QFileSystemWatcherPathKey(absolutePath), handle);

                    thread->pathInfoForHandle[handle.handle].insert(QFileSystemWatcherPathKey(fileInfo.absoluteFilePath()), pathInfo);
                    if (isDir)
                        directories->append(path);
                    else
                        files->append(path);

                    it.remove();
                    found = true;
                    thread->wakeup();
                    break;
                }
            }
            if (!found) {
                QWindowsFileSystemWatcherEngineThread *thread = new QWindowsFileSystemWatcherEngineThread();
                DEBUG() << "  ###Creating new thread" << thread << '(' << (threads.count()+1) << "threads)";
                thread->handles.append(handle.handle);
                thread->handleForDir.insert(QFileSystemWatcherPathKey(absolutePath), handle);

                thread->pathInfoForHandle[handle.handle].insert(QFileSystemWatcherPathKey(fileInfo.absoluteFilePath()), pathInfo);
                if (isDir)
                    directories->append(path);
                else
                    files->append(path);

                connect(thread, SIGNAL(fileChanged(QString,bool)),
                        this, SIGNAL(fileChanged(QString,bool)));
                connect(thread, SIGNAL(directoryChanged(QString,bool)),
                        this, SIGNAL(directoryChanged(QString,bool)));

                thread->msg = '@';
                thread->start();
                threads.append(thread);
                it.remove();
            }
        }
    }

#ifndef Q_OS_WINRT
    if (Q_LIKELY(m_driveListener)) {
        for (const QString &path : paths) {
            if (!p.contains(path))
                m_driveListener->addPath(path);
        }
    }
#endif // !Q_OS_WINRT
    return p;
}

QStringList QWindowsFileSystemWatcherEngine::removePaths(const QStringList &paths,
                                                          QStringList *files,
                                                          QStringList *directories)
{
    DEBUG() << "removePaths" << paths;
    QStringList p = paths;
    QMutableListIterator<QString> it(p);
    while (it.hasNext()) {
        QString path = it.next();
        QString normalPath = path;
        if (normalPath.endsWith(QLatin1Char('/')) || normalPath.endsWith(QLatin1Char('\\')))
            normalPath.chop(1);
        QFileInfo fileInfo(normalPath);
        DEBUG() << "removing" << normalPath;
        QString absolutePath = fileInfo.absoluteFilePath();
        QList<QWindowsFileSystemWatcherEngineThread *>::iterator jt, end;
        end = threads.end();
        for(jt = threads.begin(); jt!= end; ++jt) {
            QWindowsFileSystemWatcherEngineThread *thread = *jt;
            if (*jt == 0)
                continue;

            QMutexLocker locker(&(thread->mutex));

            QWindowsFileSystemWatcherEngine::Handle handle = thread->handleForDir.value(QFileSystemWatcherPathKey(absolutePath));
            if (handle.handle == INVALID_HANDLE_VALUE) {
                // perhaps path is a file?
                absolutePath = fileInfo.absolutePath();
                handle = thread->handleForDir.value(QFileSystemWatcherPathKey(absolutePath));
            }
            if (handle.handle != INVALID_HANDLE_VALUE) {
                QWindowsFileSystemWatcherEngineThread::PathInfoHash &h =
                        thread->pathInfoForHandle[handle.handle];
                if (h.remove(QFileSystemWatcherPathKey(fileInfo.absoluteFilePath()))) {
                    // ###
                    files->removeAll(path);
                    directories->removeAll(path);
                    it.remove();

                    if (h.isEmpty()) {
                        DEBUG() << "Closing handle" << handle.handle;
                        FindCloseChangeNotification(handle.handle);    // This one might generate a notification

                        int indexOfHandle = thread->handles.indexOf(handle.handle);
                        Q_ASSERT(indexOfHandle != -1);
                        thread->handles.remove(indexOfHandle);

                        thread->handleForDir.remove(QFileSystemWatcherPathKey(absolutePath));
                        // h is now invalid

                        if (thread->handleForDir.isEmpty()) {
                            DEBUG() << "Stopping thread " << thread;
                            locker.unlock();
                            thread->stop();
                            thread->wait();
                            locker.relock();
                            // We can't delete the thread until the mutex locker is
                            // out of scope
                        }
                    }
                }
                // Found the file, go to next one
                break;
            }
        }
    }

    // Remove all threads that we stopped
    QList<QWindowsFileSystemWatcherEngineThread *>::iterator jt, end;
    end = threads.end();
    for(jt = threads.begin(); jt != end; ++jt) {
        if (!(*jt)->isRunning()) {
            delete *jt;
            *jt = 0;
        }
    }

    threads.removeAll(0);
    return p;
}

///////////
// QWindowsFileSystemWatcherEngineThread
///////////

QWindowsFileSystemWatcherEngineThread::QWindowsFileSystemWatcherEngineThread()
        : msg(0)
{
    if (HANDLE h = CreateEvent(0, false, false, 0)) {
        handles.reserve(MAXIMUM_WAIT_OBJECTS);
        handles.append(h);
    }
}


QWindowsFileSystemWatcherEngineThread::~QWindowsFileSystemWatcherEngineThread()
{
    CloseHandle(handles.at(0));
    handles[0] = INVALID_HANDLE_VALUE;

    for (HANDLE h : qAsConst(handles)) {
        if (h == INVALID_HANDLE_VALUE)
            continue;
        FindCloseChangeNotification(h);
    }
}

static inline QString msgFindNextFailed(const QWindowsFileSystemWatcherEngineThread::PathInfoHash &pathInfos)
{
    QString result;
    QTextStream str(&result);
    str << "QFileSystemWatcher: FindNextChangeNotification failed for";
    for (const QWindowsFileSystemWatcherEngine::PathInfo &pathInfo : pathInfos)
        str << " \"" << QDir::toNativeSeparators(pathInfo.absolutePath) << '"';
    str << ' ';
    return result;
}

void QWindowsFileSystemWatcherEngineThread::run()
{
    QMutexLocker locker(&mutex);
    forever {
        QVector<HANDLE> handlesCopy = handles;
        locker.unlock();
        DEBUG() << "QWindowsFileSystemWatcherThread" << this << "waiting on" << handlesCopy.count() << "handles";
        DWORD r = WaitForMultipleObjects(handlesCopy.count(), handlesCopy.constData(), false, INFINITE);
        locker.relock();
        do {
            if (r == WAIT_OBJECT_0) {
                int m = msg;
                msg = 0;
                if (m == 'q') {
                    DEBUG() << "thread" << this << "told to quit";
                    return;
                }
                if (m != '@')
                    DEBUG() << "QWindowsFileSystemWatcherEngine: unknown message sent to thread: " << char(m);
                break;
            } else if (r > WAIT_OBJECT_0 && r < WAIT_OBJECT_0 + uint(handlesCopy.count())) {
                int at = r - WAIT_OBJECT_0;
                Q_ASSERT(at < handlesCopy.count());
                HANDLE handle = handlesCopy.at(at);

                // When removing a path, FindCloseChangeNotification might actually fire a notification
                // for some reason, so we must check if the handle exist in the handles vector
                if (handles.contains(handle)) {
                    DEBUG() << "thread" << this << "Acknowledged handle:" << at << handle;
                    QWindowsFileSystemWatcherEngineThread::PathInfoHash &h = pathInfoForHandle[handle];
                    bool fakeRemove = false;

                    if (!FindNextChangeNotification(handle)) {
                        const DWORD error = GetLastError();

                        if (error == ERROR_ACCESS_DENIED) {
                            // for directories, our object's handle appears to be woken up when the target of a
                            // watch is deleted, before the watched thing is actually deleted...
                            // anyway.. we're given an error code of ERROR_ACCESS_DENIED in that case.
                            fakeRemove = true;
                        }

                        qErrnoWarning(error, "%s", qPrintable(msgFindNextFailed(h)));
                    }
                    QMutableHashIterator<QFileSystemWatcherPathKey, QWindowsFileSystemWatcherEngine::PathInfo> it(h);
                    while (it.hasNext()) {
                        QWindowsFileSystemWatcherEngineThread::PathInfoHash::iterator x = it.next();
                        QString absolutePath = x.value().absolutePath;
                        QFileInfo fileInfo(x.value().path);
                        DEBUG() << "checking" << x.key();

                        // i'm not completely sure the fileInfo.exist() check will ever work... see QTBUG-2331
                        // ..however, I'm not completely sure enough to remove it.
                        if (fakeRemove || !fileInfo.exists()) {
                            DEBUG() << x.key() << "removed!";
                            if (x.value().isDir)
                                emit directoryChanged(x.value().path, true);
                            else
                                emit fileChanged(x.value().path, true);
                            h.erase(x);

                            // close the notification handle if the directory has been removed
                            if (h.isEmpty()) {
                                DEBUG() << "Thread closing handle" << handle;
                                FindCloseChangeNotification(handle);    // This one might generate a notification

                                int indexOfHandle = handles.indexOf(handle);
                                Q_ASSERT(indexOfHandle != -1);
                                handles.remove(indexOfHandle);

                                handleForDir.remove(QFileSystemWatcherPathKey(absolutePath));
                                // h is now invalid
                            }
                        } else if (x.value().isDir) {
                            DEBUG() << x.key() << "directory changed!";
                            emit directoryChanged(x.value().path, false);
                            x.value() = fileInfo;
                        } else if (x.value() != fileInfo) {
                            DEBUG() << x.key() << "file changed!";
                            emit fileChanged(x.value().path, false);
                            x.value() = fileInfo;
                        }
                    }
                }
            } else {
                // qErrnoWarning("QFileSystemWatcher: error while waiting for change notification");
                break;  // avoid endless loop
            }
            handlesCopy = handles;
            r = WaitForMultipleObjects(handlesCopy.count(), handlesCopy.constData(), false, 0);
        } while (r != WAIT_TIMEOUT);
    }
}


void QWindowsFileSystemWatcherEngineThread::stop()
{
    msg = 'q';
    SetEvent(handles.at(0));
}

void QWindowsFileSystemWatcherEngineThread::wakeup()
{
    msg = '@';
    SetEvent(handles.at(0));
}

QT_END_NAMESPACE

#ifndef Q_OS_WINRT
#  include "qfilesystemwatcher_win.moc"
#endif

#endif // QT_NO_FILESYSTEMWATCHER