interface.cpp 34.9 KB
Newer Older
1
#include "interface.hpp"
2
3
#include "ui_interface.h"

4
#include "savingdialog.hpp"
5
#include "structurewriter.hpp"
6
#include "structurereader.hpp"
7
8
9
10
#include "factory.hpp"
#include "transitionrule.hpp"
#include "neighborhoodrule.hpp"
#include "propertyvisitors.hpp"
11
#include "modelloadingdialog.hpp"
12
#include "configurationloadingdialog.hpp"
13
#include "neighborhoodDialog.hpp"
14
#include "colorlabel.hpp"
15

16
17
#include "gif/gifenc.h"

18
#include <QtGlobal>
19
#include <QJsonArray>
Merwane Bouri's avatar
Merwane Bouri committed
20
21
#include <QDate>
#include <QTextStream>
22
#include <QInputDialog>
Anthony Noir's avatar
Anthony Noir committed
23
#include <QTimer>
24
#include <QElapsedTimer>
Yann Boucher's avatar
Snake !  
Yann Boucher committed
25
#include <QKeyEvent>
26

27
#ifdef HAS_MULTIMEDIA
28
29
30
31
32
33
34
35
#define BAD_APPLE_AUDIO
#endif

#ifdef BAD_APPLE_AUDIO
#include <QMediaPlayer>
#endif


36
37
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
38
39
40
41
      , ui(new Ui::MainWindow)
      , simulation()
      , timer(new QTimer(this))
      , m_customizing(false)
42
43
{
    ui->setupUi(this);
Yann Boucher's avatar
Snake !  
Yann Boucher committed
44
    std::fill(std::begin(m_arrow_key_state), std::end(m_arrow_key_state), false);
45

46
47
48
    m_transition_rule = nullptr;
    m_neighborhood_rule = nullptr;

49
50
    init_transition_neighborhood_list();
    update_transition_settings();
51
    update_neighborhood_settings();
52

53
    connect(ui->action_save_struct, &QAction::triggered, this, &MainWindow::afficher_interface_sauvegarde_structure);
54
    connect(ui->struct_library, &StructureLibraryView::structure_copied, this, &MainWindow::copy_structure_clicked);
55
    connect(ui->grid_view, &GridView::zoom_changed, ui->struct_library, &StructureLibraryView::update_cell_pixel_size);
Yann Boucher's avatar
Yann Boucher committed
56
    connect(ui->statesSettingsButton, &QPushButton::clicked, this, [this]
Yann Boucher's avatar
Snake !  
Yann Boucher committed
57
58
59
60
61
62
63
            {
                ColorLabel* dialog = new ColorLabel(simulation.getAlphabet(), this);
                if (dialog->exec())
                {
                    ui_update_alphabet(dialog->getAlphabet());
                }
            });
64
    connect(ui->transition_list, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
65
            { update_transition_settings(); });
66
    connect(ui->action_open_configuration, &QAction::triggered, this, [this] { on_openPatternButton_clicked(); });
67
    connect(ui->action_bad_apple, &QAction::triggered, this, &MainWindow::play_bad_apple);
Yann Boucher's avatar
Snake !  
Yann Boucher committed
68
    connect(ui->action_snake, &QAction::triggered, this, &MainWindow::play_snake);
69
    connect(ui->action_propos_de_Cellulut, &QAction::triggered, this, [this](bool)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
70
71
72
            {
                QMessageBox::about(this, "À propos de Cellulut",
                                   "Projet de C++ réalisé dans le cadre de l'UV LO21 de l'UTC.\n\n"
73
                                   "Contributeurs : Anthony Noir, Eugène Pin, Merwane Bouri, Arthur Detree, Yann Boucher");
Yann Boucher's avatar
Snake !  
Yann Boucher committed
74
            });
75
    connect(ui->action_propos_de_Qt, &QAction::triggered, this, [this](bool)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
76
77
78
            {
                QMessageBox::aboutQt(this, "À propos de Qt");
            });
79
    connect(ui->actionCharger_depuis_une_image, &QAction::triggered, this, [this](bool)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
80
81
82
            {
                load_from_image();
            });
83
84
    connect(ui->action_save_image, &QAction::triggered, this, &MainWindow::save_as_image);
    connect(ui->action_save_gif, &QAction::triggered, this, &MainWindow::save_as_gif);
85
    connect(ui->border_combo, QOverload<int>::of(&QComboBox::activated), this, &MainWindow::load_boundary_policy);
Yann Boucher's avatar
Yann Boucher committed
86
87
    connect(ui->action_fullscreen, &QAction::triggered, this, &MainWindow::enter_fullscreen);
    connect(ui->grid_view, &GridView::exit_fullscreen, this, &MainWindow::exit_fullscreen);
88

89
    ui->struct_library->update_cell_pixel_size(ui->grid_view->cell_screen_size());
90

91
    simulation.setHistorySize(ui->recordSpinBox->value());
92
    simulation.set_boundary_policy(BoundaryPolicy::Periodic);
93
94
95
96
97
    if (!try_load_saved_state())
    {
        load_model(default_model());
        load_grid_configuration(default_configuration());
    }
Anthony Noir's avatar
Anthony Noir committed
98
99
100
101
102

    connect(timer, &QTimer::timeout, this, [this](){
        on_nextButton_clicked();
        timer->start();
    });
103
104
105
106
107
}

