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

4
#include "savingdialog.hpp"
5
#include "structurewriter.hpp"
6
7
8
9
#include "factory.hpp"
#include "transitionrule.hpp"
#include "neighborhoodrule.hpp"
#include "propertyvisitors.hpp"
10
#include "modelloadingdialog.hpp"
11
#include "neighborhoodWidget.hpp"
12

13
#include <QJsonArray>
Merwane Bouri's avatar
Merwane Bouri committed
14
15
#include <QDate>
#include <QTextStream>
16

17
18
19
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
      , ui(new Ui::MainWindow)
20
21
      , simulation(),
      m_customizing(false)
22
23
{
    ui->setupUi(this);
24

25
26
27
    m_transition_rule = nullptr;
    m_neighborhood_rule = nullptr;

28
29
    init_transition_neighborhood_list();
    update_transition_settings();
30
    update_neighborhood_settings();
31

32
    connect(ui->action_save_struct, &QAction::triggered, this, &MainWindow::afficher_interface_sauvegarde_structure);
33
    connect(ui->struct_library, &StructureLibraryView::structure_copied, this, &MainWindow::copy_structure_clicked);
34
    connect(ui->grid_view, &GridView::zoom_changed, ui->struct_library, &StructureLibraryView::update_cell_pixel_size);
35
36
    connect(ui->transition_list, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int)
            { update_transition_settings(); });
37
38
39
40
41
42
43
44
45
46
    connect(ui->action_propos_de_Cellulut, &QAction::triggered, this, [this](bool)
            {
                QMessageBox::about(this, "À propos de Cellulut",
                                   "Projet de C++ réalisé dans le cadre de l'UV LO21 de l'UTC.\n\n"
                                   "Contributeurs : Anthony Noir, Eugène Pin, Merwane Bouri, Arthur Detree, Yann Boucher");
            });
    connect(ui->action_propos_de_Qt, &QAction::triggered, this, [this](bool)
            {
                QMessageBox::aboutQt(this, "À propos de Qt");
            });
47
48
49
50
    connect(ui->actionCharger_depuis_une_image, &QAction::triggered, this, [this](bool)
            {
                load_from_image();
            });
51

52
    ui->struct_library->update_cell_pixel_size(ui->grid_view->cell_screen_size());
53
54

    load_model(default_model());
55
56
57
58
59
}

MainWindow::~MainWindow()
{
    delete ui;
60
    // 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
61
62
}

63
64
/// Connections

65
66
67
68
69
70
71
72
73
void MainWindow::on_simSpeedSpinbox_valueChanged(int arg1)
{
    ui->simSpeedSlider->setValue(arg1);
}

void MainWindow::on_simSpeedSlider_valueChanged(int value)
{
    ui->simSpeedSpinbox->setValue(value);
}
74
75
76

void MainWindow::on_openPatternButton_clicked()
{
77
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"",tr("Pattern file (*.json)"));
78
79
    if(fileName == ""){
        // L'utilisateur a annulé la recherche
80
        return;
81
82
83
84
85
86
87
    }
    // Indiquer qu'un nouveau pattern vient d'être ouvert
}

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
88
89
90
91
92
93

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

    load_model(dialog.model());
94
95
}

96
void MainWindow::on_neighborhood_list_currentTextChanged(const QString &)
97
{
98
    update_neighborhood_settings();
99
100
}

101
void MainWindow::on_widthSpinBox_valueChanged(int)
102
103
104
105
{
    ui->validateGridDim->setEnabled(true);
}

106
void MainWindow::on_heightSpinBox_valueChanged(int)
107
108
109
110
{
    ui->validateGridDim->setEnabled(true);
}

111
void MainWindow::afficher_interface_sauvegarde_structure()
112
{
113
    SavingDialog dialog(this);
114
115
116
117
118
    if (!dialog.exec())
        return;

    QString filename = QFileDialog::getSaveFileName(this, "Choisir un nom de fichier", QString(), "Format Cellulut (*.json);;Format Golly RLE (*.rle)");
    QFileInfo info(filename);
119
    //printf("%s\n", info.suffix().toStdString().c_str());
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
    // 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))
    {
        QMessageBox::information(this, "Impossible de créer le fichier",
                                 file.errorString());
        return;
    }

    QTextStream stream(&file);
    stream << QString::fromStdString(save_data);
150
151
}

152

153
154
void MainWindow::on_validateGridDim_clicked()
{
155
156
    Grid oldGrid = ui->grid_view->get_grid();

157

158
159
160
    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);
