interface.cpp 34.2 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"
Yann Boucher's avatar
Yann Boucher committed
14
#include "colorlabel.h"
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);
86

87
    ui->struct_library->update_cell_pixel_size(ui->grid_view->cell_screen_size());
88

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

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

MainWindow::~MainWindow()
{
    delete ui;
106
    // 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
107
108
}

109
110
/// Connections

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

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

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

    load_grid_configuration(dialog.configuration());
128
129
130
131
132
}

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
133
134
135
136
137
138

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

    load_model(dialog.model());
139
140
}

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

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

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

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

162
    QString filename = QFileDialog::getSaveFileName(this, "Choose a file name", "", "Cellulut format (*.json);;Golly RLE format (*.rle)");
163
    QFileInfo info(filename);
164
    //printf("%s\n", info.suffix().toStdString().c_str());
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
    // 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))
    {
188
        QMessageBox::information(this, "Unable to create file",
189
                                 file.errorString());
190
        return "";
191
192
193
194
    }

    QTextStream stream(&file);
    stream << QString::fromStdString(save_data);
195
196

    return filename;
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
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();
    unsigned palette_depth = 0;
    while (state_count >>= 1) ++palette_depth; // log2

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

    std::vector<uint8_t> palette;
    for (unsigned i = 0; i < alph.taille(); ++i)
    {
        palette.push_back(alph.getState(i).getColor().getRed());
        palette.push_back(alph.getState(i).getColor().getGreen());
        palette.push_back(alph.getState(i).getColor().getBlue());
    }

    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);
}

255

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

260

261
262
263
    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);
264

265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    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
    {
281
282
        //std::cout << "superieur\n";
        fflush(stdout);
283
284
285
        for (unsigned y = 0; y < nbrRow ; y++) {
            for (unsigned x = 0; x < nbrCol ; x++) {
                Coord pos = {static_cast<int>(x), static_cast<int>(y)};
286
287
288
289
290
291
                newGrid.set_cell(pos, oldGrid.get_state(pos));
                //std::cout << "oldState : " << oldGrid.get_state(pos) << endl;
            }
        }
    }

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

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

    ui->grid_view->set_current_pen(val);
}
304
305
306

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

    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)
        {
318
            unsigned state = rand() % alphabetSize;
319
320
321
322
323
            Coord pos = {static_cast<int>(x), static_cast<int>(y)};
            newGrid.set_cell(pos, state);
        }
    }

324
    ui->grid_view->copy_grid(newGrid);
325
}
326

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

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

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();
354
355
    m_transition_rule = Factory<TransitionRule>::make(selected).release();
    if (!m_transition_rule)
356
357
        return;

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

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

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

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

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

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

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

411
    ui->transition_list->setCurrentText(obj.value("transition_name").toString());
412
    ui->neighborhood_list->setCurrentText(obj.value("neighborhood_name").toString());
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
    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));
        }
    }


444
    update_transition_settings();
445
    update_neighborhood_settings();
446
447
    disable_rule_customization();

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

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

    // 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
467
468
    simulation.setNeighborhoodRule(m_neighborhood_rule);
    simulation.setTransitionRule(m_transition_rule);
469
    simulation.reset();
Yann Boucher's avatar
Yann Boucher committed
470
    ui_update_alphabet(alpha);
471
472

    m_loaded_model = obj;
473
474
475
}

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

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

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

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

    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();
498
499
500
501
    root["transition_data"] = trans_saver.save();

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

    QJsonArray alphabet;

505
506
507
508
509
510
511
512
513
514
515
516
517
    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);
    }

518
519
520
521
    root["alphabet"] = alphabet;

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

    ui->rule_name->setText(dialog.titre());
    disable_rule_customization();
532
533

    load_model(root);
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
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()
{
559
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"",tr("Image (*.png *.jpg *.jpeg *.bmp *.gif)"));
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    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);
}

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

590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
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();
608
    unsigned boundary_policy = data.value("boundary_policy").toInt(0);
609
610
611
612
613
    if (model.isEmpty() || config.isEmpty())
        return false;

    load_model(model);
    load_grid_configuration(config);
614
    load_boundary_policy(boundary_policy);
615
616

    return true;
617
618
}

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

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

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

    QJsonObject json_data;
632
633
634
635
636
637
638
639
    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);

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

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

    QJsonDocument doc(json_data);
    file.write(doc.toJson());
    file.close();
654
655
}

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

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

667
668
669
670
    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());
671
672
    simulation.reset();
    simulation.setGrid(g);
673
674
}

