statuswidget.cpp 17 KB

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