File: findfilemodel.cpp

package info (click to toggle)
noblenote 1.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 1,448 kB
  • sloc: cpp: 3,956; makefile: 7
file content (209 lines) | stat: -rw-r--r-- 7,150 bytes parent folder | download
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
/* nobleNote, a note taking application
 * Copyright (C) 2019 Christian Metscher <hakaishi@web.de>,
                      Fabian Deuchler <Taiko000@gmail.com>

 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.

 * nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
 */

#include "findfilemodel.h"
#include <QFileIconProvider>
#include <QDirIterator>
#include <QTextStream>
#include <QUrl>
#include <QTextDocumentFragment>
#include <QTimer>
#include <QApplication>
#include <QTextDocument>
#include <QRegularExpression>

FindFileModel::FindFileModel(QObject *parent) :
    QStandardItemModel(parent)
{
    connect(&futureWatcher,SIGNAL(finished()),this,SLOT(findInFilesFinished()));
    connect(&futureWatcher, SIGNAL(canceled()), this, SLOT(restoreOverrideCursor()));
}

QString FindFileModel::fileName(const QModelIndex &index) const
{
    return QFileInfo(itemFromIndex(index)->data(Qt::UserRole + 1).toString()).fileName();
}

QString FindFileModel::filePath(const QModelIndex &index) const
{
    return QFileInfo(itemFromIndex(index)->data(Qt::UserRole + 1).toString()).filePath();
}


qint64 FindFileModel::size(const QModelIndex &index) const
{
    return QFileInfo(itemFromIndex(index)->data(Qt::UserRole + 1).toString()).size();
}


bool FindFileModel::remove(const QModelIndex &index)
{
    QStandardItem * item = itemFromIndex(index);
    if(!item)
    {
        qWarning("FindFileModel::remove failed: itemFromIndex returned NULL");
        return false;
    }
    QString filePath = item->data(Qt::UserRole + 1).toString();
    bool b = QFile::remove(filePath);
    if(b)
         this->removeRow(index.row(),index.parent());
    return b;
}

QFileInfo FindFileModel::fileInfo(const QModelIndex &index) const
{
    return QFileInfo(itemFromIndex(index)->data(Qt::UserRole + 1).toString());
}

void FindFileModel::appendFile(QString filePath)
{
    QFileInfo info(filePath);
    if(info.path().isEmpty() || info.path() == ".")
    {
        qWarning("FindFileModel::appendFile failed: filePath must contain the full path including the file name");
        return;
    }

    QString filePathTrunc = info.filePath();

    while(filePathTrunc.count(QDir::separator()) > 1)
      filePathTrunc.remove(0,filePathTrunc.indexOf(QDir::separator())+1);

    QStandardItem * fileItem = new QStandardItem(filePathTrunc);
    fileItem->setIcon(QFileIconProvider().icon(info));
    fileItem->setData(filePath,Qt::UserRole + 1); // store as user data
    appendRow(fileItem);
}

bool FindFileModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
     QStandardItemModel::setData(index,value,role); //set new name for list item
     //rename file before changing path of original file
     //value can be folder/filename or simply filename
     bool f = QFile::rename(filePath(index),fileInfo(index).path() + QDir::separator() + QFileInfo(value.toString()).fileName());

     //change path data
     QStandardItemModel::setData(index, fileInfo(index).path() + QDir::separator() + QFileInfo(value.toString()).fileName(), Qt::UserRole + 1);
     return f;
}

QStringList FindFileModel::mimeTypes() const
{
    return QStringList(QString("text/uri-list"));
}

QMimeData *FindFileModel::mimeData(const QModelIndexList &indexes) const
{
    QList<QUrl> urls;
    for(QModelIndexList::ConstIterator it = indexes.constBegin(); it != indexes.constEnd(); ++it)
    {
        urls+=QUrl::fromLocalFile(this->filePath(*it));
    }
    QMimeData * mimeData = new QMimeData();
    mimeData->setUrls(urls);
    return mimeData;
}

 // this method may be called multiple times if the user is typing a search word
void FindFileModel::findInFiles(const QString& fileName, const QString &content,const QString &path)
{

    if(path.isEmpty() || (fileName.isEmpty() && content.isEmpty()))
        return;

    if(future.isRunning())
        future.cancel();
    else
        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

    QStringList files;
    QDirIterator it(path, QDirIterator::Subdirectories);
    while(it.hasNext())
    {
        QString filePath = it.next();
        if(it.fileInfo().isFile())
            files << filePath;
    }

    fileContainsFunctor.content = content;
    fileContainsFunctor.fileName = fileName;

    future = QtConcurrent::filtered(files,fileContainsFunctor);

    futureWatcher.setFuture(future);

    // sometimes, wait cursor persists, this is a workaround
    QTimer::singleShot(5000,this,SLOT(restoreOverrideCursor()));
}

void FindFileModel::findInFilesFinished()
{
    const auto res = future.results();
    for(QString fileName : res )
        this->appendFile(fileName);
    QApplication::restoreOverrideCursor();
}

void FindFileModel::restoreOverrideCursor()
{
    QApplication::restoreOverrideCursor();
}

bool FindFileModel::FileContains::operator ()(const QString& htmlFilePath)
{
        if(!fileName.isEmpty() && !content.isEmpty())
           return QFileInfo(htmlFilePath).baseName().contains(fileName, Qt::CaseInsensitive) || fileContentContains(htmlFilePath);
        else if(!content.isEmpty())
            return fileContentContains(htmlFilePath);
        else
            return QFileInfo(htmlFilePath).baseName().contains(fileName, Qt::CaseInsensitive);
}

bool FindFileModel::FileContains::fileContentContains(const QString &htmlFilePath)
{
    static  QRegularExpression htmlRegex("<[^>]*>");

    QFile file(htmlFilePath);
    if(file.open(QIODevice::ReadOnly))
    {
      QTextStream in(&file);
      //QTextDocumentFragment doc = QTextDocumentFragment::fromHtml(in.readAll());
      //QString noteText = doc.toPlainText();
      //return noteText.contains(content, Qt::CaseInsensitive);

      // remove this string here exactly once
      const static QString whiteSpacePreWrap = "p, li { white-space: pre-wrap; }";
      QString text = in.readAll();
      int index;
      if((index = text.indexOf(whiteSpacePreWrap)) != -1)
      {
          text.remove(index,whiteSpacePreWrap.size());
      }

      return text.remove(htmlRegex).contains(content.toHtmlEscaped(),Qt::CaseInsensitive);
    }
    return false;
}