MainWindow::~MainWindow()
{
    delete ui;
108
    // FIXME : il y a un risque de fuite de mémoire avec la gestion de pointeurs de m_transition_rule et m_neighborhood_rule, si l'application est quitée alors que ils pointent vers de la mémoire non transférée vers Simulation
109
110
}

111
112
/// Connections

113
114
115
116
117
118
119
120
121
void MainWindow::on_simSpeedSpinbox_valueChanged(int arg1)
{
    ui->simSpeedSlider->setValue(arg1);
}

void MainWindow::on_simSpeedSlider_valueChanged(int value)
{
    ui->simSpeedSpinbox->setValue(value);
}
122
123
124

void MainWindow::on_openPatternButton_clicked()
{
125
126
127
128
129
    ConfigurationLoadingDialog dialog(m_loaded_model.value("title").toString(), this);
    if (!dialog.exec())
        return;

    load_grid_configuration(dialog.configuration());
130
131
132
133
134
}

void MainWindow::on_openRuleButton_clicked()
{
    // Indiquer qu'une nouvelle règle vient d'être ouverte. La règle est sauvegardé, donc on peut lancer la simulation
135
136
137
138
139
140

    ModelLoadingDialog dialog(this);
    if (!dialog.exec())
        return;

    load_model(dialog.model());
141
142
}

143
void MainWindow::on_neighborhood_list_currentTextChanged(const QString &)
144
{
145
    update_neighborhood_settings();
146
147
}

148
void MainWindow::on_widthSpinBox_valueChanged(int)
149
150
151
152
{
    ui->validateGridDim->setEnabled(true);
}

153
void MainWindow::on_heightSpinBox_valueChanged(int)
154
155
156
157
{
    ui->validateGridDim->setEnabled(true);
}

158
QString MainWindow::afficher_interface_sauvegarde_structure()
159
{
160
    SavingDialog dialog(this);
161
    if (!dialog.exec())
162
        return "";
163

164
    QString filename = QFileDialog::getSaveFileName(this, "Choose a file name", "", "Cellulut format (*.json);;Golly RLE format (*.rle)");
165
    QFileInfo info(filename);
166
    //printf("%s\n", info.suffix().toStdString().c_str());
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
    // on pourrait utiliser un Factory ici, mais c'est possiblement overkill, les possibilités d'évolution de format de fichier sont faibles et ne justifient pas l'effort

    Structure s = ui->grid_view->selected_cells();
    s.author = dialog.auteur().toStdString();
    s.title = dialog.titre().toStdString();
    s.desc = dialog.desc().toStdString();
    s.date = dialog.date().toString().toStdString();

    std::string save_data;
    if (info.suffix() == "json")
    {
        JSONStructureWriter writer;
        save_data = writer.save_structure(s);
    }
    else if (info.suffix() == "rle")
    {
        RLEStructureWriter writer;
        save_data = writer.save_structure(s);
    }

    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly))
    {
190
        QMessageBox::information(this, "Unable to create file",
191
                                 file.errorString());
192
        return "";
193
194
195
196
    }

    QTextStream stream(&file);
    stream << QString::fromStdString(save_data);
197
198

    return filename;
199
200
}

201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
void MainWindow::save_as_image()
{
    QString filename = QFileDialog::getSaveFileName(this, tr("Save image"),"",tr("PNG (*.png);;JPG (*.jpg);;BMP (*.bmp)"));
    if (filename.isEmpty())
        return;

    QImage img = ui->grid_view->grid_image();
    if (!img.save(filename))
        QMessageBox::warning(this, "Error", "Could not save file");
}

void MainWindow::save_as_gif()
{
    const unsigned width  = ui->grid_view->get_grid().get_col();
    const unsigned height = ui->grid_view->get_grid().get_rows();
    const unsigned delay = 100/ui->simSpeedSlider->value(); // hundredths of second
    const Alphabet& alph = ui->grid_view->alphabet();
    unsigned state_count = alph.taille();
219
    unsigned palette_depth = 1;
220
221
222
223
224
225
    while (state_count >>= 1) ++palette_depth; // log2

    QString filename = QFileDialog::getSaveFileName(this, tr("Save GIF"),"",tr("GIF (*.gif)"));
    if (filename.isEmpty())
        return;

226
    std::vector<uint8_t> palette((1 << palette_depth)*3);
227
228
    for (unsigned i = 0; i < alph.taille(); ++i)
    {
229
230
231
        palette[3*i+0] = (alph.getState(i).getColor().getRed());
        palette[3*i+1] = (alph.getState(i).getColor().getGreen());
        palette[3*i+2] = (alph.getState(i).getColor().getBlue());
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
    }

    ge_GIF* gif = ge_new_gif(filename.toStdString().c_str(), width, height, palette.data(), palette_depth, 0);

    const History& hist = simulation.getHistory();
    for (unsigned k = 0; k < hist.size(); ++k)
    {
        Grid grid = hist.at(k);
        // L'historique contient une grid de taille différente, on l'ignore
        if (grid.get_col() != width || grid.get_rows() != height)
            continue;

        for(int i = 0; i < (int)height; ++i)
        {
            for(int j = 0; j < (int)width; ++j)
            {
                gif->frame[i*width + j] = grid.get_state({j,i});
            }
        }
        ge_add_frame(gif, delay);
    }

    ge_close_gif(gif);
}

257

