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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// SPDX-License-Identifier: LGPL-2.1-or-later

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

 *   Copyright (c) 2005 Jürgen Riegel <juergen.riegel@web.de>              *

 *                                                                         *

 *   This file is part of the FreeCAD CAx development system.              *

 *                                                                         *

 *   This program is free software; you can redistribute it and/or modify  *

 *   it under the terms of the GNU Library General Public License (LGPL)   *

 *   as published by the Free Software Foundation; either version 2 of     *

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

 *   for detail see the LICENCE text file.                                 *

 *                                                                         *

 *   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 Library General Public License for more details.                  *

 *                                                                         *

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

 *   License along with FreeCAD; if not, write to the Free Software        *

 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *

 *   USA                                                                   *

 *                                                                         *

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

#include <FCConfig.h>

#include <algorithm>
#include <codecvt>
#include <cstring>
#include <fstream>
#include <iostream>
#include <system_error>
#ifdef FC_OS_WIN32
# include <Windows.h>
#else
# include <unistd.h>
#endif

#include "FileInfo.h"
#include "Exception.h"
#include "TimeInfo.h"

using namespace Base;
namespace fs = std::filesystem;

//**********************************************************************************
// helper

#ifdef FC_OS_WIN32
std::string ConvertFromWideString(const std::wstring& string)

{
    int neededSize = WideCharToMultiByte(CP_UTF8, 0, string.c_str(), -1, 0, 0, 0, 0);
    char* CharString = new char[static_cast<size_t>(neededSize)];
    WideCharToMultiByte(CP_UTF8, 0, string.c_str(), -1, CharString, neededSize, 0, 0);
    std::string String(CharString);
    delete[] CharString;
    CharString = NULL;
    return String;
}

std::wstring ConvertToWideString(const std::string& string)

{
    int neededSize = MultiByteToWideChar(CP_UTF8, 0, string.c_str(), -1, 0, 0);
    wchar_t* wideCharString = new wchar_t[static_cast<size_t>(neededSize)];
    MultiByteToWideChar(CP_UTF8, 0, string.c_str(), -1, wideCharString, neededSize);
    std::wstring wideString(wideCharString);
    delete[] wideCharString;
    wideCharString = NULL;
    return wideString;
}
#endif


//**********************************************************************************
// FileInfo


FileInfo::FileInfo(const char* fileName)
{
    setFile(fileName);
}

FileInfo::FileInfo(const std::string& fileName)
{
    setFile(fileName.c_str());
}

const std::string& FileInfo::getTempPath()

{
    static std::string tempPath;

    if (tempPath.empty()) {
        fs::path tmp = fs::temp_directory_path();
        tmp += fs::path::preferred_separator;
        tempPath = pathToString(tmp);
    }

    return tempPath;
}

std::string FileInfo::getTempFileName(const char* FileName, const char* Path)

{
    // FIXME: To avoid race conditions we should rather return a file pointer
    // than a file name.
#ifdef FC_OS_WIN32
    wchar_t buf[MAX_PATH + 2];

    // Path where the file is located
    std::wstring path;
    if (Path) {
        path = ConvertToWideString(std::string(Path));
    }
    else {
        path = ConvertToWideString(getTempPath());
    }

    // File name in the path
    std::wstring file;
    if (FileName) {
        file = ConvertToWideString(std::string(FileName));
    }
    else {
        file = L"FCTempFile";
    }


    // this already creates the file
    GetTempFileNameW(path.c_str(), file.c_str(), 0, buf);
    DeleteFileW(buf);

    return std::string(ConvertFromWideString(std::wstring(buf)));
#else
    std::string buf;

    // Path where the file is located
    if (Path) {
        buf = Path;
    }
    else {
        buf = getTempPath();
    }

    // File name in the path
    if (FileName) {
        buf += "/";
        buf += FileName;
        buf += "XXXXXX";
    }
    else {
        buf += "/fileXXXXXX";
    }

    std::vector<char> vec;
    std::copy(buf.begin(), buf.end(), std::back_inserter(vec));
    vec.push_back('\0');

    /* coverity[secure_temp] mkstemp uses 0600 as the mode and is safe */
    int id = mkstemp(vec.data());
    if (id > -1) {
        FILE* file = fdopen(id, "w");
        fclose(file);
        vec.pop_back();  // remove '\0'
        std::string str(vec.begin(), vec.end());
        buf.swap(str);
        unlink(buf.c_str());
    }
    return buf;
#endif
}

fs::path FileInfo::stringToPath(const std::string& str)

{
#ifdef FC_OS_WIN32
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
    fs::path path(converter.from_bytes(str));
#else
    fs::path path(str);
#endif
    return path;
}

std::string FileInfo::pathToString(const fs::path& path)

