validator.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 = " (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.", "be consistent with Map->General menu entry translation")
  163. .arg(QString::fromStdString(LIBRARY->modh->getModInfo(mod.first).getVerificationInfo().name)), submod),
  164. true
  165. });
  166. }
  167. }
  168. }
  169. catch(const std::exception & e)
  170. {
  171. issues.insert({ tr("Exception occurs during validation: %1").arg(e.what()), true });
  172. }
  173. catch(...)
  174. {
  175. issues.insert({ tr("Unknown exception occurs during validation"), true });
  176. }
  177. return issues;
  178. }
  179. QPixmap Validator::createGreenTickIcon()
  180. {
  181. QPixmap pixmap(24, 24);
  182. pixmap.fill(Qt::transparent);
  183. QPainter painter(&pixmap);
  184. painter.setRenderHint(QPainter::Antialiasing);
  185. QBrush brush(QColor(50, 205, 50));
  186. painter.setBrush(brush);
  187. painter.setPen(Qt::NoPen);
  188. painter.drawEllipse(0, 0, 24, 24);
  189. QPen pen(Qt::white);
  190. pen.setWidth(3);
  191. painter.setPen(pen);
  192. painter.drawLine(7, 12, 10, 17); // Tick part 1
  193. painter.drawLine(10, 17, 17, 7); // Tick part 2
  194. painter.end();
  195. return pixmap;
  196. }
  197. void Validator::showValidationResults(const CMap * map)
  198. {
  199. show();
  200. setAttribute(Qt::WA_DeleteOnClose);
  201. ui->listWidget->setItemDelegate(new ValidatorItemDelegate(ui->listWidget));
  202. const std::array<QString, 2> icons{ ":/icons/mod-update.png", ":/icons/mod-delete.png" };
  203. for(auto const & issue : Validator::validate(map))
  204. {
  205. auto * item = new QListWidgetItem(QIcon(icons[issue.critical ? 1 : 0]), issue.message, ui->listWidget);
  206. ui->listWidget->addItem(item);
  207. }
  208. if(ui->listWidget->count() == 0)
  209. {
  210. QPixmap greenTick = createGreenTickIcon();
  211. QString validMessage = tr("The map is valid and has no issues.");
  212. auto * item = new QListWidgetItem(QIcon(greenTick), validMessage, ui->listWidget);
  213. ui->listWidget->addItem(item);
  214. }
  215. ui->listWidget->updateGeometry();
  216. adjustWindowSize();
  217. }
  218. void Validator::adjustWindowSize()
  219. {
  220. const int minWidth = 350;
  221. const int minHeight = 50;
  222. const int padding = 30; // reserved space for eventual scrollbars
  223. const int screenMarginVertical = 300;
  224. const int screenMarginHorizontal = 350;
  225. int contentHeight = minHeight;
  226. int contentWidth = minWidth;
  227. QStyleOptionViewItem option;
  228. option.initFrom(ui->listWidget);
  229. int listWidgetWidth = ui->listWidget->viewport()->width();
  230. for(int i = 0; i < ui->listWidget->count(); ++i)
  231. {
  232. option.rect = QRect(0, 0, listWidgetWidth, 0);
  233. auto itemSize = ui->listWidget->itemDelegate()->sizeHint(option, ui->listWidget->model()->index(i, 0));
  234. contentHeight += itemSize.height();
  235. contentWidth = qMax(contentWidth, itemSize.width());
  236. }
  237. int screenWidth = screenGeometry.width();
  238. int screenHeight = screenGeometry.height();
  239. int finalWidth = qMin(contentWidth + padding, screenWidth - screenMarginHorizontal);
  240. int finalHeight = qMin(contentHeight + padding, screenHeight - screenMarginVertical);
  241. logGlobal->warn("adjustWindowSize(): %d x %d", finalWidth, finalHeight);
  242. QWidget * parentWidget = ui->listWidget->parentWidget();
  243. if(parentWidget)
  244. {
  245. parentWidget->setFixedWidth(finalWidth + padding);
  246. parentWidget->setFixedHeight(finalHeight + padding);
  247. }
  248. ui->listWidget->resize(finalWidth, finalHeight);
  249. move((screenWidth - finalWidth) / 2, (screenHeight - finalHeight) / 2);
  250. }
  251. void ValidatorItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
  252. {
  253. painter->save();
  254. QStyleOptionViewItem opt(option);
  255. QFontMetrics metrics(option.fontMetrics);
  256. initStyleOption(&opt, index);
  257. const QRect iconRect = option.rect.adjusted(iconPadding, iconPadding, 0, 0);
  258. const QRect textRect = option.rect.adjusted(offsetForIcon, 0, -textPaddingRight, 0);
  259. if(!opt.icon.isNull())
  260. {
  261. opt.icon.paint(painter, iconRect, Qt::AlignTop | Qt::AlignLeft);
  262. }
  263. QTextOption textOption;
  264. int textWidth = metrics.horizontalAdvance(opt.text);
  265. if(textWidth + offsetForIcon + textPaddingRight > screenGeometry.width() - screenMargin)
  266. {
  267. textOption.setWrapMode(QTextOption::WordWrap);
  268. }
  269. painter->drawText(textRect, opt.text, textOption);
  270. painter->restore();
  271. }
  272. QSize ValidatorItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const
  273. {
  274. QFontMetrics metrics(option.fontMetrics);
  275. QString text = index.data(Qt::DisplayRole).toString();
  276. QStringList lines = text.split('\n');
  277. int textWidth = minItemWidth;
  278. int requiredHeight = 0;
  279. for(auto line : lines)
  280. textWidth = std::max(metrics.horizontalAdvance(line), textWidth);
  281. requiredHeight = qMax(requiredHeight, lines.size() * metrics.height());
  282. int finalWidth = qMax(textWidth + offsetForIcon, minItemWidth);
  283. finalWidth = qMin(finalWidth, screenGeometry.width() - screenMargin - offsetForIcon);
  284. QRect textBoundingRect = metrics.boundingRect(QRect(0, 0, finalWidth, 0),
  285. Qt::TextWordWrap, text);
  286. int finalHeight = qMax(textBoundingRect.height() + itemPaddingBottom, requiredHeight);
  287. return QSize(finalWidth, finalHeight);
  288. }