helper.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. #include "app.h"
  2. #include "filesystem.h"
  3. Helper::Helper()
  4. {
  5. }
  6. int Helper::getVersion(QString string) {
  7. std::string str(string.toLatin1().data());
  8. int version = 0;
  9. for (unsigned i = str.find("_v") + 2; i < str.find("_v") + 7; i += 2) {
  10. version = version * 10 + (str[i] - '0');
  11. }
  12. return version;
  13. }
  14. void Helper::checkTab(QString tabname){
  15. App *app = &App::getInstance();
  16. QList<QGroupBox *> boxes = app->window->findChildren<QGroupBox *> ();
  17. foreach (QGroupBox * box, boxes){
  18. if(box->parent()->objectName() == "centralWidget"){
  19. QLabel* boximage = app->window->findChild<QLabel*>(box->objectName() + "Image");
  20. if(box->objectName() == tabname){
  21. box->show();
  22. if(boximage != nullptr) boximage->show();
  23. } else {
  24. box->hide();
  25. if(boximage != nullptr) boximage->hide();
  26. }
  27. }
  28. }
  29. app->window->ui->serversbox->show();
  30. }
  31. void Helper::loadNews(){
  32. App *app = &App::getInstance();
  33. app->logSectionStart("Загружаем скин лаунчера");
  34. qInfo("%s:%i: %s", __FILE__, __LINE__, "Загрузка новостей с сайта");
  35. QString response = app->network->query(app->config->getValue("Network", "news"));
  36. if(response == "error"){
  37. qInfo("%s:%i: %s", __FILE__, __LINE__, "Отсутствует связь с сервером. Прервано.");
  38. app->logSectionEnd();
  39. return;
  40. }
  41. QStringList data = response.split(":::");
  42. qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Получено новостей - ", QString::number(data.count()).toUtf8().data());
  43. int counter = 1;
  44. foreach(QString news, data){
  45. qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Начинаем размещение новости №", QString::number(counter).toUtf8().data());
  46. QStringList item = news.split("|");
  47. QLabel* image = app->window->ui->newsbox->findChild<QLabel*>("news" + QString::number(counter) + "Image");
  48. QLabel* title = app->window->ui->newsbox->findChild<QLabel*>("news" + QString::number(counter) + "Title");
  49. QLabel* teaser = app->window->ui->newsbox->findChild<QLabel*>("news" + QString::number(counter) + "Teaser");
  50. qInfo("%s:%i: %s", __FILE__, __LINE__, "Устанавливаем миниатюру новости");
  51. QByteArray bytes = app->network->query_binary(item[0]);
  52. QImage img(36, 36, QImage::Format_Indexed8);
  53. img.loadFromData(bytes);
  54. QString skin = app->helper->getSkinName();
  55. if(img.bits() == nullptr){
  56. qInfo("%s:%i: %s", __FILE__, __LINE__, "Миниатюра не найдена, устанавливаем заглушку");
  57. img.load(":/res/styles/" + skin + "/nophoto.jpg");
  58. }
  59. image->setPixmap(QPixmap::fromImage(img));
  60. qInfo("%s:%i: %s", __FILE__, __LINE__, "Применяем HTML-цвета");
  61. QString hrefcolor = app->helper->htmlColors.contains("a") ? app->helper->htmlColors.lowerBound("a").value() : "blue";
  62. QString html = "<a href=\"" + item[3] +"\" style=\"color:" + hrefcolor + "; text-decoration:none;\">" + item[1] + "</a>";
  63. qInfo("%s:%i: %s", __FILE__, __LINE__, "Размещаем тексты");
  64. title->setText(html);
  65. teaser->setText(item[2]);
  66. counter = counter+1;
  67. qInfo("%s:%i: %s %s %s", __FILE__, __LINE__, "Размещена новость:", html.toUtf8().data(), QString(item[2]).toUtf8().data());
  68. }
  69. qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
  70. app->logSectionEnd();
  71. }
  72. void Helper::loadHelp(){
  73. App *app = &App::getInstance();
  74. app->logSectionStart("Создание справки");
  75. QFile file(QApplication::applicationDirPath() + "/readme.html");
  76. if(file.open(QFile::ReadOnly | QFile::Text)){
  77. qInfo("%s:%i: %s", __FILE__, __LINE__, "Справка загружена. Устанавливаем HTML-цвета и выводим.");
  78. app->window->ui->textBrowser->setHtml("");
  79. QString content = file.readAll();
  80. app->stylehtml = "<style>";
  81. for(auto e : app->helper->htmlColors.keys()){
  82. app->stylehtml = app->stylehtml + e + "{color:" + app->helper->htmlColors.value(e) + ";}";
  83. }
  84. QFile styleF;
  85. QString skin = app->helper->getSkinName();
  86. styleF.setFileName(app->app_folder + "styles/" + skin + "/readme.css");
  87. if(styleF.open(QFile::ReadOnly)){
  88. app->stylehtml = "<html><head><style type=\"text/css\">" + app->stylehtml + styleF.readAll();
  89. }
  90. app->stylehtml = app->stylehtml + "</style></head>";
  91. app->window->ui->textBrowser->setHtml(app->stylehtml + content);
  92. app->window->ui->textBrowser->document()->setDefaultStyleSheet(styleF.readAll());
  93. qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
  94. app->logSectionEnd();
  95. } else {
  96. qWarning("%s:%i: %s", __FILE__, __LINE__, "Не удалось получить информацию с сервера");
  97. qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
  98. app->logSectionEnd();
  99. }
  100. }
  101. void Helper::hideAll(){
  102. qInfo("%s:%i: %s", __FILE__, __LINE__, "Прячем ненужные элементы.");
  103. App *app = &App::getInstance();
  104. app->window->ui->optbox->hide();
  105. app->window->ui->optboxImage->hide();
  106. app->window->ui->newsbox->hide();
  107. app->window->ui->newsboxImage->hide();
  108. app->window->ui->helpbox->hide();
  109. app->window->ui->helpboxImage->hide();
  110. app->window->ui->aboutbox->hide();
  111. app->window->ui->aboutboxImage->hide();
  112. app->window->ui->dialogbox->hide();
  113. app->window->ui->loader->hide();
  114. app->window->ui->dialogList->hide();
  115. app->window->ui->startbox->hide();
  116. qInfo("%s:%i: %s", __FILE__, __LINE__, "Устанавливаем всплывающие подсказки.");
  117. app->window->ui->goOriginal->setToolTip("Запуск оригинальной версии игры");
  118. app->window->ui->goLocal->setToolTip("Запуск русской версии игры");
  119. app->window->ui->goCancel->setToolTip("Вернуться обратно");
  120. app->window->ui->goProgress->hide();
  121. app->window->ui->goHint->hide();
  122. app->window->ui->footRed->hide();
  123. app->window->ui->footYellow->hide();
  124. }
  125. void Helper::setAbout(){
  126. App *app = &App::getInstance();
  127. app->logSectionStart("О нас");
  128. qInfo("%s:%i: %s", __FILE__, __LINE__, "Размещаем информацию о хороших людях.");
  129. app->window->ui->programmerslist->setText("Gi1dor, coder");
  130. app->window->ui->designerslist->setText("Чирик, valyot, Quilanar, Eodoro");
  131. app->window->ui->translatorslist->setText("<b>Переводчики:</b> Pioneer, kitkatik134, Anadomiel, Progylkin, Drazgar, Rhymer, Влад Блюденов, "
  132. "Buddy, Quilanar, Ferdik, Alcassar, Чирик, Tukbard<br><br>"
  133. "<b>Модераторы:</b> Eodoro, unnamedartist, Marty, valyot, Invizet");
  134. app->window->ui->helperslist->setText("Menelhad, Мурзилка, Pastor, Alvees, Mirta, иван петров, vensys, "
  135. "Arkelas, Чеширская Улыбка, Shanishka70");
  136. }
  137. void Helper::findSkins(){
  138. App *app = &App::getInstance();
  139. app->logSectionStart("Темы оформления");
  140. qInfo("%s:%i: %s", __FILE__, __LINE__, "Производим поиск доступных тем.");
  141. QDir dir(QApplication::applicationDirPath() + "/styles");
  142. QStringList skins = dir.entryList(QDir::Dirs | QDir::AllDirs | QDir::NoDotAndDotDot);
  143. app->window->ui->skinSelect->addItems(skins);
  144. QString skinname = app->config->getValue("Global", "current_theme");
  145. app->window->ui->skinSelect->setCurrentText(skinname);
  146. qInfo("%s:%i: %s", __FILE__, __LINE__, "Устанавливаем отметку о файле локализации.");
  147. QString file = app->config->getValue("Local", "file");
  148. if(file == "client_local_English.dat") app->window->ui->enButton->setEnabled(false);
  149. if(file == "client_local_DE.dat") app->window->ui->deButton->setEnabled(false);
  150. if(file == "client_local_FR.dat") app->window->ui->frButton->setEnabled(false);
  151. qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
  152. app->logSectionEnd();
  153. }
  154. QString Helper::getSkinName() {
  155. App *app = &App::getInstance();
  156. QString skin = app->config->getValue("Global", "current_theme");
  157. if(skin == "-1") skin = app->config->getValue("Global", "default_theme");
  158. qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Текущая тема оформления: ", skin.toUtf8().data());
  159. return skin;
  160. }
  161. void Helper::applyShadow(QWidget * obj, QString color, int blur, int offset_x, int offset_y){
  162. QGraphicsDropShadowEffect *pLabelTextShadowEffect = new QGraphicsDropShadowEffect(obj);
  163. pLabelTextShadowEffect->setColor(QColor(color));
  164. pLabelTextShadowEffect->setBlurRadius(blur);
  165. pLabelTextShadowEffect->setOffset(offset_x, offset_y);
  166. obj->setGraphicsEffect(pLabelTextShadowEffect );
  167. }
  168. void Helper::myDialogBox(QString text, QString info, QString okText, QString cancelText, QString image, QString okAnswer, QString cancelAnswer,
  169. int w, int h, bool, bool is_cancel, bool stop_process) {
  170. App *app = &App::getInstance();
  171. if (okAnswer == "")
  172. okAnswer = "close";
  173. app->helper->dialog_ok_answer = okAnswer;
  174. if (cancelAnswer == "")
  175. cancelAnswer = "close";
  176. app->helper->dialog_cancel_answer = cancelAnswer;
  177. app->window->ui->okButton->setText(okText);
  178. app->window->ui->cancelButton->setText(cancelText);
  179. app->window->ui->dialogbox->setGeometry(0, 0, app->window->width(), app->window->height());
  180. QSettings settings( app->config->getSkinFile(), QSettings::IniFormat );
  181. settings.beginGroup("mainWindow");
  182. int left = (settings.value("width").toInt() - w)/2;
  183. int top = (settings.value("height").toInt() - h)/2;
  184. app->window->ui->dialog->setGeometry(QRect(left, top, w, h));
  185. settings.endGroup();
  186. int image_height = app->window->ui->dialog->rect().height() - app->window->ui->dialogHeader->rect().height();
  187. app->window->ui->dialogImage->setGeometry(0,
  188. app->window->ui->dialogHeader->rect().bottom(),
  189. image_height/2 ,image_height
  190. );
  191. QString skin = app->helper->getSkinName();
  192. QString iconpath = "";
  193. iconpath = FileSystem::fileExists("styles/" + skin + "/" + image) ? "styles/" + skin + "/" + image : ":/res/styles/" + skin + "/" + image;
  194. QPixmap icon(iconpath);
  195. app->window->ui->dialogImage->setPixmap(icon.scaled(app->window->ui->dialogImage->width(), app->window->ui->dialogImage->height()));
  196. if(icon.isNull()){
  197. app->window->ui->dialogImage->setGeometry(QRect(10, 10, 10, 10));
  198. }
  199. app->window->ui->dialogHeader->setGeometry(
  200. app->window->ui->dialogHeader->rect().left(),
  201. app->window->ui->dialogHeader->rect().top(),
  202. app->window->ui->dialog->rect().width(),
  203. app->window->ui->dialogHeader->rect().height()
  204. );
  205. app->window->ui->dialogInfo->setGeometry(app->window->ui->dialogImage->rect().right(),
  206. app->window->ui->dialogHeader->rect().bottom(),
  207. app->window->ui->dialog->rect().width() - app->window->ui->dialogImage->rect().width()-7,
  208. image_height - app->window->ui->cancelButton->height()
  209. );
  210. if(is_cancel){
  211. app->window->ui->cancelButton->setGeometry(
  212. app->window->ui->dialog->rect().left() + app->window->ui->dialog->width() - app->window->ui->cancelButton->width() - 20,
  213. app->window->ui->dialog->rect().bottom() - app->window->ui->cancelButton->height() - 10,
  214. app->window->ui->cancelButton->width(),
  215. app->window->ui->cancelButton->height()
  216. );
  217. app->window->ui->okButton->setGeometry(
  218. app->window->ui->dialog->rect().left() + app->window->ui->dialog->width() - app->window->ui->cancelButton->width() - app->window->ui->cancelButton->width() - 40,
  219. app->window->ui->dialog->rect().bottom() - app->window->ui->cancelButton->height() - 10,
  220. app->window->ui->cancelButton->width(),
  221. app->window->ui->cancelButton->height()
  222. );
  223. } else {
  224. app->window->ui->cancelButton->setGeometry(-1000,-1000, app->window->ui->cancelButton->width(), app->window->ui->cancelButton->height());
  225. app->window->ui->okButton->setGeometry(
  226. app->window->ui->dialog->rect().left() + app->window->ui->dialog->width() - app->window->ui->cancelButton->width() - 20,
  227. app->window->ui->dialog->rect().bottom() - app->window->ui->cancelButton->height() - 10,
  228. app->window->ui->cancelButton->width(),
  229. app->window->ui->cancelButton->height()
  230. );
  231. }
  232. if (stop_process)
  233. app->state = "dialog";
  234. app->window->ui->dialogHeader->setText(text);
  235. app->window->ui->dialogInfo->setText(info);
  236. app->window->ui->dialogImage->setText("");
  237. app->window->ui->dialogbox->show();
  238. }
  239. void Helper::setState(QString state){
  240. App *app = &App::getInstance();
  241. qInfo("%s:%i: %s%s%s%s", __FILE__, __LINE__, "Устанавливается состояние: ", state.toUtf8().data(),
  242. ". Предыдущее состояние: ", app->state.toUtf8().data());
  243. if(state == "busy"){
  244. app->window->ui->closeButton->setEnabled(false);
  245. app->window->ui->enterButton->setEnabled(false);
  246. app->window->ui->lotropathButton->setEnabled(false);
  247. app->window->ui->repairButton->setEnabled(false);
  248. app->state = "busy";
  249. app->window->ui->loader->show();
  250. }
  251. if(state == "free"){
  252. app->window->ui->closeButton->setEnabled(true);
  253. app->window->ui->enterButton->setEnabled(true);
  254. app->window->ui->lotropathButton->setEnabled(true);
  255. app->window->ui->repairButton->setEnabled(true);
  256. app->state = "free";
  257. app->window->ui->loader->hide();
  258. }
  259. if(state == "nofolder"){
  260. app->window->ui->enterButton->setEnabled(false);
  261. app->state = "nofolder";
  262. app->window->ui->loader->hide();
  263. }
  264. if (state == "runfirst") {
  265. app->window->ui->enterButton->setEnabled(false);
  266. app->window->ui->repairButton->setEnabled(false);
  267. app->state = "runfirst";
  268. app->window->ui->loader->hide();
  269. QString info = "Вы запускаете программу русификации LotRO впервые. Мастер установки поможет вам настроить программу для ее дальнейшего использования. Сейчас будет осуществлена попытка автоматически определить каталог с игрой. Для продолжения нажмите «Далее».";
  270. app->helper->myDialogBox("Добро пожаловать!", info, "Далее", "Отмена", "gandalf.png", "close gamefind", "", 400, 200, true, false);
  271. }
  272. }
  273. int Helper::dateToTimestamp(QString customDateString, QString format){
  274. int timestamp = QDateTime::fromString(customDateString, format).toTime_t();
  275. return timestamp;
  276. }
  277. void Helper::addComboItem(QComboBox* combo, QString itemName, QIcon* icon){
  278. combo->insertItem(0, itemName);
  279. combo->setItemIcon(0, *icon);
  280. }
  281. void Helper::replaceSkin(QString name){
  282. App *app = &App::getInstance();
  283. QString text = "Смена темы оформления";
  284. QString info = "Выбрана тема " + name + ". Изменения вступят в силу при следующем запуске лаунчера.";
  285. //app->helper->myDialogBox(text, info, "OK", "Отмена", "gandalf.png", "", "", 400, 120, true, false);
  286. qInfo("%s:%i: %s", __FILE__, __LINE__, "Оформляем главное окно.");
  287. QFile styleF;
  288. QString skin = app->helper->getSkinName();
  289. styleF.setFileName(app->app_folder + "styles/" + name + "/style.css");
  290. styleF.open(QFile::ReadOnly);
  291. QString qssStr = styleF.readAll();
  292. qApp->setStyleSheet(qssStr);
  293. QPixmap maskPix(":/res/styles/" + name + "/bg.png");
  294. QPixmap maskPixLocal(app->app_folder + "styles/" + name + "/bg.png");
  295. maskPix = maskPix.isNull() ? maskPixLocal : maskPix;
  296. app->window->setMask(maskPix.mask());
  297. QString color = app->helper->htmlColors.contains("a") ? app->helper->htmlColors.lowerBound("a").value() : "blue";
  298. app->config->loadSkin();
  299. QString hrefcolor = app->helper->htmlColors.contains("a") ? app->helper->htmlColors.lowerBound("a").value() : "blue";
  300. QString newtext = app->window->ui->news1Title->text().replace(color, hrefcolor);
  301. app->window->ui->news1Title->setText(newtext);
  302. newtext = app->window->ui->news2Title->text().replace(color, hrefcolor);
  303. app->window->ui->news2Title->setText(newtext);
  304. newtext = app->window->ui->news3Title->text().replace(color, hrefcolor);
  305. app->window->ui->news3Title->setText(newtext);
  306. newtext = app->window->ui->news4Title->text().replace(color, hrefcolor);
  307. app->window->ui->news4Title->setText(newtext);
  308. app->helper->loadHelp();
  309. QMovie * movie = new QMovie(":/res/styles/" + skin + "/loader.gif");
  310. if(!movie->isValid()) movie = new QMovie(app->app_folder + "styles/" + skin + "/loader.gif");
  311. app->window->ui->loader->setMovie(movie);
  312. movie->setScaledSize(QSize(app->window->ui->loader->width(), app->window->ui->loader->height()));
  313. movie->start();
  314. }
  315. QString Helper::countFormattedElapsedTime(qint64 ticks_elapsed, double average_tick_speed) {
  316. if (average_tick_speed < 0.01) {
  317. return " очень много (низкая скорость)";
  318. }
  319. qint64 secs = ticks_elapsed / average_tick_speed;
  320. qint64 mins = 0;
  321. qint64 hours = 0;
  322. qint64 days = 0;
  323. if (secs > 60) {
  324. mins = secs / 60;
  325. secs %= 60;
  326. }
  327. if (mins > 60) {
  328. hours = mins / 60;
  329. mins %= 60;
  330. }
  331. if (hours > 24) {
  332. days = hours / 24;
  333. hours %= 24;
  334. }
  335. if (days > 0)
  336. return " очень много (низкая скорость)";
  337. QString result = "";
  338. if (hours > 0) {
  339. result += QString::number(hours);
  340. if (hours % 10 == 1 && hours / 10 != 1)
  341. result += " час ";
  342. else if (hours % 10 > 1 && hours % 10 < 5 && hours / 10 != 1)
  343. result += " часа ";
  344. else
  345. result += " часов ";
  346. }
  347. if (mins > 0) {
  348. result += QString::number(mins);
  349. if (mins % 10 == 1 && mins / 10 != 1)
  350. result += " минута ";
  351. else if (mins % 10 > 1 && mins % 10 < 5 && mins / 10 != 1)
  352. result += " минуты ";
  353. else
  354. result += " минут ";
  355. }
  356. if (secs > 0 && hours == 0) {
  357. result += QString::number(secs);
  358. if (secs % 10 == 1 && secs / 10 != 1)
  359. result += " секунда ";
  360. else if (secs % 10 > 1 && secs % 10 < 5 && secs / 10 != 1)
  361. result += " секунды ";
  362. else
  363. result += " секунд ";
  364. }
  365. if (result == "")
  366. result = "совсем чуть-чуть";
  367. return result;
  368. }