{
#ifdef FC_OS_WIN32
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
    return converter.to_bytes(path.wstring());
#else
    return path.string();
#endif
}

void FileInfo::setFile(const char* name)

{
    if (!name) {
        FileName.clear();
        return;
    }

    FileName = name;

    // keep the UNC paths intact
    if (FileName.substr(0, 2) == std::string("\\\\")) {
        std::replace(FileName.begin() + 2, FileName.end(), '\\', '/');
    }
    else {
        std::replace(FileName.begin(), FileName.end(), '\\', '/');
    }
}

std::string FileInfo::filePath() const

{
    return FileName;
}

std::string FileInfo::fileName() const

{
    return FileName.substr(FileName.find_last_of('/') + 1);
}

std::string FileInfo::dirPath() const

{
    std::size_t last_pos {};
    std::string retval;
    last_pos = FileName.find_last_of('/');
    if (last_pos != std::string::npos) {
        retval = FileName.substr(0, last_pos);
    }
    else {
        retval = pathToString(fs::current_path());
    }
    return retval;
}

std::string FileInfo::fileNamePure() const

{
    std::string temp = fileName();
    std::string::size_type pos = temp.find_last_of('.');

    if (pos != std::string::npos) {
        return temp.substr(0, pos);
    }

    return temp;
}

std::wstring FileInfo::toStdWString() const

{
    // As FileName is UTF-8 is encoded we have to convert it
    // for Windows because the path names are UTF-16 encoded.
#ifdef FC_OS_WIN32
    return ConvertToWideString(FileName);
#else
    // On other platforms it's discouraged to use wchar_t for file names
    throw Base::FileException("Cannot use FileInfo::toStdWString() on this platform");
#endif
}

std::string FileInfo::extension() const

{
    std::string::size_type pos = FileName.find_last_of('.');
    if (pos == std::string::npos) {
        return {};
    }
    return FileName.substr(pos + 1);
}

std::string FileInfo::completeExtension() const

{
    std::string::size_type pos = FileName.find_first_of('.');
    if (pos == std::string::npos) {
        return {};
    }
    return FileName.substr(pos + 1);
}

bool FileInfo::hasExtension(const char* Ext) const

{
#ifdef FC_OS_WIN32
    return _stricmp(Ext, extension().c_str()) == 0;
#else
    return strcasecmp(Ext, extension().c_str()) == 0;
#endif
}

bool FileInfo::hasExtension(std::initializer_list<const char*> Exts) const

{
    return std::ranges::any_of(Exts, [this](const char* ext) { return hasExtension(ext); });
}

bool FileInfo::exists() const

{
    fs::path path(stringToPath(FileName));
    return fs::exists(path);
}

bool FileInfo::isReadable() const

{
    fs::path path = stringToPath(FileName);
    if (!fs::exists(path)) {
        return false;
    }
    fs::file_status stat = fs::status(path);
    fs::perms perms = stat.permissions();
    return (perms & fs::perms::owner_read) == fs::perms::owner_read;
}

bool directoryIsWritable(const fs::path& dir)

{
    try {
        if (!fs::exists(dir) || !fs::is_directory(dir)) {
            return false;
        }
        fs::path test_file = dir / (".fs_perm_test_" + std::to_string(std::rand()) + ".tmp");
        {
            std::ofstream ofs(test_file);
            if (!ofs) {
                return false;
            }
        }
        std::error_code ec;
        fs::remove(test_file, ec);
        return true;
    }
    catch (...) {
        return false;
    }
}

bool FileInfo::isWritable() const

{
    fs::path path = stringToPath(FileName);
    if (!fs::exists(path)) {
        return false;
    }
    if (fs::is_directory(path)) {
        return directoryIsWritable(path);
    }
#ifdef FC_OS_WIN32
    // convert filename from UTF-8 to windows WSTRING
    std::wstring fileNameWstring = toStdWString();
    // requires import of <windows.h>
    DWORD attributes = GetFileAttributes(fileNameWstring.c_str());
    if (attributes == INVALID_FILE_ATTRIBUTES) {
        // Log the error?
        std::clog << "GetFileAttributes failed for file: " << FileName << '\n';
        // usually indicates some kind of network file issue, so the file is probably not writable
        return false;
    }
    if ((attributes & FILE_ATTRIBUTE_READONLY) != 0) {
        return false;
    }
    // TEST if file is truly writable, because windows ACL does not map well to POSIX perms,
    //  and there are other potential blockers (app or shared file locks, etc)
    HANDLE hFile = CreateFileW(
        fileNameWstring.c_str(),
        GENERIC_WRITE,
        0,  // ----> no sharing: fail if anyone else has it open
        nullptr,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        nullptr
    );

    if (hFile == INVALID_HANDLE_VALUE) {
        DWORD err = GetLastError();
        if (err == ERROR_SHARING_VIOLATION || err == ERROR_LOCK_VIOLATION) {
            return false;
        }
        return false;
    }
    if (!CloseHandle(hFile)) {
        std::clog << "CloseHandle failed for file: " << FileName
                  << " while checking for write access." << '\n';
    }
#endif
    fs::file_status stat = fs::status(path);
    fs::perms perms = stat.permissions();
    return (perms & fs::perms::owner_write) == fs::perms::owner_write;
}

