-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApplication.cpp
More file actions
213 lines (180 loc) · 8.56 KB
/
Application.cpp
File metadata and controls
213 lines (180 loc) · 8.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#include "Application.h"
#include <iostream>
Application::Application(unsigned width, unsigned height)
: m_window(sf::VideoMode(width, height), "Paint (Non copyright)"),
m_canvas(width, height)
{
m_window.setKeyRepeatEnabled(false);
// Активный инструмент — карандаш
m_activeTool = new PencilTool(&m_canvas);
// Текущий цвет
currentColor = sf::Color::Black;
m_activeTool->setColor(currentColor);
m_thickness = 3.f;
m_activeTool->setThickness(m_thickness);
// Палитра кнопок
m_colorButtons = {
ColorButton({10, 10}, sf::Color::Black),
ColorButton({50, 10}, sf::Color::Red),
ColorButton({90, 10}, sf::Color::Green),
ColorButton({130, 10}, sf::Color::Blue),
ColorButton({170, 10}, sf::Color::Yellow),
ColorButton({210, 10}, sf::Color::Magenta),
ColorButton({250, 10}, sf::Color::Cyan),
ColorButton({290, 10}, sf::Color(255, 165, 0)) // оранжевый
};
for (size_t i = 0; i < m_colorButtons.size(); ++i) {
m_colorButtons[i].setSelected(i == 0);
}
m_toolButtons = {
ToolButton({6, 50}, {35,35}, ToolType::Pencil),
ToolButton({46, 50}, {35,35}, ToolType::Eraser),
ToolButton({86,50}, {35,35}, ToolType::Rect),
ToolButton({126,50}, {35,35}, ToolType::Circle),
ToolButton({166,50}, {35,35}, ToolType::Triangle),
ToolButton({206,50}, {35,35}, ToolType::Fill),
};
m_toolButtons[0].setSelected(true);
createTool(ToolType::Pencil);
m_activeTool->setColor(currentColor);
m_activeTool->setThickness(m_thickness);
}
void Application::run() {
while (m_window.isOpen()) {
processEvents();
render();
}
}
void Application::createTool(ToolType type) { //Фабрика
if (m_activeTool) { delete m_activeTool; m_activeTool = nullptr; }
m_activeType = type;
switch (type) {
case ToolType::Pencil: m_activeTool = new PencilTool(&m_canvas); break;
case ToolType::Eraser: m_activeTool = new EraserTool(&m_canvas); break;
case ToolType::Rect: m_activeTool = new RectangleTool(&m_canvas); break;
case ToolType::Circle: m_activeTool = new CircleTool(&m_canvas); break;
case ToolType::Triangle: m_activeTool = new TriangleTool(&m_canvas); break;
case ToolType::Fill: m_activeTool = new FillTool(&m_canvas); break;
}
// прокидываем общие параметры
if (m_activeTool) {
m_activeTool->setColor(currentColor); // ластик игнорирует
m_activeTool->setThickness(m_thickness);
}
}
void Application::processEvents() {
sf::Event event;
while (m_window.pollEvent(event)) {
// Закрытие окна
if (event.type == sf::Event::Closed)
m_window.close();
// --------------------- МЫШЬ ДВИЖЕТСЯ ---------------------
if (event.type == sf::Event::MouseMoved) {
sf::Vector2f mouse = m_window.mapPixelToCoords({ event.mouseMove.x, event.mouseMove.y });
// hover для цветов/инструментов
for (auto& cb : m_colorButtons) cb.setHovered(cb.isClicked(mouse));
for (auto& tb : m_toolButtons) tb.setHovered(tb.isClicked(mouse));
// событие активному инструменту
if (m_activeTool) m_activeTool->onMouseMoved(mouse);
}
// --------------------- НАЖАТИЕ ЛКМ ---------------------
if (event.type == sf::Event::MouseButtonPressed &&
event.mouseButton.button == sf::Mouse::Left) {
sf::Vector2f mouse = m_window.mapPixelToCoords({ event.mouseButton.x, event.mouseButton.y });
// 1) палитра — выбираем цвет и выходим
for (size_t i = 0; i < m_colorButtons.size(); ++i) {
if (m_colorButtons[i].isClicked(mouse)) {
currentColor = m_colorButtons[i].getColor();
if (m_activeTool) m_activeTool->setColor(currentColor);
// визуальное выделение
m_colorButtons[m_selectedColorIndex].setSelected(false);
m_colorButtons[i].setSelected(true);
m_selectedColorIndex = static_cast<int>(i);
return; // событие обработано UI
}
}
// 2) кнопки инструментов — переключаем и выходим
for (auto& tbtn : m_toolButtons) {
if (tbtn.isClicked(mouse)) {
for (auto& b : m_toolButtons) b.setSelected(false);
tbtn.setSelected(true);
createTool(tbtn.type()); // фабрика
return; // событие обработано UI
}
}
// 3) НЕ UI: это «рисовательное» действие → делаем снапшот ДO изменения
// <<< НОВОЕ ДЕЙСТВИЕ ДЛЯ UNDO >>>
m_history.push(m_canvas.copyToImage());
// 4) отправляем событие активному инструменту
if (m_activeTool) m_activeTool->onMousePressed(mouse, sf::Mouse::Left);
}
// --------------------- ОТПУСКАНИЕ КНОПКИ МЫШИ ---------------------
if (event.type == sf::Event::MouseButtonReleased) {
sf::Vector2f pos = m_window.mapPixelToCoords({ event.mouseButton.x, event.mouseButton.y });
if (m_activeTool) m_activeTool->onMouseReleased(pos, event.mouseButton.button);
}
// --------------------- КЛАВИАТУРА ---------------------
if (event.type == sf::Event::KeyPressed) {
// Ctrl + S — сохранить
if (event.key.control && event.key.code == sf::Keyboard::S) {
auto t = std::time(nullptr);
std::tm tm;
#ifdef _WIN32
localtime_s(&tm, &t);
#else
localtime_r(&t, &tm);
#endif
char buf[64];
std::strftime(buf, sizeof(buf), "save_%Y%m%d_%H%M%S.png", &tm);
if (m_canvas.saveToFile(buf))
std::cout << "Сохранено: saves/" << buf << "\n";
else
std::cout << "Ошибка сохранения!\n";
}
// Ctrl + N — очистка холста (сохраняем снимок перед очисткой)
if (event.key.control && event.key.code == sf::Keyboard::N) {
m_history.push(m_canvas.copyToImage()); // <<< ДЛЯ UNDO
m_canvas.clear(sf::Color::White);
}
// Ctrl + Z — Undo
if (event.key.control && event.key.code == sf::Keyboard::Z && !event.key.shift) {
sf::Image out;
if (m_history.undo(m_canvas.copyToImage(), out)) {
m_canvas.updateFromImage(out);
}
}
// Ctrl + Y или Ctrl + Shift + Z — Redo
if ((event.key.control && event.key.code == sf::Keyboard::Y) ||
(event.key.control && event.key.shift && event.key.code == sf::Keyboard::Z)) {
sf::Image out;
if (m_history.redo(m_canvas.copyToImage(), out)) {
m_canvas.updateFromImage(out);
}
}
// Толщина кисти [ / ]
if (event.key.code == sf::Keyboard::LBracket) {
m_thickness = std::max(1.f, m_thickness - 1.f);
if (m_activeTool) m_activeTool->setThickness(m_thickness);
}
if (event.key.code == sf::Keyboard::RBracket) {
m_thickness = std::min(64.f, m_thickness + 1.f);
if (m_activeTool) m_activeTool->setThickness(m_thickness);
}
}
}
}
void Application::render() {
m_window.clear(sf::Color::White);
// Рисуем холст
m_canvas.displayOn(m_window);
// Рисуем кнопки
for (auto& btn : m_colorButtons) {
btn.draw(m_window);
}
for (auto& btn : m_colorButtons) btn.draw(m_window);
for (auto& tbtn : m_toolButtons) tbtn.draw(m_window);
if (auto* shape = dynamic_cast<RectangleTool*>(m_activeTool)) shape->drawPreview(m_window);
else if (auto* shape = dynamic_cast<CircleTool*>(m_activeTool)) shape->drawPreview(m_window);
else if (auto* shape = dynamic_cast<TriangleTool*>(m_activeTool)) shape->drawPreview(m_window);
m_window.display();
}