dialog-file.cpp 20 KB
Newer Older
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1
2
3
4
// Copyright (c) 2020 INRA Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

Gauthier Quesnel's avatar
Gauthier Quesnel committed
5
6
7
8
9
10
#ifdef _WIN32
#define NOMINMAX
#define WINDOWS_LEAN_AND_MEAN
#include <windows.h>
#endif

Gauthier Quesnel's avatar
Gauthier Quesnel committed
11
#include "gui.hpp"
12
#include "node-editor.hpp"
Gauthier Quesnel's avatar
Gauthier Quesnel committed
13
14
15
16
17
18
19
20

#include <fmt/format.h>

#include <algorithm>
#include <array>
#include <filesystem>
#include <vector>

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#if defined(__linux__)
#include <errno.h>
#include <pwd.h>
#include <unistd.h>
#elif defined(__APPLE__)
#include <errno.h>
#include <mach-o/dyld.h>
#include <pwd.h>
#include <unistd.h>
#elif defined(_WIN32)
#include <KnownFolders.h>
#include <shlobj.h>
#include <wchar.h>
#include <windows.h>
#endif

Gauthier Quesnel's avatar
Gauthier Quesnel committed
37
38
namespace irt {

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
#if defined(__linux__) || defined(__APPLE__)
std::optional<std::filesystem::path>
get_home_directory()
{
    if (auto* home = std::getenv("HOME"); home)
        return std::filesystem::path{ home };

    auto size = sysconf(_SC_GETPW_R_SIZE_MAX);
    if (size == -1)
        size = 16384u;

    std::vector<char> buf(size, '\0');
    struct passwd pwd;
    struct passwd* result;

    const auto s = getpwuid_r(getpid(), &pwd, buf.data(), size, &result);
    if (!result)
        return std::nullopt;

    return std::filesystem::path{ std::string_view{ buf.data() } };
}
#elif defined(_WIN32)
std::optional<std::filesystem::path>
get_home_directory()
{
    PWSTR path{ nullptr };
    const auto hr =
      ::SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &path);

    std::filesystem::path ret;

    if (SUCCEEDED(hr))
        ret = path;

    ::CoTaskMemFree(path);

    return ret;
}
#endif

#if defined(__linux__)
std::optional<std::filesystem::path>
get_executable_directory()
{
    std::vector<char> buf(PATH_MAX, '\0');
    const auto size = readlink("/proc/self/exe", buf.data(), PATH_MAX);

    if (size <= 0)
        return std::nullopt;

    return std::filesystem::path{ std::string_view{ buf.data(), size } };
}
#elif defined(__APPLE__)
std::optional<std::filesystem::path>
get_executable_directory()
{
    std::vector<char> buf(MAXPATHLEN, '\0');
    uint32_t size{ 0 };

    if (_NSGetExecutablePath(buf.data(), &size))
        return std::nullopt;

    return std::filesystem::path{ std::string_view{ buf.data(), size } };
}
#elif defined(_WIN32)
std::optional<std::filesystem::path>
get_executable_directory()
{
    std::wstring filepath;
    auto size = ::GetModuleFileNameW(NULL, &filepath[0], 0u);

    while (static_cast<size_t>(size) > filepath.size()) {
        filepath.resize(size, '\0');
        size = ::GetModuleFileNameW(
          NULL, &filepath[0], static_cast<DWORD>(filepath.size()));
    }

    if (!size)
        return std::nullopt;

    return std::filesystem::path{ filepath };
}
#endif

123
application::settings_manager::settings_manager() noexcept
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
    try {
        if (auto home = get_home_directory(); home) {
            home_dir = home.value();
            home_dir /= "irritator";
        } else {
            log_w.log(
              3,
              "Fail to retrieve home directory. Use current directory instead");
            home_dir = std::filesystem::current_path();
        }

        if (auto install = get_executable_directory(); install) {
            executable_dir = install.value();
        } else {
            log_w.log(
              3,
              "Fail to retrieve executable directory. Use current directory "
              "instead");
            executable_dir = std::filesystem::current_path();
        }

        log_w.log(5,
                  "home: %s\ninstall: %s\n",
                  home_dir.u8string().c_str(),
                  executable_dir.u8string().c_str());

        // TODO Fill the libraries vectors with users and systems directory.

    } catch (const std::exception& /*e*/) {
        log_w.log(2, "Fail to initialize application");
155
156
157
    }
}

