File: xmlnotereader.cpp

package info (click to toggle)
noblenote 1.0.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, jessie, jessie-kfreebsd, sid, stretch
  • size: 1,308 kB
  • ctags: 464
  • sloc: cpp: 3,748; makefile: 6
file content (311 lines) | stat: -rw-r--r-- 10,272 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
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
/* nobleNote, a note taking application
 * Copyright (C) 2012 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 "xmlnotereader.h"
#include <QTextCursor>
#include <QDirIterator>
#include <QApplication>


XmlNoteReader::XmlNoteReader(const QString& filePath, QTextDocument *doc)
{
    document_ = doc;

    QFile file(filePath);
    if(!file.open(QIODevice::ReadOnly))
    {
        //qDebug(qPrintable(QString("XmlNoteReader::XmlNoteReader failed : could not open filepath ") + QDir::toNativeSeparators(filePath)));
           return;
    }
    QXmlStreamReader::setDevice(&file);
    read();
    // if uuid wasn't inside the xml text try to get it out of the filename
    if(uuid_.isNull())
        uuid_ = QUuid(QFileInfo(filePath).baseName());

    // remove the title inside the document and the empty 2nd line, because the title is already in the window title
    QTextCursor cursor(document_); // point to start of the document
    cursor.select(QTextCursor::LineUnderCursor);
    QString titleLine = cursor.selectedText();
    if(titleLine.trimmed() == title_.trimmed())
        cursor.deleteChar();
    cursor.movePosition(QTextCursor::NextBlock,QTextCursor::KeepAnchor,2);
    QString emptyLine = cursor.selectedText();
    if(emptyLine.trimmed().isEmpty())
        cursor.deleteChar();

    file.close(); // local object gets destroyed
}

void XmlNoteReader::read()
{
    if( !this->QXmlStreamReader::device())
    {
        qDebug("XmlNoteReader::read failed: input device NULL");
        return;
    }

    // skip everything until <note-content>
    while(!atEnd())
    {
        readNext();

        if(name() == "note-content")
        {
            if(!document_) // if no document_ set where note content can be written into
                skipCurrentElement();
            else
                readContent();
        }
        else if(name() == "id" || name() == "uuid") // only "id" is written
        {
            QString idStr = readElementText();
            uuid_ = parseUuid(idStr);
        }
        else if(name() == "title")
        {
            title_ = readElementText();
        }
        else if(name() == "last-change-date")
        {
            lastChange_ = QDateTime::fromString(readElementText(),Qt::ISODate);
        }
        else if(name() == "last-metadata-change")
        {
            lastMetadataChange_ = QDateTime::fromString(readElementText(),Qt::ISODate);
        }
        else if(name() == "create-date")
        {
            createDate_ = QDateTime::fromString(readElementText(),Qt::ISODate);
        }
        else if(name() == "tag")
        {
            tag_ = readElementText();
        }

        if (QXmlStreamReader::hasError())
        {
            qDebug("XmlNoteReader::read failed: Error reading xml content");
            return;
        }
    }
}

void XmlNoteReader::readContent()
{
    QTextCursor cursor(document_->rootFrame());
    QTextCharFormat format;
    bool linkFormat = false;
    Q_UNUSED(linkFormat);
    while (!atEnd())
    {
        TokenType token = readNext();

        switch(token)
        {
        // read the text between the formatting elements
        case Characters:
        {
            // this commented out code does not work with formatted text and multiple links
            // TODO a QTextDocumentFragment must be created via QTextCursor::selected, the fragment must be exported to html
            // the link applied and reinserted via QTextCursor::insertHtml
//            if(linkFormat)
//            {
//                qDebug("link inserted");
//                cursor.insertHtml("<a href=\"" + text().toString() + "\">" + text().toString() + "</a>");
//            }
//            else
                cursor.insertText(text().toString(),format);
            break;
        }

            // read elements <bold> <italic> and set the formatting
        case StartElement:
        {
            if(name() == "bold")
                format.setFontWeight(QFont::Bold);

            if(name() == "italic")
                format.setFontItalic(true);

            if(name() == "underline")
                format.setUnderlineStyle(QTextCharFormat::SingleUnderline);

            if(name() == "strikethrough" || name() == "strikeout") // only strikethrough is written, but strikeout is also allowed for reading
                format.setFontStrikeOut(true);

            if(name() == "highlight")
                format.setBackground(QColor(255,255,0));

            if(qualifiedName() == "size:small")
                format.setFontPointSize(QApplication::font().pointSize()* 0.8f);

            if(qualifiedName() == "size:large")
                format.setFontPointSize(QApplication::font().pointSize()*1.4f);

            if(qualifiedName() == "size:huge")
                format.setFontPointSize(QApplication::font().pointSize()*1.6f);

            if(name() == "monospace")
                format.setFontFamily("Monospace");

            if(qualifiedName() == "link:url")
                linkFormat = true;

                break;
        }
           // unset formatting
        case EndElement:
        {
            if(name() == "note-content") // end of note content, exit this method
                return;

            if(name() == "bold")
                format.setFontWeight(QFont::Normal);

            if(name() == "italic")
                format.setFontItalic(false);

            if(name() == "underline")
                format.setUnderlineStyle(QTextCharFormat::NoUnderline);

            if(name() == "strikethrough" || name() == "strikeout") // only strikethrough is written, but strikeout is also allowed for reading
                format.setFontStrikeOut(false);

            if(name() == "highlight")
                format.clearBackground();

            if(qualifiedName() == "size:small" || qualifiedName() == "size:large" || qualifiedName() == "size:huge") // mutual exclusive options
                format.setFontPointSize(QApplication::font().pointSizeF());

            if(name() == "monospace")
                format.setFontFamily(QApplication::font().family());

            if(name() == "link:url")
                linkFormat = false;

            // ignore id

            break;
        }
        default:; // suppress compiler warnings
        }

        if (QXmlStreamReader::hasError())
        {
            qDebug("XmlNoteReader::read failed: Error reading xml content");
            return;
        }
    }
}

/*static*/ QUuid XmlNoteReader::parseUuid(QString idStr)
{
    QUuid uuid;
     // try to parse the rightmost 32 digits and four hyphens
    uuid = QUuid(idStr.rightRef(32 + 4).toString());

    if(uuid.isNull()) // if parsing fails, try more complex parsing
    {
        if(idStr.leftRef(QString("urn:uuid:").length()) == "urn:uuid:") // check if first 9 chars match "urn:uuid:"
        {
            QStringRef uuidRef = idStr.midRef(QString("urn:uuid:").length(),32+4); //32 digits and four hyphens
            uuid = QUuid(uuidRef.toString());
        }
        else // try to parse the whole string
        {
            uuid = QUuid(idStr.simplified());
        }
    }

    if(uuid.isNull())
        qDebug("XmlNoteReader::parseUuid : error parsing UUID, null UUID has been generated");

    return uuid;
}

