aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/coreplugin/locator/spotlightlocatorfilter.mm
blob: 11c29fac5478210bbb57d2217e234f09a82ac9fc (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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** 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 General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** 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-3.0.html.
**
****************************************************************************/

#include "spotlightlocatorfilter.h"

#include <utils/qtcassert.h>

#include <QMutex>
#include <QMutexLocker>
#include <QWaitCondition>

#include <Foundation/NSArray.h>
#include <Foundation/NSDictionary.h>
#include <Foundation/NSMetadata.h>
#include <Foundation/NSNotification.h>
#include <Foundation/NSOperation.h>
#include <Foundation/NSPredicate.h>

#include <CoreServices/CoreServices.h>

namespace Core {
namespace Internal {

// #pragma mark -- SpotlightIterator

class SpotlightIterator : public BaseFileFilter::Iterator
{
public:
    SpotlightIterator(const QString &expression);
    ~SpotlightIterator();

    void toFront();
    bool hasNext() const;
    QString next();
    QString filePath() const;
    QString fileName() const;

private:
    void ensureNext();

    NSMetadataQuery *m_query;
    id<NSObject> m_progressObserver;
    id<NSObject> m_finishObserver;
    QMutex m_mutex;
    QWaitCondition m_waitForItems;
    NSMutableArray *m_queue;
    QStringList m_filePaths;
    QStringList m_fileNames;
    int m_index;
    unsigned int m_queueIndex;
    bool m_finished;
};

SpotlightIterator::SpotlightIterator(const QString &expression)
    : m_index(-1),
      m_queueIndex(-1),
      m_finished(false)
{
    @autoreleasepool {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:expression.toNSString()];
        m_query = [[NSMetadataQuery alloc] init];
        m_query.predicate = predicate;
        m_query.searchScopes = [NSArray arrayWithObject:NSMetadataQueryLocalComputerScope];
        m_queue = [[NSMutableArray alloc] init];
        m_progressObserver = [[[NSNotificationCenter defaultCenter]
                addObserverForName:NSMetadataQueryGatheringProgressNotification
                            object:m_query
                             queue:nil
                        usingBlock:^(NSNotification *note) {
                            [m_query disableUpdates];
                            QMutexLocker lock(&m_mutex); Q_UNUSED(lock)
                            [m_queue addObjectsFromArray:[note.userInfo objectForKey:(NSString *)kMDQueryUpdateAddedItems]];
                            [m_query enableUpdates];
                            m_waitForItems.wakeAll();
                        }] retain];
        m_finishObserver = [[[NSNotificationCenter defaultCenter]
                addObserverForName:NSMetadataQueryDidFinishGatheringNotification
                            object:m_query
                             queue:nil
                        usingBlock:^(NSNotification *) {
                            QMutexLocker lock(&m_mutex); Q_UNUSED(lock)
                            m_finished = true;
                            m_waitForItems.wakeAll();
                        }] retain];
        [m_query startQuery];
    }
}

SpotlightIterator::~SpotlightIterator()
{
    [[NSNotificationCenter defaultCenter] removeObserver:m_progressObserver];
    [m_progressObserver release];
    [[NSNotificationCenter defaultCenter] removeObserver:m_finishObserver];
    [m_finishObserver release];
    [m_query stopQuery];
    [m_query release];
    [m_queue release];
}

void SpotlightIterator::toFront()
{
    m_index = -1;
}

bool SpotlightIterator::hasNext() const
{
    auto that = const_cast<SpotlightIterator *>(this);
    that->ensureNext();
    return (m_index + 1 < m_filePaths.size());
}

QString SpotlightIterator::next()
{
    ensureNext();
    ++m_index;
    QTC_ASSERT(m_index < m_filePaths.size(), return QString());
    return m_filePaths.at(m_index);
}

QString SpotlightIterator::filePath() const
{
    QTC_ASSERT(m_index < m_filePaths.size(), return QString());
    return m_filePaths.at(m_index);
}

QString SpotlightIterator::fileName() const
{
    QTC_ASSERT(m_index < m_fileNames.size(), return QString());
    return m_fileNames.at(m_index);
}

void SpotlightIterator::ensureNext()
{
    if (m_index + 1 < m_filePaths.size()) // nothing to do
        return;
    if (m_index >= 10000) // limit the amount of data that is passed on
        return;
    @autoreleasepool {
        // check if there are items in the queue, otherwise wait for some
        m_mutex.lock();
        bool itemAvailable = (m_queueIndex + 1 < m_queue.count);
        if (!itemAvailable && !m_finished) {
            m_waitForItems.wait(&m_mutex);
            itemAvailable = (m_queueIndex + 1 < m_queue.count);
        }
        if (itemAvailable) {
            ++m_queueIndex;
            NSMetadataItem *item = [m_queue objectAtIndex:m_queueIndex];
            m_filePaths.append(QString::fromNSString([item valueForAttribute:NSMetadataItemPathKey]));
            m_fileNames.append(QString::fromNSString([item valueForAttribute:NSMetadataItemFSNameKey]));

        }
        m_mutex.unlock();
    }
}

// #pragma mark -- SpotlightLocatorFilter

SpotlightLocatorFilter::SpotlightLocatorFilter()
{
    setId("SpotlightFileNamesLocatorFilter");
    setDisplayName(tr("Spotlight File Name Index"));
    setShortcutString(QLatin1String("md"));
}

void SpotlightLocatorFilter::prepareSearch(const QString &entry)
{
    if (entry.isEmpty()) {
        setFileIterator(new BaseFileFilter::ListIterator(QStringList()));
    } else {
        // only pass the file name part to spotlight to allow searches like "somepath/*foo"
        int lastSlash = entry.lastIndexOf(QLatin1Char('/'));
        QString quoted = entry.mid(lastSlash + 1);
        quoted.replace(QLatin1Char('\\'), QLatin1String("\\\\"))
            .replace(QLatin1Char('\''), QLatin1String("\\\'"))
            .replace(QLatin1Char('\"'), QLatin1String("\\\""));
        setFileIterator(new SpotlightIterator(
                            QString::fromLatin1("kMDItemFSName like%1 \"*%2*\"")
                            .arg(caseSensitivity(entry) == Qt::CaseInsensitive ? QLatin1String("[c]")
                                                                               : QString())
                            .arg(quoted)));
    }
    BaseFileFilter::prepareSearch(entry);
}

void SpotlightLocatorFilter::refresh(QFutureInterface<void> &future)
{
    Q_UNUSED(future)
}

} // Internal
} // Core