1/****************************************************************************
2**
3** Copyright (C) 2018 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the examples of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:BSD$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51#include "gameoflifemodel.h"
52#include <QFile>
53#include <QTextStream>
54#include <QRect>
55
56GameOfLifeModel::GameOfLifeModel(QObject *parent)
57 : QAbstractTableModel(parent)
58{
59 clear();
60}
61
62//! [modelsize]
63int GameOfLifeModel::rowCount(const QModelIndex &parent) const
64{
65 if (parent.isValid())
66 return 0;
67
68 return height;
69}
70
71int GameOfLifeModel::columnCount(const QModelIndex &parent) const
72{
73 if (parent.isValid())
74 return 0;
75
76 return width;
77}
78//! [modelsize]
79
80//! [read]
81QVariant GameOfLifeModel::data(const QModelIndex &index, int role) const
82{
83 if (!index.isValid() || role != CellRole)
84 return QVariant();
85
86 return QVariant(m_currentState[cellIndex(coordinates: {index.column(), index.row()})]);
87}
88//! [read]
89
90//! [write]
91bool GameOfLifeModel::setData(const QModelIndex &index, const QVariant &value, int role)
92{
93 if (role != CellRole || data(index, role) == value)
94 return false;
95
96 m_currentState[cellIndex(coordinates: {index.column(), index.row()})] = value.toBool();
97 emit dataChanged(topLeft: index, bottomRight: index, roles: {role});
98
99 return true;
100}
101//! [write]
102
103Qt::ItemFlags GameOfLifeModel::flags(const QModelIndex &index) const
104{
105 if (!index.isValid())
106 return Qt::NoItemFlags;
107
108 return Qt::ItemIsEditable;
109}
110
111//! [update]
112void GameOfLifeModel::nextStep()
113{
114 StateContainer newValues;
115
116 for (std::size_t i = 0; i < size; ++i) {
117 bool currentState = m_currentState[i];
118
119 int cellNeighborsCount = this->cellNeighborsCount(cellCoordinates: cellCoordinatesFromIndex(cellIndex: static_cast<int>(i)));
120
121 newValues[i] = currentState == true
122 ? cellNeighborsCount == 2 || cellNeighborsCount == 3
123 : cellNeighborsCount == 3;
124 }
125
126 m_currentState = std::move(newValues);
127
128 emit dataChanged(topLeft: index(row: 0, column: 0), bottomRight: index(row: height - 1, column: width - 1), roles: {CellRole});
129}
130//! [update]
131
132//! [loader]
133bool GameOfLifeModel::loadFile(const QString &fileName)
134{
135 QFile file(fileName);
136 if (!file.open(flags: QIODevice::ReadOnly))
137 return false;
138
139 QTextStream in(&file);
140 loadPattern(plainText: in.readAll());
141
142 return true;
143}
144
145void GameOfLifeModel::loadPattern(const QString &plainText)
146{
147 clear();
148
149 QStringList rows = plainText.split(sep: "\n");
150 QSize patternSize(0, rows.count());
151 for (QString row : rows) {
152 if (row.size() > patternSize.width())
153 patternSize.setWidth(row.size());
154 }
155
156 QPoint patternLocation((width - patternSize.width()) / 2, (height - patternSize.height()) / 2);
157
158 for (int y = 0; y < patternSize.height(); ++y) {
159 const QString line = rows[y];
160
161 for (int x = 0; x < line.length(); ++x) {
162 QPoint cellPosition(x + patternLocation.x(), y + patternLocation.y());
163 m_currentState[cellIndex(coordinates: cellPosition)] = line[x] == 'O';
164 }
165 }
166
167 emit dataChanged(topLeft: index(row: 0, column: 0), bottomRight: index(row: height - 1, column: width - 1), roles: {CellRole});
168}
169//! [loader]
170
171void GameOfLifeModel::clear()
172{
173 m_currentState.fill(u: false);
174 emit dataChanged(topLeft: index(row: 0, column: 0), bottomRight: index(row: height - 1, column: width - 1), roles: {CellRole});
175}
176
177int GameOfLifeModel::cellNeighborsCount(const QPoint &cellCoordinates) const
178{
179 int count = 0;
180
181 for (int x = -1; x <= 1; ++x) {
182 for (int y = -1; y <= 1; ++y) {
183 if (x == 0 && y == 0)
184 continue;
185
186 const QPoint neighborPosition { cellCoordinates.x() + x, cellCoordinates.y() + y };
187 if (!areCellCoordinatesValid(coordinates: neighborPosition))
188 continue;
189
190 if (m_currentState[cellIndex(coordinates: neighborPosition)])
191 ++count;
192
193 if (count > 3)
194 return count;
195 }
196 }
197
198 return count;
199}
200
201bool GameOfLifeModel::areCellCoordinatesValid(const QPoint &coordinates)
202{
203 return QRect(0, 0, width, height).contains(p: coordinates);
204}
205
206QPoint GameOfLifeModel::cellCoordinatesFromIndex(int cellIndex)
207{
208 return {cellIndex % width, cellIndex / width};
209}
210
211std::size_t GameOfLifeModel::cellIndex(const QPoint &coordinates)
212{
213 return std::size_t(coordinates.y() * width + coordinates.x());
214}
215

source code of qtdeclarative/examples/quick/tableview/gameoflife/gameoflifemodel.cpp