Gauthier Quesnel's avatar
Gauthier Quesnel committed
158
159
160
161
162
struct file_dialog
{
    std::vector<std::filesystem::path> paths;
    std::filesystem::path current;
    std::filesystem::path selected;
163
164
165
166
167
#if defined(__APPLE__)
    // @TODO Remove this part when XCode allows u8string concatenation.
    std::string temp;
    char buffer[512];
#else
168
    std::u8string temp;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
169
    char8_t buffer[512];
170
#endif
Gauthier Quesnel's avatar
Gauthier Quesnel committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193

    bool is_open = true;

#ifdef _WIN32
    uint32_t drives{ 0 };

    void fill_drives()
    {
        DWORD mask = ::GetLogicalDrives();
        uint32_t ret = { 0 };

        for (int i = 0; i < 26; ++i) {
            if (!(mask & (1 << i)))
                continue;

            char rootName[4] = { static_cast<char>('A' + i), ':', '\\', '\0' };
            UINT type = ::GetDriveTypeA(rootName);
            if (type == DRIVE_REMOVABLE || type == DRIVE_FIXED)
                ret |= (1 << i);
        }

        drives = ret;
    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
194
195
196
#else
    void fill_drives()
    {}
Gauthier Quesnel's avatar
Gauthier Quesnel committed
197
198
#endif

199
200
    const char8_t** file_filters;
    const char8_t** extension_filters;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
201
202
203
204
205
206

    bool have_good_file_name_starts(const std::filesystem::path& p)
    {
        if (file_filters == nullptr)
            return true;

207
        const char8_t** filters = file_filters;
208
209
210
211
212
213
214
215
216
217

#if defined(__APPLE__)
        // @TODO Remove this part when XCode allows u8string find/compare.
        while (*filters) {
            if (p.u8string().find(reinterpret_cast<const char*>(*filters)) == 0)
                return true;

            ++filters;
        }
#else
Gauthier Quesnel's avatar
Gauthier Quesnel committed
218
        while (*filters) {
219
            if (p.u8string().find(*filters) == 0)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
220
221
222
223
                return true;

            ++filters;
        }
224
#endif
Gauthier Quesnel's avatar
Gauthier Quesnel committed
225
226
227
228
229
230
231
232
233

        return false;
    }

    bool have_good_extension(const std::filesystem::path& p)
    {
        if (extension_filters == nullptr)
            return true;

234
        const char8_t** filters = extension_filters;
235
236
237
238

#if defined(__APPLE__)
        // @TODO Remove this part when XCode allows u8string find/compare.
        while (*filters) {
239
240
            if (p.extension().u8string() ==
                reinterpret_cast<const char*>(*filters))
241
242
243
244
245
                return true;

            ++filters;
        }
#else
Gauthier Quesnel's avatar
Gauthier Quesnel committed
246
        while (*filters) {
247
            if (p.extension().u8string() == *filters)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
248
249
250
251
                return true;

            ++filters;
        }
252
#endif
Gauthier Quesnel's avatar
Gauthier Quesnel committed
253
254
255
256
257
258

        return false;
    }

    void copy_files_and_directories(const std::filesystem::path& current_path)
    {
259
260
261
        std::error_code err;
        for (std::filesystem::directory_iterator it(current_path, err), et;
             !err && it != et;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
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
             ++it) {

            if (it->is_directory(err) && !err) {
                paths.emplace_back(*it);
                continue;
            }

            if (it->is_regular_file(err) && !err) {
                if (have_good_extension(*it) &&
                    have_good_file_name_starts(*it)) {
                    paths.emplace_back(*it);
                    continue;
                }
            }
        }
    }

    void sort()
    {
        std::sort(std::begin(paths),
                  std::end(paths),
                  [](const auto& lhs, const auto& rhs) {
                      if (std::filesystem::is_directory(lhs)) {
                          if (std::filesystem::is_directory(rhs))
                              return lhs.filename() < rhs.filename();

                          return true;
                      }

                      if (std::filesystem::is_directory(rhs))
                          return false;

                      return lhs.filename() < rhs.filename();
                  });
    }

    void clear()
    {
        paths.clear();
        selected.clear();
        current.clear();
    }

    void show_drives([[maybe_unused]] bool* path_click,
                     [[maybe_unused]] std::filesystem::path* next)
    {
#ifdef _WIN32
        char current_drive = static_cast<char>(current.c_str()[0]);
        char drive_string[] = { current_drive, ':', '\0' };

        ImGui::PushItemWidth(4 * ImGui::GetFontSize());
        if (ImGui::BeginCombo("##select_win_drive", drive_string)) {
            for (int i = 0; i < 26; ++i) {
                if (!(drives & (1 << i)))
                    continue;

                char drive_char = static_cast<char>('A' + i);
                char selectable_string[] = { drive_char, ':', '\0' };
                bool is_selected = current_drive == drive_char;
                if (ImGui::Selectable(selectable_string, is_selected) &&
                    !is_selected) {
                    char new_current[] = { drive_char, ':', '\\', '\0' };
                    std::error_code err;
                    std::filesystem::current_path(new_current, err);
                    if (!err) {
                        selected.clear();
                        *path_click = true;
                        *next = std::filesystem::current_path(err);
                    }
                }
            }

            ImGui::EndCombo();
        }
        ImGui::PopItemWidth();
        ImGui::SameLine();
#endif
    }

    void show_path(bool* path_click, std::filesystem::path* next)
    {
        for (auto it = current.begin(), et = current.end(); it != et; ++it) {
            if (it != current.begin())
                ImGui::SameLine();

347
            if (ImGui::Button((const char*)it->u8string().c_str())) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
348
                next->clear();
349
350
351
352
#if _WIN32
                if (it == current.begin())
                    ++it;
#endif
Gauthier Quesnel's avatar
Gauthier Quesnel committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
                for (auto jt = current.begin(); jt != it; ++jt)
                    *next /= jt->native();
                *next /= it->native();

                selected.clear();
                *path_click = true;
                break;
            }
        }
    }
};

