statuswidget.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. #include "ui_statuswidget.h"
  2. #include "statuswidget.h"
  3. #include "models/patchdownloader.h"
  4. #include "widgets/mainwindow.h"
  5. #include "constants.h"
  6. #include <QDesktopServices>
  7. #include <QUrl>
  8. #include <QDebug>
  9. #include <QMessageBox>
  10. #include <QRandomGenerator>
  11. StatusWidget::StatusWidget(QWidget *parent)
  12. : QWidget(parent)
  13. , ui(new Ui::StatusWidget)
  14. {
  15. ui->setupUi(this);
  16. last_statusbar_update_time_.start();
  17. ui->galadriel_tooltip_example->hide();
  18. connect(ui->weekly_code_widget, &WeeklyCodeWidget::showCompletedTooltip, this, [this](){setToolTipMessage("ЕЖЕНЕДЕЛЬНЫЙ КОД СКОПИРОВАН В БУФЕР ОБМЕНА", E_INFO);});
  19. connect(ui->weekly_code_widget, &WeeklyCodeWidget::showHelpTooltip, this, [this](){setToolTipMessage("КЛИКНИТЕ ПО ЕЖЕНЕДЕЛЬНОМУ КОДУ, ЧТОБЫ СКОПИРОВАТЬ ЕГО", E_INFO);});
  20. connect(ui->weekly_code_widget, &WeeklyCodeWidget::showNoTooltip, this, [this](){unsetToolTipMessage(E_INFO);});
  21. connect(ui->news_list, &NewsListWidget::showHelpToolTip, this, [this](){setToolTipMessage("НАЖМИТЕ НА ЗАГОЛОВОК НОВОСТИ, ЧТОБЫ ОТКРЫТЬ ЕЕ В БРАУЗЕРЕ", E_INFO);});
  22. connect(ui->news_list, &NewsListWidget::showNoToolTip, this, [this](){unsetToolTipMessage(E_INFO);});
  23. connect(ui->server_status_widget, &ServerStatusWidget::showServersTooltip, this, [this](QString message){setToolTipMessage(message, E_INFO);});
  24. connect(ui->server_status_widget, &ServerStatusWidget::showNoTooltip, this, [this](){unsetToolTipMessage(E_INFO);});
  25. connect(&PatchDownloader::instance(), &PatchDownloader::started, this, &StatusWidget::onPatchDownloaderStarted);
  26. connect(&PatchDownloader::instance(), &PatchDownloader::progressChanged, this, &StatusWidget::onPatchDownloaderProgressChanged);
  27. connect(&PatchDownloader::instance(), &PatchDownloader::finished, this, &StatusWidget::onPatchDownloaderFinished);
  28. connect(&PatchInstaller::instance(), &PatchInstaller::started, this, &StatusWidget::onPatchInstallerStarted);
  29. connect(&PatchInstaller::instance(), &PatchInstaller::progressChanged, this, &StatusWidget::onPatchInstallerProgressChanged);
  30. connect(&PatchInstaller::instance(), &PatchInstaller::finished, this, &StatusWidget::onPatchInstallerFinished);
  31. connect(&PatchInstaller::instance(), &PatchInstaller::videosDownloadProgressChanged, this, &StatusWidget::onPatchInstallerVideoProgressChanged);
  32. generateRandomTooltipMessage();
  33. random_tooltip_generator_timer_.setInterval(5 * 1000);
  34. connect(&random_tooltip_generator_timer_, &QTimer::timeout, this, &StatusWidget::generateRandomTooltipMessage);
  35. random_tooltip_generator_timer_.start();
  36. process_completed_tooltip_hide_timer_.setInterval(4 * 1000); // 4 seconds message "Installation completed" will be shown
  37. process_completed_tooltip_hide_timer_.stop();
  38. connect(&process_completed_tooltip_hide_timer_, &QTimer::timeout, this, [this](){unsetToolTipMessage(E_PROCESS); process_completed_tooltip_hide_timer_.stop();});
  39. ui->texts_block_label->setTooltipParentWidget(this);
  40. ui->texts_block_label->setTooltipText("Перевод всех текстовых элементов в игре: названий, квестов, меню и т.д.");
  41. ui->graphics_block_label->setTooltipParentWidget(this);
  42. ui->graphics_block_label->setTooltipText("Переведенные карты локаций и элементы графического интерфейса.");
  43. ui->video_block_label->setTooltipParentWidget(this);
  44. ui->video_block_label->setTooltipText("Переведенные и озвученные видеоролики и кат-сцены.");
  45. ui->audio_block_label->setTooltipParentWidget(this);
  46. ui->audio_block_label->setTooltipText("Переведенные и озвученные реплики персонажей.");
  47. ui->loadscreens_block_label->setTooltipParentWidget(this);
  48. ui->loadscreens_block_label->setTooltipText("Загрузочные экраны от команды Наследия");
  49. }
  50. StatusWidget::~StatusWidget()
  51. {
  52. delete ui;
  53. ui = nullptr;
  54. }
  55. void StatusWidget::updateFontsSizes()
  56. {
  57. ui->game_button->setFont(trajan_11pt);
  58. ui->news_label->setFont(trajan_10pt);
  59. }
  60. void StatusWidget::setToolTipMessage(QString message, StatusWidget::ToolTipState state)
  61. {
  62. if (state == E_RANDOM) {
  63. random_tooltip_generator_timer_.start();
  64. } else {
  65. random_tooltip_generator_timer_.stop();
  66. }
  67. tooltip_messages_[state] = message;
  68. tooltip_state_ = ToolTipState(int(tooltip_state_) | int(state));
  69. QString message_id = message;
  70. if (state == E_PROCESS) {
  71. message_id = "E_PROCESS";
  72. }
  73. if (tooltip_state_ < state * 2) {
  74. if (!tooltip_widgets_.contains(message_id)) {
  75. createTooltipMessageWidget(message_id);
  76. }
  77. tooltip_widgets_[message_id]->setText(message);
  78. fadeBetweenToolTips(message_id);
  79. }
  80. }
  81. void StatusWidget::unsetToolTipMessage(StatusWidget::ToolTipState state)
  82. {
  83. tooltip_state_ = ToolTipState(int(tooltip_state_) & (~int(state)));
  84. ToolTipState showing_state = E_RANDOM;
  85. if (tooltip_state_ & E_INFO) {
  86. showing_state = E_INFO;
  87. } else if (tooltip_state_ & E_ERROR) {
  88. showing_state = E_ERROR;
  89. } else if (tooltip_state_ & E_PROCESS) {
  90. showing_state = E_PROCESS;
  91. }
  92. QString message_id = tooltip_messages_[showing_state];
  93. if (showing_state == E_PROCESS) {
  94. message_id = "E_PROCESS";
  95. }
  96. if (showing_state == E_RANDOM) {
  97. random_tooltip_generator_timer_.start();
  98. } else {
  99. random_tooltip_generator_timer_.stop();
  100. }
  101. if (!tooltip_widgets_.contains(message_id)) {
  102. createTooltipMessageWidget(message_id);
  103. }
  104. tooltip_widgets_[message_id]->setText(tooltip_messages_[showing_state]);
  105. fadeBetweenToolTips(message_id);
  106. }
  107. void StatusWidget::onErrorStatusChanged(AppErrorStatus status)
  108. {
  109. if (status == E_NO_ERRORS) {
  110. init_error_type_message_ = "";
  111. unsetToolTipMessage(E_ERROR);
  112. ui->news_list->updateNewsWidget();
  113. ui->server_status_widget->updateServerStatus();
  114. ui->weekly_code_widget->updateWeeklyCodeWidget();
  115. return;
  116. }
  117. error_timeout_message_ = "Повторная попытка инициализации через 10 секунд";
  118. if (status & E_WRONG_GAME_FOLDER) {
  119. init_error_type_message_ = "Ошибка инициализации: некорректная папка с игрой!\n";
  120. setToolTipMessage(init_error_type_message_ + error_timeout_message_, E_ERROR);
  121. return;
  122. }
  123. if (status & E_DAT_FILES_MISSING) {
  124. init_error_type_message_ = "Ошибка инициализации: отсутствуют файлы данных игры!\n";
  125. setToolTipMessage(init_error_type_message_ + error_timeout_message_, E_ERROR);
  126. return;
  127. }
  128. if (status & E_WRONG_FILE_PERMISSIONS) {
  129. init_error_type_message_ = "Ошибка инициализации: недостаточно прав для изменения файлов данных!\n";
  130. setToolTipMessage(init_error_type_message_ + error_timeout_message_, E_ERROR);
  131. return;
  132. }
  133. if (status & E_CANNOT_ACCESS_DAT_FILES) {
  134. init_error_type_message_ = "Ошибка инициализации: нет доступа к файлам данных!\n";
  135. setToolTipMessage(init_error_type_message_ + error_timeout_message_, E_ERROR);
  136. return;
  137. }
  138. if (status & E_DAT_FILE_INCORRECT) {
  139. init_error_type_message_ = "Ошибка инициализации: формат файла данных устарел или некорректен!\n";
  140. setToolTipMessage(init_error_type_message_ + error_timeout_message_, E_ERROR);
  141. return;
  142. }
  143. if (status & E_NO_SERVER_CONNECTION) {
  144. init_error_type_message_ = "Ошибка инициализации: нет связи с сервером Наследия!\n";
  145. setToolTipMessage(init_error_type_message_ + error_timeout_message_, E_ERROR);
  146. return;
  147. }
  148. }
  149. void StatusWidget::onSecondsToNextTryToInitChanged(size_t seconds_elapsed)
  150. {
  151. if (!init_error_type_message_.isEmpty()) {
  152. error_timeout_message_ = "Повторная попытка инициализации через " + QString::number(seconds_elapsed) + " секунд";
  153. setToolTipMessage(init_error_type_message_ + error_timeout_message_, E_ERROR);
  154. }
  155. }
  156. void StatusWidget::resizeEvent(QResizeEvent *)
  157. {
  158. double coefficient = window_width / default_window_width;
  159. // ui->game_button->move(QPoint(820, 460) * coefficient);
  160. // ui->game_button->resize(QSize(150, 60) * coefficient);
  161. // ui->progressBar->move(QPoint(320, 480) * coefficient);
  162. // ui->progressBar->resize(QSize(470, 40) * coefficient);
  163. // ui->progress_label->move(QPoint(330, 390) * coefficient);
  164. // ui->progress_label->resize(QSize(380, 90) * coefficient);
  165. // ui->news_label->move(QPoint(45, 33)* coefficient);
  166. // ui->news_label->resize(QSize(180, 21) * coefficient);
  167. // ui->news_scroll_area->move(QPoint(40, 75) * coefficient);
  168. // ui->news_scroll_area->resize(QSize(240, 440) * coefficient);
  169. // ui->server_status_widget->move(QPoint(820, 90) * coefficient);
  170. // ui->server_status_widget->resize(QSize(155, 320) * coefficient);
  171. // ui->weekly_code_widget->move(QPoint(810, 13) * coefficient);
  172. // ui->weekly_code_widget->resize(QSize(173, 57) * coefficient);
  173. // ui->galadriel_widget->move(QPoint(320, 20) * coefficient);
  174. // ui->galadriel_widget->resize(QSize(531, 461) * coefficient);
  175. // ui->news_tooltip->move(QPoint(38, 13) * coefficient);
  176. // ui->news_tooltip->resize(QSize(365, 114) * coefficient);
  177. // ui->weekly_code_tooltip_1->move(QPoint(38, 13) * coefficient);
  178. // ui->weekly_code_tooltip_1->resize(QSize(365, 114) * coefficient);
  179. // ui->weekly_code_tooltip_2->move(QPoint(38, 13) * coefficient);
  180. // ui->weekly_code_tooltip_2->resize(QSize(365, 114) * coefficient);
  181. // ui->server_status_tooltip->move(QPoint(38, 13) * coefficient);
  182. // ui->server_status_tooltip->resize(QSize(365, 114) * coefficient);
  183. // ui->patches_status->move(QPoint(38, 13) * coefficient);
  184. // ui->patches_status->resize(QSize(385, 114) * coefficient);
  185. updateFontsSizes();
  186. }
  187. void StatusWidget::generateRandomTooltipMessage()
  188. {
  189. quint32 number = QRandomGenerator::system()->generate();
  190. QVector<QString> messages = {
  191. "<p style=\"font-size: 22px; \">Atra du evarínya ono varda! Я видела тебя в своём зеркале...</p>",
  192. "<p style=\"font-size: 22px; \">Опасно ходить в рейды в одиночку! Зачищать инсты лучше в хорошей компании :)</p>",
  193. "<p style=\"font-size: 22px; \">Какое-то ещё мудрое высказывание в стиле эльфов...</p>",
  194. "<p style=\"font-size: 22px; \">Мудрые сидят в дискорде Наследия, <a href=\"https://discord.gg/j25MdKR\" style=\"color: yellow\">присоединяйся</a>!</p>",
  195. };
  196. setToolTipMessage(messages[number % messages.size()], E_RANDOM);
  197. }
  198. void StatusWidget::fadeBetweenToolTips(QString tooltip_id)
  199. {
  200. if (tooltip_id == current_tooltip_message_) {
  201. return;
  202. }
  203. QPropertyAnimation* showing_anim = tooltip_animations_[tooltip_id];
  204. showing_anim->setDirection(QAbstractAnimation::Forward);
  205. if (showing_anim->state() == QAbstractAnimation::Stopped) {
  206. showing_anim->start();
  207. }
  208. if (tooltip_widgets_.contains(current_tooltip_message_)) {
  209. QString msg = current_tooltip_message_;
  210. connect(tooltip_animations_[current_tooltip_message_], &QPropertyAnimation::finished, this, [&, msg](){
  211. if (tooltip_effects_.contains(msg) && tooltip_effects_[msg]->opacity() == 0) {
  212. tooltip_widgets_.take(msg)->deleteLater();
  213. tooltip_effects_.take(msg)->deleteLater();
  214. tooltip_animations_.take(msg)->deleteLater();
  215. }
  216. });
  217. QPropertyAnimation* hiding_anim = tooltip_animations_[current_tooltip_message_];
  218. hiding_anim->setDirection(QAbstractAnimation::Backward);
  219. if (hiding_anim->state() == QAbstractAnimation::Stopped) {
  220. hiding_anim->start();
  221. }
  222. }
  223. current_tooltip_message_ = tooltip_id;
  224. }
  225. void StatusWidget::onPatchDownloaderStarted() {
  226. process_completed_tooltip_hide_timer_.stop();
  227. all_patch_operations_finished_ = false;
  228. ui->game_button->setEnabled(false);
  229. setToolTipMessage("Проверка обновлений русификации...", E_PROCESS);
  230. }
  231. void StatusWidget::onPatchDownloaderFinished() {
  232. all_patch_operations_finished_ = true;
  233. ui->game_button->setEnabled(true);
  234. setToolTipMessage("Скачивание данных русификации завершено!", E_PROCESS);
  235. process_completed_tooltip_hide_timer_.start();
  236. }
  237. void StatusWidget::onPatchDownloaderProgressChanged(Downloader::Status status) {
  238. if (last_statusbar_update_time_.elapsed() > 450) {
  239. double download_percent = double(status.downloaded_bytes) * 100.0 / double(status.total_bytes);
  240. QString text = "Загрузка данных: " + QString::number(download_percent, 'f', 1) + "% ("
  241. + Downloader::getSizeFormatted(status.downloaded_bytes) + "/"
  242. + Downloader::getSizeFormatted(status.total_bytes) + ")\n"
  243. + "До конца загрузки: " + Downloader::getElapsedTimeFormatted(status.elapsed_time);
  244. setToolTipMessage(text, E_PROCESS);
  245. last_statusbar_update_time_.restart();
  246. }
  247. }
  248. void StatusWidget::onPatchInstallerStarted() {
  249. process_completed_tooltip_hide_timer_.stop();
  250. all_patch_operations_finished_ = false;
  251. ui->game_button->setEnabled(false);
  252. setToolTipMessage("<p style=\"font-size: 22px; \">Подготовка русификатора...</p>", E_PROCESS);
  253. }
  254. void StatusWidget::onPatchInstallerFinished() {
  255. all_patch_operations_finished_ = true;
  256. ui->game_button->setEnabled(true);
  257. setToolTipMessage("<p style=\"font-size: 22px; \">Все операции выполнены!</p>", E_PROCESS);
  258. process_completed_tooltip_hide_timer_.start();
  259. }
  260. void StatusWidget::onPatchInstallerProgressChanged(PatchInstaller::Status status) {
  261. if (last_statusbar_update_time_.elapsed() > 450 || status.finished_parts == 0) {
  262. QString text = "Установка русификации: "
  263. + QString::number(double(status.finished_parts) * 100.0 / double(status.total_parts), 'f', 1)
  264. + "%\n(" + QString::number(status.finished_parts)
  265. + " фрагментов из " + QString::number(status.total_parts) + ")";
  266. setToolTipMessage(text, E_PROCESS);
  267. last_statusbar_update_time_.restart();
  268. }
  269. }
  270. void StatusWidget::onPatchInstallerVideoProgressChanged(int finished_videos, int total_videos, Downloader::Status status) {
  271. if (last_statusbar_update_time_.elapsed() > 450) {
  272. double download_percent = double(status.downloaded_bytes) * 100.0 / double(status.total_bytes);
  273. QString text = "Загрузка и установка видеороликов ("
  274. + QString::number(finished_videos + 1) + " из " + QString::number(total_videos)
  275. + ")\n"
  276. + "Загружено: " + QString::number(download_percent, 'f', 1) + "% ("
  277. + Downloader::getSizeFormatted(status.downloaded_bytes) + "/"
  278. + Downloader::getSizeFormatted(status.total_bytes) + ")";
  279. setToolTipMessage(text, E_PROCESS);
  280. last_statusbar_update_time_.restart();
  281. }
  282. }
  283. void StatusWidget::on_game_button_clicked()
  284. {
  285. MainWindow* window = qobject_cast<MainWindow*>(parentWidget()->parentWidget()->parentWidget());
  286. window->showChooseVersionDialog();
  287. }
  288. void StatusWidget::createTooltipMessageWidget(QString tooltip_id)
  289. {
  290. tooltip_widgets_[tooltip_id] = new QLabel(this);
  291. tooltip_widgets_[tooltip_id]->setGeometry(ui->galadriel_tooltip_example->geometry());
  292. tooltip_widgets_[tooltip_id]->setStyleSheet(ui->galadriel_tooltip_example->styleSheet());
  293. tooltip_widgets_[tooltip_id]->setFont(ui->galadriel_tooltip_example->font());
  294. tooltip_widgets_[tooltip_id]->setWordWrap(true);
  295. tooltip_widgets_[tooltip_id]->setOpenExternalLinks(true);
  296. tooltip_widgets_[tooltip_id]->setAlignment(Qt::AlignCenter);
  297. tooltip_effects_[tooltip_id] = new QGraphicsOpacityEffect(tooltip_widgets_[tooltip_id]);
  298. tooltip_effects_[tooltip_id]->setOpacity(0);
  299. tooltip_animations_[tooltip_id] = new QPropertyAnimation(tooltip_effects_[tooltip_id], "opacity");
  300. tooltip_animations_[tooltip_id]->setDuration(300);
  301. tooltip_animations_[tooltip_id]->setStartValue(0);
  302. tooltip_animations_[tooltip_id]->setEndValue(1);
  303. tooltip_animations_[tooltip_id]->setDirection(QAbstractAnimation::Forward);
  304. tooltip_widgets_[tooltip_id]->setGraphicsEffect(tooltip_effects_[tooltip_id]);
  305. tooltip_widgets_[tooltip_id]->show();
  306. }
  307. void StatusWidget::on_check_for_updates_button_clicked()
  308. {
  309. QMetaObject::invokeMethod(&PatchDownloader::instance(), &PatchDownloader::startPatchDownloaderChain, Qt::QueuedConnection);
  310. }