Browse Source

Remove utils/stdcompat/string_view.hpp

pull/6465/head
Gleb Mazovetskiy 3 years ago
parent
commit
8c1a847f41
  1. 2
      Source/DiabloUI/credits.cpp
  2. 8
      Source/DiabloUI/diabloui.cpp
  3. 2
      Source/DiabloUI/diabloui.h
  4. 12
      Source/DiabloUI/dialogs.cpp
  5. 6
      Source/DiabloUI/dialogs.h
  6. 6
      Source/DiabloUI/multi/selgame.cpp
  7. 2
      Source/DiabloUI/settingsmenu.cpp
  8. 30
      Source/DiabloUI/ui_item.h
  9. 8
      Source/appfat.cpp
  10. 11
      Source/appfat.h
  11. 2
      Source/automap.cpp
  12. 34
      Source/control.cpp
  13. 8
      Source/control.h
  14. 224
      Source/controls/controller_buttons.cpp
  15. 227
      Source/controls/controller_buttons.h
  16. 10
      Source/controls/controller_motion.cpp
  17. 2
      Source/controls/game_controls.cpp
  18. 4
      Source/controls/plrctrls.cpp
  19. 112
      Source/debug.cpp
  20. 4
      Source/debug.h
  21. 14
      Source/diablo.cpp
  22. 4
      Source/discord/discord.cpp
  23. 6
      Source/dvlnet/zerotier_native.cpp
  24. 8
      Source/engine/assets.cpp
  25. 2
      Source/engine/direction.cpp
  26. 5
      Source/engine/direction.hpp
  27. 8
      Source/engine/render/dun_render.cpp
  28. 4
      Source/engine/render/dun_render.hpp
  29. 4
      Source/engine/render/scrollrt.cpp
  30. 56
      Source/engine/render/text_render.cpp
  31. 24
      Source/engine/render/text_render.hpp
  32. 2
      Source/engine/sound_defs.hpp
  33. 2
      Source/error.cpp
  34. 4
      Source/error.h
  35. 6
      Source/help.cpp
  36. 10
      Source/init.cpp
  37. 2
      Source/inv.cpp
  38. 2
      Source/inv.h
  39. 2
      Source/itemdat.cpp
  40. 4
      Source/itemdat.h
  41. 44
      Source/items.cpp
  42. 2
      Source/items.h
  43. 2
      Source/loadsave.cpp
  44. 4
      Source/minitext.cpp
  45. 2
      Source/misdat.h
  46. 8
      Source/monster.cpp
  47. 2
      Source/monster.h
  48. 2
      Source/msg.cpp
  49. 8
      Source/multi.cpp
  50. 2
      Source/objects.cpp
  51. 128
      Source/options.cpp
  52. 142
      Source/options.h
  53. 4
      Source/panels/charpanel.cpp
  54. 8
      Source/panels/mainpanel.cpp
  55. 2
      Source/panels/spell_book.cpp
  56. 12
      Source/panels/spell_list.cpp
  57. 18
      Source/pfile.cpp
  58. 6
      Source/platform/ctr/keyboard.cpp
  59. 8
      Source/platform/ctr/keyboard.h
  60. 9
      Source/platform/locale.cpp
  61. 4
      Source/platform/switch/keyboard.cpp
  62. 4
      Source/platform/switch/keyboard.h
  63. 4
      Source/platform/vita/keyboard.cpp
  64. 4
      Source/platform/vita/keyboard.h
  65. 2
      Source/player.cpp
  66. 12
      Source/plrmsg.cpp
  67. 6
      Source/plrmsg.h
  68. 7
      Source/qol/chatlog.cpp
  69. 2
      Source/qol/chatlog.h
  70. 2
      Source/qol/itemlabels.cpp
  71. 2
      Source/qol/stash.cpp
  72. 2
      Source/qol/stash.h
  73. 2
      Source/quests.cpp
  74. 12
      Source/stores.cpp
  75. 2
      Source/stores.h
  76. 4
      Source/towners.h
  77. 6
      Source/utils/console.cpp
  78. 4
      Source/utils/console.h
  79. 16
      Source/utils/file_name_generator.hpp
  80. 15
      Source/utils/file_util.cpp
  81. 7
      Source/utils/file_util.h
  82. 5
      Source/utils/format_int.cpp
  83. 64
      Source/utils/language.cpp
  84. 13
      Source/utils/language.h
  85. 37
      Source/utils/log.hpp
  86. 5
      Source/utils/parse_int.hpp
  87. 7
      Source/utils/stdcompat/string_view.hpp
  88. 5
      Source/utils/str_case.hpp
  89. 15
      Source/utils/str_cat.hpp
  90. 23
      Source/utils/str_split.hpp
  91. 19
      Source/utils/string_or_view.hpp
  92. 2
      Source/utils/ui_fwd.h
  93. 6
      Source/utils/utf8.cpp
  94. 11
      Source/utils/utf8.hpp
  95. 2
      test/str_cat_test.cpp

2
Source/DiabloUI/credits.cpp

