validator.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. * validator.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "validator.h"
  12. #include "mapcontroller.h"
  13. #include "ui_validator.h"
  14. #include "../lib/entities/hero/CHero.h"
  15. #include "../lib/mapping/CMap.h"
  16. #include "../lib/mapObjects/MapObjects.h"
  17. #include "../lib/modding/CModHandler.h"
  18. #include "../lib/modding/ModDescription.h"
  19. #include "../lib/spells/CSpellHandler.h"
  20. Validator::Validator(const CMap * map, QWidget *parent) :
  21. QDialog(parent),
  22. ui(new Ui::Validator)
  23. {
  24. ui->setupUi(this);
  25. screenGeometry = QApplication::primaryScreen()->availableGeometry();
  26. setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
  27. showValidationResults(map);
  28. }
  29. Validator::~Validator()
  30. {
  31. delete ui;
  32. }
  33. std::set<Validator::Issue> Validator::validate(const CMap * map)
  34. {
  35. std::set<Validator::Issue> issues;
  36. if(!map)
  37. {
  38. issues.insert({ tr("Map is not loaded"), true });
  39. return issues;
  40. }
  41. try
  42. {
  43. //check player settings
  44. int hplayers = 0;
  45. int cplayers = 0;
  46. std::map<PlayerColor, int> amountOfTowns;
  47. std::map<PlayerColor, int> amountOfHeroes;
  48. for(int i = 0; i < map->players.size(); ++i)
  49. {
  50. auto & p = map->players[i];
  51. if (p.canAnyonePlay())
  52. amountOfTowns[PlayerColor(i)] = 0;
  53. if(p.canComputerPlay)
  54. ++cplayers;
  55. if(p.canHumanPlay)
  56. ++hplayers;
  57. if(p.allowedFactions.empty())
  58. issues.insert({ tr("No factions allowed for player %1").arg(i), true });
  59. }
  60. if(hplayers + cplayers == 0)
  61. issues.insert({ tr("No players allowed to play this map"), true });
  62. if(hplayers + cplayers == 1)
  63. issues.insert({ tr("Map is allowed for one player and cannot be started"), true });
  64. if(!hplayers)
  65. issues.insert({ tr("No human players allowed to play this map"), true });
  66. std::set<const CHero * > allHeroesOnMap; //used to find hero duplicated
  67. //checking all objects in the map
  68. for(auto o : map->objects)
  69. {
  70. //owners for objects
  71. if(o->getOwner() == PlayerColor::UNFLAGGABLE)
  72. {
  73. if(o->asOwnable())
  74. {
  75. issues.insert({ tr("Ownable object %1 is UNFLAGGABLE but must have NEUTRAL or player owner").arg(o->instanceName.c_str()), true });
  76. }
  77. }
  78. if(o->getOwner() != PlayerColor::NEUTRAL && o->getOwner().getNum() < map->players.size())
  79. {
  80. if(!map->players[o->getOwner().getNum()].canAnyonePlay())
  81. issues.insert({ tr("Object %1 is assigned to non-playable player %2").arg(o->instanceName.c_str(), o->getOwner().toString().c_str()), true });
  82. }
  83. //count towns
  84. if(auto * ins = dynamic_cast<CGTownInstance *>(o.get()))
  85. {
  86. ++amountOfTowns[ins->getOwner()];
  87. }
  88. //checking and counting heroes and prisons
  89. if(auto * ins = dynamic_cast<CGHeroInstance *>(o.get()))
  90. {
  91. if(ins->ID == Obj::PRISON)
  92. {
  93. if(ins->getOwner() != PlayerColor::NEUTRAL)
  94. issues.insert({ tr("Prison %1 must be a NEUTRAL").arg(ins->instanceName.c_str()), true });
  95. }
  96. else
  97. {
  98. if(ins->getOwner() == PlayerColor::NEUTRAL)
  99. issues.insert({ tr("Hero %1 must have an owner").arg(ins->instanceName.c_str()), true });
  100. ++amountOfHeroes[ins->getOwner()];
  101. }
  102. if(ins->getHeroTypeID().hasValue())
  103. {
  104. if(map->allowedHeroes.count(ins->getHeroTypeID()) == 0)
  105. issues.insert({ tr("Hero %1 is prohibited by map settings").arg(ins->getHeroType()->getNameTranslated().c_str()), false });
  106. if(!allHeroesOnMap.insert(ins->getHeroType()).second)
  107. issues.insert({ tr("Hero %1 has duplicate on map").arg(ins->getHeroType()->getNameTranslated().c_str()), false });
  108. }
  109. else if(ins->ID != Obj::RANDOM_HERO)
  110. issues.insert({ tr("Hero %1 has an empty type and must be removed").arg(ins->instanceName.c_str()), true });
  111. }
  112. //checking for arts
  113. if(auto * ins = dynamic_cast<CGArtifact *>(o.get()))
  114. {
  115. if(ins->ID == Obj::SPELL_SCROLL)
  116. {
  117. if (ins->getArtifactInstance())
  118. {
  119. if (map->allowedSpells.count(ins->getArtifactInstance()->getScrollSpellID()) == 0)
  120. issues.insert({ tr("Spell scroll %1 is prohibited by map settings").arg(ins->getArtifactInstance()->getScrollSpellID().toEntity(LIBRARY->spells())->getNameTranslated().c_str()), false });
  121. }
  122. else
  123. issues.insert({ tr("Spell scroll %1 doesn't have instance assigned and must be removed").arg(ins->instanceName.c_str()), true });
  124. }
  125. else
  126. {
  127. if(ins->ID == Obj::ARTIFACT && map->allowedArtifact.count(ins->getArtifactType()) == 0)
  128. {
  129. issues.insert({ tr("Artifact %1 is prohibited by map settings").arg(ins->getObjectName().c_str()), false });
  130. }
  131. }
  132. }
  133. }
  134. //verification of starting towns
  135. for (const auto & [player, counter] : amountOfTowns)
  136. {
  137. if (counter == 0)
  138. {
  139. // FIXME: heroesNames are empty even though heroes are on the map
  140. // if(map->players[playerTCounter.first].heroesNames.empty())
  141. if(amountOfHeroes.count(player) == 0)
  142. issues.insert({ tr("Player %1 has no towns and heroes assigned").arg(player + 1), true });
  143. else
  144. issues.insert({ tr("Player %1 doesn't have any starting town").arg(player + 1), false });
  145. }
  146. }
  147. //verification of map name and description
  148. if(map->name.empty())
  149. issues.insert({ tr("Map name is not specified"), false });
  150. if(map->description.empty())
  151. issues.insert({ tr("Map description is not specified"), false });
  152. //verification for mods
  153. for(auto & mod : MapController::modAssessmentMap(*map))
  154. {
  155. if(!map->mods.count(mod.first))
  156. {
  157. QString submod;
  158. if(!mod.second.parent.empty())
  159. submod = " ("+ tr("submod of") +" "+ QString::fromStdString(mod.second.parent) + ")";
  160. issues.insert({
  161. tr("Map contains object(s) from mod '%1'%2, but the mod is missing from the map's required mods list."
  162. " Add it to the map's required mods in Map->General settings.", "should be consistent with Map->General menu entry translation")
  163. .arg(QString::fromStdString(LIBRARY->modh->getModInfo(mod.first).getVerificationInfo().name), submod), true });
  164. }
  165. }
  166. }
  167. catch(const std::exception & e)
  168. {
  169. issues.insert({ tr("Exception occurs during validation: %1").arg(e.what()), true });
  170. }
  171. catch(...)
  172. {
  173. issues.insert({ tr("Unknown exception occurs during validation"), true });
  174. }
  175. return issues;
  176. }
  177. QPixmap Validator::createGreenTickIcon()
  178. {
  179. QPixmap pixmap(24, 24);
  180. pixmap.fill(Qt::transparent);
  181. QPainter painter(&pixmap);
  182. painter.setRenderHint(QPainter::Antialiasing);
  183. QBrush brush(QColor(50, 205, 50));
  184. painter.setBrush(brush);
  185. painter.setPen(Qt::NoPen);
  186. painter.drawEllipse(0, 0, 24, 24);
  187. QPen pen(Qt::white);
  188. pen.setWidth(3);
  189. painter.setPen(pen);
  190. painter.drawLine(7, 12, 10, 17); // Tick part 1
  191. painter.drawLine(10, 17, 17, 7); // Tick part 2
  192. painter.end();
  193. return pixmap;
  194. }
  195. void Validator::showValidationResults(const CMap * map)
  196. {
  197. show();
  198. setAttribute(Qt::WA_DeleteOnClose);
  199. ui->listWidget->setItemDelegate(new ValidatorItemDelegate(ui->listWidget));
  200. const std::array<QString, 2> icons{ ":/icons/mod-update.png", ":/icons/mod-delete.png" };
  201. for(auto const & issue : Validator::validate(map))
  202. {
  203. auto * item = new QListWidgetItem(QIcon(icons[issue.critical ? 1 : 0]), issue.message, ui->listWidget);
  204. ui->listWidget->addItem(item);
  205. }
  206. if(ui->listWidget->count() == 0)
  207. {
  208. QPixmap greenTick = createGreenTickIcon();
  209. QString validMessage = tr("The map is valid and has no issues.");
  210. auto * item = new QListWidgetItem(QIcon(greenTick), validMessage, ui->listWidget);
  211. ui->listWidget->addItem(item);
  212. }
  213. ui->listWidget->updateGeometry();
  214. adjustWindowSize();
  215. }
  216. void Validator::adjustWindowSize()
  217. {
  218. const int minWidth = 350;
  219. const int minHeight = 50;
  220. const int padding = 30; // reserved space for eventual scrollbars
  221. const int screenMarginVertical = 300;
  222. const int screenMarginHorizontal = 350;
  223. int contentHeight = minHeight;
  224. int contentWidth = minWidth;
  225. QStyleOptionViewItem option;
  226. option.initFrom(ui->listWidget);
  227. int listWidgetWidth = ui->listWidget->viewport()->width();
  228. for(int i = 0; i < ui->listWidget->count(); ++i)
  229. {
  230. option.rect = QRect(0, 0, listWidgetWidth, 0);
  231. auto itemSize = ui->listWidget->itemDelegate()->sizeHint(option, ui->listWidget->model()->index(i, 0));
  232. contentHeight += itemSize.height();
  233. contentWidth = qMax(contentWidth, itemSize.width());
  234. }
  235. int screenWidth = screenGeometry.width();
  236. int screenHeight = screenGeometry.height();
  237. int finalWidth = qMin(contentWidth + padding, screenWidth - screenMarginHorizontal);
  238. int finalHeight = qMin(contentHeight + padding, screenHeight - screenMarginVertical);
  239. logGlobal->warn("adjustWindowSize(): %d x %d", finalWidth, finalHeight);
  240. QWidget * parentWidget = ui->listWidget->parentWidget();
  241. if(parentWidget)
  242. {
  243. parentWidget->setFixedWidth(finalWidth + padding);
  244. parentWidget->setFixedHeight(finalHeight + padding);
  245. }
  246. ui->listWidget->resize(finalWidth, finalHeight);
  247. move((screenWidth - finalWidth) / 2, (screenHeight - finalHeight) / 2);
  248. }
  249. void ValidatorItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
  250. {
  251. painter->save();
  252. QStyleOptionViewItem opt(option);
  253. QFontMetrics metrics(option.fontMetrics);
  254. initStyleOption(&opt, index);
  255. const QRect iconRect = option.rect.adjusted(iconPadding, iconPadding, 0, 0);
  256. const QRect textRect = option.rect.adjusted(offsetForIcon, 0, -textPaddingRight, 0);
  257. if(!opt.icon.isNull())
  258. {
  259. opt.icon.paint(painter, iconRect, Qt::AlignTop | Qt::AlignLeft);
  260. }
  261. QTextOption textOption;
  262. int textWidth = metrics.horizontalAdvance(opt.text);
  263. if(textWidth + offsetForIcon + textPaddingRight > screenGeometry.width() - screenMargin)
  264. {
  265. textOption.setWrapMode(QTextOption::WordWrap);
  266. }
  267. painter->drawText(textRect, opt.text, textOption);
  268. painter->restore();
  269. }
  270. QSize ValidatorItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const
  271. {
  272. QFontMetrics metrics(option.fontMetrics);
  273. QString text = index.data(Qt::DisplayRole).toString();
  274. QStringList lines = text.split('\n');
  275. int textWidth = minItemWidth;
  276. int requiredHeight = 0;
  277. for(auto line : lines)
  278. textWidth = std::max(metrics.horizontalAdvance(line), textWidth);
  279. requiredHeight = qMax(requiredHeight, lines.size() * metrics.height());
  280. int finalWidth = qMax(textWidth + offsetForIcon, minItemWidth);
  281. finalWidth = qMin(finalWidth, screenGeometry.width() - screenMargin - offsetForIcon);
  282. QRect textBoundingRect = metrics.boundingRect(QRect(0, 0, finalWidth, 0),
  283. Qt::TextWordWrap, text);
  284. int finalHeight = qMax(textBoundingRect.height() + itemPaddingBottom, requiredHeight);
  285. return QSize(finalWidth, finalHeight);
  286. }