258
259
void MainWindow::on_validateGridDim_clicked()
{
260
261
    Grid oldGrid = ui->grid_view->get_grid();

262

263
264
265
    unsigned int nbrRow = ui->heightSpinBox->value(); // nbr de lignes => axe y
    unsigned int nbrCol = ui->widthSpinBox->value(); // nbr de colonne => axe x
    Grid newGrid(nbrRow, nbrCol);
266

267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
    unsigned oldNbrRow = oldGrid.get_rows(); // rows = nbr de lignes => axe y
    unsigned oldNbrCol = oldGrid.get_col(); // col = nbr de colonne => axe x

    if(oldNbrRow <= nbrRow && oldNbrCol <= nbrCol) {
        //std::cout << "superieur\n";
        fflush(stdout);
        for (unsigned y = 0; y < oldNbrRow ; y++) {
            for (unsigned x = 0; x < oldNbrCol ; x++) {
                Coord pos = {static_cast<int>(x), static_cast<int>(y)};
                newGrid.set_cell(pos, oldGrid.get_state(pos));
                //std::cout << "oldState : " << oldGrid.get_state(pos) << endl;
            }
        }
    }
    else
    {
283
284
        //std::cout << "superieur\n";
        fflush(stdout);
285
286
287
        for (unsigned y = 0; y < nbrRow ; y++) {
            for (unsigned x = 0; x < nbrCol ; x++) {
                Coord pos = {static_cast<int>(x), static_cast<int>(y)};
288
289
290
291
292
293
                newGrid.set_cell(pos, oldGrid.get_state(pos));
                //std::cout << "oldState : " << oldGrid.get_state(pos) << endl;
            }
        }
    }

294
    ui->grid_view->copy_grid(newGrid);
295
296
    simulation.reset();
    simulation.setGrid(newGrid);
297
298
    ui->validateGridDim->setEnabled(false);
}
299
300
301
302
303
304
305

void MainWindow::on_nbrStateComboBox_currentTextChanged(const QString &arg1)
{
    unsigned val = arg1.toInt();

    ui->grid_view->set_current_pen(val);
}
306
307
308

void MainWindow::on_randomPatternButton_clicked()
{
309
    int alphabetSize = simulation.getAlphabet().taille();
310
311
312
313
314
315
316
317
318
319

    Grid oldGrid = ui->grid_view->get_grid();
    unsigned nbrRow = oldGrid.get_rows(); // rows = nbr de lignes => axe y
    unsigned nbrCol = oldGrid.get_col(); // col = nbr de colonne => axe x
    Grid newGrid(nbrRow, nbrCol);

    for (unsigned y = 0; y < nbrRow; ++y)
    {
        for (unsigned x = 0; x < nbrCol; ++x)
        {
320
            unsigned state = rand() % alphabetSize;
321
322
323
324
325
            Coord pos = {static_cast<int>(x), static_cast<int>(y)};
            newGrid.set_cell(pos, state);
        }
    }

326
    ui->grid_view->copy_grid(newGrid);
327
}
328

329
330
331
332
333
void MainWindow::on_drawCellButton_clicked()
{
    ui->grid_view->fill_selection(ui->nbrStateComboBox->currentIndex());
}

334
335
336
337
338
void MainWindow::copy_structure_clicked(const Structure &s)
{
    ui->grid_view->set_clipboard(s);
    statusBar()->showMessage("Structure copied.", 5000);
}
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355

void MainWindow::init_transition_neighborhood_list()
{
    for (const auto& transition : Factory<TransitionRule>::list_choices())
    {
        ui->transition_list->addItem(QString::fromStdString(transition));
    }

    for (const auto& rule : Factory<NeighborhoodRule>::list_choices())
    {
        ui->neighborhood_list->addItem(QString::fromStdString(rule));
    }
}

void MainWindow::update_transition_settings()
{
    std::string selected = ui->transition_list->currentText().toStdString();
356
357
    m_transition_rule = Factory<TransitionRule>::make(selected).release();
    if (!m_transition_rule)
358
359
        return;

360
    if (m_transition_rule->get_properties().size() == 0)
361
362
363
364
365
366
        ui->rule_settings_area->hide();
    else
    {
        ui->rule_settings_area->show();

        UIBuilderVisitor visit(ui->rule_settings_area);
367
        for (auto& prop : m_transition_rule->get_properties())
368
369
            prop->accept(visit);
    }
370
}
371
372
373
void MainWindow::update_neighborhood_settings()
{
    std::string selected = ui->neighborhood_list->currentText().toStdString();
374
375
    m_neighborhood_rule = Factory<NeighborhoodRule>::make(selected).release();
    if (!m_neighborhood_rule)
376
377
        return;

378
    if (m_neighborhood_rule->get_properties().size() == 0)
379
380
381
382
383
384
        ui->neighborhood_settings_area->hide();
    else
    {
        ui->neighborhood_settings_area->show();

        UIBuilderVisitor visit(ui->neighborhood_settings_area);
385
        for (auto& prop : m_neighborhood_rule->get_properties())
386
387
388
            prop->accept(visit);
    }
}
389

390
391
void MainWindow::enable_rule_customization()
{
Yann Boucher's avatar
Yann Boucher committed
392
    //ui->simulation_tab->setEnabled(false);
Yann Boucher's avatar
Yann Boucher committed
393
    ui->savePatternButton->setEnabled(false);
394
    ui->customize_button->setText("Cancel customization");
395
    ui->rule_settings->setEnabled(true);
396
    m_customizing = true;
397
398
}