161

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    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
    {
178
179
        //std::cout << "superieur\n";
        fflush(stdout);
180
181
182
        for (unsigned y = 0; y < nbrRow ; y++) {
            for (unsigned x = 0; x < nbrCol ; x++) {
                Coord pos = {static_cast<int>(x), static_cast<int>(y)};
183
184
185
186
187
188
                newGrid.set_cell(pos, oldGrid.get_state(pos));
                //std::cout << "oldState : " << oldGrid.get_state(pos) << endl;
            }
        }
    }

189
    ui->grid_view->copy_grid(newGrid);
190

191
192
    ui->validateGridDim->setEnabled(false);
}
193
194
195
196
197
198
199

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

    ui->grid_view->set_current_pen(val);
}
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

void MainWindow::on_randomPatternButton_clicked()
{
    // TODO Prendre en compte l'alphabet !
    // int nbr = rand() % nbr de states différents;

    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)
        {
            // TODO Remplacer 2 par le nbr d'états différents
            // TODO comprendre pourquoi il faut inverser x et y (???)
            unsigned state = rand() % 2;
            Coord pos = {static_cast<int>(x), static_cast<int>(y)};
219
            //std::cout << "position x= "<< pos.x << " y= "<< pos.y << endl;
220
221
222
223
            newGrid.set_cell(pos, state);
        }
    }

224
    ui->grid_view->copy_grid(newGrid);
225
}
226
227
228

void MainWindow::on_nbrStatesComboBox_currentTextChanged(const QString &arg1)
{
229
230
    // A mettre dans la fonction valider
    /*
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    // Nombre d'états possibles
    int val = arg1.toInt();
    // Nombre de valeurs dans le comboxBox (en partant de 0)
    int currentNbrValue = ui->nbrStateComboBox->count();
    // Si on change le nbr d'états
    if (val != currentNbrValue) {
        // Si on ajoute des états
        if (val > currentNbrValue) {
            for(int i = currentNbrValue; i < val; i++ ) {
                ui->nbrStateComboBox->addItem(QString::number(i));
            }
        }
        // Si on retire des états
        else {
            for(int i = currentNbrValue - 1; i >= val; i-- ) {
                ui->nbrStateComboBox->removeItem(i);
            }
        }
    }
250
    */
251
}
252

253
254
255
256
257
void MainWindow::on_drawCellButton_clicked()
{
    ui->grid_view->fill_selection(ui->nbrStateComboBox->currentIndex());
}

258
259
260
261
262
void MainWindow::copy_structure_clicked(const Structure &s)
{
    ui->grid_view->set_clipboard(s);
    statusBar()->showMessage("Structure copied.", 5000);
}
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279

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();
280
281
    m_transition_rule = Factory<TransitionRule>::make(selected).release();
    if (!m_transition_rule)
282
283
        return;

284
    if (m_transition_rule->get_properties().size() == 0)
285
286
287
288
289
290
        ui->rule_settings_area->hide();
    else
    {
        ui->rule_settings_area->show();

        UIBuilderVisitor visit(ui->rule_settings_area);
291
        for (auto& prop : m_transition_rule->get_properties())
292
293
            prop->accept(visit);
    }
294
}
295
296
297
void MainWindow::update_neighborhood_settings()
{
    std::string selected = ui->neighborhood_list->currentText().toStdString();
298
299
    m_neighborhood_rule = Factory<NeighborhoodRule>::make(selected).release();
    if (!m_neighborhood_rule)
300
301
        return;

302
    if (m_neighborhood_rule->get_properties().size() == 0)
303
304
305
306
307
308
        ui->neighborhood_settings_area->hide();
    else
    {
        ui->neighborhood_settings_area->show();

        UIBuilderVisitor visit(ui->neighborhood_settings_area);
309
        for (auto& prop : m_neighborhood_rule->get_properties())
310
311
312
            prop->accept(visit);
    }
}
313

314
315
316
void MainWindow::enable_rule_customization()
{
    ui->simulation_tab->setEnabled(false);
317
    ui->customize_button->setText("Cancel customization");
318
    ui->rule_settings->setEnabled(true);
319
    m_customizing = true;
320
321
}

322
323
324
325
326
void MainWindow::disable_rule_customization()
{
    ui->simulation_tab->setEnabled(true);
    ui->customize_button->setEnabled(true);
    ui->rule_settings->setEnabled(false);
327
328
    ui->customize_button->setText("Customize...");
    m_customizing = false;
329
330
331
332
333
}

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