@ -36,7 +36,7 @@ public:
CreditsRenderer(char const *const *text, std::size_t textLines)
{
for (size_t i = 0; i < textLines; i++) {
string_view orgText = _(text[i]);
std::string_view orgText = _(text[i]);
uint16_t offset = 0;
size_t indexFirstNotTab = 0;

8
Source/DiabloUI/diabloui.cpp

@ -637,7 +637,7 @@ void UiDestroy()
UnloadUiGFX();
}
bool UiValidPlayerName(string_view name)
bool UiValidPlayerName(std::string_view name)
{
if (name.empty())
return false;
@ -655,7 +655,7 @@ bool UiValidPlayerName(string_view name)
if (!c_all_of(name, IsBasicLatin))
return false;
string_view bannedNames[] = {
std::string_view bannedNames[] = {
"gvdl",
"dvou",
"tiju",
@ -670,8 +670,8 @@ bool UiValidPlayerName(string_view name)
for (char &character : buffer)
character++;
string_view tempName { buffer };
for (string_view bannedName : bannedNames) {
std::string_view tempName { buffer };
for (std::string_view bannedName : bannedNames) {
if (tempName.find(bannedName) != tempName.npos)
return false;
}

2
Source/DiabloUI/diabloui.h

@ -82,7 +82,7 @@ void UiDestroy();
void UiTitleDialog();
void UnloadUiGFX();
void UiInitialize();
bool UiValidPlayerName(string_view name); /* check */
bool UiValidPlayerName(std::string_view name); /* check */
void UiSelHeroMultDialog(bool (*fninfo)(bool (*fninfofunc)(_uiheroinfo *)), bool (*fncreate)(_uiheroinfo *), bool (*fnremove)(_uiheroinfo *), void (*fnstats)(unsigned int, _uidefaultstats *), _selhero_selections *dlgresult, uint32_t *saveNumber);
void UiSelHeroSingDialog(bool (*fninfo)(bool (*fninfofunc)(_uiheroinfo *)), bool (*fncreate)(_uiheroinfo *), bool (*fnremove)(_uiheroinfo *), void (*fnstats)(unsigned int, _uidefaultstats *), _selhero_selections *dlgresult, uint32_t *saveNumber, _difficulty *difficulty);
bool UiCreditsDialog();

12
Source/DiabloUI/dialogs.cpp

@ -1,6 +1,7 @@
#include "DiabloUI/dialogs.h"
#include <cstdint>
#include <string_view>
#include <utility>
#include "DiabloUI/button.h"
@ -17,7 +18,6 @@
#include "utils/display.h"
#include "utils/language.h"
#include "utils/log.hpp"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -54,7 +54,7 @@ OptionalClxSprite LoadDialogSprite(bool hasCaption, bool isError)
return (*ownedDialogSprite)[0];
}
bool Init(string_view caption, string_view text, bool error, bool renderBehind)
bool Init(std::string_view caption, std::string_view text, bool error, bool renderBehind)
{
if (!renderBehind) {
if (!UiLoadBlackBackground()) {
@ -137,7 +137,7 @@ void DialogLoop(const std::vector<std::unique_ptr<UiItemBase>> &items, const std
} while (!dialogEnd);
}
void UiOkDialog(string_view caption, string_view text, bool error, const std::vector<std::unique_ptr<UiItemBase>> &renderBehind)
void UiOkDialog(std::string_view caption, std::string_view text, bool error, const std::vector<std::unique_ptr<UiItemBase>> &renderBehind)
{
static bool inDialog = false;
@ -183,17 +183,17 @@ void UiOkDialog(string_view caption, string_view text, bool error, const std::ve
} // namespace
void UiErrorOkDialog(string_view caption, string_view text, const std::vector<std::unique_ptr<UiItemBase>> &renderBehind)
void UiErrorOkDialog(std::string_view caption, std::string_view text, const std::vector<std::unique_ptr<UiItemBase>> &renderBehind)
{
UiOkDialog(caption, text, /*error=*/true, renderBehind);
}
void UiErrorOkDialog(string_view caption, string_view text, bool error)
void UiErrorOkDialog(std::string_view caption, std::string_view text, bool error)
{
UiOkDialog(caption, text, error, vecNULL);
}
void UiErrorOkDialog(string_view text, const std::vector<std::unique_ptr<UiItemBase>> &renderBehind)
void UiErrorOkDialog(std::string_view text, const std::vector<std::unique_ptr<UiItemBase>> &renderBehind)
{
UiErrorOkDialog({}, text, renderBehind);
}

6
Source/DiabloUI/dialogs.h

@ -1,13 +1,13 @@
#pragma once
#include <cstddef>
#include <string_view>
#include "DiabloUI/ui_item.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
void UiErrorOkDialog(string_view text, const std::vector<std::unique_ptr<UiItemBase>> &renderBehind);
void UiErrorOkDialog(string_view caption, string_view text, const std::vector<std::unique_ptr<UiItemBase>> &renderBehind);
void UiErrorOkDialog(std::string_view text, const std::vector<std::unique_ptr<UiItemBase>> &renderBehind);
void UiErrorOkDialog(std::string_view caption, std::string_view text, const std::vector<std::unique_ptr<UiItemBase>> &renderBehind);
} // namespace devilution

6
Source/DiabloUI/multi/selgame.cpp

@ -80,7 +80,7 @@ bool IsGameCompatible(const GameData &data)
static std::string GetErrorMessageIncompatibility(const GameData &data)
{
if (data.programid != GAME_ID) {
string_view gameMode;
std::string_view gameMode;
switch (data.programid) {
case GameIdDiabloFull:
gameMode = _("Diablo");
@ -103,7 +103,7 @@ static std::string GetErrorMessageIncompatibility(const GameData &data)
}
}
void UiInitGameSelectionList(string_view search)
void UiInitGameSelectionList(std::string_view search)
{
selgame_enteringGame = false;
selgame_selectedGame = 0;
@ -228,7 +228,7 @@ void selgame_GameSelection_Focus(int value)
std::string infoString = std::string(_("Join the public game already in progress."));
infoString.append("\n\n");
if (IsGameCompatible(gameInfo.gameData)) {
string_view difficulty;
std::string_view difficulty;
switch (gameInfo.gameData.nDifficulty) {
case DIFF_NORMAL:
difficulty = _("Normal");

2
Source/DiabloUI/settingsmenu.cpp

@ -360,7 +360,7 @@ void UiSettingsMenu()
optionDescription[0] = '\0';
string_view titleText;
std::string_view titleText;
switch (shownMenu) {
case ShownMenuType::Categories:
titleText = _("Settings");

30
Source/DiabloUI/ui_item.h

@ -179,7 +179,7 @@ public:
{
}
[[nodiscard]] string_view GetText() const
[[nodiscard]] std::string_view GetText() const
{
if (text_ != nullptr)
return text_;
@ -227,7 +227,7 @@ class UiArtTextButton : public UiItemBase {
public:
using Callback = void (*)();
UiArtTextButton(string_view text, Callback action, SDL_Rect rect, UiFlags flags = UiFlags::None)
UiArtTextButton(std::string_view text, Callback action, SDL_Rect rect, UiFlags flags = UiFlags::None)
: UiItemBase(UiType::ArtTextButton, rect, flags)
, text_(text)
, action_(action)
@ -239,7 +239,7 @@ public:
UiItemBase::SetFlags(flags);
}
[[nodiscard]] string_view GetText() const
[[nodiscard]] std::string_view GetText() const
{
return text_;
}
@ -250,7 +250,7 @@ public:
}
private:
string_view text_;
std::string_view text_;
Callback action_;
};
@ -258,7 +258,7 @@ private:
class UiEdit : public UiItemBase {
public:
UiEdit(string_view hint, char *value, std::size_t maxLength, bool allowEmpty, SDL_Rect rect, UiFlags flags = UiFlags::None)
UiEdit(std::string_view hint, char *value, std::size_t maxLength, bool allowEmpty, SDL_Rect rect, UiFlags flags = UiFlags::None)
: UiItemBase(UiType::Edit, rect, flags)
, m_hint(hint)
, m_value(value)
@ -268,7 +268,7 @@ public:
}
// private:
string_view m_hint;
std::string_view m_hint;
char *m_value;
std::size_t m_max_length;
bool m_allowEmpty;
@ -280,19 +280,19 @@ public:
class UiText : public UiItemBase {
public:
UiText(string_view text, SDL_Rect rect, UiFlags flags = UiFlags::ColorDialogWhite)
UiText(std::string_view text, SDL_Rect rect, UiFlags flags = UiFlags::ColorDialogWhite)
: UiItemBase(UiType::Text, rect, flags)
, text_(text)
{
}
[[nodiscard]] string_view GetText() const
[[nodiscard]] std::string_view GetText() const
{
return text_;
}
private:
string_view text_;
std::string_view text_;
};
//=============================================================================
@ -303,7 +303,7 @@ class UiButton : public UiItemBase {
public:
using Callback = void (*)();
UiButton(string_view text, Callback action, SDL_Rect rect, UiFlags flags = UiFlags::None)
UiButton(std::string_view text, Callback action, SDL_Rect rect, UiFlags flags = UiFlags::None)
: UiItemBase(UiType::Button, rect, flags)
, text_(text)
, action_(action)
@ -311,7 +311,7 @@ public:
{
}
[[nodiscard]] string_view GetText() const
[[nodiscard]] std::string_view GetText() const
{
return text_;
}
@ -337,7 +337,7 @@ public:
}
private:
string_view text_;
std::string_view text_;
Callback action_;
// State
@ -348,14 +348,14 @@ private:
class UiListItem {
public:
UiListItem(string_view text = "", int value = 0, UiFlags uiFlags = UiFlags::None)
UiListItem(std::string_view text = "", int value = 0, UiFlags uiFlags = UiFlags::None)
: m_text(text)
, m_value(value)
, uiFlags(uiFlags)
{
}
UiListItem(string_view text, std::vector<DrawStringFormatArg> &args, int value = 0, UiFlags uiFlags = UiFlags::None)
UiListItem(std::string_view text, std::vector<DrawStringFormatArg> &args, int value = 0, UiFlags uiFlags = UiFlags::None)
: m_text(text)
, args(args)
, m_value(value)
@ -364,7 +364,7 @@ public:
}
// private:
string_view m_text;
std::string_view m_text;
std::vector<DrawStringFormatArg> args;
int m_value;
UiFlags uiFlags;

8
Source/appfat.cpp

@ -46,7 +46,7 @@ void FreeDlg()
} // namespace
void app_fatal(string_view str)
void app_fatal(std::string_view str)
{
FreeDlg();
UiErrorOkDialog(_("Error"), str);
@ -60,7 +60,7 @@ void assert_fail(int nLineNo, const char *pszFile, const char *pszFail)
}
#endif
void ErrDlg(const char *title, string_view error, string_view logFilePath, int logLineNr)
void ErrDlg(const char *title, std::string_view error, std::string_view logFilePath, int logLineNr)
{
FreeDlg();
@ -70,7 +70,7 @@ void ErrDlg(const char *title, string_view error, string_view logFilePath, int l
diablo_quit(1);
}
void InsertCDDlg(string_view archiveName)
void InsertCDDlg(std::string_view archiveName)
{
std::string text = fmt::format(
fmt::runtime(_("Unable to open main data archive ({:s}).\n"
@ -82,7 +82,7 @@ void InsertCDDlg(string_view archiveName)
diablo_quit(1);
}
void DirErrorDlg(string_view error)
void DirErrorDlg(std::string_view error)
{
std::string text = fmt::format(fmt::runtime(_(/* TRANSLATORS: Error when Program is not allowed to write data */ "Unable to write to location:\n{:s}")), error);

11
Source/appfat.h

@ -5,10 +5,11 @@
*/
#pragma once
#include <string_view>
#include <SDL.h>
#include "utils/attributes.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -26,7 +27,7 @@ namespace devilution {
* @brief Terminates the game and displays an error message box.
* @param str Error message.
*/
[[noreturn]] void app_fatal(string_view str);
[[noreturn]] void app_fatal(std::string_view str);
#ifdef _DEBUG
/**
@ -40,16 +41,16 @@ namespace devilution {
/**
* @brief Terminates the game and displays an error dialog box based on the given dialog_id.
*/
[[noreturn]] void ErrDlg(const char *title, string_view error, string_view logFilePath, int logLineNr);
[[noreturn]] void ErrDlg(const char *title, std::string_view error, std::string_view logFilePath, int logLineNr);
/**
* @brief Terminates the game with an insert CD error dialog.
*/
[[noreturn]] void InsertCDDlg(string_view archiveName);
[[noreturn]] void InsertCDDlg(std::string_view archiveName);
/**
* @brief Terminates the game with a read-only directory error dialog.
*/
[[noreturn]] void DirErrorDlg(string_view error);
[[noreturn]] void DirErrorDlg(std::string_view error);
} // namespace devilution

2
Source/automap.cpp

@ -762,7 +762,7 @@ void DrawAutomapText(const Surface &out)
DrawString(out, description, linePosition);
linePosition.y += 15;
string_view difficulty;
std::string_view difficulty;
switch (sgGameInitInfo.nDifficulty) {
case DIFF_NORMAL:
difficulty = _("Normal");

34
Source/control.cpp

@ -338,12 +338,12 @@ struct TextCmdItem {
const std::string text;
const std::string description;
const std::string requiredParameter;
std::string (*actionProc)(const string_view);
std::string (*actionProc)(const std::string_view);
};
extern std::vector<TextCmdItem> TextCmdList;
std::string TextCmdHelp(const string_view parameter)
std::string TextCmdHelp(const std::string_view parameter)
{
if (parameter.empty()) {
std::string ret;
@ -375,7 +375,7 @@ const dungeon_type DungeonTypeForArena[] = {
dungeon_type::DTYPE_HELL, // SL_ARENA_CIRCLE_OF_LIFE
};
std::string TextCmdArena(const string_view parameter)
std::string TextCmdArena(const std::string_view parameter)
{
std::string ret;
if (!gbIsMultiplayer) {
@ -407,7 +407,7 @@ std::string TextCmdArena(const string_view parameter)
return ret;
}
std::string TextCmdArenaPot(const string_view parameter)
std::string TextCmdArenaPot(const std::string_view parameter)
{
std::string ret;
if (!gbIsMultiplayer) {
@ -432,7 +432,7 @@ std::string TextCmdArenaPot(const string_view parameter)
return ret;
}
std::string TextCmdInspect(const string_view parameter)
std::string TextCmdInspect(const std::string_view parameter)
{
std::string ret;
if (!gbIsMultiplayer) {
@ -486,9 +486,9 @@ bool IsQuestEnabled(const Quest &quest)
}
}
std::string TextCmdLevelSeed(const string_view parameter)
std::string TextCmdLevelSeed(const std::string_view parameter)
{
string_view levelType = setlevel ? "set level" : "dungeon level";
std::string_view levelType = setlevel ? "set level" : "dungeon level";
char gameId[] = {
static_cast<char>((sgGameInitInfo.programid >> 24) & 0xFF),
@ -498,8 +498,8 @@ std::string TextCmdLevelSeed(const string_view parameter)
'\0'
};
string_view mode = gbIsMultiplayer ? "MP" : "SP";
string_view questPool = UseMultiplayerQuests() ? "MP" : "Full";
std::string_view mode = gbIsMultiplayer ? "MP" : "SP";
std::string_view questPool = UseMultiplayerQuests() ? "MP" : "Full";
uint32_t questFlags = 0;
for (const Quest &quest : Quests) {
@ -531,7 +531,7 @@ std::vector<TextCmdItem> TextCmdList = {
{ N_("/seedinfo"), N_("Show seed infos for current level."), "", &TextCmdLevelSeed },
};
bool CheckTextCommand(const string_view text)
bool CheckTextCommand(const std::string_view text)
{
if (text.size() < 1 || text[0] != '/')
return false;
@ -543,7 +543,7 @@ bool CheckTextCommand(const string_view text)
}
TextCmdItem &textCmd = *textCmdIterator;
string_view parameter = "";
std::string_view parameter = "";
if (text.length() > (textCmd.text.length() + 1))
parameter = text.substr(textCmd.text.length() + 1);
const std::string result = textCmd.actionProc(parameter);
@ -742,7 +742,7 @@ void ToggleCharPanel()
OpenCharPanel();
}
void AddPanelString(string_view str)
void AddPanelString(std::string_view str)
{
if (InfoString.empty())
InfoString = str;
@ -810,7 +810,7 @@ void DrawFlaskValues(const Surface &out, Point pos, int currValue, int maxValue)
{
UiFlags color = (currValue > 0 ? (currValue == maxValue ? UiFlags::ColorGold : UiFlags::ColorWhite) : UiFlags::ColorRed);
auto drawStringWithShadow = [out, color](string_view text, Point pos) {
auto drawStringWithShadow = [out, color](std::string_view text, Point pos) {
DrawString(out, text, pos + Displacement { -1, -1 }, UiFlags::ColorBlack | UiFlags::KerningFitSpacing, 0);
DrawString(out, text, pos, color | UiFlags::KerningFitSpacing, 0);
};
@ -1198,13 +1198,13 @@ void DrawInfoBox(const Surface &out)
PrintMonstHistory(monster.type().type);
}
} else if (pcursitem == -1) {
InfoString = string_view(Towners[pcursmonst].name);
InfoString = std::string_view(Towners[pcursmonst].name);
}
}
if (pcursplr != -1) {
InfoColor = UiFlags::ColorWhitegold;
auto &target = Players[pcursplr];
InfoString = string_view(target._pName);
InfoString = std::string_view(target._pName);
AddPanelString(fmt::format(fmt::runtime(_("{:s}, Level: {:d}")), _(PlayersData[static_cast<std::size_t>(target._pClass)].className), target._pLevel));
AddPanelString(fmt::format(fmt::runtime(_("Hit Points {:d} of {:d}")), target._pHitPoints >> 6, target._pMaxHP >> 6));
}
@ -1537,7 +1537,7 @@ bool IsTalkActive()
return true;
}
void control_new_text(string_view text)
void control_new_text(std::string_view text)
{
strncat(TalkMessage, text.data(), sizeof(TalkMessage) - strlen(TalkMessage) - 1);
}
@ -1601,7 +1601,7 @@ void CloseGoldDrop()
SDL_StopTextInput();
}
void GoldDropNewText(string_view text)
void GoldDropNewText(std::string_view text)
{
for (char vkey : text) {
int digit = vkey - '0';

8
Source/control.h

@ -8,6 +8,7 @@
#include <cstddef>
#include <cstdint>
#include <optional>
#include <string_view>
#include <SDL.h>
@ -24,7 +25,6 @@
#include "spelldat.h"
#include "spells.h"
#include "utils/attributes.h"
#include "utils/stdcompat/string_view.hpp"
#include "utils/string_or_view.hpp"
#include "utils/ui_fwd.h"
@ -81,7 +81,7 @@ void SetSpell();
void SetSpeedSpell(size_t slot);
void ToggleSpell(size_t slot);
void AddPanelString(string_view str);
void AddPanelString(std::string_view str);
void AddPanelString(std::string &&str);
void DrawPanelBox(const Surface &out, SDL_Rect srcRect, Point targetPosition);
Point GetPanelPosition(UiPanels panel, Point offset = { 0, 0 });
@ -187,11 +187,11 @@ void control_release_talk_btn();
void control_type_message();
void control_reset_talk();
bool IsTalkActive();
void control_new_text(string_view text);
void control_new_text(std::string_view text);
bool control_presskeys(SDL_Keycode vkey);
void DiabloHotkeyMsg(uint32_t dwMsg);
void CloseGoldDrop();
void GoldDropNewText(string_view text);
void GoldDropNewText(std::string_view text);
extern Rectangle ChrBtnsRect[4];
} // namespace devilution

224
Source/controls/controller_buttons.cpp

@ -4,116 +4,116 @@
namespace devilution {
namespace controller_button_icon {
const string_view Playstation_Triangle = "\uE000";
const string_view Playstation_Square = "\uE001";
const string_view Playstation_X = "\uE002";
const string_view Playstation_Circle = "\uE003";
const string_view Playstation_Options = "\uE004";
const string_view Playstation_Share = "\uE005";
const string_view Playstation_L2 = "\uE006";
const string_view Playstation_R2 = "\uE007";
const string_view Playstation_L1 = "\uE008";
const string_view Playstation_R1 = "\uE009";
const string_view Playstation_DPad_Up = "\uE00A";
const string_view Playstation_DPad_Right = "\uE00B";
const string_view Playstation_DPad_Down = "\uE00C";
const string_view Playstation_DPad_Left = "\uE00D";
const string_view Playstation_LStick_NW = "\uE00E";
const string_view Playstation_LStick_W = "\uE00F";
const string_view Playstation_LStick_SW = "\uE010";
const string_view Playstation_LStick_N = "\uE011";
const string_view Playstation_LStick = "\uE012";
const string_view Playstation_LStick_S = "\uE013";
const string_view Playstation_LStick_NE = "\uE014";
const string_view Playstation_LStick_E = "\uE015";
const string_view Playstation_LStick_SE = "\uE016";
const string_view Playstation_L3 = "\uE017";
const string_view Playstation_RStick_NW = "\uE018";
const string_view Playstation_RStick_W = "\uE019";
const string_view Playstation_RStick_SW = "\uE01A";
const string_view Playstation_RStick_N = "\uE01B";
const string_view Playstation_RStick = "\uE01C";
const string_view Playstation_RStick_S = "\uE01D";
const string_view Playstation_RStick_NE = "\uE01E";
const string_view Playstation_RStick_E = "\uE01F";
const string_view Playstation_RStick_SE = "\uE020";
const string_view Playstation_R3 = "\uE021";
const string_view Playstation_Touchpad = "\uE022";
const string_view Nintendo_X = "\uE023";
const string_view Nintendo_Y = "\uE024";
const string_view Nintendo_B = "\uE025";
const string_view Nintendo_A = "\uE026";
const string_view Nintendo_Plus = "\uE027";
const string_view Nintendo_Minus = "\uE028";
const string_view Nintendo_ZL = "\uE029";
const string_view Nintendo_ZR = "\uE02A";
const string_view Nintendo_L = "\uE02B";
const string_view Nintendo_R = "\uE02C";
const string_view Nintendo_DPad_Up = "\uE02D";
const string_view Nintendo_DPad_Right = "\uE02E";
const string_view Nintendo_DPad_Down = "\uE02F";
const string_view Nintendo_DPad_Left = "\uE030";
const string_view Nintendo_LStick_NW = "\uE031";
const string_view Nintendo_LStick_W = "\uE032";
const string_view Nintendo_LStick_SW = "\uE033";
const string_view Nintendo_LStick_N = "\uE034";
const string_view Nintendo_LStick = "\uE035";
const string_view Nintendo_LStick_S = "\uE036";
const string_view Nintendo_LStick_NE = "\uE037";
const string_view Nintendo_LStick_E = "\uE038";
const string_view Nintendo_LStick_SE = "\uE039";
const string_view Nintendo_LStick_Click = "\uE03A";
const string_view Nintendo_RStick_NW = "\uE03B";
const string_view Nintendo_RStick_W = "\uE03C";
const string_view Nintendo_RStick_SW = "\uE03D";
const string_view Nintendo_RStick_N = "\uE03E";
const string_view Nintendo_RStick = "\uE03F";
const string_view Nintendo_RStick_S = "\uE040";
const string_view Nintendo_RStick_NE = "\uE041";
const string_view Nintendo_RStick_E = "\uE042";
const string_view Nintendo_RStick_SE = "\uE043";
const string_view Nintendo_RStick_Click = "\uE044";
const string_view Nintendo_Home = "\uE045";
const string_view Nintendo_Screenshot = "\uE046";
const string_view Nintendo_SL = "\uE047";
const string_view Nintendo_SR = "\uE048";
const string_view Xbox_Y = "\uE049";
const string_view Xbox_X = "\uE04A";
const string_view Xbox_A = "\uE04B";
const string_view Xbox_B = "\uE04C";
const string_view Xbox_Menu = "\uE04D";
const string_view Xbox_View = "\uE04E";
const string_view Xbox_LT = "\uE04F";
const string_view Xbox_RT = "\uE050";
const string_view Xbox_LB = "\uE051";
const string_view Xbox_RB = "\uE052";
const string_view Xbox_DPad_Up = "\uE053";
const string_view Xbox_DPad_Right = "\uE054";
const string_view Xbox_DPad_Down = "\uE055";
const string_view Xbox_DPad_Left = "\uE056";
const string_view Xbox_LStick_NW = "\uE057";
const string_view Xbox_LStick_W = "\uE058";
const string_view Xbox_LStick_SW = "\uE059";
const string_view Xbox_LStick_N = "\uE05A";
const string_view Xbox_LStick = "\uE05B";
const string_view Xbox_LStick_NE = "\uE05C";
const string_view Xbox_LStick_E = "\uE05D";
const string_view Xbox_LStick_SE = "\uE05E";
const string_view Xbox_LStick_Click = "\uE05F";
const string_view Xbox_RStick_NW = "\uE060";
const string_view Xbox_RStick_W = "\uE061";
const string_view Xbox_RStick_SW = "\uE062";
const string_view Xbox_RStick_N = "\uE063";
const string_view Xbox_RStick = "\uE064";
const string_view Xbox_RStick_S = "\uE065";
const string_view Xbox_RStick_NE = "\uE066";
const string_view Xbox_RStick_E = "\uE067";
const string_view Xbox_RStick_SE = "\uE068";
const string_view Xbox_RStick_Click = "\uE069";
const string_view Xbox_Xbox = "\uE06A";
const std::string_view Playstation_Triangle = "\uE000";
const std::string_view Playstation_Square = "\uE001";
const std::string_view Playstation_X = "\uE002";
const std::string_view Playstation_Circle = "\uE003";
const std::string_view Playstation_Options = "\uE004";
const std::string_view Playstation_Share = "\uE005";
const std::string_view Playstation_L2 = "\uE006";
const std::string_view Playstation_R2 = "\uE007";
const std::string_view Playstation_L1 = "\uE008";
const std::string_view Playstation_R1 = "\uE009";
const std::string_view Playstation_DPad_Up = "\uE00A";
const std::string_view Playstation_DPad_Right = "\uE00B";
const std::string_view Playstation_DPad_Down = "\uE00C";
const std::string_view Playstation_DPad_Left = "\uE00D";
const std::string_view Playstation_LStick_NW = "\uE00E";
const std::string_view Playstation_LStick_W = "\uE00F";
const std::string_view Playstation_LStick_SW = "\uE010";
const std::string_view Playstation_LStick_N = "\uE011";
const std::string_view Playstation_LStick = "\uE012";
const std::string_view Playstation_LStick_S = "\uE013";
const std::string_view Playstation_LStick_NE = "\uE014";
const std::string_view Playstation_LStick_E = "\uE015";
const std::string_view Playstation_LStick_SE = "\uE016";
const std::string_view Playstation_L3 = "\uE017";
const std::string_view Playstation_RStick_NW = "\uE018";
const std::string_view Playstation_RStick_W = "\uE019";
const std::string_view Playstation_RStick_SW = "\uE01A";
const std::string_view Playstation_RStick_N = "\uE01B";
const std::string_view Playstation_RStick = "\uE01C";
const std::string_view Playstation_RStick_S = "\uE01D";
const std::string_view Playstation_RStick_NE = "\uE01E";
const std::string_view Playstation_RStick_E = "\uE01F";
const std::string_view Playstation_RStick_SE = "\uE020";
const std::string_view Playstation_R3 = "\uE021";
const std::string_view Playstation_Touchpad = "\uE022";
const std::string_view Nintendo_X = "\uE023";
const std::string_view Nintendo_Y = "\uE024";
const std::string_view Nintendo_B = "\uE025";
const std::string_view Nintendo_A = "\uE026";
const std::string_view Nintendo_Plus = "\uE027";
const std::string_view Nintendo_Minus = "\uE028";
const std::string_view Nintendo_ZL = "\uE029";
const std::string_view Nintendo_ZR = "\uE02A";
const std::string_view Nintendo_L = "\uE02B";
const std::string_view Nintendo_R = "\uE02C";
const std::string_view Nintendo_DPad_Up = "\uE02D";
const std::string_view Nintendo_DPad_Right = "\uE02E";
const std::string_view Nintendo_DPad_Down = "\uE02F";
const std::string_view Nintendo_DPad_Left = "\uE030";
const std::string_view Nintendo_LStick_NW = "\uE031";
const std::string_view Nintendo_LStick_W = "\uE032";
const std::string_view Nintendo_LStick_SW = "\uE033";
const std::string_view Nintendo_LStick_N = "\uE034";
const std::string_view Nintendo_LStick = "\uE035";
const std::string_view Nintendo_LStick_S = "\uE036";
const std::string_view Nintendo_LStick_NE = "\uE037";
const std::string_view Nintendo_LStick_E = "\uE038";
const std::string_view Nintendo_LStick_SE = "\uE039";
const std::string_view Nintendo_LStick_Click = "\uE03A";
const std::string_view Nintendo_RStick_NW = "\uE03B";
const std::string_view Nintendo_RStick_W = "\uE03C";
const std::string_view Nintendo_RStick_SW = "\uE03D";
const std::string_view Nintendo_RStick_N = "\uE03E";
const std::string_view Nintendo_RStick = "\uE03F";
const std::string_view Nintendo_RStick_S = "\uE040";
const std::string_view Nintendo_RStick_NE = "\uE041";
const std::string_view Nintendo_RStick_E = "\uE042";
const std::string_view Nintendo_RStick_SE = "\uE043";
const std::string_view Nintendo_RStick_Click = "\uE044";
const std::string_view Nintendo_Home = "\uE045";
const std::string_view Nintendo_Screenshot = "\uE046";
const std::string_view Nintendo_SL = "\uE047";
const std::string_view Nintendo_SR = "\uE048";
const std::string_view Xbox_Y = "\uE049";
const std::string_view Xbox_X = "\uE04A";
const std::string_view Xbox_A = "\uE04B";
const std::string_view Xbox_B = "\uE04C";
const std::string_view Xbox_Menu = "\uE04D";
const std::string_view Xbox_View = "\uE04E";
const std::string_view Xbox_LT = "\uE04F";
const std::string_view Xbox_RT = "\uE050";
const std::string_view Xbox_LB = "\uE051";
const std::string_view Xbox_RB = "\uE052";
const std::string_view Xbox_DPad_Up = "\uE053";
const std::string_view Xbox_DPad_Right = "\uE054";
const std::string_view Xbox_DPad_Down = "\uE055";
const std::string_view Xbox_DPad_Left = "\uE056";
const std::string_view Xbox_LStick_NW = "\uE057";
const std::string_view Xbox_LStick_W = "\uE058";
const std::string_view Xbox_LStick_SW = "\uE059";
const std::string_view Xbox_LStick_N = "\uE05A";
const std::string_view Xbox_LStick = "\uE05B";
const std::string_view Xbox_LStick_NE = "\uE05C";
const std::string_view Xbox_LStick_E = "\uE05D";
const std::string_view Xbox_LStick_SE = "\uE05E";
const std::string_view Xbox_LStick_Click = "\uE05F";
const std::string_view Xbox_RStick_NW = "\uE060";
const std::string_view Xbox_RStick_W = "\uE061";
const std::string_view Xbox_RStick_SW = "\uE062";
const std::string_view Xbox_RStick_N = "\uE063";
const std::string_view Xbox_RStick = "\uE064";
const std::string_view Xbox_RStick_S = "\uE065";
const std::string_view Xbox_RStick_NE = "\uE066";
const std::string_view Xbox_RStick_E = "\uE067";
const std::string_view Xbox_RStick_SE = "\uE068";
const std::string_view Xbox_RStick_Click = "\uE069";
const std::string_view Xbox_Xbox = "\uE06A";
} // namespace controller_button_icon
string_view ToPlayStationIcon(ControllerButton button)
std::string_view ToPlayStationIcon(ControllerButton button)
{
switch (button) {
case devilution::ControllerButton_BUTTON_A:
@ -153,7 +153,7 @@ string_view ToPlayStationIcon(ControllerButton button)
}
}
string_view ToNintendoIcon(ControllerButton button)
std::string_view ToNintendoIcon(ControllerButton button)
{
switch (button) {
case devilution::ControllerButton_BUTTON_A:
@ -193,7 +193,7 @@ string_view ToNintendoIcon(ControllerButton button)
}
}
string_view ToXboxIcon(ControllerButton button)
std::string_view ToXboxIcon(ControllerButton button)
{
switch (button) {
case devilution::ControllerButton_BUTTON_A:
@ -233,7 +233,7 @@ string_view ToXboxIcon(ControllerButton button)
}
}
string_view ToGenericButtonText(ControllerButton button)
std::string_view ToGenericButtonText(ControllerButton button)
{
switch (button) {
case devilution::ControllerButton_BUTTON_A:
@ -277,7 +277,7 @@ string_view ToGenericButtonText(ControllerButton button)
}
}
string_view ToString(ControllerButton button)
std::string_view ToString(ControllerButton button)
{
switch (GamepadType) {
case devilution::GamepadLayout::PlayStation:

227
Source/controls/controller_buttons.h

@ -3,8 +3,7 @@
#include <cstdint>
#include <functional>
#include "utils/stdcompat/string_view.hpp"
#include <string_view>
namespace devilution {
@ -65,119 +64,119 @@ inline bool IsDPadButton(ControllerButton button)
}
namespace controller_button_icon {
extern const string_view Playstation_Triangle;
extern const string_view Playstation_Square;
extern const string_view Playstation_X;
extern const string_view Playstation_Circle;
extern const string_view Playstation_Options;
extern const string_view Playstation_Share;
extern const string_view Playstation_L2;
extern const string_view Playstation_R2;
extern const string_view Playstation_L1;
extern const string_view Playstation_R1;
extern const string_view Playstation_DPad_Up;
extern const string_view Playstation_DPad_Right;
extern const string_view Playstation_DPad_Down;
extern const string_view Playstation_DPad_Left;
extern const string_view Playstation_LStick_NW;
extern const string_view Playstation_LStick_W;
extern const string_view Playstation_LStick_SW;
extern const string_view Playstation_LStick_N;
extern const string_view Playstation_LStick;
extern const string_view Playstation_LStick_S;
extern const string_view Playstation_LStick_NE;
extern const string_view Playstation_LStick_E;
extern const string_view Playstation_LStick_SE;
extern const string_view Playstation_L3;
extern const string_view Playstation_RStick_NW;
extern const string_view Playstation_RStick_W;
extern const string_view Playstation_RStick_SW;
extern const string_view Playstation_RStick_N;
extern const string_view Playstation_RStick;
extern const string_view Playstation_RStick_S;
extern const string_view Playstation_RStick_NE;
extern const string_view Playstation_RStick_E;
extern const string_view Playstation_RStick_SE;
extern const string_view Playstation_R3;
extern const string_view Playstation_Touchpad;
extern const string_view Nintendo_X;
extern const string_view Nintendo_Y;
extern const string_view Nintendo_B;
extern const string_view Nintendo_A;
extern const string_view Nintendo_Plus;
extern const string_view Nintendo_Minus;
extern const string_view Nintendo_ZL;
extern const string_view Nintendo_ZR;
extern const string_view Nintendo_L;
extern const string_view Nintendo_R;
extern const string_view Nintendo_DPad_Up;
extern const string_view Nintendo_DPad_Right;
extern const string_view Nintendo_DPad_Down;
extern const string_view Nintendo_DPad_Left;
extern const string_view Nintendo_LStick_NW;
extern const string_view Nintendo_LStick_W;
extern const string_view Nintendo_LStick_SW;
extern const string_view Nintendo_LStick_N;
extern const string_view Nintendo_LStick;
extern const string_view Nintendo_LStick_S;
extern const string_view Nintendo_LStick_NE;
extern const string_view Nintendo_LStick_E;
extern const string_view Nintendo_LStick_SE;
extern const string_view Nintendo_LStick_Click;
extern const string_view Nintendo_RStick_NW;
extern const string_view Nintendo_RStick_W;
extern const string_view Nintendo_RStick_SW;
extern const string_view Nintendo_RStick_N;
extern const string_view Nintendo_RStick;
extern const string_view Nintendo_RStick_S;
extern const string_view Nintendo_RStick_NE;
extern const string_view Nintendo_RStick_E;
extern const string_view Nintendo_RStick_SE;
extern const string_view Nintendo_RStick_Click;
extern const string_view Nintendo_Home;
extern const string_view Nintendo_Screenshot;
extern const string_view Nintendo_SL;
extern const string_view Nintendo_SR;
extern const string_view Xbox_Y;
extern const string_view Xbox_X;
extern const string_view Xbox_A;
extern const string_view Xbox_B;
extern const string_view Xbox_Menu;
extern const string_view Xbox_View;
extern const string_view Xbox_LT;
extern const string_view Xbox_RT;
extern const string_view Xbox_LB;
extern const string_view Xbox_RB;
extern const string_view Xbox_DPad_Up;
extern const string_view Xbox_DPad_Right;
extern const string_view Xbox_DPad_Down;
extern const string_view Xbox_DPad_Left;
extern const string_view Xbox_LStick_NW;
extern const string_view Xbox_LStick_W;
extern const string_view Xbox_LStick_SW;
extern const string_view Xbox_LStick_N;
extern const string_view Xbox_LStick;
extern const string_view Xbox_LStick_NE;
extern const string_view Xbox_LStick_E;
extern const string_view Xbox_LStick_SE;
extern const string_view Xbox_LStick_Click;
extern const string_view Xbox_RStick_NW;
extern const string_view Xbox_RStick_W;
extern const string_view Xbox_RStick_SW;
extern const string_view Xbox_RStick_N;
extern const string_view Xbox_RStick;
extern const string_view Xbox_RStick_S;
extern const string_view Xbox_RStick_NE;
extern const string_view Xbox_RStick_E;
extern const string_view Xbox_RStick_SE;
extern const string_view Xbox_RStick_Click;
extern const string_view Xbox_Xbox;
extern const std::string_view Playstation_Triangle;
extern const std::string_view Playstation_Square;
extern const std::string_view Playstation_X;
extern const std::string_view Playstation_Circle;
extern const std::string_view Playstation_Options;
extern const std::string_view Playstation_Share;
extern const std::string_view Playstation_L2;
extern const std::string_view Playstation_R2;
extern const std::string_view Playstation_L1;
extern const std::string_view Playstation_R1;
extern const std::string_view Playstation_DPad_Up;
extern const std::string_view Playstation_DPad_Right;
extern const std::string_view Playstation_DPad_Down;
extern const std::string_view Playstation_DPad_Left;
extern const std::string_view Playstation_LStick_NW;
extern const std::string_view Playstation_LStick_W;
extern const std::string_view Playstation_LStick_SW;
extern const std::string_view Playstation_LStick_N;
extern const std::string_view Playstation_LStick;
extern const std::string_view Playstation_LStick_S;
extern const std::string_view Playstation_LStick_NE;
extern const std::string_view Playstation_LStick_E;
extern const std::string_view Playstation_LStick_SE;
extern const std::string_view Playstation_L3;
extern const std::string_view Playstation_RStick_NW;
extern const std::string_view Playstation_RStick_W;
extern const std::string_view Playstation_RStick_SW;
extern const std::string_view Playstation_RStick_N;
extern const std::string_view Playstation_RStick;
extern const std::string_view Playstation_RStick_S;
extern const std::string_view Playstation_RStick_NE;
extern const std::string_view Playstation_RStick_E;
extern const std::string_view Playstation_RStick_SE;
extern const std::string_view Playstation_R3;
extern const std::string_view Playstation_Touchpad;
extern const std::string_view Nintendo_X;
extern const std::string_view Nintendo_Y;
extern const std::string_view Nintendo_B;
extern const std::string_view Nintendo_A;
extern const std::string_view Nintendo_Plus;
extern const std::string_view Nintendo_Minus;
extern const std::string_view Nintendo_ZL;
extern const std::string_view Nintendo_ZR;
extern const std::string_view Nintendo_L;
extern const std::string_view Nintendo_R;
extern const std::string_view Nintendo_DPad_Up;
extern const std::string_view Nintendo_DPad_Right;
extern const std::string_view Nintendo_DPad_Down;
extern const std::string_view Nintendo_DPad_Left;
extern const std::string_view Nintendo_LStick_NW;
extern const std::string_view Nintendo_LStick_W;
extern const std::string_view Nintendo_LStick_SW;
extern const std::string_view Nintendo_LStick_N;
extern const std::string_view Nintendo_LStick;
extern const std::string_view Nintendo_LStick_S;
extern const std::string_view Nintendo_LStick_NE;
extern const std::string_view Nintendo_LStick_E;
extern const std::string_view Nintendo_LStick_SE;
extern const std::string_view Nintendo_LStick_Click;
extern const std::string_view Nintendo_RStick_NW;
extern const std::string_view Nintendo_RStick_W;
extern const std::string_view Nintendo_RStick_SW;
extern const std::string_view Nintendo_RStick_N;
extern const std::string_view Nintendo_RStick;
extern const std::string_view Nintendo_RStick_S;
extern const std::string_view Nintendo_RStick_NE;
extern const std::string_view Nintendo_RStick_E;
extern const std::string_view Nintendo_RStick_SE;
extern const std::string_view Nintendo_RStick_Click;
extern const std::string_view Nintendo_Home;
extern const std::string_view Nintendo_Screenshot;
extern const std::string_view Nintendo_SL;
extern const std::string_view Nintendo_SR;
extern const std::string_view Xbox_Y;
extern const std::string_view Xbox_X;
extern const std::string_view Xbox_A;
extern const std::string_view Xbox_B;
extern const std::string_view Xbox_Menu;
extern const std::string_view Xbox_View;
extern const std::string_view Xbox_LT;
extern const std::string_view Xbox_RT;
extern const std::string_view Xbox_LB;
extern const std::string_view Xbox_RB;
extern const std::string_view Xbox_DPad_Up;
extern const std::string_view Xbox_DPad_Right;
extern const std::string_view Xbox_DPad_Down;
extern const std::string_view Xbox_DPad_Left;
extern const std::string_view Xbox_LStick_NW;
extern const std::string_view Xbox_LStick_W;
extern const std::string_view Xbox_LStick_SW;
extern const std::string_view Xbox_LStick_N;
extern const std::string_view Xbox_LStick;
extern const std::string_view Xbox_LStick_NE;
extern const std::string_view Xbox_LStick_E;
extern const std::string_view Xbox_LStick_SE;
extern const std::string_view Xbox_LStick_Click;
extern const std::string_view Xbox_RStick_NW;
extern const std::string_view Xbox_RStick_W;
extern const std::string_view Xbox_RStick_SW;
extern const std::string_view Xbox_RStick_N;
extern const std::string_view Xbox_RStick;
extern const std::string_view Xbox_RStick_S;
extern const std::string_view Xbox_RStick_NE;
extern const std::string_view Xbox_RStick_E;
extern const std::string_view Xbox_RStick_SE;
extern const std::string_view Xbox_RStick_Click;
extern const std::string_view Xbox_Xbox;
} // namespace controller_button_icon
string_view ToPlayStationIcon(ControllerButton button);
string_view ToNintendoIcon(ControllerButton button);
string_view ToXboxIcon(ControllerButton button);
string_view ToGenericButtonText(ControllerButton button);
string_view ToString(ControllerButton button);
std::string_view ToPlayStationIcon(ControllerButton button);
std::string_view ToNintendoIcon(ControllerButton button);
std::string_view ToXboxIcon(ControllerButton button);
std::string_view ToGenericButtonText(ControllerButton button);
std::string_view ToString(ControllerButton button);
} // namespace devilution

10
Source/controls/controller_motion.cpp

@ -70,7 +70,7 @@ void ScaleJoystickAxes(float *x, float *y, float deadzone)
bool IsMovementOverriddenByPadmapper(ControllerButton button)
{
ControllerButtonEvent releaseEvent { button, true };
string_view actionName = sgOptions.Padmapper.ActionNameTriggeredByButtonEvent(releaseEvent);
std::string_view actionName = sgOptions.Padmapper.ActionNameTriggeredByButtonEvent(releaseEvent);
ControllerButtonCombo buttonCombo = sgOptions.Padmapper.ButtonComboForAction(actionName);
return buttonCombo.modifier != ControllerButton_NONE;
}
@ -78,12 +78,12 @@ bool IsMovementOverriddenByPadmapper(ControllerButton button)
bool TriggersQuickSpellAction(ControllerButton button)
{
ControllerButtonEvent releaseEvent { button, true };
string_view actionName = sgOptions.Padmapper.ActionNameTriggeredByButtonEvent(releaseEvent);
std::string_view actionName = sgOptions.Padmapper.ActionNameTriggeredByButtonEvent(releaseEvent);
string_view prefix { "QuickSpell" };
std::string_view prefix { "QuickSpell" };
if (actionName.size() < prefix.size())
return false;
string_view truncatedActionName { actionName.data(), prefix.size() };
std::string_view truncatedActionName { actionName.data(), prefix.size() };
return truncatedActionName == prefix;
}
@ -248,7 +248,7 @@ void SimulateRightStickWithPadmapper(ControllerButtonEvent ctrlEvent)
if (!ctrlEvent.up && ctrlEvent.button == SuppressedButton)
return;
string_view actionName = sgOptions.Padmapper.ActionNameTriggeredByButtonEvent(ctrlEvent);
std::string_view actionName = sgOptions.Padmapper.ActionNameTriggeredByButtonEvent(ctrlEvent);
bool upTriggered = actionName == "MouseUp";
bool downTriggered = actionName == "MouseDown";
bool leftTriggered = actionName == "MouseLeft";

2
Source/controls/game_controls.cpp

@ -335,7 +335,7 @@ bool IsSimulatedMouseClickBinding(ControllerButtonEvent ctrlEvent)
return false;
if (!ctrlEvent.up && ctrlEvent.button == SuppressedButton)
return false;
string_view actionName = sgOptions.Padmapper.ActionNameTriggeredByButtonEvent(ctrlEvent);
std::string_view actionName = sgOptions.Padmapper.ActionNameTriggeredByButtonEvent(ctrlEvent);
return IsAnyOf(actionName, "LeftMouseClick1", "LeftMouseClick2", "RightMouseClick1", "RightMouseClick2");
}

4
Source/controls/plrctrls.cpp

@ -1484,7 +1484,7 @@ bool ContinueSimulatedMouseEvent(const SDL_Event &event, const ControllerButtonE
return SimulatingMouseWithPadmapper || IsSimulatedMouseClickBinding(gamepadEvent);
}
string_view ControlTypeToString(ControlTypes controlType)
std::string_view ControlTypeToString(ControlTypes controlType)
{
switch (controlType) {
case ControlTypes::None:
@ -1514,7 +1514,7 @@ void LogControlDeviceAndModeChange(ControlTypes newControlDevice, ControlTypes n
}
#ifndef USE_SDL1
string_view GamepadTypeToString(GamepadLayout gamepadLayout)
std::string_view GamepadTypeToString(GamepadLayout gamepadLayout)
{
switch (gamepadLayout) {
case GamepadLayout::Nintendo:

112
Source/debug.cpp

@ -120,15 +120,15 @@ void PrintDebugMonster(const Monster &monster)
}
struct DebugCmdItem {
const string_view text;
const string_view description;
const string_view requiredParameter;
std::string (*actionProc)(const string_view);
const std::string_view text;
const std::string_view description;
const std::string_view requiredParameter;
std::string (*actionProc)(const std::string_view);
};
extern std::vector<DebugCmdItem> DebugCmdList;
std::string DebugCmdHelp(const string_view parameter)
std::string DebugCmdHelp(const std::string_view parameter)
{
if (parameter.empty()) {
std::string ret = "Available Debug Commands: ";
@ -151,7 +151,7 @@ std::string DebugCmdHelp(const string_view parameter)
return StrCat("Description: ", dbgCmdItem.description, "\nParameters: ", dbgCmdItem.requiredParameter);
}
std::string DebugCmdGiveGoldCheat(const string_view parameter)
std::string DebugCmdGiveGoldCheat(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
@ -171,7 +171,7 @@ std::string DebugCmdGiveGoldCheat(const string_view parameter)
return "You are now rich! If only this was as easy in real life...";
}
std::string DebugCmdTakeGoldCheat(const string_view parameter)
std::string DebugCmdTakeGoldCheat(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
@ -191,7 +191,7 @@ std::string DebugCmdTakeGoldCheat(const string_view parameter)
return "You are poor...";
}
std::string DebugCmdWarpToLevel(const string_view parameter)
std::string DebugCmdWarpToLevel(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
const ParseIntResult<int> parsedParam = ParseInt<int>(parameter, /*min=*/0);
@ -207,7 +207,7 @@ std::string DebugCmdWarpToLevel(const string_view parameter)
return StrCat("Welcome to level ", level, ".");
}
std::string DebugCmdLoadQuestMap(const string_view parameter)
std::string DebugCmdLoadQuestMap(const std::string_view parameter)
{
if (parameter.empty()) {
std::string ret = "What mapid do you want to visit?";
@ -241,14 +241,14 @@ std::string DebugCmdLoadQuestMap(const string_view parameter)
return StrCat("Mapid ", level, " is not known. Do you want to write a mod?");
}
std::string DebugCmdLoadMap(const string_view parameter)
std::string DebugCmdLoadMap(const std::string_view parameter)
{
TestMapPath.clear();
int mapType = 0;
Point spawn = {};
int count = 0;
for (string_view arg : SplitByChar(parameter, ' ')) {
for (std::string_view arg : SplitByChar(parameter, ' ')) {
switch (count) {
case 0:
TestMapPath = StrCat(arg, ".dun");
@ -286,7 +286,7 @@ std::string DebugCmdLoadMap(const string_view parameter)
return "Welcome to this unique place.";
}
std::string ExportDun(const string_view parameter)
std::string ExportDun(const std::string_view parameter)
{
std::string levelName = StrCat(currlevel, "-", glSeedTbl[currlevel], ".dun");
@ -353,7 +353,7 @@ std::string ExportDun(const string_view parameter)
return StrCat(levelName, " saved. Happy mapping!");
}
std::unordered_map<string_view, _talker_id> TownerShortNameToTownerId = {
std::unordered_map<std::string_view, _talker_id> TownerShortNameToTownerId = {
{ "griswold", _talker_id::TOWN_SMITH },
{ "pepin", _talker_id::TOWN_HEALER },
{ "ogden", _talker_id::TOWN_TAVERN },
@ -367,7 +367,7 @@ std::unordered_map<string_view, _talker_id> TownerShortNameToTownerId = {
{ "nut", _talker_id::TOWN_COWFARM },
};
std::string DebugCmdVisitTowner(const string_view parameter)
std::string DebugCmdVisitTowner(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
@ -407,7 +407,7 @@ std::string DebugCmdVisitTowner(const string_view parameter)
return StrCat("Couldn't find ", parameter, ".");
}
std::string DebugCmdResetLevel(const string_view parameter)
std::string DebugCmdResetLevel(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
@ -439,7 +439,7 @@ std::string DebugCmdResetLevel(const string_view parameter)
return StrCat("Level ", level, " was restored and looks fabulous.");
}
std::string DebugCmdGodMode(const string_view parameter)
std::string DebugCmdGodMode(const std::string_view parameter)
{
DebugGodMode = !DebugGodMode;
if (DebugGodMode)
@ -447,14 +447,14 @@ std::string DebugCmdGodMode(const string_view parameter)
return "You are mortal, beware of the darkness.";
}
std::string DebugCmdLighting(const string_view parameter)
std::string DebugCmdLighting(const std::string_view parameter)
{
ToggleLighting();
return "All raindrops are the same.";
}
std::string DebugCmdMapReveal(const string_view parameter)
std::string DebugCmdMapReveal(const std::string_view parameter)
{
for (int x = 0; x < DMAXX; x++)
for (int y = 0; y < DMAXY; y++)
@ -463,7 +463,7 @@ std::string DebugCmdMapReveal(const string_view parameter)
return "The way is made clear when viewed from above";
}
std::string DebugCmdMapHide(const string_view parameter)
std::string DebugCmdMapHide(const std::string_view parameter)
{
for (int x = 0; x < DMAXX; x++)
for (int y = 0; y < DMAXY; y++)
@ -472,7 +472,7 @@ std::string DebugCmdMapHide(const string_view parameter)
return "The way is made unclear when viewed from below";
}
std::string DebugCmdVision(const string_view parameter)
std::string DebugCmdVision(const std::string_view parameter)
{
DebugVision = !DebugVision;
if (DebugVision)
@ -481,7 +481,7 @@ std::string DebugCmdVision(const string_view parameter)
return "My path is set.";
}
std::string DebugCmdPath(const string_view parameter)
std::string DebugCmdPath(const std::string_view parameter)
{
DebugPath = !DebugPath;
if (DebugPath)
@ -490,7 +490,7 @@ std::string DebugCmdPath(const string_view parameter)
return "The path is hidden.";
}
std::string DebugCmdQuest(const string_view parameter)
std::string DebugCmdQuest(const std::string_view parameter)
{
if (parameter.empty()) {
std::string ret = "You must provide an id. This could be: all";
@ -532,7 +532,7 @@ std::string DebugCmdQuest(const string_view parameter)
return StrCat(QuestsData[questId]._qlstr, " enabled.");
}
std::string DebugCmdLevelUp(const string_view parameter)
std::string DebugCmdLevelUp(const std::string_view parameter)
{
const int levels = ParseInt<int>(parameter, /*min=*/1).value_or(1);
for (int i = 0; i < levels; i++)
@ -540,7 +540,7 @@ std::string DebugCmdLevelUp(const string_view parameter)
return "New experience leads to new insights.";
}
std::string DebugCmdMaxStats(const string_view parameter)
std::string DebugCmdMaxStats(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
ModifyPlrStr(myPlayer, myPlayer.GetMaximumAttributeValue(CharacterAttribute::Strength) - myPlayer._pBaseStr);
@ -550,7 +550,7 @@ std::string DebugCmdMaxStats(const string_view parameter)
return "Who needs elixirs anyway?";
}
std::string DebugCmdMinStats(const string_view parameter)
std::string DebugCmdMinStats(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
ModifyPlrStr(myPlayer, -myPlayer._pBaseStr);
@ -560,7 +560,7 @@ std::string DebugCmdMinStats(const string_view parameter)
return "From hero to zero.";
}
std::string DebugCmdSetSpellsLevel(const string_view parameter)
std::string DebugCmdSetSpellsLevel(const std::string_view parameter)
{
const ParseIntResult<uint8_t> parsedArg = ParseInt<uint8_t>(parameter);
if (!parsedArg.ok())
@ -577,7 +577,7 @@ std::string DebugCmdSetSpellsLevel(const string_view parameter)
return "Knowledge is power.";
}
std::string DebugCmdRefillHealthMana(const string_view parameter)
std::string DebugCmdRefillHealthMana(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
myPlayer.RestoreFullLife();
@ -588,7 +588,7 @@ std::string DebugCmdRefillHealthMana(const string_view parameter)
return "Ready for more.";
}
std::string DebugCmdChangeHealth(const string_view parameter)
std::string DebugCmdChangeHealth(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
int change = -1;
@ -611,7 +611,7 @@ std::string DebugCmdChangeHealth(const string_view parameter)
return "Health has changed.";
}
std::string DebugCmdChangeMana(const string_view parameter)
std::string DebugCmdChangeMana(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
int change = -1;
@ -634,24 +634,24 @@ std::string DebugCmdChangeMana(const string_view parameter)
return "Mana has changed.";
}
std::string DebugCmdGenerateUniqueItem(const string_view parameter)
std::string DebugCmdGenerateUniqueItem(const std::string_view parameter)
{
return DebugSpawnUniqueItem(parameter.data());
}
std::string DebugCmdGenerateItem(const string_view parameter)
std::string DebugCmdGenerateItem(const std::string_view parameter)
{
return DebugSpawnItem(parameter.data());
}
std::string DebugCmdExit(const string_view parameter)
std::string DebugCmdExit(const std::string_view parameter)
{
gbRunGame = false;
gbRunGameResult = false;
return "See you again my Lord.";
}
std::string DebugCmdArrow(const string_view parameter)
std::string DebugCmdArrow(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
@ -673,7 +673,7 @@ std::string DebugCmdArrow(const string_view parameter)
return "I can shoot any arrow.";
}
std::string DebugCmdTalkToTowner(const string_view parameter)
std::string DebugCmdTalkToTowner(const std::string_view parameter)
{
if (DebugTalkToTowner(parameter.data())) {
return "Hello from the other side.";
@ -681,7 +681,7 @@ std::string DebugCmdTalkToTowner(const string_view parameter)
return "NPC not found.";
}
std::string DebugCmdShowGrid(const string_view parameter)
std::string DebugCmdShowGrid(const std::string_view parameter)
{
DebugGrid = !DebugGrid;
if (DebugGrid)
@ -690,14 +690,14 @@ std::string DebugCmdShowGrid(const string_view parameter)
return "Back to boring.";
}
std::string DebugCmdSpawnUniqueMonster(const string_view parameter)
std::string DebugCmdSpawnUniqueMonster(const std::string_view parameter)
{
if (leveltype == DTYPE_TOWN)
return "Do you want to kill the towners?!?";
std::string name;
int count = 1;
for (string_view arg : SplitByChar(parameter, ' ')) {
for (std::string_view arg : SplitByChar(parameter, ' ')) {
const ParseIntResult<int> parsedArg = ParseInt<int>(arg);
if (!parsedArg.ok())
return "Failed to parse argument as integer";
@ -780,14 +780,14 @@ std::string DebugCmdSpawnUniqueMonster(const string_view parameter)
return *ret;
}
std::string DebugCmdSpawnMonster(const string_view parameter)
std::string DebugCmdSpawnMonster(const std::string_view parameter)
{
if (leveltype == DTYPE_TOWN)
return "Do you want to kill the towners?!?";
std::string name;
int count = 1;
for (string_view arg : SplitByChar(parameter, ' ')) {
for (std::string_view arg : SplitByChar(parameter, ' ')) {
const ParseIntResult<int> parsedArg = ParseInt<int>(arg);
if (!parsedArg.ok())
return "Failed to parse argument as integer";
@ -866,7 +866,7 @@ std::string DebugCmdSpawnMonster(const string_view parameter)
return *ret;
}
std::string DebugCmdShowTileData(const string_view parameter)
std::string DebugCmdShowTileData(const std::string_view parameter)
{
std::string paramList[] = {
"dPiece",
@ -924,7 +924,7 @@ std::string DebugCmdShowTileData(const string_view parameter)
return "Special powers activated.";
}
std::string DebugCmdScrollView(const string_view parameter)
std::string DebugCmdScrollView(const std::string_view parameter)
{
DebugScrollViewEnabled = !DebugScrollViewEnabled;
if (DebugScrollViewEnabled)
@ -933,7 +933,7 @@ std::string DebugCmdScrollView(const string_view parameter)
return "If you want to see the world, you need to explore it yourself.";
}
std::string DebugCmdItemInfo(const string_view parameter)
std::string DebugCmdItemInfo(const std::string_view parameter)
{
Player &myPlayer = *MyPlayer;
Item *pItem = nullptr;
@ -953,7 +953,7 @@ std::string DebugCmdItemInfo(const string_view parameter)
return StrCat("Numitems: ", ActiveItemCount);
}
std::string DebugCmdQuestInfo(const string_view parameter)
std::string DebugCmdQuestInfo(const std::string_view parameter)
{
if (parameter.empty()) {
std::string ret = "You must provide an id. This could be:";
@ -976,7 +976,7 @@ std::string DebugCmdQuestInfo(const string_view parameter)
return StrCat("\nQuest: ", QuestsData[quest._qidx]._qlstr, "\nActive: ", quest._qactive, " Var1: ", quest._qvar1, " Var2: ", quest._qvar2);
}
std::string DebugCmdPlayerInfo(const string_view parameter)
std::string DebugCmdPlayerInfo(const std::string_view parameter)
{
if (parameter.empty()) {
return StrCat("Provide a player ID between 0 and ", Players.size() - 1);
@ -1000,22 +1000,22 @@ std::string DebugCmdPlayerInfo(const string_view parameter)
"\nInvincible:", player._pInvincible ? 1 : 0, " HitPoints:", player._pHitPoints);
}
std::string DebugCmdToggleFPS(const string_view parameter)
std::string DebugCmdToggleFPS(const std::string_view parameter)
{
frameflag = !frameflag;
return "";
}
std::string DebugCmdChangeTRN(const string_view parameter)
std::string DebugCmdChangeTRN(const std::string_view parameter)
{
std::string out;
const auto parts = SplitByChar(parameter, ' ');
auto it = parts.begin();
if (it != parts.end()) {
const string_view first = *it;
const std::string_view first = *it;
if (++it != parts.end()) {
const string_view second = *it;
string_view prefix;
const std::string_view second = *it;
std::string_view prefix;
if (first == "mon") {
prefix = "monsters\\monsters\\";
} else if (first == "plr") {
@ -1036,7 +1036,7 @@ std::string DebugCmdChangeTRN(const string_view parameter)
return out;
}
std::string DebugCmdSearchMonster(const string_view parameter)
std::string DebugCmdSearchMonster(const std::string_view parameter)
{
if (parameter.empty()) {
std::string ret = "What should I search? I'm too lazy to search for everything... you must provide a monster name!";
@ -1051,7 +1051,7 @@ std::string DebugCmdSearchMonster(const string_view parameter)
return "We will find this bastard!";
}
std::string DebugCmdSearchItem(const string_view parameter)
std::string DebugCmdSearchItem(const std::string_view parameter)
{
if (parameter.empty()) {
std::string ret = "What should I search? I'm too lazy to search for everything... you must provide a item name!";
@ -1066,7 +1066,7 @@ std::string DebugCmdSearchItem(const string_view parameter)
return "Are you greedy? Anyway I will help you.";
}
std::string DebugCmdSearchObject(const string_view parameter)
std::string DebugCmdSearchObject(const std::string_view parameter)
{
if (parameter.empty()) {
std::string ret = "What should I search? I'm too lazy to search for everything... you must provide a object name!";
@ -1081,7 +1081,7 @@ std::string DebugCmdSearchObject(const string_view parameter)
return "I will look for the pyramids. Oh sorry, I'm looking for what you want, of course.";
}
std::string DebugCmdClearSearch(const string_view parameter)
std::string DebugCmdClearSearch(const std::string_view parameter)
{
SearchMonsters.clear();
SearchItems.clear();
@ -1176,14 +1176,14 @@ void SetDebugLevelSeedInfos(uint32_t mid1Seed, uint32_t mid2Seed, uint32_t mid3S
glEndSeed[currlevel] = endSeed;
}
bool CheckDebugTextCommand(const string_view text)
bool CheckDebugTextCommand(const std::string_view text)
{
auto debugCmdIterator = c_find_if(DebugCmdList, [&](const DebugCmdItem &elem) { return text.find(elem.text) == 0 && (text.length() == elem.text.length() || text[elem.text.length()] == ' '); });
if (debugCmdIterator == DebugCmdList.end())
return false;
auto &dbgCmd = *debugCmdIterator;
string_view parameter = "";
std::string_view parameter = "";
if (text.length() > (dbgCmd.text.length() + 1))
parameter = text.substr(dbgCmd.text.length() + 1);
const auto result = dbgCmd.actionProc(parameter);
@ -1305,7 +1305,7 @@ bool IsDebugAutomapHighlightNeeded()
bool ShouldHighlightDebugAutomapTile(Point position)
{
auto matchesSearched = [](const string_view name, const std::vector<std::string> &searchedNames) {
auto matchesSearched = [](const std::string_view name, const std::vector<std::string> &searchedNames) {
const std::string lowercaseName = AsciiStrToLower(name);
for (const auto &searchedName : searchedNames) {
if (lowercaseName.find(searchedName) != std::string::npos) {

4
Source/debug.h

@ -6,12 +6,12 @@
#pragma once
#include <cstdint>
#include <string_view>
#include <unordered_map>
#include "diablo.h"
#include "engine.h"
#include "engine/clx_sprite.hpp"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -35,7 +35,7 @@ void LoadDebugGFX();
void GetDebugMonster();
void NextDebugMonster();
void SetDebugLevelSeedInfos(uint32_t mid1Seed, uint32_t mid2Seed, uint32_t mid3Seed, uint32_t endSeed);
bool CheckDebugTextCommand(const string_view text);
bool CheckDebugTextCommand(const std::string_view text);
bool IsDebugGridTextNeeded();
bool IsDebugGridInMegatiles();
bool GetDebugGridText(Point dungeonCoords, char *debugGridTextBuffer);

14
Source/diablo.cpp

@ -5,6 +5,7 @@
*/
#include <array>
#include <cstdint>
#include <string_view>
#include <fmt/format.h>
@ -81,7 +82,6 @@
#include "utils/language.h"
#include "utils/parse_int.hpp"
#include "utils/paths.h"
#include "utils/stdcompat/string_view.hpp"
#include "utils/str_cat.hpp"
#include "utils/utf8.hpp"
@ -666,7 +666,7 @@ void HandleMouseButtonUp(Uint8 button, uint16_t modState)
}
}
bool HandleTextInput(string_view text)
bool HandleTextInput(std::string_view text)
{
if (IsTalkActive()) {
control_new_text(text);
@ -894,7 +894,7 @@ void RunGameLoop(interface_mode uMsg)
}
}
void PrintWithRightPadding(string_view str, size_t width)
void PrintWithRightPadding(std::string_view str, size_t width)
{
printInConsole(str);
if (str.size() >= width)
@ -902,7 +902,7 @@ void PrintWithRightPadding(string_view str, size_t width)
printInConsole(std::string(width - str.size(), ' '));
}
void PrintHelpOption(string_view flags, string_view description)
void PrintHelpOption(std::string_view flags, std::string_view description)
{
printInConsole(" ");
PrintWithRightPadding(flags, 20);
@ -950,14 +950,14 @@ void PrintHelpOption(string_view flags, string_view description)
diablo_quit(0);
}
void PrintFlagMessage(string_view flag, string_view message)
void PrintFlagMessage(std::string_view flag, std::string_view message)
{
printInConsole(flag);
printInConsole(message);
printNewlineInConsole();
}
void PrintFlagRequiresArgument(string_view flag)
void PrintFlagRequiresArgument(std::string_view flag)
{
PrintFlagMessage(flag, " requires an argument");
}
@ -975,7 +975,7 @@ void DiabloParseFlags(int argc, char **argv)
bool createDemoReference = false;
#endif
for (int i = 1; i < argc; i++) {
const string_view arg = argv[i];
const std::string_view arg = argv[i];
if (arg == "-h" || arg == "--help") {
PrintHelpAndExit();
} else if (arg == "--version") {

4
Source/discord/discord.cpp

@ -88,7 +88,7 @@ std::string GetLocationString()
std::string GetCharacterString()
{
const string_view charClassStr = _(PlayersData[static_cast<int>(MyPlayer->_pClass)].className);
const std::string_view charClassStr = _(PlayersData[static_cast<int>(MyPlayer->_pClass)].className);
return fmt::format(fmt::runtime(_(/* TRANSLATORS: Discord character, i.e. "Lv 6 Warrior" */ "Lv {} {}")), tracked_data.playerLevel, charClassStr);
}
@ -100,7 +100,7 @@ std::string GetDetailString()
std::string GetStateString()
{
constexpr std::array<const char *, 3> DifficultyStrs = { N_("Normal"), N_("Nightmare"), N_("Hell") };
const string_view difficultyStr = _(DifficultyStrs[sgGameInitInfo.nDifficulty]);
const std::string_view difficultyStr = _(DifficultyStrs[sgGameInitInfo.nDifficulty]);
return fmt::format(fmt::runtime(_(/* TRANSLATORS: Discord state i.e. "Nightmare difficulty" */ "{} difficulty")), difficultyStr);
}

6
Source/dvlnet/zerotier_native.cpp

@ -49,12 +49,12 @@ std::atomic_bool zt_joined(false);
std::unordered_map<uint64_t, zts_event_t> ztPeerEvents;
#ifdef DVL_ZT_SYMLINK
bool HasMultiByteChars(string_view path)
bool HasMultiByteChars(std::string_view path)
{
return c_any_of(path, IsTrailUtf8CodeUnit);
}
std::string ComputeAlternateFolderName(string_view path)
std::string ComputeAlternateFolderName(std::string_view path)
{
const size_t hashSize = crypto_generichash_BYTES;
unsigned char hash[hashSize];
@ -69,7 +69,7 @@ std::string ComputeAlternateFolderName(string_view path)
return fmt::format("{:02x}", fmt::join(hash, ""));
}
std::string ToZTCompliantPath(string_view configPath)
std::string ToZTCompliantPath(std::string_view configPath)
{
if (!HasMultiByteChars(configPath))
return std::string(configPath);

8
Source/engine/assets.cpp

@ -76,7 +76,7 @@ AssetRef FindAsset(const char *filename)
AssetRef result;
result.path[0] = '\0';
const string_view filenameStr = filename;
const std::string_view filenameStr = filename;
char pathBuf[AssetRef::PathBufSize];
char *const pathEnd = pathBuf + AssetRef::PathBufSize;
char *const relativePath = &pathBuf[AssetRef::PathBufSize - filenameStr.size() - 1];
@ -88,7 +88,7 @@ AssetRef FindAsset(const char *filename)
// Absolute path:
if (relativePath[0] == '/') {
if (FileExists(relativePath)) {
*BufCopy(result.path, string_view(relativePath, filenameStr.size())) = '\0';
*BufCopy(result.path, std::string_view(relativePath, filenameStr.size())) = '\0';
}
return result;
}
@ -96,7 +96,7 @@ AssetRef FindAsset(const char *filename)
// Unpacked MPQ file:
char *const unpackedMpqPath = FindUnpackedMpqFile(relativePath);
if (unpackedMpqPath != nullptr) {
*BufCopy(result.path, string_view(unpackedMpqPath, pathEnd - unpackedMpqPath)) = '\0';
*BufCopy(result.path, std::string_view(unpackedMpqPath, pathEnd - unpackedMpqPath)) = '\0';
return result;
}
@ -105,7 +105,7 @@ AssetRef FindAsset(const char *filename)
char *assetsPath = relativePath - assetsPathPrefix.size();
std::memcpy(assetsPath, assetsPathPrefix.data(), assetsPathPrefix.size());
if (FileExists(assetsPath)) {
*BufCopy(result.path, string_view(assetsPath, pathEnd - assetsPath)) = '\0';
*BufCopy(result.path, std::string_view(assetsPath, pathEnd - assetsPath)) = '\0';
}
return result;
}

2
Source/engine/direction.cpp

@ -2,7 +2,7 @@
namespace devilution {
string_view DirectionToString(Direction direction)
std::string_view DirectionToString(Direction direction)
{
switch (direction) {
case Direction::South:

5
Source/engine/direction.hpp

@ -1,10 +1,9 @@
#pragma once
#include <cstdint>
#include <string_view>
#include <type_traits>
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
enum class Direction : std::uint8_t {
@ -40,6 +39,6 @@ constexpr Direction Opposite(Direction facing)
return static_cast<Direction>((static_cast<std::underlying_type_t<Direction>>(facing) + 4) % 8);
}
string_view DirectionToString(Direction direction);
std::string_view DirectionToString(Direction direction);
} // namespace devilution

8
Source/engine/render/dun_render.cpp

@ -61,7 +61,7 @@ int_fast16_t GetTileHeight(TileType tile)
}
#ifdef DEBUG_STR
std::pair<string_view, UiFlags> GetTileDebugStr(TileType tile)
std::pair<std::string_view, UiFlags> GetTileDebugStr(TileType tile)
{
// clang-format off
switch (tile) {
@ -1092,7 +1092,7 @@ void RenderBlackTileFull(uint8_t *DVL_RESTRICT dst, uint16_t dstPitch)
#ifdef DUN_RENDER_STATS
std::unordered_map<DunRenderType, size_t, DunRenderTypeHash> DunRenderStats;
string_view TileTypeToString(TileType tileType)
std::string_view TileTypeToString(TileType tileType)
{
// clang-format off
switch (tileType) {
@ -1107,7 +1107,7 @@ string_view TileTypeToString(TileType tileType)
// clang-format on
}
string_view MaskTypeToString(MaskType maskType)
std::string_view MaskTypeToString(MaskType maskType)
{
// clang-format off
switch (maskType) {
@ -1173,7 +1173,7 @@ void RenderTile(const Surface &out, Point position,
}
#ifdef DEBUG_STR
const std::pair<string_view, UiFlags> debugStr = GetTileDebugStr(tile);
const std::pair<std::string_view, UiFlags> debugStr = GetTileDebugStr(tile);
DrawString(out, debugStr.first, Rectangle { Point { position.x + 2, position.y - 29 }, Size { 28, 28 } }, debugStr.second);
#endif
}

4
Source/engine/render/dun_render.hpp

@ -251,9 +251,9 @@ struct DunRenderTypeHash {
};
extern std::unordered_map<DunRenderType, size_t, DunRenderTypeHash> DunRenderStats;
string_view TileTypeToString(TileType tileType);
std::string_view TileTypeToString(TileType tileType);
string_view MaskTypeToString(MaskType maskType);
std::string_view MaskTypeToString(MaskType maskType);
#endif
/**

4
Source/engine/render/scrollrt.cpp

@ -1254,7 +1254,7 @@ void DrawView(const Surface &out, Point startPosition)
void DrawFPS(const Surface &out)
{
static int framesSinceLastUpdate = 0;
static string_view formatted {};
static std::string_view formatted {};
if (!frameflag || !gbActive) {
return;
@ -1273,7 +1273,7 @@ void DrawFPS(const Surface &out)
const char *end = fps >= 100 * FpsPow10
? BufCopy(buf, fps / FpsPow10, " FPS")
: BufCopy(buf, fps / FpsPow10, ".", fps % FpsPow10, " FPS");
formatted = { buf, static_cast<string_view::size_type>(end - buf) };
formatted = { buf, static_cast<std::string_view::size_type>(end - buf) };
};
DrawString(out, formatted, Point { 8, 68 }, UiFlags::ColorRed);
}

56
Source/engine/render/text_render.cpp

@ -139,12 +139,12 @@ bool IsSmallFontTallRow(uint16_t row)
return IsCJK(row) || IsHangul(row);
}
void GetFontPath(GameFontTables size, uint16_t row, string_view ext, char *out)
void GetFontPath(GameFontTables size, uint16_t row, std::string_view ext, char *out)
{
*fmt::format_to(out, R"(fonts\{}-{:02x}{})", FontSizes[size], row, ext) = '\0';
}
void GetFontPath(string_view language_code, GameFontTables size, uint16_t row, string_view ext, char *out)
void GetFontPath(std::string_view language_code, GameFontTables size, uint16_t row, std::string_view ext, char *out)
{
*fmt::format_to(out, R"(fonts\{}\{}-{:02x}{})", language_code, FontSizes[size], row, ext) = '\0';
}
@ -171,8 +171,8 @@ OptionalClxSpriteList LoadFont(GameFontTables size, text_color color, uint16_t r
char path[32];
// Try loading the language-specific variant first:
const string_view language_code = GetLanguageCode();
const string_view language_tag = language_code.substr(0, 2);
const std::string_view language_code = GetLanguageCode();
const std::string_view language_tag = language_code.substr(0, 2);
if (language_tag == "zh" || language_tag == "ja" || language_tag == "ko") {
GetFontPath(language_code, size, row, ".clx", &path[0]);
font = LoadOptionalClx(path);
@ -258,7 +258,7 @@ bool IsBreakAllowed(char32_t codepoint, char32_t nextCodepoint)
return IsFullWidthPunct(codepoint) && !IsFullWidthPunct(nextCodepoint);
}
std::size_t CountNewlines(string_view fmt, const DrawStringFormatArg *args, std::size_t argsLen)
std::size_t CountNewlines(std::string_view fmt, const DrawStringFormatArg *args, std::size_t argsLen)
{
std::size_t result = c_count(fmt, '\n');
for (std::size_t i = 0; i < argsLen; ++i) {
@ -270,7 +270,7 @@ std::size_t CountNewlines(string_view fmt, const DrawStringFormatArg *args, std:
class FmtArgParser {
public:
FmtArgParser(string_view fmt,
FmtArgParser(std::string_view fmt,
DrawStringFormatArg *args,
size_t len,
size_t offset = 0)
@ -281,14 +281,14 @@ public:
{
}
std::optional<std::size_t> operator()(string_view &rest)
std::optional<std::size_t> operator()(std::string_view &rest)
{
std::optional<std::size_t> result;
if (rest[0] != '{')
return result;
std::size_t closingBracePos = rest.find('}', 1);
if (closingBracePos == string_view::npos) {
if (closingBracePos == std::string_view::npos) {
LogError("Unclosed format argument: {}", fmt_);
return result;
}
@ -311,7 +311,7 @@ public:
result = std::nullopt;
} else {
if (!args_[*result].HasFormatted()) {
const auto fmtStr = positional ? "{}" : fmt::string_view(rest.data(), fmtLen);
const auto fmtStr = positional ? "{}" : std::string_view(rest.data(), fmtLen);
args_[*result].SetFormatted(fmt::format(fmt::runtime(fmtStr), args_[*result].GetIntValue()));
}
rest.remove_prefix(fmtLen);
@ -325,13 +325,13 @@ public:
}
private:
string_view fmt_;
std::string_view fmt_;
DrawStringFormatArg *args_;
std::size_t len_;
std::size_t next_;
};
bool ContainsSmallFontTallCodepoints(string_view text)
bool ContainsSmallFontTallCodepoints(std::string_view text)
{
while (!text.empty()) {
const char32_t next = ConsumeFirstUtf8CodePoint(&text);
@ -345,14 +345,14 @@ bool ContainsSmallFontTallCodepoints(string_view text)
return false;
}
int GetLineHeight(string_view fmt, DrawStringFormatArg *args, std::size_t argsLen, GameFontTables fontIndex)
int GetLineHeight(std::string_view fmt, DrawStringFormatArg *args, std::size_t argsLen, GameFontTables fontIndex)
{
constexpr std::array<int, 6> LineHeights = { 12, 26, 38, 42, 50, 22 };
if (fontIndex == GameFont12 && IsSmallFontTall()) {
char32_t prev = U'\0';
char32_t next;
FmtArgParser fmtArgParser { fmt, args, argsLen };
string_view rest = fmt;
std::string_view rest = fmt;
while (!rest.empty()) {
if ((prev == U'{' || prev == U'}') && static_cast<char>(prev) == rest[0]) {
rest.remove_prefix(1);
@ -407,14 +407,14 @@ int GetLineStartX(UiFlags flags, const Rectangle &rect, int lineWidth)
return rect.position.x;
}
uint32_t DoDrawString(const Surface &out, string_view text, Rectangle rect, Point &characterPosition,
uint32_t DoDrawString(const Surface &out, std::string_view text, Rectangle rect, Point &characterPosition,
int spacing, int lineHeight, int lineWidth, int rightMargin, int bottomMargin,
UiFlags flags, GameFontTables size, text_color color, bool outline)
{
CurrentFont currentFont;
char32_t next;
string_view remaining = text;
std::string_view remaining = text;
size_t cpLen;
for (; !remaining.empty() && remaining[0] != '\0'
&& (next = DecodeFirstUtf8CodePoint(remaining, &cpLen)) != Utf8DecodeError;
@ -466,7 +466,7 @@ void UnloadFonts()
Fonts.clear();
}
int GetLineWidth(string_view text, GameFontTables size, int spacing, int *charactersInLine)
int GetLineWidth(std::string_view text, GameFontTables size, int spacing, int *charactersInLine)
{
int lineWidth = 0;
CurrentFont currentFont;
@ -499,7 +499,7 @@ int GetLineWidth(string_view text, GameFontTables size, int spacing, int *charac
return lineWidth != 0 ? (lineWidth - spacing) : 0;
}
int GetLineWidth(string_view fmt, DrawStringFormatArg *args, std::size_t argsLen, size_t argsOffset, GameFontTables size, int spacing, int *charactersInLine)
int GetLineWidth(std::string_view fmt, DrawStringFormatArg *args, std::size_t argsLen, size_t argsOffset, GameFontTables size, int spacing, int *charactersInLine)
{
int lineWidth = 0;
CurrentFont currentFont;
@ -509,7 +509,7 @@ int GetLineWidth(string_view fmt, DrawStringFormatArg *args, std::size_t argsLen
char32_t next;
FmtArgParser fmtArgParser { fmt, args, argsLen, argsOffset };
string_view rest = fmt;
std::string_view rest = fmt;
while (!rest.empty()) {
if ((prev == U'{' || prev == U'}') && static_cast<char>(prev) == rest[0]) {
rest.remove_prefix(1);
@ -552,7 +552,7 @@ int GetLineWidth(string_view fmt, DrawStringFormatArg *args, std::size_t argsLen
return lineWidth != 0 ? (lineWidth - spacing) : 0;
}
int GetLineHeight(string_view text, GameFontTables fontIndex)
int GetLineHeight(std::string_view text, GameFontTables fontIndex)
{
if (fontIndex == GameFont12 && IsSmallFontTall() && ContainsSmallFontTallCodepoints(text)) {
return SmallFontTallLineHeight;
@ -571,7 +571,7 @@ int AdjustSpacingToFitHorizontally(int &lineWidth, int maxSpacing, int character
return maxSpacing - spacingRedux;
}
std::string WordWrapString(string_view text, unsigned width, GameFontTables size, int spacing)
std::string WordWrapString(std::string_view text, unsigned width, GameFontTables size, int spacing)
{
std::string output;
if (text.empty() || text[0] == '\0')
@ -580,7 +580,7 @@ std::string WordWrapString(string_view text, unsigned width, GameFontTables size
output.reserve(text.size());
const char *begin = text.data();
const char *processedEnd = text.data();
string_view::size_type lastBreakablePos = string_view::npos;
std::string_view::size_type lastBreakablePos = std::string_view::npos;
std::size_t lastBreakableLen;
bool lastBreakableKeep = false;
unsigned lineWidth = 0;
@ -589,7 +589,7 @@ std::string WordWrapString(string_view text, unsigned width, GameFontTables size
char32_t codepoint = U'\0'; // the current codepoint
char32_t nextCodepoint; // the next codepoint
std::size_t nextCodepointLen;
string_view remaining = text;
std::string_view remaining = text;
nextCodepoint = DecodeFirstUtf8CodePoint(remaining, &nextCodepointLen);
do {
codepoint = nextCodepoint;
@ -600,7 +600,7 @@ std::string WordWrapString(string_view text, unsigned width, GameFontTables size
nextCodepoint = !remaining.empty() ? DecodeFirstUtf8CodePoint(remaining, &nextCodepointLen) : U'\0';
if (codepoint == U'\n') { // Existing line break, scan next line
lastBreakablePos = string_view::npos;
lastBreakablePos = std::string_view::npos;
lineWidth = 0;
output.append(processedEnd, remaining.data());
processedEnd = remaining.data();
@ -631,7 +631,7 @@ std::string WordWrapString(string_view text, unsigned width, GameFontTables size
continue; // String is still within the limit, continue to the next symbol
}
if (lastBreakablePos == string_view::npos) { // Single word longer than width
if (lastBreakablePos == std::string_view::npos) { // Single word longer than width
continue;
}
@ -646,7 +646,7 @@ std::string WordWrapString(string_view text, unsigned width, GameFontTables size
// Restart from the beginning of the new line.
remaining = text.substr(lastBreakablePos + lastBreakableLen);
processedEnd = remaining.data();
lastBreakablePos = string_view::npos;
lastBreakablePos = std::string_view::npos;
lineWidth = 0;
nextCodepoint = !remaining.empty() ? DecodeFirstUtf8CodePoint(remaining, &nextCodepointLen) : U'\0';
} while (!remaining.empty() && remaining[0] != '\0');
@ -657,7 +657,7 @@ std::string WordWrapString(string_view text, unsigned width, GameFontTables size
/**
* @todo replace Rectangle with cropped Surface
*/
uint32_t DrawString(const Surface &out, string_view text, const Rectangle &rect, UiFlags flags, int spacing, int lineHeight)
uint32_t DrawString(const Surface &out, std::string_view text, const Rectangle &rect, UiFlags flags, int spacing, int lineHeight)
{
GameFontTables size = GetSizeFromFlags(flags);
text_color color = GetColorFromFlags(flags);
@ -707,7 +707,7 @@ uint32_t DrawString(const Surface &out, string_view text, const Rectangle &rect,
return bytesDrawn;
}
void DrawStringWithColors(const Surface &out, string_view fmt, DrawStringFormatArg *args, std::size_t argsLen, const Rectangle &rect, UiFlags flags, int spacing, int lineHeight)
void DrawStringWithColors(const Surface &out, std::string_view fmt, DrawStringFormatArg *args, std::size_t argsLen, const Rectangle &rect, UiFlags flags, int spacing, int lineHeight)
{
GameFontTables size = GetSizeFromFlags(flags);
text_color color = GetColorFromFlags(flags);
@ -745,7 +745,7 @@ void DrawStringWithColors(const Surface &out, string_view fmt, DrawStringFormatA
char32_t prev = U'\0';
char32_t next;
string_view remaining = fmt;
std::string_view remaining = fmt;
FmtArgParser fmtArgParser { fmt, args, argsLen };
size_t cpLen;
for (; !remaining.empty() && remaining[0] != '\0'

24
Source/engine/render/text_render.hpp

@ -8,6 +8,7 @@
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@ -17,7 +18,6 @@
#include "engine.h"
#include "engine/clx_sprite.hpp"
#include "engine/rectangle.hpp"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -62,7 +62,7 @@ public:
Int
};
DrawStringFormatArg(string_view value, UiFlags flags)
DrawStringFormatArg(std::string_view value, UiFlags flags)
: type_(Type::StringView)
, string_view_value_(value)
, flags_(flags)
@ -81,7 +81,7 @@ public:
return type_;
}
string_view GetFormatted() const
std::string_view GetFormatted() const
{
if (type_ == Type::StringView)
return string_view_value_;
@ -111,7 +111,7 @@ public:
private:
Type type_;
union {
string_view string_view_value_;
std::string_view string_view_value_;
int int_value_;
};
@ -136,7 +136,7 @@ void LoadSmallSelectionSpinner();
* @param charactersInLine Receives characters read until newline or terminator
* @return Line width in pixels
*/
int GetLineWidth(string_view text, GameFontTables size = GameFont12, int spacing = 1, int *charactersInLine = nullptr);
int GetLineWidth(std::string_view text, GameFontTables size = GameFont12, int spacing = 1, int *charactersInLine = nullptr);
/**
* @brief Calculate pixel width of first line of text, respecting kerning
@ -149,9 +149,9 @@ int GetLineWidth(string_view text, GameFontTables size = GameFont12, int spacing
* @param charactersInLine Receives characters read until newline or terminator
* @return Line width in pixels
*/
int GetLineWidth(string_view fmt, DrawStringFormatArg *args, size_t argsLen, size_t argsOffset, GameFontTables size, int spacing, int *charactersInLine = nullptr);
int GetLineWidth(std::string_view fmt, DrawStringFormatArg *args, size_t argsLen, size_t argsOffset, GameFontTables size, int spacing, int *charactersInLine = nullptr);
int GetLineHeight(string_view text, GameFontTables fontIndex);
int GetLineHeight(std::string_view text, GameFontTables fontIndex);
/**
* @brief Builds a multi-line version of the given text so it'll fit within the given width.
@ -165,7 +165,7 @@ int GetLineHeight(string_view text, GameFontTables fontIndex);
* @param spacing Any adjustment to apply between each character
* @return A copy of the source text with newlines inserted where appropriate
*/
[[nodiscard]] std::string WordWrapString(string_view text, unsigned width, GameFontTables size = GameFont12, int spacing = 1);
[[nodiscard]] std::string WordWrapString(std::string_view text, unsigned width, GameFontTables size = GameFont12, int spacing = 1);
/**
* @brief Draws a line of text within a clipping rectangle (positioned relative to the origin of the output buffer).
@ -186,7 +186,7 @@ int GetLineHeight(string_view text, GameFontTables fontIndex);
* @param lineHeight Allows overriding the default line height, useful for multi-line strings.
* @return The number of bytes rendered, including characters "drawn" outside the buffer.
*/
uint32_t DrawString(const Surface &out, string_view text, const Rectangle &rect, UiFlags flags = UiFlags::None, int spacing = 1, int lineHeight = -1);
uint32_t DrawString(const Surface &out, std::string_view text, const Rectangle &rect, UiFlags flags = UiFlags::None, int spacing = 1, int lineHeight = -1);
/**
* @brief Draws a line of text at the given position relative to the origin of the output buffer.
@ -203,7 +203,7 @@ uint32_t DrawString(const Surface &out, string_view text, const Rectangle &rect,
* This value may be adjusted if the flag UIS_FIT_SPACING is passed in the flags parameter.
* @param lineHeight Allows overriding the default line height, useful for multi-line strings.
*/
inline void DrawString(const Surface &out, string_view text, const Point &position, UiFlags flags = UiFlags::None, int spacing = 1, int lineHeight = -1)
inline void DrawString(const Surface &out, std::string_view text, const Point &position, UiFlags flags = UiFlags::None, int spacing = 1, int lineHeight = -1)
{
DrawString(out, text, { position, { out.w() - position.x, 0 } }, flags, spacing, lineHeight);
}
@ -223,9 +223,9 @@ inline void DrawString(const Surface &out, string_view text, const Point &positi
* This value may be adjusted if the flag UIS_FIT_SPACING is passed in the flags parameter.
* @param lineHeight Allows overriding the default line height, useful for multi-line strings.
*/
void DrawStringWithColors(const Surface &out, string_view fmt, DrawStringFormatArg *args, std::size_t argsLen, const Rectangle &rect, UiFlags flags = UiFlags::None, int spacing = 1, int lineHeight = -1);
void DrawStringWithColors(const Surface &out, std::string_view fmt, DrawStringFormatArg *args, std::size_t argsLen, const Rectangle &rect, UiFlags flags = UiFlags::None, int spacing = 1, int lineHeight = -1);
inline void DrawStringWithColors(const Surface &out, string_view fmt, std::vector<DrawStringFormatArg> args, const Rectangle &rect, UiFlags flags = UiFlags::None, int spacing = 1, int lineHeight = -1)
inline void DrawStringWithColors(const Surface &out, std::string_view fmt, std::vector<DrawStringFormatArg> args, const Rectangle &rect, UiFlags flags = UiFlags::None, int spacing = 1, int lineHeight = -1)
{
return DrawStringWithColors(out, fmt, args.data(), args.size(), rect, flags, spacing, lineHeight);
}

2
Source/engine/sound_defs.hpp

@ -2,8 +2,6 @@
#include <SDL_version.h>
#include "utils/stdcompat/string_view.hpp"
#define VOLUME_MIN -1600
#define VOLUME_MAX 0
#define VOLUME_STEPS 64

2
Source/error.cpp

@ -112,7 +112,7 @@ void InitDiabloMsg(diablo_message e)
InitDiabloMsg(LanguageTranslate(MsgStrings[e]));
}
void InitDiabloMsg(string_view msg)
void InitDiabloMsg(std::string_view msg)
{
if (DiabloMessages.size() >= MAX_SEND_STR_LEN)
return;

4
Source/error.h

@ -7,9 +7,9 @@
#include <cstdint>
#include <string>
#include <string_view>
#include "engine.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -72,7 +72,7 @@ enum diablo_message : uint8_t {
};
void InitDiabloMsg(diablo_message e);
void InitDiabloMsg(string_view msg);
void InitDiabloMsg(std::string_view msg);
bool IsDiabloMsgAvailable();
void CancelCurrentDiabloMsg();
void ClrDiabloMsg();

6
Source/help.cpp

@ -4,6 +4,7 @@
* Implementation of the in-game help text.
*/
#include <string>
#include <string_view>
#include <vector>
#include "DiabloUI/ui_flags.hpp"
@ -14,7 +15,6 @@
#include "qol/chatlog.h"
#include "stores.h"
#include "utils/language.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -195,7 +195,7 @@ void DrawHelp(const Surface &out)
const int lineHeight = LineHeight();
const int blankLineHeight = BlankLineHeight();
string_view title;
std::string_view title;
if (gbIsHellfire)
title = gbIsSpawn ? _("Shareware Hellfire Help") : _("Hellfire Help");
else
@ -215,7 +215,7 @@ void DrawHelp(const Surface &out)
const int numLines = NumVisibleLines();
const int contentY = titleBottom + DividerLineMarginY() + ContentPaddingY();
for (int i = 0; i < numLines; i++) {
const string_view line = HelpTextLines[i + SkipLines];
const std::string_view line = HelpTextLines[i + SkipLines];
if (line.empty()) {
continue;
}

10
Source/init.cpp

@ -79,7 +79,7 @@ namespace {
constexpr char ExtraFontsVersion[] = "1\n";
#ifdef UNPACKED_MPQS
std::optional<std::string> FindUnpackedMpqData(const std::vector<std::string> &paths, string_view mpqName)
std::optional<std::string> FindUnpackedMpqData(const std::vector<std::string> &paths, std::string_view mpqName)
{
std::string targetPath;
for (const std::string &path : paths) {
@ -94,7 +94,7 @@ std::optional<std::string> FindUnpackedMpqData(const std::vector<std::string> &p
return std::nullopt;
}
#else
std::optional<MpqArchive> LoadMPQ(const std::vector<std::string> &paths, string_view mpqName)
std::optional<MpqArchive> LoadMPQ(const std::vector<std::string> &paths, std::string_view mpqName)
{
std::optional<MpqArchive> archive;
std::string mpqAbsPath;
@ -133,7 +133,7 @@ std::vector<std::string> GetMPQSearchPaths()
// add `XDG_DATA_DIRS`.
const char *xdgDataDirs = std::getenv("XDG_DATA_DIRS");
if (xdgDataDirs != nullptr) {
for (const string_view path : SplitByChar(xdgDataDirs, ':')) {
for (const std::string_view path : SplitByChar(xdgDataDirs, ':')) {
std::string fullPath(path);
if (!path.empty() && path.back() != '/')
fullPath += '/';
@ -182,7 +182,7 @@ bool CheckExtraFontsVersion(AssetRef &&ref)
if (!handle.read(version_contents.get(), size))
return true;
return string_view { version_contents.get(), size } != ExtraFontsVersion;
return std::string_view { version_contents.get(), size } != ExtraFontsVersion;
}
} // namespace
@ -266,7 +266,7 @@ void LoadLanguageArchive()
lang_mpq = std::nullopt;
#endif
string_view code = GetLanguageCode();
std::string_view code = GetLanguageCode();
if (code != "en") {
std::string langMpqName { code };
#ifdef UNPACKED_MPQS

2
Source/inv.cpp

@ -1794,7 +1794,7 @@ int SyncDropItem(Point position, _item_indexes idx, uint16_t icreateinfo, int is
return PlaceItemInWorld(std::move(item), position);
}
int SyncDropEar(Point position, uint16_t icreateinfo, uint32_t iseed, uint8_t cursval, string_view heroname)
int SyncDropEar(Point position, uint16_t icreateinfo, uint32_t iseed, uint8_t cursval, std::string_view heroname)
{
if (ActiveItemCount >= MAXITEMS)
return -1;

2
Source/inv.h

@ -224,7 +224,7 @@ int ClampDurability(const Item &item, int durability);
int16_t ClampToHit(const Item &item, int16_t toHit);
uint8_t ClampMaxDam(const Item &item, uint8_t maxDam);
int SyncDropItem(Point position, _item_indexes idx, uint16_t icreateinfo, int iseed, int id, int dur, int mdur, int ch, int mch, int ivalue, uint32_t ibuff, int toHit, int maxDam);
int SyncDropEar(Point position, uint16_t icreateinfo, uint32_t iseed, uint8_t cursval, string_view heroname);
int SyncDropEar(Point position, uint16_t icreateinfo, uint32_t iseed, uint8_t cursval, std::string_view heroname);
int8_t CheckInvHLight();
bool CanUseScroll(Player &player, SpellID spell);
void ConsumeStaffCharge(Player &player);

2
Source/itemdat.cpp

@ -9,7 +9,7 @@
namespace devilution {
string_view ItemTypeToString(ItemType itemType)
std::string_view ItemTypeToString(ItemType itemType)
{
switch (itemType) {
case ItemType::Misc:

4
Source/itemdat.h

@ -6,10 +6,10 @@
#pragma once
#include <cstdint>
#include <string_view>
#include "objdat.h"
#include "spelldat.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -253,7 +253,7 @@ enum class ItemType : int8_t {
None = -1,
};
string_view ItemTypeToString(ItemType itemType);
std::string_view ItemTypeToString(ItemType itemType);
enum unique_base_item : int8_t {
UITYPE_NONE,

44
Source/items.cpp

@ -650,9 +650,9 @@ void GetBookSpell(Item &item, int lvl)
if (s == maxSpells)
s = 1;
}
const string_view spellName = GetSpellData(bs).sNameText;
const size_t iNameLen = string_view(item._iName).size();
const size_t iINameLen = string_view(item._iIName).size();
const std::string_view spellName = GetSpellData(bs).sNameText;
const size_t iNameLen = std::string_view(item._iName).size();
const size_t iINameLen = std::string_view(item._iIName).size();
CopyUtf8(item._iName + iNameLen, spellName, sizeof(item._iName) - iNameLen);
CopyUtf8(item._iIName + iINameLen, spellName, sizeof(item._iIName) - iINameLen);
item._iSpell = bs;
@ -1107,12 +1107,12 @@ int GetStaffPrefixId(int lvl, bool onlygood, bool hellfireItem)
std::string GenerateStaffName(const ItemData &baseItemData, SpellID spellId, bool translate)
{
string_view baseName = translate ? _(baseItemData.iName) : baseItemData.iName;
string_view spellName = translate ? pgettext("spell", GetSpellData(spellId).sNameText) : GetSpellData(spellId).sNameText;
string_view normalFmt = translate ? pgettext("spell", /* TRANSLATORS: Constructs item names. Format: {Item} of {Spell}. Example: War Staff of Firewall */ "{0} of {1}") : "{0} of {1}";
std::string_view baseName = translate ? _(baseItemData.iName) : baseItemData.iName;
std::string_view spellName = translate ? pgettext("spell", GetSpellData(spellId).sNameText) : GetSpellData(spellId).sNameText;
std::string_view normalFmt = translate ? pgettext("spell", /* TRANSLATORS: Constructs item names. Format: {Item} of {Spell}. Example: War Staff of Firewall */ "{0} of {1}") : "{0} of {1}";
std::string name = fmt::format(fmt::runtime(normalFmt), baseName, spellName);
if (!StringInPanel(name.c_str())) {
string_view shortName = translate ? _(baseItemData.iSName) : baseItemData.iSName;
std::string_view shortName = translate ? _(baseItemData.iSName) : baseItemData.iSName;
name = fmt::format(fmt::runtime(normalFmt), shortName, spellName);
}
return name;
@ -1120,14 +1120,14 @@ std::string GenerateStaffName(const ItemData &baseItemData, SpellID spellId, boo
std::string GenerateStaffNameMagical(const ItemData &baseItemData, SpellID spellId, int preidx, bool translate, std::optional<bool> forceNameLengthCheck)
{
string_view baseName = translate ? _(baseItemData.iName) : baseItemData.iName;
string_view magicFmt = translate ? pgettext("spell", /* TRANSLATORS: Constructs item names. Format: {Prefix} {Item} of {Spell}. Example: King's War Staff of Firewall */ "{0} {1} of {2}") : "{0} {1} of {2}";
string_view spellName = translate ? pgettext("spell", GetSpellData(spellId).sNameText) : GetSpellData(spellId).sNameText;
string_view prefixName = translate ? _(ItemPrefixes[preidx].PLName) : ItemPrefixes[preidx].PLName;
std::string_view baseName = translate ? _(baseItemData.iName) : baseItemData.iName;
std::string_view magicFmt = translate ? pgettext("spell", /* TRANSLATORS: Constructs item names. Format: {Prefix} {Item} of {Spell}. Example: King's War Staff of Firewall */ "{0} {1} of {2}") : "{0} {1} of {2}";
std::string_view spellName = translate ? pgettext("spell", GetSpellData(spellId).sNameText) : GetSpellData(spellId).sNameText;
std::string_view prefixName = translate ? _(ItemPrefixes[preidx].PLName) : ItemPrefixes[preidx].PLName;
std::string identifiedName = fmt::format(fmt::runtime(magicFmt), prefixName, baseName, spellName);
if (forceNameLengthCheck ? *forceNameLengthCheck : !StringInPanel(identifiedName.c_str())) {
string_view shortName = translate ? _(baseItemData.iSName) : baseItemData.iSName;
std::string_view shortName = translate ? _(baseItemData.iSName) : baseItemData.iSName;
identifiedName = fmt::format(fmt::runtime(magicFmt), prefixName, shortName, spellName);
}
return identifiedName;
@ -1156,16 +1156,16 @@ void GetStaffPower(const Player &player, Item &item, int lvl, SpellID bs, bool o
CalcItemValue(item);
}
std::string GenerateMagicItemName(const string_view &baseNamel, const PLStruct *pPrefix, const PLStruct *pSufix, bool translate)
std::string GenerateMagicItemName(const std::string_view &baseNamel, const PLStruct *pPrefix, const PLStruct *pSufix, bool translate)
{
if (pPrefix != nullptr && pSufix != nullptr) {
string_view fmt = translate ? _(/* TRANSLATORS: Constructs item names. Format: {Prefix} {Item} of {Suffix}. Example: King's Long Sword of the Whale */ "{0} {1} of {2}") : "{0} {1} of {2}";
std::string_view fmt = translate ? _(/* TRANSLATORS: Constructs item names. Format: {Prefix} {Item} of {Suffix}. Example: King's Long Sword of the Whale */ "{0} {1} of {2}") : "{0} {1} of {2}";
return fmt::format(fmt::runtime(fmt), translate ? _(pPrefix->PLName) : pPrefix->PLName, baseNamel, translate ? _(pSufix->PLName) : pSufix->PLName);
} else if (pPrefix != nullptr) {
string_view fmt = translate ? _(/* TRANSLATORS: Constructs item names. Format: {Prefix} {Item}. Example: King's Long Sword */ "{0} {1}") : "{0} {1}";
std::string_view fmt = translate ? _(/* TRANSLATORS: Constructs item names. Format: {Prefix} {Item}. Example: King's Long Sword */ "{0} {1}") : "{0} {1}";
return fmt::format(fmt::runtime(fmt), translate ? _(pPrefix->PLName) : pPrefix->PLName, baseNamel);
} else if (pSufix != nullptr) {
string_view fmt = translate ? _(/* TRANSLATORS: Constructs item names. Format: {Item} of {Suffix}. Example: Long Sword of the Whale */ "{0} of {1}") : "{0} of {1}";
std::string_view fmt = translate ? _(/* TRANSLATORS: Constructs item names. Format: {Item} of {Suffix}. Example: Long Sword of the Whale */ "{0} of {1}") : "{0} of {1}";
return fmt::format(fmt::runtime(fmt), baseNamel, translate ? _(pSufix->PLName) : pSufix->PLName);
}
@ -1824,8 +1824,8 @@ void printItemMiscGenericGamepad(const Item &item, const bool isOil, bool isCast
void printItemMiscGamepad(const Item &item, bool isOil, bool isCastOnTarget)
{
string_view activateButton;
string_view castButton;
std::string_view activateButton;
std::string_view castButton;
switch (GamepadType) {
case GamepadLayout::Generic:
printItemMiscGenericGamepad(item, isOil, isCastOnTarget);
@ -2275,7 +2275,7 @@ StringOrView GetTranslatedItemName(const Item &item)
return _(baseItemData.iName);
} else if (item._iMiscId == IMISC_BOOK) {
std::string name;
const string_view spellName = pgettext("spell", GetSpellData(item._iSpell).sNameText);
const std::string_view spellName = pgettext("spell", GetSpellData(item._iSpell).sNameText);
StrAppend(name, _(baseItemData.iName));
StrAppend(name, spellName);
return name;
@ -3398,7 +3398,7 @@ void RecreateItem(const Player &player, Item &item, _item_indexes idx, uint16_t
gbIsHellfire = tmpIsHellfire;
}
void RecreateEar(Item &item, uint16_t ic, uint32_t iseed, uint8_t bCursval, string_view heroName)
void RecreateEar(Item &item, uint16_t ic, uint32_t iseed, uint8_t bCursval, std::string_view heroName)
{
InitializeItem(item, IDI_EAR);
@ -3876,7 +3876,7 @@ bool DoOil(Player &player, int cii)
case IPL_NOMINSTR:
return _("no strength requirement");
case IPL_INVCURS:
return { string_view(" ") };
return { std::string_view(" ") };
case IPL_ADDACLIFE:
if (item._iFMinDam == item._iFMaxDam)
return fmt::format(fmt::runtime(_("lightning damage: {:d}")), item._iFMinDam);
@ -4788,7 +4788,7 @@ void Item::updateRequiredStatsCacheForPlayer(const Player &player)
StringOrView Item::getName() const
{
if (isEmpty()) {
return string_view("");
return std::string_view("");
} else if (!_iIdentified || _iCreateInfo == 0 || _iMagical == ITEM_QUALITY_NORMAL) {
return GetTranslatedItemName(*this);
} else if (_iMagical == ITEM_QUALITY_UNIQUE) {

2
Source/items.h

@ -520,7 +520,7 @@ void CreateRndItem(Point position, bool onlygood, bool sendmsg, bool delta);
void CreateRndUseful(Point position, bool sendmsg);
void CreateTypeItem(Point position, bool onlygood, ItemType itemType, int imisc, bool sendmsg, bool delta, bool spawn = false);
void RecreateItem(const Player &player, Item &item, _item_indexes idx, uint16_t icreateinfo, uint32_t iseed, int ivalue, bool isHellfire);
void RecreateEar(Item &item, uint16_t ic, uint32_t iseed, uint8_t bCursval, string_view heroName);
void RecreateEar(Item &item, uint16_t ic, uint32_t iseed, uint8_t bCursval, std::string_view heroName);
void CornerstoneSave();
void CornerstoneLoad(Point position);
void SpawnQuestItem(_item_indexes itemid, Point position, int randarea, int selflag, bool sendmsg);

2
Source/loadsave.cpp

@ -896,7 +896,7 @@ void LoadPortal(LoadHelper *file, int i)
pPortal->ltype = GetLevelType(pPortal->level);
}
void GetLevelNames(string_view prefix, char *out)
void GetLevelNames(std::string_view prefix, char *out)
{
char suf;
uint8_t num;

4
Source/minitext.cpp

@ -6,6 +6,7 @@
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include "DiabloUI/ui_flags.hpp"
@ -19,7 +20,6 @@
#include "playerdat.hpp"
#include "textdat.h"
#include "utils/language.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -39,7 +39,7 @@ const int LineHeight = 38;
std::vector<std::string> TextLines;
void LoadText(string_view text)
void LoadText(std::string_view text)
{
TextLines.clear();

2
Source/misdat.h

@ -7,6 +7,7 @@
#include <cstddef>
#include <cstdint>
#include <string_view>
#include <type_traits>
#include <vector>
@ -15,7 +16,6 @@
#include "engine/clx_sprite.hpp"
#include "spelldat.h"
#include "utils/enum_traits.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {

8
Source/monster.cpp

@ -11,6 +11,7 @@
#include <algorithm>
#include <array>
#include <string_view>
#include <fmt/core.h>
#include <fmt/format.h>
@ -42,7 +43,6 @@
#include "utils/cl2_to_clx.hpp"
#include "utils/file_name_generator.hpp"
#include "utils/language.h"
#include "utils/stdcompat/string_view.hpp"
#include "utils/str_cat.hpp"
#include "utils/utf8.hpp"
@ -2959,7 +2959,7 @@ void HorkDemonAi(Monster &monster)
monster.checkStandAnimationIsLoaded(monster.direction);
}
string_view GetMonsterTypeText(const MonsterData &monsterData)
std::string_view GetMonsterTypeText(const MonsterData &monsterData)
{
switch (monsterData.monsterClass) {
case MonsterClass::Animal:
@ -3321,10 +3321,10 @@ void InitMonsterSND(CMonster &monsterType)
};
const MonsterData &data = MonstersData[monsterType.type];
string_view soundSuffix = data.soundSuffix != nullptr ? data.soundSuffix : data.assetsSuffix;
std::string_view soundSuffix = data.soundSuffix != nullptr ? data.soundSuffix : data.assetsSuffix;
for (int i = 0; i < 4; i++) {
string_view prefix = prefixes[i];
std::string_view prefix = prefixes[i];
if (prefix == "s" && !data.hasSpecialSound)
continue;

2
Source/monster.h

@ -321,7 +321,7 @@ struct Monster { // note: missing field _mAFNum
* Internally it returns a name stored in global array of monsters' data.
* @return Monster's name
*/
string_view name() const
std::string_view name() const
{
if (uniqueType != UniqueMonsterType::None)
return pgettext("monster", UniqueMonstersData[static_cast<int8_t>(uniqueType)].mName);

2
Source/msg.cpp

@ -55,7 +55,7 @@ int dwRecCount;
namespace {
#ifdef LOG_RECEIVED_MESSAGES
string_view CmdIdString(_cmd_id cmd)
std::string_view CmdIdString(_cmd_id cmd)
{
// clang-format off
switch (cmd) {

8
Source/multi.cpp

@ -7,6 +7,7 @@
#include <cstddef>
#include <cstdint>
#include <ctime>
#include <string_view>
#include <SDL.h>
#include <config.h>
@ -29,7 +30,6 @@
#include "tmsg.h"
#include "utils/endian.hpp"
#include "utils/language.h"
#include "utils/stdcompat/string_view.hpp"
#include "utils/str_cat.hpp"
namespace devilution {
@ -158,7 +158,7 @@ bool IsNetPlayerValid(const Player &player)
&& static_cast<uint8_t>(player._pClass) < enum_size<HeroClass>::value
&& player.plrlevel < NUMLEVELS
&& InDungeonBounds(player.position.tile)
&& !string_view(player._pName).empty();
&& !std::string_view(player._pName).empty();
}
void CheckPlayerInfoTimeouts()
@ -259,7 +259,7 @@ void PlayerLeftMsg(int pnum, bool left)
delta_close_portal(pnum);
RemovePlrMissiles(player);
if (left) {
string_view pszFmt = _("Player '{:s}' just left the game");
std::string_view pszFmt = _("Player '{:s}' just left the game");
switch (sgdwPlayerLeftReasonTbl[pnum]) {
case LEAVE_ENDING:
pszFmt = _("Player '{:s}' killed Diablo and left the game!");
@ -843,7 +843,7 @@ void recv_plrinfo(int pnum, const TCmdPlrInfoHdr &header, bool recv)
player.plractive = true;
gbActivePlayers++;
string_view szEvent;
std::string_view szEvent;
if (sgbPlayerTurnBitTbl[pnum]) {
szEvent = _("Player '{:s}' (level {:d}) just joined the game");
} else {

2
Source/objects.cpp

@ -4876,7 +4876,7 @@ StringOrView Object::name() const
default:
break;
}
return string_view();
return std::string_view();
}
void GetObjectStr(const Object &object)

128
Source/options.cpp

@ -162,7 +162,7 @@ float GetIniFloat(const char *sectionName, const char *keyName, float defaultVal
return (float)GetIni().GetDoubleValue(sectionName, keyName, defaultValue);
}
bool GetIniValue(string_view sectionName, string_view keyName, char *string, int stringSize, const char *defaultString = "")
bool GetIniValue(std::string_view sectionName, std::string_view keyName, char *string, int stringSize, const char *defaultString = "")
{
std::string sectionNameStr { sectionName };
std::string keyNameStr { keyName };
@ -212,7 +212,7 @@ void SetIniValue(const char *sectionName, const char *keyName, const char *value
ini.SetValue(sectionName, keyName, value, nullptr, true);
}
void SetIniValue(string_view sectionName, string_view keyName, string_view value)
void SetIniValue(std::string_view sectionName, std::string_view keyName, std::string_view value)
{
std::string sectionNameStr { sectionName };
std::string keyNameStr { keyName };
@ -413,11 +413,11 @@ void SaveOptions()
SaveIni();
}
string_view OptionEntryBase::GetName() const
std::string_view OptionEntryBase::GetName() const
{
return _(name);
}
string_view OptionEntryBase::GetDescription() const
std::string_view OptionEntryBase::GetDescription() const
{
return _(description);
}
@ -435,11 +435,11 @@ void OptionEntryBase::NotifyValueChanged()
callback();
}
void OptionEntryBoolean::LoadFromIni(string_view category)
void OptionEntryBoolean::LoadFromIni(std::string_view category)
{
value = GetIniBool(category.data(), key.data(), defaultValue);
}
void OptionEntryBoolean::SaveToIni(string_view category) const
void OptionEntryBoolean::SaveToIni(std::string_view category) const
{
SetIniValue(category.data(), key.data(), value);
}
@ -452,7 +452,7 @@ OptionEntryType OptionEntryBoolean::GetType() const
{
return OptionEntryType::Boolean;
}
string_view OptionEntryBoolean::GetValueDescription() const
std::string_view OptionEntryBoolean::GetValueDescription() const
{
return value ? _("ON") : _("OFF");
}
@ -461,16 +461,16 @@ OptionEntryType OptionEntryListBase::GetType() const
{
return OptionEntryType::List;
}
string_view OptionEntryListBase::GetValueDescription() const
std::string_view OptionEntryListBase::GetValueDescription() const
{
return GetListDescription(GetActiveListIndex());
}
void OptionEntryEnumBase::LoadFromIni(string_view category)
void OptionEntryEnumBase::LoadFromIni(std::string_view category)
{
value = GetIniInt(category.data(), key.data(), defaultValue);
}
void OptionEntryEnumBase::SaveToIni(string_view category) const
void OptionEntryEnumBase::SaveToIni(std::string_view category) const
{
SetIniValue(category.data(), key.data(), value);
}
@ -479,7 +479,7 @@ void OptionEntryEnumBase::SetValueInternal(int value)
this->value = value;
this->NotifyValueChanged();
}
void OptionEntryEnumBase::AddEntry(int value, string_view name)
void OptionEntryEnumBase::AddEntry(int value, std::string_view name)
{
entryValues.push_back(value);
entryNames.push_back(name);
@ -488,7 +488,7 @@ size_t OptionEntryEnumBase::GetListSize() const
{
return entryValues.size();
}
string_view OptionEntryEnumBase::GetListDescription(size_t index) const
std::string_view OptionEntryEnumBase::GetListDescription(size_t index) const
{
return _(entryNames[index].data());
}
@ -505,7 +505,7 @@ void OptionEntryEnumBase::SetActiveListIndex(size_t index)
this->NotifyValueChanged();
}
void OptionEntryIntBase::LoadFromIni(string_view category)
void OptionEntryIntBase::LoadFromIni(std::string_view category)
{
value = GetIniInt(category.data(), key.data(), defaultValue);
if (std::find(entryValues.begin(), entryValues.end(), value) == entryValues.end()) {
@ -514,7 +514,7 @@ void OptionEntryIntBase::LoadFromIni(string_view category)
entryNames.clear();
}
}
void OptionEntryIntBase::SaveToIni(string_view category) const
void OptionEntryIntBase::SaveToIni(std::string_view category) const
{
SetIniValue(category.data(), key.data(), value);
}
@ -531,7 +531,7 @@ size_t OptionEntryIntBase::GetListSize() const
{
return entryValues.size();
}
string_view OptionEntryIntBase::GetListDescription(size_t index) const
std::string_view OptionEntryIntBase::GetListDescription(size_t index) const
{
if (entryNames.empty()) {
for (auto value : entryValues) {
@ -553,15 +553,15 @@ void OptionEntryIntBase::SetActiveListIndex(size_t index)
this->NotifyValueChanged();
}
string_view OptionCategoryBase::GetKey() const
std::string_view OptionCategoryBase::GetKey() const
{
return key;
}
string_view OptionCategoryBase::GetName() const
std::string_view OptionCategoryBase::GetName() const
{
return _(name);
}
string_view OptionCategoryBase::GetDescription() const
std::string_view OptionCategoryBase::GetDescription() const
{
return _(description);
}
@ -680,11 +680,11 @@ OptionEntryResolution::OptionEntryResolution()
: OptionEntryListBase("", OptionEntryFlags::CantChangeInGame | OptionEntryFlags::RecreateUI, N_("Resolution"), N_("Affect the game's internal resolution and determine your view area. Note: This can differ from screen resolution, when Upscaling, Integer Scaling or Fit to Screen is used."))
{
}
void OptionEntryResolution::LoadFromIni(string_view category)
void OptionEntryResolution::LoadFromIni(std::string_view category)
{
size = { GetIniInt(category.data(), "Width", DEFAULT_WIDTH), GetIniInt(category.data(), "Height", DEFAULT_HEIGHT) };
}
void OptionEntryResolution::SaveToIni(string_view category) const
void OptionEntryResolution::SaveToIni(std::string_view category) const
{
SetIniValue(category.data(), "Width", size.width);
SetIniValue(category.data(), "Height", size.height);
@ -800,7 +800,7 @@ size_t OptionEntryResolution::GetListSize() const
CheckResolutionsAreInitialized();
return resolutions.size();
}
string_view OptionEntryResolution::GetListDescription(size_t index) const
std::string_view OptionEntryResolution::GetListDescription(size_t index) const
{
CheckResolutionsAreInitialized();
return resolutions[index].second;
@ -827,7 +827,7 @@ OptionEntryResampler::OptionEntryResampler()
N_("Resampler"), N_("Audio resampler"))
{
}
void OptionEntryResampler::LoadFromIni(string_view category)
void OptionEntryResampler::LoadFromIni(std::string_view category)
{
char resamplerStr[32];
if (GetIniValue(category, key, resamplerStr, sizeof(resamplerStr))) {
@ -842,7 +842,7 @@ void OptionEntryResampler::LoadFromIni(string_view category)
UpdateDependentOptions();
}
void OptionEntryResampler::SaveToIni(string_view category) const
void OptionEntryResampler::SaveToIni(std::string_view category) const
{
SetIniValue(category, key, ResamplerToString(resampler_));
}
@ -852,7 +852,7 @@ size_t OptionEntryResampler::GetListSize() const
return NumResamplers;
}
string_view OptionEntryResampler::GetListDescription(size_t index) const
std::string_view OptionEntryResampler::GetListDescription(size_t index) const
{
return ResamplerToString(static_cast<Resampler>(index));
}
@ -884,14 +884,14 @@ OptionEntryAudioDevice::OptionEntryAudioDevice()
: OptionEntryListBase("Device", OptionEntryFlags::CantChangeInGame, N_("Device"), N_("Audio device"))
{
}
void OptionEntryAudioDevice::LoadFromIni(string_view category)
void OptionEntryAudioDevice::LoadFromIni(std::string_view category)
{
char deviceStr[100];
GetIniValue(category, key, deviceStr, sizeof(deviceStr), "");
deviceName_ = deviceStr;
}
void OptionEntryAudioDevice::SaveToIni(string_view category) const
void OptionEntryAudioDevice::SaveToIni(std::string_view category) const
{
#if SDL_VERSION_ATLEAST(2, 0, 0)
SetIniValue(category, key, deviceName_);
@ -907,17 +907,17 @@ size_t OptionEntryAudioDevice::GetListSize() const
#endif
}
string_view OptionEntryAudioDevice::GetListDescription(size_t index) const
std::string_view OptionEntryAudioDevice::GetListDescription(size_t index) const
{
constexpr int MaxWidth = 500;
string_view deviceName = GetDeviceName(index);
std::string_view deviceName = GetDeviceName(index);
if (deviceName.empty())
return "System Default";
while (GetLineWidth(deviceName, GameFont24, 1) > MaxWidth) {
size_t lastSymbolIndex = FindLastUtf8Symbols(deviceName);
deviceName = string_view(deviceName.data(), lastSymbolIndex);
deviceName = std::string_view(deviceName.data(), lastSymbolIndex);
}
return deviceName;
@ -926,7 +926,7 @@ string_view OptionEntryAudioDevice::GetListDescription(size_t index) const
size_t OptionEntryAudioDevice::GetActiveListIndex() const
{
for (size_t i = 0; i < GetListSize(); i++) {
string_view deviceName = GetDeviceName(i);
std::string_view deviceName = GetDeviceName(i);
if (deviceName == deviceName_)
return i;
}
@ -939,7 +939,7 @@ void OptionEntryAudioDevice::SetActiveListIndex(size_t index)
NotifyValueChanged();
}
string_view OptionEntryAudioDevice::GetDeviceName(size_t index) const
std::string_view OptionEntryAudioDevice::GetDeviceName(size_t index) const
{
#if SDL_VERSION_ATLEAST(2, 0, 0)
if (index != 0)
@ -1167,7 +1167,7 @@ OptionEntryLanguageCode::OptionEntryLanguageCode()
: OptionEntryListBase("Code", OptionEntryFlags::CantChangeInGame | OptionEntryFlags::RecreateUI, N_("Language"), N_("Define what language to use in game."))
{
}
void OptionEntryLanguageCode::LoadFromIni(string_view category)
void OptionEntryLanguageCode::LoadFromIni(std::string_view category)
{
if (GetIniValue(category, key, szCode, sizeof(szCode))) {
if (HasTranslation(szCode)) {
@ -1210,7 +1210,7 @@ void OptionEntryLanguageCode::LoadFromIni(string_view category)
LogVerbose("No suitable translation found");
strcpy(szCode, "en");
}
void OptionEntryLanguageCode::SaveToIni(string_view category) const
void OptionEntryLanguageCode::SaveToIni(std::string_view category) const
{
SetIniValue(category, key, szCode);
}
@ -1260,7 +1260,7 @@ size_t OptionEntryLanguageCode::GetListSize() const
CheckLanguagesAreInitialized();
return languages.size();
}
string_view OptionEntryLanguageCode::GetListDescription(size_t index) const
std::string_view OptionEntryLanguageCode::GetListDescription(size_t index) const
{
CheckLanguagesAreInitialized();
return languages[index].second;
@ -1333,7 +1333,7 @@ std::vector<OptionEntryBase *> KeymapperOptions::GetEntries()
return entries;
}
KeymapperOptions::Action::Action(string_view key, const char *name, const char *description, uint32_t defaultKey, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index)
KeymapperOptions::Action::Action(std::string_view key, const char *name, const char *description, uint32_t defaultKey, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index)
: OptionEntryBase(key, OptionEntryFlags::None, name, description)
, defaultKey(defaultKey)
, actionPressed(std::move(actionPressed))
@ -1342,12 +1342,12 @@ KeymapperOptions::Action::Action(string_view key, const char *name, const char *
, dynamicIndex(index)
{
if (index != 0) {
dynamicKey = fmt::format(fmt::runtime(fmt::string_view(key.data(), key.size())), index);
dynamicKey = fmt::format(fmt::runtime(std::string_view(key.data(), key.size())), index);
this->key = dynamicKey;
}
}
string_view KeymapperOptions::Action::GetName() const
std::string_view KeymapperOptions::Action::GetName() const
{
if (dynamicIndex == 0)
return _(name);
@ -1355,7 +1355,7 @@ string_view KeymapperOptions::Action::GetName() const
return dynamicName;
}
void KeymapperOptions::Action::LoadFromIni(string_view category)
void KeymapperOptions::Action::LoadFromIni(std::string_view category)
{
std::array<char, 64> result;
if (!GetIniValue(category.data(), key.data(), result.data(), result.size())) {
@ -1381,7 +1381,7 @@ void KeymapperOptions::Action::LoadFromIni(string_view category)
// actions while keeping the same order as they have been added.
SetValue(keyIt->second);
}
void KeymapperOptions::Action::SaveToIni(string_view category) const
void KeymapperOptions::Action::SaveToIni(std::string_view category) const
{
if (boundKey == SDLK_UNKNOWN) {
// Just add an empty config entry if the action is unbound.
@ -1395,7 +1395,7 @@ void KeymapperOptions::Action::SaveToIni(string_view category) const
SetIniValue(category.data(), key.data(), keyNameIt->second.c_str());
}
string_view KeymapperOptions::Action::GetValueDescription() const
std::string_view KeymapperOptions::Action::GetValueDescription() const
{
if (boundKey == SDLK_UNKNOWN)
return "";
@ -1435,7 +1435,7 @@ bool KeymapperOptions::Action::SetValue(int value)
return true;
}
void KeymapperOptions::AddAction(string_view key, const char *name, const char *description, uint32_t defaultKey, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index)
void KeymapperOptions::AddAction(std::string_view key, const char *name, const char *description, uint32_t defaultKey, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index)
{
actions.emplace_front(key, name, description, defaultKey, std::move(actionPressed), std::move(actionReleased), std::move(enable), index);
}
@ -1494,7 +1494,7 @@ bool KeymapperOptions::IsNumberEntryKey(SDL_Keycode vkey) const
return ((vkey >= SDLK_0 && vkey <= SDLK_9) || vkey == SDLK_BACKSPACE);
}
string_view KeymapperOptions::KeyNameForAction(string_view actionName) const
std::string_view KeymapperOptions::KeyNameForAction(std::string_view actionName) const
{
for (const Action &action : actions) {
if (action.key == actionName && action.boundKey != SDLK_UNKNOWN) {
@ -1504,7 +1504,7 @@ string_view KeymapperOptions::KeyNameForAction(string_view actionName) const
return "";
}
uint32_t KeymapperOptions::KeyForAction(string_view actionName) const
uint32_t KeymapperOptions::KeyForAction(std::string_view actionName) const
{
for (const Action &action : actions) {
if (action.key == actionName && action.boundKey != SDLK_UNKNOWN) {
@ -1552,7 +1552,7 @@ std::vector<OptionEntryBase *> PadmapperOptions::GetEntries()
return entries;
}
PadmapperOptions::Action::Action(string_view key, const char *name, const char *description, ControllerButtonCombo defaultInput, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index)
PadmapperOptions::Action::Action(std::string_view key, const char *name, const char *description, ControllerButtonCombo defaultInput, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index)
: OptionEntryBase(key, OptionEntryFlags::None, name, description)
, defaultInput(defaultInput)
, actionPressed(std::move(actionPressed))
@ -1561,12 +1561,12 @@ PadmapperOptions::Action::Action(string_view key, const char *name, const char *
, dynamicIndex(index)
{
if (index != 0) {
dynamicKey = fmt::format(fmt::runtime(fmt::string_view(key.data(), key.size())), index);
dynamicKey = fmt::format(fmt::runtime(std::string_view(key.data(), key.size())), index);
this->key = dynamicKey;
}
}
string_view PadmapperOptions::Action::GetName() const
std::string_view PadmapperOptions::Action::GetName() const
{
if (dynamicIndex == 0)
return _(name);
@ -1574,7 +1574,7 @@ string_view PadmapperOptions::Action::GetName() const
return dynamicName;
}
void PadmapperOptions::Action::LoadFromIni(string_view category)
void PadmapperOptions::Action::LoadFromIni(std::string_view category)
{
std::array<char, 64> result;
if (!GetIniValue(category.data(), key.data(), result.data(), result.size())) {
@ -1621,7 +1621,7 @@ void PadmapperOptions::Action::LoadFromIni(string_view category)
// the actions while keeping the same order as they have been added.
SetValue(input);
}
void PadmapperOptions::Action::SaveToIni(string_view category) const
void PadmapperOptions::Action::SaveToIni(std::string_view category) const
{
if (boundInput.button == ControllerButton_NONE) {
// Just add an empty config entry if the action is unbound.
@ -1652,18 +1652,18 @@ void PadmapperOptions::Action::UpdateValueDescription() const
boundInputShortDescription = "";
return;
}
string_view buttonName = ToString(boundInput.button);
std::string_view buttonName = ToString(boundInput.button);
if (boundInput.modifier == ControllerButton_NONE) {
boundInputDescription = std::string(buttonName);
boundInputShortDescription = std::string(Shorten(buttonName));
return;
}
string_view modifierName = ToString(boundInput.modifier);
std::string_view modifierName = ToString(boundInput.modifier);
boundInputDescription = StrCat(modifierName, "+", buttonName);
boundInputShortDescription = StrCat(Shorten(modifierName), "+", Shorten(buttonName));
}
string_view PadmapperOptions::Action::Shorten(string_view buttonName) const
std::string_view PadmapperOptions::Action::Shorten(std::string_view buttonName) const
{
size_t index = 0;
size_t chars = 0;
@ -1674,15 +1674,15 @@ string_view PadmapperOptions::Action::Shorten(string_view buttonName) const
break;
index++;
}
return string_view(buttonName.data(), index);
return std::string_view(buttonName.data(), index);
}
string_view PadmapperOptions::Action::GetValueDescription() const
std::string_view PadmapperOptions::Action::GetValueDescription() const
{
return GetValueDescription(false);
}
string_view PadmapperOptions::Action::GetValueDescription(bool useShortName) const
std::string_view PadmapperOptions::Action::GetValueDescription(bool useShortName) const
{
if (GamepadType != boundInputDescriptionType)
UpdateValueDescription();
@ -1699,7 +1699,7 @@ bool PadmapperOptions::Action::SetValue(ControllerButtonCombo value)
return true;
}
void PadmapperOptions::AddAction(string_view key, const char *name, const char *description, ControllerButtonCombo defaultInput, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index)
void PadmapperOptions::AddAction(std::string_view key, const char *name, const char *description, ControllerButtonCombo defaultInput, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index)
{
if (committed)
return;
@ -1751,7 +1751,7 @@ void PadmapperOptions::ReleaseAllActiveButtons()
}
}
bool PadmapperOptions::IsActive(string_view actionName) const
bool PadmapperOptions::IsActive(std::string_view actionName) const
{
for (const Action &action : actions) {
if (action.key != actionName)
@ -1762,7 +1762,7 @@ bool PadmapperOptions::IsActive(string_view actionName) const
return false;
}
string_view PadmapperOptions::ActionNameTriggeredByButtonEvent(ControllerButtonEvent ctrlEvent) const
std::string_view PadmapperOptions::ActionNameTriggeredByButtonEvent(ControllerButtonEvent ctrlEvent) const
{
if (!gbRunGame)
return "";
@ -1777,7 +1777,7 @@ string_view PadmapperOptions::ActionNameTriggeredByButtonEvent(ControllerButtonE
return releaseAction->key;
}
string_view PadmapperOptions::InputNameForAction(string_view actionName, bool useShortName) const
std::string_view PadmapperOptions::InputNameForAction(std::string_view actionName, bool useShortName) const
{
for (const Action &action : actions) {
if (action.key == actionName && action.boundInput.button != ControllerButton_NONE) {
@ -1787,7 +1787,7 @@ string_view PadmapperOptions::InputNameForAction(string_view actionName, bool us
return "";
}
ControllerButtonCombo PadmapperOptions::ButtonComboForAction(string_view actionName) const
ControllerButtonCombo PadmapperOptions::ButtonComboForAction(std::string_view actionName) const
{
for (const auto &action : actions) {
if (action.key == actionName && action.boundInput.button != ControllerButton_NONE) {
@ -1834,10 +1834,10 @@ bool PadmapperOptions::CanDeferToMovementHandler(const Action &action) const
return false;
if (spselflag) {
const string_view prefix { "QuickSpell" };
const string_view key { action.key };
const std::string_view prefix { "QuickSpell" };
const std::string_view key { action.key };
if (key.size() >= prefix.size()) {
const string_view truncated { key.data(), prefix.size() };
const std::string_view truncated { key.data(), prefix.size() };
if (truncated == prefix)
return false;
}
@ -1855,7 +1855,7 @@ constexpr char ResamplerSpeex[] = "Speex";
constexpr char ResamplerSDL[] = "SDL";
} // namespace
string_view ResamplerToString(Resampler resampler)
std::string_view ResamplerToString(Resampler resampler)
{
switch (resampler) {
#ifdef DEVILUTIONX_RESAMPLER_SPEEX
@ -1871,7 +1871,7 @@ string_view ResamplerToString(Resampler resampler)
}
}
std::optional<Resampler> ResamplerFromString(string_view resampler)
std::optional<Resampler> ResamplerFromString(std::string_view resampler)
{
#ifdef DEVILUTIONX_RESAMPLER_SPEEX
if (resampler == ResamplerSpeex)

142
Source/options.h

@ -5,6 +5,7 @@
#include <cstdint>
#include <forward_list>
#include <optional>
#include <string_view>
#include <unordered_map>
#include <SDL_version.h>
@ -15,7 +16,6 @@
#include "engine/sound_defs.hpp"
#include "pack.h"
#include "utils/enum_traits.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -57,8 +57,8 @@ enum class Resampler : uint8_t {
#endif
};
string_view ResamplerToString(Resampler resampler);
std::optional<Resampler> ResamplerFromString(string_view resampler);
std::string_view ResamplerToString(Resampler resampler);
std::optional<Resampler> ResamplerFromString(std::string_view resampler);
enum class FloatingNumbers : uint8_t {
/** @brief Show no floating numbers. */
@ -100,28 +100,28 @@ use_enum_as_flags(OptionEntryFlags);
class OptionEntryBase {
public:
OptionEntryBase(string_view key, OptionEntryFlags flags, const char *name, const char *description)
OptionEntryBase(std::string_view key, OptionEntryFlags flags, const char *name, const char *description)
: flags(flags)
, key(key)
, name(name)
, description(description)
{
}
[[nodiscard]] virtual string_view GetName() const;
[[nodiscard]] string_view GetDescription() const;
[[nodiscard]] virtual std::string_view GetName() const;
[[nodiscard]] std::string_view GetDescription() const;
[[nodiscard]] virtual OptionEntryType GetType() const = 0;
[[nodiscard]] OptionEntryFlags GetFlags() const;
void SetValueChangedCallback(std::function<void()> callback);
[[nodiscard]] virtual string_view GetValueDescription() const = 0;
virtual void LoadFromIni(string_view category) = 0;
virtual void SaveToIni(string_view category) const = 0;
[[nodiscard]] virtual std::string_view GetValueDescription() const = 0;
virtual void LoadFromIni(std::string_view category) = 0;
virtual void SaveToIni(std::string_view category) const = 0;
OptionEntryFlags flags;
protected:
string_view key;
std::string_view key;
const char *name;
const char *description;
void NotifyValueChanged();
@ -132,7 +132,7 @@ private:
class OptionEntryBoolean : public OptionEntryBase {
public:
OptionEntryBoolean(string_view key, OptionEntryFlags flags, const char *name, const char *description, bool defaultValue)
OptionEntryBoolean(std::string_view key, OptionEntryFlags flags, const char *name, const char *description, bool defaultValue)
: OptionEntryBase(key, flags, name, description)
, defaultValue(defaultValue)
, value(defaultValue)
@ -145,9 +145,9 @@ public:
void SetValue(bool value);
[[nodiscard]] OptionEntryType GetType() const override;
[[nodiscard]] string_view GetValueDescription() const override;
void LoadFromIni(string_view category) override;
void SaveToIni(string_view category) const override;
[[nodiscard]] std::string_view GetValueDescription() const override;
void LoadFromIni(std::string_view category) override;
void SaveToIni(std::string_view category) const override;
private:
bool defaultValue;
@ -157,15 +157,15 @@ private:
class OptionEntryListBase : public OptionEntryBase {
public:
[[nodiscard]] virtual size_t GetListSize() const = 0;
[[nodiscard]] virtual string_view GetListDescription(size_t index) const = 0;
[[nodiscard]] virtual std::string_view GetListDescription(size_t index) const = 0;
[[nodiscard]] virtual size_t GetActiveListIndex() const = 0;
virtual void SetActiveListIndex(size_t index) = 0;
[[nodiscard]] OptionEntryType GetType() const override;
[[nodiscard]] string_view GetValueDescription() const override;
[[nodiscard]] std::string_view GetValueDescription() const override;
protected:
OptionEntryListBase(string_view key, OptionEntryFlags flags, const char *name, const char *description)
OptionEntryListBase(std::string_view key, OptionEntryFlags flags, const char *name, const char *description)
: OptionEntryBase(key, flags, name, description)
{
}
@ -173,16 +173,16 @@ protected:
class OptionEntryEnumBase : public OptionEntryListBase {
public:
void LoadFromIni(string_view category) override;
void SaveToIni(string_view category) const override;
void LoadFromIni(std::string_view category) override;
void SaveToIni(std::string_view category) const override;
[[nodiscard]] size_t GetListSize() const override;
[[nodiscard]] string_view GetListDescription(size_t index) const override;
[[nodiscard]] std::string_view GetListDescription(size_t index) const override;
[[nodiscard]] size_t GetActiveListIndex() const override;
void SetActiveListIndex(size_t index) override;
protected:
OptionEntryEnumBase(string_view key, OptionEntryFlags flags, const char *name, const char *description, int defaultValue)
OptionEntryEnumBase(std::string_view key, OptionEntryFlags flags, const char *name, const char *description, int defaultValue)
: OptionEntryListBase(key, flags, name, description)
, defaultValue(defaultValue)
, value(defaultValue)
@ -195,19 +195,19 @@ protected:
}
void SetValueInternal(int value);
void AddEntry(int value, string_view name);
void AddEntry(int value, std::string_view name);
private:
int defaultValue;
int value;
std::vector<string_view> entryNames;
std::vector<std::string_view> entryNames;
std::vector<int> entryValues;
};
template <typename T>
class OptionEntryEnum : public OptionEntryEnumBase {
public:
OptionEntryEnum(string_view key, OptionEntryFlags flags, const char *name, const char *description, T defaultValue, std::initializer_list<std::pair<T, string_view>> entries)
OptionEntryEnum(std::string_view key, OptionEntryFlags flags, const char *name, const char *description, T defaultValue, std::initializer_list<std::pair<T, std::string_view>> entries)
: OptionEntryEnumBase(key, flags, name, description, static_cast<int>(defaultValue))
{
for (auto entry : entries) {
@ -226,16 +226,16 @@ public:
class OptionEntryIntBase : public OptionEntryListBase {
public:
void LoadFromIni(string_view category) override;
void SaveToIni(string_view category) const override;
void LoadFromIni(std::string_view category) override;
void SaveToIni(std::string_view category) const override;
[[nodiscard]] size_t GetListSize() const override;
[[nodiscard]] string_view GetListDescription(size_t index) const override;
[[nodiscard]] std::string_view GetListDescription(size_t index) const override;
[[nodiscard]] size_t GetActiveListIndex() const override;
void SetActiveListIndex(size_t index) override;
protected:
OptionEntryIntBase(string_view key, OptionEntryFlags flags, const char *name, const char *description, int defaultValue)
OptionEntryIntBase(std::string_view key, OptionEntryFlags flags, const char *name, const char *description, int defaultValue)
: OptionEntryListBase(key, flags, name, description)
, defaultValue(defaultValue)
, value(defaultValue)
@ -260,14 +260,14 @@ private:
template <typename T>
class OptionEntryInt : public OptionEntryIntBase {
public:
OptionEntryInt(string_view key, OptionEntryFlags flags, const char *name, const char *description, T defaultValue, std::initializer_list<T> entries)
OptionEntryInt(std::string_view key, OptionEntryFlags flags, const char *name, const char *description, T defaultValue, std::initializer_list<T> entries)
: OptionEntryIntBase(key, flags, name, description, static_cast<int>(defaultValue))
{
for (auto entry : entries) {
AddEntry(static_cast<int>(entry));
}
}
OptionEntryInt(string_view key, OptionEntryFlags flags, const char *name, const char *description, T defaultValue)
OptionEntryInt(std::string_view key, OptionEntryFlags flags, const char *name, const char *description, T defaultValue)
: OptionEntryInt(key, flags, name, description, defaultValue, { defaultValue })
{
}
@ -285,20 +285,20 @@ class OptionEntryLanguageCode : public OptionEntryListBase {
public:
OptionEntryLanguageCode();
void LoadFromIni(string_view category) override;
void SaveToIni(string_view category) const override;
void LoadFromIni(std::string_view category) override;
void SaveToIni(std::string_view category) const override;
[[nodiscard]] size_t GetListSize() const override;
[[nodiscard]] string_view GetListDescription(size_t index) const override;
[[nodiscard]] std::string_view GetListDescription(size_t index) const override;
[[nodiscard]] size_t GetActiveListIndex() const override;
void SetActiveListIndex(size_t index) override;
string_view operator*() const
std::string_view operator*() const
{
return szCode;
}
OptionEntryLanguageCode &operator=(string_view code)
OptionEntryLanguageCode &operator=(std::string_view code)
{
assert(code.size() < 6);
memcpy(szCode, code.data(), code.size());
@ -318,11 +318,11 @@ class OptionEntryResolution : public OptionEntryListBase {
public:
OptionEntryResolution();
void LoadFromIni(string_view category) override;
void SaveToIni(string_view category) const override;
void LoadFromIni(std::string_view category) override;
void SaveToIni(std::string_view category) const override;
[[nodiscard]] size_t GetListSize() const override;
[[nodiscard]] string_view GetListDescription(size_t index) const override;
[[nodiscard]] std::string_view GetListDescription(size_t index) const override;
[[nodiscard]] size_t GetActiveListIndex() const override;
void SetActiveListIndex(size_t index) override;
void InvalidateList();
@ -344,11 +344,11 @@ class OptionEntryResampler : public OptionEntryListBase {
public:
OptionEntryResampler();
void LoadFromIni(string_view category) override;
void SaveToIni(string_view category) const override;
void LoadFromIni(std::string_view category) override;
void SaveToIni(std::string_view category) const override;
[[nodiscard]] size_t GetListSize() const override;
[[nodiscard]] string_view GetListDescription(size_t index) const override;
[[nodiscard]] std::string_view GetListDescription(size_t index) const override;
[[nodiscard]] size_t GetActiveListIndex() const override;
void SetActiveListIndex(size_t index) override;
@ -367,18 +367,18 @@ class OptionEntryAudioDevice : public OptionEntryListBase {
public:
OptionEntryAudioDevice();
void LoadFromIni(string_view category) override;
void SaveToIni(string_view category) const override;
void LoadFromIni(std::string_view category) override;
void SaveToIni(std::string_view category) const override;
[[nodiscard]] size_t GetListSize() const override;
[[nodiscard]] string_view GetListDescription(size_t index) const override;
[[nodiscard]] std::string_view GetListDescription(size_t index) const override;
[[nodiscard]] size_t GetActiveListIndex() const override;
void SetActiveListIndex(size_t index) override;
std::string operator*() const
{
for (size_t i = 0; i < GetListSize(); i++) {
string_view deviceName = GetDeviceName(i);
std::string_view deviceName = GetDeviceName(i);
if (deviceName == deviceName_)
return deviceName_;
}
@ -386,27 +386,27 @@ public:
}
private:
string_view GetDeviceName(size_t index) const;
std::string_view GetDeviceName(size_t index) const;
std::string deviceName_;
};
struct OptionCategoryBase {
OptionCategoryBase(string_view key, const char *name, const char *description)
OptionCategoryBase(std::string_view key, const char *name, const char *description)
: key(key)
, name(name)
, description(description)
{
}
[[nodiscard]] string_view GetKey() const;
[[nodiscard]] string_view GetName() const;
[[nodiscard]] string_view GetDescription() const;
[[nodiscard]] std::string_view GetKey() const;
[[nodiscard]] std::string_view GetName() const;
[[nodiscard]] std::string_view GetDescription() const;
virtual std::vector<OptionEntryBase *> GetEntries() = 0;
protected:
string_view key;
std::string_view key;
const char *name;
const char *description;
};
@ -655,18 +655,18 @@ struct KeymapperOptions : OptionCategoryBase {
// The implicit copy constructor would copy that reference instead of referencing the copy.
Action(const Action &) = delete;
Action(string_view key, const char *name, const char *description, uint32_t defaultKey, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index);
Action(std::string_view key, const char *name, const char *description, uint32_t defaultKey, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index);
[[nodiscard]] string_view GetName() const override;
[[nodiscard]] std::string_view GetName() const override;
[[nodiscard]] OptionEntryType GetType() const override
{
return OptionEntryType::Key;
}
void LoadFromIni(string_view category) override;
void SaveToIni(string_view category) const override;
void LoadFromIni(std::string_view category) override;
void SaveToIni(std::string_view category) const override;
[[nodiscard]] string_view GetValueDescription() const override;
[[nodiscard]] std::string_view GetValueDescription() const override;
bool SetValue(int value);
@ -687,7 +687,7 @@ struct KeymapperOptions : OptionCategoryBase {
std::vector<OptionEntryBase *> GetEntries() override;
void AddAction(
string_view key, const char *name, const char *description, uint32_t defaultKey,
std::string_view key, const char *name, const char *description, uint32_t defaultKey,
std::function<void()> actionPressed,
std::function<void()> actionReleased = nullptr,
std::function<bool()> enable = nullptr,
@ -697,8 +697,8 @@ struct KeymapperOptions : OptionCategoryBase {
void KeyReleased(SDL_Keycode key) const;
bool IsTextEntryKey(SDL_Keycode vkey) const;
bool IsNumberEntryKey(SDL_Keycode vkey) const;
string_view KeyNameForAction(string_view actionName) const;
uint32_t KeyForAction(string_view actionName) const;
std::string_view KeyNameForAction(std::string_view actionName) const;
uint32_t KeyForAction(std::string_view actionName) const;
private:
std::forward_list<Action> actions;
@ -715,23 +715,23 @@ struct PadmapperOptions : OptionCategoryBase {
*/
class Action final : public OptionEntryBase {
public:
Action(string_view key, const char *name, const char *description, ControllerButtonCombo defaultInput, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index);
Action(std::string_view key, const char *name, const char *description, ControllerButtonCombo defaultInput, std::function<void()> actionPressed, std::function<void()> actionReleased, std::function<bool()> enable, unsigned index);
// OptionEntryBase::key may be referencing Action::dynamicKey.
// The implicit copy constructor would copy that reference instead of referencing the copy.
Action(const Action &) = delete;
[[nodiscard]] string_view GetName() const override;
[[nodiscard]] std::string_view GetName() const override;
[[nodiscard]] OptionEntryType GetType() const override
{
return OptionEntryType::PadButton;
}
void LoadFromIni(string_view category) override;
void SaveToIni(string_view category) const override;
void LoadFromIni(std::string_view category) override;
void SaveToIni(std::string_view category) const override;
[[nodiscard]] string_view GetValueDescription() const override;
[[nodiscard]] string_view GetValueDescription(bool useShortName) const;
[[nodiscard]] std::string_view GetValueDescription() const override;
[[nodiscard]] std::string_view GetValueDescription(bool useShortName) const;
bool SetValue(ControllerButtonCombo value);
@ -749,7 +749,7 @@ struct PadmapperOptions : OptionCategoryBase {
mutable std::string dynamicName;
void UpdateValueDescription() const;
string_view Shorten(string_view buttonName) const;
std::string_view Shorten(std::string_view buttonName) const;
friend struct PadmapperOptions;
};
@ -758,7 +758,7 @@ struct PadmapperOptions : OptionCategoryBase {
std::vector<OptionEntryBase *> GetEntries() override;
void AddAction(
string_view key, const char *name, const char *description, ControllerButtonCombo defaultInput,
std::string_view key, const char *name, const char *description, ControllerButtonCombo defaultInput,
std::function<void()> actionPressed,
std::function<void()> actionReleased = nullptr,
std::function<bool()> enable = nullptr,
@ -767,10 +767,10 @@ struct PadmapperOptions : OptionCategoryBase {
void ButtonPressed(ControllerButton button);
void ButtonReleased(ControllerButton button, bool invokeAction = true);
void ReleaseAllActiveButtons();
bool IsActive(string_view actionName) const;
string_view ActionNameTriggeredByButtonEvent(ControllerButtonEvent ctrlEvent) const;
string_view InputNameForAction(string_view actionName, bool useShortName = false) const;
ControllerButtonCombo ButtonComboForAction(string_view actionName) const;
bool IsActive(std::string_view actionName) const;
std::string_view ActionNameTriggeredByButtonEvent(ControllerButtonEvent ctrlEvent) const;
std::string_view InputNameForAction(std::string_view actionName, bool useShortName = false) const;
ControllerButtonCombo ButtonComboForAction(std::string_view actionName) const;
private:
std::forward_list<Action> actions;

4
Source/panels/charpanel.cpp

@ -218,8 +218,8 @@ void DrawShadowString(const Surface &out, const PanelEntry &entry)
return;
constexpr int Spacing = 0;
const string_view textStr = LanguageTranslate(entry.label);
string_view text;
const std::string_view textStr = LanguageTranslate(entry.label);
std::string_view text;
std::string wrapped;
if (entry.labelLength > 0) {
wrapped = WordWrapString(textStr, entry.labelLength, GameFont12, Spacing);

8
Source/panels/mainpanel.cpp

@ -25,13 +25,13 @@ OptionalOwnedClxSpriteList PanelButton;
OptionalOwnedClxSpriteList PanelButtonGrime;
OptionalOwnedClxSpriteList PanelButtonDownGrime;
void DrawButtonText(const Surface &out, string_view text, Rectangle placement, UiFlags style, int spacing = 1)
void DrawButtonText(const Surface &out, std::string_view text, Rectangle placement, UiFlags style, int spacing = 1)
{
DrawString(out, text, { placement.position + Displacement { 0, 1 }, placement.size }, UiFlags::AlignCenter | UiFlags::KerningFitSpacing | UiFlags::ColorBlack, spacing);
DrawString(out, text, placement, UiFlags::AlignCenter | UiFlags::KerningFitSpacing | style, spacing);
}
void DrawButtonOnPanel(Point position, string_view text, int frame)
void DrawButtonOnPanel(Point position, std::string_view text, int frame)
{
RenderClxSprite(*pBtmBuff, (*PanelButton)[frame], position);
int spacing = 2;
@ -44,7 +44,7 @@ void DrawButtonOnPanel(Point position, string_view text, int frame)
DrawButtonText(*pBtmBuff, text, { position, { (*PanelButton)[0].width(), 0 } }, UiFlags::ColorButtonface, spacing);
}
void RenderMainButton(const Surface &out, int buttonId, string_view text, int frame)
void RenderMainButton(const Surface &out, int buttonId, std::string_view text, int frame)
{
Point panelPosition { PanBtnPos[buttonId].x + 4, PanBtnPos[buttonId].y + 17 };
DrawButtonOnPanel(panelPosition, text, frame);
@ -97,7 +97,7 @@ void LoadMainPanel()
constexpr size_t NumOtherPlayers = 3;
// Render the unpressed voice buttons to pBtmBuff.
string_view text = _("voice");
std::string_view text = _("voice");
const int textWidth = GetLineWidth(text, GameFont12, 1);
for (size_t i = 0; i < NumOtherPlayers; ++i) {
Point position { 176, static_cast<int>(GetMainPanel().size.height + 101 + 18 * i) };

2
Source/panels/spell_book.cpp

@ -66,7 +66,7 @@ SpellID GetSpellFromSpellPage(size_t page, size_t entry)
constexpr Size SpellBookDescription { 250, 43 };
constexpr int SpellBookDescriptionPaddingHorizontal = 2;
void PrintSBookStr(const Surface &out, Point position, string_view text, UiFlags flags = UiFlags::None)
void PrintSBookStr(const Surface &out, Point position, std::string_view text, UiFlags flags = UiFlags::None)
{
DrawString(out, text,
Rectangle(GetPanelPosition(UiPanels::Spell, position + Displacement { SPLICONLENGTH, 0 }),

12
Source/panels/spell_list.cpp

@ -26,7 +26,7 @@ namespace devilution {
namespace {
void PrintSBookSpellType(const Surface &out, Point position, string_view text, uint8_t rectColorIndex)
void PrintSBookSpellType(const Surface &out, Point position, std::string_view text, uint8_t rectColorIndex)
{
DrawLargeSpellIconBorder(out, position, rectColorIndex);
@ -37,7 +37,7 @@ void PrintSBookSpellType(const Surface &out, Point position, string_view text, u
DrawString(out, text, position, UiFlags::ColorWhite | UiFlags::Outlined);
}
void PrintSBookHotkey(const Surface &out, Point position, const string_view text)
void PrintSBookHotkey(const Surface &out, Point position, const std::string_view text)
{
// Align the hot key text with the top-right corner of the spell icon
position += Displacement { SPLICONLENGTH - (GetLineWidth(text.data()) + 5), 5 - SPLICONLENGTH };
@ -65,7 +65,7 @@ bool GetSpellListSelection(SpellID &pSpell, SpellType &pSplType)
return false;
}
std::optional<string_view> GetHotkeyName(SpellID spellId, SpellType spellType, bool useShortName = false)
std::optional<std::string_view> GetHotkeyName(SpellID spellId, SpellType spellType, bool useShortName = false)
{
Player &myPlayer = *MyPlayer;
for (size_t t = 0; t < NumHotkeys; t++) {
@ -107,7 +107,7 @@ void DrawSpell(const Surface &out)
const Point position = GetMainPanel().position + Displacement { 565, 119 };
DrawLargeSpellIcon(out, position, spl);
std::optional<string_view> hotkeyName = GetHotkeyName(spl, myPlayer._pRSplType, true);
std::optional<std::string_view> hotkeyName = GetHotkeyName(spl, myPlayer._pRSplType, true);
if (hotkeyName)
PrintSBookHotkey(out, position, *hotkeyName);
}
@ -135,7 +135,7 @@ void DrawSpellList(const Surface &out)
SetSpellTrans(transType);
DrawLargeSpellIcon(out, spellListItem.location, spellId);
std::optional<string_view> shortHotkeyName = GetHotkeyName(spellId, spellListItem.type, true);
std::optional<std::string_view> shortHotkeyName = GetHotkeyName(spellId, spellListItem.type, true);
if (shortHotkeyName)
PrintSBookHotkey(out, spellListItem.location, *shortHotkeyName);
@ -188,7 +188,7 @@ void DrawSpellList(const Surface &out)
case SpellType::Invalid:
break;
}
std::optional<string_view> fullHotkeyName = GetHotkeyName(spellId, spellListItem.type);
std::optional<std::string_view> fullHotkeyName = GetHotkeyName(spellId, spellListItem.type);
if (fullHotkeyName) {
AddPanelString(fmt::format(fmt::runtime(_("Spell Hotkey {:s}")), *fullHotkeyName));
}

18
Source/pfile.cpp

@ -7,6 +7,7 @@
#include <cstdint>
#include <string>
#include <string_view>
#include <unordered_map>
#include <fmt/core.h>
@ -26,7 +27,6 @@
#include "utils/language.h"
#include "utils/parse_int.hpp"
#include "utils/paths.h"
#include "utils/stdcompat/string_view.hpp"
#include "utils/str_cat.hpp"
#include "utils/str_split.hpp"
#include "utils/utf8.hpp"
@ -51,7 +51,7 @@ namespace {
/** List of character names for the character selection screen. */
char hero_names[MAX_CHARACTERS][PlayerNameLength];
std::string GetSavePath(uint32_t saveNum, string_view savePrefix = {})
std::string GetSavePath(uint32_t saveNum, std::string_view savePrefix = {})
{
return StrCat(paths::PrefPath(), savePrefix,
gbIsSpawn
@ -78,7 +78,7 @@ std::string GetStashSavePath()
);
}
bool GetSaveNames(uint8_t index, string_view prefix, char *out)
bool GetSaveNames(uint8_t index, std::string_view prefix, char *out)
{
char suf;
if (index < giNumberOfLevels)
@ -255,14 +255,14 @@ struct CompareCounter {
}
};
inline bool string_ends_with(string_view value, string_view suffix)
inline bool string_ends_with(std::string_view value, std::string_view suffix)
{
if (suffix.size() > value.size())
return false;
return std::equal(suffix.rbegin(), suffix.rend(), value.rbegin());
}
void CreateDetailDiffs(string_view prefix, string_view memoryMapFile, CompareInfo &compareInfoReference, CompareInfo &compareInfoActual, std::unordered_map<std::string, size_t> &foundDiffs)
void CreateDetailDiffs(std::string_view prefix, std::string_view memoryMapFile, CompareInfo &compareInfoReference, CompareInfo &compareInfoActual, std::unordered_map<std::string, size_t> &foundDiffs)
{
// Note: Detail diffs are currently only supported in unit tests
std::string memoryMapFileAssetName = StrCat(paths::BasePath(), "/test/fixtures/memory_map/", memoryMapFile, ".txt");
@ -276,7 +276,7 @@ void CreateDetailDiffs(string_view prefix, string_view memoryMapFile, CompareInf
size_t readBytes = SDL_RWsize(handle);
std::unique_ptr<std::byte[]> memoryMapFileData { new std::byte[readBytes] };
SDL_RWread(handle, memoryMapFileData.get(), readBytes, 1);
const string_view buffer(reinterpret_cast<const char *>(memoryMapFileData.get()), readBytes);
const std::string_view buffer(reinterpret_cast<const char *>(memoryMapFileData.get()), readBytes);
std::unordered_map<std::string, CompareCounter> counter;
@ -327,7 +327,7 @@ void CreateDetailDiffs(string_view prefix, string_view memoryMapFile, CompareInf
return value;
};
for (string_view line : SplitByChar(buffer, '\n')) {
for (std::string_view line : SplitByChar(buffer, '\n')) {
if (!line.empty() && line.back() == '\r')
line.remove_suffix(1);
if (line.empty())
@ -338,7 +338,7 @@ void CreateDetailDiffs(string_view prefix, string_view memoryMapFile, CompareInf
if (it == end)
continue;
string_view command = *it;
std::string_view command = *it;
bool dataExistsReference = compareInfoReference.dataExists;
bool dataExistsActual = compareInfoActual.dataExists;
@ -391,7 +391,7 @@ void CreateDetailDiffs(string_view prefix, string_view memoryMapFile, CompareInf
} else if (command == "M") {
const auto countAsString = std::string(*++it);
const auto bitsAsString = std::string(*++it);
string_view comment = *++it;
std::string_view comment = *++it;
CompareCounter count = getCounter(countAsString);
const ParseIntResult<size_t> parsedBytes = ParseInt<size_t>(bitsAsString);

6
Source/platform/ctr/keyboard.cpp

@ -7,8 +7,8 @@
constexpr size_t MAX_TEXT_LENGTH = 255;
struct vkbdEvent {
devilution::string_view hintText;
devilution::string_view inText;
std::string_view hintText;
std::string_view inText;
char *outText;
size_t maxLength;
};
@ -16,7 +16,7 @@ struct vkbdEvent {
static vkbdEvent events[16];
static int eventCount = 0;
void ctr_vkbdInput(devilution::string_view hintText, devilution::string_view inText, char *outText, size_t maxLength)
void ctr_vkbdInput(std::string_view hintText, std::string_view inText, char *outText, size_t maxLength)
{
if (eventCount >= sizeof(events))
return;

8
Source/platform/ctr/keyboard.h

@ -1,6 +1,8 @@
#include <3ds.h>
#pragma once
#include <string_view>
#include "utils/stdcompat/string_view.hpp"
#include <3ds.h>
/**
* @brief Queues a request for user input for the next call to ctr_vkbdFlush()
@ -10,7 +12,7 @@
* @param outText Pointer to a buffer to receive user input
* @param maxLength Size of the buffer
*/
void ctr_vkbdInput(devilution::string_view title, devilution::string_view inText, char *outText, size_t maxLength);
void ctr_vkbdInput(std::string_view title, std::string_view inText, char *outText, size_t maxLength);
/**
* @brief Processes pending requests for user input

9
Source/platform/locale.cpp

@ -2,6 +2,7 @@
#include <algorithm>
#include <cstdint>
#include <string_view>
#ifdef __ANDROID__
#include <SDL.h>
@ -27,13 +28,11 @@
#include <clocale>
#endif
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
namespace {
#if (defined(_WIN32) && WINVER >= 0x0600 && !defined(NXDK)) || (defined(__APPLE__) && defined(USE_COREFOUNDATION))
std::string IetfToPosix(string_view langCode)
std::string IetfToPosix(std::string_view langCode)
{
/*
* Handle special case for simplified/traditional Chinese. IETF/BCP-47 specifies that only the script should be
@ -179,10 +178,10 @@ std::vector<std::string> GetLocales()
CFRelease(languages);
#else
constexpr auto svOrEmpty = [](const char *cString) -> string_view {
constexpr auto svOrEmpty = [](const char *cString) -> std::string_view {
return cString != nullptr ? cString : "";
};
string_view languages = svOrEmpty(std::getenv("LANGUAGE"));
std::string_view languages = svOrEmpty(std::getenv("LANGUAGE"));
if (languages.empty()) {
languages = svOrEmpty(std::getenv("LANG"));
if (languages.empty()) {

4
Source/platform/switch/keyboard.cpp

@ -8,7 +8,7 @@
#include "utils/utf8.hpp"
static void switch_keyboard_get(devilution::string_view guide_text, devilution::string_view initial_text, char *buf, unsigned buf_len)
static void switch_keyboard_get(std::string_view guide_text, std::string_view initial_text, char *buf, unsigned buf_len)
{
Result rc = 0;
@ -62,7 +62,7 @@ static void switch_create_and_push_sdlkey_event(uint32_t event_type, SDL_Scancod
SDL_PushEvent(&event);
}
void switch_start_text_input(devilution::string_view guide_text, devilution::string_view initial_text, unsigned max_length)
void switch_start_text_input(std::string_view guide_text, std::string_view initial_text, unsigned max_length)
{
char text[max_length] = { '\0' };
switch_keyboard_get(guide_text, initial_text, text, sizeof(text));

4
Source/platform/switch/keyboard.h

@ -1,6 +1,6 @@
#pragma once
#include "utils/stdcompat/string_view.hpp"
#include <string_view>
/**
* @brief Prompts the user for text input, pushes the user-provided text to the event queue, then returns
@ -8,4 +8,4 @@
* @param initial_text An optional prefilled value for the input
* @param max_length How many bytes of input to accept from the user (certain characters will take multiple bytes)
*/
void switch_start_text_input(devilution::string_view guide_text, devilution::string_view initial_text, unsigned max_length);
void switch_start_text_input(std::string_view guide_text, std::string_view initial_text, unsigned max_length);

4
Source/platform/vita/keyboard.cpp

@ -83,7 +83,7 @@ static int vita_input_thread(void *ime_buffer)
return 0;
}
static int vita_keyboard_get(devilution::string_view guide_text, devilution::string_view initial_text, unsigned max_len, SceWChar16 *buf)
static int vita_keyboard_get(std::string_view guide_text, std::string_view initial_text, unsigned max_len, SceWChar16 *buf)
{
SceWChar16 title[SCE_IME_DIALOG_MAX_TITLE_LENGTH];
SceWChar16 text[SCE_IME_DIALOG_MAX_TEXT_LENGTH];
@ -116,7 +116,7 @@ static int vita_keyboard_get(devilution::string_view guide_text, devilution::str
return 1;
}
void vita_start_text_input(devilution::string_view guide_text, devilution::string_view initial_text, unsigned max_length)
void vita_start_text_input(std::string_view guide_text, std::string_view initial_text, unsigned max_length)
{
SceWChar16 ime_buffer[SCE_IME_DIALOG_MAX_TEXT_LENGTH];
if (vita_keyboard_get(guide_text, initial_text, max_length, ime_buffer)) {

4
Source/platform/vita/keyboard.h

@ -1,5 +1,5 @@
#pragma once
#include "utils/stdcompat/string_view.hpp"
#include <string_view>
void vita_start_text_input(devilution::string_view guide_text, devilution::string_view initial_text, unsigned max_length);
void vita_start_text_input(std::string_view guide_text, std::string_view initial_text, unsigned max_length);

2
Source/player.cpp

@ -2146,7 +2146,7 @@ void LoadPlrGFX(Player &player, player_graphic graphic)
char prefix[3] = { CharChar[static_cast<std::size_t>(cls)], ArmourChar[player._pgfxnum >> 4], WepChar[static_cast<std::size_t>(animWeaponId)] };
char pszName[256];
*fmt::format_to(pszName, R"(plrgfx\{0}\{1}\{1}{2})", path, string_view(prefix, 3), szCel) = 0;
*fmt::format_to(pszName, R"(plrgfx\{0}\{1}\{1}{2})", path, std::string_view(prefix, 3), szCel) = 0;
const uint16_t animationWidth = GetPlayerSpriteWidth(cls, graphic, animWeaponId);
animationData.sprites = LoadCl2Sheet(pszName, animationWidth);
std::optional<std::array<uint8_t, 256>> trn = GetClassTRN(player);

12
Source/plrmsg.cpp

@ -31,14 +31,14 @@ struct PlayerMessage {
/** The text message to display on screen */
std::string text;
/** First portion of text that should be rendered in gold */
string_view from;
std::string_view from;
/** The line height of the text */
int lineHeight;
};
std::array<PlayerMessage, 8> Messages;
int CountLinesOfText(string_view text)
int CountLinesOfText(std::string_view text)
{
return 1 + c_count(text, '\n');
}
@ -66,19 +66,19 @@ void plrmsg_delay(bool delay)
message.time += plrmsgTicks;
}
void EventPlrMsg(string_view text, UiFlags style)
void EventPlrMsg(std::string_view text, UiFlags style)
{
PlayerMessage &message = GetNextMessage();
message.style = style;
message.time = SDL_GetTicks();
message.text = std::string(text);
message.from = string_view(message.text.data(), 0);
message.from = std::string_view(message.text.data(), 0);
message.lineHeight = GetLineHeight(message.text, GameFont12) + 3;
AddMessageToChatLog(text);
}
void SendPlrMsg(Player &player, string_view text)
void SendPlrMsg(Player &player, std::string_view text)
{
PlayerMessage &message = GetNextMessage();
@ -87,7 +87,7 @@ void SendPlrMsg(Player &player, string_view text)
message.style = UiFlags::ColorWhite;
message.time = SDL_GetTicks();
message.text = from + std::string(text);
message.from = string_view(message.text.data(), from.size());
message.from = std::string_view(message.text.data(), from.size());
message.lineHeight = GetLineHeight(message.text, GameFont12) + 3;
AddMessageToChatLog(text, &player);
}

6
Source/plrmsg.h

@ -7,19 +7,19 @@
#include <cstdint>
#include <string>
#include <string_view>
#include <SDL.h>
#include "DiabloUI/ui_flags.hpp"
#include "engine.h"
#include "player.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
void plrmsg_delay(bool delay);
void EventPlrMsg(string_view text, UiFlags style = UiFlags::ColorWhitegold);
void SendPlrMsg(Player &player, string_view text);
void EventPlrMsg(std::string_view text, UiFlags style = UiFlags::ColorWhitegold);
void SendPlrMsg(Player &player, std::string_view text);
void InitPlrMsg();
void DrawPlrMsg(const Surface &out);

7
Source/qol/chatlog.cpp

@ -4,8 +4,8 @@
* Implementation of the in-game chat log.
*/
#include <ctime>
#include <string>
#include <string_view>
#include <vector>
#include <fmt/format.h>
@ -24,7 +24,6 @@
#include "minitext.h"
#include "stores.h"
#include "utils/language.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -116,7 +115,7 @@ void ToggleChatLog()
}
}
void AddMessageToChatLog(string_view message, Player *player, UiFlags flags)
void AddMessageToChatLog(std::string_view message, Player *player, UiFlags flags)
{
MessageCounter++;
time_t timeResult = time(nullptr);
@ -177,7 +176,7 @@ void DrawChatLog(const Surface &out)
if (i + SkipLines >= ChatLogLines.size())
break;
MultiColoredText &text = ChatLogLines[ChatLogLines.size() - (i + SkipLines + 1)];
const string_view line = text.text;
const std::string_view line = text.text;
std::vector<DrawStringFormatArg> args;
for (auto &x : text.colors) {

2
Source/qol/chatlog.h

@ -13,7 +13,7 @@ namespace devilution {
extern bool ChatLogFlag;
void ToggleChatLog();
void AddMessageToChatLog(string_view message, Player *player = nullptr, UiFlags flags = UiFlags::ColorWhite);
void AddMessageToChatLog(std::string_view message, Player *player = nullptr, UiFlags flags = UiFlags::ColorWhite);
void DrawChatLog(const Surface &out);
void ChatLogScrollUp();
void ChatLogScrollDown();

2
Source/qol/itemlabels.cpp

@ -4,6 +4,7 @@
#include <cmath>
#include <limits>
#include <string>
#include <string_view>
#include <vector>
#include <fmt/format.h>
@ -19,7 +20,6 @@
#include "stores.h"
#include "utils/format_int.hpp"
#include "utils/language.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {

2
Source/qol/stash.cpp

@ -662,7 +662,7 @@ void CloseGoldWithdraw()
SDL_StopTextInput();
}
void GoldWithdrawNewText(string_view text)
void GoldWithdrawNewText(std::string_view text)
{
for (char vkey : text) {
int digit = vkey - '0';

2
Source/qol/stash.h

@ -90,7 +90,7 @@ void StartGoldWithdraw();
void WithdrawGoldKeyPress(SDL_Keycode vkey);
void DrawGoldWithdraw(const Surface &out, int amount);
void CloseGoldWithdraw();
void GoldWithdrawNewText(string_view text);
void GoldWithdrawNewText(std::string_view text);
/**
* @brief Checks whether the given item can be placed on the specified player's stash.

2
Source/quests.cpp

@ -218,7 +218,7 @@ int QuestLogMouseToEntry()
return -1;
}
void PrintQLString(const Surface &out, int x, int y, string_view str, bool marked, bool disabled = false)
void PrintQLString(const Surface &out, int x, int y, std::string_view str, bool marked, bool disabled = false)
{
int width = GetLineWidth(str);
x += std::max((257 - width) / 2, 0);

12
Source/stores.cpp

@ -7,6 +7,7 @@
#include <algorithm>
#include <cstdint>
#include <string_view>
#include <fmt/format.h>
@ -26,7 +27,6 @@
#include "towners.h"
#include "utils/format_int.hpp"
#include "utils/language.h"
#include "utils/stdcompat/string_view.hpp"
#include "utils/str_cat.hpp"
#include "utils/utf8.hpp"
@ -245,7 +245,7 @@ void AddSTextVal(size_t y, int val)
stext[y]._sval = val;
}
void AddSText(uint8_t x, size_t y, string_view text, UiFlags flags, bool sel, int cursId = -1, bool cursIndent = false)
void AddSText(uint8_t x, size_t y, std::string_view text, UiFlags flags, bool sel, int cursId = -1, bool cursIndent = false)
{
stext[y]._sx = x;
stext[y]._syoff = 0;
@ -267,7 +267,7 @@ void AddOptionsBackButton()
void AddItemListBackButton(bool selectable = false)
{
const int line = BackButtonLine();
string_view text = _("Back");
std::string_view text = _("Back");
if (!selectable && IsSmallFontTall()) {
AddSText(0, line, text, UiFlags::ColorWhite | UiFlags::AlignRight, selectable);
} else {
@ -926,7 +926,7 @@ void StoreConfirm(Item &item)
AddSTextVal(8, item._iIvalue);
PrintStoreItem(item, 9, itemColor);
string_view prompt;
std::string_view prompt;
switch (stextshold) {
case TalkID::BoyBuy:
@ -2062,7 +2062,7 @@ int TakeGold(Player &player, int cost, bool skipMaxPiles)
return cost;
}
void DrawSelector(const Surface &out, const Rectangle &rect, string_view text, UiFlags flags)
void DrawSelector(const Surface &out, const Rectangle &rect, std::string_view text, UiFlags flags)
{
int lineWidth = GetLineWidth(text);
@ -2155,7 +2155,7 @@ void FreeStoreMem()
}
}
void PrintSString(const Surface &out, int margin, int line, string_view text, UiFlags flags, int price, int cursId, bool cursIndent)
void PrintSString(const Surface &out, int margin, int line, std::string_view text, UiFlags flags, int price, int cursId, bool cursIndent)
{
const Point uiPosition = GetUIRectangle().position;
int sx = uiPosition.x + 32 + margin;

2
Source/stores.h

@ -88,7 +88,7 @@ void SetupTownStores();
void FreeStoreMem();
void PrintSString(const Surface &out, int margin, int line, string_view text, UiFlags flags, int price = 0, int cursId = -1, bool cursIndent = false);
void PrintSString(const Surface &out, int margin, int line, std::string_view text, UiFlags flags, int price = 0, int cursId = -1, bool cursIndent = false);
void DrawSLine(const Surface &out, int sy);
void DrawSTextHelp();
void ClearSText(int s, int e);

4
Source/towners.h

@ -8,11 +8,11 @@
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string_view>
#include "items.h"
#include "player.h"
#include "quests.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
@ -42,7 +42,7 @@ struct Towner {
const uint8_t *animOrder; // unowned
void (*talk)(Player &player, Towner &towner);
string_view name;
std::string_view name;
/** Tile position of NPC */
Point position;

6
Source/utils/console.cpp

@ -25,7 +25,7 @@ HANDLE GetStderrHandle()
return handle;
}
void WriteToStderr(string_view str)
void WriteToStderr(std::string_view str)
{
HANDLE handle = GetStderrHandle();
if (handle == NULL)
@ -35,7 +35,7 @@ void WriteToStderr(string_view str)
} // namespace
void printInConsole(string_view str)
void printInConsole(std::string_view str)
{
OutputDebugString(std::string(str).c_str());
WriteToStderr(str);
@ -72,7 +72,7 @@ void vprintfInConsole(const char *fmt, va_list ap)
namespace devilution {
void printInConsole(string_view str)
void printInConsole(std::string_view str)
{
std::fwrite(str.data(), sizeof(char), str.size(), stderr);
}

4
Source/utils/console.h

@ -2,13 +2,13 @@
#include <cstdarg>
#include <cstddef>
#include <string_view>
#include "utils/attributes.h"
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
void printInConsole(string_view str);
void printInConsole(std::string_view str);
void printNewlineInConsole();
void printfInConsole(const char *fmt, ...) DVL_PRINTF_ATTRIBUTE(1, 2);
void vprintfInConsole(const char *fmt, std::va_list ap) DVL_PRINTF_ATTRIBUTE(1, 0);

16
Source/utils/file_name_generator.hpp

@ -2,15 +2,15 @@
#include <cstring>
#include <initializer_list>
#include <string_view>
#include "utils/stdcompat/string_view.hpp"
#include "utils/str_cat.hpp"
namespace devilution {
class BaseFileNameGenerator {
public:
BaseFileNameGenerator(std::initializer_list<string_view> prefixes, string_view suffix)
BaseFileNameGenerator(std::initializer_list<std::string_view> prefixes, std::string_view suffix)
: suffix_(suffix)
, prefixEnd_(Append(buf_, prefixes))
{
@ -23,14 +23,14 @@ public:
}
protected:
static char *Append(char *buf, std::initializer_list<string_view> strings)
static char *Append(char *buf, std::initializer_list<std::string_view> strings)
{
for (string_view str : strings)
for (std::string_view str : strings)
buf = BufCopy(buf, str);
return buf;
}
[[nodiscard]] string_view Suffix() const
[[nodiscard]] std::string_view Suffix() const
{
return suffix_;
}
@ -44,7 +44,7 @@ protected:
}
private:
string_view suffix_;
std::string_view suffix_;
char *prefixEnd_;
char buf_[256];
};
@ -59,7 +59,7 @@ private:
*/
class FileNameGenerator : public BaseFileNameGenerator {
public:
FileNameGenerator(std::initializer_list<string_view> prefixes, string_view suffix, unsigned min = 1)
FileNameGenerator(std::initializer_list<std::string_view> prefixes, std::string_view suffix, unsigned min = 1)
: BaseFileNameGenerator(prefixes, suffix)
, min_(min)
{
@ -86,7 +86,7 @@ private:
*/
class FileNameWithCharAffixGenerator : public BaseFileNameGenerator {
public:
FileNameWithCharAffixGenerator(std::initializer_list<string_view> prefixes, string_view suffix, const char *chars)
FileNameWithCharAffixGenerator(std::initializer_list<std::string_view> prefixes, std::string_view suffix, const char *chars)
: BaseFileNameGenerator(prefixes, suffix)
, chars_(chars)
{

15
Source/utils/file_util.cpp

@ -1,18 +1,17 @@
#include "utils/file_util.h"
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <algorithm>
#include <string>
#include <string_view>
#include <vector>
#include <SDL.h>
#include "utils/log.hpp"
#include "utils/stdcompat/filesystem.hpp"
#include "utils/stdcompat/string_view.hpp"
#ifdef USE_SDL1
#include "utils/sdl2_to_1_2_backports.h"
@ -50,7 +49,7 @@
namespace devilution {
#if (defined(_WIN64) || defined(_WIN32)) && !defined(NXDK)
std::unique_ptr<wchar_t[]> ToWideChar(string_view path)
std::unique_ptr<wchar_t[]> ToWideChar(std::string_view path)
{
constexpr std::uint32_t flags = MB_ERR_INVALID_CHARS;
const int utf16Size = ::MultiByteToWideChar(CP_UTF8, flags, path.data(), path.size(), nullptr, 0);
@ -64,16 +63,16 @@ std::unique_ptr<wchar_t[]> ToWideChar(string_view path)
}
#endif
string_view Dirname(string_view path)
std::string_view Dirname(std::string_view path)
{
while (path.size() > 1 && path.back() == DirectorySeparator)
path.remove_suffix(1);
if (path.size() == 1 && path.back() == DirectorySeparator)
return DIRECTORY_SEPARATOR_STR;
const size_t sep = path.find_last_of(DIRECTORY_SEPARATOR_STR);
if (sep == string_view::npos)
if (sep == std::string_view::npos)
return ".";
return string_view { path.data(), sep };
return std::string_view { path.data(), sep };
}
bool FileExists(const char *path)
@ -265,7 +264,7 @@ void RecursivelyCreateDir(const char *path)
std::string cur { path };
do {
paths.push_back(cur);
string_view parent = Dirname(cur);
std::string_view parent = Dirname(cur);
if (parent == cur)
break;
cur.assign(parent.data(), parent.size());

7
Source/utils/file_util.h

@ -4,8 +4,7 @@
#include <cstdio>
#include <memory>
#include <string>
#include "utils/stdcompat/string_view.hpp"
#include <string_view>
namespace devilution {
@ -25,7 +24,7 @@ inline bool FileExists(const std::string &str)
}
bool DirectoryExists(const char *path);
string_view Dirname(string_view path);
std::string_view Dirname(std::string_view path);
bool FileExistsAndIsWriteable(const char *path);
bool GetFileSize(const char *path, std::uintmax_t *size);
@ -44,7 +43,7 @@ void RemoveFile(const char *path);
FILE *OpenFile(const char *path, const char *mode);
#if (defined(_WIN64) || defined(_WIN32)) && !defined(NXDK)
std::unique_ptr<wchar_t[]> ToWideChar(string_view path);
std::unique_ptr<wchar_t[]> ToWideChar(std::string_view path);
#endif
} // namespace devilution

5
Source/utils/format_int.cpp

@ -1,7 +1,8 @@
#include "utils/format_int.hpp"
#include <string_view>
#include "utils/language.h"
#include "utils/stdcompat/string_view.hpp"
#include "utils/str_cat.hpp"
namespace devilution {
@ -23,7 +24,7 @@ std::string FormatInteger(int n)
return out;
}
const string_view separator = _(/* TRANSLATORS: Thousands separator */ ",");
const std::string_view separator = _(/* TRANSLATORS: Thousands separator */ ",");
out.reserve(len + separator.size() * (numLen - 1) / GroupSize);
if (n < 0) {
out += '-';

64
Source/utils/language.cpp

@ -2,6 +2,7 @@
#include <cstdint>
#include <memory>
#include <string_view>
#include <unordered_map>
#include <vector>
@ -13,7 +14,6 @@
#include "utils/file_util.h"
#include "utils/log.hpp"
#include "utils/paths.h"
#include "utils/stdcompat/string_view.hpp"
#ifdef USE_SDL1
#include "utils/sdl2_to_1_2_backports.h"
@ -40,14 +40,14 @@ using TranslationRef = uint32_t;
struct StringHash {
size_t operator()(const char *str) const noexcept
{
return std::hash<string_view> {}(str);
return std::hash<std::string_view> {}(str);
}
};
struct StringEq {
bool operator()(const char *lhs, const char *rhs) const noexcept
{
return string_view(lhs) == string_view(rhs);
return std::string_view(lhs) == std::string_view(rhs);
}
};
@ -62,7 +62,7 @@ TranslationRef EncodeTranslationRef(uint32_t offset, uint32_t size)
return (offset << TranslationRefSizeBits) | size;
}
string_view GetTranslation(TranslationRef ref)
std::string_view GetTranslation(TranslationRef ref)
{
return { &translationValues[ref >> TranslationRefSizeBits], ref & TranslationRefSizeMask };
}
@ -104,13 +104,13 @@ void SwapLE(MoEntry &entry)
entry.offset = SDL_SwapLE32(entry.offset);
}
string_view TrimLeft(string_view str)
std::string_view TrimLeft(std::string_view str)
{
str.remove_prefix(std::min(str.find_first_not_of(" \t"), str.size()));
return str;
}
string_view TrimRight(string_view str)
std::string_view TrimRight(std::string_view str)
{
str.remove_suffix(str.size() - (str.find_last_not_of(" \t") + 1));
return str;
@ -129,16 +129,16 @@ tl::function_ref<int(int n)> GetLocalPluralId = PluralIfNotOne;
/**
* Match plural=(n != 1);"
*/
void SetPluralForm(string_view expression)
void SetPluralForm(std::string_view expression)
{
const string_view key = "plural=";
const string_view::size_type keyPos = expression.find(key);
if (keyPos == string_view::npos)
const std::string_view key = "plural=";
const std::string_view::size_type keyPos = expression.find(key);
if (keyPos == std::string_view::npos)
return;
expression.remove_prefix(keyPos + key.size());
const string_view::size_type semicolonPos = expression.find(';');
if (semicolonPos != string_view::npos) {
const std::string_view::size_type semicolonPos = expression.find(';');
if (semicolonPos != std::string_view::npos) {
expression.remove_suffix(expression.size() - semicolonPos);
}
@ -216,19 +216,19 @@ void SetPluralForm(string_view expression)
/**
* Parse "nplurals=2;"
*/
void ParsePluralForms(string_view string)
void ParsePluralForms(std::string_view string)
{
const string_view pluralsKey = "nplurals";
const string_view::size_type pluralsPos = string.find(pluralsKey);
if (pluralsPos == string_view::npos)
const std::string_view pluralsKey = "nplurals";
const std::string_view::size_type pluralsPos = string.find(pluralsKey);
if (pluralsPos == std::string_view::npos)
return;
string.remove_prefix(pluralsPos + pluralsKey.size());
const string_view::size_type eqPos = string.find('=');
if (eqPos == string_view::npos)
const std::string_view::size_type eqPos = string.find('=');
if (eqPos == std::string_view::npos)
return;
string_view value = string.substr(eqPos + 1);
std::string_view value = string.substr(eqPos + 1);
if (value.empty() || value[0] < '0')
return;
@ -241,16 +241,16 @@ void ParsePluralForms(string_view string)
SetPluralForm(value);
}
void ParseMetadata(string_view metadata)
void ParseMetadata(std::string_view metadata)
{
string_view::size_type delim;
std::string_view::size_type delim;
while (!metadata.empty() && ((delim = metadata.find(':')) != string_view::npos)) {
const string_view key = TrimLeft(string_view(metadata.data(), delim));
string_view val = TrimLeft(string_view(metadata.data() + delim + 1, metadata.size() - delim - 1));
while (!metadata.empty() && ((delim = metadata.find(':')) != std::string_view::npos)) {
const std::string_view key = TrimLeft(std::string_view(metadata.data(), delim));
std::string_view val = TrimLeft(std::string_view(metadata.data() + delim + 1, metadata.size() - delim - 1));
if ((delim = val.find('\n')) != string_view::npos) {
val = string_view(val.data(), delim);
if ((delim = val.find('\n')) != std::string_view::npos) {
val = std::string_view(val.data(), delim);
metadata.remove_prefix(val.data() - metadata.data() + val.size() + 1);
} else {
metadata.remove_prefix(metadata.size());
@ -290,7 +290,7 @@ bool ReadEntry(const std::byte *data, size_t dataSize, const MoEntry &e, char *r
} // namespace
string_view LanguageParticularTranslate(string_view context, string_view message)
std::string_view LanguageParticularTranslate(std::string_view context, std::string_view message)
{
constexpr const char Glue = '\004';
@ -307,7 +307,7 @@ string_view LanguageParticularTranslate(string_view context, string_view message
return GetTranslation(it->second);
}
string_view LanguagePluralTranslate(const char *singular, string_view plural, int count)
std::string_view LanguagePluralTranslate(const char *singular, std::string_view plural, int count)
{
int n = GetLocalPluralId(count);
@ -321,7 +321,7 @@ string_view LanguagePluralTranslate(const char *singular, string_view plural, in
return GetTranslation(it->second);
}
string_view LanguageTranslate(const char *key)
std::string_view LanguageTranslate(const char *key)
{
auto it = translation[0].find(key);
if (it == translation[0].end()) {
@ -344,7 +344,7 @@ bool HasTranslation(const std::string &locale)
});
}
string_view GetLanguageCode()
std::string_view GetLanguageCode()
{
if (!forceLocale.empty())
return forceLocale;
@ -353,7 +353,7 @@ string_view GetLanguageCode()
bool IsSmallFontTall()
{
const string_view code = GetLanguageCode().substr(0, 2);
const std::string_view code = GetLanguageCode().substr(0, 2);
return code == "zh" || code == "ja" || code == "ko";
}
@ -493,7 +493,7 @@ void LanguageInitialize()
: ReadEntry(handle, src[i], keyPtr) && ReadEntry(handle, dst[i], valuePtr)) {
// Plural keys also have a plural form but it does not participate in lookup.
// Plural values are \0-terminated.
string_view value { valuePtr, dst[i].length + 1 };
std::string_view value { valuePtr, dst[i].length + 1 };
for (size_t j = 0; j < PluralForms && !value.empty(); j++) {
const size_t formValueEnd = value.find('\0');
translation[j].emplace(keyPtr, EncodeTranslationRef(value.data() - &translationValues[0], formValueEnd));

13
Source/utils/language.h

@ -1,8 +1,7 @@
#pragma once
#include <string>
#include "utils/stdcompat/string_view.hpp"
#include <string_view>
#define _(x) LanguageTranslate(x)
#define ngettext(x, y, z) LanguagePluralTranslate(x, y, z)
@ -12,7 +11,7 @@
extern std::string forceLocale;
devilution::string_view GetLanguageCode();
std::string_view GetLanguageCode();
bool HasTranslation(const std::string &locale);
void LanguageInitialize();
@ -22,8 +21,8 @@ void LanguageInitialize();
*
* @return guaranteed to be null-terminated.
*/
devilution::string_view LanguageTranslate(const char *key);
inline devilution::string_view LanguageTranslate(const std::string &key)
std::string_view LanguageTranslate(const char *key);
inline std::string_view LanguageTranslate(const std::string &key)
{
return LanguageTranslate(key.c_str());
}
@ -33,14 +32,14 @@ inline devilution::string_view LanguageTranslate(const std::string &key)
*
* @return guaranteed to be null-terminated if `plural` is.
*/
devilution::string_view LanguagePluralTranslate(const char *singular, devilution::string_view plural, int count);
std::string_view LanguagePluralTranslate(const char *singular, std::string_view plural, int count);
/**
* @brief Returns the translation for the given key and context identifier.
*
* @return guaranteed to be null-terminated.
*/
devilution::string_view LanguageParticularTranslate(devilution::string_view context, devilution::string_view message);
std::string_view LanguageParticularTranslate(std::string_view context, std::string_view message);
// Chinese and Japanese, and Korean small font is 16px instead of a 12px one for readability.
bool IsSmallFontTall();

37
Source/utils/log.hpp

@ -1,10 +1,11 @@
#pragma once
#include <string_view>
#include <SDL.h>
#include <fmt/core.h>
#include <fmt/ranges.h>
#include "utils/stdcompat/string_view.hpp"
#include "utils/str_cat.hpp"
#ifdef USE_SDL1
@ -14,7 +15,7 @@
namespace devilution {
// Local definition to fix compilation issue due to header conflict.
[[noreturn]] void app_fatal(string_view);
[[noreturn]] void app_fatal(std::string_view);
enum class LogCategory {
Application = SDL_LOG_CATEGORY_APPLICATION,
@ -42,7 +43,7 @@ enum class LogPriority {
namespace detail {
template <typename... Args>
std::string format(string_view fmt, Args &&...args)
std::string format(std::string_view fmt, Args &&...args)
{
FMT_TRY
{
@ -63,99 +64,99 @@ std::string format(string_view fmt, Args &&...args)
} // namespace detail
template <typename... Args>
void Log(string_view fmt, Args &&...args)
void Log(std::string_view fmt, Args &&...args)
{
auto str = detail::format(fmt, std::forward<Args>(args)...);
SDL_Log("%s", str.c_str());
}
template <typename... Args>
void LogVerbose(LogCategory category, string_view fmt, Args &&...args)
void LogVerbose(LogCategory category, std::string_view fmt, Args &&...args)
{
auto str = detail::format(fmt, std::forward<Args>(args)...);
SDL_LogVerbose(static_cast<int>(category), "%s", str.c_str());
}
template <typename... Args>
void LogVerbose(string_view fmt, Args &&...args)
void LogVerbose(std::string_view fmt, Args &&...args)
{
LogVerbose(defaultCategory, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void LogDebug(LogCategory category, string_view fmt, Args &&...args)
void LogDebug(LogCategory category, std::string_view fmt, Args &&...args)
{
auto str = detail::format(fmt, std::forward<Args>(args)...);
SDL_LogDebug(static_cast<int>(category), "%s", str.c_str());
}
template <typename... Args>
void LogDebug(string_view fmt, Args &&...args)
void LogDebug(std::string_view fmt, Args &&...args)
{
LogDebug(defaultCategory, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void LogInfo(LogCategory category, string_view fmt, Args &&...args)
void LogInfo(LogCategory category, std::string_view fmt, Args &&...args)
{
auto str = detail::format(fmt, std::forward<Args>(args)...);
SDL_LogInfo(static_cast<int>(category), "%s", str.c_str());
}
template <typename... Args>
void LogInfo(string_view fmt, Args &&...args)
void LogInfo(std::string_view fmt, Args &&...args)
{
LogInfo(defaultCategory, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void LogWarn(LogCategory category, string_view fmt, Args &&...args)
void LogWarn(LogCategory category, std::string_view fmt, Args &&...args)
{
auto str = detail::format(fmt, std::forward<Args>(args)...);
SDL_LogWarn(static_cast<int>(category), "%s", str.c_str());
}
template <typename... Args>
void LogWarn(string_view fmt, Args &&...args)
void LogWarn(std::string_view fmt, Args &&...args)
{
LogWarn(defaultCategory, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void LogError(LogCategory category, string_view fmt, Args &&...args)
void LogError(LogCategory category, std::string_view fmt, Args &&...args)
{
auto str = detail::format(fmt, std::forward<Args>(args)...);
SDL_LogError(static_cast<int>(category), "%s", str.c_str());
}
template <typename... Args>
void LogError(string_view fmt, Args &&...args)
void LogError(std::string_view fmt, Args &&...args)
{
LogError(defaultCategory, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void LogCritical(LogCategory category, string_view fmt, Args &&...args)
void LogCritical(LogCategory category, std::string_view fmt, Args &&...args)
{
auto str = detail::format(fmt, std::forward<Args>(args)...);
SDL_LogCritical(static_cast<int>(category), "%s", str.c_str());
}
template <typename... Args>
void LogCritical(string_view fmt, Args &&...args)
void LogCritical(std::string_view fmt, Args &&...args)
{
LogCritical(defaultCategory, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void LogMessageV(LogCategory category, LogPriority priority, string_view fmt, Args &&...args)
void LogMessageV(LogCategory category, LogPriority priority, std::string_view fmt, Args &&...args)
{
auto str = detail::format(fmt, std::forward<Args>(args)...);
SDL_LogMessageV(static_cast<int>(category), static_cast<SDL_LogPriority>(priority), "%s", str.c_str());
}
template <typename... Args>
void LogMessageV(string_view fmt, Args &&...args)
void LogMessageV(std::string_view fmt, Args &&...args)
{
LogMessageV(defaultCategory, fmt, std::forward<Args>(args)...);
}

5
Source/utils/parse_int.hpp

@ -1,10 +1,9 @@
#pragma once
#include <charconv>
#include <string_view>
#include <system_error>
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
enum class ParseIntStatus {
@ -32,7 +31,7 @@ struct ParseIntResult {
template <typename IntT>
ParseIntResult<IntT> ParseInt(
string_view str, IntT min = std::numeric_limits<IntT>::min(),
std::string_view str, IntT min = std::numeric_limits<IntT>::min(),
IntT max = std::numeric_limits<IntT>::max())
{
IntT value;

7
Source/utils/stdcompat/string_view.hpp

@ -1,7 +0,0 @@
#pragma once
#include <string>
#include <string_view> // IWYU pragma: export
namespace devilution {
using ::std::string_view;
} // namespace devilution

5
Source/utils/str_case.hpp

@ -1,14 +1,13 @@
#pragma once
#include <string>
#include "utils/stdcompat/string_view.hpp"
#include <string_view>
namespace devilution {
void AsciiStrToLower(std::string &str);
[[nodiscard]] inline std::string AsciiStrToLower(string_view str)
[[nodiscard]] inline std::string AsciiStrToLower(std::string_view str)
{
std::string copy { str.data(), str.size() };
AsciiStrToLower(copy);

15
Source/utils/str_cat.hpp

@ -2,10 +2,9 @@
#include <cstring>
#include <string>
#include <string_view>
#include <type_traits>
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
/**
@ -20,18 +19,18 @@ char *BufCopy(char *out, int value);
void StrAppend(std::string &out, int value);
/**
* @brief Copies the given string_view to the given buffer.
* @brief Copies the given std::string_view to the given buffer.
*/
inline char *BufCopy(char *out, string_view value)
inline char *BufCopy(char *out, std::string_view value)
{
std::memcpy(out, value.data(), value.size());
return out + value.size();
}
/**
* @brief Copies the given string_view to the given string.
* @brief Copies the given std::string_view to the given string.
*/
inline void StrAppend(std::string &out, string_view value)
inline void StrAppend(std::string &out, std::string_view value)
{
out.append(value);
}
@ -43,7 +42,7 @@ inline void StrAppend(std::string &out, string_view value)
*/
inline char *BufCopy(char *out, const char *str)
{
return BufCopy(out, string_view(str != nullptr ? str : "(nullptr)"));
return BufCopy(out, std::string_view(str != nullptr ? str : "(nullptr)"));
}
/**
@ -51,7 +50,7 @@ inline char *BufCopy(char *out, const char *str)
*/
inline void StrAppend(std::string &out, const char *str)
{
out.append(string_view(str != nullptr ? str : "(nullptr)"));
out.append(std::string_view(str != nullptr ? str : "(nullptr)"));
}
template <typename... Args>

23
Source/utils/str_split.hpp

@ -1,34 +1,33 @@
#pragma once
#include <iterator>
#include <string_view>
#include <type_traits>
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
class SplitByCharIterator {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = string_view;
using value_type = std::string_view;
using reference = std::add_lvalue_reference<value_type>::type;
using pointer = std::add_pointer<value_type>::type;
static SplitByCharIterator begin(string_view text, char split_by) // NOLINT(readability-identifier-naming)
static SplitByCharIterator begin(std::string_view text, char split_by) // NOLINT(readability-identifier-naming)
{
return SplitByCharIterator(split_by, text, text.substr(0, text.find(split_by)));
}
static SplitByCharIterator end(string_view text, char split_by) // NOLINT(readability-identifier-naming)
static SplitByCharIterator end(std::string_view text, char split_by) // NOLINT(readability-identifier-naming)
{
return SplitByCharIterator(split_by, text, text.substr(text.size()));
}
[[nodiscard]] string_view operator*() const
[[nodiscard]] std::string_view operator*() const
{
return slice_;
}
[[nodiscard]] const string_view *operator->() const
[[nodiscard]] const std::string_view *operator->() const
{
return &slice_;
}
@ -60,7 +59,7 @@ public:
}
private:
SplitByCharIterator(char split_by, string_view text, string_view slice)
SplitByCharIterator(char split_by, std::string_view text, std::string_view slice)
: split_by_(split_by)
, text_(text)
, slice_(slice)
@ -68,13 +67,13 @@ private:
}
const char split_by_;
const string_view text_;
string_view slice_;
const std::string_view text_;
std::string_view slice_;
};
class SplitByChar {
public:
explicit SplitByChar(string_view text, char split_by)
explicit SplitByChar(std::string_view text, char split_by)
: text_(text)
, split_by_(split_by)
{
@ -91,7 +90,7 @@ public:
}
private:
const string_view text_;
const std::string_view text_;
const char split_by_;
};

19
Source/utils/string_or_view.hpp

@ -1,10 +1,9 @@
#pragma once
#include <string>
#include <string_view>
#include <utility>
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
class StringOrView {
@ -21,7 +20,7 @@ public:
{
}
StringOrView(string_view str)
StringOrView(std::string_view str)
: owned_(false)
, view_(str)
{
@ -33,7 +32,7 @@ public:
if (other.owned_) {
new (&str_) std::string(std::move(other.str_));
} else {
new (&view_) string_view(other.view_);
new (&view_) std::string_view(other.view_);
}
}
@ -45,11 +44,11 @@ public:
} else {
str_.~basic_string();
owned_ = false;
new (&view_) string_view(other.view_);
new (&view_) std::string_view(other.view_);
}
} else {
if (other.owned_) {
view_.~string_view();
view_.~basic_string_view();
owned_ = true;
new (&str_) std::string(std::move(other.str_));
} else {
@ -64,7 +63,7 @@ public:
if (owned_) {
str_.~basic_string();
} else {
view_.~string_view();
view_.~basic_string_view();
}
}
@ -73,12 +72,12 @@ public:
return owned_ ? str_.empty() : view_.empty();
}
string_view str() const
std::string_view str() const
{
return owned_ ? str_ : view_;
}
operator string_view() const
operator std::string_view() const
{
return str();
}
@ -87,7 +86,7 @@ private:
bool owned_;
union {
std::string str_;
string_view view_;
std::string_view view_;
};
};

2
Source/utils/ui_fwd.h

@ -31,6 +31,6 @@ void ReinitializeIntegerScale();
#endif
void ReinitializeRenderer();
void ResizeWindow();
void UiErrorOkDialog(string_view caption, string_view text, bool error = true);
void UiErrorOkDialog(std::string_view caption, std::string_view text, bool error = true);
} // namespace devilution

6
Source/utils/utf8.cpp

@ -13,7 +13,7 @@ namespace devilution {
namespace {
/** Truncates `str` to at most `len` at a code point boundary. */
string_view TruncateUtf8(string_view str, std::size_t len)
std::string_view TruncateUtf8(std::string_view str, std::size_t len)
{
if (str.size() > len) {
std::size_t truncIndex = len;
@ -26,7 +26,7 @@ string_view TruncateUtf8(string_view str, std::size_t len)
} // namespace
char32_t DecodeFirstUtf8CodePoint(string_view input, std::size_t *len)
char32_t DecodeFirstUtf8CodePoint(std::string_view input, std::size_t *len)
{
uint32_t codepoint = 0;
uint8_t state = UTF8_ACCEPT;
@ -45,7 +45,7 @@ char32_t DecodeFirstUtf8CodePoint(string_view input, std::size_t *len)
return Utf8DecodeError;
}
void CopyUtf8(char *dest, string_view source, std::size_t bytes)
void CopyUtf8(char *dest, std::string_view source, std::size_t bytes)
{
source = TruncateUtf8(source, bytes - 1);
std::memcpy(dest, source.data(), source.size());

11
Source/utils/utf8.hpp

@ -2,10 +2,9 @@
#include <cstdint>
#include <string>
#include <string_view>
#include <utility>
#include "utils/stdcompat/string_view.hpp"
namespace devilution {
constexpr char32_t Utf8DecodeError = 0xD83F;
@ -16,12 +15,12 @@ constexpr char32_t Utf8DecodeError = 0xD83F;
* Sets `len` to the length of the code point in bytes.
* Returns `Utf8DecodeError` on error.
*/
char32_t DecodeFirstUtf8CodePoint(string_view input, std::size_t *len);
char32_t DecodeFirstUtf8CodePoint(std::string_view input, std::size_t *len);
/**
* Decodes and removes the first code point from UTF8-encoded input.
*/
inline char32_t ConsumeFirstUtf8CodePoint(string_view *input)
inline char32_t ConsumeFirstUtf8CodePoint(std::string_view *input)
{
std::size_t len;
const char32_t result = DecodeFirstUtf8CodePoint(*input, &len);
@ -56,7 +55,7 @@ inline bool IsTrailUtf8CodeUnit(char x)
/**
* Returns the start byte index of the last code point in a UTF-8 string.
*/
inline std::size_t FindLastUtf8Symbols(string_view input)
inline std::size_t FindLastUtf8Symbols(std::string_view input)
{
if (input.empty())
return 0;
@ -73,7 +72,7 @@ inline std::size_t FindLastUtf8Symbols(string_view input)
* @param source The source string
* @param bytes Max number of bytes to copy
*/
void CopyUtf8(char *dest, string_view source, std::size_t bytes);
void CopyUtf8(char *dest, std::string_view source, std::size_t bytes);
void AppendUtf8(char32_t codepoint, std::string &out);

2
test/str_cat_test.cpp

@ -14,7 +14,7 @@ TEST(StrCatTest, BufCopyBasicTest)
{
char buf[5];
char *end = BufCopy(buf, "a", "b", "c", 5);
EXPECT_EQ(string_view(buf, end - buf), "abc5");
EXPECT_EQ(std::string_view(buf, end - buf), "abc5");
}
} // namespace

Loading…
Cancel
Save