399
400
void MainWindow::disable_rule_customization()
{
Yann Boucher's avatar
Yann Boucher committed
401
    //ui->simulation_tab->setEnabled(true);
Yann Boucher's avatar
Yann Boucher committed
402
    ui->savePatternButton->setEnabled(true);
403
404
    ui->customize_button->setEnabled(true);
    ui->rule_settings->setEnabled(false);
405
406
    ui->customize_button->setText("Customize...");
    m_customizing = false;
407
408
409
410
411
}

void MainWindow::load_model(const QJsonObject &obj)
{
    ui->rule_name->setText(obj.value("title").toString());
412

413
    ui->transition_list->setCurrentText(obj.value("transition_name").toString());
414
    ui->neighborhood_list->setCurrentText(obj.value("neighborhood_name").toString());
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
    bool alpha_initialise = false;
    Alphabet alpha;
    if (obj.value("alphabet").isArray())
    {
        for (auto entry : obj.value("alphabet").toArray())
        {
            if (!entry.isObject())
                continue;

            auto entry_obj = entry.toObject();
            std::string name = entry_obj.value("name").toString().toStdString();

            if (!entry_obj.value("color").isArray())
                continue;

            auto color_array = entry_obj.value("color").toArray();
            stateColor color(color_array[0].toInt(), color_array[1].toInt(), color_array[2].toInt());

            // Initialisation avec le premier élement
            if (!alpha_initialise)
            {
                alpha = Alphabet(state(color, name));
                alpha_initialise = true;
            }
            else
                alpha.newEtat(state(color, name));
        }
    }


446
    update_transition_settings();
447
    update_neighborhood_settings();
448
449
    disable_rule_customization();

450
451
    {
        PropertyLoaderVisitor loader(obj.value("transition_data").toObject());
452
        for (auto& prop : m_transition_rule->get_properties())
453
454
            prop->accept(loader);
        UIBuilderVisitor visit(ui->rule_settings_area);
455
        for (auto& prop : m_transition_rule->get_properties())
456
457
458
459
460
            prop->accept(visit);
    }

    {
        PropertyLoaderVisitor loader(obj.value("neighborhood_data").toObject());
461
        for (auto& prop : m_neighborhood_rule->get_properties())
462
463
            prop->accept(loader);
        UIBuilderVisitor visit(ui->neighborhood_settings_area);
464
        for (auto& prop : m_neighborhood_rule->get_properties())
465
466
            prop->accept(visit);
    }
467
468

    // On transfère la propriété de ces pointeurs vers Simulation, qui en est désormais propriétaire pour l'exécution de l'automate
469
470
    simulation.setNeighborhoodRule(m_neighborhood_rule);
    simulation.setTransitionRule(m_transition_rule);
471
    simulation.reset();
Yann Boucher's avatar
Yann Boucher committed
472
    ui_update_alphabet(alpha);
473
474

    m_loaded_model = obj;
475
476
477
}

void MainWindow::save_model()
478
479
480
481
482
{
    SavingDialog dialog(this);
    if (!dialog.exec())
        return;

483
    QString filename = QFileDialog::getSaveFileName(this, "Choose a file name", QString(), "Automaton model file (*.json)");
484

485
    PropertySaverVisitor trans_saver;
486
    for (auto& prop : m_transition_rule->get_properties())
487
488
489
        prop->accept(trans_saver);

    PropertySaverVisitor neighborhood_saver;
490
    for (auto& prop : m_neighborhood_rule->get_properties())
491
        prop->accept(neighborhood_saver);
492
493
494
495
496
497
498
499

    QJsonObject root;
    root["title"] = dialog.titre();
    root["author"] = dialog.auteur();
    root["desc"] = dialog.desc();
    root["date"] = dialog.date().toString();

    root["transition_name"] = ui->transition_list->currentText();
500
501
502
503
    root["transition_data"] = trans_saver.save();

    root["neighborhood_name"] = ui->neighborhood_list->currentText();
    root["neighborhood_data"] = neighborhood_saver.save();
504
505
506

    QJsonArray alphabet;

507
508
509
510
511
512
513
514
515
516
517
518
519
    for (unsigned i = 0; i < simulation.getAlphabet().taille(); ++i)
    {
        auto state = simulation.getAlphabet().getState(i);
        QJsonArray color;
        QJsonObject entry;
        entry["name"] = QString::fromStdString(state.getStateLabel());
        color.push_back(state.getColor().getRed());
        color.push_back(state.getColor().getGreen());
        color.push_back(state.getColor().getBlue());
        entry["color"] = color;
        alphabet.push_back(entry);
    }

520
521
522
523
    root["alphabet"] = alphabet;

    QJsonDocument doc(root);
    QFile file(filename);
524
525
    if (!file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate))
    {
526
        QMessageBox::information(this, "Unable to create file",
527
528
                                 file.errorString());
    }
529
530
    file.write(doc.toJson());
    file.close();
531
532
533

    ui->rule_name->setText(dialog.titre());
    disable_rule_customization();