335
    ui->transition_list->setCurrentText(obj.value("transition_name").toString());
336
    ui->neighborhood_list->setCurrentText(obj.value("neighborhood_name").toString());
337

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    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));
        }
    }


368
    update_transition_settings();
369
    update_neighborhood_settings();
370
371
    disable_rule_customization();

372
373
    {
        PropertyLoaderVisitor loader(obj.value("transition_data").toObject());
374
        for (auto& prop : m_transition_rule->get_properties())
375
376
            prop->accept(loader);
        UIBuilderVisitor visit(ui->rule_settings_area);
377
        for (auto& prop : m_transition_rule->get_properties())
378
379
380
381
382
            prop->accept(visit);
    }

    {
        PropertyLoaderVisitor loader(obj.value("neighborhood_data").toObject());
383
        for (auto& prop : m_neighborhood_rule->get_properties())
384
385
            prop->accept(loader);
        UIBuilderVisitor visit(ui->neighborhood_settings_area);
386
        for (auto& prop : m_neighborhood_rule->get_properties())
387
388
            prop->accept(visit);
    }
389

390
391
    ui_update_alphabet(alpha);

392
    // 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
393
394
    simulation.setNeighborhoodRule(m_neighborhood_rule);
    simulation.setTransitionRule(m_transition_rule);
395
396
397
    simulation.setAlphabet(alpha);

    m_loaded_model = obj;
398
399
400
}

void MainWindow::save_model()
401
402
403
404
405
406
407
{
    SavingDialog dialog(this);
    if (!dialog.exec())
        return;

    QString filename = QFileDialog::getSaveFileName(this, "Choisir un nom de fichier", QString(), "Modèle d'automate (*.json)");

408
    PropertySaverVisitor trans_saver;
409
    for (auto& prop : m_transition_rule->get_properties())
410
411
412
        prop->accept(trans_saver);

    PropertySaverVisitor neighborhood_saver;
413
    for (auto& prop : m_neighborhood_rule->get_properties())
414
        prop->accept(neighborhood_saver);
415
416
417
418
419
420
421
422

    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();
423
424
425
426
    root["transition_data"] = trans_saver.save();

    root["neighborhood_name"] = ui->neighborhood_list->currentText();
    root["neighborhood_data"] = neighborhood_saver.save();
427
428
429

    QJsonArray alphabet;

430
431
432
433
434
435
436
437
438
439
440
441
442
    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);
    }

443
444
445
446
447
448
449
    root["alphabet"] = alphabet;

    QJsonDocument doc(root);
    QFile file(filename);
    file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
    file.write(doc.toJson());
    file.close();
450
451
452

    ui->rule_name->setText(dialog.titre());
    disable_rule_customization();
453
454

    load_model(root);
455
456
}

457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
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()
{
480
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"",tr("Image (*.png *.jpg *.jpeg *.bmp *.gif"));
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
    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);
}

499
500
501
502
503
504
505
506
507
508
void MainWindow::ui_update_alphabet(const Alphabet &alpha)
{
    ui->grid_view->set_alphabet(alpha);
    ui->nbrStateComboBox->clear();
    for (unsigned i = 0; i < alpha.taille(); ++i)
        ui->nbrStateComboBox->addItem(QString::number(i));
    ui->nbrStatesComboBox->clear();
    ui->nbrStatesComboBox->addItem(QString::number(alpha.taille()));
}

509
510
511
512
513
514
515
516
517
518
519
520
void MainWindow::save_grid_configuration()
{
    Structure grid_data = ui->grid_view->get_grid().to_structure();

    QJsonObject json_data;
}

void MainWindow::load_grid_configuration()
{

}

521
522
QJsonObject MainWindow::default_model() const
{
523
524
525
526
527
528
529
530
531
532
533
534
    const char* json = R"(
    {
        "title" : "Game of Life",
        "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));
535

536
    return doc.object();
537
538
539
540
541
542
543
544
545
}

void MainWindow::on_saveRuleButton_clicked()
{
    save_model();
}

void MainWindow::on_customize_button_clicked()
{
546
547
548
549
550
551
552
553
554
    if (!m_customizing)
    {
        enable_rule_customization();
    }
    else
    {
        disable_rule_customization();
        load_model(m_loaded_model);
    }
555
}
556

557
558
559
560
561

void MainWindow::on_savePatternButton_clicked()
{
    afficher_interface_sauvegarde_structure();
}