file_dialog fd;

bool
Gauthier Quesnel's avatar
Gauthier Quesnel committed
368
load_file_dialog(std::filesystem::path& out)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
369
370
371
372
373
374
375
376
377
378
379
{
    if (fd.current.empty()) {
        fd.fill_drives();
        fd.selected.clear();
        std::error_code error;
        fd.current = std::filesystem::current_path(error);
    }

    std::filesystem::path next;
    bool res = false;

380
    if (ImGui::BeginPopupModal("Select file path to load")) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
381
382
383
384
385
386
387
388
        bool path_click = false;

        fd.show_drives(&path_click, &next);

        if (!path_click)
            fd.show_path(&path_click, &next);

        if (!path_click) {
389
390
391
392
            ImGui::BeginChild("##select_files",
                              ImVec2{ 0.f, 350.f },
                              true,
                              ImGuiWindowFlags_HorizontalScrollbar);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
393
394
395
396
397
398
399
400
401
402
403
404

            if (ImGui::Selectable("..##select_file", (fd.selected == ".."))) {
                if (next.empty()) {
                    next = fd.current.parent_path();
                    fd.selected.clear();
                    path_click = true;
                }
            }

            for (auto it = fd.paths.begin(), et = fd.paths.end(); it != et;
                 ++it) {
                fd.temp.clear();
405
                if (std::filesystem::is_directory(*it)) {
406
#if defined(__APPLE__)
407
408
                    // @TODO Remove this part when XCode allows u8string
                    // concatenation.
409
                    fd.temp = "[Dir] ";
410
411
                    fd.temp += reinterpret_cast<const char*>(
                      it->filename().u8string().c_str());
412
#else
413
414
                    fd.temp = u8"[Dir] ";
                    fd.temp += it->filename().u8string();
415
#endif
416
417
                } else
                    fd.temp = it->filename().u8string();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
418

419
                if (ImGui::Selectable((const char*)fd.temp.c_str(),
Gauthier Quesnel's avatar
Gauthier Quesnel committed
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
                                      (it->filename() == fd.selected))) {
                    fd.selected = it->filename();

                    if (std::filesystem::is_directory(*it)) {
                        if (next.empty()) {
                            fd.selected.clear();
                            next = fd.current;
                            next /= it->filename();
                            path_click = true;
                        }
                    }
                    break;
                }
            }

            ImGui::EndChild();
        }

        if (path_click) {
            fd.paths.clear();
440
            static const char8_t* filters[] = { u8".irt", nullptr };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
441
442
443
444
445
446
447
448
            fd.extension_filters = filters;
            fd.file_filters = nullptr;

            fd.copy_files_and_directories(next);
            fd.sort();
            fd.current = next;
        }

449
450
        ImGui::Text("File Name: %s",
                    (const char*)fd.selected.u8string().c_str());
Gauthier Quesnel's avatar
Gauthier Quesnel committed
451

452
453
454
455
        const auto item_spacing = ImGui::GetStyle().ItemSpacing.x;
        const auto region_width = ImGui::GetContentRegionAvail().x;
        const auto button_size =
          ImVec2{ (region_width - item_spacing) / 2.f, 0 };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
456

457
        if (ImGui::Button("Ok", button_size)) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
458
459
460
461
462
463
464
465
466
            auto sel = fd.current;
            sel /= fd.selected;
            out = sel;
            res = true;
        }

        ImGui::SetItemDefaultFocus();
        ImGui::SameLine();