534
535

    load_model(root);
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
static unsigned closest_state(const Alphabet& alph, const QColor& color)
{
    unsigned best_distance = std::numeric_limits<unsigned>::max();
    unsigned best_match = 0;
    for (unsigned i = 0; i < alph.taille(); ++i)
    {
        state s = alph.getState(i);
        unsigned r_diff = qAbs(color.red() - s.getColor().getRed());
        unsigned g_diff = qAbs(color.green() - s.getColor().getGreen());
        unsigned b_diff = qAbs(color.blue() - s.getColor().getBlue());
        unsigned distance = r_diff*r_diff + g_diff*g_diff + b_diff*b_diff;
        if (distance < best_distance)
        {
            best_distance = distance;
            best_match = i;
        }
    }

    return best_match;
}

void MainWindow::load_from_image()
{
561
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"",tr("Image (*.png *.jpg *.jpeg *.bmp *.gif)"));
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
    QImage img(fileName);
    if (img.isNull())
        return;

    Grid grid = ui->grid_view->get_grid();

    img = img.scaled(grid.get_col(),
                     grid.get_rows());
    for (int x = 0; x < img.width(); ++x)
        for (int y = 0; y < img.height(); ++y)
        {
            unsigned closest = closest_state(ui->grid_view->alphabet(), img.pixelColor(x, y));
            grid.set_cell(Coord{x, y}, closest);
        }

    ui->grid_view->copy_grid(grid);
}

580
581
void MainWindow::ui_update_alphabet(const Alphabet &alpha)
{
Yann Boucher's avatar
Yann Boucher committed
582
    simulation.setAlphabet(alpha);
583
    ui->struct_library->set_alphabet(alpha);
584
585
586
    ui->grid_view->set_alphabet(alpha);
    ui->nbrStateComboBox->clear();
    for (unsigned i = 0; i < alpha.taille(); ++i)
Yann Boucher's avatar
Yann Boucher committed
587
    {
588
        ui->nbrStateComboBox->addItem(QString::number(i));
Yann Boucher's avatar
Yann Boucher committed
589
    }
590
591
}

592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
bool MainWindow::try_load_saved_state()
{
    QFile file("saved_state.json");
    if (!file.open(QFile::ReadOnly | QFile::Text))
    {
        return false;
    }
    QTextStream in(&file);

    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(in.readAll().toUtf8(), &parseError);
    if(parseError.error != QJsonParseError::NoError)
    {
        return false;
    }
    QJsonObject data = jsonDoc.object();
    QJsonObject model = data.value("model").toObject();
    QJsonObject config = data.value("config").toObject();
610
    unsigned boundary_policy = data.value("boundary_policy").toInt(0);
611
612
613
614
615
    if (model.isEmpty() || config.isEmpty())
        return false;

    load_model(model);
    load_grid_configuration(config);
616
    load_boundary_policy(boundary_policy);
617
618

    return true;
619
620
}

621
622
void MainWindow::save_grid_configuration()
{
623
624
625
    const Grid& grid = ui->grid_view->get_grid();
    Structure grid_data = grid.to_structure();

626
    QString title = QInputDialog::getText(this, "Choose a title", "Configuration title : ");
627
628
629
630
631
    if (title.isEmpty())
        return;

    RLEStructureWriter writer;
    std::string structure_data = writer.save_structure(grid_data);
632
633

    QJsonObject json_data;
634
635
636
637
638
639
640
641
    json_data["width"] = (int)grid.get_col();
    json_data["height"] = (int)grid.get_rows();
    json_data["title"] = title;
    json_data["model"] = m_loaded_model.value("title");
    json_data["left"] = grid_data.top_left.x;
    json_data["top"] = grid_data.top_left.y;
    json_data["data"] = QString::fromStdString(structure_data);

642
    QString filename = QFileDialog::getSaveFileName(this, "Choose a file name", "", "Cellulut configuration  (*.json)");
643
644
645
646
647
648
    if (filename.isEmpty())
        return;

    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QFile::Text | QFile::Truncate))
    {
649
        QMessageBox::information(this, "Unable to create file",
650
651
652
653
654
655
                                 file.errorString());
    }

    QJsonDocument doc(json_data);
    file.write(doc.toJson());
    file.close();
656
657
}

658
void MainWindow::load_grid_configuration(const QJsonObject& configuration)
659
{
660
661
    Grid g(configuration.value("height").toInt(10),
           configuration.value("width").toInt(10));
662
    Coord origin;
663
664
    origin.x = configuration.value("left").toInt(0);
    origin.y = configuration.value("top").toInt(0);
665

666
    RLEStructureReader reader(configuration.value("data").toString().toStdString());
667
    Structure s = reader.read_structure();
668

669
670
671
672
    ui->grid_view->copy_grid(g);
    ui->grid_view->paste_structure_at(origin, s);
    ui->widthSpinBox->setValue(g.get_col());
    ui->heightSpinBox->setValue(g.get_rows());
673
674
    simulation.reset();
    simulation.setGrid(g);
675
676
}

677
678
QJsonObject MainWindow::default_model() const
{
679
680
681
    const char* json = R"(
    {
        "title" : "Game of Life",
682
683
        "neighborhood_name" : "Moore",
        "neighborhood_data" : {},
684
685
686
687
688
689
690
691
692
        "transition_name" : "Game of Life",
        "transition_data" : {},
        "alphabet" : [
        {"name" : "Dead", "color" : [255, 255, 255]},
        {"name" : "Alive", "color" : [0, 0, 255]}]
    }
)";

    QJsonDocument doc = QJsonDocument::fromJson(QByteArray(json));
693

694
    return doc.object();
