#include "fcreatechat.h" #include "ui_fcreatechat.h" #include #include FCreateChat::FCreateChat(QWidget *parent) : QDialog(parent) , m_chatServer(nullptr) , m_StyleChat(nullptr) , ui(new Ui::FCreateChat) , m_isEditMode(false) , m_existingServerName("") { ui->setupUi(this); setWindowTitle("TTW Bot app: Создать чат"); m_StyleChat = nullptr; QStringList fontList; // Создаем сервер чата на порту 7998 (можно сделать настраиваемым) m_chatServer = nullptr; // Подключаем кнопки connect(ui->btnTest, &QPushButton::clicked, this, &FCreateChat::onBtnTestClicked); connect(ui->btnAdd, &QPushButton::clicked, this, &FCreateChat::onBtnAddClicked); } FCreateChat::~FCreateChat() { if (m_StyleChat) { delete m_StyleChat; } delete ui; } void FCreateChat::setEditMode(bool isEditMode) { m_isEditMode = isEditMode; if (isEditMode) { ui->btnAdd->setText("Изменить"); setWindowTitle("TTW Bot app: Редактировать чат"); } else { ui->btnAdd->setText("Создать"); setWindowTitle("TTW Bot app: Создать чат"); } } void FCreateChat::loadExistingServer(HttpServerChat *server, const QString &name) { if (!server) return; m_isEditMode = true; m_chatServer = server; m_existingServerName = name; setEditMode(true); FSettingsWS *settingsWS = ui->widget; if (settingsWS) { settingsWS->sbPort->setValue(server->port()); settingsWS->cbFreez->setChecked(server->isFreez()); settingsWS->sbTime->setValue(server->getMessageTimeout()); settingsWS->sbCount->setValue(server->getMaxMsgCount()); } ui->lineEdit->setText(name); FColorSetting *colorSetting = ui->wBlock; if (colorSetting) { QString backgroundColor = server->getBackgroundColor(); QColor bgColor(backgroundColor); if (!bgColor.isValid()) { // Если не удалось распознать цвет, используем значение по умолчанию bgColor = QColor("#89F336"); } // Ищем индекс цвета в комбобоксе int bgIndex = -1; for (int i = 0; i < colorSetting->cbBackgroundColor->count(); ++i) { QVariant itemData = colorSetting->cbBackgroundColor->itemData(i); if (itemData.canConvert()) { QColor itemColor = itemData.value(); if (itemColor == bgColor || itemColor.name() == bgColor.name()) { bgIndex = i; break; } } } if (bgIndex >= 0) { colorSetting->cbBackgroundColor->setCurrentIndex(bgIndex); } else { // Если цвет не найден, устанавливаем по тексту (резервный вариант) colorSetting->cbBackgroundColor->setCurrentText(bgColor.name()); } // Аналогично для blockColor QString blockColorHex = server->getBlockColor(); QColor blColor(blockColorHex); if (!blColor.isValid()) blColor = QColor("#FFFFFF"); int blIndex = -1; for (int i = 0; i < colorSetting->cbBlockColor->count(); ++i) { QVariant itemData = colorSetting->cbBlockColor->itemData(i); if (itemData.canConvert()) { QColor itemColor = itemData.value(); if (itemColor == blColor || itemColor.name() == blColor.name()) { blIndex = i; break; } } } if (blIndex >= 0) { colorSetting->cbBlockColor->setCurrentIndex(blIndex); } else { colorSetting->cbBlockColor->setCurrentText(blColor.name()); } // Аналогично для borderColor QString borderColorHex = server->getBorderColor(); QColor brColor(borderColorHex); if (!brColor.isValid()) brColor = QColor("#000000"); int brIndex = -1; for (int i = 0; i < colorSetting->cbBorderColor->count(); ++i) { QVariant itemData = colorSetting->cbBorderColor->itemData(i); if (itemData.canConvert()) { QColor itemColor = itemData.value(); if (itemColor == brColor || itemColor.name() == brColor.name()) { brIndex = i; break; } } } if (brIndex >= 0) { colorSetting->cbBorderColor->setCurrentIndex(brIndex); } else { colorSetting->cbBorderColor->setCurrentText(brColor.name()); } colorSetting->sbBorderSize->setValue(server->getBorderSize()); colorSetting->sbPadding->setValue(server->getPadding()); colorSetting->hsBlockTransparant->setValue(server->getTransparency()); } FFontSetting *fontSetting = ui->wFont; if (fontSetting) { // Загрузка шрифта QString fontFamily = server->getFontFamily(); int fontIndex = fontSetting->cbFontStyle->findText(fontFamily); if (fontIndex >= 0) { fontSetting->cbFontStyle->setCurrentIndex(fontIndex); } else { fontSetting->cbFontStyle->setCurrentIndex(0); } fontSetting->sbFontSize->setValue(server->getFontSize()); // Загрузка цвета шрифта QString fontColorHex = server->getFontColor(); QColor fcColor(fontColorHex); if (!fcColor.isValid()) fcColor = QColor("#000000"); int fcIndex = -1; for (int i = 0; i < fontSetting->cbFontColor->count(); ++i) { QVariant itemData = fontSetting->cbFontColor->itemData(i); if (itemData.canConvert()) { QColor itemColor = itemData.value(); if (itemColor == fcColor || itemColor.name() == fcColor.name()) { fcIndex = i; break; } } } if (fcIndex >= 0) { fontSetting->cbFontColor->setCurrentIndex(fcIndex); } else { fontSetting->cbFontColor->setCurrentText(fcColor.name()); } } } void FCreateChat::createServer() { if (m_chatServer) { m_chatServer->stop(); delete m_chatServer; m_chatServer = nullptr; } // Получаем настройки из формы FSettingsWS *settingsWS = ui->widget; if (!settingsWS) { QMessageBox::warning(this, "Ошибка", "Не найдены настройки сервера"); return; } // Получаем порт из настроек int port = settingsWS->sbPort->value(); // Получаем список шрифтов из FFontSetting FFontSetting *fontSetting = ui->wFont; QStringList fontList; if (fontSetting && fontSetting->cbFontStyle) { // Добавляем все шрифты из комбобокса for (int i = 0; i < fontSetting->cbFontStyle->count(); ++i) { fontList.append(fontSetting->cbFontStyle->itemText(i)); } } // Получаем цвет фона из FColorSetting FColorSetting *colorSetting = ui->wBlock; QString backgroundColor = "#89F336"; // По умолчанию черный if (colorSetting && colorSetting->cbBackgroundColor) { QVariant bgData = colorSetting->cbBackgroundColor->currentData(); if (bgData.canConvert()) { QColor bgColor = bgData.value(); backgroundColor = bgColor.name(); } else { // Резервный вариант QColor bgColor(colorSetting->cbBackgroundColor->currentText()); if (bgColor.isValid()) { backgroundColor = bgColor.name(); } } } // Создаем сервер с полученными настройками m_chatServer = new HttpServerChat(fontList, port, backgroundColor, nullptr); // Запускаем сервер // Применяем остальные настройки сразу if (m_chatServer) { applyCurrentSettingsToServer(); if (!m_chatServer->start()) { QMessageBox::warning(this, "Ошибка", QString("Не удалось запустить сервер чата на порту %1").arg(port)); delete m_chatServer; m_chatServer = nullptr; } } } void FCreateChat::applyCurrentSettingsToServer() { if (!m_chatServer) return; FColorSetting *colorSetting = ui->wBlock; FFontSetting *fontSetting = ui->wFont; FSettingsWS *settingsWS = ui->widget; if (!colorSetting || !fontSetting || !settingsWS) return; // Применяем цвета QColor bgColor; QVariant bgData = colorSetting->cbBackgroundColor->currentData(); if (bgData.canConvert()) { bgColor = bgData.value(); } else { bgColor = QColor(colorSetting->cbBackgroundColor->currentText()); } m_chatServer->changeBackground(bgColor.isValid() ? bgColor.name() : "#89F336"); // Цвет блока QColor blockColor; QVariant blockData = colorSetting->cbBlockColor->currentData(); if (blockData.canConvert()) { blockColor = blockData.value(); m_chatServer->setBlockColor(blockColor.name()); } else { m_chatServer->setBlockColor(colorSetting->cbBlockColor->currentText()); } // Цвет границы QColor borderColor; QVariant borderData = colorSetting->cbBorderColor->currentData(); if (borderData.canConvert()) { borderColor = borderData.value(); m_chatServer->setBorderColor(borderColor.name()); } else { m_chatServer->setBorderColor(colorSetting->cbBorderColor->currentText()); } m_chatServer->setBorderSize(colorSetting->sbBorderSize->value()); m_chatServer->setPadding(colorSetting->sbPadding->value()); m_chatServer->setTransparency(colorSetting->hsBlockTransparant->value()); // Настройки шрифта m_chatServer->setFontFamily(fontSetting->cbFontStyle->currentText()); m_chatServer->setFontSize(fontSetting->sbFontSize->value()); QColor fontColor; QVariant fontData = fontSetting->cbFontColor->currentData(); if (fontData.canConvert()) { fontColor = fontData.value(); m_chatServer->setFontColor(fontColor.name()); } else { m_chatServer->setFontColor(fontSetting->cbFontColor->currentText()); } // Настройки сервера bool freez = settingsWS->cbFreez->isChecked(); m_chatServer->setFreez(freez); m_chatServer->setDeleteMode(!freez, settingsWS->sbCount->value()); m_chatServer->setMessageTimeout(settingsWS->sbTime->value()); } void FCreateChat::onBtnTestClicked() { // Если сервер не создан, создаем временный if (!m_chatServer) { createServer(); if (!m_chatServer) { QMessageBox::warning(this, "Ошибка", "Не удалось создать сервер для теста"); return; } } // Применяем текущие настройки к серверу applyCurrentSettingsToServer(); // Создаем тестовое сообщение createTestMessage(true); } void FCreateChat::onBtnAddClicked() { if (m_isEditMode && m_chatServer) { FSettingsWS *settingsWS = ui->widget; FColorSetting *colorSetting = ui->wBlock; FFontSetting *fontSetting = ui->wFont; if (!settingsWS || !colorSetting || !fontSetting) { QMessageBox::warning(this, "Ошибка", "Не найдены настройки сервера"); return; } int newPort = settingsWS->sbPort->value(); bool portChanged = (newPort != m_chatServer->port()); if (portChanged) { m_chatServer->stop(); delete m_chatServer; m_chatServer = nullptr; createServer(); } if (!m_chatServer) { QMessageBox::warning(this, "Ошибка", "Не удалось обновить сервер"); return; } // Применяем все настройки QColor bgColor = colorSetting->cbBackgroundColor->currentData().value(); if (!bgColor.isValid()) { bgColor = QColor(colorSetting->cbBackgroundColor->currentText()); } m_chatServer->changeBackground(bgColor.name()); m_chatServer->setBlockColor(colorSetting->cbBlockColor->currentText()); m_chatServer->setBorderColor(colorSetting->cbBorderColor->currentText()); m_chatServer->setBorderSize(colorSetting->sbBorderSize->value()); m_chatServer->setPadding(colorSetting->sbPadding->value()); m_chatServer->setTransparency(colorSetting->hsBlockTransparant->value()); m_chatServer->setFontFamily(fontSetting->cbFontStyle->currentText()); m_chatServer->setFontSize(fontSetting->sbFontSize->value()); m_chatServer->setFontColor(fontSetting->cbFontColor->currentText()); bool freez = settingsWS->cbFreez->isChecked(); m_chatServer->setFreez(freez); // Удаление по времени = НЕ freez bool deleteByTime = !freez; int maxCount = settingsWS->sbCount->value(); m_chatServer->setDeleteMode(deleteByTime, maxCount); m_chatServer->setMessageTimeout(settingsWS->sbTime->value()); QString newName = ui->lineEdit->text(); if (newName.isEmpty()) { newName = QString("Чат сервер (порт %1)").arg(m_chatServer->port()); } emit serverUpdated(m_chatServer, newName); accept(); } else { // Режим создания createServer(); if (!m_chatServer) { QMessageBox::warning(this, "Ошибка", "Не удалось создать сервер"); return; } createTestMessage(false); QString name = ui->lineEdit->text(); if (name.isEmpty()) { name = QString("Чат сервер (порт %1)").arg(m_chatServer->port()); } emit serverCreated(m_chatServer, name); m_chatServer = nullptr; accept(); } } void FCreateChat::createTestMessage(bool isTest) { if (!m_chatServer) { QMessageBox::warning(this, "Ошибка", "Сервер чата не запущен"); return; } StyleChat style; // Получаем настройки из виджетов // 1. Получаем настройки цвета блока из FColorSetting FColorSetting *colorSetting = ui->wBlock; if (colorSetting) { QColor blockColor = colorSetting->cbBlockColor->currentData().value(); if (!blockColor.isValid()) { blockColor = QColor(colorSetting->cbBlockColor->currentText()); } style.blockColor = blockColor.name(); QColor borderColor = colorSetting->cbBorderColor->currentData().value(); if (!borderColor.isValid()) { borderColor = QColor(colorSetting->cbBorderColor->currentText()); } style.borderColor = borderColor.name(); style.borderSize = colorSetting->sbBorderSize->value(); style.padding = colorSetting->sbPadding->value(); // Прозрачность style.transparency = colorSetting->hsBlockTransparant->value(); // Цвет фона страницы QColor pageBackgroundColor = colorSetting->cbBackgroundColor->currentData().value(); if (!pageBackgroundColor.isValid()) { pageBackgroundColor = QColor(colorSetting->cbBackgroundColor->currentText()); } style.bColor = pageBackgroundColor.name(); // Обновляем цвет фона в сервере m_chatServer->changeBackground(style.bColor); } // 2. Получаем настройки шрифта из FFontSetting FFontSetting *fontSetting = ui->wFont; if (fontSetting) { style.fontFamily = fontSetting->cbFontStyle->currentText(); style.fontSize = fontSetting->sbFontSize->value(); QColor fontColor = fontSetting->cbFontColor->currentData().value(); if (!fontColor.isValid()) { fontColor = QColor(fontSetting->cbFontColor->currentText()); } style.fontColor = fontColor.name(); } // 3. Получаем настройки из FSettingsWS FSettingsWS *settingsWS = ui->widget; if (settingsWS) { // Используем sbTime как время отображения сообщения style.timeMsg = settingsWS->sbTime->value(); // Получаем состояние чекбокса "Вечно" (freez) style.freez = settingsWS->cbFreez->isChecked(); // Настраиваем режим удаления bool deleteByTime = !settingsWS->cbFreez->isChecked(); // Если "Вечно" выбрано, то НЕ удаляем по времени int maxCount = settingsWS->sbCount->value(); m_chatServer->setDeleteMode(deleteByTime, maxCount); } // Заполняем тестовые данные style.nick = isTest ? "Тестовый пользователь" : "Пользователь"; style.context = ui->lineEdit->text().isEmpty() ? (isTest ? "Это тестовое сообщение!" : "Новое сообщение") : ui->lineEdit->text(); // Добавляем сообщение в сервер m_chatServer->addMessage(style); // Очищаем поле ввода, если это не тест if (!isTest) { ui->lineEdit->clear(); } }