File indexing completed on 2025-03-09 03:49:42

0001 /*
0002     SPDX-FileCopyrightText: 1998 Anders Widell <awl@hem.passagen.se>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include "Bookmark.h"
0008 
0009 #include "History.h"
0010 #include "LevelMap.h"
0011 
0012 #include <QDir>
0013 #include <QFile>
0014 #include <QStandardPaths>
0015 
0016 #include <fcntl.h>
0017 #include <sys/stat.h>
0018 #include <sys/types.h>
0019 #include <unistd.h>
0020 
0021 #include <cassert>
0022 #include <cstdio>
0023 
0024 void Bookmark::fileName(QString &p) const
0025 {
0026     p = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/bookmark%1").arg(number_);
0027 }
0028 
0029 Bookmark::Bookmark(int _num)
0030     : number_(_num)
0031 {
0032     QString p;
0033     fileName(p);
0034     FILE *file = fopen(QFile::encodeName(p).constData(), "r");
0035     if (file == nullptr)
0036         return;
0037 
0038     char buf[4096];
0039     buf[0] = '\0';
0040     fgets(buf, 4096, file);
0041     if (sscanf(buf, "%d %d %d", &collection_, &level_, &moves_) != 3) {
0042         collection_ = level_ = -1;
0043         data_ = QString();
0044         fclose(file);
0045         return;
0046     }
0047 
0048     data_ = QString();
0049     int len;
0050     while (!feof(file)) {
0051         len = fread(buf, 1, 4095, file);
0052         if (ferror(file))
0053             break;
0054         buf[len] = '\0';
0055         data_ += QString::fromLatin1(buf);
0056     }
0057     fclose(file);
0058 
0059     data_ = data_.trimmed();
0060 }
0061 
0062 void Bookmark::set(int _collection, int _level, int _moves, History *_h)
0063 {
0064     assert(_collection >= 0);
0065     if (_collection < 0)
0066         return;
0067 
0068     collection_ = _collection;
0069     level_ = _level;
0070     moves_ = _moves;
0071 
0072     data_ = QString();
0073     _h->save(data_);
0074 
0075     // ensure folder exists
0076     QDir bookmarksDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
0077     if (!bookmarksDir.mkpath(QStringLiteral("."))) {
0078         return;
0079     }
0080     QString p;
0081     fileName(p);
0082     FILE *file = fopen(QFile::encodeName(p).constData(), "w");
0083     if (file == nullptr)
0084         return;
0085     fprintf(file, "%d %d %d\n", collection_, level_, moves_);
0086     fprintf(file, "%s\n", data_.toLatin1().constData());
0087     fclose(file);
0088 }
0089 
0090 bool Bookmark::goTo(LevelMap *_map, History *_h)
0091 {
0092     return _h->load(_map, data_.toLatin1().constData()) != nullptr;
0093 }