695
696
}

697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
QJsonObject MainWindow::default_configuration() const
{
    const char* json = R"(
    {
    "data": "x = 2, y = 2\n!",
    "height": 50,
    "left": 0,
    "model": "Game of Life",
    "title": "Game of Life Default",
    "top": 0,
    "width": 50
    }
)";

    QJsonDocument doc = QJsonDocument::fromJson(QByteArray(json));

    return doc.object();
}

716
717
718
719
void MainWindow::play_bad_apple()
{
    static QJsonArray bad_apple_frame_list;
    static QTimer bad_apple_timer;
720
721
722
#ifdef BAD_APPLE_AUDIO
    static QMediaPlayer bad_apple_player;
#endif
Yann Boucher's avatar
Yann Boucher committed
723
    static QElapsedTimer bad_apple_elapsed;
724

725
    QFile f("extras/bad_apple.json");
726
    if (!f.open(QFile::ReadOnly | QFile::Text))
727
    {
728
        QMessageBox::warning(this, "", "Couldn't open 'extras/bad_apple.json'\n");
729
730
        return;
    }
731
732
733
734
735
736
737
738
739
740
    QTextStream in(&f);

    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(in.readAll().toUtf8(), &parseError);
    QJsonObject frames = jsonDoc.object();

    bad_apple_timer.stop();
    bad_apple_frame_list = frames["data"].toArray();

    {
741
        connect(&bad_apple_timer, &QTimer::timeout, this, [this]
Yann Boucher's avatar
Snake !  
Yann Boucher committed
742
                                      {
743
#ifdef BAD_APPLE_AUDIO
Yann Boucher's avatar
Yann Boucher committed
744
745
746
747
748
                                          unsigned frame_idx;
                                          if (bad_apple_player.state() == QMediaPlayer::PlayingState)
                                              frame_idx = bad_apple_player.position()/(1000.f/30);
                                          else
                                              frame_idx = bad_apple_elapsed.elapsed()/(1000.f/30);
749
#else
Yann Boucher's avatar
Snake !  
Yann Boucher committed
750
                                          unsigned frame_idx = bad_apple_elapsed.elapsed()/(1000.f/30);
751
#endif
Yann Boucher's avatar
Snake !  
Yann Boucher committed
752
753
754
755
756
                                          if ((int)frame_idx >= bad_apple_frame_list.size())
                                          {
                                              bad_apple_timer.stop();
                                              return;
                                          }
757

Yann Boucher's avatar
Snake !  
Yann Boucher committed
758
                                          Grid grid(120, 160);
759

Yann Boucher's avatar
Snake !  
Yann Boucher committed
760
                                          QJsonObject frame = bad_apple_frame_list[frame_idx].toObject();
761

Yann Boucher's avatar
Snake !  
Yann Boucher committed
762
763
764
                                          Coord origin;
                                          origin.x = frame.value("left").toInt();
                                          origin.y = frame.value("top").toInt();
765

Yann Boucher's avatar
Snake !  
Yann Boucher committed
766
767
768
                                          RLEStructureReader reader(frame.value("data").toString().toStdString());
                                          Structure s = reader.read_structure();
                                          s.top_left = origin;
769

Yann Boucher's avatar
Snake !  
Yann Boucher committed
770
771
772
773
                                          for (auto cell : s)
                                          {
                                              grid.set_cell(cell.first + s.top_left, cell.second);
                                          }
774

Yann Boucher's avatar
Snake !  
Yann Boucher committed
775
                                          ui->grid_view->copy_grid(grid);
776
                                      }, Qt::UniqueConnection);
777
778
779
780
781
782
    };

    // On coupe la simulation si elle est en train de s'exécuter
    if (timer->isActive())
    {
        on_playPauseButton_clicked();
783
    }
784

785
786
787
#ifdef BAD_APPLE_AUDIO
    bad_apple_player.setMedia(QUrl::fromLocalFile("extras/bad-apple.wav"));
    bad_apple_player.play();
788
#else
789
    QMessageBox::information(this, "", "Music functionnality is only available with Qt Multimedia module (might be unavailable with Qt 6)");
790
791
#endif

Yann Boucher's avatar
Yann Boucher committed
792
    bad_apple_elapsed.start();
793
    bad_apple_timer.start(11);
794
795
796
    statusBar()->showMessage("Original : \"Bad Apple!!\" feat. Nomico by Alstroemeria Records", 60000);
}