467
        if (ImGui::Button("Cancel", button_size)) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
            res = true;
        }

        if (res) {
            ImGui::CloseCurrentPopup();
            fd.clear();
        }

        ImGui::EndPopup();
    }

    return res;
}

bool
Gauthier Quesnel's avatar
Gauthier Quesnel committed
483
save_file_dialog(std::filesystem::path& out)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
484
485
486
487
488
489
{
    if (fd.current.empty()) {
        fd.fill_drives();
        fd.selected.clear();
        std::error_code error;
        fd.current = std::filesystem::current_path(error);
490
491
492
493
494
495
496

        static const std::u8string default_file_name = u8"file-name.irt";
        const size_t max_size =
          std::min(std::size(default_file_name), std::size(fd.buffer) - 1);

        std::copy_n(std::begin(default_file_name), max_size, fd.buffer);
        fd.buffer[max_size] = u8'\0';
Gauthier Quesnel's avatar
Gauthier Quesnel committed
497
498
499
500
501
    }

    std::filesystem::path next;
    bool res = false;

502
    if (ImGui::BeginPopupModal("Select file path to save")) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
503
504
505
506
507
508
509
510
        bool path_click = false;

        fd.show_drives(&path_click, &next);

        if (!path_click)
            fd.show_path(&path_click, &next);

        if (!path_click) {
511
512
513
514
            ImGui::BeginChild("##select_files",
                              ImVec2{ 0.f, 350.f },
                              true,
                              ImGuiWindowFlags_HorizontalScrollbar);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
515
516
517
518
519
520
521
522
523
524
525
526
            if (ImGui::Selectable("..##select_file", (fd.selected == ".."))) {
                if (next.empty()) {
                    next = fd.current.parent_path();
                    fd.selected.clear();
                    path_click = true;
                }
            }

            for (auto it = fd.paths.begin(), et = fd.paths.end(); it != et;
                 ++it) {
                fd.temp.clear();
                if (std::filesystem::is_directory(*it))
527
#if defined(__APPLE__)
528
529
                    // @TODO Remove this part when XCode allows u8string
                    // concatenation.
530
531
                    fd.temp = "[Dir] ";
#else
532
                    fd.temp = u8"[Dir] ";
533
#endif
534
535

                fd.temp = it->filename().u8string();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
536

537
                if (ImGui::Selectable((const char*)fd.temp.c_str(),
Gauthier Quesnel's avatar
Gauthier Quesnel committed
538
539
540
541
542
543
544
545
546
547
548
549
550
                                      (it->filename() == fd.selected))) {
                    fd.selected = it->filename();

                    if (std::filesystem::is_directory(*it)) {
                        if (next.empty()) {
                            fd.selected.clear();
                            next = fd.current;
                            next /= it->filename();
                            path_click = true;
                        }
                    }

                    if (std::filesystem::is_regular_file(*it)) {
551
552
553
554
555
556
557
558
                        const size_t max_size =
                          std::min(std::size(it->filename().u8string()),
                                   std::size(fd.buffer) - 1);

                        std::copy_n(std::begin(it->filename().u8string()),
                                    max_size,
                                    fd.buffer);
                        fd.buffer[max_size] = u8'\0';
Gauthier Quesnel's avatar
Gauthier Quesnel committed
559
560
561
562
563
564
565
566
567
568
569
                    }

                    break;
                }
            }

            ImGui::EndChild();
        }

        if (path_click) {
            fd.paths.clear();
570
            static const char8_t* filters[] = { u8".irt", nullptr };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
571
572
573
574
575
576
577
578
            fd.extension_filters = filters;
            fd.file_filters = nullptr;

            fd.copy_files_and_directories(next);
            fd.sort();
            fd.current = next;
        }

579
580
        ImGui::InputText(
          "File Name", (char*)fd.buffer, IM_ARRAYSIZE(fd.buffer));
Gauthier Quesnel's avatar
Gauthier Quesnel committed
581
582
        ImGui::Text("Directory name: %s",
                    (const char*)fd.current.u8string().c_str());
Gauthier Quesnel's avatar
Gauthier Quesnel committed
583

584
585
        const auto item_spacing = ImGui::GetStyle().ItemSpacing.x;
        const auto region_width = ImGui::GetContentRegionAvail().x;
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
        const auto button_size =
          ImVec2{ (region_width - item_spacing) / 2.f, 0 };

        if (ImGui::Button("Ok", button_size)) {
            auto sel = fd.current;
            sel /= fd.buffer;
            out = sel;
            res = true;
        }

        ImGui::SetItemDefaultFocus();
        ImGui::SameLine();

        if (ImGui::Button("Cancel", button_size)) {
            res = true;
        }

        if (res) {
            ImGui::CloseCurrentPopup();
            fd.clear();
        }

        ImGui::EndPopup();
    }

    return res;
}

