File size: 7,877 Bytes
985c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: LGPL-2.1-or-later
/****************************************************************************

 *                                                                          *

 *   Copyright (c) 2025 The FreeCAD Project Association AISBL               *

 *                                                                          *

 *   This file is part of FreeCAD.                                          *

 *                                                                          *

 *   FreeCAD is free software: you can redistribute it and/or modify it     *

 *   under the terms of the GNU Lesser General Public License as            *

 *   published by the Free Software Foundation, either version 2.1 of the   *

 *   License, or (at your option) any later version.                        *

 *                                                                          *

 *   FreeCAD is distributed in the hope that it will be useful, but         *

 *   WITHOUT ANY WARRANTY; without even the implied warranty of             *

 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU       *

 *   Lesser General Public License for more details.                        *

 *                                                                          *

 *   You should have received a copy of the GNU Lesser General Public       *

 *   License along with FreeCAD. If not, see                                *

 *   <https://www.gnu.org/licenses/>.                                       *

 *                                                                          *

 ***************************************************************************/

#include <QFile>
#include <QMetaObject>
#include <QMutexLocker>
#include <QObject>
#include <QProcess>
#include <QTimer>

#include "ThumbnailSource.h"

#include <QThread>

#include "FileUtilities.h"

#include <App/Application.h>

using namespace Start;

ThumbnailSource::F3DInstallation ThumbnailSource::_f3d {};
QMutex ThumbnailSource::_mutex;

ThumbnailSource::ThumbnailSource(QString file)
    : _file(std::move(file))
{}

ThumbnailSourceSignals* ThumbnailSource::signals()

{
    return &_signals;
}

void ThumbnailSource::run()

{
    _thumbnailPath = getPathToCachedThumbnail(_file);
    if (!useCachedThumbnail(_thumbnailPath, _file)) {
        // Go through the mutex to ensure data is not stale.
        // Contention on the lock is diminished because of first checking the cache.
        setupF3D();
        if (_f3d.major < 2) {
            return;
        }
        const ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
            "User parameter:BaseApp/Preferences/Mod/Start"
        );
        const auto f3d = QString::fromUtf8(hGrp->GetASCII("f3d", "f3d").c_str());
        QStringList args(_f3d.baseArgs);
        args << QLatin1String("--output=") + _thumbnailPath << _file;

        QProcess process;
        Base::Console().log("Creating thumbnail for %s...\n", _file.toStdString());
        process.start(f3d, args);
        if (!process.waitForFinished()) {
            process.kill();
            Base::Console().log("Creating thumbnail for %s timed out\n", _file.toStdString());
            return;
        }
        if (process.exitStatus() == QProcess::CrashExit) {
            Base::Console().log("Creating thumbnail for %s crashed\n", _file.toStdString());
            return;
        }
        if (process.exitCode() != 0) {
            Base::Console().log("Creating thumbnail for %s failed\n", _file.toStdString());
            return;
        }
        Base::Console().log(
            "Creating thumbnail for %s succeeded, wrote to %s\n",
            _file.toStdString(),
            _thumbnailPath.toStdString()
        );
    }
    if (QFile thumbnailFile(_thumbnailPath); thumbnailFile.exists()) {
        thumbnailFile.open(QIODevice::OpenModeFlag::ReadOnly);
        Q_EMIT _signals.thumbnailAvailable(_file, thumbnailFile.readAll());
    }
}

std::tuple<int, int, int> extractF3DVersion(const QString& stdoutString)

{
    int major {0};
    int minor {0};
    int patch {0};
    for (auto lines = stdoutString.split(QLatin1Char('\n')); const auto& line : lines) {
        if (line.startsWith(QLatin1String("Version: "))) {
            const auto substring = line.mid(8);
            if (auto split = substring.split(QLatin1Char('.')); split.size() >= 3) {
                try {
                    major = split[0].toInt();
                    minor = split[1].toInt();
                    patch = split[2].toInt();
                }
                catch (...) {
                    Base::Console().log(
                        "Could not determine F3D version, disabling thumbnail generation\n"
                    );
                }
            }
            break;
        }
    }
    return std::make_tuple(major, minor, patch);
}

QStringList getF3DOptions(const QString& f3d)

{
    // F3D is under active development, and the available options change with some regularity.
    // Rather than hardcode per version, just check the ones we care about.
    QStringList optionsToTest {
        QStringLiteral("--load-plugins=occt"),
        QStringLiteral("--config=thumbnail"),
        QStringLiteral("--verbose=quiet"),
        QStringLiteral("--resolution=256,256"),
        QStringLiteral("--filename=0"),
        QStringLiteral("--grid=0"),
        QStringLiteral("--axis=0"),
        QStringLiteral("--no-background"),
        QStringLiteral("--max-size=100")  // Max input file size in MB
    };
    QStringList goodOptions;
    for (const auto& option : optionsToTest) {
        QStringList args;
        args << option << QStringLiteral("--no-render");
        QProcess process;
        process.start(f3d, args);
        if (!process.waitForFinished()) {
            process.kill();
            continue;
        }
        auto stderrAsBytes = process.readAllStandardError();
        if (auto stderrAsString = QString::fromUtf8(stderrAsBytes);
            !stderrAsString.contains(QLatin1String("Unknown option"))) {
            goodOptions.append(option);
        }
    }
    return goodOptions;
}

void ThumbnailSource::setupF3D()

{
    QMutexLocker locker(&_mutex);
    if (_f3d.initialized) {
        return;
    }

    // This method makes repeated blocking calls to f3d (both directly, the call below, and
    // indirectly, by calling getF3DOptions). By holding the mutex above, it ensures that these
    // calls complete before any process can attempt to make a real call to f3d to create thumbnail
    // data. ThumbnailSource is run in its own thread, so blocking here is appropriate and will not
    // affect any other part of the program.

    _f3d.initialized = true;  // Set immediately so we can use early-return below
    const ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
        "User parameter:BaseApp/Preferences/Mod/Start"
    );
    const auto f3d = QString::fromUtf8(hGrp->GetASCII("f3d", "f3d").c_str());
    const QStringList args {QLatin1String("--version")};
    QProcess process;
    process.start(f3d, args);
    if (!process.waitForFinished()) {
        process.kill();
    }
    if (process.exitCode() != 0) {
        return;
    }
    const QByteArray stdoutBytes = process.readAllStandardOutput();
    const auto stdoutString = QString::fromUtf8(stdoutBytes);
    const auto version = extractF3DVersion(stdoutString);
    _f3d.major = std::get<0>(version);
    _f3d.minor = std::get<1>(version);
    if (_f3d.major >= 2) {
        _f3d.baseArgs = getF3DOptions(f3d);
    }
    Base::Console().log("Running f3d version %d.%d\n", _f3d.major, _f3d.minor);
}