From c348019bf5f73ac5bcc5a5f6b3af9ab0c9df4eeb Mon Sep 17 00:00:00 2001 From: PTyTb Date: Thu, 29 Jan 2026 14:50:57 +0300 Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=BE=D1=87=D0=B8=D0=BD=D0=B8=D0=BB=20?= =?UTF-8?q?=D1=86=D0=B2=D0=B5=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fcreatechat.cpp | 219 +++++++++++++++++++++++++++++++++++++++------- fcreatechat.h | 1 + webserverchat.cpp | 117 +++++++++++-------------- 3 files changed, 243 insertions(+), 94 deletions(-) diff --git a/fcreatechat.cpp b/fcreatechat.cpp index 0190396..62188cb 100644 --- a/fcreatechat.cpp +++ b/fcreatechat.cpp @@ -69,17 +69,78 @@ void FCreateChat::loadExistingServer(HttpServerChat *server, const QString &name FColorSetting *colorSetting = ui->wBlock; if (colorSetting) { - QString backgroundColor = colorSetting->hexToColorName(server->getBackgroundColor()); - colorSetting->cbBackgroundColor->setCurrentText(backgroundColor); + 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; + } + } + } - QString blockColor = colorSetting->hexToColorName(server->getBlockColor()); - colorSetting->cbBlockColor->setCurrentText(blockColor); + 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"); - QString borderColor = colorSetting->hexToColorName(server->getBorderColor()); - colorSetting->cbBorderColor->setCurrentText(borderColor); + 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()); @@ -88,13 +149,39 @@ void FCreateChat::loadExistingServer(HttpServerChat *server, const QString &name FFontSetting *fontSetting = ui->wFont; if (fontSetting) { - QString fontFamily = colorSetting->hexToColorName(server->getFontFamily()); - fontSetting->cbFontStyle->setCurrentText(fontFamily); + // Загрузка шрифта + 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 fontColor = colorSetting->hexToColorName(server->getFontColor()); - fontSetting->cbFontColor->setCurrentText(fontColor); + // Загрузка цвета шрифта + 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()); + } } } @@ -133,40 +220,112 @@ void FCreateChat::createServer() QString backgroundColor = "#89F336"; // По умолчанию черный if (colorSetting && colorSetting->cbBackgroundColor) { - QColor bgColor = colorSetting->cbBackgroundColor->currentData().value(); - if (!bgColor.isValid()) { - bgColor = QColor(colorSetting->cbBackgroundColor->currentText()); + 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(); + } } - backgroundColor = bgColor.name(); } - // Создаем сервер с полученными настройками m_chatServer = new HttpServerChat(fontList, port, backgroundColor, nullptr); // Запускаем сервер - if (!m_chatServer->start()) { - QMessageBox::warning(this, "Ошибка", - QString("Не удалось запустить сервер чата на порту %1").arg(port)); - } else { + // Применяем остальные настройки сразу + 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 || !m_isEditMode) { - // Если нет сервера или это не режим редактирования, создаем временный - if (m_chatServer && !m_isEditMode) { - m_chatServer->stop(); - delete m_chatServer; - } + // Если сервер не создан, создаем временный + if (!m_chatServer) { createServer(); + if (!m_chatServer) { + QMessageBox::warning(this, "Ошибка", "Не удалось создать сервер для теста"); + return; + } } - if (!m_chatServer) { - QMessageBox::warning(this, "Ошибка", "Не удалось создать сервер"); - return; - } + // Применяем текущие настройки к серверу + applyCurrentSettingsToServer(); // Создаем тестовое сообщение createTestMessage(true); diff --git a/fcreatechat.h b/fcreatechat.h index ce89fa8..429d6ce 100644 --- a/fcreatechat.h +++ b/fcreatechat.h @@ -34,6 +34,7 @@ private: bool m_isEditMode; QString m_existingServerName; void createServer(); + void applyCurrentSettingsToServer(); void createTestMessage(bool isTest = false); }; diff --git a/webserverchat.cpp b/webserverchat.cpp index 9037e60..a20100e 100644 --- a/webserverchat.cpp +++ b/webserverchat.cpp @@ -295,6 +295,8 @@ QString HttpServerChat::generateHTML() " opacity: 1;\n" " max-width: 100%;\n" " word-wrap: break-word;\n" + " padding: 5px 10px;\n" + " box-sizing: border-box;\n" "}\n" ".message-icon { \n" " width: 1.5em; \n" @@ -308,31 +310,23 @@ QString HttpServerChat::generateHTML() "let fetching = false;\n" "const deleteByTime = %3;\n" "\n" - "function hexToRgb(hex) {\n" - " console.log('hexToRgb input:', hex);\n" - " \n" - " // Создаем временный canvas элемент для парсинга цвета\n" - " const ctx = document.createElement('canvas').getContext('2d');\n" - " ctx.fillStyle = hex;\n" - " const color = ctx.fillStyle;\n" - " \n" - " // Если цвет не распознан, используем значение по умолчанию\n" - " if (!color || color === 'rgba(0, 0, 0, 0)') {\n" - " console.log('Color not recognized, using default');\n" - " return '74, 175, 80'; // #4CAF50\n" - " }\n" - " \n" - " // Парсим цвет в формате rgb(r, g, b)\n" - " const match = color.match(/rgb\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)/);\n" - " \n" - " if (match) {\n" - " console.log('Parsed RGB:', match[1], match[2], match[3]);\n" - " return `${match[1]}, ${match[2]}, ${match[3]}`;\n" - " }\n" - " \n" - " console.log('Failed to parse, using default');\n" - " return '74, 175, 80'; // #4CAF50\n" - "}\n" + "function hexToRgba(hex, alpha) {\n" + " // Убираем # если есть\n" + " hex = hex.replace('#', '');\n" + " \n" + " // Расширяем короткую форму (#RGB -> #RRGGBB)\n" + " if (hex.length === 3) {\n" + " hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];\n" + " }\n" + " \n" + " // Конвертируем HEX в RGB\n" + " const r = parseInt(hex.substring(0, 2), 16);\n" + " const g = parseInt(hex.substring(2, 4), 16);\n" + " const b = parseInt(hex.substring(4, 6), 16);\n" + " \n" + " // Возвращаем RGBA строку\n" + " return `rgba(${r}, ${g}, ${b}, ${alpha})`;\n" + "}\n" "\n" "function fetchMessages() {\n" " if (fetching) return;\n" @@ -351,10 +345,8 @@ QString HttpServerChat::generateHTML() " });\n" " \n" " // 2. УДАЛЯЕМ ТОЛЬКО ТЕ СООБЩЕНИЯ, КОТОРЫХ НЕТ В НОВЫХ ДАННЫХ\n" - " // И КОТОРЫЕ НЕ ЗАМОРОЖЕНЫ\n" " existingMessages.forEach((div, msgId) => {\n" " if (!newIds.has(msgId)) {\n" - " // Проверяем, заморожено ли сообщение\n" " const isFreez = div.getAttribute('data-freez') === 'true';\n" " if (!isFreez) {\n" " div.style.opacity = '0';\n" @@ -378,37 +370,36 @@ QString HttpServerChat::generateHTML() " div.id = msgId;\n" " div.setAttribute('data-freez', msg.freez ? 'true' : 'false');\n" " \n" - " // ПРИМЕНЯЕМ СТИЛИ\n" -" function hexToRgb(hex) {\n" -" console.log('hexToRgb input:', hex);\n" -" if (!hex || !hex.startsWith('#')) {\n" -" console.log('Not a hex color, using default');\n" -" return '74, 175, 80'; // #4CAF50\n" -" }\n" -" // Убираем # и проверяем длину\n" -" let cleanHex = hex.substring(1);\n" -" // Убираем альфа-канал если есть\n" -" if (cleanHex.length === 8) {\n" -" cleanHex = cleanHex.substring(0, 6);\n" -" }\n" -" // Расширяем короткую форму (#rgb → #rrggbb)\n" -" if (cleanHex.length === 3) {\n" -" cleanHex = cleanHex[0] + cleanHex[0] + \n" -" cleanHex[1] + cleanHex[1] + \n" -" cleanHex[2] + cleanHex[2];\n" -" }\n" -" // Проверяем, что строка состоит из шестнадцатеричных символов\n" -" if (cleanHex.length !== 6 || !/^[0-9A-Fa-f]{6}$/.test(cleanHex)) {\n" -" console.log('Invalid hex format, using default');\n" -" return '74, 175, 80'; // #4CAF50\n" -" }\n" -" // Конвертируем HEX в RGB\n" -" const r = parseInt(cleanHex.substring(0, 2), 16);\n" -" const g = parseInt(cleanHex.substring(2, 4), 16);\n" -" const b = parseInt(cleanHex.substring(4, 6), 16);\n" -" console.log('Parsed RGB:', r, g, b);\n" -" return `${r}, ${g}, ${b}`;\n" -" }\n" + " // ПРИМЕНЯЕМ СТИЛИ С ПРОЗРАЧНОСТЬЮ\n" + " const alpha = msg.transparency / 255;\n" + " \n" + " // Цвет фона блока с прозрачностью\n" + " if (msg.color) {\n" + " div.style.backgroundColor = hexToRgba(msg.color, alpha);\n" + " }\n" + " \n" + " // Граница с прозрачностью\n" + " if (msg.borderColor && msg.borderSize > 0) {\n" + " div.style.border = msg.borderSize + 'px solid ' + hexToRgba(msg.borderColor, alpha);\n" + " } else {\n" + " div.style.border = 'none';\n" + " }\n" + " \n" + " // Внутренние отступы\n" + " if (msg.padding > 0) {\n" + " div.style.padding = msg.padding + 'px';\n" + " }\n" + " \n" + " // Шрифт\n" + " if (msg.family) {\n" + " div.style.fontFamily = msg.family;\n" + " }\n" + " if (msg.fontSize > 0) {\n" + " div.style.fontSize = msg.fontSize + 'px';\n" + " }\n" + " if (msg.fontColor) {\n" + " div.style.color = msg.fontColor;\n" + " }\n" " \n" " // ФОРМИРУЕМ СОДЕРЖИМОЕ\n" " let content = '' + msg.nickname + ': ' + msg.content + '';\n" @@ -418,10 +409,8 @@ QString HttpServerChat::generateHTML() " container.appendChild(div);\n" " existingMessages.set(msgId, div);\n" " \n" - " // 4. УСТАНАВЛИВАЕМ ТАЙМЕР УДАЛЕНИЯ ТОЛЬКО ЕСЛИ:\n" - " // - включено удаление по времени (deleteByTime)\n" - " // - сообщение НЕ заморожено (freez = false)\n" - " if (deleteByTime && (!msg.freez || msg.freez === false)) {\n" + " // 4. УСТАНАВЛИВАЕМ ТАЙМЕР УДАЛЕНИЯ\n" + " if (deleteByTime && !msg.freez) {\n" " setTimeout(() => {\n" " if (existingMessages.has(msgId)) {\n" " const messageDiv = existingMessages.get(msgId);\n" @@ -433,14 +422,14 @@ QString HttpServerChat::generateHTML() " existingMessages.delete(msgId);\n" " }, 500);\n" " }\n" - " }, (parseInt(msg.timeMsg) || 10) * 1000);\n" + " }, (msg.timeMsg || 10) * 1000);\n" " }\n" " }\n" " });\n" " \n" " // 5. ОБРАБОТКА РЕЖИМА УДАЛЕНИЯ ПО КОЛИЧЕСТВУ\n" " if (!deleteByTime) {\n" - " const maxMessages = 100;\n" + " const maxMessages = msg.maxCount || 100;\n" " if (existingMessages.size > maxMessages) {\n" " const messagesArray = Array.from(existingMessages.entries());\n" " messagesArray.sort((a, b) => {\n"