675
676
QJsonObject MainWindow::default_model() const
{
677
678
679
    const char* json = R"(
    {
        "title" : "Game of Life",
680
681
        "neighborhood_name" : "Moore",
        "neighborhood_data" : {},
682
683
684
685
686
687
688
689
690
        "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));
691

692
    return doc.object();
693
694
}

695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
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();
}

714
715
716
717
718
void MainWindow::play_bad_apple()
{
    static QJsonArray bad_apple_frame_list;
    static QTimer bad_apple_timer;
    static bool bad_apple_connected;
719
720
721
#ifdef BAD_APPLE_AUDIO
    static QMediaPlayer bad_apple_player;
#else
722
    static QElapsedTimer bad_apple_elapsed;
723
#endif
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
741
742
    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();

    if (!bad_apple_connected)
    {
        bad_apple_timer.callOnTimeout([this]
Yann Boucher's avatar
Snake !  
Yann Boucher committed
743
                                      {
744
#ifdef BAD_APPLE_AUDIO
Yann Boucher's avatar
Snake !  
Yann Boucher committed
745
                                          unsigned frame_idx = bad_apple_player.position()/(1000.f/30);
746
#else
Yann Boucher's avatar
Snake !  
Yann Boucher committed
747
                                          unsigned frame_idx = bad_apple_elapsed.elapsed()/(1000.f/30);
748
#endif
Yann Boucher's avatar
Snake !  
Yann Boucher committed
749
750
751
752
753
                                          if ((int)frame_idx >= bad_apple_frame_list.size())
                                          {
                                              bad_apple_timer.stop();
                                              return;
                                          }
754

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

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

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

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

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

Yann Boucher's avatar
Snake !  
Yann Boucher committed
772
773
                                          ui->grid_view->copy_grid(grid);
                                      });
774
775
776
777
778
779
    };

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

782
783
784
#ifdef BAD_APPLE_AUDIO
    bad_apple_player.setMedia(QUrl::fromLocalFile("extras/bad-apple.wav"));
    bad_apple_player.play();
785
#else
786
787
    QMessageBox::information(this, "", "Music functionnality is only available with Qt 5");
    bad_apple_elapsed.start();
788
789
#endif

790
    bad_apple_timer.start(11);
791
792
793
    statusBar()->showMessage("Original : \"Bad Apple!!\" feat. Nomico by Alstroemeria Records", 60000);
}

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

    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

814
815
    QWidget::grabKeyboard();

Yann Boucher's avatar
Snake !  
Yann Boucher committed
816
817
818
    static auto restore = [&]
    {
        ui_update_alphabet(simulation.getAlphabet());
819
        QWidget::releaseKeyboard();
Yann Boucher's avatar
Snake !  
Yann Boucher committed
820
821
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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
        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();
    }

    if (!snake_connected)
    {
        snake_timer.callOnTimeout([this]
                                  {
                                      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);
                                  });
        snake_connected = true;
    }
    snake_timer.start(100);
}

915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
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;
939
    save_data["boundary_policy"] = ui->border_combo->currentIndex();
940
941
942
943
944
945
946
947
948
949
950
951
952
953

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

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

980
981
982
983
984
985
986
void MainWindow::on_saveRuleButton_clicked()
{
    save_model();
}

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

998
999
1000

void MainWindow::on_savePatternButton_clicked()
{
1001
    save_grid_configuration();
1002
}
Anthony Noir's avatar
Anthony Noir committed
1003
1004
1005
1006
1007
1008

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

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

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

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

void MainWindow::on_recordSpinBox_valueChanged(int newSize) {
    simulation.setHistorySize(newSize);
}
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083

void MainWindow::on_pushButton_clicked()
{
    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)
        {
            unsigned state = 0;
            Coord pos = {static_cast<int>(x), static_cast<int>(y)};
            newGrid.set_cell(pos, state);
        }
    }

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

1084
1085
1086
1087
1088
1089
1090
1091
1092
1093

void MainWindow::on_simSpeedSlider_sliderMoved(int position)
{
    int frequence = position;
    if (frequence == 0)
        return;

    timer->setInterval(1000/frequence);
}

1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110

void MainWindow::load_boundary_policy(int index)
{
    switch (index)
    {
        default:
        case 0:
            simulation.set_boundary_policy(BoundaryPolicy::Periodic);
            break;
        case 1:
            simulation.set_boundary_policy(BoundaryPolicy::Inert);
            break;
    }

    if (index >= 0 && index < ui->border_combo->count())
        ui->border_combo->setCurrentIndex(index);
}