bool FileInfo::setPermissions(Permissions perms)

{
    fs::perms mode = fs::perms::none;

    if (perms & FileInfo::ReadOnly) {
        mode |= fs::perms::owner_read;
    }
    if (perms & FileInfo::WriteOnly) {
        mode |= fs::perms::owner_write;
    }

    if (mode == fs::perms::none) {  // bad argument
        return false;
    }

    fs::path file_path = stringToPath(FileName);
    if (!fs::exists(file_path)) {
        return false;
    }

    fs::permissions(file_path, mode);
    fs::file_status stat = fs::status(file_path);
    return stat.permissions() == mode;
}

bool FileInfo::isFile() const

{
    fs::path path = stringToPath(FileName);
    if (fs::exists(path)) {
        return fs::is_regular_file(path);
    }

    // TODO: Check for valid file name
    return true;
}

bool FileInfo::isDir() const

{
    fs::path path = stringToPath(FileName);
    if (fs::exists(path)) {
        return fs::is_directory(path);
    }

    return false;
}

unsigned int FileInfo::size() const

{
    unsigned int bytes {};
    fs::path path = stringToPath(FileName);
    if (fs::exists(path)) {
        bytes = fs::file_size(path);
    }

    return bytes;
}

template<typename TP>

std::time_t to_time_t(TP tp)

{
    using namespace std::chrono;
    auto sctp = time_point_cast<system_clock::duration>(tp - TP::clock::now() + system_clock::now());
    return system_clock::to_time_t(sctp);
}

TimeInfo FileInfo::lastModified() const

{
    TimeInfo ti = TimeInfo::null();

    if (exists()) {
        fs::path path = stringToPath(FileName);
        ti.setTime_t(to_time_t(fs::last_write_time(path)));
    }

    return ti;
}

bool FileInfo::deleteFile() const

{
    try {
        fs::path path = stringToPath(FileName);
        return fs::remove(path);
    }
    catch (const fs::filesystem_error& e) {
        std::clog << e.what() << '\n';
        return false;
    }
}

bool FileInfo::renameFile(const char* NewName)

{
    try {
        fs::path old_path = stringToPath(FileName);
        fs::path new_path = stringToPath(NewName);
        fs::rename(old_path, new_path);
        FileName = NewName;
        return true;
    }
    catch (const fs::filesystem_error& e) {
        std::clog << "Error in renameFile: " << e.what() << '\n';
        return false;
    }
}

bool FileInfo::copyTo(const char* NewName) const

{
    try {
        fs::path old_path = stringToPath(FileName);
        fs::path new_path = stringToPath(NewName);
        fs::copy(old_path, new_path);
        return true;
    }
    catch (const fs::filesystem_error&) {
        return false;
    }
}

bool FileInfo::createDirectory() const

{
    try {
        fs::path path(stringToPath(FileName));
        return fs::create_directory(path);
    }
    catch (const fs::filesystem_error&) {
        return false;
    }
}

bool FileInfo::createDirectories() const

{
    try {
        fs::path path(stringToPath(FileName));
        if (fs::exists(path)) {
            return true;
        }

        return fs::create_directories(path);
    }
    catch (const fs::filesystem_error&) {
        return false;
    }
}

bool FileInfo::deleteDirectory() const

{
    if (!isDir()) {
        return false;
    }

    try {
        fs::path path = stringToPath(FileName);
        return fs::remove(path);
    }
    catch (const fs::filesystem_error& e) {
        std::clog << e.what() << '\n';
        return false;
    }
}

bool FileInfo::deleteDirectoryRecursive() const

{
    if (!isDir()) {
        return false;
    }

    try {
        fs::path path = stringToPath(FileName);
        return fs::remove_all(path) > 0;
    }
    catch (const fs::filesystem_error& e) {
        std::clog << e.what() << '\n';
        return false;
    }
}

std::vector<Base::FileInfo> FileInfo::getDirectoryContent() const

{
    std::error_code ec;
    std::vector<Base::FileInfo> list;
    fs::path path = stringToPath(FileName);

    for (const fs::directory_entry& f : fs::directory_iterator {path, ec}) {
        list.emplace_back(pathToString(f.path()));
    }

    return list;
}