bool
select_directory_dialog(std::filesystem::path& out)
{
    if (fd.current.empty()) {
        fd.fill_drives();
        fd.selected.clear();
        std::error_code error;
        fd.current = std::filesystem::current_path(error);
    }

    std::filesystem::path next;
    bool res = false;

    if (ImGui::BeginPopupModal("Select directory")) {
        bool path_click = false;

        fd.show_drives(&path_click, &next);

        if (!path_click)
            fd.show_path(&path_click, &next);

        if (!path_click) {
            ImGui::BeginChild("##select_files",
                              ImVec2{ 0.f, 350.f },
                              true,
                              ImGuiWindowFlags_HorizontalScrollbar);
            if (ImGui::Selectable("..##select_file", (fd.selected == ".."))) {
                if (next.empty()) {
                    next = fd.current.parent_path();
                    fd.selected.clear();
                    path_click = true;
                }
            }

            for (auto it = fd.paths.begin(), et = fd.paths.end(); it != et;
                 ++it) {
                fd.temp.clear();
                if (std::filesystem::is_directory(*it)) {
#if defined(__APPLE__)
                    // @TODO Remove this part when XCode allows u8string
                    // concatenation.
                    fd.temp = "[Dir] ";
                    fd.temp += reinterpret_cast<const char*>(
                      it->filename().u8string().c_str());
#else
                    fd.temp = u8"[Dir] ";
                    fd.temp += it->filename().u8string();
#endif

                    if (ImGui::Selectable((const char*)fd.temp.c_str(),
                                          (it->filename() == fd.selected))) {
                        fd.selected = it->filename();

                        if (next.empty()) {
                            fd.selected.clear();
                            next = fd.current;
                            next /= it->filename();
                            path_click = true;
                        }
                        break;
                    }
                }
            }

            ImGui::EndChild();
        }

        if (path_click) {
            fd.paths.clear();
            fd.extension_filters = nullptr;
            fd.file_filters = nullptr;

            fd.copy_files_and_directories(next);
            fd.sort();
            fd.current = next;
        }

        ImGui::Text("Directory name: %s",
                    (const char*)fd.current.u8string().c_str());

        const auto item_spacing = ImGui::GetStyle().ItemSpacing.x;
        const auto region_width = ImGui::GetContentRegionAvail().x;
        const auto button_size =
          ImVec2{ (region_width - item_spacing) / 2.f, 0 };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
698

699
        if (ImGui::Button("Ok", button_size)) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
700
701
702
703
704
705
706
707
708
            auto sel = fd.current;
            sel /= fd.buffer;
            out = sel;
            res = true;
        }

        ImGui::SetItemDefaultFocus();
        ImGui::SameLine();

709
        if (ImGui::Button("Cancel", button_size)) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
710
711
712
713
714
715
716
717
718
719
720
721
722
723
            res = true;
        }

        if (res) {
            ImGui::CloseCurrentPopup();
            fd.clear();
        }

        ImGui::EndPopup();
    }

    return res;
}

Gauthier Quesnel's avatar
Gauthier Quesnel committed
724
} // namespace irt