Yann Boucher's avatar
Snake !  
Yann Boucher committed
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
void MainWindow::play_snake()
{
    static QTimer snake_timer;
    static Coord snake_dir;
    static std::list<Coord> snake_body;

    statusBar()->showMessage("Controls : ZQSD", 60000);

    Alphabet alph;
    alph.newEtat(state{stateColor{0, 0, 0}, "Snake"});
    alph.newEtat(state{stateColor{255, 0, 0}, "Apple"});

    ui->grid_view->set_alphabet(alph);

    snake_body.clear();
    snake_dir = {+1, 0};

    on_pushButton_clicked(); // reset la grille

816
817
    QWidget::grabKeyboard();

Yann Boucher's avatar
Snake !  
Yann Boucher committed
818
819
820
    static auto restore = [&]
    {
        ui_update_alphabet(simulation.getAlphabet());
821
        QWidget::releaseKeyboard();
Yann Boucher's avatar
Snake !  
Yann Boucher committed
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
        snake_timer.stop();
        on_pushButton_clicked(); // reset la grille
    };

    static auto spawn_apple = [&]
    {
        unsigned attempt_limit = 10000;
        while (attempt_limit>0)
        {
            --attempt_limit;
            int rand_x = rand() % ui->grid_view->get_grid().get_col();
            int rand_y = rand() % ui->grid_view->get_grid().get_rows();
            Coord c = {rand_x, rand_y};
            Grid g = ui->grid_view->get_grid();
            if (g.get_state(c) != 0)
                continue;

            g.set_cell(c, 2);
            ui->grid_view->copy_grid(g);
            break;
        }
        if (attempt_limit <= 0) // plus possible de placer de pomme
        {
            restore();
            return;
        }
    };

    static auto advance_snake = [&](bool expand)
    {
        Coord next = snake_body.back() + snake_dir;
        snake_body.push_back(next);
        Grid g = ui->grid_view->get_grid();
        if (g.get_state(snake_body.back()) == 1 ||
            next.x < 0 || next.y < 0 ||
            next.x >= (int)g.get_col() || next.y >= (int)g.get_rows())
        {
            restore();
            return;
        }
        // manger la pomme
        else if (g.get_state(snake_body.back()) == 2)
        {
            expand = true;
            spawn_apple();
        }
        g = ui->grid_view->get_grid();
        g.set_cell(snake_body.back(), 1);
        ui->grid_view->copy_grid(g);

        auto tail = snake_body.front();
        if (!expand)
        {
            snake_body.pop_front();
            Grid g = ui->grid_view->get_grid();
            g.set_cell(tail, 0);
            ui->grid_view->copy_grid(g);
        }
    };

    Coord start = {3, 1};
    snake_body.push_back(start);
    Grid g = ui->grid_view->get_grid();
    g.set_cell(start, 1);
    ui->grid_view->copy_grid(g);

    advance_snake(true);
    advance_snake(true);
    spawn_apple();

    // On coupe la simulation si elle est en train de s'exécuter
    if (timer->isActive())
    {
        on_playPauseButton_clicked();
    }

898

Yann Boucher's avatar
Snake !  
Yann Boucher committed
899
    {
900
       connect(&snake_timer, &QTimer::timeout, this, [this]
Yann Boucher's avatar
Snake !  
Yann Boucher committed
901
902
903
904
905
906
907
908
909
910
                                  {
                                      if (m_arrow_key_state[0] && snake_dir != Coord{+1, 0})
                                          snake_dir = {-1, 0};
                                      else if (m_arrow_key_state[1] && snake_dir != Coord{0, -1})
                                          snake_dir = {0, +1};
                                      else if (m_arrow_key_state[2] && snake_dir != Coord{-1, 0})
                                          snake_dir = {+1, 0};
                                      else if (m_arrow_key_state[3] && snake_dir != Coord{0, +1})
                                          snake_dir = {0, -1};
                                      advance_snake(false);
911
912
                                  }, Qt::UniqueConnection);

Yann Boucher's avatar
Snake !  
Yann Boucher committed
913
914
915
916
    }
    snake_timer.start(100);
}

917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
void MainWindow::closeEvent(QCloseEvent *e)
{
    // Sauvegarder l'état actuel de l'application

    const Grid& grid = ui->grid_view->get_grid();
    Structure grid_data = grid.to_structure();

    RLEStructureWriter writer;
    std::string structure_data = writer.save_structure(grid_data);

    QJsonObject config_data;
    config_data["width"] = (int)grid.get_col();
    config_data["height"] = (int)grid.get_rows();
    config_data["title"] = "Saved configuration";
    config_data["model"] = m_loaded_model.value("title");
    config_data["left"] = grid_data.top_left.x;
    config_data["top"] = grid_data.top_left.y;
    config_data["data"] = QString::fromStdString(structure_data);

    QJsonObject model = m_loaded_model;

    QJsonObject save_data;
    save_data["config"] = config_data;
    save_data["model"] = model;
941
    save_data["boundary_policy"] = ui->border_combo->currentIndex();
942
943
944
945
946
947
948
949
950
951
952
953
954
955

    QFile file("saved_state.json");
    if (!file.open(QIODevice::WriteOnly | QFile::Text | QFile::Truncate))
    {
        return;
    }

    QJsonDocument doc(save_data);
    file.write(doc.toJson());
    file.close();

    QMainWindow::closeEvent(e);
}

Yann Boucher's avatar
Snake !  
Yann Boucher committed
956
957
void MainWindow::keyPressEvent(QKeyEvent *event)
{
958
    if (event->key() == Qt::Key_Q || event->key() == Qt::Key_Left)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
959
        m_arrow_key_state[0] = true;
960
    if (event->key() == Qt::Key_S || event->key() == Qt::Key_Down)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
961
        m_arrow_key_state[1] = true;
962
    if (event->key() == Qt::Key_D || event->key() == Qt::Key_Right)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
963
        m_arrow_key_state[2] = true;
964
    if (event->key() == Qt::Key_Z || event->key() == Qt::Key_Up)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
965
        m_arrow_key_state[3] = true;
Yann Boucher's avatar
Yann Boucher committed
966

Yann Boucher's avatar
Snake !  
Yann Boucher committed
967
968
969
970
971
    QMainWindow::keyPressEvent(event);
}

void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
972
    if (event->key() == Qt::Key_Q || event->key() == Qt::Key_Left)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