/*static*/ QUuid XmlNoteReader::uuid(QString filePath)
{
    QFile file(filePath);
    if(!file.open(QIODevice::ReadOnly))
    {
        return QUuid();
    }
    QXmlStreamReader reader(&file);
    while(!reader.atEnd())
    {
        if(reader.readNextStartElement() && (reader.name() == "id" || reader.name() == "uuid"))
        {
            QString idStr = reader.readElementText();
            return parseUuid(idStr);
        }
        if (reader.hasError())
        {
            //qDebug("XmlNoteReader::uuid failed: Error reading xml content, returning null UUID");
            return QUuid();
        }
    }
    // if uuid wasn't inside the xml text try to get it out of the filename
    return QUuid(QFileInfo(filePath).baseName());
}

/*static*/ QString XmlNoteReader::findUuid(const QUuid uuid, const QString &path)
{
    if(uuid.isNull())
        return QString();

    QDirIterator it(path, QDirIterator::Subdirectories);
    while(it.hasNext())
    {
              QString filePath = it.next();
                  if(uuid == XmlNoteReader::uuid(filePath))
                      return filePath;
    }
    return QString();
}

/*static*/ bool XmlNoteReader::mightBeXmlNote(const QString &filePath)
{
    QFile file(filePath);
    if(!file.open(QIODevice::ReadOnly))
    {
        return false;
    }
    QXmlStreamReader reader(&file);
    while(!reader.atEnd())
    {
        reader.readNext();
        if(reader.isStartElement())
        {
            if(reader.name() == "note")
                return true;
            else if(reader.name() == "html" || reader.name() == "head") // detect html
                return false;
        }
        if(reader.hasError()) // this should detect plain text
            return false;
    }
    return false;
}