973
        m_arrow_key_state[0] = false;
974
    if (event->key() == Qt::Key_S || event->key() == Qt::Key_Down)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
975
        m_arrow_key_state[1] = false;
976
    if (event->key() == Qt::Key_D || event->key() == Qt::Key_Right)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
977
        m_arrow_key_state[2] = false;
978
    if (event->key() == Qt::Key_Z || event->key() == Qt::Key_Up)
Yann Boucher's avatar
Snake !  
Yann Boucher committed
979
980
981
982
        m_arrow_key_state[3] = false;
    QMainWindow::keyReleaseEvent(event);
}

983
984
985
986
987
988
989
void MainWindow::on_saveRuleButton_clicked()
{
    save_model();
}

void MainWindow::on_customize_button_clicked()
{
990
991
992
993
994
995
996
997
998
    if (!m_customizing)
    {
        enable_rule_customization();
    }
    else
    {
        disable_rule_customization();
        load_model(m_loaded_model);
    }
999
}
1000

1001
1002
1003

void MainWindow::on_savePatternButton_clicked()
{
1004
    save_grid_configuration();
1005
}
Anthony Noir's avatar
Anthony Noir committed
1006
1007
1008
1009
1010
1011

void MainWindow::on_nextButton_clicked()
{
    simulation.setGrid(ui->grid_view->get_grid());
    simulation.step();
    ui->grid_view->copy_grid(simulation.getGrid());
1012
    ui->stepsPeriodLabel->setText(simulation.getPeriod()!=-1?QString::number(simulation.getPeriod())+" steps":"none");
Anthony Noir's avatar
Anthony Noir committed
1013
    ui->nbStepsLabel->setText(QString::number(simulation.getTime())+" steps");
Anthony Noir's avatar
Anthony Noir committed
1014
1015
1016
    if(simulation.frozen()) {
        ui->simStatusLabel->setText("Status : frozen");
    }
Anthony Noir's avatar
Anthony Noir committed
1017
1018
1019
1020
1021
}

void MainWindow::on_prevButton_clicked()
{
    if(!simulation.back()) {
1022
        QMessageBox::warning(this, "Unable to step back", "Empty history : unable to step back");
Anthony Noir's avatar
Anthony Noir committed
1023
1024
    }
    ui->grid_view->copy_grid(simulation.getGrid());
1025
    ui->nbStepsLabel->setText(QString::number(simulation.getTime())+" steps");
Anthony Noir's avatar
Anthony Noir committed
1026
1027
1028
1029
1030
1031
}

void MainWindow::on_playPauseButton_clicked()
{
    if(timer->isActive()) {
        //Pause
Merwane Bouri's avatar
Merwane Bouri committed
1032
        ui->playPauseButton->setText("Play");
Anthony Noir's avatar
Anthony Noir committed
1033
        ui->simStatusLabel->setText("Status : inactive");
Anthony Noir's avatar
Anthony Noir committed
1034
1035
1036
        timer->stop();
    } else {
        //Play
Merwane Bouri's avatar
Merwane Bouri committed
1037
        ui->playPauseButton->setText("Pause");
Anthony Noir's avatar
Anthony Noir committed
1038
        ui->simStatusLabel->setText("Status : active");
Anthony Noir's avatar
Anthony Noir committed
1039
1040
        int frequence = ui->simSpeedSpinbox->value();
        if(frequence == 0) {
1041
            QMessageBox::critical(this, "Unable to start", "Speed needs to be nonzero.");
Anthony Noir's avatar
Anthony Noir committed
1042
        } else if(!simulation.runnable()) {
1043
            QMessageBox::critical(this, "Unable to start", "Unable to begin the simulation : incompatible rules.");
Anthony Noir's avatar
Anthony Noir committed
1044
1045
1046
1047
1048
1049
        } else {
            timer->setInterval(1000/frequence);
            timer->start();
        }
    }
}
Anthony Noir's avatar
reset  
Anthony Noir committed
1050
1051
1052
1053
1054

void MainWindow::on_resetButton_clicked() {
    if(timer->isActive()) {
        timer->stop();
    }
Merwane Bouri's avatar
Merwane Bouri committed
1055
    ui->playPauseButton->setText("Play");
Anthony Noir's avatar
reset  
Anthony Noir committed
1056
1057
    simulation.reset();
    ui->grid_view->copy_grid(simulation.getGrid());
Anthony Noir's avatar
Anthony Noir committed
1058
    ui->stepsPeriodLabel->setText(QString::number(simulation.getPeriod())+" steps");
Anthony Noir's avatar
Anthony Noir committed
1059
    ui->nbStepsLabel->setText(QString::number(simulation.getTime())+" steps");
Anthony Noir's avatar
reset  
Anthony Noir committed
1060
}
Anthony Noir's avatar
Anthony Noir committed
1061
1062
1063
1064

void MainWindow::on_recordSpinBox_valueChanged(int newSize) {
    simulation.setHistorySize(newSize);
}
1065

Yann Boucher's avatar
Yann Boucher committed
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
void MainWindow::enter_fullscreen()
{
    ui->grid_view->enter_fullscreen();
}

void MainWindow::exit_fullscreen()
{
    ui->grid_view->setParent(ui->grid);
    ui->gridLayout_2->addWidget(ui->grid_view, 0, 0, 1, 1);
    this->activateWindow();
}